text stringlengths 13 6.01M |
|---|
using DistCWebSite.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DistCWebSite.Core.Interfaces
{
public interface IM_UserRespository
{
void Add(M_User user);
void Update(M_User user);
void Delete(M_User user);
IEnumerable<M_User> GetList();
M_User Get(int id);
}
}
|
/***********************************************
*
* Base class for All Weapon Animation
* functions should contain instructions that
* are always called in the same order
*
***********************************************/
namespace DChild.Gameplay.Player
{
public abstract class WeaponAnimation : PlayerAnimation.SubAnimation
{
public WeaponAnimation(SpineAnimation animation, string m_idleAnimation) : base(animation, m_idleAnimation)
{
}
protected void DoGroundAttack(string attack)
{
var entry = m_animation.SetAnimation(0, attack, false);
entry.MixDuration = 0;
}
protected void BlendAttack(string attack)
{
var entry = m_animation.SetAnimation(1, attack, false);
entry.MixDuration = 0;
var attackAnimation = m_animation.skeletonAnimation.skeleton.Data.FindAnimation(attack);
m_animation.AddEmptyAnimation(1, 0.2f, attackAnimation.Duration);
}
}
}
|
using System;
namespace FBS.Domain.FlightControl
{
public class Flight
{
public Guid Id { get; set; }
public DateTime Date { get; set; }
public TimeSpan Duration { get; set; }
public Airport From { get; set; }
public Airport To { get; set; }
public string Gate { get; set; }
public Plane Plane { get; set; }
public string Number { get; set; }
}
} |
using MvvmHelpers;
using AdminJonganggur.Models;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using AdminJonganggur.Services;
using System.ComponentModel;
using AdminJonganggur;
namespace AdminJonganggur.ViewModel
{
public class PerusahaanVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string namap;
public string NamaP
{
get { return namap; }
set
{
namap = value;
PropertyChanged(this, new PropertyChangedEventArgs("NamaP"));
}
}
private string username;
public string Username
{
get { return username; }
set
{
username = value;
PropertyChanged(this, new PropertyChangedEventArgs("Username"));
}
}
private string password;
public string Password
{
get { return password; }
set
{
password = value;
PropertyChanged(this, new PropertyChangedEventArgs("Password"));
}
}
private string alamat;
public string Alamat
{
get { return alamat; }
set
{
alamat = value;
PropertyChanged(this, new PropertyChangedEventArgs("Alamat"));
}
}
private string tentang;
public string Tentang
{
get { return tentang; }
set
{
tentang = value;
PropertyChanged(this, new PropertyChangedEventArgs("Tentang"));
}
}
public Command AddPerusahaanCommand
{
get
{
return new Command(() =>
{
Daftar();
});
}
}
private async void Daftar()
{
//null or empty field validation, check weather email and password is null or empty
if (string.IsNullOrEmpty(NamaP) || string.IsNullOrEmpty(Username) ||
string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Alamat) ||
string.IsNullOrEmpty(Tentang))
await App.Current.MainPage.DisplayAlert("Peringatan", "Harap isi semua data!", "OK");
else
{
//call AddUser function which we define in Firebase helper class
var user = await FirebaseHelper.AddPerusahaan(NamaP, Username, Password, Alamat, Tentang);
//AddUser return true if data insert successfuly
if (user)
{
await App.Current.MainPage.DisplayAlert("Daftar Sukses", "", "Ok");
}
else
await App.Current.MainPage.DisplayAlert("Error", "Daftar Gagal", "OK");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using Lucene.Net.Documents;
using Profiling2.Domain.Contracts.Search;
using Profiling2.Domain.Extensions;
using Profiling2.Domain.Prf.Units;
using Profiling2.Infrastructure.Search.IndexWriters;
namespace Profiling2.Infrastructure.Search
{
public class UnitIndexer : BaseIndexer, ILuceneIndexer<UnitIndexer>
{
protected readonly ILog log = LogManager.GetLogger(typeof(UnitIndexer));
public UnitIndexer()
{
this.indexWriter = UnitIndexWriterSingleton.Instance;
}
protected override void AddNoCommit<T>(T obj)
{
Unit unit = obj as Unit;
if (unit != null && !unit.Archive && this.indexWriter != null)
{
Document doc = new Document();
doc.Add(new NumericField("Id", Field.Store.YES, true).SetIntValue(unit.Id));
if (!string.IsNullOrEmpty(unit.UnitName))
{
Field nameField = new Field("Name", unit.UnitName, Field.Store.YES, Field.Index.ANALYZED);
nameField.Boost = 2.0f;
doc.Add(nameField);
}
// aliases make multi-values for Name field
foreach (UnitAlias alias in unit.UnitAliases.Where(x => !string.IsNullOrEmpty(x.UnitName) && !x.Archive))
{
Field aliasField = new Field("Name", alias.UnitName, Field.Store.YES, Field.Index.ANALYZED);
aliasField.Boost = 1.5f;
doc.Add(aliasField);
}
// add name changes
foreach (UnitHierarchy uh in unit.GetParentChangedNameUnitHierarchiesRecursive(new List<UnitHierarchy>()).Where(x => x.ParentUnit != null))
{
Field field = new Field("ParentNameChange", uh.ParentUnit.UnitName, Field.Store.YES, Field.Index.ANALYZED);
field.Boost = 0.5f;
doc.Add(field);
}
foreach (UnitHierarchy uh in unit.GetChildChangedNameUnitHierarchiesRecursive(new List<UnitHierarchy>()).Where(x => x.Unit != null))
{
Field field = new Field("ChildNameChange", uh.Unit.UnitName, Field.Store.YES, Field.Index.ANALYZED);
field.Boost = 0.5f;
doc.Add(field);
}
if (!string.IsNullOrEmpty(unit.BackgroundInformation))
{
doc.Add(new Field("BackgroundInformation", unit.BackgroundInformation, Field.Store.YES, Field.Index.ANALYZED));
}
if (unit.Organization != null)
{
doc.Add(new Field("Organization", unit.Organization.OrgShortName, Field.Store.YES, Field.Index.ANALYZED));
}
if (unit.HasStartDate())
{
// minimal date for searching
DateTime? start = unit.GetStartDateTime();
if (!start.HasValue)
log.Error("Encountered invalid start date for UnitID=" + unit.Id + ": " + unit.GetStartDateString());
doc.Add(new Field("StartDateDisplay", unit.GetStartDateString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
}
if (unit.HasEndDate())
{
// maximal date for searching
DateTime? end = unit.GetEndDateTime();
if (!end.HasValue)
log.Error("Encountered invalid end date for UnitID=" + unit.Id + ": " + unit.GetEndDateString());
doc.Add(new Field("EndDateDisplay", unit.GetEndDateString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
}
this.indexWriter.AddDocument(doc);
}
}
}
}
|
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;
using System.Data.OleDb;
namespace Management_Plus
{
public partial class Wellcome : Form
{
int a = 31;
ShopDetails sd = null;
public Wellcome()
{
InitializeComponent();
process.Start();
}
public void check()
{
}
private void process_Tick(object sender, EventArgs e)
{
process.Interval = 10;
if (panel1.Width <= 465)
{
panel1.Width += 1;
switch (a)
{
case 1: lbl_3.Text = "Initializing Modules...5%";
break;
case 2: lbl_3.Text = "Initializing Modules...10%";
break;
case 93: lbl_3.Text = "Initializing Modules...15%";
break;
case 124: lbl_3.Text = "Initializing Modules...20%";
break;
case 155: lbl_3.Text = "Initializing Modules...25%";
break;
case 186: lbl_3.Text = "Initializing Modules...30%";
break;
case 217: lbl_3.Text = "Initializing Modules...35%";
break;
case 248: lbl_3.Text = "Initializing Modules...40%";
break;
case 279: lbl_3.Text = "Initializing Modules...50%";
break;
case 310: lbl_3.Text = "Initializing Modules...60%";
break;
case 341: lbl_3.Text = "Initializing Modules...70%";
break;
case 372: lbl_3.Text = "Initializing Modules...80%";
break;
case 403: lbl_3.Text = "Initializing Modules...85%";
break;
case 434: lbl_3.Text = "Initializing Modules...95%";
break;
case 460: lbl_3.Text = "Initializing Modules...100%";
break;
}
a++;
if (panel1.Width == 465)
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\project database\Management Plus.mdb");
con.Open();
OleDbCommand cmd = new OleDbCommand("select shopname from shopregistration", con);
OleDbDataReader dr = cmd.ExecuteReader();
if (!dr.HasRows)
{
this.Hide();
sd = new ShopDetails();
sd.ShowDialog();
this.Close();
}
else
{
this.Hide();
Register rr = new Register();
rr.ShowDialog();
this.Close();
}
dr.Close();
con.Close();
}
}
}
private void Wellcome_Load(object sender, EventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Mirror;
public class RoomPlayerUIControler : NetworkBehaviour
{
private const string playerImagePrefix ="PlayerType";
private const int startingCharNumber = 1;
private const int maxCharTypes = 8;
public int charID {get;private set;} = startingCharNumber;
public int playerNumber {get;private set;} = 0;
public bool isReadyToPlay {get;private set;} = false;
[Header("UI Elements")]
[SerializeField] private Image player1Controls = null;
[SerializeField] private Image player2Controls = null;
[SerializeField] private Image player3Controls = null;
[SerializeField] private Button player1NextCharButton = null;
[SerializeField] private Button player1PreviousCharButton = null;
[SerializeField] private Button player1ReadyButton = null;
[SerializeField] private Button player2NextCharButton = null;
[SerializeField] private Button player2PreviousCharButton = null;
[SerializeField] private Button player2ReadyButton = null;
[SerializeField] private Button player3NextCharButton = null;
[SerializeField] private Button player3PreviousCharButton = null;
[SerializeField] private Button player3ReadyButton = null;
[SerializeField] private Image player1Card = null;
[SerializeField] private Image player2Card = null;
[SerializeField] private Image player3Card = null;
// Start is called before the first frame update
void Start()
{
if (isLocalPlayer){
gameObject.transform.Find("LobbyPlayerHUD").gameObject.SetActive(true);
startupUI();
}
}
// Update is called once per frame
void Update()
{
UpdateOtherPlayersDisplay();
}
public void startupUI(){
playerNumber = GameObject.FindGameObjectsWithTag("RoomPlayer").Length;
RegisterPlayerNumber(playerNumber);
player1Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
player2Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
player3Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
switch (playerNumber){
case 1:
player2Controls.gameObject.SetActive(false);
player3Controls.gameObject.SetActive(false);
break;
case 2:
player1Controls.gameObject.SetActive(false);
player3Controls.gameObject.SetActive(false);
break;
case 3:
player1Controls.gameObject.SetActive(false);
player2Controls.gameObject.SetActive(false);
break;
}
}
public void nextChar(){
charID++;
if (charID > 8) charID =0;
switch (playerNumber){
case 1:
player1Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
break;
case 2:
player2Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
break;
case 3:
player3Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
break;
}
CmdUpdatePlayerMonitor(playerNumber,charID,isReadyToPlay);
}
public void previousChar(){
charID--;
if (charID < 0) charID =8;
switch (playerNumber){
case 1:
player1Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
break;
case 2:
player2Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
break;
case 3:
player3Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + charID.ToString());
break;
}
Debug.Log(charID);
CmdUpdatePlayerMonitor(playerNumber,charID,isReadyToPlay);
}
public void ToggleReady(){
isReadyToPlay=!isReadyToPlay;
switch (playerNumber){
case 1:
if (isReadyToPlay){
player1ReadyButton.GetComponentInChildren<TMPro.TMP_Text>().text = "Cancelar";
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player1ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=green>Pronto</color>";
}else{
player1ReadyButton.GetComponentInChildren<TMPro.TMP_Text>().text = "Pronto";
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player1ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=red>Escolhendo</color>";
}
break;
case 2:
if (isReadyToPlay){
player2ReadyButton.GetComponentInChildren<TMPro.TMP_Text>().text = "Cancelar";
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player2ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=green>Pronto</color>";
}else{
player2ReadyButton.GetComponentInChildren<TMPro.TMP_Text>().text = "Pronto";
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player2ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=red>Escolhendo</color>";
}
break;
case 3:
if (isReadyToPlay){
player3ReadyButton.GetComponentInChildren<TMPro.TMP_Text>().text = "Cancelar";
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player3ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=green>Pronto</color>";
}else{
player3ReadyButton.GetComponentInChildren<TMPro.TMP_Text>().text = "Pronto";
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player3ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=red>Escolhendo</color>";
}
break;
}
CmdUpdatePlayerMonitor(playerNumber,charID,isReadyToPlay);
}
[Command]
public void CmdUpdatePlayerMonitor(int playerNumber,int playerCharID,bool ready){
PlayerChoiceTracking playerChoiceScript;
playerChoiceScript = GameObject.Find("DummyObjectPlayerOptions").GetComponent<PlayerChoiceTracking>();
switch(playerNumber){
case 1:
playerChoiceScript.p1CharId = playerCharID;
playerChoiceScript.player1Ready = ready;
break;
case 2:
playerChoiceScript.p2CharId = playerCharID;
playerChoiceScript.player2Ready = ready;
break;
case 3:
playerChoiceScript.p3CharId = playerCharID;
playerChoiceScript.player3Ready = ready;
break;
}
}
[ClientRpc]
public void RpcDisableUI(){
gameObject.transform.Find("LobbyPlayerHUD").gameObject.SetActive(false);
}
public void UpdateOtherPlayersDisplay(){
PlayerChoiceTracking playerChoiceScript;
playerChoiceScript = GameObject.Find("DummyObjectPlayerOptions").GetComponent<PlayerChoiceTracking>();
if (playerNumber != 1){
if (playerChoiceScript.player1Ready){
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player1ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=green>Pronto</color>";
}else{
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player1ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=red>Escolhendo...</color>";
}
if (player1Card.sprite.name != (playerImagePrefix + playerChoiceScript.p1CharId.ToString()) ){
player1Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + playerChoiceScript.p1CharId.ToString());
}
}
if (playerNumber != 2){
if (playerChoiceScript.player2Ready){
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player2ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=green>Pronto</color>";
}else{
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player2ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=red>Escolhendo...</color>";
}
if (player2Card.sprite.name != (playerImagePrefix + playerChoiceScript.p2CharId.ToString()) ){
player2Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + playerChoiceScript.p2CharId.ToString());
}
}
if (playerNumber != 3){
if (playerChoiceScript.player3Ready){
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player3ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=green>Pronto</color>";
}else{
gameObject.transform.Find("LobbyPlayerHUD/PlayerSelectPanel/Player3ReadyText").gameObject.GetComponentInChildren<TMPro.TMP_Text>().text = "<color=red>Escolhendo...</color>";
}
if (player3Card.sprite.name != (playerImagePrefix + playerChoiceScript.p3CharId.ToString()) ){
player3Card.sprite=Resources.Load<Sprite>("Sprites/" + playerImagePrefix + playerChoiceScript.p3CharId.ToString());
}
}
}
public void RegisterPlayerNumber(int localPlayerNumber){
PlayerChoiceTracking playerChoiceScript;
playerChoiceScript = GameObject.Find("DummyObjectPlayerOptions").GetComponent<PlayerChoiceTracking>();
playerChoiceScript.localPlayerPlayerNumber = localPlayerNumber;
}
[ClientRpc]
public void RpcShowQuestionnaire(int playerNumber){
Debug.Log("RPC");
if (isLocalPlayer){
if (playerNumber == GameObject.FindGameObjectWithTag("PlayerOptionsContainer").GetComponent<PlayerChoiceTracking>().localPlayerPlayerNumber){
gameObject.transform.Find("QuestionnaireCanvas").gameObject.SetActive(true);
}
}
}
[Command]
public void CmdNotifyServerQuestionaireCompleted(int playerNumber){
GameObject.Find("P"+ playerNumber + "QuestionarioRespondidoCheckbox").GetComponent<Toggle>().isOn = true;
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Server_CS.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class OnlineController : ControllerBase
{
/// <summary>
/// Запрос на получение всех пользователей и их состояния (В сети/Не в сети)
/// <br>GET: api/Online</br>
/// </summary>
/// <returns>Словарь пользователей (В сети/Не в сети)</returns>
[HttpGet]
public List<string> Get()
{
return Program.OnlineUsers;
}
/// <summary>
/// Получения сигнала онлайн пользователя
/// <br>POST: api/Online</br>
/// </summary>
/// <returns>Возвращает ok если всё прошло успешно</returns>
[Authorize]
[HttpPost]
public string Post()
{
var name = User.Identity.Name;
if (name == null) return "No name";
if (Program.OnlineUsers.Contains(name))
{
Program.OnlineUsersTimeout[name] = DateTime.Now;
}
else
{
Program.OnlineUsers.Add(name);
Program.OnlineUsersTimeout.Add(name, DateTime.Now);
Program.Messages.Add(new Message
{
Name = "",
Text = $"{name} connected",
Ts = (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds
});
}
return "ok";
}
}
} |
using System.Data.Entity.ModelConfiguration;
using Efa.Domain.Entities;
namespace Efa.Infra.Data.EntityConfig
{
public class AlunoConfiguration : EntityTypeConfiguration<Aluno>
{
public AlunoConfiguration()
{
ToTable("Aluno");
HasKey(a => a.AlunoId).HasOptional(a => a.Notas);
Property(a => a.Nome).IsRequired();
Property(a => a.NotasId).IsOptional();
Property(a => a.TurmaId).IsOptional();
Property(a => a.Telefone).HasMaxLength(10);
Property(a => a.Celular).HasMaxLength(10);
Ignore(a => a.ResultadoValidacao);
HasOptional(a => a.Turma)
.WithMany()
.HasForeignKey(a => a.TurmaId);
}
}
} |
using System.Collections;
using GeoAPI.Extensions.Feature;
using GeoAPI.Geometries;
using SharpMap.Layers;
using System.Collections.Generic;
namespace SharpMap.UI.Snapping
{
public class SnapRule : ISnapRule
{
public ILayer SourceLayer { get; set; }
public ILayer TargetLayer { get; set; }
public SnapRole SnapRole { get; set; }
public virtual bool Obligatory { get; set; }
public int PixelGravity { get; set; } // TODO: explain it
/// <summary>
///
/// </summary>
/// <param name="sourceFeature"></param>
/// <param name="sourceGeometry"></param>
/// <param name="snapTargets"></param>
/// <param name="worldPos"></param>
/// <param name="envelope"></param>
/// <param name="trackingIndex"></param>
/// based of the selected tracker in the snapSource the rule can behave differently
/// (only snap branches' first and last coordinate).
/// <returns></returns>
public virtual ISnapResult Execute(IFeature sourceFeature, IGeometry sourceGeometry, IList<IFeature> snapTargets, ICoordinate worldPos, IEnvelope envelope, int trackingIndex)
{
return Snap(TargetLayer, SnapRole, sourceGeometry, worldPos, envelope, PixelGravity, snapTargets);
}
public ISnapResult Snap(ILayer layer, SnapRole snapRole, IGeometry snapSource, ICoordinate worldPos, IEnvelope envelope, int pixelGravity, IList<IFeature> snapTargets)
{
var targetVectorLayer = (VectorLayer)layer;
var snapCandidates = targetVectorLayer.DataSource.GetFeatures(envelope);
if (!layer.Visible)
return null;
// hack preserve snapTargets functionality
IList<IGeometry> snapTargetGeometries = new List<IGeometry>();
if (null != snapTargets)
{
for (int i = 0; i < snapTargets.Count; i++)
{
snapTargetGeometries.Add(snapTargets[i].Geometry);
}
}
double minDistance = double.MaxValue; // TODO: incapsulate minDistance in ISnapResult
ISnapResult snapResult = null;
foreach (IFeature feature in snapCandidates)
{
IGeometry geometry = feature.Geometry;
if ((null != snapTargets) && (snapTargetGeometries.IndexOf(geometry) == -1))
continue;
if (snapRole == SnapRole.None)
continue;
if (geometry is IPolygon)
{
IPolygon polygon = (IPolygon)geometry;
switch (snapRole)
{
case SnapRole.Free:
SnappingHelper.PolygonSnapFree(ref minDistance, ref snapResult, polygon, worldPos);
break;
default:
//case SnapRole.FreeAtObject:
SnappingHelper.PolygonSnapFreeAtObject(ref minDistance, ref snapResult, polygon, worldPos);
break;
}
}
if (geometry is ILineString)
{
ILineString lineString = (ILineString)geometry;
switch (snapRole)
{
case SnapRole.Free:
SnappingHelper.LineStringSnapFree(ref minDistance, ref snapResult, lineString, worldPos);
break;
case SnapRole.FreeAtObject:
SnappingHelper.LineStringSnapFreeAtObject(ref minDistance, ref snapResult, feature, lineString, worldPos);
break;
case SnapRole.TrackersNoStartNoEnd:
break;
case SnapRole.AllTrackers:
SnappingHelper.LineStringSnapAllTrackers(ref minDistance, ref snapResult, lineString, worldPos);
break;
case SnapRole.Start:
SnappingHelper.LineStringSnapStart(ref snapResult, lineString);
break;
case SnapRole.End:
SnappingHelper.LineStringSnapEnd(ref snapResult, lineString);
break;
case SnapRole.StartEnd:
SnappingHelper.LineStringSnapStartEnd(ref minDistance, ref snapResult, lineString, worldPos);
break;
}
}
else if (geometry is IPoint)
{
SnappingHelper.PointSnap(ref snapResult, geometry);
}
} // foreach (IGeometry geometry in snapCandidates)
return snapResult;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SubmarineEnemy : Enemy
{
[SerializeField]
public bool canFire;
[SerializeField]
protected Transform playerTransform;
[SerializeField]
protected Transform muzzleTransform;
[SerializeField]
protected GameObject bulletFX;
[SerializeField]
protected AudioClip fireSound;
private AudioSource audioSource;
private Coroutine shootBehave;
public Vector2 minSpreadDegrees;
public Vector2 maxSpreadDegrees;
private Transform player;
// Use this for initialization
void Start () {
audioSource = GetComponent<AudioSource>();
//transform.LookAt(playerTransform);
//transform.rotation *= Quaternion.Euler(0, -30, 0);
}
public void AimAtPlayer(Transform player)
{
this.player = player;
//transform.LookAt(new Vector3(player.position.x+40f, transform.position.y, player.position.z +40f));
//muzzleTransform.LookAt(new Vector3(player.position.x, muzzleTransform.position.y, player.position.z));
}
// Update is called once per frame
void Update () {
Fire();
}
public void Fire()
{
if(canFire)
{
muzzleTransform.LookAt(player);
Shoot();
canFire = false;
shootBehave = StartCoroutine(ShootBehaviour());
}
}
public void Shoot()
{
audioSource.clip = fireSound;
audioSource.Play();
Quaternion rotation = CalculateProjectileRotation();
var Bullet = Instantiate(bulletFX, muzzleTransform.position, rotation);
Destroy(Bullet, 5f);
}
public IEnumerator ShootBehaviour()
{
yield return new WaitForSeconds(1.2f);
canFire = true;
}
private Quaternion CalculateProjectileRotation()
{
Quaternion barrelEndStartRotation = muzzleTransform.rotation;
Vector3 newRotation = new Vector3(
Random.Range(minSpreadDegrees.x, maxSpreadDegrees.x),
Random.Range(minSpreadDegrees.y, maxSpreadDegrees.y),
0f);
muzzleTransform.Rotate(newRotation);
Quaternion rotation = muzzleTransform.rotation;
muzzleTransform.rotation = barrelEndStartRotation;
return rotation;
}
}
|
using System;
namespace BankAccountAPI.Models
{
public class Class1
{
}
}
|
using Caliburn.Micro;
using RRExpress.AppCommon;
using RRExpress.AppCommon.Attributes;
using System.Windows.Input;
using Xamarin.Forms;
namespace RRExpress.Seller.ViewModels {
[Regist(InstanceMode.Singleton)]
public class OrdersViewModel : BaseVM {
public override string Title {
get {
return "我的订单";
}
}
public BaseVM MasterVM { get; }
public BaseVM DetailVM { get; }
public bool IsShowFilter { get; set; }
public ICommand ShowFilterCmd { get; }
public OrdersViewModel() {
this.DetailVM = IoC.Get<OrderListViewModel>();
this.MasterVM = IoC.Get<OrderFilterViewModel>();
this.ShowFilterCmd = new Command(() => {
this.IsShowFilter = !this.IsShowFilter;
this.NotifyOfPropertyChange(() => this.IsShowFilter);
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anywhere2Go.DataAccess.Entity
{
public class TaskPriority
{
public string taskPriorityId { get; set; }
public string taskPriorityName { get; set; }
public int point { get; set; }
public int sort { get; set; }
public bool isActive { get; set; }
public DateTime? createDate { get; set; }
public DateTime? updateDate { get; set; }
public string createBy { get; set; }
public string updateBy { get; set; }
}
public class TaskPriorityConfig : EntityTypeConfiguration<TaskPriority>
{
public TaskPriorityConfig()
{
ToTable("TaskPriority");
Property(t => t.taskPriorityId).HasColumnName("task_priority_id");
Property(t => t.taskPriorityName).HasColumnName("task_priority_name").HasMaxLength(50);
Property(t => t.point).HasColumnName("point");
Property(t => t.sort).HasColumnName("sort");
Property(t => t.isActive).HasColumnName("isActive");
Property(t => t.createDate).HasColumnName("create_date");
Property(t => t.updateDate).HasColumnName("update_date");
Property(t => t.createBy).HasColumnName("create_by");
Property(t => t.updateBy).HasColumnName("update_by");
HasKey(t => t.taskPriorityId);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Test.API.Data;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Test.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
public ApplicationDbContext DbContext { get; }
public StudentsController(ApplicationDbContext dbContext)
{
DbContext = dbContext;
}
// GET: api/<StudentsController>
[HttpGet]
public ActionResult<IEnumerable<Student>> Get()
{
return Ok(DbContext.Students.ToList());
}
// GET api/<StudentsController>/5
[HttpGet("{id}")]
public ActionResult<Student> GetById(int id)
{
if(id == 0)
{
return BadRequest();
}
var student = DbContext.Students.Where(a => a.Id == id).SingleOrDefault();
if(student == null)
{
return NotFound();
}
return Ok(student);
}
// POST api/<StudentsController>
[HttpPost]
public ActionResult<Student> Post([FromBody] Student student)
{
DbContext.Students.Add(student);
DbContext.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = student.Id }, student);
}
// PUT api/<StudentsController>/5
[HttpPut("{id}")]
public ActionResult<Student> Put(int id, [FromBody] Student student)
{
if(id == 0)
{
return BadRequest();
}
var studentInDb = DbContext.Students.Find(id);
if (studentInDb == null)
{
return NotFound();
}
studentInDb.Name = student.Name;
studentInDb.GradeId = student.GradeId;
DbContext.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = student.Id }, student);
}
// DELETE api/<StudentsController>/5
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
if (id == 0)
{
return BadRequest();
}
var studentInDb = DbContext.Students.Find(id);
if (studentInDb == null)
{
return NotFound();
}
DbContext.Students.Remove(studentInDb);
DbContext.SaveChanges();
return NoContent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace AweShur.Core
{
public enum DBDialectEnum
{
SQLServer,
PostgreSQL,
SQLite,
MySQL,
}
public class DBDialect
{
private static readonly Lazy<DBDialect>[] _instance
= { new Lazy<DBDialect>(() => new DBDialect(DBDialectEnum.SQLServer)),
new Lazy<DBDialect>(() => new DBDialect(DBDialectEnum.PostgreSQL)),
new Lazy<DBDialect>(() => new DBDialect(DBDialectEnum.SQLite)),
new Lazy<DBDialect>(() => new DBDialect(DBDialectEnum.MySQL)) };
public DBDialectEnum Dialect { get; }
public string Encapsulation { get; }
public string GetIdentitySql { get; }
public string GetPagedListSql { get; }
public string GetFromToListSql { get; }
public string GetSchemaSql { get; }
private static DBDialect Retreive(DBDialectEnum dialect)
{
return new DBDialect(dialect);
}
public class ColumnDefinition
{
public string ColumnName;
public string DBDataType;
public int MaxLength;
public bool IsNullable;
public bool IsIdentity;
public bool IsPrimaryKey;
public bool IsComputed;
}
private static Dictionary<string, Type> typesDict = new Dictionary<string, Type>() {
{ "int", typeof(Int32) },
{ "bit", typeof(bool) },
{ "bigint", typeof(Int64) },
{ "smallint", typeof(Int16) },
{ "tinyint", typeof(Byte) },
{ "real", typeof(Single) },
{ "float", typeof(Double) },
{ "nvarchar", typeof(string) },
{ "varchar", typeof(string) },
{ "date", typeof(DateTime) },
{ "datetime", typeof(DateTime) },
{ "ntext", typeof(string) },
{ "text", typeof(string) },
{ "nchar", typeof(string) },
{ "char", typeof(string) },
{ "money", typeof(Decimal) },
{ "decimal", typeof(Decimal) },
{ "numeric", typeof(Decimal) },
{ "timestamp", typeof(Byte[]) },
{ "binary", typeof(Byte[]) },
{ "uniqueidentifier", typeof(Guid) },
};
private static Dictionary<Type, BasicType> basicTypesDict = new Dictionary<Type, BasicType>() {
{ typeof(Int32), BasicType.Number },
{ typeof(bool), BasicType.Bit },
{ typeof(Int64), BasicType.Number },
{ typeof(Int16), BasicType.Number },
{ typeof(Byte), BasicType.Number },
{ typeof(Single), BasicType.Number },
{ typeof(Double), BasicType.Number },
{ typeof(string), BasicType.Text },
{ typeof(DateTime), BasicType.DateTime },
{ typeof(Decimal), BasicType.Number },
{ typeof(Byte[]), BasicType.Bynary },
{ typeof(Guid), BasicType.GUID },
};
public static Type GetColumnType(string dbDataType)
{
return typesDict[dbDataType];
//if (typesDict.ContainsKey(dbDataType))
//{
// return typesDict[dbDataType];
//}
//return typeof(int);
}
public static BasicType GetBasicType(Type type)
{
return basicTypesDict[type];
}
public string GetFullTableName(string tableName)
{
if (BusinessBaseProvider.TableSchemas.ContainsKey(tableName))
{
return BusinessBaseProvider.TableSchemas[tableName] + "." + tableName;
}
return tableName;
}
public IEnumerable<ColumnDefinition> GetSchema(string tableName, int dbNumber = 0)
{
string tableSchema = "";
if (Dialect == DBDialectEnum.SQLServer)
{
tableSchema = "dbo";
tableName = tableName.Replace("[", "").Replace("]", "");
}
if (tableName.Contains('.'))
{
string[] parts = tableName.Split('.');
tableSchema = parts[0];
tableName = parts[1];
}
return DB.InstanceNumber(dbNumber).Query<ColumnDefinition>(GetSchemaSql, new { TableName = tableName, TableSchema = tableSchema });
}
public static Func<DBDialectEnum, string, IDbConnection> GetStaticConnection;
public IDbConnection GetConnection(string connectionString)
{
IDbConnection conn = GetStaticConnection.Invoke(Dialect, connectionString);
// switch (Dialect)
// {
// case DBDialectEnum.PostgreSQL:
// conn = new Npgsql.NpgsqlConnection(connectionString);
// break;
// case DBDialectEnum.SQLite:
// throw new Exception("To come for .NET Core 1.0");
//// break;
// case DBDialectEnum.MySQL:
// throw new Exception("To come for .NET Core 1.0");
//// break;
// default:
// conn = new System.Data.SqlClient.SqlConnection(connectionString);
// break;
// }
return conn;
}
private DBDialect(DBDialectEnum dialect)
{
switch (dialect)
{
case DBDialectEnum.PostgreSQL:
Dialect = DBDialectEnum.PostgreSQL;
Encapsulation = "{0}";
GetIdentitySql = string.Format("SELECT LASTVAL() AS id");
GetPagedListSql = "Select {SelectColumns} from {FromClause} {WhereClause} {GroupByClause} Order By {OrderBy} LIMIT {RowsPerPage} OFFSET (({PageNumber}-1) * {RowsPerPage})";
GetFromToListSql = "Select {SelectColumns} from {FromClause} {WhereClause} {GroupByClause} Order By {OrderBy} LIMIT {RowCount} OFFSET ({FromRecord})";
break;
case DBDialectEnum.SQLite:
Dialect = DBDialectEnum.SQLite;
Encapsulation = "{0}";
GetIdentitySql = string.Format("SELECT LAST_INSERT_ROWID() AS id");
GetPagedListSql = "Select {SelectColumns} from {FromClause} {WhereClause} {GroupByClause} Order By {OrderBy} LIMIT {RowsPerPage} OFFSET (({PageNumber}-1) * {RowsPerPage})";
GetFromToListSql = "Select {SelectColumns} from {FromClause} {WhereClause} {GroupByClause} Order By {OrderBy} LIMIT {RowCount} OFFSET ({FromRecord})";
break;
case DBDialectEnum.MySQL:
Dialect = DBDialectEnum.MySQL;
Encapsulation = "`{0}`";
GetIdentitySql = string.Format("SELECT LAST_INSERT_ID() AS id");
GetPagedListSql = "Select {SelectColumns} from {FromClause} {WhereClause} {GroupByClause} Order By {OrderBy} LIMIT {Offset},{RowsPerPage}";
GetFromToListSql = "Select {SelectColumns} from {FromClause} {WhereClause} {GroupByClause} Order By {OrderBy} LIMIT {FromRecord},{RowCount}";
break;
default:
Dialect = DBDialectEnum.SQLServer;
Encapsulation = "[{0}]";
GetIdentitySql = string.Format("SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [id]");
GetPagedListSql = "SELECT {SelectNamedColumns} FROM (SELECT ROW_NUMBER() OVER(ORDER BY {OrderBy}) AS PagedNumber, {SelectColumns} FROM {FromClause} {WhereClause} {GroupByClause}) AS u WHERE PagedNUMBER BETWEEN (({PageNumber}-1) * {RowsPerPage} + 1) AND ({PageNumber} * {RowsPerPage})";
GetFromToListSql = "SELECT {SelectNamedColumns} FROM (SELECT ROW_NUMBER() OVER(ORDER BY {OrderBy}) AS PagedNumber, {SelectColumns} FROM {FromClause} {WhereClause} {GroupByClause}) AS u WHERE PagedNUMBER BETWEEN ({FromRecord} + 1) AND ({FromRecord} + {RowCount})";
GetSchemaSql = @"SELECT col.COLUMN_NAME AS ColumnName
, col.DATA_TYPE AS DBDataType
, col.CHARACTER_MAXIMUM_LENGTH AS MaxLength
, CAST(CASE col.IS_NULLABLE
WHEN 'NO' THEN 0
ELSE 1
END AS bit) AS IsNullable
, COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsIdentity') AS IsIdentity
, CAST(ISNULL(pk.is_primary_key, 0) AS bit) AS IsPrimaryKey
, CAST((case when col.COLUMN_DEFAULT is NULL OR
COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsComputed') = 1 then 0 else 1 end) As bit) AS IsComputed
FROM INFORMATION_SCHEMA.COLUMNS AS col
LEFT JOIN(SELECT SCHEMA_NAME(o.schema_id)AS TABLE_SCHEMA
, o.name AS TABLE_NAME
, c.name AS COLUMN_NAME
, i.is_primary_key
FROM sys.indexes AS i JOIN sys.index_columns AS ic ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
JOIN sys.objects AS o ON i.object_id = o.object_id
LEFT JOIN sys.columns AS c ON ic.object_id = c.object_id
AND c.column_id = ic.column_id
WHERE i.is_primary_key = 1) AS pk ON col.TABLE_NAME = pk.TABLE_NAME
AND col.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND col.COLUMN_NAME = pk.COLUMN_NAME
WHERE col.TABLE_NAME = @TableName
AND col.TABLE_SCHEMA = @TableSchema
ORDER BY col.ORDINAL_POSITION";
break;
}
}
public static DBDialect Instance(DBDialectEnum dialect)
{
return _instance[(int)dialect].Value;
}
//public string SQLListColumns(List<PropertyDefinition> properties)
//{
// StringBuilder sb = new StringBuilder();
// string keyExpression = "";
// var addedAny = false;
// foreach (PropertyDefinition prop in properties)
// {
// if (prop.IsDBField)
// {
// if (prop.IsPrimaryKey)
// {
// if (keyExpression != "")
// {
// keyExpression += ",";
// }
// if (prop.BasicType == BasicType.Number)
// {
// //SQL Server.
// keyExpression += "LTRIM(STR(" + Encapsulate(prop.FieldName) + "))";
// }
// else
// {
// keyExpression += Encapsulate(prop.FieldName);
// }
// }
// else
// {
// if (addedAny)
// {
// sb.Append(",");
// }
// sb.Append(Encapsulate(prop.FieldName));
// addedAny = true;
// }
// }
// }
// return keyExpression + " As " + Encapsulate("key") + ", " + sb.ToString();
//}
public string SQLAllColumns(List<PropertyDefinition> properties)
{
StringBuilder sb = new StringBuilder();
var addedAny = false;
foreach (PropertyDefinition prop in properties)
{
if (prop.IsDBField)
{
if (addedAny)
{
sb.Append(",");
}
sb.Append(Encapsulate(prop.FieldName));
addedAny = true;
}
}
return sb.ToString();
}
public string SQLWherePrimaryKey(List<PropertyDefinition> properties)
{
StringBuilder sb = new StringBuilder();
var addedAny = false;
foreach (PropertyDefinition prop in properties)
{
if (prop.IsDBField && prop.IsPrimaryKey)
{
if (addedAny)
{
sb.Append(" AND ");
}
sb.Append(Encapsulate(prop.FieldName) + "=@" + prop.FieldName);
addedAny = true;
}
}
return sb.ToString();
}
public string SQLInsertProperties(List<PropertyDefinition> properties)
{
StringBuilder sb = new StringBuilder();
var addedAny = false;
foreach (PropertyDefinition prop in properties)
{
if (prop.IsDBField && !prop.IsIdentity && !prop.IsComputed)
{
if (addedAny)
{
sb.Append(", ");
}
sb.Append(Encapsulate(prop.FieldName));
addedAny = true;
}
}
return sb.ToString();
}
public string SQLInsertValues(List<PropertyDefinition> properties)
{
StringBuilder sb = new StringBuilder();
var addedAny = false;
foreach (PropertyDefinition prop in properties)
{
if (prop.IsDBField && !prop.IsIdentity && !prop.IsComputed)
{
if (addedAny)
{
sb.Append(", ");
}
sb.Append("@" + prop.FieldName);
addedAny = true;
}
}
return sb.ToString();
}
public string SQLUpdatePropertiesValues(List<PropertyDefinition> properties)
{
StringBuilder sb = new StringBuilder();
var addedAny = false;
foreach (PropertyDefinition prop in properties)
{
if (prop.IsDBField && !prop.IsIdentity
&& !prop.IsReadOnly && !prop.IsComputed)
{
if (addedAny)
{
sb.Append(", ");
}
sb.Append(Encapsulate(prop.FieldName) + "=@" + prop.FieldName);
addedAny = true;
}
}
return sb.ToString();
}
public string Encapsulate(string databaseword)
{
if (Dialect == DBDialectEnum.SQLServer && databaseword.Contains("."))
{
string[] parts = databaseword.Split('.');
// No more than 2.
return string.Format(Encapsulation, parts[0]) + "."
+ string.Format(Encapsulation, parts[1]);
}
return string.Format(Encapsulation, databaseword);
}
}
}
|
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 WinformControlUse
{
public partial class Forml : Form
{
public Forml()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "陈杰" && textBox2.Text == "123"|| textBox1.Text == "何辉" && textBox2.Text == "456")
{
FrmStudent f = new FrmStudent();
f.Show();
this.Hide();
}
else
{
MessageBox.Show("账号或密码错误");
}
}
private void Form3_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UEditor.Services
{
public interface IAlbumService
{
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace ContactProject.Repository
{
public class ContactRepository:IContactRepository
{
private MVCEntities context;
public ContactRepository(MVCEntities context)
{
this.context = context;
}
public IEnumerable<Contact> GetContacts()
{
return context.Contact.ToList();
}
public Contact GetContactByID(int ContactId)
{
return context.Contact.Find(ContactId);
}
public void InsertContact(Contact Contact)
{
context.Contact.Add(Contact);
}
public void DeleteContact(Contact Contact)
{
context.Entry(Contact).State = EntityState.Modified;
}
public void UpdateContact(Contact Contact)
{
context.Entry(Contact).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using EnsureThat.Annotations;
using EnsureThat.Internals;
using JetBrains.Annotations;
using NotNullAttribute = System.Diagnostics.CodeAnalysis.NotNullAttribute;
namespace EnsureThat.Enforcers
{
[SuppressMessage("Performance", "CA1822:Mark members as static")]
public sealed class StringArg
{
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string IsNotNull([ValidatedNotNull, NotNull]string value, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string IsNotNullOrWhiteSpace([ValidatedNotNull, NotNull]string value, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
if (string.IsNullOrWhiteSpace(value))
throw Ensure.ExceptionFactory.ArgumentException(ExceptionMessages.Strings_IsNotNullOrWhiteSpace_Failed, paramName);
return value;
}
[return: NotNull]
public string IsNotNullOrEmpty([ValidatedNotNull, NotNull]string value, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
if (string.IsNullOrEmpty(value))
throw Ensure.ExceptionFactory.ArgumentException(ExceptionMessages.Strings_IsNotNullOrEmpty_Failed, paramName);
return value;
}
public string IsNotEmptyOrWhiteSpace(string value, [InvokerParameterName] string paramName = null)
{
if (value == null)
{
return null;
}
if (value.Length == 0)
{
throw Ensure.ExceptionFactory.ArgumentException(ExceptionMessages.Strings_IsNotEmptyOrWhiteSpace_Failed, paramName);
}
foreach (var t in value)
{
if (!Char.IsWhiteSpace(t))
{
return value; //succeed and return as soon as we see a non-whitespace character
}
}
throw Ensure.ExceptionFactory.ArgumentException(ExceptionMessages.Strings_IsNotEmptyOrWhiteSpace_Failed, paramName);
}
public string IsNotEmpty(string value, [InvokerParameterName] string paramName = null)
{
if (value?.Length == 0)
throw Ensure.ExceptionFactory.ArgumentException(ExceptionMessages.Strings_IsNotEmpty_Failed, paramName);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string HasLength([ValidatedNotNull, NotNull]string value, int expected, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
if (value.Length != expected)
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_SizeIs_Failed, expected, value.Length),
paramName);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string HasLengthBetween([ValidatedNotNull, NotNull]string value, int minLength, int maxLength, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
var length = value.Length;
if (length < minLength)
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_HasLengthBetween_Failed_ToShort, minLength, maxLength, length),
paramName);
if (length > maxLength)
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_HasLengthBetween_Failed_ToLong, minLength, maxLength, length),
paramName);
return value;
}
[return: NotNull]
public string Matches(string value, [RegexPattern] string match, [InvokerParameterName] string paramName = null)
=> Matches(value, new Regex(match), paramName);
[return: NotNull]
public string Matches(string value, Regex match, [InvokerParameterName] string paramName = null)
{
if (!match.IsMatch(value))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_Matches_Failed, value, match),
paramName);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
[Obsolete("Use 'HasLength' instead. This will be removed in an upcoming version.")]
public string SizeIs([ValidatedNotNull, NotNull] string value, int expected, [InvokerParameterName] string paramName = null)
=> HasLength(value, expected, paramName);
public string Is(string value, string expected, [InvokerParameterName] string paramName = null)
=> IsEqualTo(value, expected, paramName);
public string Is(string value, string expected, StringComparison comparison, [InvokerParameterName] string paramName = null)
=> IsEqualTo(value, expected, comparison, paramName);
public string IsEqualTo(string value, string expected, [InvokerParameterName] string paramName = null)
{
if (!StringEquals(value, expected))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsEqualTo_Failed, value, expected),
paramName);
return value;
}
public string IsEqualTo(string value, string expected, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (!StringEquals(value, expected, comparison))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsEqualTo_Failed, value, expected),
paramName);
return value;
}
public string IsNot(string value, string notExpected, [InvokerParameterName] string paramName = null)
=> IsNotEqualTo(value, notExpected, paramName);
public string IsNot(string value, string notExpected, StringComparison comparison, [InvokerParameterName] string paramName = null)
=> IsNotEqualTo(value, notExpected, comparison, paramName);
public string IsNotEqualTo(string value, string notExpected, [InvokerParameterName] string paramName = null)
{
if (StringEquals(value, notExpected))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsNotEqualTo_Failed, value, notExpected),
paramName);
return value;
}
public string IsNotEqualTo(string value, string notExpected, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (StringEquals(value, notExpected, comparison))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsNotEqualTo_Failed, value, notExpected),
paramName);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public Guid IsGuid([ValidatedNotNull, NotNull]string value, [InvokerParameterName] string paramName = null)
{
if (!Guid.TryParse(value, out var parsed))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsGuid_Failed, value),
paramName);
return parsed;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string StartsWith([ValidatedNotNull, NotNull]string value, [NotNull] string expectedStartsWith, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
if (!value.StartsWith(expectedStartsWith, StringComparison.CurrentCulture))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_StartsWith_Failed, value, expectedStartsWith),
paramName);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string StartsWith([ValidatedNotNull, NotNull]string value, [NotNull] string expectedStartsWith, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
if (!value.StartsWith(expectedStartsWith, comparison))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_StartsWith_Failed, value, expectedStartsWith),
paramName);
return value;
}
public string IsLt(string value, string limit, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (!StringIsLt(value, limit, comparison))
throw Ensure.ExceptionFactory.ArgumentOutOfRangeException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotLt, value, limit), paramName, value);
return value;
}
public string IsLte(string value, string limit, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (StringIsGt(value, limit, comparison))
throw Ensure.ExceptionFactory.ArgumentOutOfRangeException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotLte, value, limit), paramName, value);
return value;
}
public string IsGt(string value, string limit, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (!StringIsGt(value, limit, comparison))
throw Ensure.ExceptionFactory.ArgumentOutOfRangeException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotGt, value, limit), paramName, value);
return value;
}
public string IsGte(string value, string limit, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (StringIsLt(value, limit, comparison))
throw Ensure.ExceptionFactory.ArgumentOutOfRangeException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotGte, value, limit), paramName, value);
return value;
}
public string IsInRange(string value, string min, string max, StringComparison comparison, [InvokerParameterName] string paramName = null)
{
if (StringIsLt(value, min, comparison))
throw Ensure.ExceptionFactory.ArgumentOutOfRangeException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotInRange_ToLow, value, min), paramName, value);
if (StringIsGt(value, max, comparison))
throw Ensure.ExceptionFactory.ArgumentOutOfRangeException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNotInRange_ToHigh, value, max), paramName, value);
return value;
}
[return: NotNull]
[ContractAnnotation("value:null => halt")]
public string IsAllLettersOrDigits([ValidatedNotNull, NotNull] string value, [InvokerParameterName] string paramName = null)
{
Ensure.Any.IsNotNull(value, paramName);
for (var i = 0; i < value.Length; i++)
if (!char.IsLetterOrDigit(value[i]))
throw Ensure.ExceptionFactory.ArgumentException(
string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsAllLettersOrDigits_Failed, value),
paramName);
return value;
}
private static bool StringEquals(string x, string y)
=> string.Equals(x, y, StringComparison.Ordinal);
private static bool StringEquals(string x, string y, StringComparison comparison)
=> string.Equals(x, y, comparison);
private static bool StringIsLt(string x, string y, StringComparison c)
=> string.Compare(x, y, c) < 0;
private static bool StringIsGt(string x, string y, StringComparison c)
=> string.Compare(x, y, c) > 0;
}
}
|
using System.Reflection;
[assembly: AssemblyTitle("FastAnimations")]
[assembly: AssemblyVersion("1.7.1")]
|
using System.Xml;
using AIMLbot.AIMLTagHandlers;
using AIMLbot.Utils;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AIMLbot.UnitTest.TagTests
{
[TestClass]
public class InputTagTests
{
private User _user;
private Request _request;
private SubQuery _query;
private Input _botTagHandler;
[TestInitialize]
public void Setup()
{
_user = new User();
_request = new Request("This is a test", _user);
_query = new SubQuery();
_query.InputStar.Insert(0, "first star");
_query.InputStar.Insert(0, "second star");
}
[TestMethod]
public void testResultHandlers()
{
XmlNode testNode = StaticHelpers.GetNode("<input/>");
Result mockResult = new Result(_user, _request);
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("", _botTagHandler.ProcessChange());
_request = new Request("Sentence 1. Sentence 2", _user);
mockResult.InputSentences.Add("Result 1");
mockResult.InputSentences.Add("Result 2");
_user.AddResult(mockResult);
Result mockResult2 = new Result(_user, _request);
mockResult2.InputSentences.Add("Result 3");
mockResult2.InputSentences.Add("Result 4");
_user.AddResult(mockResult2);
Assert.AreEqual("Result 3", _botTagHandler.ProcessChange());
testNode = StaticHelpers.GetNode("<input index=\"1\"/>");
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("Result 3", _botTagHandler.ProcessChange());
testNode = StaticHelpers.GetNode("<input index=\"2,1\"/>");
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("Result 1", _botTagHandler.ProcessChange());
testNode = StaticHelpers.GetNode("<input index=\"1,2\"/>");
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("Result 4", _botTagHandler.ProcessChange());
testNode = StaticHelpers.GetNode("<input index=\"2,2\"/>");
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("Result 2", _botTagHandler.ProcessChange());
testNode = StaticHelpers.GetNode("<input index=\"1,3\"/>");
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("", _botTagHandler.ProcessChange());
testNode = StaticHelpers.GetNode("<input index=\"3\"/>");
_botTagHandler = new Input(_user, _request, testNode);
Assert.AreEqual("", _botTagHandler.ProcessChange());
}
}
} |
using System;
using System.Collections.Generic;
namespace Zesty.Core.Entities
{
public class Resource
{
public Guid Id { get; set; }
public Guid ParentId { get; set; }
public string Url { get; set; }
public string Title { get; set; }
public string Image { get; set; }
public string Label { get; set; }
public int Order { get; set; }
public bool IsPublic { get; set; }
public bool RequireToken { get; set; }
public string Type { get; set; }
public Domain Domain { get; set; }
public List<Resource> Childs { get; set; }
}
}
|
using Alabo.App.Kpis.Kpis.Domain.Configs;
using Alabo.App.Kpis.Kpis.Domain.Entities;
using Alabo.App.Kpis.Kpis.Domain.Repositories;
using Alabo.App.Kpis.Kpis.Dtos;
using Alabo.Data.People.Teams.Domain.Services;
using Alabo.Data.People.Users.Domain.Services;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities;
using Alabo.Domains.Repositories;
using Alabo.Domains.Services;
using Alabo.Exceptions;
using Alabo.Framework.Basic.AutoConfigs.Domain.Services;
using Alabo.Framework.Core.Enums.Enum;
using Alabo.Users.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alabo.App.Kpis.Kpis.Domain.Services
{
/// <summary>
/// </summary>
public class KpiService : ServiceBase<Kpi, long>, IKpiService
{
/// <summary>
/// The kpi repository
/// </summary>
private readonly IKpiRepository _kpiRepository;
public KpiService(IUnitOfWork unitOfWork, IRepository<Kpi, long> repository) : base(unitOfWork, repository)
{
_kpiRepository = Repository<IKpiRepository>();
}
/// <summary>
/// 加入记录,计算TotalValue的值
/// </summary>
/// <param name="kpi">The KPI.</param>
/// <exception cref="Exception">请设置时间方式</exception>
public void AddSingle(Kpi kpi)
{
if (Convert.ToInt16(kpi.Type) <= 0) {
throw new ValidException("请设置时间方式");
}
var lastSingle = GetLastSingle(kpi);
if (lastSingle != null) {
kpi.TotalValue = lastSingle.TotalValue + kpi.Value; // 值叠加
} else {
kpi.TotalValue = kpi.Value;
}
Add(kpi);
}
/// <summary>
/// 获取最后一条记录
/// </summary>
/// <param name="kpi"></param>
public Kpi GetLastSingle(Kpi kpi)
{
return _kpiRepository.GetLastSingle(kpi);
}
/// <summary>
/// 获取绩效列表
/// </summary>
/// <param name="query">查询</param>
public PagedList<KpiView> GetKpiList(object query)
{
var config = Resolve<IAutoConfigService>().GetList<KpiAutoConfig>();
var model = Resolve<IKpiService>().GetPagedList<KpiView>(query);
model.ForEach(r => { r.Module = config?.FirstOrDefault(u => u.Id == r.ModuleId)?.Name; });
return model;
}
/// <summary>
/// 根据Kpi访问和用户获取团队方式
/// </summary>
/// <param name="kpiTeamType"></param>
/// <param name="user">用户</param>
public IList<User> GetUserByKpiTeamType(KpiTeamType kpiTeamType, User user)
{
var userList = new List<User>();
if (user != null)
{
//会员本身
if (kpiTeamType == KpiTeamType.UserSelf) {
userList.Add(user);
}
// 直推
if (kpiTeamType == KpiTeamType.RecommendUser) {
if (user.ParentId > 0)
{
var parentUser = Resolve<IUserService>().GetSingle(user.ParentId);
if (parentUser != null) {
userList.Add(parentUser);
}
}
}
// 团队
if (kpiTeamType == KpiTeamType.TeamUser) {
userList = Resolve<ITeamService>().GetTeamByGradeId(user.Id, user.GradeId, true).ToList();
}
}
return userList;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
namespace com.zhifez.seagj {
public class UI_TmKiosk : Base {
public static UI_TmKiosk instance;
public Transform container;
public Text title;
public Text values;
public Text instructions;
//--------------------------------------------------
// private
//--------------------------------------------------
//--------------------------------------------------
// public
//--------------------------------------------------
public void Setup ( TransmissionMachine _tmMachine ) {
title.text = _tmMachine.name;
instructions.text = "press W/S or Arrow Up/Down keys to switch between an offset value to alter (arranged by linked satelite dishes)";
instructions.text += "\npress A/D or Arrow Left/Right keys to change the offset value";
instructions.text += "\npress ESCAPE to close this window";
enabled = true;
}
public void UpdateValues ( TransmissionMachine tm ) {
values.text = "";
if ( tm.linkedSatDishes.Count <= 0 ) {
values.text = "this machine is not linked to any satelite dish";
values.text += "\ngo to the central kiosk to link them up";
return;
}
for ( int a=0; a<tm.linkedSatDishes.Count; ++a ) {
if ( a > 0 ) {
values.text += "\n";
}
values.text += tm.linkedSatDishes[a].sateliteDish.name;
float _valueX = tm.linkedSatDishes[a].sateliteDish.valueX;
float _valueY = tm.linkedSatDishes[a].sateliteDish.valueY;
values.text += " (str: " + _valueX.ToString ( "N2" );
values.text += ", spd: " + _valueY.ToString ( "N2" ) + ")";
int _index = Mathf.FloorToInt ( ( float ) tm.linkedSatDishIndex / 2f );
string _selected = "";
if ( _index == a && tm.linkedSatDishIndex % 2 == 0 ) {
_selected += "> ";
}
float _valueDeci = tm.linkedSatDishes[a].signalStrengthOffset;
values.text += "\n " + _selected + "signal strength offset: " + _valueDeci.ToString ( "N2" );
_selected = "";
if ( _index == a && tm.linkedSatDishIndex % 2 == 1 ) {
_selected += "> ";
}
_valueDeci = tm.linkedSatDishes[a].signalSpeedOffset;
values.text += "\n " + _selected + "signal speed offset: " + _valueDeci.ToString ( "N2" );
}
}
//--------------------------------------------------
// protected
//--------------------------------------------------
protected void Awake () {
instance = this;
container.localScale = Vector3.zero;
container.gameObject.SetActive ( false );
enabled = false;
}
protected void OnDisable () {
container.DOScale ( Vector3.zero, 0.2f )
.SetEase ( Ease.InBack )
.OnComplete ( () => {
container.gameObject.SetActive ( false );
} );
}
protected void OnEnable () {
container.localScale = Vector3.zero;
container.gameObject.SetActive ( true );
container.DOScale ( Vector3.one, 0.2f )
.SetEase ( Ease.OutBack );
}
protected void Update () {
}
}
} |
using Irony.Parsing;
namespace Bitbrains.AmmyParser
{
public class AstAmmyBindSourceAncestorData : IAstAmmyBindSourceSource, IBaseData
{
public AstAmmyBindSourceAncestorData(SourceSpan span, FullQualifiedNameData ancestorType, int? level)
{
Span = span;
AncestorType = ancestorType;
Level = level;
}
public override string ToString()
{
return $"$ancestor<{AncestorType}>({Level})";
}
public SourceSpan Span { get; }
public FullQualifiedNameData AncestorType { get; }
public int? Level { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Efa.Domain.Entities;
using Efa.Domain.Interfaces.Repository;
using Efa.Infra.Data.Context;
namespace Efa.Infra.Data.Repository
{
public class AlunoRepository : RepositoryBase<Aluno, EfaContext>, IAlunoRepository
{
public void AddAlunoTurma(IEnumerable<Aluno> alunos, Guid turmaId)
{
foreach (var aluno in alunos)
{
aluno.TurmaId = turmaId;
base.Update(aluno);
}
}
public IEnumerable<Aluno> GetAlunosNaoVinculados()
{
return base.Find(a => a.TurmaId == null).ToList();
}
public void DesvinculaAlunos(Guid turmaId)
{
foreach (var aluno in base.Find(a => a.TurmaId == turmaId).ToList())
{
aluno.TurmaId = null;
base.Update(aluno);
}
}
public IEnumerable<Aluno> GetAlunosTurma(Guid turmaId)
{
return base.DbSet.Include("Turma.Professor").Include("Notas").Where(a => a.TurmaId == turmaId).ToList();
//return base.Find(a => a.TurmaId == turmaId).ToList();
}
public IEnumerable<Aluno> GetAlunos()
{
return base.DbSet.Include("Turma.Professor").Include("Notas").ToList();
}
}
} |
using OpenAccessRuntime.metadata;
using OpenAccessRuntime.Relational.metadata;
using OpenAccessRuntime.Relational.sql;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Hosting;
using Telerik.Data.Dsl;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Metadata;
using Telerik.OpenAccess.Metadata.Fluent;
using Telerik.OpenAccess.Metadata.Fluent.Artificial;
using Telerik.OpenAccess.Runtime.Schema;
using Telerik.OpenAccess.SPI;
using Sparda.Core.Helpers;
namespace ArtificialTypesWeb
{
public partial class FluentModelContextMetadataSource : FluentMetadataSource
{
public const bool CACHING_ACTIVATED = false;
private List<MappingConfiguration> mappingConfigurations = new List<MappingConfiguration>();
private MetadataContainer _metaModel;
private bool _isLoaded = false;
public const string META_DATA_CACHE_FOLDER = "MetaDataCache";
public FluentModelContextMetadataSource() { }
public FluentModelContextMetadataSource(OpenAccessContext fluentModel)
{
DefaultMap(fluentModel);
}
public class ConnectionString
{
public ConnectionString(string connectionString)
{
try
{
var values = connectionString.ToLower().Split(';').Select(c => c.Split('=')).ToList();
this.DataSource = values.First(c => c[0] == "data source")[1];
this.InitialCatalog = values.First(c => c[0] == "initial catalog")[1];
}
catch (Exception)
{
}
}
public ConnectionString(ConnectionStringSettings con)
: this(con.ConnectionString)
{
this.Name = con.Name;
}
public string Name { get; set; }
public string DataSource { get; set; }
public string InitialCatalog { get; set; }
public bool Equals(ConnectionString other)
{
return other != null && other.InitialCatalog == this.InitialCatalog && other.DataSource == this.DataSource;
}
}
private void DefaultMap(OpenAccessContext fluentModel)
{
var connectionString = new ConnectionString(fluentModel.Connection.ConnectionString);
var connection = ConfigurationManager.ConnectionStrings.OfType<ConnectionStringSettings>().Select(c => new ConnectionString(c)).FirstOrDefault(c => c.Equals(connectionString));
string folder = HostingEnvironment.ApplicationPhysicalPath + FluentModelContextMetadataSource.META_DATA_CACHE_FOLDER;
Directory.CreateDirectory(folder);
var fileName = fluentModel.Connection.ConnectionString;
if (connection == null)
{
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + ";" + "=" + ".";
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
fileName = folder + "\\" + r.Replace(fileName, "").Replace(" ", "") + ".rlinq";
}
else
{
fileName = folder + "\\" + connection.Name + ".rlinq";
}
var name = fileName.Split('\\').Last().Replace(".rlinq", "");
var flag = fileName.Length < 260;
if (CACHING_ACTIVATED && flag && File.Exists(fileName))
{
var rlinq = File.ReadAllText(fileName);
MetadataSource xmlMetadataSource = XmlMetadataSource.FromXml(rlinq);
_metaModel = xmlMetadataSource.GetModel();
}
else
{
var reader = DbSchemaReaderImp.Create(fluentModel.Connection, fluentModel.Metadata.BackendType);
var tryCount = 5;
while (tryCount > 0)
{
System.Threading.Thread.Sleep(500);
try
{
reader.Execute();
break;
}
catch
{
tryCount--;
}
}
_metaModel = reader.MetadataContainer;
ModelSettings modelSettings = new ModelSettings();
//string backendType = modelSettings.BackendConfigurationSettings.BackendConfiguration.Backend;
//Backend backend = Telerik.OpenAccess.Helpers.EnumerationHelper.GetEnumValue<Backend>(backendType, Backend.MsSql);
IDefaultSchemaMapper defaultSchemaMapper = OpenAccessRuntime.Relational.MappingHandler.GetDefaultSchemaMapper(fluentModel.Metadata.BackendType);
//metaModel.BackendType = backend;
ITypeResolver typeResolver = defaultSchemaMapper.GetTypeResolver(_metaModel);
object namingStrategy = Reflection.Instantiate("Telerik.OpenAccess.Metadata.DefaultNamingStrategy", modelSettings.NamingSettings);
MetadataWorker metadataWorker = Reflection.InvokeStaticMethod(typeof(MetadataWorker), "With", _metaModel, namingStrategy) as MetadataWorker;
var metaWorkerContext = metadataWorker.GetProperty("Context");
metaWorkerContext.SetProperty("TypeResolver", typeResolver);
var defaultMapper = metaWorkerContext.GetProperty("DefaultMapper");
defaultMapper.InvokeMethod("Map");
var rling = _metaModel.ToString();
rling = rling.Replace("name=\"FromTablesAndProcedures\"", string.Format("name=\"{0}\"", name)).Replace("name=\"\"", string.Format("name=\"Sparda.{0}.DAL\"", name));
if (flag) File.WriteAllText(fileName, rling, System.Text.Encoding.Unicode);
//MetadataSource xmlMetadataSource = XmlMetadataSource.FromXml(rling);
}
//Sparda.Shell.FluentContext.ClassGenerator.Generate(_metaModel, name, fluentModel.Metadata.BackendType);
Dictionary<string, MappingConfiguration> configs = new Dictionary<string, MappingConfiguration>();
foreach (var persitendType in _metaModel.PersistentTypes)
{
configs[persitendType.Name] = new MappingConfiguration(persitendType.Table.Name + "Entities", "ArtificialTypesWeb");
}
foreach (var persitendType in _metaModel.PersistentTypes)
{
MappingConfiguration myConfig = configs[persitendType.Name];
var count = 0;
bool hasPK = false;
foreach (var property in persitendType.GetMembers(false))
{
try
{
if (property is MetaPrimitiveMember)
{
var metaPrimitiveMember = (MetaPrimitiveMember)property;
//MetaColumn column = metaPrimitiveMember.Column;
//MetaIndex index = _metaModel.Indexes.SingleOrDefault(c => c.Columns.Any(x => x.Column.Name == column.Name && c.Table == column.Table));
//var type = Type.GetType(metaPrimitiveMember.MemberType.FullName);
var type = ((MetaPrimitiveType)metaPrimitiveMember.MemberType).ClrType;
if (type == typeof(string))
{
StringPropertyConfiguration primitivePropertyConfiguration = myConfig
.HasArtificialStringProperty(metaPrimitiveMember.PropertyName)
.HasFieldName(metaPrimitiveMember.PropertyName)
.HasColumnType(metaPrimitiveMember.Column.SqlType)
.ToColumn(metaPrimitiveMember.Column.Name);
if (metaPrimitiveMember.Column.Length.HasValue) primitivePropertyConfiguration.HasLength(metaPrimitiveMember.Column.Length.Value);
if (metaPrimitiveMember.Column.IsNullable.HasValue)
if (metaPrimitiveMember.Column.IsNullable.Value) primitivePropertyConfiguration.IsNullable();
else primitivePropertyConfiguration.IsNotNullable();
//if (index != null && index.Unique) primitivePropertyConfiguration.
//primitivePropertyConfiguration.
if (metaPrimitiveMember.IsIdentity)
{
primitivePropertyConfiguration.IsIdentity();
hasPK = true;
}
if (!string.IsNullOrEmpty(metaPrimitiveMember.Column.Converter)) primitivePropertyConfiguration.WithConverter(metaPrimitiveMember.Column.Converter);
}
else
{
PrimitivePropertyConfiguration primitivePropertyConfiguration = myConfig
.HasArtificialPrimitiveProperty(metaPrimitiveMember.PropertyName, type)
.HasFieldName(metaPrimitiveMember.PropertyName)
.HasColumnType(metaPrimitiveMember.Column.SqlType)
.ToColumn(metaPrimitiveMember.Column.Name);
if (metaPrimitiveMember.Column.IsNullable.HasValue)
if (metaPrimitiveMember.Column.IsNullable.Value) primitivePropertyConfiguration.IsNullable();
else primitivePropertyConfiguration.IsNotNullable();
if (metaPrimitiveMember.IsIdentity)
{
var keyGenerator = KeyGenerator.Default;
switch (fluentModel.Metadata.BackendType)
{
case Backend.Ads:
break;
case Backend.Azure:
break;
case Backend.FamilyMask:
break;
case Backend.Firebird:
break;
case Backend.MsSql:
break;
case Backend.MsSql2000:
break;
case Backend.MsSql2005:
break;
case Backend.MsSql2008:
break;
case Backend.MsSql2012:
break;
case Backend.MsSql2014:
break;
case Backend.MySql:
break;
case Backend.Oracle:
break;
case Backend.Oracle10:
break;
case Backend.Oracle11:
break;
case Backend.Oracle12:
break;
case Backend.Oracle9:
break;
case Backend.PostgreSql:
break;
case Backend.SQLite:
//http://www.sqlite.org/autoinc.html
keyGenerator = KeyGenerator.Autoinc;
break;
case Backend.SqlAnywhere:
break;
case Backend.SqlCe:
break;
case Backend.VersionMask:
break;
case Backend.VistaDb:
break;
default:
break;
}
if (metaPrimitiveMember.Column.IsBackendCalculated || MetadataWorker.GetIdentityMembers(persitendType).Count > 1)
{
keyGenerator = KeyGenerator.Autoinc;
}
primitivePropertyConfiguration.IsIdentity(keyGenerator);
hasPK = true;
}
if (metaPrimitiveMember.IsVersion) primitivePropertyConfiguration.IsVersion();
if (!string.IsNullOrEmpty(metaPrimitiveMember.Column.Converter)) primitivePropertyConfiguration.WithConverter(metaPrimitiveMember.Column.Converter);
}
myConfig.MapType().WithConcurencyControl(OptimisticConcurrencyControlStrategy.Changed).ToTable(persitendType.Table.Name);
}
else if (property is MetaNavigationMember)
{
var metaNavigationMember = (MetaNavigationMember)property;
var oppositeMember = metaNavigationMember.GetOppositeMember();
ArtificialNavigationPropertyConfiguration navigationPropertyConfiguration = null;
switch (metaNavigationMember.Association.AssociationType)
{
case AssociationType.Collection:
break;
case AssociationType.DictionaryJointable:
break;
case AssociationType.ManyToManyJointable:
navigationPropertyConfiguration = myConfig
.HasArtificialCollectionAssociation(metaNavigationMember.PropertyName, configs[metaNavigationMember.MemberType.Name].ConfiguredType)
.HasFieldName(metaNavigationMember.PropertyName)
.WithOppositeCollection(oppositeMember.PropertyName)
.IsManaged();
if (metaNavigationMember.Association != null)
{
var associationParts = metaNavigationMember.Association.GetType().GetProperty("AssociationParts", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(metaNavigationMember.Association) as IList<MetaAssociationPart>;
if (associationParts != null && associationParts.Count == 2)
{
var ownPart = associationParts.First(c => c.IdentityMember.Column.Table.Name == persitendType.Table.Name);
var oppositePart = associationParts.First(c => c != ownPart);
navigationPropertyConfiguration.MapJoinTable(ownPart.ForeignKeyColumn.Table.Name, ownPart.ForeignKeyColumn.Name, oppositePart.ForeignKeyColumn.Name);
}
}
break;
case AssociationType.OneToMany:
if (metaNavigationMember.Multiplicity == Telerik.OpenAccess.Metadata.Multiplicity.Many)
{
navigationPropertyConfiguration = myConfig
.HasArtificialCollectionAssociation(metaNavigationMember.PropertyName, configs[metaNavigationMember.MemberType.Name].ConfiguredType)
.HasFieldName(metaNavigationMember.PropertyName)
.WithOpposite(oppositeMember.PropertyName)
.IsManaged();
}
else
{
navigationPropertyConfiguration = myConfig
.HasArtificialAssociation(metaNavigationMember.PropertyName, configs[metaNavigationMember.MemberType.Name].ConfiguredType)
.HasFieldName(metaNavigationMember.PropertyName)
.WithOppositeCollection(oppositeMember.PropertyName)
.IsManaged();
if (metaNavigationMember.Association != null)
{
var associationParts = MetadataWorker.GetAssociationPartsForAssociation(metaNavigationMember.Association, AssociationPartType.ForeignKey);
if (associationParts != null && associationParts.Any())
{
if (associationParts.Count == 1)
navigationPropertyConfiguration.ToColumn(associationParts.First().ForeignKeyMember.Column.Name);
else
{
}
//navigationPropertyConfiguration.ToColumn(associationParts.First().ForeignKeyMember.Column.Name);
}
}
}
break;
case AssociationType.OneToManyJointable:
break;
case AssociationType.OneToOne:
navigationPropertyConfiguration = myConfig
.HasArtificialAssociation(metaNavigationMember.PropertyName, configs[metaNavigationMember.MemberType.Name].ConfiguredType)
.HasFieldName(metaNavigationMember.PropertyName)
.WithOpposite(oppositeMember.PropertyName)
.IsManaged();
if (metaNavigationMember.Association != null)
{
var associationParts = MetadataWorker.GetAssociationPartsForAssociation(metaNavigationMember.Association, AssociationPartType.ForeignKey);
if (associationParts != null && associationParts.Any())
{
if (associationParts.Count == 1)
navigationPropertyConfiguration.ToColumn(associationParts.First().ForeignKeyMember.Column.Name);
else
{
}
//navigationPropertyConfiguration.ToColumn(associationParts.First().ForeignKeyMember.Column.Name);
}
}
break;
case AssociationType.PolymorphicReference:
break;
case AssociationType.Reference:
break;
case AssociationType.StructReference:
break;
default:
break;
}
}
count++;
}
catch (Exception ex)
{
}
}
if (hasPK && count > 0) mappingConfigurations.Add(myConfig);
}
}
#region CustomMap
//private void CustomMap(OpenAccessContext fluentModel)
//{
// var reader = DbSchemaReaderImp.Create(fluentModel.Connection, fluentModel.Metadata.BackendType);
// var tryCount = 5;
// while (tryCount > 0)
// {
// System.Threading.Thread.Sleep(500);
// try
// {
// reader.Execute();
// break;
// }
// catch
// {
// tryCount--;
// }
// }
// var container = reader.MetadataContainer;
// var getMappingResolver = reader.ExecuteMethod<RelationalMappingResolver>("GetMappingResolver");
// var driver = getMappingResolver.GetPrivateFieldValue<object>("sqlDriver");
// //Database2ClrMapperEntry.Parse()
// //list.Add(new Database2ClrMapperEntry("bit", typeof(bool)));
// //list.Add(new Database2ClrMapperEntry("bit", new bool?(true), typeof(bool?)));
// //list.Add(new Database2ClrMapperEntry("tinyint", typeof(short)));
// //list.Add(new Database2ClrMapperEntry("tinyint", new bool?(true), typeof(short?)));
// //list.Add(new Database2ClrMapperEntry("smallint", typeof(short)));
// //list.Add(new Database2ClrMapperEntry("smallint", new bool?(true), typeof(short?)));
// //list.Add(new Database2ClrMapperEntry("integer", typeof(int)));
// //list.Add(new Database2ClrMapperEntry("integer", new bool?(true), typeof(int?)));
// //list.Add(new Database2ClrMapperEntry("bigint", typeof(long)));
// //list.Add(new Database2ClrMapperEntry("bigint", new bool?(true), typeof(long?)));
// //var javaTypeMappings = getMappingResolver.GetPrivateFieldValue<System.Collections.Generic.Dictionary<Telerik.OpenAccess.Reflect.Class, RelationalJavaTypeMapping>>("javaTypeMappings");
// //var relationalTypes = getMappingResolver.GetPrivateFieldValue<System.Collections.Generic.Dictionary<string, RelationalTypeMapping>>("relationalTypes");
// //var standardTypes = getMappingResolver.GetPrivateFieldValue<System.Collections.Generic.Dictionary<int, RelationalTypeMapping>>("standardTypes");
// //var telerikCommonUIAssembly = typeof(Telerik.OpenAccess.Common.UI.DomainServiceMetadataSource).Assembly;
// //DefaultMappingSettings defaultMappingSettings = DefaultMappingSettings.GetDefaultMappingSettings(container, fluentModel.GetScope().Database.BackendConfiguration, true, string.Empty);
// //MetadataContainer defaultMappedContainer = telerikCommonUIAssembly.GetType("Telerik.OpenAccess.Common.UI.DefaultMappingHelper").ExecuteMethod<MetadataContainer>("GetDefaultMappedContainer", defaultMappingSettings);
// foreach (var table in container.Tables.Where(c => c.Columns.Any(x => x.IsPrimaryKey)).OrderBy(c => c.Name))
// {
// MappingConfiguration myConfig = new MappingConfiguration(table.Name, Constants.ArtificialTypesNameSpace);
// // myConfig.MapType().WithConcurencyControl(OptimisticConcurrencyControlStrategy.Changed).ToTable(table.Name);
// var count = 0;
// bool hasPK = false;
// foreach (var column in table.Columns.Where(c => c.AdoType.HasValue).OrderBy(c => c.Name))
// {
// try
// {
// Type type = null;
// try
// {
// var typeName = driver.ExecuteMethod<TypeName>("GetDefaultClrType", false, column);
// if (typeName.IsResolved) type = typeName.ToType();
// }
// catch (Exception)
// {
// }
// //RelationalTypeMapping typeMapping = getMappingResolver.getTypeMapping(column.AdoType.Value);
// //var typeConverter = getMappingResolver.CreateConverter(typeMapping.ConverterFactory);
// //var type = typeConverter.DefaultType;
// // var clrType = this.Metadata.DefaultMapping.Default.AdoMap.FirstOrDefault(c => (c.AdoType == (Telerik.OpenAccess.OpenAccessType)column.AdoType.Value | c.SqlType == column.SqlType));
// if (type != null)
// {
// PrimitivePropertyConfiguration primitivePropertyConfiguration = null;
// if (column.IsNullable == false && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
// {
// type = Nullable.GetUnderlyingType(type);
// }
// primitivePropertyConfiguration = myConfig.HasArtificialPrimitiveProperty(column.Name, type).HasFieldName(column.Name);
// //if (column.IsPrimaryKey)
// // primitivePropertyConfiguration = myConfig.HasArtificialPrimitiveProperty(Constants.PrimaryKeyName, type).HasFieldName(Constants.PrimaryKeyName).IsIdentity();
// //else
// // primitivePropertyConfiguration = myConfig.HasArtificialPrimitiveProperty(column.Name, type).HasFieldName(column.Name);
// if (primitivePropertyConfiguration != null)
// {
// if (column.IsPrimaryKey)
// {
// hasPK = true;
// primitivePropertyConfiguration = primitivePropertyConfiguration.IsIdentity();
// }
// primitivePropertyConfiguration.ToColumn(column.Name);
// if (column.IsNullable == true)
// {
// primitivePropertyConfiguration.IsNullable();
// }
// myConfig.MapType().WithConcurencyControl(OptimisticConcurrencyControlStrategy.Changed).ToTable(table.Name);
// count++;
// }
// }
// else
// {
// }
// }
// catch (Exception ex)
// {
// }
// }
// if (hasPK && count > 0) mappingConfigurations.Add(myConfig);
// }
//}
#endregion
protected override IList<MappingConfiguration> PrepareMapping()
{
//List<MappingConfiguration> mappingConfigurations = new List<MappingConfiguration>();
//var categoryConfiguration = new MappingConfiguration("Category", Constants.ArtificialTypesNameSpace);
//var productConfiguration = new MappingConfiguration("Product", Constants.ArtificialTypesNameSpace);
////************************ Primitive Properties ************************
//// Category Identity 1 : Id
//categoryConfiguration.HasArtificialPrimitiveProperty("Id", typeof(string))
// .HasFieldName("Id")
// .ToColumn("Id")
// .IsIdentity(KeyGenerator.Autoinc);
//// Category Identity 2 : Name
//categoryConfiguration.HasArtificialPrimitiveProperty("Name", typeof(string))
// .HasFieldName("Name")
// .ToColumn("Name")
// .IsIdentity();
//// Product Identity : ProductId
//productConfiguration.HasArtificialPrimitiveProperty("Id", typeof(string))
// .HasFieldName("Id")
// .ToColumn("Id")
// .IsIdentity(KeyGenerator.Autoinc);
//// Product FoeignKey 1 : CategoryId
//productConfiguration.HasArtificialPrimitiveProperty("CategoryId", typeof(string))
// .HasFieldName("CategoryId")
// .ToColumn("CategoryId");
//// Product FoeignKey 2 : CategoryName
//productConfiguration.HasArtificialPrimitiveProperty("CategoryName", typeof(string))
// .HasFieldName("CategoryName")
// .ToColumn("CategoryName");
////************************ Navigation Properties ************************
//categoryConfiguration.HasArtificialCollectionAssociation("Products", productConfiguration.ConfiguredType)
// .HasFieldName("Products")
// .WithOpposite("Category")
// .IsManaged();
//productConfiguration.HasArtificialAssociation("Category", categoryConfiguration.ConfiguredType)
// .HasFieldName("Category")
// .WithOppositeCollection("Products")
// .IsManaged()
// .ToColumn("CategoryId" /* should be CategoryId and CategoryName */);
////Can not use HasConstraint instead of TolColumn here because no parameters.
//mappingConfigurations.Add(categoryConfiguration);
//mappingConfigurations.Add(productConfiguration);
return mappingConfigurations;
}
protected override MetadataContainer CreateModel()
{
if (_metaModel != null)
{
if (!_isLoaded)
{
var p = base.CreateModel().PersistentTypes;
_isLoaded = true;
_metaModel.PersistentTypes.Clear();
foreach (var item in p)
{
_metaModel.PersistentTypes.Add(item);
}
}
//_metaModel.PersistentTypes = base.CreateModel().PersistentTypes;
//System.Collections.Generic.IList<Telerik.OpenAccess.Metadata.MetaPersistentType> persistentTypes = _metaModel.PersistentTypes;
//dictionary.fullname2mpt = persistentTypes.ToDictionary<Telerik.OpenAccess.Metadata.MetaPersistentType, string>((Telerik.OpenAccess.Metadata.MetaPersistentType k) => k.FullName);
return _metaModel;
}
return base.CreateModel();
}
protected override void SetContainerSettings(MetadataContainer container)
{
container.NameGenerator.RemoveCamelCase = false;
container.NameGenerator.SourceStrategy = Telerik.OpenAccess.Metadata.NamingSourceStrategy.Property;
}
public bool IsLoaded
{
get
{
return mappingConfigurations.Any();
}
}
}
} |
using UnityEngine;
using System.Collections;
public class PotionScript : MonoBehaviour {
void OnTriggerEnter2D(Collider2D coll)
{
GameObject.Find("Health").GetComponent<Health>().FullHealth();
Destroy(gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace birthdaybumps
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (string.IsNullOrEmpty(Request.QueryString["code"]) && Session["access_token"] == null)
{
Facebook fb = new Facebook(ConfigurationSettings.AppSettings["FacebookClientID"].ToString(),
ConfigurationSettings.AppSettings["FacebookSignIn"].ToString(),
ConfigurationSettings.AppSettings["FacebookRedirectUrl"].ToString());
Response.Redirect(fb.FinalSignInUrl);
}
else if (Session["access_token"] == null)
{
lblCode.Text = Request.QueryString["code"].ToString();
WebHeaderCollection collection = new WebHeaderCollection();
string redirectUrl = "https"
+ "://" + ConfigurationSettings.AppSettings["FacebookWebUrl"]
+ ConfigurationSettings.AppSettings["FacebookRedirectUrl"];
collection.Add("code", lblCode.Text);
collection.Add("redirect_uri", HttpUtility.UrlEncode
(
HttpContext.Current.Request.Url.Scheme
+ "://" + HttpContext.Current.Request.Url.Authority
+ ConfigurationSettings.AppSettings["FacebookRedirectUrl"]
)
);
collection.Add("client_secret", ConfigurationSettings.AppSettings["FacebookClientSecret"]);
string accessToken = GetWebResponse(
"https://graph.facebook.com/oauth/access_token?client_id="
+ ConfigurationSettings.AppSettings["FacebookClientID"] + "&redirect_uri=" + redirectUrl +
"&client_secret=" + ConfigurationSettings.AppSettings["FacebookClientSecret"]
+ "&code=" + lblCode.Text
, collection);
string tokens = accessToken.Split('&')[0];
string access = tokens.Split('=')[1];
//facebookToken = FacebookToken.FromJson(accessToken);
Session["access_token"] = access;
WebHeaderCollection web = new WebHeaderCollection();
string jsonOutput = GetWebResponse
(
"https://graph.facebook.com/me?fields=name,gender,email,birthday,picture,family.fields(name,gender,birthday,picture,relationship_status),friends.fields(name,gender,birthday,picture,relationship_status)&access_token=" + Session["access_token"],
web
);
result(jsonOutput);
Session["jsonOutput"] = jsonOutput;
Response.Redirect(@"https://birthdaybumps.apphb.com/Index.aspx");
BindGV();
}
else if (Session["access_token"] != null)
{
if (Session["jsonOutput"] != null)
{
result(Session["jsonOutput"].ToString());
BindGV();
}
}
}
}
protected void btnToken_Click(object sender, EventArgs e)
{
WebHeaderCollection collection = new WebHeaderCollection();
string redirectUrl = "https"
+ "://" + ConfigurationSettings.AppSettings["FacebookWebUrl"]
+ ConfigurationSettings.AppSettings["FacebookRedirectUrl"];
collection.Add("code", lblCode.Text);
collection.Add("redirect_uri", HttpUtility.UrlEncode
(
HttpContext.Current.Request.Url.Scheme
+ "://" + HttpContext.Current.Request.Url.Authority
+ ConfigurationSettings.AppSettings["FacebookRedirectUrl"]
)
);
collection.Add("client_secret", ConfigurationSettings.AppSettings["FacebookClientSecret"]);
string accessToken = GetWebResponse(
"https://graph.facebook.com/oauth/access_token?client_id="
+ ConfigurationSettings.AppSettings["FacebookClientID"] + "&redirect_uri=" + redirectUrl +
"&client_secret=" + ConfigurationSettings.AppSettings["FacebookClientSecret"]
+ "&code=" + lblCode.Text
, collection);
string tokens = accessToken.Split('&')[0];
string access = tokens.Split('=')[1];
//facebookToken = FacebookToken.FromJson(accessToken);
Session["access_token"] = access;
}
private string GetWebResponse(string url, WebHeaderCollection parameters)
{
HttpWebRequest request = null;
request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
//var sb = new StringBuilder();
//foreach (var key in parameters.AllKeys)
// sb.Append(key + "=" + parameters[key] + "&");
//request.Headers = sb.ToString();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
string result = reader.ReadToEnd();
return result;
}
private string PostWebResponse(string url, NameValueCollection parameters)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWebRequest.Method = "POST";
var sb = new StringBuilder();
foreach (var key in parameters.AllKeys)
sb.Append(key + "=" + parameters[key] + "&");
sb.Length = sb.Length - 1;
byte[] requestBytes = Encoding.UTF8.GetBytes(sb.ToString());
httpWebRequest.ContentLength = requestBytes.Length;
using (var requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
}
WebResponse response = httpWebRequest.GetResponse();
Task<WebResponse> responseTask = Task.Factory.FromAsync<WebResponse>(httpWebRequest.BeginGetResponse, httpWebRequest.EndGetResponse, null);
using (var responseStream = responseTask.Result.GetResponseStream())
{
var reader = new StreamReader(responseStream);
return reader.ReadToEnd();
}
}
protected void btnFriends_Click(object sender, EventArgs e)
{
WebHeaderCollection web = new WebHeaderCollection();
string jsonOutput = GetWebResponse
(
"https://graph.facebook.com/me?fields=name,gender,email,birthday,picture,family.fields(name,gender,birthday,picture,relationship_status),friends.fields(name,gender,birthday,picture,relationship_status)&access_token=" + Session["access_token"],
web
);
result(jsonOutput);
Session["jsonOutput"] = jsonOutput;
BindGV();
}
public void result(string jsonOutput)
{
facebookResult = FacebookResult.FromJson(jsonOutput);
}
public void BindGV()
{
BindGV1();
BindGV2();
BindGV3();
BindGV4();
BindGV5();
//BindGV6();
BindGV7();
BindGV8();
BindGV9();
BindGV10();
BindGV11();
BindGV12();
}
private void BindGV12()
{
var query = from widowed in facebookResult.friends.data
where widowed.relationship_status == "Widowed"
orderby widowed.name
select widowed;
Label12.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView12.DataSource = tb;
GridView12.DataBind();
}
private void BindGV11()
{
var query = from divorced in facebookResult.friends.data
where divorced.relationship_status == "Divorced"
orderby divorced.name
select divorced;
Label11.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView11.DataSource = tb;
GridView11.DataBind();
}
private void BindGV10()
{
var query = from separated in facebookResult.friends.data
where separated.relationship_status == "Separated"
orderby separated.name
select separated;
Label10.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView10.DataSource = tb;
GridView10.DataBind();
}
private void BindGV9()
{
var query = from open in facebookResult.friends.data
where open.relationship_status == "In an open relationship"
orderby open.name
select open;
Label9.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView9.DataSource = tb;
GridView9.DataBind();
}
private void BindGV8()
{
var query = from engaged in facebookResult.friends.data
where engaged.relationship_status == "Engaged"
orderby engaged.name
select engaged;
Label8.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView8.DataSource = tb;
GridView8.DataBind();
}
private void BindGV7()
{
var query = from relationship in facebookResult.friends.data
where relationship.relationship_status == "In a relationship"
orderby relationship.name
select relationship;
Label7.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView7.DataSource = tb;
GridView7.DataBind();
}
private void BindGV6()
{
var query = from bday in facebookResult.family.data
where (!string.IsNullOrEmpty(bday.birthday) && DateTime.Parse(bday.birthday).Day == DateTime.Now.Day
&& DateTime.Parse(bday.birthday).Month == DateTime.Now.Month)
orderby bday.name
select bday;
Label6.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum2>(query.ToList());
GridView6.DataSource = tb;
GridView6.DataBind();
}
private void BindGV5()
{
var query = from upcomingBDay in facebookResult.friends.data
where (!string.IsNullOrEmpty(upcomingBDay.birthday) && DateTime.Parse(upcomingBDay.birthday).Month >= DateTime.Now.Month)
orderby upcomingBDay.name
select upcomingBDay;
Label5.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView5.DataSource = tb;
GridView5.DataBind();
}
public void BindGV4()
{
var query = from married in facebookResult.friends.data
where married.relationship_status == "Married"
orderby married.name
select married;
Label4.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView4.DataSource = tb;
GridView4.DataBind();
}
public void BindGV3()
{
var query = from complicated in facebookResult.friends.data
where complicated.relationship_status == "It's complicated"
orderby complicated.name
select complicated;
Label3.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView3.DataSource = tb;
GridView3.DataBind();
}
public void BindGV2()
{
var query = from single in facebookResult.friends.data
where single.relationship_status == "Single"
orderby single.name
select single;
Label2.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView2.DataSource = tb;
GridView2.DataBind();
}
public void BindGV1()
{
IEnumerable<Datum> query = from bday in facebookResult.friends.data.AsEnumerable()
where (!string.IsNullOrEmpty(bday.birthday) && DateTime.Parse(bday.birthday).Day == DateTime.Now.Day
&& DateTime.Parse(bday.birthday).Month == DateTime.Now.Month)
orderby bday.name
select bday;
Label1.Text = "(" + query.Count().ToString() + ")";
DataTable tb = FacebookHeper.ToDataTable<Datum>(query.ToList());
GridView1.DataSource = tb;
GridView1.DataBind();
}
public birthdaybumps.FacebookToken facebookToken { get; set; }
public birthdaybumps.FacebookResult facebookResult { get; set; }
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView1.PageIndex = e.NewPageIndex;
this.BindGV1();
}
protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView2.PageIndex = e.NewPageIndex;
this.BindGV2();
}
protected void GridView3_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView3.PageIndex = e.NewPageIndex;
this.BindGV3();
}
protected void GridView4_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView4.PageIndex = e.NewPageIndex;
this.BindGV4();
}
protected void GridView5_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView5.PageIndex = e.NewPageIndex;
this.BindGV5();
}
protected void GridView6_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView6.PageIndex = e.NewPageIndex;
this.BindGV6();
}
protected void GridView7_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView7.PageIndex = e.NewPageIndex;
this.BindGV7();
}
protected void GridView8_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView8.PageIndex = e.NewPageIndex;
this.BindGV8();
}
protected void GridView9_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView9.PageIndex = e.NewPageIndex;
this.BindGV9();
}
protected void GridView10_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView10.PageIndex = e.NewPageIndex;
this.BindGV10();
}
protected void GridView11_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView11.PageIndex = e.NewPageIndex;
this.BindGV11();
}
protected void GridView12_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
result(Session["jsonOutput"].ToString());
GridView12.PageIndex = e.NewPageIndex;
this.BindGV12();
}
protected void btnFBFriends_Click(object sender, EventArgs e)
{
}
}
} |
using mvvm.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace mvvm.Views
{
/// <summary>
/// Interaction logic for StudentsInformationView.xaml
/// </summary>
public partial class StudentsInformationView : UserControl
{
public StudentsInformationView()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string[] info = new string[] { tbFirst.Text, tbSecond.Text };
TreeViewBase item = (TreeViewBase)StudentsTree.SelectedItem;
item.EditInfo(info);
}
private void StudentsTree_SelectedItemChanged_1(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewBase item = (TreeViewBase)StudentsTree.SelectedItem;
string[] info = item.GetInfo();
tbFirst.Text = info[0];
tbSecond.Text = info[1];
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
string[] info = new string[] { tbFirst.Text, tbSecond.Text };
TreeViewBase item = (TreeViewBase)StudentsTree.SelectedItem;
item.AddInfo(info);
}
}
} |
public enum Color
{
Red, Green, Grey, Blue, Magenta, White
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Collections.ObjectModel;
namespace JoeCalc
{
public partial class MainPage : ContentPage
{
List<Operand> operands = new List<Operand>();
public static HistoryEntry testEquation = new HistoryEntry()
{
equation = "5 + 7",
isResult = false
};
public static HistoryEntry testResult = new HistoryEntry()
{
equation = "12",
isResult = true
};
ObservableCollection<HistoryEntry> _HistoryList = new ObservableCollection<HistoryEntry>();
public ObservableCollection<HistoryEntry> HistoryList { get { return _HistoryList; } }
public void HistoryListPage()
{
historyBox.ItemsSource = _HistoryList;
// ObservableCollection allows items to be added after ItemsSource
// is set and the UI will react to changes
_HistoryList.Add(new HistoryEntry { equation = "5 + 7", isResult = false });
_HistoryList.Add(new HistoryEntry { equation = "12", isResult = true });
}
//private IList<HistoryEntry> HistoryList = new List<HistoryEntry>()
//{
// testEquation,
// testResult
//};
//private ObservableCollection<HistoryEntry> _HistoryList;
//public ObservableCollection<HistoryEntry> HistoryList {
// get
// {
// return _HistoryList ?? _HistoryList == new ObservableCollection<HistoryEntry>;
// }
// set
// {
// if (_HistoryList != value)
// {
// _HistoryList = value;
// //SetPropertyChanged();
// }
// }
//}
Operation op = new Operation();
String operation = "";
String operand = "";
bool equalsPressed = false;
public MainPage()
{
InitializeComponent();
BindingContext = new ViewModels.HistoryViewModel();
}
void OnClearButtonClicked(object sender, EventArgs e)
{
result.CursorPosition = 0;
result.Text = "";
result.SetCursor = false;
equalsPressed = false;
runningResult.Text = "";
operand = "";
operation = "";
}
void OnOperatorButtonClicked(object sender, EventArgs e)
{
string str0 = result.Text;
int cursorPosition = result.CursorPosition;
if (equalsPressed)
{
equalsPressed = false;
}
if (cursorPosition > 0)
{
Button b = (Button)sender;
operation = b.Text;
string formattedOperator = "";
switch (operation)
{
case "/":
operation = "/";
formattedOperator = "/";
break;
case "X":
operation = "*";
formattedOperator = "x";
break;
case "-":
operation = "-";
formattedOperator = "-";
break;
case "+":
operation = "+";
formattedOperator = "+";
break;
default:
break;
}
string str1 = str0.Substring(0, cursorPosition);
string str2 = str0.Substring(cursorPosition);
char before = '\0';
char after = '\0';
if (str1.Length > 0)
{
before = str1[str1.Length - 1];
}
if (str2.Length > 0)
{
after = str2[0];
}
if (before == 'x' || before == '/' || before == '+' || before == '-')
{
string str3 = str1.Substring(0, str1.Length - 1);
result.CursorPosition = cursorPosition;
result.Text = str3 + formattedOperator + str2;
}
else if (after == 'x' || after == '/' || after == '+' || after == '-')
{
string str3 = str2.Substring(1);
result.CursorPosition = cursorPosition + 1;
result.Text = str1 + formattedOperator + str3;
}
else
{
result.CursorPosition = cursorPosition + 1;
result.Text = str1 + formattedOperator + str2;
}
operand = "";
operands = op.BreakDownOperation(result.Text);
UpdateRunningResult();
}
}
void OnParenthesesButtonClicked(object sender, EventArgs e)
{
string str0 = result.Text;
int cursorPosition = result.CursorPosition;
if (equalsPressed)
{
operand = "(";
result.CursorPosition = 1;
result.Text = "(";
equalsPressed = false;
}
else if (str0.Length > 0 && cursorPosition > 0)
{
char x = str0[cursorPosition - 1];
string parenth;
int parenthSize = 1;
bool parenthSwitch = false;
int openCount = 0;
int closedCount = 0;
for (int i = 0; i < cursorPosition; i++)
{
if (str0[i] == '(')
{
openCount++;
parenthSwitch = true;
}
else if (str0[i] == ')')
{
closedCount++;
if (closedCount >= openCount)
{
parenthSwitch = false;
}
}
}
if (Char.IsNumber(x) && parenthSwitch || (x == ')' && closedCount < openCount))
{
parenth = ")";
}
else if ((Char.IsNumber(x) && !parenthSwitch) || (x == ')' && closedCount >= openCount))
{
parenth = "x(";
parenthSize = 2;
}
else if (x == '.' && parenthSwitch)
{
parenth = "0)";
parenthSize = 2;
}
else if (x == '.' && !parenthSwitch)
{
parenth = "0x(";
parenthSize = 3;
}
else
{
parenth = "(";
}
string str1 = str0.Substring(0, cursorPosition);
string str2 = str0.Substring(cursorPosition);
string str3 = str1 + parenth + str2;
operand += parenth;
result.CursorPosition = cursorPosition + parenthSize;
result.Text = str3;
}
else if (cursorPosition == 0)
{
operand = "(" + operand;
result.CursorPosition = 1;
result.Text = "(" + str0;
}
else
{
operand = "(";
result.CursorPosition = 1;
result.Text = "(";
}
operands = op.BreakDownOperation(result.Text);
UpdateRunningResult();
}
void OnDeleteButtonClicked(object sender, EventArgs e)
{
int cursorPosition = result.CursorPosition;
int selectionLength = result.SelectionLength;
string str0 = result.Text;
if (str0 == "") { }
else if (equalsPressed)
{
result.CursorPosition = 0;
result.Text = "";
operand = "";
equalsPressed = false;
operands = op.BreakDownOperation("");
}
else if (selectionLength > 0)
{
string str1 = str0.Substring(0, cursorPosition - selectionLength);
string str2 = str0.Substring(cursorPosition);
str0 = str1 + str2;
result.CursorPosition = cursorPosition;
result.Text = str0;
operands = op.BreakDownOperation(result.Text);
if (operands.Count > 0)
{
operand = op.GetOperand(operands, cursorPosition).Number;
}
else
{
operand = "";
}
UpdateRunningResult();
}
else
{
string str1 = str0.Substring(0, cursorPosition - 1);
string str2 = str0.Substring(cursorPosition);
str0 = str1 + str2;
cursorPosition--;
result.CursorPosition = cursorPosition;
result.Text = str0;
operands = op.BreakDownOperation(result.Text);
if (operands.Count > 0)
{
operand = op.GetOperand(operands, cursorPosition).Number;
}
else
{
operand = "";
}
UpdateRunningResult();
}
}
void OnNumButtonClicked(object sender, EventArgs e)
{
Button b = (Button)sender;
if ((result.Text == "") || (result.Text == "0") || equalsPressed)
{
operand = b.Text;
result.CursorPosition = 1;
equalsPressed = false;
result.Text = b.Text;
}
else
{
int cursorPosition = result.CursorPosition;
result.CursorPosition = cursorPosition + 1;
string str0 = result.Text;
string str1 = str0.Substring(0, cursorPosition);
string str2 = str0.Substring(cursorPosition);
char before = '\0';
char after = '\0';
if (str1.Length > 0)
{
before = str1[str1.Length - 1];
}
if (str2.Length > 0)
{
after = str2[0];
}
if (before == ')')
{
result.Text = str1 + 'x' + b.Text + str2;
}
else if (after == '(')
{
result.Text = str1 + b.Text + 'x' + str2;
}
else
{
result.Text = str1 + b.Text + str2;
}
if (cursorPosition == str0.Length)
operand += b.Text;
}
operands = op.BreakDownOperation(result.Text);
UpdateRunningResult();
}
void OnSignButtonClicked(object sender, EventArgs e)
{
string str0 = result.Text;
int cursorPosition = result.CursorPosition;
if (str0 == "" || equalsPressed) // If Result is Empty
{
operand = "(-";
result.CursorPosition = 2;
equalsPressed = false;
result.Text = "(-";
operands = op.BreakDownOperation(result.Text);
}
else // If Result is Not Empty
{
operands = op.BreakDownOperation(str0);
Operand currentOperand = op.GetOperand(operands, cursorPosition);
operand = currentOperand.Number;
//if (cursorPosition < str0.Length) // If Cursor is not at the end
// operand = currentOperand.Number; // Set operand to current operand
int currentStartPosition = currentOperand.StartPosition; // Set start postion to current operand's start
if (operand == "x" || operand == "/" || operand == "+" || operand == "-") // If operand is an operator
{
if (cursorPosition == str0.Length)
{
currentOperand.Number = "";
operand = "";
currentStartPosition = cursorPosition;
}
else
{
currentOperand = op.GetOperand(operands, cursorPosition + 1);
operand = currentOperand.Number;
currentStartPosition = currentOperand.StartPosition;
}
}
if (operand.Contains("-"))
{
string str1 = str0.Substring(0, currentStartPosition);
string str2;
if (str0.Length >= currentStartPosition + 2)
{
str2 = str0.Substring(currentStartPosition + 2);
}
else if (str0.Length == currentStartPosition + 1)
{
str2 = str0.Substring(currentStartPosition + 1);
}
else
{
str2 = str0.Substring(currentStartPosition);
}
string str3 = str1 + str2;
operand = operand.Remove(0, 2);
cursorPosition -= 2;
result.CursorPosition = cursorPosition;
result.Text = str3;
}
else if (operand == "" && cursorPosition == str0.Length)
{
string str1 = str0 + "(-";
operand = "(-";
cursorPosition += 2;
result.CursorPosition = cursorPosition;
result.Text = str1;
}
else
{
string str1 = str0.Substring(0, currentStartPosition);
string str2 = str0.Substring(currentStartPosition);
string str3 = str1 + "(-" + str2;
operand = operand.Insert(0, "(-");
cursorPosition += 2;
result.CursorPosition = cursorPosition;
result.Text = str3;
}
operands = op.BreakDownOperation(result.Text);
UpdateRunningResult();
}
}
void OnDotButtonClicked(object sender, EventArgs e)
{
if (operand.Contains(".")) { }
else if (result.Text == "" || equalsPressed)
{
result.CursorPosition = 2;
result.Text = "0.";
operand = "0.";
equalsPressed = false;
operands = op.BreakDownOperation(result.Text);
}
else
{
string str0 = result.Text;
int cursorPosition = result.CursorPosition;
Operand currentOperand = op.GetOperand(operands, cursorPosition);
string currentNumber;
int currentStartPosition;
if ((currentOperand == null) || !double.TryParse(currentOperand.Number, out double _))
{
currentNumber = "";
currentStartPosition = cursorPosition;
}
else
{
currentNumber = currentOperand.Number;
currentStartPosition = currentOperand.StartPosition;
}
if (currentNumber.Contains(".")) { }
else if ((currentNumber == "") || (currentStartPosition == cursorPosition))
{
string str1 = str0.Substring(0, cursorPosition);
string str2 = str0.Substring(cursorPosition);
string str3 = str1 + "0." + str2;
operand += "0.";
result.CursorPosition = cursorPosition + 2;
result.Text = str3;
operands = op.BreakDownOperation(result.Text);
UpdateRunningResult();
}
else
{
string str1 = str0.Substring(0, cursorPosition);
string str2 = str0.Substring(cursorPosition);
string str3 = str1 + "." + str2;
operand += ".";
result.CursorPosition = cursorPosition + 1;
result.Text = str3;
operands = op.BreakDownOperation(result.Text);
UpdateRunningResult();
}
}
}
void OnEqualsButtonClicked(object sender, EventArgs e)
{
ResultWithBool resultWithBool = new ResultWithBool("", false);
string equation = result.Text;
if (equation != "" && (Char.IsNumber(equation[equation.Length - 1]) || equation[equation.Length - 1] == ')'))
{
equation = equation.Replace("x", "*");
int openCount = 0;
int closedCount = 0;
for (int i = 0; i < equation.Length; i++)
{
if (equation[i] == '(')
{
openCount++;
}
else if (equation[i] == ')')
{
closedCount++;
}
if (i < equation.Length - 1 && Char.IsNumber(equation[i]))
{
if (equation[i + 1] == '(')
{
string str1 = equation.Substring(0, i + 1);
string str2 = equation.Substring(i + 1);
equation = str1 + '*' + str2;
}
}
if (i > 0 && Char.IsNumber(equation[i]))
{
if (equation[i - 1] == ')')
{
string str1 = equation.Substring(0, i);
string str2 = equation.Substring(i);
equation = str1 + '*' + str2;
}
}
}
int missingClosed = openCount - closedCount;
for (int i = 0; i < missingClosed; i++)
{
equation += ")";
}
operands = op.BreakDownOperation(equation);
resultWithBool = op.SolveOperation(operands);
string answer = resultWithBool.Result;
if (resultWithBool.Error)
{
DependencyService.Get<IMessage>().ShortAlert(answer);
runningResult.Text = "";
}
else
{
operand = answer;
operation = "";
runningResult.Text = "";
equalsPressed = true;
result.CursorPosition = answer.Length;
result.Text = answer;
HistoryEntry historyEquation = new HistoryEntry()
{
equation = equation,
isResult = false
};
HistoryList.Add(historyEquation);
HistoryEntry historyResult = new HistoryEntry()
{
equation = answer,
isResult = true
};
HistoryList.Add(historyResult);
}
}
else
{
string errorMsg = "Invalid format";
DependencyService.Get<IMessage>().ShortAlert(errorMsg);
runningResult.Text = "";
}
}
void UpdateRunningResult()
{
ResultWithBool resultWithBool = new ResultWithBool("", false);
string equation = result.Text;
operands = op.BreakDownOperation(equation);
char endChar = '\0';
if (equation != "")
{
endChar = equation[equation.Length - 1];
}
if (operands.Count > 2 && (Char.IsNumber(endChar) || endChar == ')'))
{
equation = equation.Replace("x", "*");
int openCount = 0;
int closedCount = 0;
for (int i = 0; i < equation.Length; i++)
{
if (equation[i] == '(')
{
openCount++;
}
else if (equation[i] == ')')
{
closedCount++;
}
if (i < equation.Length - 1 && Char.IsNumber(equation[i]))
{
if (equation[i + 1] == '(')
{
string str1 = equation.Substring(0, i + 1);
string str2 = equation.Substring(i + 1);
equation = str1 + '*' + str2;
}
}
if (i > 0 && Char.IsNumber(equation[i]))
{
if (equation[i - 1] == ')')
{
string str1 = equation.Substring(0, i);
string str2 = equation.Substring(i);
equation = str1 + '*' + str2;
}
}
}
int missingClosed = openCount - closedCount;
for (int i = 0; i < missingClosed; i++)
{
equation += ")";
}
operands = op.BreakDownOperation(equation);
resultWithBool = op.SolveOperation(operands);
if (resultWithBool.Error)
{
runningResult.Text = "";
}
else
{
runningResult.Text = resultWithBool.Result;
}
}
else
{
runningResult.Text = "";
}
}
void OnHistoryButtonClicked(object sender, EventArgs e)
{
if (historyBox.IsVisible)
{
historyBox.IsVisible = false;
}
else
{
historyBox.IsVisible = true;
}
}
void OnTestButtonClicked(object sender, EventArgs e)
{
string message = "Can't enter more than 15 digits";
DependencyService.Get<IMessage>().ShortAlert(message);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Diese Klasse befüllt das Whiteboard mit den Klassifikationsattributen des Protokolls.
/// </summary>
public class WhiteboardValueLoader : MonoBehaviour
{
private DataVisClassification classificationValues;
public Text nameValue;
public Text accuracyValue;
public Text resultValue;
public UIConfusionMatrixGenerator matrixGenerator;
/// <summary>
/// Methode befüllt die Klassenvariablen
/// </summary>
public void setClassification(DataVisClassification classificationValues)
{
this.classificationValues = classificationValues;
}
/// <summary>
/// Methode befüllt die UI Elemente des Canvases auf dem Whiteboard
/// </summary>
public void printValues()
{
matrixGenerator.delteCurrentmatrix();
nameValue.text = classificationValues.name;
accuracyValue.text = classificationValues.accuracy;
resultValue.text = classificationValues.getResultAsString();
if (matrixGenerator == null) { Debug.LogError("Error matrixGenerator Null"); }
// Generiert die Confusion Matrix
matrixGenerator.setMatrixValues(classificationValues.confusionMatrix);
matrixGenerator.printMatrixToCanvas();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Regadera : MonoBehaviour, IHerramientaBase
{
public Tier tier;
public string nombre;
public string descripcion;
public TipoHerramienta tipoHerramientaU;
public int durabilidadAc;
public int durabilidadTOT;
public TipoObjeto tipoObjeto;
public Sprite icono;
public Tier Tier { get; set; }
public string Nombre { get; set; }
public string Descripcion { get; set; }
public TipoHerramienta TipoHerramientaU { get; set; }
public GameObject ObjetoRelacionado { get; set; }
public TipoObjeto TipoObjeto { get; set; }
public int DurabilidadAc { get; set; }
public int DurabilidadTOT { get; set; }
public Sprite Icono { get; set; }
public int AguaActual { get; private set; }
private int capacidadRegadera;
//Autodestruccion
public bool Autodestruir
{
get => autodestruir;
set
{
if (!value)
{
tiempoPasado = 0;
}
autodestruir = value;
}
}
private float tiempoPasado;
private float tiempoNecesario;
private bool autodestruir;
void Awake()
{
Tier = tier;
Nombre = nombre;
Descripcion = descripcion;
TipoHerramientaU = tipoHerramientaU;
ObjetoRelacionado = transform.gameObject;
TipoObjeto = tipoObjeto;
DurabilidadAc = durabilidadAc;
DurabilidadTOT = durabilidadTOT;
Icono = icono;
tiempoNecesario = float.Parse(GestorDatos.DatosGenericos["Items"]["TiempoDesaparicionS"].ToString());
capacidadRegadera = int.Parse(GestorDatos.Herramientas[Enum.GetName(typeof(TipoHerramienta), TipoHerramientaU)][Enum.GetName(typeof(Tier), Tier)]["Capacidad"].ToString());
tiempoPasado = 0;
autodestruir = false;
AguaActual = capacidadRegadera;
}
private void Update()
{
if (autodestruir)
{
tiempoPasado += Time.deltaTime;
if (tiempoPasado >= tiempoNecesario)
{
Destroy(gameObject);
}
}
}
public override string ToString()
{
return Nombre;
}
public bool Usar()
{
if (AguaActual > 0)
{
AguaActual--;
return true;
}
else
{
return false;
}
}
public void Recargar()
{
AguaActual = capacidadRegadera;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.EntityFrameworkCore;
using ZavenDotNetInterview.Abstract;
using ZaventDotNetInterview.Models;
namespace ZavenDotNetInterview.Data.Repository
{
public class Repository<TEntity> : IRepository<TEntity> where TEntity : BaseEntityModel
{
protected readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public virtual TEntity Get(Guid id)
{
return Context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().OrderBy(t => t.CreatedAt).ToList();
}
public virtual Guid Add(TEntity entity)
{
Context.Set<TEntity>().Add(entity);
return entity.Id;
}
}
}
|
using PhanMemQuanLyKhachSan.Model;
using QuanLyNhaHang.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Menu = QuanLyNhaHang.Helper.Menu;
namespace QuanLyNhaHang
{
public partial class frmManHinhChinh : Form
{
private Button currentBtn;
private Panel leftBorderBtn;
private Form currentChildForm;
public frmManHinhChinh()
{
InitializeComponent();
LoadTable();
LoadCategory();
}
private void OpenChildForm(Form childForm)
{
//open only form
if (currentChildForm != null)
{
currentChildForm.Close();
}
currentChildForm = childForm;
//End
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm);
panel1.Tag = childForm;
childForm.BringToFront();
childForm.Show();
// lblTitleChildForm.Text = childForm.Text;
}
private void QuanLyNhaHang_Click(object sender, EventArgs e)
{
flpTable.Controls.Clear();
OpenChildForm(new frmQuanLyNhaHang());
}
private void quảnLýNhânViênToolStripMenuItem_Click(object sender, EventArgs e)
{
flpTable.Controls.Clear();
OpenChildForm(new frmQuanLyNhanVien());
}
private void quảnLýKháchHàngToolStripMenuItem_Click(object sender, EventArgs e)
{
flpTable.Controls.Clear();
OpenChildForm(new frmQuanLyKhachHang());
}
private void đăngXuấtToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void liênHệToolStripMenuItem_Click(object sender, EventArgs e)
{
flpTable.Controls.Clear();
OpenChildForm(new frmLienHe());
}
private void trangChủToolStripMenuItem_Click(object sender, EventArgs e)
{
LoadTable();
LoadCategory();
if (currentChildForm != null)
{
currentChildForm.Close();
}
}
void LoadTable()
{
List<Table> tableList = TableDAO.Instance.LoadTableList();
foreach (Table item in tableList)
{
Button btn = new Button() { Width = TableDAO.TableWidth, Height = TableDAO.TableHeight };
btn.Text = item.MaBan + Environment.NewLine + item.TrangThai;
btn.Click += btn_Click;
btn.Tag = item;
switch (item.TrangThai)
{
case "Đang Sử Dụng":
btn.BackColor = Color.Green;
break;
default:
btn.BackColor = Color.IndianRed;
break;
}
flpTable.Controls.Add(btn);
}
}
void btn_Click(object sender, EventArgs e)
{
string tableID = ((sender as Button).Tag as Table).MaBan;
lsvOrder.Tag = (sender as Button).Tag;
ShowOrder(tableID);
}
void ShowOrder(string id)
{
lsvOrder.Items.Clear();
List<Menu> listBillInfo = MenuDAO.Instance.GetListMenu(id);
float totalPrice = 0;
foreach (Menu item in listBillInfo)
{
ListViewItem lsvItem = new ListViewItem(item.MaPYC.ToString());
lsvItem.SubItems.Add(item.FoodName.ToString());
lsvItem.SubItems.Add(item.Count.ToString());
lsvItem.SubItems.Add(item.Price.ToString());
lsvItem.SubItems.Add(item.TotalPrice.ToString());
txtMaPYC.Text = item.MaPYC.ToString();
totalPrice += item.TotalPrice;
lsvOrder.Items.Add(lsvItem);
}
CultureInfo culture = new CultureInfo("vi-VN");
Thread.CurrentThread.CurrentCulture = culture;
txtTotalPrice.Text = totalPrice.ToString("c", culture);
}
void LoadCategory()
{
List<Category> listCategory = CategoryDAO.Instance.GetListCategory();
cmbNhomMA.DataSource = listCategory;
cmbNhomMA.DisplayMember = "TenNhomMA";
}
void LoadFoodListByCategoryID(string id)
{
List<Food> listFood = FoodDAO.Instance.GetFoodByCategoryID(id);
cmbMA.DataSource = listFood;
cmbMA.DisplayMember = "TenMA";
}
private void btnThemMonAn_Click(object sender, EventArgs e)
{
Table table = lsvOrder.Tag as Table;
string idOrder = OrderDAO.Instance.GetUncheckOrderID(table.MaBan);
string foodID = (cmbMA.SelectedItem as Food).MaMA;
int count = (int)nmFoodCount.Value;
if (idOrder == "-1")
{
OrderDAO.Instance.InsertOrder(table.MaBan);
OrderDetailDAO.Instance.InsertOrderInfo(OrderDAO.Instance.GetMaxIDOrder(), foodID, count);
}
else
{
OrderDetailDAO.Instance.InsertOrderInfo(idOrder, foodID, count);
}
ShowOrder(table.MaBan);
}
private void cmbNhomMA_SelectedIndexChanged(object sender, EventArgs e)
{
string id = "";
ComboBox cb = sender as ComboBox;
if (cb.SelectedItem == null)
return;
Category selected = cb.SelectedItem as Category;
id = selected.MaNhomMA;
LoadFoodListByCategoryID(id);
}
private void btnThanhToan_Click(object sender, EventArgs e)
{
Table table = lsvOrder.Tag as Table;
string idBill = OrderDAO.Instance.GetUncheckOrderID(table.MaBan);
if (idBill != "-1")
{
if (MessageBox.Show("Bạn có chắc thanh toán hóa đơn cho bàn " + table.MaBan, "Thông báo", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
{
OrderDAO.Instance.CheckOut(idBill);
ShowOrder(table.MaBan);
LoadTable();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EmberMemory.Components.Collector
{
public interface ICollectorContainer
{
public ValueTask Run(CancellationToken cancellationToken);
}
public interface ICollectorContainer<T> : ICollectorContainer where T : ICollector
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIHitEffect : MonoBehaviour {
public AnimationCurve scaleCurve;
public float time = 0.3f;
void Start () {
transform.localScale = Vector3.zero;
StartCoroutine(Animate());
}
private IEnumerator Animate()
{
var t = 0.0f;
while (t < time)
{
t += GameManager.Instance.asUpdateTime;
transform.localScale = Vector3.one * scaleCurve.Evaluate(t / time);
yield return new WaitForSecondsRealtime(GameManager.Instance.asUpdateTime);
}
Destroy(gameObject);
}
}
|
using System;
using System.Xml.Linq;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
namespace work_with_the_register
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (radioButton1.Checked) SaveToXML();
else if (radioButton2.Checked) SaveToTxt();
else if (radioButton3.Checked) SaveToBinary();
else SaveToRegistry();
}
private void Form1_Load(object sender, EventArgs e)
{
//different ways to read params
//ReadFromXML();
//ReadFromTxt();
//ReadFromBinary();
ReadFromRegistry();
}
//functions to save and restore parameters
private void SaveToTxt()
{
string writePath = @".\params.txt";
try
{
using (StreamWriter sw = new StreamWriter(writePath, false, System.Text.Encoding.Default))
{
sw.WriteLine(this.Location.X);
sw.WriteLine(this.Location.Y);
sw.WriteLine(this.Width);
sw.WriteLine(this.Height);
sw.WriteLine(this.textBox1.Text);
sw.WriteLine(this.checkBox1.Checked);
sw.WriteLine(this.checkBox2.Checked);
sw.WriteLine(this.radioButton1.Checked);
sw.WriteLine(this.radioButton2.Checked);
sw.WriteLine(this.radioButton3.Checked);
sw.WriteLine(this.radioButton4.Checked);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadFromTxt()
{
string readPath = @".\params.txt";
var file = new FileInfo(readPath);
if (file.Exists && file.Length != 0)
{
try
{
using (StreamReader sr = new StreamReader(readPath, System.Text.Encoding.Default))
{
this.Location = new Point(Convert.ToInt32(sr.ReadLine()), Convert.ToInt32(sr.ReadLine()));
this.Width = Convert.ToInt32(sr.ReadLine());
this.Height = Convert.ToInt32(sr.ReadLine());
this.textBox1.Text = sr.ReadLine();
this.checkBox1.Checked = Convert.ToBoolean(sr.ReadLine());
this.checkBox2.Checked = Convert.ToBoolean(sr.ReadLine());
this.radioButton1.Checked = Convert.ToBoolean(sr.ReadLine());
this.radioButton2.Checked = Convert.ToBoolean(sr.ReadLine());
this.radioButton3.Checked = Convert.ToBoolean(sr.ReadLine());
this.radioButton4.Checked = Convert.ToBoolean(sr.ReadLine());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void SaveToXML()
{
try
{
var xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Parameters",
new XElement("X", this.Location.X),
new XElement("Y", this.Location.Y),
new XElement("Width", this.Width),
new XElement("Height", this.Height),
new XElement("Text", this.textBox1.Text),
new XElement("checkBox_1", this.checkBox1.Checked),
new XElement("checkBox_2", this.checkBox2.Checked),
new XElement("rb_1", this.radioButton1.Checked),
new XElement("rb_2", this.radioButton2.Checked),
new XElement("rb_3", this.radioButton3.Checked),
new XElement("rb_4", this.radioButton3.Checked)
));
//save it to the current directory
xmlDoc.Save(Path.Combine(Environment.CurrentDirectory, "xmlParams.xml"));
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadFromXML()
{
string xmlPath = @".\xmlParams.xml";
var file = new FileInfo(xmlPath);
if (file.Exists && file.Length != 0)
{
XmlTextReader reader = new XmlTextReader(xmlPath);
reader.ReadToFollowing("Parameters");
reader.MoveToFirstAttribute();
//location
reader.ReadToFollowing("X");
Point p = new Point();
p.X = Convert.ToInt32(reader.ReadElementContentAsString());
reader.ReadToFollowing("Y");
p.Y = Convert.ToInt32(reader.ReadElementContentAsString());
this.Location = p;
//sizes
Size s = new Size();
reader.ReadToFollowing("Width");
s.Width = Convert.ToInt32(reader.ReadElementContentAsString());
reader.ReadToFollowing("Height");
s.Height = Convert.ToInt32(reader.ReadElementContentAsString());
this.Size = s;
//text
reader.ReadToFollowing("Text");
this.textBox1.Text = reader.ReadElementContentAsString();
//checkboxes
reader.ReadToFollowing("checkBox_1");
this.checkBox1.Checked = Convert.ToBoolean(reader.ReadElementContentAsString());
reader.ReadToFollowing("checkBox_2");
this.checkBox2.Checked = Convert.ToBoolean(reader.ReadElementContentAsString());
//radio
reader.ReadToFollowing("rb_1");
this.radioButton1.Checked = Convert.ToBoolean(reader.ReadElementContentAsString());
reader.ReadToFollowing("rb_2");
this.radioButton2.Checked = Convert.ToBoolean(reader.ReadElementContentAsString());
reader.ReadToFollowing("rb_3");
this.radioButton3.Checked = Convert.ToBoolean(reader.ReadElementContentAsString());
reader.ReadToFollowing("rb_4");
this.radioButton4.Checked = Convert.ToBoolean(reader.ReadElementContentAsString());
reader.Close();
file.Delete();
}
}
private void SaveToBinary()
{
string writePath = @".\params.dat";
try
{
using (BinaryWriter bw = new BinaryWriter(File.Open(writePath, FileMode.OpenOrCreate)))
{
bw.Write(this.Location.X);
bw.Write(this.Location.Y);
bw.Write(this.Width);
bw.Write(this.Height);
bw.Write(this.textBox1.Text);
bw.Write(this.checkBox1.Checked);
bw.Write(this.checkBox2.Checked);
bw.Write(this.radioButton1.Checked);
bw.Write(this.radioButton2.Checked);
bw.Write(this.radioButton3.Checked);
bw.Write(this.radioButton4.Checked);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReadFromBinary()
{
string readPath = @".\params.dat";
FileInfo file = new FileInfo(readPath);
if (file.Exists && file.Length != 0)
{
try
{
using (BinaryReader br = new BinaryReader(File.Open(readPath, FileMode.Open)))
{
while (br.PeekChar() > -1)
{
Point p = new Point(br.ReadInt32(), br.ReadInt32());
this.Width = br.ReadInt32();
this.Height = br.ReadInt32();
this.textBox1.Text = br.ReadString();
this.checkBox1.Checked = br.ReadBoolean();
this.checkBox2.Checked = br.ReadBoolean();
this.radioButton1.Checked = br.ReadBoolean();
this.radioButton2.Checked = br.ReadBoolean();
this.radioButton3.Checked = br.ReadBoolean();
this.radioButton4.Checked = br.ReadBoolean();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void SaveToRegistry()
{
RegistryKey currentUser = Registry.CurrentUser;
RegistryKey paramsKey = currentUser.CreateSubKey("Parameters");
paramsKey.SetValue("X", this.Location.X);
paramsKey.SetValue("Y", this.Location.Y);
paramsKey.SetValue("Width", this.Width);
paramsKey.SetValue("Height", this.Height);
paramsKey.SetValue("Text", this.textBox1.Text);
paramsKey.SetValue("checkBox_1", this.checkBox1.Checked);
paramsKey.SetValue("checkBox_2", this.checkBox2.Checked);
paramsKey.SetValue("rb_1", this.radioButton1.Checked);
paramsKey.SetValue("rb_2", this.radioButton2.Checked);
paramsKey.SetValue("rb_3", this.radioButton3.Checked);
paramsKey.SetValue("rb_4", this.radioButton4.Checked);
paramsKey.Close();
}
private void ReadFromRegistry()
{
try
{
RegistryKey paramsKey = Registry.CurrentUser.CreateSubKey("Parameters");
if (paramsKey.ValueCount != 0)
{
Point p = new Point();
p.X = Convert.ToInt32(paramsKey.GetValue("X"));
p.Y = Convert.ToInt32(paramsKey.GetValue("Y"));
this.Location = p;
this.Width = Convert.ToInt32(paramsKey.GetValue("Width"));
this.Height = Convert.ToInt32(paramsKey.GetValue("Height"));
this.Text = paramsKey.GetValue("Text").ToString();
this.checkBox1.Checked = Convert.ToBoolean(paramsKey.GetValue("checkBox_1"));
this.checkBox2.Checked = Convert.ToBoolean(paramsKey.GetValue("checkBox_2"));
this.radioButton1.Checked = Convert.ToBoolean(paramsKey.GetValue("rb_1"));
this.radioButton2.Checked = Convert.ToBoolean(paramsKey.GetValue("rb_2"));
this.radioButton3.Checked = Convert.ToBoolean(paramsKey.GetValue("rb_3"));
this.radioButton4.Checked = Convert.ToBoolean(paramsKey.GetValue("rb_4"));
//close
paramsKey.Close();
Registry.CurrentUser.DeleteSubKey("Parameters");
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Yaringa.Models.Token;
namespace Yaringa.UnitTests.Models.Token {
public class FakeTokensClient : ITokensClient {
public async Task<TokenDTO> CreateAsync(TokenCreationDTO dto) {
return new TokenDTO() {
Access_token = "part1.part2.part3",
Token_type = "bearer",
Expires_in = 1799,
Refresh_token = "1234567890",
};
}
public Task<TokenDTO> CreateAsync(TokenCreationDTO dto, CancellationToken cancellationToken) {
throw new NotImplementedException();
}
public async Task<TokenDTO> RefreshAsync(TokenRefreshDTO dto) {
return new TokenDTO() {
Access_token = "part1.part2.part3",
Token_type = "bearer",
Expires_in = 1799,
Refresh_token = "1234567890",
};
}
public Task<TokenDTO> RefreshAsync(TokenRefreshDTO dto, CancellationToken cancellationToken) {
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace SPA.Models.DAO
{
public static class Animaux_enqueteDAO
{
/// <summary>
/// Recupere les animaux de l'enquete
/// </summary>
/// <param name="Id">id de l'enquete</param>
/// <returns></returns>
public static List<Animaux_enquete> GetAnimaux(string Id)
{
List<Animaux_enquete> animaux_Enquetes = new List<Animaux_enquete>();
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"SELECT * FROM Animaux_enquete WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", Id);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
while (dr.Read())
{
Animaux_enquete animal = new Animaux_enquete();
//display retrieved record (first column only/string value)
animal.Enquete.Id = dr.GetString(0);
animal.Race = Race_animal.GetRace_AnimalBdd(dr.GetInt32(1));
animal.Nombre = dr.GetInt32(2);
animaux_Enquetes.Add(animal);
}
}
else
{
Console.WriteLine("No data found.");
}
dr.Close();
}
return animaux_Enquetes;
}
catch (Exception ex)
{
throw;
}
}
public static bool AddAnimalEnquete(Animaux_enquete animal)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"INSERT INTO Animaux_enquete (Id, Race, Nombre) VALUES (@Id, @Race, @Nombre);";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", animal.Enquete.Id);
cmd.Parameters.AddWithValue("@Race", animal.Race.Id);
cmd.Parameters.AddWithValue("@Nombre", animal.Nombre);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
public static bool UpdateAnimalEnquete(Animaux_enquete animal)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"UPDATE Animaux_enquete SET Race = @Race, Nombre = @Nombre WHERE Id = @Id;";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", animal.Enquete.Id);
cmd.Parameters.AddWithValue("@Race", animal.Race.Id);
cmd.Parameters.AddWithValue("@Nombre", animal.Nombre);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
public static bool DeleteAnimauxEnquete(Enquete enquete)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"DELETE FROM Animaux_enquete WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", enquete.Id);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
public static bool DeleteAnimal(Animaux_enquete animal)
{
bool res = false;
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"DELETE FROM Animaux_enquete WHERE Id = @Id AND Race = @Race AND Nombre = @Nombre";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", animal.Enquete.Id);
cmd.Parameters.AddWithValue("@Race", animal.Race.Id);
cmd.Parameters.AddWithValue("@Nombre", animal.Nombre);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
res = true;
}
dr.Close();
}
return res;
}
catch (Exception ex)
{
throw;
}
}
public static int GetNombreAnimaux(string Id)
{
try
{
using (SqlConnection conn = new SqlConnection(Variables.connectionSql))
{
//retrieve the SQL Server instance version
string query = @"SELECT sum(Nombre) FROM Animaux_enquete WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", Id);
//open connection
conn.Open();
//execute the SQLCommand
SqlDataReader dr = cmd.ExecuteReader();
//check if there are records
if (dr.HasRows)
{
if (dr.Read())
{
return !dr.IsDBNull(0) ? dr.GetInt32(0) : 0;
}
}
else
{
Console.WriteLine("No data found.");
}
dr.Close();
}
return 0;
}
catch (Exception ex)
{
throw;
}
}
}
}
|
namespace TripLog.Services
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Models;
public interface ITripLogDataService
{
Task<IEnumerable<TripLogEntry>> ReadAllEntriesAsync();
Task AddEntryAsync(TripLogEntry entry);
Task DeleteEntryAsync(TripLogEntry entry);
}
} |
using System;
namespace Cache.Core.Events
{
public class CacheEventArgs<TKey> : EventArgs
{
protected TKey key;
public CacheEventArgs(TKey key)
{
if(key != null)
this.key = key;
else
throw new ArgumentException("Key must not be empty");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace rockpaperscissorslizardspock
{
class playerHuman : Player
{
public override void SetGestures()
{
Console.WriteLine("Enter your gesture: Rock, Paper, Scissors, Lizard, Spock");
if (gestures == "rock")
{
if (playerHuman == "lizard" || playerHuman == "scissors") ;
{
Console.WriteLine("You Win!");
}
else if (playerHuman == "paper")
{
Console.WriteLine ("You Lose!");
lose++;
}
else if (playerHuman == "spock")
{
Console.WriteLine ("You Lose!");
lose++;
}
}
else if (playerGesture == "paper")
{
if (playerHuman == "spock")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "rock")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "lizard")
{
Console.WriteLine ("You Lose!");
lose++;
}
else if (playerHuman == "scissors")
{
Console.WriteLine ("You Lose!");
lose++;
}
}
else if (playerGesture == "scissors")
{
if (playerHuman == "paper")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "lizard")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "rock")
{
Console.WriteLine ("You Lose!");
lose++;
}
else if (playerHuman == "spock")
{
Console.WriteLine ("You Lose!);
lose++;
}
}
else if ( playerGesture == "lizard")
{
if (playerHuman == "paper")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "spock")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "scissors")
{
Console.WriteLine ("You Lose!");
lose++;
}
else if (playerHuman == "rock")
{
Console.WriteLine ("You Lose!");
lose++;
}
}
else if (playerGesture == "spock")
{
if (playerHuman == "rock")
{
Console.WriteLine("You Win!");
win++;
}
else if (playerHuman == "scissors")
{
Console.WriteLine ("You Win!");
win++;
}
else if (playerHuman == "paper")
{
Console.WriteLine ("You Lose!");
lose++;
}
else if (playerHuman == "lizard")
{
Console.WriteLine("You Lose!");
lose++;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using IRAP.Global;
namespace IRAP.Client.Global.WarningLight
{
public class ZLan6042 : WarningLight
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private static int redStatus = 0;
private static int yellowStatus = 0;
private static int greenStatus = 0;
private Socket clientSocket = null;
private static ZLan6042 _instance = null;
public ZLan6042()
{
}
~ZLan6042()
{
if (clientSocket != null)
{
if (clientSocket.Connected)
{
byte[] data = new byte[12]
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x01, 0x05, 0x00, 0x10, 0x00, 0x00,
};
data[9] = 0x10;
clientSocket.Send(data, data.Length, SocketFlags.None);
Thread.Sleep(100);
data[9] = 0x11;
clientSocket.Send(data, data.Length, SocketFlags.None);
Thread.Sleep(100);
data[9] = 0x12;
clientSocket.Send(data, data.Length, SocketFlags.None);
Thread.Sleep(100);
}
}
}
public static ZLan6042 Instance
{
get
{
if (_instance == null)
_instance = new ZLan6042();
return _instance;
}
}
private void SetLightCmdWithStatus(ref byte[] data, int status)
{
if (status == 1)
{
data[10] = 0xff;
}
else
data[10] = 0x00;
data[11] = 0x00;
}
public override void SetLightStatus(int red, int yellow, int green)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
SetLightStatus("192.168.57.150", red, yellow, green);
}
public override void SetLightStatus(string ipAddress, int red, int yellow, int green)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
int port = 4196;
WriteLog.Instance.Write(
string.Format("建立 [{0}:{1}] 的 Socket 连接", ipAddress, port),
strProcedureName);
if (clientSocket == null)
{
clientSocket =
new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
}
if (!clientSocket.Connected)
{
try
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipAddress), port);
clientSocket.Connect(ipep);
}
catch (SocketException ex)
{
WriteLog.Instance.Write(
string.Format(
"无法连接告警灯控制盒[{0}:{1}],原因:[{2}]",
ipAddress,
port,
ex.Message),
strProcedureName);
return;
}
}
if (clientSocket.Connected)
{
byte[] data = new byte[12]
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x06,
0x01, 0x05, 0x00, 0x10, 0x00, 0x00,
};
if (red != redStatus)
{
WriteLog.Instance.Write("发送控制红灯的继电器触点状态", strProcedureName);
redStatus = red;
data[9] = 0x10;
SetLightCmdWithStatus(ref data, red);
clientSocket.Send(data, data.Length, SocketFlags.None);
Thread.Sleep(50);
}
if (yellow != yellowStatus)
{
WriteLog.Instance.Write("发送控制黄灯的继电器触点状态", strProcedureName);
yellowStatus = yellow;
data[9] = 0x11;
SetLightCmdWithStatus(ref data, yellow);
clientSocket.Send(data, data.Length, SocketFlags.None);
Thread.Sleep(50);
}
if (green != greenStatus)
{
WriteLog.Instance.Write("发送控制绿灯的继电器触点状态", strProcedureName);
greenStatus = green;
data[9] = 0x12;
SetLightCmdWithStatus(ref data, green);
clientSocket.Send(data, data.Length, SocketFlags.None);
Thread.Sleep(50);
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurtleEgg : MonoBehaviour
{
public float speed;
private GameController gameController;
void Start () {
gameController = GameObject.Find("GameController").GetComponent<GameController>();
}
void Update () {
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player")) {
gameController.PlaySoundEffect("eggColected");
other.GetComponent<PlayerController>().CollectEgg(1);
Destroy(gameObject);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiEmpresas.Models
{
public class EmpresaDbContext : DbContext
{
public EmpresaDbContext(DbContextOptions<EmpresaDbContext> options) : base(options)
{
}
public DbSet<Empresa> Empresas { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyDev.BL;
using System.Data;
using EasyDev.Applications.SQMS;
namespace SQMS.Services
{
public class MonitorPointService : GenericService, IPortalPartService
{
public EnumerationService EnumService { get; private set; }
protected override void Initialize()
{
BOName = "MPASSIGNMENT";
EnumService = ServiceManager.CreateService<EnumerationService>();
base.Initialize();
}
public void UpdateMonitorPointTimeSchema(string timeschemaId, string mpid)
{
try
{
DefaultSession.ExecuteCommand(
string.Format("update {0} set schemaid=:schemaid where organizationid=:orgid and mpid=:mpid", BOName), timeschemaId, CurrentUser.OrganizationID, mpid);
}
catch (Exception e)
{
throw e;
}
}
public DataSet GetListDataByType(string type)
{
try
{
DataSet ds = DefaultSession.GetDataSetFromCommand(@"select mpa.mpid,mpa.mpname,mpa.isvoid,mpa.importance,mpa.longitude,mpa.latitude from mpassignment mpa
left join enumeration e on mpa.importance=e.enumid where mpa.organizationid=:orgid and mptype=:type", CurrentUser.OrganizationID, type);
ds.Tables[0].TableName = BOName;
return ds;
}
catch (Exception e)
{
throw e;
}
}
#region IPortalPartService 成员
public DataSet GetPortalPartData()
{
try
{
DataSet ds = new DataSet();
DataTable dt = DefaultSession.GetDataTableFromCommand(@"select t.mpid, t.mpname,t.chargeperson,t.empid, t.trend from
(
select max(MP.MPID) mpid,
max(q.qualitylevel) qualitylevel,
max(MP.MPNAME) mpname,
max(q.chargeperson) empid,
max(e.empname) chargeperson,
sum(decode(
sign(to_number(to_char(q.created, 'yyyyiw'))-to_number(to_char(sysdate,'yyyyiw'))),0,1,-1,-1,49,1,0)*nvl(Q.QUALITYLEVEL,0)) trend
from mpassignment mp
left join quality q on MP.MPID = Q.MPID and q.organizationid=:organizationid
left join employee e on e.empid = q.chargeperson and e.organizationid=:organizationid
where MP.organizationid=:organizationid and to_char(q.created, 'yyyy')=to_char(sysdate,'yyyy')
group by mp.mpid
order by qualitylevel desc
) t where rownum<=5", CurrentUser.OrganizationID, CurrentUser.OrganizationID, CurrentUser.OrganizationID);
dt.TableName = "WeekTrend";
ds.Tables.Add(dt);
dt = DefaultSession.GetDataTableFromCommand(@"select t.mpid, t.mpname, t.chargeperson,t.empid, t.trend from
(
select max(MP.MPID) mpid,
max(q.qualitylevel) qualitylevel,
max(e.empname) chargeperson,
max(q.chargeperson) empid,
max(MP.MPNAME) mpname,
sum(decode(
to_number(to_char(q.created, 'yyyymm'))-to_number(to_char(sysdate, 'yyyymm')),0,1,
to_number(to_char(q.created, 'yyyymm'))-to_number(to_char(add_months(q.created, -1),'yyyymm')),0,-1,0)*nvl(Q.QUALITYLEVEL,0)) trend
from mpassignment mp
left join quality q on MP.MPID = Q.MPID and q.organizationid=:organizationid
left join employee e on e.empid = q.chargeperson and e.organizationid=:organizationid
where MP.organizationid=:organizationid and to_char(q.created, 'yyyy')=to_char(sysdate,'yyyy')
group by mp.mpid
order by qualitylevel desc
) t
where rownum<=5", CurrentUser.OrganizationID, CurrentUser.OrganizationID, CurrentUser.OrganizationID);
dt.TableName = "MonthTrend";
ds.Tables.Add(dt);
dt = DefaultSession.GetDataTableFromCommand(@"select t.mpid,t.empid, t.mpname,t.chargeperson, t.trend from
(
select max(MP.MPID) mpid,
max(e.empname) chargeperson,
max(q.qualitylevel) qualitylevel,
max(q.chargeperson) empid,
max(MP.MPNAME) mpname,
sum(decode(
to_number(to_char(q.created, 'yyyy'))-to_number(to_char(sysdate, 'yyyy')),0,1,
to_number(to_char(q.created, 'yyyy'))-to_number(to_char(add_months(q.created, -1),'yyyy')),1,-1,0)*nvl(Q.QUALITYLEVEL,0)) trend
from mpassignment mp
left join quality q on MP.MPID = Q.MPID and q.organizationid=:organizationid
left join employee e on e.empid=q.chargeperson and e.organizationid=:organizationid
where MP.organizationid=:organizationid and to_char(q.created, 'yyyy')=to_char(sysdate,'yyyy')
group by mp.mpname
order by qualitylevel desc
) t
where rownum<=5", CurrentUser.OrganizationID, CurrentUser.OrganizationID, CurrentUser.OrganizationID);
dt.TableName = "YearTrend";
ds.Tables.Add(dt);
return ds;
}
catch (Exception e)
{
throw e;
}
}
#endregion
}
}
|
using SOP_IAA.Models;
using SOP_IAA_DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.Data;
using System.Net;
using System.Web.Script.Serialization;
using System.IO;
using System.Web.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace SOP_IAA.Controllers
{
public class ContratoViewController : Controller
{
private Proyecto_IAAEntities db = new Proyecto_IAAEntities();
// GET: Contrato
public ActionResult Index()
{
var contrato = db.Contrato.Include(c => c.contratista).Include(c => c.fondo).Include(c => c.zona);
return View(contrato.ToList());
}
// GET
public ActionResult Create()
{
var model = new ContratoViewModels();
ViewBag.idContratista = new SelectList(db.contratista, "id", "nombre");
ViewBag.idFondo = new SelectList(db.fondo, "id", "nombre");
ViewBag.idZona = new SelectList(db.zona, "id", "nombre");
var mquery = (from p in db.persona
join i in db.ingeniero
on p.id equals i.idPersona
select new SelectListItem
{
Value = p.id.ToString(),
Text = p.nombre + " " + p.apellido1 + " " + p.apellido2
}
);
ViewBag.idIngeniero = new SelectList(mquery, "Value", "Text");
ViewBag.idLaboratorio = new SelectList(db.laboratorioCalidad, "id", "nombre");
return View();
}
//POST
[HttpPost]
public ActionResult Create(string jsonContrato, string jsonLaboratorios, string jsonIngenieros)
{
if (ModelState.IsValid)
{
List<int> listLaboratios = new List<int>();
List<int> listIngenieros = new List<int>();
Contrato contrato = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Contrato>(jsonContrato);
//Obtener los laboratios
dynamic jObj = JsonConvert.DeserializeObject(jsonLaboratorios);
foreach (var child in jObj.Laboratorios.Children())
{
//listLaboratios.Add((int)child);
contrato.laboratorioCalidad.Add(db.laboratorioCalidad.Find((int)child));
}
//inserción del contrato a la DB
db.Contrato.Add(contrato);
db.SaveChanges();
//obtención del id del contrato
var idContrato = contrato.id;
//Obtener ingenieros.
jObj = JsonConvert.DeserializeObject(jsonIngenieros);
foreach (var child in jObj.Ingenieros.Children())
{
//Creación del ingeniero-contrato.
ingenieroContrato ing_contrato = new ingenieroContrato();
ing_contrato.idContrato = idContrato;
ing_contrato.idIngeniero = (int)child;
db.ingenieroContrato.Add(ing_contrato);
db.SaveChanges();
}
}
//RedirectToAction("Index", "Contrato");
return View("Index");
}
// GET: Obtener los detalles de un ingeniero específico
public ActionResult IngenieroDetalles(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// SE busca el id de ingeniero en la lista de ingenieros
ingeniero ingeniero = db.ingeniero.Find(id);
if (ingeniero == null)
{
//Si no se encuetra una coincidencia se retorna un NotFound
return HttpNotFound();
}
// Se crea un objeto con las propiedades de ingeniero y persona
var obj = new ingeniero
{
idPersona = ingeniero.idPersona,
persona = new persona
{
id = ingeniero.persona.id,
nombre = ingeniero.persona.nombre,
apellido1 = ingeniero.persona.apellido1,
apellido2 = ingeniero.persona.apellido2
},
rol = ingeniero.rol,
descripcion = ingeniero.descripcion,
departamento = ingeniero.departamento
};
//Se procede a convertir a JSON el objeto recien creado
var json = new JavaScriptSerializer().Serialize(obj);
//Se retorna el JSON
return Json(json, JsonRequestBehavior.AllowGet);
}
// GET: Obtener los detalles de un laboratorios específico
public ActionResult LaboratorioDetalles(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// SE busca el id de ingeniero en la lista de ingenieros
laboratorioCalidad laboratorio = db.laboratorioCalidad.Find(id);
if (laboratorio == null)
{
//Si no se encuetra una coincidencia se retorna un NotFound
return HttpNotFound();
}
laboratorioCalidad lab = new laboratorioCalidad {
id=laboratorio.id,
nombre = laboratorio.nombre,
tipo= laboratorio.tipo
};
//Se procede a convertir a JSON el objeto recien creado
var json = new JavaScriptSerializer().Serialize(lab);
//Se retorna el JSON
return Json(json, JsonRequestBehavior.AllowGet);
}
// GET: Obtener los detalles de un contrato específico
public ActionResult Details(int? id)
{
Contrato contrato = db.Contrato.Find(id);
return View();
}
}
} |
using UnityEditor;
using UnityAtoms.Editor;
namespace UnityAtoms.BaseAtoms.Editor
{
/// <summary>
/// A custom property drawer for Void BaseEventReferences. Makes it possible to choose between an Event, Event Instancer, Collection Cleared, List Cleared, Collection Instancer Cleared or List Instancer Cleared.
/// </summary>
[CustomPropertyDrawer(typeof(VoidBaseEventReference), true)]
public class VoidBaseEventReferenceDrawer : AtomBaseReferenceDrawer
{
protected class UsageEvent : UsageData
{
public override int Value { get => VoidBaseEventReferenceUsage.EVENT; }
public override string PropertyName { get => "_event"; }
public override string DisplayName { get => "Use Event"; }
}
protected class UsageEventInstancer : UsageData
{
public override int Value { get => VoidBaseEventReferenceUsage.EVENT_INSTANCER; }
public override string PropertyName { get => "_eventInstancer"; }
public override string DisplayName { get => "Use Event Instancer"; }
}
protected class UsageCollectionCleared : UsageData
{
public override int Value { get => VoidBaseEventReferenceUsage.COLLECTION_CLEARED_EVENT; }
public override string PropertyName { get => "_collection"; }
public override string DisplayName { get => "Use Collection Cleared Event"; }
}
protected class UsageListCleared : UsageData
{
public override int Value { get => VoidBaseEventReferenceUsage.LIST_CLEARED_EVENT; }
public override string PropertyName { get => "_list"; }
public override string DisplayName { get => "Use List Cleared Event"; }
}
protected class UsageCollectionInstancerCleared : UsageData
{
public override int Value { get => VoidBaseEventReferenceUsage.COLLECTION_INSTANCER_CLEARED_EVENT; }
public override string PropertyName { get => "_collectionInstancer"; }
public override string DisplayName { get => "Use Collection Instancer Cleared Event"; }
}
protected class UsageListInstancerCleared : UsageData
{
public override int Value { get => VoidBaseEventReferenceUsage.LIST_INSTANCER_CLEARED_EVENT; }
public override string PropertyName { get => "_listInstancer"; }
public override string DisplayName { get => "Use List Instancer Cleared Event"; }
}
private readonly UsageData[] _usages = new UsageData[6] {
new UsageEvent(),
new UsageEventInstancer(),
new UsageCollectionCleared(),
new UsageListCleared(),
new UsageCollectionInstancerCleared(),
new UsageListInstancerCleared()
};
protected override UsageData[] GetUsages(SerializedProperty prop = null) => _usages;
}
}
|
using System;
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Weapon : MonoBehaviour {
bool shooting;
bool waitToSwing;
bool[] reloading = new bool[4];
int[] CLIP_SIZES = {8, 1, 15};
int[] clip_sizes = new int[3];
int[] ammo_ammounts = new int[3]; // the amount of bullet is this + clip_sizes
float[] WAIT_TIMES = {1f, 0.3f, 1.6f, 0.075f};
Animator anim;
AudioSource weaponSound;
public AudioClip pistol_shoot_clip;
public AudioClip knife_shoot_clip;
public AudioClip shotgun_shoot_clip;
public AudioClip smg_shoot_clip;
public GameObject bullet; // Assign the bullet prefab in the editor
GameObject melee;
GameObject pistol;
GameObject smg;
GameObject shotgun;
PlayerHealth playerHealth;
WaveLogic waveLogic;
Transform myTransform;
enum weapons {
melee,
pistol,
shotgun,
smg
}
weapons curWeapon;
void Start() {
shooting = false;
waitToSwing = false;
for (int i = 0; i < reloading.Length; ++i)
reloading[i] = false;
ammo_ammounts[0] = 50;
ammo_ammounts[1] = 25;
ammo_ammounts[2] = 160;
myTransform = transform;
curWeapon = weapons.shotgun;
weaponSound = GameObject.FindWithTag("Gun Shot").GetComponent<AudioSource>();
weaponSound.clip = shotgun_shoot_clip;
melee = GameObject.FindWithTag("Knife");
pistol = GameObject.FindWithTag("Pistol");
shotgun = GameObject.FindWithTag("Shotgun");
smg = GameObject.FindWithTag("SubmachineGun");
playerHealth = GameObject.FindWithTag("Player").GetComponent<PlayerHealth>();
waveLogic = GameObject.FindWithTag("Wave Logic").GetComponent<WaveLogic>();
melee.SetActive(false);
pistol.SetActive(false);
smg.SetActive(false);
anim = shotgun.GetComponent<Animator>();
bullet.tag = "ShotgunBullet";
clip_sizes[0] = CLIP_SIZES[0];
clip_sizes[1] = CLIP_SIZES[1];
clip_sizes[2] = CLIP_SIZES[2];
GameObject.FindWithTag("Ammo").GetComponent<Text>().text = " 1 / " + ammo_ammounts[1] + " ";
UpdateUI();
}
void FixedUpdate() {
if (shooting || playerHealth.GetHealth() < 1 || reloading[(int) curWeapon]
|| waveLogic.Won() || waitToSwing)
return;
CheckKeyInput(GameObject.FindWithTag("Center").transform.position);
}
void Ammunition() {
switch(curWeapon) {
case weapons.pistol:
GunReloading(0);
break;
case weapons.shotgun:
GunReloading(1);
break;
case weapons.smg:
GunReloading(2);
break;
}
}
void CheckKeyInput(Vector3 position) {
int current = (int) curWeapon;
// Stuck in reloading animation and can't shoot while dead
// If the key is pressed create a game object (bullet) and then apply a force
if (Input.GetKey(KeyCode.Mouse0) && curWeapon != weapons.melee) {
// can't shoot if there's no ammo of that weapon's type
if ((current == 1 && clip_sizes[current - 1] == 0)
|| (current == 2 && clip_sizes[current - 1] == 0)
|| (current == 3 && clip_sizes[current - 1] == 0)) {
return;
}
GameObject gO = Instantiate(bullet, position, Quaternion.Euler(90, 0, 0)) as GameObject;
gO.GetComponent<Rigidbody>().AddForce(myTransform.forward * 200);
weaponSound.Play();
Ammunition();
// Ammunition has a side effect on reloading[current]
if (reloading[current])
return;
if (curWeapon != weapons.shotgun)
anim.SetTrigger("Shoot");
StartCoroutine(WaitToShoot());
}
// If key is pressed and you're holding the knife
else if (Input.GetKey(KeyCode.Mouse0)) {
anim.SetTrigger("Shoot");
weaponSound.Play();
StartCoroutine(WaitToShoot());
}
// Switch to Knife
else if (Input.GetKeyDown(KeyCode.Alpha1) && current != 0) {
curWeapon = weapons.melee;
shotgun.SetActive(false);
smg.SetActive(false);
pistol.SetActive(false);
melee.SetActive(true);
anim = melee.GetComponent<Animator>();
weaponSound.clip = knife_shoot_clip;
UpdateUI();
}
// Switch to Pistol
else if (Input.GetKeyDown(KeyCode.Alpha2) && current != 1) {
curWeapon = weapons.pistol;
melee.SetActive(false);
shotgun.SetActive(false);
smg.SetActive(false);
pistol.SetActive(true);
bullet.tag = "PistolBullet";
anim = pistol.GetComponent<Animator>();
weaponSound.clip = pistol_shoot_clip;
UpdateUI();
}
// Switch to Shotgun
else if (Input.GetKeyDown(KeyCode.Alpha3) && current != 2) {
curWeapon = weapons.shotgun;
melee.SetActive(false);
pistol.SetActive(false);
smg.SetActive(false);
shotgun.SetActive(true);
bullet.tag = "ShotgunBullet";
anim = shotgun.GetComponent<Animator>();
weaponSound.clip = shotgun_shoot_clip;
UpdateUI();
}
// Switch to SMG
else if (Input.GetKeyDown(KeyCode.Alpha4) && current != 3) {
curWeapon = weapons.smg;
melee.SetActive(false);
pistol.SetActive(false);
shotgun.SetActive(false);
smg.SetActive(true);
bullet.tag = "SMGBullet";
anim = smg.GetComponent<Animator>();
weaponSound.clip = smg_shoot_clip;
UpdateUI();
}
}
public void AmmoPickup() {
for (int i = 0; i < ammo_ammounts.Length; ++i) {
ammo_ammounts[i] += CLIP_SIZES[i];
// fixes case for if the gun is empty
if (clip_sizes[i] == 0 && (int) curWeapon == i) // if holding, animate
GunReloading(i);
else if (clip_sizes[i] == 0) {
clip_sizes[i] = CLIP_SIZES[i];
ammo_ammounts[i] = 0;
}
}
UpdateUI();
}
// If the knife is swinging to hurt the enemy
public bool GetSwinging() {
return shooting && curWeapon == weapons.melee;
}
public void StopSwinging() {
shooting = false;
}
void GunReloading(int i) {
--clip_sizes[i];
UpdateUI();
// Reload the gun
if (clip_sizes[i] <= 0 && ammo_ammounts[i] > 0) {
if (curWeapon != weapons.smg) {
anim.SetTrigger("Reload");
if (curWeapon == weapons.pistol) {
AudioSource aS = pistol.GetComponent<AudioSource>();
aS.Play();
}
} else {
AudioSource aS = smg.GetComponent<AudioSource>();
smg.transform.Find("ScifiRifle").GetComponent<Animator>().SetTrigger("Reload");
aS.Play();
}
StartCoroutine(WaitReload(i + 1));
int newTotal = ammo_ammounts[i] - CLIP_SIZES[i];
// If ammo is more than max clip size then subtract it, if not make it 0
ammo_ammounts[i] = newTotal > 0 ? newTotal : 0;
// Current clip size is the max clip size, the left overs, or 0
clip_sizes[i] = newTotal >= 0 ? CLIP_SIZES[i] : Math.Abs(newTotal);
}
// Shotgun reloads when others don't
else if (ammo_ammounts[i] == 0 && i == 1) {
anim.SetTrigger("Reload");
}
}
void UpdateUI() {
string ammo = "";
switch(curWeapon) {
case weapons.pistol:
ammo = " " + clip_sizes[0] + " / " + ammo_ammounts[0] + " ";
break;
case weapons.shotgun:
ammo = " " + clip_sizes[1] + " / " + ammo_ammounts[1] + " ";
break;
case weapons.smg:
ammo = (clip_sizes[2] < 10 ? " " : "") + clip_sizes[2] + " / " + ammo_ammounts[2];
break;
}
GameObject.FindWithTag("Ammo").GetComponent<Text>().text = ammo;
}
// You just used a weapon, wait to shoot again.
IEnumerator WaitToShoot() {
shooting = true;
waitToSwing = true;
yield return new WaitForSeconds(WAIT_TIMES[(int) curWeapon]);
shooting = false;
waitToSwing = false;
}
IEnumerator WaitReload(int i) {
reloading[i] = true;
yield return new WaitForSeconds(1.6f);
UpdateUI();
reloading[i] = false;
}
}
|
using System;
namespace Inventory.Models
{
public class OrderDishGarnishModel : BaseModel
{
public int OrderDishId { get; set; }
public Guid DishGuid { get; set; }
public Guid GarnishGuid { get; set; }
public decimal Quantity { get; set; }
public decimal Price { get; set; }
public override void Merge(ObservableObject source)
{
if (source is OrderDishGarnishModel)
{
Merge((OrderDishGarnishModel)source);
}
}
private void Merge(OrderDishGarnishModel source)
{
Id = source.Id;
OrderDishId = source.OrderDishId;
DishGuid = source.DishGuid;
GarnishGuid = source.GarnishGuid;
Quantity = source.Quantity;
Price = source.Price;
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace tellick_admin.Repository {
public class TellickAdminContext : DbContext {
public TellickAdminContext(DbContextOptions<TellickAdminContext> options) : base(options) {
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<Log> Logs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Project>().HasOne(l => l.Customer).WithMany().HasForeignKey(l => l.CustomerId);
modelBuilder.Entity<Log>().HasOne(l => l.Project).WithMany().HasForeignKey(l => l.ProjectId);
}
}
} |
using System;
namespace AlgorithmProblems.Dynamic_Programming
{
/// <summary>
/// Pivot floor: floor from which when the egg is dropped it will break.
/// We need to return the minimum number of trails in worst case to get this privot floor
/// We are given the number of floors and the number of eggs for the experiment.
/// </summary>
class EggDropMinTrials
{
/// <summary>
/// We can solve this problem using dynamic programming
/// We need to consider 2 cases: when the egg breaks and when the egg does not breaks
/// trials(floor, egg) = min(1 + max(trials(floor-f, egg), trials(floor-1, egg-1)));
/// for f -> 1 to floor as we will be getting the worst case so we do the max
/// and we will do min to get the minimum number of trails
///
///
/// The running time is O((floors^2)*eggs)
/// The space requirement can be optimized to O(floors) if we dont get the whole matrix
/// </summary>
/// <param name="floors">number of floors for which the pivot needs to be found</param>
/// <param name="eggs">number of eggs which we have to find the pivot floor</param>
/// <returns></returns>
public static int GetMinTrials(int floors, int eggs)
{
if(floors <= 0)
{
throw new ArgumentException("Floors are not valid");
}
if(eggs <= 0)
{
throw new ArgumentException("number of eggs are not valid");
}
int[] prevTrials = new int[floors+1];
int[] currTrials = new int[floors+1];
for (int floor = 1; floor <= floors; floor++)
{
prevTrials[floor] = floor;
}
for (int e = 2; e<=eggs; e++)
{
for (int floor = 1; floor<=floors; floor++)
{
currTrials[floor] = int.MaxValue;
for (int f = 1; f<=floor; f++)
{
int currVal = 1 + Math.Max(currTrials[floor - f], prevTrials[f - 1]);
if(currTrials[floor]> currVal)
{
currTrials[floor] = currVal;
}
}
}
prevTrials = currTrials;
currTrials = new int[floors + 1];
}
return prevTrials[floors];
}
public static void TestEggDropMinTrials()
{
int floors = 36;
int eggs = 2;
Console.WriteLine("The min trials for {0} floors and {1} eggs is {2}", floors, eggs, GetMinTrials(floors, eggs));
floors = 10;
eggs = 1;
Console.WriteLine("The min trials for {0} floors and {1} eggs is {2}", floors, eggs, GetMinTrials(floors, eggs));
floors = 10;
eggs = 4;
Console.WriteLine("The min trials for {0} floors and {1} eggs is {2}", floors, eggs, GetMinTrials(floors, eggs));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbstractFactoryPattern.AbstractEntity
{
public interface IVehicle
{
IBike GetBike(string bike);
IScooter GetScooter(string scooter);
}
}
|
using System;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Azure.Batch.SoftwareEntitlement
{
/// <summary>
/// Options for running as a standalone server
/// </summary>
/// <remarks>Built by a <see cref="ServerOptionBuilder"/> from an instance of
/// <see cref="ServerCommandLine"/> and only used if all validation passes.</remarks>
public class ServerOptions
{
/// <summary>
/// Gets the certificate to use when checking the signature of a token
/// </summary>
public X509Certificate2 SigningCertificate { get; }
/// <summary>
/// Gets the certificate to use when decrypting a token
/// </summary>
public X509Certificate2 EncryptionCertificate { get; }
/// <summary>
/// Gets the certificate to use with our HTTPS connections
/// </summary>
public X509Certificate2 ConnectionCertificate { get; }
/// <summary>
/// Gets the host URL for our server
/// </summary>
public Uri ServerUrl { get; }
/// <summary>
/// The issuer we expect to see on tokens presented to use for verification
/// </summary>
public string Audience { get; }
/// <summary>
/// The issuer we expect to see on tokens presented to us for verification
/// </summary>
public string Issuer { get; }
/// <summary>
/// The server will automatically shut down after processing one request
/// </summary>
public bool ExitAfterRequest { get; }
/// <summary>
/// Initialize a blank set of server options
/// </summary>
public ServerOptions()
{
}
/// <summary>
/// Create a modified <see cref="ServerOptions"/> with the specified signing certificate
/// </summary>
/// <param name="certificate">Signing certificate to use (may not be null).</param>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithSigningCertificate(X509Certificate2 certificate)
{
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}
return new ServerOptions(this, signingCertificate: certificate);
}
/// <summary>
/// Create a modified <see cref="ServerOptions"/> with the specified encryption certificate
/// </summary>
/// <param name="certificate">Signing certificate to use (may not be null).</param>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithEncryptionCertificate(X509Certificate2 certificate)
{
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}
return new ServerOptions(this, encryptionCertificate: certificate);
}
/// <summary>
/// Create a modified <see cref="ServerOptions"/> with the specified connection certificate
/// </summary>
/// <param name="certificate">Signing certificate to use (may not be null).</param>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithConnectionCertificate(X509Certificate2 certificate)
{
if (certificate == null)
{
throw new ArgumentNullException(nameof(certificate));
}
return new ServerOptions(this, connectionCertificate: certificate);
}
/// <summary>
/// Create a modified <see cref="ServerOptions"/> with the specified server URL
/// </summary>
/// <param name="url">Hosting URL to use (may not be null).</param>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithServerUrl(Uri url)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
return new ServerOptions(this, serverUrl: url);
}
/// <summary>
/// Specify the audience expected in the token
/// </summary>
/// <param name="audience">The audience expected within the generated token.</param>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithAudience(string audience)
{
if (string.IsNullOrEmpty(audience))
{
throw new ArgumentException("Expect to have an audience", nameof(audience));
}
return new ServerOptions(this, audience: audience);
}
/// <summary>
/// Specify the issuer expected in the token
/// </summary>
/// <param name="issuer">The audience expected within the generated token.</param>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithIssuer(string issuer)
{
if (string.IsNullOrEmpty(issuer))
{
throw new ArgumentException("Expect to have an issuer", nameof(issuer));
}
return new ServerOptions(this, issuer: issuer);
}
/// <summary>
/// Indicate whether the server should automatically shut down after processing one request
/// </summary>
/// <returns>New instance of <see cref="ServerOptions"/>.</returns>
public ServerOptions WithAutomaticExitAfterOneRequest()
{
return new ServerOptions(this, exitAfterRequest: true);
}
/// <summary>
/// Mutating constructor used to create variations of an existing set of options
/// </summary>
/// <param name="original">Original server options to copy.</param>
/// <param name="signingCertificate">Certificate to use for signing tokens (optional).</param>
/// <param name="encryptionCertificate">Certificate to use for encrypting tokens (optional).</param>
/// <param name="connectionCertificate">Certificate to use for our HTTPS connection (optional).</param>
/// <param name="serverUrl">Server host URL (optional).</param>
/// <param name="audience">Audience we expect to find in each token.</param>
/// <param name="issuer">Issuer we expect to find in each token.</param>
/// <param name="exitAfterRequest">Specify whether to automatically shut down after one request.</param>
private ServerOptions(
ServerOptions original,
X509Certificate2 signingCertificate = null,
X509Certificate2 encryptionCertificate = null,
X509Certificate2 connectionCertificate = null,
Uri serverUrl = null,
string audience = null,
string issuer = null,
bool? exitAfterRequest = null)
{
if (original == null)
{
throw new ArgumentNullException(nameof(original));
}
SigningCertificate = signingCertificate ?? original.SigningCertificate;
EncryptionCertificate = encryptionCertificate ?? original.EncryptionCertificate;
ConnectionCertificate = connectionCertificate ?? original.ConnectionCertificate;
ServerUrl = serverUrl ?? original.ServerUrl;
Audience = audience ?? original.Audience;
Issuer = issuer ?? original.Issuer;
ExitAfterRequest = exitAfterRequest ?? original.ExitAfterRequest;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _036_BOOLEAN
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите координаты шахматной доски x1,y1,x2,y2 от 1 до 8");
int point_x1 = Convert.ToInt32(Console.ReadLine());
int point_y1 = Convert.ToInt32(Console.ReadLine());
int point_x2 = Convert.ToInt32(Console.ReadLine());
int point_y2 = Convert.ToInt32(Console.ReadLine());
bool compareX1X2 = point_x1 == point_x2;
bool compareY1Y2 = point_y1 == point_y2;
bool res = compareX1X2 || compareY1Y2;
Console.WriteLine("Результат = {0}", res);
}
}
}
|
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 Proyecto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSalir_Click(object sender, EventArgs e)
{
}
private void btnAceptar_Click(object sender, EventArgs e)
{
if (this.txtUsuario.Text == "Jennifer" || this.txtContrasenia.Text == "12345")
{
Inicio llamar = new Inicio();
llamar.Show();
}
else
{
MessageBox.Show("Error");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Food_Enforcement.Models;
using static Food_Enforcement.Models.EF_Models;
//using static Food_Enforcement.APIHandlerManager.APIHandler;
using Food_Enforcement.DataAccess;
using System.Net.Http;
using Newtonsoft.Json;
namespace Food_Enforcement.Controllers
{
public class HomeController : Controller
{
public ApplicationDBContext dbContext;
//Base URL for the IEXTrading API. Method specific URLs are appended to this base URL.
static string BASE_URL = "https://api.fda.gov/food/";
HttpClient httpClient;
public HomeController(ApplicationDBContext context)
{
dbContext = context;
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
public RootObject GetRootObject()
{
string FOOD_API_PATH = BASE_URL + "/enforcement.json?search=report_date:[20040101+TO+20131231]&limit=50";
string foodData = "";
RootObject rootObject = null;
httpClient.BaseAddress = new Uri(FOOD_API_PATH);
// It can take a few requests to get back a prompt response, if the API has not received
// calls in the recent past and the server has put the service on hibernation
try
{
HttpResponseMessage response = httpClient.GetAsync(FOOD_API_PATH).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
foodData = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
if (!foodData.Equals(""))
{
// JsonConvert is part of the NewtonSoft.Json Nuget package
rootObject = JsonConvert.DeserializeObject<RootObject>(foodData);
dbContext.Meta.Add(rootObject.meta);
dbContext.Results.Add(rootObject.meta.results);
foreach (Result result in rootObject.results)
{
dbContext.Result.Add(result);
}
dbContext.SaveChanges();
ViewBag.dbSuccessComp = 1;
}
}
catch (Exception e)
{
// This is a useful place to insert a breakpoint and observe the error message
Console.WriteLine(e.Message);
}
return rootObject;
}
public IActionResult Index()
{
ViewBag.dbSuccessComp = 0;
RootObject rootObject = GetRootObject();
return View(rootObject);
}
public IActionResult MainView()
{
//Food_Enforcement.APIHandlerManager.APIHandler webHandler = new Food_Enforcement.APIHandlerManager.APIHandler();
RootObject rootObject = GetRootObject();
return View(rootObject);
}
public IActionResult Privacy()
{
return View();
}
public IActionResult About()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using System.Threading.Tasks;
public abstract class ITask
{
private Task mTask;
public string Name { get; set; }
public void Start()
{
mTask = new Task(Run);
mTask.Start();
}
public abstract void Run();
public bool IsCanceled()
{
return mTask.IsCanceled;
}
public void Stop()
{
mTask.Dispose();
}
} |
using System;
using Tomelt.ContentManagement.Utilities;
namespace Tomelt.ContentManagement.Aspects {
public interface IPublishingControlAspect {
LazyField<DateTime?> ScheduledPublishUtc { get; }
}
} |
using System.Collections.Generic;
namespace gView.Framework.Symbology
{
public class AnnotationPolygonCollection : List<IAnnotationPolygonCollision>, IAnnotationPolygonCollision
{
#region IAnnotationPolygonCollision Member
public bool CheckCollision(IAnnotationPolygonCollision poly)
{
foreach (IAnnotationPolygonCollision child in this)
{
if (child.CheckCollision(poly))
{
return true;
}
}
return false;
}
public bool Contains(float x, float y)
{
foreach (IAnnotationPolygonCollision child in this)
{
if (child.Contains(x, y))
{
return true;
}
}
return false;
}
public AnnotationPolygonEnvelope Envelope
{
get
{
if (this.Count == 0)
{
return new AnnotationPolygonEnvelope(0, 0, 0, 0);
}
AnnotationPolygonEnvelope env = this[0].Envelope;
for (int i = 1; i < this.Count; i++)
{
env.Append(this[i].Envelope);
}
return env;
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapHidingPlane : MonoBehaviour {
// Use this for initialization
void Start () {
GetComponent<MeshRenderer> ().enabled = false;
}
public void RevealMap() {
GetComponent<MeshRenderer> ().enabled = true;
}
// This is called by Broadcast. if you change the name, look for the broadcast string and change it too.
public void HideMap() {
GetComponent<MeshRenderer> ().enabled = false;
}
public void OnTriggerEnter(Collider c) {
RevealMap ();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class facultyTab : MonoBehaviour
{
[SerializeField] public GameObject[] Tabs;
public void OpenTeachersTab()
{
Tabs[0].SetActive(true);
Tabs[1].SetActive(false);
Tabs[2].SetActive(false);
}
public void OpenAdminTab()
{
Tabs[0].SetActive(false);
Tabs[1].SetActive(true);
Tabs[2].SetActive(false);
}
public void OpenCJTab()
{
Tabs[0].SetActive(false);
Tabs[1].SetActive(false);
Tabs[2].SetActive(true);
}
// Start is called before the first frame update
void Start()
{
Tabs[0].SetActive(true);
Tabs[1].SetActive(false);
Tabs[2].SetActive(false);
}
// Update is called once per frame
void Update()
{
}
}
|
using UnityEngine;
using UnityAtoms.BaseAtoms;
using UnityAtoms.MonoHooks;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Set variable value Action of type `Collision2DGameObject`. Inherits from `SetVariableValue<Collision2DGameObject, Collision2DGameObjectPair, Collision2DGameObjectVariable, Collision2DGameObjectConstant, Collision2DGameObjectReference, Collision2DGameObjectEvent, Collision2DGameObjectPairEvent, Collision2DGameObjectVariableInstancer>`.
/// </summary>
[EditorIcon("atom-icon-purple")]
[CreateAssetMenu(menuName = "Unity Atoms/Actions/Set Variable Value/Collision2DGameObject", fileName = "SetCollision2DGameObjectVariableValue")]
public sealed class SetCollision2DGameObjectVariableValue : SetVariableValue<
Collision2DGameObject,
Collision2DGameObjectPair,
Collision2DGameObjectVariable,
Collision2DGameObjectConstant,
Collision2DGameObjectReference,
Collision2DGameObjectEvent,
Collision2DGameObjectPairEvent,
Collision2DGameObjectCollision2DGameObjectFunction,
Collision2DGameObjectVariableInstancer>
{ }
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CountdownLettersWPF.API
{
public interface IAnagramsEndpoint
{
Task<List<string>> GetAnagrams(string text);
}
} |
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace RabbitMQManager.Models
{
public class MessageBodyEvent : EventArgs
{
public MessageBodyEvent(string message, IBasicProperties basicProperties, IModel model)
{
Message = message;
BasicProperties = basicProperties;
Model = model;
}
public string Message { get ; set; }
public IBasicProperties BasicProperties { get; set; }
public IModel Model { get; set; }
}
} |
namespace FootballApp_AutomaticMigrationEnabled_false.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class RenameNameToNameOfTeamInTeamsTable : DbMigration
{
public override void Up()
{
AddColumn("dbo.Teams", "NameOfTeam", c => c.String());
Sql("Update Teams set NameOfTeam=Name"); //Changed this column name from Team Class and we added this line for to avoid data loss.
DropColumn("dbo.Teams", "Name");
}
public override void Down()
{
AddColumn("dbo.Teams", "Name", c => c.String());
Sql("Update Teams set Name=NameOfTeam");
DropColumn("dbo.Teams", "NameOfTeam");
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace PatientsRegistry.Domain.Validation
{
public class BirthdateAttribute : ValidationAttribute
{
private static readonly BirthdateAttribute _instance = new BirthdateAttribute();
public static bool IsInvalid(object value)
{
return !_instance.IsValid(value);
}
public override bool IsValid(object value)
{
if (value == null) return true;
var date = (DateTime)value;
return date <= DateTime.UtcNow && date >= new DateTime(1900, 01, 01);
}
}
}
|
// Copyright (c) Bruno Brant. All rights reserved.
using System;
using Xunit;
namespace RestLittle.Tests
{
public class InputManagerTests
{
[Fact]
public void GetLastInputTime_ReturnsValidDateTime()
{
var sut = new InputManager();
var time = sut.GetLastInputTime();
// BUG: this may fail when running in CI
Assert.InRange(time, DateTime.Now.AddDays(-1), DateTime.Now);
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace OcenaKlientow.Migrations
{
public partial class temp : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Benefity",
columns: table => new
{
BenefitId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
DataUaktyw = table.Column<string>(nullable: true),
DataZakon = table.Column<string>(nullable: true),
LiczbaDni = table.Column<int>(nullable: false),
Nazwa = table.Column<string>(nullable: true),
Opis = table.Column<string>(nullable: true),
RodzajId = table.Column<int>(nullable: false),
WartoscProc = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Benefity", x => x.BenefitId);
});
migrationBuilder.CreateTable(
name: "Klienci",
columns: table => new
{
KlientId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
CzyFizyczna = table.Column<bool>(nullable: false),
DrugieImie = table.Column<string>(nullable: true),
DrugieNazwisko = table.Column<string>(nullable: true),
Imie = table.Column<string>(nullable: true),
KwotaKredytu = table.Column<double>(nullable: false),
NIP = table.Column<string>(nullable: true),
Nazwa = table.Column<string>(nullable: true),
Nazwisko = table.Column<string>(nullable: true),
PESEL = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Klienci", x => x.KlientId);
});
migrationBuilder.CreateTable(
name: "Oceny",
columns: table => new
{
OcenaId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
DataCzas = table.Column<string>(nullable: true),
KlientId = table.Column<int>(nullable: false),
StatusId = table.Column<int>(nullable: false),
SumaPkt = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Oceny", x => x.OcenaId);
});
migrationBuilder.CreateTable(
name: "Parametry",
columns: table => new
{
ParametrId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Nazwa = table.Column<string>(nullable: true),
Wartosc = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Parametry", x => x.ParametrId);
});
migrationBuilder.CreateTable(
name: "Platnosci",
columns: table => new
{
PlatnoscId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
DataWymag = table.Column<string>(nullable: true),
DataZaplaty = table.Column<string>(nullable: true),
Kwota = table.Column<double>(nullable: false),
ZamowienieId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Platnosci", x => x.PlatnoscId);
});
migrationBuilder.CreateTable(
name: "PrzypisaneStatusy",
columns: table => new
{
BenefitId = table.Column<int>(nullable: false),
StatusId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PrzypisaneStatusy", x => new { x.BenefitId, x.StatusId });
});
migrationBuilder.CreateTable(
name: "RodzajeBenefitow",
columns: table => new
{
RodzajId = table.Column<int>(nullable: false),
Nazwa = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RodzajeBenefitow", x => new { x.RodzajId, x.Nazwa });
});
migrationBuilder.CreateTable(
name: "Statusy",
columns: table => new
{
StatusId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Nazwa = table.Column<string>(nullable: true),
ProgDolny = table.Column<int>(nullable: false),
ProgGorny = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Statusy", x => x.StatusId);
});
migrationBuilder.CreateTable(
name: "Wyliczono",
columns: table => new
{
OcenaId = table.Column<int>(nullable: false),
ParametrId = table.Column<int>(nullable: false),
WartoscWyliczona = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Wyliczono", x => new { x.OcenaId, x.ParametrId });
});
migrationBuilder.CreateTable(
name: "Zamowienia",
columns: table => new
{
ZamowienieId = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
CzyZweryfikowano = table.Column<bool>(nullable: false),
DataZamowienia = table.Column<string>(nullable: true),
KlientId = table.Column<int>(nullable: false),
Kwota = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Zamowienia", x => x.ZamowienieId);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Benefity");
migrationBuilder.DropTable(
name: "Klienci");
migrationBuilder.DropTable(
name: "Oceny");
migrationBuilder.DropTable(
name: "Parametry");
migrationBuilder.DropTable(
name: "Platnosci");
migrationBuilder.DropTable(
name: "PrzypisaneStatusy");
migrationBuilder.DropTable(
name: "RodzajeBenefitow");
migrationBuilder.DropTable(
name: "Statusy");
migrationBuilder.DropTable(
name: "Wyliczono");
migrationBuilder.DropTable(
name: "Zamowienia");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimE
{
class Program
{
static void Main(string[] args)
{
int prim = 0;
Console.WriteLine("Kérek egy számot!");
prim = int.Parse(Console.ReadLine());
int i = 0;
if (prim > 1)
{
for (i = 2; i <= Math.Sqrt(prim); i++)
{
if (prim % i == 0)
{
Console.WriteLine("Nem prím! ");
break;
}
}
}
if (i > Math.Sqrt(prim))
{
Console.WriteLine("A szám prím!");
}
Console.ReadKey();
}
}
}
|
using MessagePack;
using System;
using System.IO.MemoryMappedFiles;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//WriteMemory();
WriteMemorySerialize();
}
static void WriteMemory()
{
Console.WriteLine("Please enter a message, and then press Enter.");
using (var sharedMemory = MemoryMappedFile.CreateNew("SharedMemory", 1024))
{
while (true)
{
var str = Console.ReadLine();
var data = str.ToCharArray();
using (var accessor = sharedMemory.CreateViewAccessor())
{
accessor.Write(0, data.Length);
accessor.WriteArray(sizeof(int), data, 0, data.Length);
}
}
}
}
static void WriteMemorySerialize()
{
using (var sharedMemory = MemoryMappedFile.CreateNew("SharedMemory", 1024))
{
{
Console.WriteLine("Please press Enter.");
Console.ReadLine();
var data = new User
{
Id = 1,
UserId = 1,
Name = "Shion",
Age = 17,
};
var serialized = MessagePackSerializer.Serialize<IDataProtocol>(data);
using (var accessor = sharedMemory.CreateViewAccessor())
{
accessor.Write(0, serialized.Length);
accessor.WriteArray(sizeof(int), serialized, 0, serialized.Length);
}
}
{
Console.WriteLine("Please press Enter.");
Console.ReadLine();
var data = new Command
{
Id = 2,
Name = "IncrementAge",
UserId = 1,
};
var serialized = MessagePackSerializer.Serialize<IDataProtocol>(data);
using (var accessor = sharedMemory.CreateViewAccessor())
{
accessor.Write(0, serialized.Length);
accessor.WriteArray(sizeof(int), serialized, 0, serialized.Length);
}
}
}
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;
using IRAP.Global;
using IRAP.Client.User;
using IRAP.Entity.Kanban;
using IRAP.Entity.MDM;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.MDM
{
public partial class frmMethodStandardProperties : IRAP.Client.GUI.MDM.frmCustomProperites
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private DataTable dtMethodStandards = null;
private DataTable dtRecordingMode = null;
public frmMethodStandardProperties()
{
InitializeComponent();
dtMethodStandards = new DataTable();
dtMethodStandards.Columns.Add("Level", typeof(int));
dtMethodStandards.Columns.Add("T20LeafID", typeof(int));
dtMethodStandards.Columns.Add("ParameterName", typeof(string));
dtMethodStandards.Columns.Add("LowLimit", typeof(long));
dtMethodStandards.Columns.Add("Criterion", typeof(string));
dtMethodStandards.Columns.Add("HighLimit", typeof(long));
dtMethodStandards.Columns.Add("Scale", typeof(int));
dtMethodStandards.Columns.Add("UnitOfMeasure", typeof(string));
dtMethodStandards.Columns.Add("RecordingMode", typeof(int));
dtMethodStandards.Columns.Add("SamplingCycle", typeof(long));
dtMethodStandards.Columns.Add("RTDBDSLinkID", typeof(int));
dtMethodStandards.Columns.Add("RTDBTagName", typeof(string));
dtMethodStandards.Columns.Add("Reference", typeof(bool));
grdMethodStandards.DataSource = dtMethodStandards;
dtRecordingMode = new DataTable();
dtRecordingMode.Columns.Add("ID", typeof(int));
dtRecordingMode.Columns.Add("Name", typeof(string));
dtRecordingMode.Rows.Add(new object[] { 0, "不采集" });
dtRecordingMode.Rows.Add(new object[] { 1, "按时间" });
dtRecordingMode.Rows.Add(new object[] { 2, "按产量" });
GetStandardList();
GetCriterionList();
riluRecordingMode.DataSource = dtRecordingMode;
riluRecordingMode.DisplayMember = "Name";
riluRecordingMode.ValueMember = "ID";
riluRecordingMode.NullText = "";
riluRecordingMode.Columns.Clear();
}
private void GetCriterionList()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
List<ScopeCriterionType> criterionItems = new List<ScopeCriterionType>();
WriteLog.Instance.Write("获取比较标准项列表", strProcedureName);
IRAPKBClient.Instance.sfn_GetList_ScopeCriterionType(
IRAPUser.Instance.SysLogID,
ref criterionItems,
out errCode,
out errText);
WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName);
if (errCode == 0)
{
riluCriterion.DataSource = criterionItems;
}
riluCriterion.DisplayMember = "TypeHint";
riluCriterion.ValueMember = "TypeCode";
riluCriterion.NullText = "";
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取标准项列表
/// </summary>
private void GetStandardList()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
List<SubTreeLeaf> standardItems = new List<SubTreeLeaf>();
WriteLog.Instance.Write("获取工艺标准项列表", strProcedureName);
IRAPKBClient.Instance.sfn_AccessibleSubtreeLeaves(
IRAPUser.Instance.CommunityID,
20,
5140, // 工艺参数
IRAPUser.Instance.ScenarioIndex,
IRAPUser.Instance.SysLogID,
ref standardItems,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
for (int i = standardItems.Count - 1; i >= 0; i--)
if (standardItems[i].LeafStatus != 0)
standardItems.Remove(standardItems[i]);
risluStandardName.DataSource = standardItems;
}
//riluStandardName.DisplayMember = "NodeName";
//riluStandardName.ValueMember = "LeafID";
//riluStandardName.NullText = "";
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public override void GetProperties(int t102LeafID, int t216LeafID)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
#region 获取产品与工序的关联ID
IRAPMDMClient.Instance.ufn_GetMethodID(
IRAPUser.Instance.CommunityID,
t102LeafID,
216,
t216LeafID,
IRAPUser.Instance.SysLogID,
ref c64ID,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
{
XtraMessageBox.Show(
errText,
Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
#endregion
if (c64ID == 0)
{
XtraMessageBox.Show(
"当前产品和工序的关联未生成!",
Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
else
{
List<MethodStandard> standards = new List<MethodStandard>();
#region 获取指定产品和工序所对应的工艺标准
IRAPMDMClient.Instance.ufn_GetList_MethodStandard(
IRAPUser.Instance.CommunityID,
t102LeafID,
t216LeafID,
"",
IRAPUser.Instance.SysLogID,
ref standards,
out errCode,
out errText);
WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName);
if (dtMethodStandards != null)
{
foreach (MethodStandard methodStandard in standards)
{
dtMethodStandards.Rows.Add(new object[]
{
methodStandard.Ordinal,
methodStandard.T20LeafID,
methodStandard.ParameterName,
methodStandard.LowLimit,
methodStandard.Criterion,
methodStandard.HighLimit,
methodStandard.Scale,
methodStandard.UnitOfMeasure,
methodStandard.RecordingMode,
methodStandard.SamplingCycle,
methodStandard.RTDBDSLinkID,
methodStandard.RTDBTagName,
methodStandard.Reference,
});
}
}
//for (int i = 0; i < grdvMethodStandards.Columns.Count; i++)
// grdvMethodStandards.Columns[i].BestFit();
grdvMethodStandards.BestFitColumns();
grdvMethodStandards.LayoutChanged();
grdvMethodStandards.OptionsBehavior.Editable = true;
grdvMethodStandards.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
grdMethodStandards.UseEmbeddedNavigator = true;
#endregion
#region 如果当前显示的数据是模板数据
if (standards.Count > 0 && standards[0].Reference)
{
lblTitle.Text += "(模板数据)";
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
#endregion
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 生成当前产品在当前工序的工艺参数标准行集属性XML串
/// </summary>
protected override string GenerateRSAttrXML()
{
string strMethodStandardXML = "";
int i = 1;
dtMethodStandards.DefaultView.Sort = "Level asc";
DataTable dt = dtMethodStandards.Copy();
dt = dtMethodStandards.DefaultView.ToTable();
foreach (DataRow dr in dt.Rows)
{
strMethodStandardXML = strMethodStandardXML +
string.Format("<Row RealOrdinal=\"{0}\" T20LeafID=\"{1}\" LowLimit=\"{2}\" " +
"Criterion=\"{3}\" HighLimit=\"{4}\" Scale=\"{5}\" UnitOfMeasure=\"{6}\" " +
"RecordingMode=\"{7}\" SamplingCycle=\"{8}\" RTDBDSLinkID=\"{9}\" " +
"RTDBTagName=\"{10}\" />",
i++,
dr["T20LeafID"].ToString(),
dr["LowLimit"].ToString(),
dr["Criterion"].ToString(),
dr["HighLimit"].ToString(),
dr["Scale"].ToString(),
dr["UnitOfMeasure"].ToString(),
dr["RecordingMode"].ToString(),
dr["SamplingCycle"].ToString(),
dr["RTDBDSLinkID"].ToString(),
dr["RTDBTagName"].ToString());
}
return string.Format("<RSAttr>{0}</RSAttr>", strMethodStandardXML);
}
private void grdvMethodStandards_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
{
DataRow dr = grdvMethodStandards.GetDataRow(e.RowHandle);
dr["Level"] = dtMethodStandards.Rows.Count + 1;
dr["T20LeafID"] = 0;
dr["ParameterName"] = "";
dr["LowLimit"] = 0;
dr["Criterion"] = "GELE";
dr["HighLimit"] = 0;
dr["Scale"] = 0;
dr["UnitOfMeasure"] = "";
dr["RecordingMode"] = 0;
dr["SamplingCycle"] = 0;
dr["RTDBDSLinkID"] = 0;
dr["RTDBTagName"] = "";
dr["Reference"] = false;
SetEditorMode(true);
}
private void grdvMethodStandards_RowDeleted(object sender, DevExpress.Data.RowDeletedEventArgs e)
{
SetEditorMode(true);
}
private void grdvMethodStandards_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
{
SetEditorMode(true);
}
}
}
|
using WinterIsComing.Contracts;
namespace WinterIsComing.Models.Spells
{
public class Cleave : ISpell
{
private const int CleaveEnergyCost = 15;
private int damage;
private int healt;
public Cleave(int damage, int healt)
{
this.Damage = damage;
this.healt = healt;
this.EnergyCost = CleaveEnergyCost;
}
public int Damage {
get {
if (this.healt <= 80)
{
return this.damage + this.healt*2;
}
return this.damage;
}
private set { this.damage = value; }
}
public int EnergyCost { get; private set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
[SerializeField]
List<GameObject> characterPrefabs = null;
public List<GameObject> CharacterPrefabs => characterPrefabs;
[SerializeField]
Dictionary<string, GameObject> characterPrefabDict = new Dictionary<string, GameObject>();
public static GameManager instance;
public System.Action<GameObject, GameObject> OnKill;
// Start is called before the first frame update
void Start()
{
if (instance != null)
Debug.LogError("More than one GameManager in a scene");
else
instance = this;
OnKill += KillMessage;
}
// Update is called once per frame
void Update()
{
}
void KillMessage(GameObject one, GameObject other)
{
Debug.Log("Kill");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using ArtificialArt.Lyrics;
namespace WaveBuilder
{
/// <summary>
/// Manages selections of themes
/// </summary>
internal class ThemeSelectionManager
{
#region Fields
/// <summary>
/// Whether theme selection is currently locked
/// </summary>
private bool isLocked = false;
#endregion
#region Internal Methods
/// <summary>
/// Add themes from combo box (from view to model)
/// </summary>
/// <param name="lyricSongFactory">lyric song factory (model)</param>
/// <param name="lyricTrackViewerSource">lyric track viewer (view)</param>
internal void AddThemesFromComboBox(LyricSongFactory lyricSongFactory, LyricTrackViewer lyricTrackViewerSource)
{
AddThemeFromComboBox(lyricSongFactory, lyricTrackViewerSource, true);
AddThemeFromComboBox(lyricSongFactory, lyricTrackViewerSource, false);
}
/// <summary>
/// Clear themes from view
/// </summary>
/// <param name="comboBoxList1">comboBox List 1</param>
/// <param name="comboBoxList2">comboBox List 2</param>
internal void ClearThemes(List<ComboBox> comboBoxList1, List<ComboBox> comboBoxList2)
{
foreach (ComboBox comboBox in comboBoxList1)
{
comboBox.IsEnabled = false;
comboBox.SelectedItem = null;
comboBox.IsEnabled = true;
}
foreach (ComboBox comboBox in comboBoxList2)
{
comboBox.IsEnabled = false;
comboBox.SelectedItem = null;
comboBox.IsEnabled = true;
}
}
/// <summary>
/// Add themes from model to view
/// </summary>
/// <param name="lyricSongFactory">model</param>
/// <param name="lyricTrackViewerSource">view</param>
internal void AddThemesToComboBox(LyricSongFactory lyricSongFactory, LyricTrackViewer lyricTrackViewerSource)
{
AddThemeToComboBox(lyricSongFactory, lyricTrackViewerSource, true);
AddThemeToComboBox(lyricSongFactory, lyricTrackViewerSource, false);
}
/// <summary>
/// Add combo boxes if all of them are full
/// </summary>
/// <param name="lyricSongFactory">lyric song factory (model)</param>
/// <param name="lyricTrackViewerSource">lyric track viewer sources</param>
internal void AddNewComboBoxesIfNeeded(LyricSongFactory lyricSongFactory, LyricTrackViewer lyricTrackViewerSource)
{
AddNewComboBoxesIfNeeded(lyricSongFactory, lyricTrackViewerSource, true);
AddNewComboBoxesIfNeeded(lyricSongFactory, lyricTrackViewerSource, false);
}
#endregion
#region Private Methods
/// <summary>
/// Add themes from combo box (from view to model)
/// </summary>
/// <param name="lyricSongFactory">lyric song factory (model)</param>
/// <param name="lyricTrackViewerSource">lyric track viewer (view)</param>
/// <param name="isThemeDesired">whether we manage desired or undesired themes</param>
private void AddThemeFromComboBox(LyricSongFactory lyricSongFactory, LyricTrackViewer lyricTrackViewer, bool isThemeDesired)
{
IEnumerable<ComboBox> comboBoxList;
if (isThemeDesired)
comboBoxList = lyricTrackViewer.ComboBoxDesiredThemesList;
else
comboBoxList = lyricTrackViewer.ComboBoxUndesiredThemesList;
foreach (ComboBox comboBox in comboBoxList)
{
if (comboBox.SelectedItem != null)
{
if (isThemeDesired)
{
lyricSongFactory.AddTheme((string)comboBox.SelectedItem);
}
else
{
lyricSongFactory.CensorTheme((string)comboBox.SelectedItem);
}
}
}
}
/// <summary>
/// Add themes from model to view
/// </summary>
/// <param name="lyricSongFactory">model</param>
/// <param name="lyricTrackViewerSource">view</param>
/// <param name="isThemeDesired">whether we manage desired or undesired themes</param>
private void AddThemeToComboBox(LyricSongFactory lyricSongFactory, LyricTrackViewer lyricTrackViewerSource, bool isThemeDesired)
{
IEnumerable<ComboBox> comboBoxList;
if (isThemeDesired)
comboBoxList = lyricTrackViewerSource.ComboBoxDesiredThemesList;
else
comboBoxList = lyricTrackViewerSource.ComboBoxUndesiredThemesList;
List<string> themeNameList;
if (isThemeDesired)
themeNameList = lyricSongFactory.ThemeList;
else
themeNameList = lyricSongFactory.ThemeBlackList;
foreach (string themeName in themeNameList)
if (!isContainTheme(themeName, comboBoxList))
AddThemeToNextEmptyComboBox(themeName, comboBoxList);
}
private bool isContainTheme(string themeName, IEnumerable<ComboBox> comboBoxList)
{
foreach (ComboBox comboBox in comboBoxList)
if (comboBox.SelectedItem != null && ((string)comboBox.SelectedItem) == themeName)
return true;
return false;
}
/// <summary>
/// Add theme to next empyt combo box
/// </summary>
/// <param name="themeName">theme name</param>
/// <param name="comboBoxList">list of combo box</param>
private void AddThemeToNextEmptyComboBox(string themeName, IEnumerable<ComboBox> comboBoxList)
{
foreach (ComboBox comboBox in comboBoxList)
if (comboBox.SelectedItem == null || ((string)comboBox.SelectedItem) == "")
{
comboBox.IsEnabled = false;
comboBox.SelectedItem = themeName;
comboBox.IsEnabled = true;
return;
}
}
/// <summary>
/// Add combo boxes if all of them are full
/// </summary>
/// <param name="lyricTrackViewerSource">lyric track viewer sources</param>
/// <param name="lyricTrackViewerSource">lyric Track Viewer Source (view)</param>
/// <param name="isThemeDesired">whether we manage desired themes or undesired themes</param>
private void AddNewComboBoxesIfNeeded(LyricSongFactory lyricSongFactory, LyricTrackViewer lyricTrackViewerSource, bool isThemeDesired)
{
IEnumerable<ComboBox> comboBoxList;
if (isThemeDesired)
comboBoxList = lyricTrackViewerSource.ComboBoxDesiredThemesList;
else
comboBoxList = lyricTrackViewerSource.ComboBoxUndesiredThemesList;
foreach (ComboBox comboBox in comboBoxList)
if (comboBox.SelectedItem == null || ((string)comboBox.SelectedItem).Trim() == "")
return;
lyricTrackViewerSource.AddComboBox(lyricSongFactory, isThemeDesired);
}
#endregion
#region Properties
/// <summary>
/// Whether theme selection is currently locked
/// </summary>
public bool IsLocked
{
get { return isLocked; }
set { isLocked = value; }
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyObjectCollision : MonoBehaviour {
public GameObject cameraLeap;
private MoveLeap script;
// Use this for initialization
void Start () {
script = cameraLeap.GetComponentInChildren<MoveLeap>();
}
// Update is called once per frame
void Update () {
}
private void OnTriggerEnter(Collider other)
{
print("ontrigger enter");
// if (other.gameObject.layer == 8)
script.collisionWithWall = true;
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.layer == 8)
script.collisionWithWall = false;
}
}
|
using Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using MetadataDiscover;
using Guid.Web;
using BusinessLogicalLayer;
using System.IO;
namespace Guid.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string entity = " ")
{
Type type = null;
Type[] types = AssemblyUtils.GetEntities().ToArray();
if (!string.IsNullOrWhiteSpace(entity))
foreach (Type t in types)
{
if (AssemblyUtils.GetEntityDisplayAttribute(t).Trim().ToUpper() == entity.Replace("Entity.", "").Trim().ToUpper())
{
type = t;
}
}
return View(type);
}
[HttpPost]
public ActionResult Index([ModelBinder(typeof(EntityModelBinder))]object obj)
{
new EntityBLL().Insert((EntityBase)obj);
string text = AssemblyUtils.GetEntityDisplayAttribute(obj.GetType());
return RedirectToAction("index", new { entity = text });
}
public ActionResult edit(int id, string entity)
{
Type type = null;
Type[] types = AssemblyUtils.GetEntities().ToArray();
if (entity != null)
foreach (Type t in types)
{
if (t.Name.Replace("Entity.", "").Trim().ToUpper() == entity.Replace("Entity.", "").Trim().ToUpper())
{
type = t;
}
}
object p = Activator.CreateInstance(type);
p.GetType().GetProperty("ID").SetValue(p, id);
object objEdit = new EntityBLL().GetById(((EntityBase)p), type);
return View(objEdit);
}
public FileResult ReportWebMaker(string entity, string tipo)
{
Type type = AssemblyUtils.GetEntityByName(entity.Replace("Entity.", "").Trim().ToUpper());
object obj = Activator.CreateInstance(type);
List<object> listItem = new EntityBLL().GetAll(((EntityBase)obj), type);
//if(listItem.Count > 0)
// if(((EntityBase)(listItem[0])).ID >0)
if (!System.IO.Directory.Exists(@"C:\Users\Public\Reporty"))
System.IO.Directory.CreateDirectory(@"C:\Users\Public\Reporty");
string nome = @"C:\Users\Public\Reporty\" + entity.Trim().ToUpper() + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "") + ((tipo.ToUpper().Contains("EXCEL")) ? ".xls" : ".pdf");
if (tipo.ToUpper().Contains("EXCEL"))
ExcelCreator.ExcelCreation.ListToExcel(listItem, nome, type);
else
PDFCreator.PDFCreation.BuildPDF(listItem, nome, type);
byte[] fileBytes = System.IO.File.ReadAllBytes(nome);
System.IO.File.Delete(nome);
if (tipo.Contains("EXCEL"))
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, entity.Trim().ToUpper() + ".xls");
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, entity.Trim().ToUpper() + ".pdf");
//return RedirectToAction("index", new { entity = entity }); ;
}
[HttpPost]
public ActionResult edit([ModelBinder(typeof(EntityModelBinder))]object obj)
{
new EntityBLL().Insert((EntityBase)obj);
string text = AssemblyUtils.GetEntityDisplayAttribute(obj.GetType());
return RedirectToAction("index", new { entity = text });
}
public ActionResult delite(int id, string entity)
{
Type type = null;
Type[] types = AssemblyUtils.GetEntities().ToArray();
if (entity != null)
foreach (Type t in types)
{
if (t.Name.Replace("Entity.", "").Trim().ToUpper() == entity.Replace("Entity.", "").Trim().ToUpper())
{
type = t;
}
}
object p = Activator.CreateInstance(type);
p.GetType().GetProperty("ID").SetValue(p, id);
object objEdit = new EntityBLL().GetById(((EntityBase)p), type);
return View(objEdit);
}
[HttpPost]
public ActionResult delite(string entity, int id)
{
Type type = null;
Type[] types = AssemblyUtils.GetEntities().ToArray();
if (entity != null)
foreach (Type t in types)
{
if (t.Name.Replace("Entity.", "").Trim().ToUpper() == entity.Replace("Entity.", "").Trim().ToUpper())
{
type = t;
}
}
object obj = Activator.CreateInstance(type);
obj.GetType().GetProperty("ID").SetValue(obj, id);
new EntityBLL().Delete((EntityBase)obj, obj.GetType());
string text = AssemblyUtils.GetEntityDisplayAttribute(obj.GetType());
return RedirectToAction("index", new { entity = text });
}
}
} |
using Knjizara.Models; // dodato da bi se koristilo Racun i RacunZaposleni
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Knjizara.Controllers
{
[Autorizacija(Roles = "Zaposleni")]
public class ZaposleniRacunController : Controller
{
// GET: ZaposleniSviRacuniView
public ActionResult ZaposleniSviRacuniView()
{
IzborRacuna();
return View();
}
// GET: ZaposleniRacunView
public ActionResult ZaposleniRacunView()
{
return View();
}
// GET: KreiranRacun
public ActionResult KreiranRacun()
{
IzborRacuna();
IzborStavkeRacuna();
return View("PrikazZaposleniRacunView");
}
// GET: IzmenaZaposleniRacunView
public ActionResult IzmenaZaposleniRacunView()
{
IzborStavkeRacuna();
TempData.Keep("SifraRacun");
return View();
}
// metoda koja popunjava dropdownlist podacima iz tabele Racun za korisnicko ime
public void IzborRacuna()
{
SelectList sviRacuni = RacunZaposleni.IzaberiRacun(User.Identity.Name);
if (sviRacuni != null)
{
ViewBag.podaciRacuni = sviRacuni;
}
}
// metoda koja popunjava dropdownlist podacima iz tabele StavkaRacun za sifru racuna
public void IzborStavkeRacuna()
{
SelectList sveStavkeRacuna = RacunZaposleni.IzaberiStavkaRacun(Convert.ToInt32(TempData["SifraRacun"]));
if (sveStavkeRacuna != null)
{
ViewBag.podaciStavkeRacuna = sveStavkeRacuna;
}
}
// metoda koja ili upucuje na kreiranje racuna ili upucuje na izmenu stavke racuna
public ActionResult SviRacuni(FormCollection forma)
{
switch (forma["dugme"])
{
case "Kreirajte nov racun":
{
return RedirectToAction("ZaposleniRacunView");
}
case "Izmenite stavke postojeceg racuna":
{
return RedirectToAction("KreiranRacun");
}
default: return View();
}
}
// metoda koja poziva metodu IzmeniRacun iz RacunZaposleni i menja racun sa podacima unetim u formu
public ActionResult IzmenaRacun(FormCollection forma)
{
IzborRacuna();
if (string.IsNullOrEmpty(forma["Datum"]))
{
ModelState.AddModelError("Datum", "Obavezan je datum racuna");
}
if (ModelState.IsValid)
{
Racun izmenaRacun = new Racun();
izmenaRacun.RacunID = Convert.ToInt32(forma["listaRacuna"]);
izmenaRacun.Datum = Convert.ToDateTime(forma["Datum"]);
izmenaRacun.Zaposleni = User.Identity.Name;
RacunZaposleni.IzmeniRacun(izmenaRacun);
RacunZaposleni.UkupnaCenaKreiranRacun(Convert.ToInt32(forma["listaRacuna"]));
TempData["IzmenaRacun"] = Convert.ToInt32(forma["listaRacuna"]);
return RedirectToAction("ZaposleniSviRacuniView");
}
else
{
return View("ZaposleniSviRacuniView");
}
}
// metoda koja poziva metodu KreirajRacun iz RacunZaposleni i kreira nov racun sa podacima unetim u formu
[HttpPost]
public ActionResult RacunKreiraj(Racun novRacun)
{
if (ModelState.IsValid)
{
novRacun.Zaposleni = User.Identity.Name;
RacunZaposleni.KreirajRacun(novRacun);
TempData["SifraRacun"] = novRacun.RacunID;
return RedirectToAction("ZaposleniStavkaRacunView", "ZaposleniStavkaRacun");
}
else
{
return View("ZaposleniRacunView");
}
}
// metoda koja ili prikazuje racun izabran iz dropdownlist ili bira racun za izmenu iz dropdownlist
[HttpPost]
public ActionResult KreiranRacun(FormCollection forma)
{
IzborRacuna();
TempData.Remove("SifraRacun");
switch (forma["dugme"])
{
case "Prikazite kreiran racun":
{
TempData["SifraRacun"] = Convert.ToInt32(forma["listaRacuna"]);
RacunZaposleni.UkupnaCenaKreiranRacun(Convert.ToInt32(forma["listaRacuna"]));
return RedirectToAction("KreiranRacun");
}
case "Izmenite kreiran racun":
{
TempData["SifraRacun"] = Convert.ToInt32(forma["listaRacuna"]);
return RedirectToAction("IzmenaZaposleniRacunView");
}
default: return View("PrikazZaposleniRacunView");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace testMonogame
{
class PushableBlock : IObject, ISprite, IBlock
{
Texture2D texture;
Rectangle destRect;
Rectangle orig;
String pushSide;
bool pushed;
public int X { get; set; }
public int Y { get; set; }
Rectangle sourceRect = new Rectangle(17, 0, 16, 16);
Color color = Color.White;
public PushableBlock(Texture2D incTexture, Vector2 pos,String pushSideIn)
{
texture = incTexture;
X = (int)pos.X;
Y = (int)pos.Y;
destRect = new Rectangle(X, Y, 32, 32);
orig = new Rectangle(X, Y, 32, 32);
pushed = false;
pushSide = pushSideIn;
}
public Rectangle getDestRect()
{
return destRect;
}
public void Update(GameManager game)
{
// NULL
}
public void Draw(SpriteBatch spriteBatch)
{
destRect = new Rectangle(X, Y, 32, 32);
spriteBatch.Draw(texture, destRect, sourceRect, color);
}
public void Interact(IPlayer player)
{
if (pushed == false)
{
Rectangle playerRect = player.getDestRect();
Rectangle intersect = Rectangle.Intersect(destRect, playerRect);
//this will only be called if we already know that they are intersecting.
int xCollisionSize = intersect.Width;
int yCollisionSize = intersect.Height;
if (xCollisionSize > yCollisionSize)
{
//top
if (playerRect.Y < destRect.Y)
{
if (pushSide.Equals("top"))
{
Y = Y + destRect.Height;
orig.Y = Y;
pushed = true;
}
}
else // bottom
{
if (pushSide.Equals("bottom"))
{
Y = Y - destRect.Height;
orig.Y = Y;
pushed = true;
}
}
}
else // We are in a Left / Right style collision
{
// left
if (playerRect.X < destRect.X)
{
if (pushSide.Equals("left"))
{
X = X + destRect.Width;
orig.X = X;
pushed = true;
}
}
else //right
{
if (pushSide.Equals("right"))
{
X = X - destRect.Width;
orig.X = X;
pushed = true;
}
}
}
}
}
public void transitionShift(int x, int y)
{
//update the block x,y
X = X + x;
Y = Y + y;
}
public void resetToOriginalPos()
{
//reset block x,y
X = orig.X;
Y = orig.Y;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
namespace Oracle.Admin
{
public partial class FrmAdminPersoneller : Form
{
OracleBaglantisi conn = new OracleBaglantisi();
void PersonelListele()
{
try
{
OracleCommand cmd = new OracleCommand("select * from TBL_PERSONELLER", conn.baglanti());
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Reset()
{
txtAd.Text = null;
txtSoyad.Text = null;
txtGorev.Text = null;
txtTelefon.Text = null;
txtTC.Text = null;
txtePosta.Text = null;
rchAdres.Text = null;
txtKullanici.Text = null;
txtSifre.Text = null;
}
public FrmAdminPersoneller()
{
InitializeComponent();
}
private void FrmAdminPersoneller_Load(object sender, EventArgs e)
{
PersonelListele();
}
private void btnEkle_Click(object sender, EventArgs e)
{
OracleCommand cmd = new OracleCommand("insert into TBL_PERSONELLER(PERSONELAD,PERSONELSOYAD,GOREV,TELEFON,TC,MAIL,ADRES,KULLANICIADI,SIFRE) values(:P1, :P2, :P3, :P4, :P5,:P6,:P7,:P8,:P9)", conn.baglanti());
cmd.Parameters.Add(":P1", OracleDbType.Varchar2).Value = txtAd.Text;
cmd.Parameters.Add(":P2", OracleDbType.Varchar2).Value = txtSoyad.Text;
cmd.Parameters.Add(":P3", OracleDbType.Varchar2).Value = txtGorev.Text;
cmd.Parameters.Add(":P4", OracleDbType.Varchar2).Value = txtTelefon.Text;
cmd.Parameters.Add(":P5", OracleDbType.Varchar2).Value = txtTC.Text;
cmd.Parameters.Add(":P6", OracleDbType.Varchar2).Value = txtePosta.Text;
cmd.Parameters.Add(":P7", OracleDbType.Varchar2).Value = rchAdres.Text;
cmd.Parameters.Add(":P8", OracleDbType.Varchar2).Value = txtKullanici.Text;
cmd.Parameters.Add(":P9", OracleDbType.Varchar2).Value = txtSifre.Text;
cmd.ExecuteNonQuery();
conn.baglanti().Close();
PersonelListele();
Reset();
MessageBox.Show("Personel Eklendi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnGuncelle_Click(object sender, EventArgs e)
{
OracleCommand cmd = new OracleCommand("update TBL_PERSONELLER set PERSONELAD=:P1,PERSONELSOYAD=:P2,GOREV=:P3,TELEFON=:P4,TC=:P5,MAIL=:P6,ADRES=:P7,KULLANICIADI=:P8,SIFRE=:P9 where PERSONELID=:P10", conn.baglanti());
cmd.Parameters.Add(":P1", OracleDbType.Varchar2).Value = txtAd.Text;
cmd.Parameters.Add(":P2", OracleDbType.Varchar2).Value = txtSoyad.Text;
cmd.Parameters.Add(":P3", OracleDbType.Varchar2).Value = txtGorev.Text;
cmd.Parameters.Add(":P4", OracleDbType.Varchar2).Value = txtTelefon.Text;
cmd.Parameters.Add(":P5", OracleDbType.Varchar2).Value = txtTC.Text;
cmd.Parameters.Add(":P6", OracleDbType.Varchar2).Value = txtePosta.Text;
cmd.Parameters.Add(":P7", OracleDbType.Varchar2).Value = rchAdres.Text;
cmd.Parameters.Add(":P8", OracleDbType.Varchar2).Value = txtKullanici.Text;
cmd.Parameters.Add(":P9", OracleDbType.Varchar2).Value = txtSifre.Text;
cmd.Parameters.Add(":P10", OracleDbType.Varchar2).Value = txtPersonelID.Text;
cmd.ExecuteNonQuery();
conn.baglanti().Close();
PersonelListele();
Reset();
MessageBox.Show("Personel Güncellendi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int select = dataGridView1.SelectedCells[0].RowIndex;
txtPersonelID.Text = dataGridView1.Rows[select].Cells[0].Value.ToString();
txtAd.Text = dataGridView1.Rows[select].Cells[1].Value.ToString();
txtSoyad.Text = dataGridView1.Rows[select].Cells[2].Value.ToString();
txtGorev.Text = dataGridView1.Rows[select].Cells[3].Value.ToString();
txtTelefon.Text = dataGridView1.Rows[select].Cells[4].Value.ToString();
txtTC.Text = dataGridView1.Rows[select].Cells[5].Value.ToString();
txtePosta.Text = dataGridView1.Rows[select].Cells[6].Value.ToString();
rchAdres.Text = dataGridView1.Rows[select].Cells[7].Value.ToString();
txtKullanici.Text = dataGridView1.Rows[select].Cells[8].Value.ToString();
txtSifre.Text = dataGridView1.Rows[select].Cells[9].Value.ToString();
}
private void btnSil_Click(object sender, EventArgs e)
{
OracleCommand cmd = new OracleCommand("Delete TBL_PERSONELLER WHERE PERSONELID=:P1", conn.baglanti());
cmd.Parameters.Add(":P1", OracleDbType.Int32).Value = txtPersonelID.Text;
cmd.ExecuteNonQuery();
conn.baglanti().Close();
PersonelListele();
Reset();
MessageBox.Show("Personel Silindi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
private void btnTemizle_Click(object sender, EventArgs e)
{
PersonelListele();
Reset();
}
}
}
|
namespace Models
{
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Interfaces;
public class Login : ILogin
{
public int Id { get; set; }
[Required, StringLength(4000, MinimumLength = 1), Index(IsUnique = true)]
public string SessionId { get; set; }
[ForeignKey(nameof(UserId))]
public virtual User User { get; set; }
public bool IsActive { get; set; }
[Required]
public int UserId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DevExpress.XtraTreeList.Nodes;
using System.Threading;
namespace IRAP.UFMPS.Library
{
abstract class TCustomDocumentProcess
{
protected UserControls.UCMonitorLog showLog = null;
protected TreeListNode nodeParentLog = null;
protected Thread _thread;
protected static List<string> processingFiles = new List<string>();
protected string dataFileName;
protected TTaskInfo _task = null;
private TCustomDocumentProcess()
{
throw new System.NotImplementedException();
}
public TCustomDocumentProcess(
string dataFileName,
TTaskInfo taskInfo,
UserControls.UCMonitorLog showLog,
TreeListNode parentNode)
{
this.showLog = showLog;
this._task = taskInfo;
this.dataFileName = dataFileName;
this.nodeParentLog = parentNode;
}
~TCustomDocumentProcess()
{
}
public static List<string> GetProcessingFiles()
{
return processingFiles;
}
public string DataFileName
{
get { return dataFileName; }
}
protected abstract bool DocumentProcessing();
protected void AfterDocumentProcessing()
{
// 文件处理完成后
if (_task.BackupFileFlag && _task.BackupFileFolder.Trim() != "")
{
if (!Directory.Exists(_task.BackupFileFolder))
{
Directory.CreateDirectory(_task.BackupFileFolder);
}
try
{
InvokeWriteLog(string.Format("将处理后的文件[{0}]移动到[{1}]文件夹。",
dataFileName,
_task.BackupFileFolder));
int i = 0;
string destinationFileName = string.Format("{0}{1}",
_task.BackupFileFolder,
Path.GetFileName(dataFileName));
do
{
try
{
File.Move(dataFileName, destinationFileName);
break;
}
catch
{
destinationFileName = string.Format("{0}{1}({2}){3}",
_task.BackupFileFolder,
Path.GetFileNameWithoutExtension(dataFileName),
++i,
Path.GetExtension(dataFileName));
}
} while (true);
}
catch (Exception error)
{
InvokeWriteLog(string.Format("移动文件[{0}]时发生错误:{1}", dataFileName, error.Message));
File.Delete(dataFileName);
}
}
else
{
InvokeWriteLog(string.Format("删除文件[{0}]", dataFileName));
File.Delete(dataFileName);
}
}
/// <summary>
/// 线程运行入口
/// </summary>
public virtual void RunProcessing()
{
if (processingFiles.IndexOf(dataFileName) < 0)
{
try
{
try
{
processingFiles.Add(dataFileName);
if (DocumentProcessing())
{
AfterDocumentProcessing();
}
}
catch (Exception error)
{
InvokeWriteLog(error.Message);
}
}
finally
{
processingFiles.Remove(dataFileName);
InvokeWriteLog(string.Format("文件[{0}]处理完毕。", dataFileName));
}
}
}
protected void InvokeWriteLog(string message)
{
showLog.Invoke(new InvokeAddLogs(WriteLog), new object[] { null, message });
}
/// <summary>
/// 记录日志
/// </summary>
protected void WriteLog(object sender, string message)
{
if (nodeParentLog == null)
{
nodeParentLog = showLog.WriteLog(string.Format("处理数据文件[{0}]", dataFileName));
}
if (message.Trim() != "")
{
showLog.WriteLog(message, nodeParentLog);
}
}
public void Start()
{
if (_thread == null)
{
_thread = new Thread(new ThreadStart(this.RunProcessing));
_thread.IsBackground = false;
_thread.Start();
}
else
{
InvokeWriteLog("文件已经在处理中......");
}
}
}
}
|
using Data.Common.QueryBuilder;
using Microsoft.EntityFrameworkCore.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Data.Contracts
{
public interface IRepository : IDisposable
{ }
public interface IRepository<T> : IRepository where T : class
{
IQuery<T> Query();
IList<T> Search(IQuery<T> query);
Task<List<T>> SearchAsync(IQuery<T> query);
IList<T> ListAll(Func<IQueryable<T>, IIncludableQueryable<T, object>> relationships = null);
T SingleOrDefault(Expression<Func<T, bool>> predicate, Func<IQueryable<T>, IIncludableQueryable<T, object>> relationships = null);
T FirstOrDefault(Expression<Func<T, bool>> predicate, Func<IQueryable<T>, IIncludableQueryable<T, object>> relationships = null);
T LastOrDefault(Expression<Func<T, bool>> predicate, Func<IQueryable<T>, IIncludableQueryable<T, object>> relationships = null);
bool Any(Expression<Func<T, bool>> predicate, Func<IQueryable<T>, IIncludableQueryable<T, object>> relationships = null);
TResult Max<TResult>(Expression<Func<T, TResult>> selector, Expression<Func<T, bool>> predicate = null);
int Count(Expression<Func<T, bool>> predicate);
T Add(T entity);
T Update(T entity);
T Delete(T entity);
void Delete(Expression<Func<T, bool>> predicate);
T Reload(T entity);
IList<T> FromSql(string query, params object[] parameters);
}
}
|
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.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using PeopleSearch.Models;
using System.Threading;
namespace PeopleSearch.Controllers
{
public class SearchController : ApiController
{
private PeopleContext db = new PeopleContext();
public SearchController() { }
public SearchController(PeopleContext context)
{
this.db = context;
}
// GET: api/Search
public IQueryable<People> GetPeople()
{
return db.People;
}
// GET: api/Search/searchString
[HttpGet]
[Route("api/Search/{searchString}")]
[ResponseType(typeof(People))]
public IQueryable<People> GetPeople(string searchString)
{
var people = from p in db.People
select p;
if (!String.IsNullOrEmpty(searchString))
{
people = people.Where(s => s.FirstName.Contains(searchString) || s.LastName.Contains(searchString));
}
if (searchString.StartsWith("s"))
{
Thread.Sleep(2500);
}
return people;
}
}
} |
using Common.Contracts;
using Common.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Common.DbTools
{
public class DbGroup : IDbGroup
{
public DbGroup()
{
}
public Group GetGroup(string name)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
return context.Groups.FirstOrDefault(g => g.Name == name);
}
}
public void Create(Group group)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
LocalController lc = context.LocalControllers.Include("Groups").FirstOrDefault(l => l.Code == group.LCCode);
if (lc != null)
{
if (!lc.Groups.Any(g => g.Name == group.Name))
{
lc.Groups.Add(group);
context.SaveChanges();
}
else
{
MessageBox.Show("The group with this name already exists in local system.", "Name taken", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Can't find Local Controller.", "Local Controller error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
public void IncreaseNumber(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
var group = context.Groups.FirstOrDefault(g => g.Name == code);
if (group.Id > 0)
{
group.NumOfUnits++;
context.SaveChanges();
}
}
}
public List<string> ReadAll(string code)
{
using (ApplicationDbContext context = new ApplicationDbContext())
{
var codes = new List<string>();
var groups = context.Groups.Where(g => g.LCCode == code).ToList();
foreach (var group in groups)
{
codes.Add(group.Name);
}
return codes;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DiverManager : MonoBehaviour
{
public GameObject Diver;
[SerializeField]
List<GameObject> diverCount = new List<GameObject>();
public GameObject subMarine;
[SerializeField]
List<GameObject> subMarineList = new List<GameObject>();
public GameObject helicopter;
[SerializeField]
List<GameObject> helicopterList = new List<GameObject>();
[SerializeField]
List<GameObject> enemyList = new List<GameObject>();
[SerializeField]
private DayAndNightCycle dayAndNight;
private Coroutine spawnWave;
private int spawnedEnemies;
[SerializeField]
private int waveCount = 1;
public int WaveCount
{
get { return waveCount; }
set { waveCount = value; }
}
[SerializeField]
private bool waveActive = false;
public bool WaveIsActive
{
get { return waveActive; }
set { waveActive = value; }
}
[SerializeField]
private bool canSpawn = true;
public bool CanSpawnEnemies
{
get { return canSpawn; }
set { canSpawn = value; }
}
private float randomSpawnTimer;
[SerializeField]
private int killedEnemies;
[SerializeField]
public GameObject player;
[SerializeField]
private float enemyAddition;
public static DiverManager Instance { get; private set; }
private bool hasStartedMusic = false;
private bool stopMusic = false;
private AudioController musicControl;
private Coroutine musicRoutine;
private Transform directionTransform;
private void Awake()
{
Instance = this;
}
private void Start()
{
if (dayAndNight == null)
{
dayAndNight = FindObjectOfType<DayAndNightCycle>();
}
directionTransform = GetComponentInChildren<Transform>();
}
private void Update()
{
if (waveActive)
{
Spawn();
if (killedEnemies >= enemyAddition + waveCount * 2)
{
waveActive = false;
stopMusic = true;
StopBattleMusic();
}
if (dayAndNight != null)
{
if (dayAndNight._dayPhases == DayAndNightCycle.DayPhases.Dawn && killedEnemies < enemyAddition + waveCount * 2)
{
dayAndNight.TimeMultiplier = 0;
}
else
{
dayAndNight.TimeMultiplier = 344f * 2;
}
if (dayAndNight._dayPhases == DayAndNightCycle.DayPhases.Dusk)
{
stopMusic = false;
StartBattleMusic();
}
}
}
else if (!waveActive)
{
subMarineList.Clear();
helicopterList.Clear();
diverCount.Clear();
enemyList.Clear();
spawnedEnemies = 0;
killedEnemies = 0;
if (spawnWave != null)
{
StopCoroutine(spawnWave);
}
}
}
public void Spawn()
{
if (canSpawn)
{
SpawnSubmarine(waveCount);
canSpawn = false;
spawnWave = StartCoroutine(waveCoolDown());
}
}
/// <summary>
/// Spawns amount of submarines depending on the wave.
/// </summary>
/// <param name="waveCount">Amount of waves player has survived</param>
private void SpawnSubmarine(int waveCount)
{
for (int i = 0; i < subMarineList.Count; i++)
{
if (subMarineList[i] == null)
{
subMarineList.RemoveAt(i);
killedEnemies = killedEnemies + 1;
}
}
for (int e = 0; e < diverCount.Count; e++)
{
if (diverCount[e] == null)
{
diverCount.RemoveAt(e);
killedEnemies = killedEnemies + 1;
}
}
for (int i = 0; i < helicopterList.Count; i++)
{
if (helicopterList[i] == null)
{
helicopterList.RemoveAt(i);
killedEnemies = killedEnemies + 1;
}
}
if (enemyList.Count < enemyAddition + waveCount * 2)
{
if (subMarineList.Count < waveCount / 3)
{
Vector3 direction = GetRandomDirection();
float distance = Random.Range(16f, 25f);
var submarine = Instantiate(subMarine, direction * distance + new Vector3(0f, -5f, 0f), Quaternion.identity);
submarine.GetComponentInChildren<SubmarineEnemy>().AimAtPlayer(player.transform);
subMarineList.Add(submarine);
enemyList.Add(submarine);
spawnedEnemies++;
}
if (diverCount.Count < enemyAddition + waveCount)
{
Vector3 direction = GetRandomDirection();
float distance = Random.Range(5f, 15f);
var diver = Instantiate(Diver, direction * distance + new Vector3(0f, -2.5f, 0f), Quaternion.identity);
diver.GetComponent<DiverAttackers>().LookAtPlayer(player.transform);
diverCount.Add(diver);
enemyList.Add(diver);
spawnedEnemies++;
}
if (helicopterList.Count < waveCount / 4)
{
Vector3 direction = GetRandomDirection();
float distance = Random.Range(16f, 25f);
var heli = Instantiate(helicopter, direction * distance + new Vector3(0f, 30f, 0f), Quaternion.identity);
heli.GetComponent<Helicopter>().FindBoat(player.transform);
helicopterList.Add(heli);
enemyList.Add(heli);
spawnedEnemies++;
}
randomSpawnTimer = Random.Range(5, 20);
}
}
private Vector3 GetRandomDirection()
{
Vector3 rotation = new Vector3(0f, Random.Range(0f, 359f), 0f);
directionTransform.Rotate(rotation);
Vector3 direction = directionTransform.forward;
return direction;
}
public void StartBattleMusic()
{
if (!hasStartedMusic)
{
musicControl = GetComponent<AudioController>();
musicControl.Play("BattleMusic", transform.position);
GetComponentInChildren<AudioSource>().loop = true;
hasStartedMusic = true;
}
}
public void StopBattleMusic()
{
if (hasStartedMusic && stopMusic)
{
musicControl.Stop("BattleMusic");
hasStartedMusic = false;
stopMusic = false;
}
}
IEnumerator waveCoolDown()
{
if (waveActive)
{
yield return new WaitForSeconds(randomSpawnTimer);
canSpawn = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using StockTracking.BLL;
using StockTracking.DAL.DTO;
namespace StockTracking
{
public partial class FrmUsersList : Form
{
public FrmUsersList()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
FrmUsers frm = new FrmUsers();
this.Hide();
frm.ShowDialog();
this.Visible = true;
}
EmployeeBLL bll = new EmployeeBLL();
EmployeeDTO dto = new EmployeeDTO();
private void FrmUsersList_Load(object sender, EventArgs e)
{
dto = bll.Select();
cmbPermission.DataSource = dto.permission;
cmbPermission.DisplayMember = "PermissionType";
cmbPermission.ValueMember = "ID";
cmbPermission.SelectedIndex = -1;
dataGridView1.DataSource = dto.Employees;
dataGridView1.Columns[0].HeaderText = "ID";
dataGridView1.Columns[1].HeaderText = "User Number";
dataGridView1.Columns[2].HeaderText = "Name";
dataGridView1.Columns[3].HeaderText = "Surname";
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].HeaderText = "Permission";
}
private void btnClear_Click(object sender, EventArgs e)
{
CleanAll();
dataGridView1.DataSource = dto.Employees;
}
private void CleanAll()
{
txtName.Clear();
txtUser.Clear();
txtSurname.Clear();
cmbPermission.SelectedIndex = -1;
}
private void btnSearch_Click(object sender, EventArgs e)
{
List<EmployeeDetailDTO> list = dto.Employees;
if (txtName.Text.Trim() == "" && txtSurname.Text.Trim() == "" && txtUser.Text.Trim() == "" && cmbPermission.SelectedIndex == -1)
MessageBox.Show("Please introduce any field to search");
else
{
if (txtName.Text.Trim() != "")
list = list.Where(x => x.Name.Contains(txtName.Text)).ToList();
if (txtSurname.Text.Trim() != "")
list = list.Where(x => x.Surname.Contains(txtSurname.Text)).ToList();
if (txtUser.Text.Trim() != "")
list = list.Where(x => x.UserNumer == Convert.ToInt32(txtUser.Text)).ToList();
if (cmbPermission.SelectedIndex != -1)
list = list.Where(x => x.Permission == Convert.ToInt32(cmbPermission.SelectedValue)).ToList();
}
dataGridView1.DataSource = list;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (detail.UserNumer == 0)
MessageBox.Show("Select a empote from the table");
else
{
FrmUsers frm = new FrmUsers();
frm.detail = detail;
frm.isUpdate = true;
this.Hide();
frm.ShowDialog();
this.Visible = true;
bll = new EmployeeBLL();
dto = bll.Select();
dataGridView1.DataSource = dto.Employees;
CleanAll();
}
}
EmployeeDetailDTO detail = new EmployeeDetailDTO();
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
detail = new EmployeeDetailDTO();
detail.ID= Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
detail.UserNumer = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[1].Value);
detail.Name = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
detail.Surname = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
detail.Password = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
detail.Permission = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[5].Value);
}
}
}
|
using Abp.Domain.Entities.Auditing;
namespace Abp.Authorization.Users
{
/// <summary>
/// Represents role record of a user.
/// </summary>
public class UserRole : CreationAuditedEntity<long> //TODO: Add a unique index for UserId, RoleId
{
/// <summary>
/// User Id.
/// </summary>
public virtual long UserId { get; set; }
/// <summary>
/// Role Id.
/// </summary>
public virtual int RoleId { get; set; }
public UserRole()
{
}
public UserRole(long userId, int roleId)
{
UserId = userId;
RoleId = roleId;
}
}
} |
#region MIT License
/*
* Copyright (c) 2013 University of Jyväskylä, Department of Mathematical
* Information Technology.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
/*
* Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen.
*/
using System;
using System.Reflection;
using Jypeli.Controls;
namespace Jypeli
{
/// <summary>
/// Metodityyppi, joka ottaa parametrikseen entisen ja nykyisen muuttujan arvon ja palauttaa totuusarvon.
/// Voidaan käyttää erilaisten sääntöjen tekemiseen.
/// </summary>
/// <typeparam name="T">Arvojen tyyppi</typeparam>
/// <param name="prev">Vanha arvo</param>
/// <param name="curr">Uusi arvo</param>
/// <returns>true tai false</returns>
public delegate bool ChangePredicate<T>(T prev, T curr);
/// <summary>
/// Ohjaintapahtumien kuuntelija.
/// </summary>
public interface Listener : Destroyable
{
/// <summary>
/// Kuuntelee tapahtumaa vain tietyssä kontekstissa.
/// </summary>
/// <param name="context"></param>
Listener InContext(ListenContext context);
/// <summary>
/// Kuuntelee tapahtumaa vain tietyssä kontekstissa.
/// Esim. Keyboard.Listen(parametrit).InContext(omaIkkuna) kuuntelee
/// haluttua näppäimistötapahtumaa ainoastaan kun ikkuna on näkyvissä ja päällimmäisenä.
/// </summary>
/// <param name="obj">Konteksti.</param>
Listener InContext(ControlContexted obj);
}
/// <summary>
/// Ohjaintapahtumien kuuntelija.
/// </summary>
/// <typeparam name="State">Tila</typeparam>
/// <typeparam name="Ctrl">Kontrolli</typeparam>
public class Listener<State, Ctrl> : Listener
{
private ChangePredicate<State> isTriggered;
private Delegate handler;
private object[] handlerParams;
private bool isDestroyed;
private string _controlName;
private string _helpText;
private bool dynamicContext;
private ListenContext context;
private ControlContexted contextedObject;
/// <summary>
/// Konteksti, jossa kontrolleja kuunnellaan.
/// </summary>
/// <value>The context.</value>
internal ListenContext Context
{
get { return (dynamicContext ? contextedObject.ControlContext : context); }
}
/// <summary>
/// Kontrolli, jota kuunnellaan.
/// </summary>
/// <value>The control.</value>
public Ctrl Control { get; private set; }
/// <summary>
/// Kontrollin nimi jota kuunnellaan. Käytetään vain ohjeen yhteydessä.
/// </summary>
public string ControlName
{
get { return _controlName; }
set { _controlName = value; }
}
/// <summary>
/// Ohjeteksti.
/// </summary>
public string HelpText
{
get { return _helpText; }
set { _helpText = value; }
}
/// <summary>
/// Luo uuden ohjaintapahtumien kuuntelijan
/// </summary>
/// <param name="triggerRule"></param>
/// <param name="context"></param>
/// <param name="ctrl"></param>
/// <param name="controlName"></param>
/// <param name="helpText"></param>
/// <param name="handler"></param>
/// <param name="args"></param>
public Listener(ChangePredicate<State> triggerRule, ListenContext context, Ctrl ctrl, string controlName, string helpText, Delegate handler, params object[] args)
{
this.isDestroyed = false;
this.isTriggered = triggerRule;
this.handler = handler;
this.Control = ctrl;
this._controlName = controlName;
this._helpText = helpText;
this.handlerParams = args;
this.Destroyed = null;
this.dynamicContext = false;
this.context = context;
this.contextedObject = null;
}
/// <summary>
/// Luo uuden ohjaintapahtumien kuuntelijan
/// </summary>
/// <param name="triggerRule"></param>
/// <param name="contexted"></param>
/// <param name="ctrl"></param>
/// <param name="controlName"></param>
/// <param name="helpText"></param>
/// <param name="handler"></param>
/// <param name="args"></param>
public Listener(ChangePredicate<State> triggerRule, ControlContexted contexted, Ctrl ctrl, string controlName, string helpText, Delegate handler, params object[] args)
{
this.isDestroyed = false;
this.isTriggered = triggerRule;
this.handler = handler;
this.Control = ctrl;
this._controlName = controlName;
this._helpText = helpText;
this.handlerParams = args;
this.Destroyed = null;
this.dynamicContext = true;
this.context = null;
this.contextedObject = contexted;
}
/// <summary>
/// Kutsuu tapahtumankäsittelijää.
/// </summary>
public void Invoke()
{
MethodInfo handlerMethod = handler.Method;
handlerMethod.Invoke(handler.Target, handlerParams);
}
/// <summary>
/// Kutsuu tapahtumankäsittelijää, mikäli sen ehto on toteutunut
/// </summary>
/// <param name="oldState">Vanha tila</param>
/// <param name="newState">Uusi tila</param>
public void CheckAndInvoke(State oldState, State newState)
{
if (!IsDestroyed && Context != null && !Context.IsDestroyed && Context.Active && isTriggered(oldState, newState))
Invoke();
}
/// <summary>
/// Kuuntelee tapahtumaa vain tietyssä kontekstissa.
/// </summary>
/// <param name="context"></param>
public Listener InContext(ListenContext context)
{
this.dynamicContext = false;
this.context = context;
return this;
}
/// <summary>
/// Kuuntelee tapahtumaa vain tietyssä kontekstissa.
/// Esim. Keyboard.Listen(parametrit).InContext(omaIkkuna) kuuntelee
/// haluttua näppäimistötapahtumaa ainoastaan kun ikkuna on näkyvissä ja päällimmäisenä.
/// </summary>
/// <param name="obj"></param>
public Listener InContext(ControlContexted obj)
{
this.dynamicContext = true;
this.contextedObject = obj;
return this;
}
#region Destroyable Members
/// <summary>
/// Onko olio tuhottu.
/// </summary>
/// <returns></returns>
public bool IsDestroyed
{
get { return isDestroyed; }
}
/// <summary>
/// Tuhoaa kuuntelijan
/// </summary>
public void Destroy()
{
isDestroyed = true;
OnDestroyed();
}
/// <summary>
/// Tapahtuu, kun olio tuhotaan.
/// </summary>
public event Action Destroyed;
private void OnDestroyed()
{
if (Destroyed != null)
Destroyed();
}
#endregion
}
}
|
using System;
namespace ITCastOCSS.Model
{
/// <summary>
/// Elective:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class Elective
{
public Elective()
{}
#region Model
private int _eid;
private int? _sid;
private int? _cid;
private decimal? _score;
/// <summary>
///
/// </summary>
public int EID
{
set{ _eid=value;}
get{return _eid;}
}
/// <summary>
///
/// </summary>
public int? SID
{
set{ _sid=value;}
get{return _sid;}
}
/// <summary>
///
/// </summary>
public int? CID
{
set{ _cid=value;}
get{return _cid;}
}
/// <summary>
///
/// </summary>
public decimal? Score
{
set{ _score=value;}
get{return _score;}
}
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace com.Sconit.Web.Models.SearchModels.ORD
{
public class IpMasterSearchModel:SearchModelBase
{
public string IpNo { get; set; }
public int? Status { get; set; }
public string PartyFrom { get; set; }
public string PartyTo { get; set; }
public int? IpOrderType { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string ShipFromAddress { get; set; }
public string type { get; set; }
public string Dock { get; set; }
public string Item { get; set; }
public string OrderNo { get; set; }
public string ExternalIpNo { get; set; }
public string ManufactureParty { get; set; }
public string Flow { get; set; }
public int? OrderSubType { get; set; }
public int? IpDetailType { get; set; }
public string CreateUserName { get; set; }
}
} |
using SmallWebApi.Adapters.Interface;
namespace SmallWebApi.Adapters
{
public class SomeAdapter : ISomePort
{
public void Save()
{
//TODO
}
}
}
|
using FluentAssertions;
using NUnit.Framework;
namespace Hatchet.Tests.ParserTests
{
[TestFixture]
public class EmptyFileTests
{
[Test]
public void Parse_EmptyFile_ReturnsNull()
{
// Arrange
var input = "";
var parser = new Parser();
// Act
var result = parser.Parse(ref input);
// Assert
result.Should().BeNull();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace TfsMobileServices.Controllers
{
public class TfsAccountController : ApiController
{
[Authorize]
public bool Get()
{
return true;
}
}
} |
using JT808.Protocol.Attributes;
using JT808.Protocol.Enums;
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 平台通用应答
/// </summary>
public class JT808_0x8001 : JT808Bodies, IJT808MessagePackFormatter<JT808_0x8001>
{
public override ushort MsgId { get; } = 0x8001;
public ushort MsgNum { get; set; }
/// <summary>
/// <see cref="JT808.Protocol.Enums.JT808MsgId"/>
/// </summary>
public ushort AckMsgId { get; set; }
public JT808PlatformResult JT808PlatformResult { get; set; }
public JT808_0x8001 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8001 jT808_0X8001 = new JT808_0x8001();
jT808_0X8001.MsgNum = reader.ReadUInt16();
jT808_0X8001.AckMsgId = reader.ReadUInt16();
jT808_0X8001.JT808PlatformResult = (JT808PlatformResult)reader.ReadByte();
return jT808_0X8001;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8001 value, IJT808Config config)
{
writer.WriteUInt16(value.MsgNum);
writer.WriteUInt16(value.AckMsgId);
writer.WriteByte((byte)value.JT808PlatformResult);
}
}
}
|
using Alabo.Cloud.People.UserRightss.Domain.Dtos;
using Alabo.Cloud.People.UserRightss.Domain.Entities;
using Alabo.Cloud.People.UserRightss.Domain.Services;
using Alabo.Data.People.Users.Domain.Services;
using Alabo.Extensions;
using Alabo.Framework.Basic.AutoConfigs.Domain.Services;
using Alabo.Framework.Basic.Grades.Domain.Configs;
using Alabo.Framework.Core.WebApis.Controller;
using Alabo.Framework.Core.WebApis.Filter;
using Alabo.Helpers;
using Alabo.Industry.Shop.Orders.Dtos;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using ZKCloud.Open.ApiBase.Models;
namespace Alabo.Cloud.People.UserRightss.Controllers
{
[ApiExceptionFilter]
[Route("Api/UserRights/[action]")]
public class ApiUserRightsController : ApiBaseController<UserRights, long>
{
public ApiUserRightsController()
{
BaseService = Resolve<IUserRightsService>();
}
/// <summary>
/// 开通页
/// </summary>
/// <param name="loginUserId"></param>
/// <returns></returns>
[HttpGet]
[Display(Description = "开通页")]
[ApiAuth]
public ApiResult<UserRightsOutput> OpenPage([FromQuery] long loginUserId, Guid gradeId)
{
var user = Ioc.Resolve<IUserService>().GetSingle(r => r.Id == loginUserId);
var result = Resolve<IUserRightsService>().GetView(loginUserId).FirstOrDefault(x => x.GradeId == gradeId);
//如果开通准营销中心和营销中心职能是管理员才能推荐开通
// 准营销中心,和营销中心的开通只能是管理员
//if (gradeId == Guid.Parse("f2b8d961-3fec-462d-91e8-d381488ea972") || gradeId == Guid.Parse("cc873faa-749b-449b-b85a-c7d26f626feb"))
//{
//如果不是管理员提示无权限
//if (result.OpenType == Domain.Enums.UserRightOpenType.AdminOpenHightGrade && !Resolve<IUserService>().IsAdmin(user.Id))
//{
// return ApiResult.Failure<UserRightsOutput>("您无权开通");
//}
//else
//{
// //管理员帮他人开通
// result.OpenType = Domain.Enums.UserRightOpenType.AdminOpenHightGrade;
//}
//}
return ApiResult.Success(result);
}
/// <summary>
/// 获取商家权益
/// </summary>
[HttpGet]
[Display(Description = "商家权益")]
[ApiAuth]
public ApiResult<IList<UserRightsOutput>> GetView([FromQuery] long loginUserId)
{
var result = Resolve<IUserRightsService>().GetView(loginUserId);
return ApiResult.Success(result);
}
/// <summary>
/// 商家服务订购
/// </summary>
/// <param name="parameter"></param>
[HttpPost]
[Display(Description = "商家服务订购")]
[ApiAuth]
public async Task<ApiResult<OrderBuyOutput>> Buy([FromBody] UserRightsOrderInput parameter)
{
if (!this.IsFormValid()) {
return ApiResult.Failure<OrderBuyOutput>(this.FormInvalidReason(),
MessageCodes.ParameterValidationFailure);
}
// var usr = Resolve<IUserService>().GetByIdNoTracking(parameter.UserId);
var result = await Resolve<IUserRightsService>().Buy(parameter);
if (!result.Item1.Succeeded) {
return ApiResult.Failure<OrderBuyOutput>(result.Item1.ToString(), MessageCodes.ServiceFailure);
}
var user = Resolve<IUserService>().GetSingle(s => s.Mobile == parameter.Mobile);
//如果该用户推荐人为空 则直接绑定当前登陆的账户
if (user != null && user.ParentId <= 0)
{
user.ParentId = parameter.UserId;
Resolve<IUserService>().Update(user);
}
return ApiResult.Success(result.Item2);
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="mobile"></param>
/// <returns></returns>
[HttpGet]
[Display(Description = "获取用户信息")]
[ApiAuth]
public ApiResult<string> GetUserIntro([FromQuery] string mobile)
{
var user = Resolve<IUserService>().GetSingleByUserNameOrMobile(mobile);
if (user == null)
{
var result = $"手机号为{mobile}的用户不存在,将注册为新用户";
return ApiResult.Success<string>(result);
}
var userGrades = Resolve<IAutoConfigService>().GetList<UserGradeConfig>();
var buyGrade = userGrades.FirstOrDefault(r => r.Id == user.GradeId);
if (buyGrade?.Price == 0)
{
var result = $"姓名:{user.Name},当前级别{buyGrade?.Name},可激活";
return ApiResult.Success<string>(result);
}
else
{
var result = $"姓名:{user.Name},当前级别{buyGrade?.Name},不可激活";
return ApiResult.Success<string>(result);
}
}
/// <summary>
/// </summary>
/// <param name="modelInput"></param>
/// <returns></returns>
[HttpPost]
[ApiAuth]
public ApiResult AddPorts([FromBody] AddPortsInput modelInput)
{
if (!this.IsFormValid()) {
return ApiResult.Failure("数据验证不通过");
}
if (modelInput.LoginUserId < 1) {
return ApiResult.Failure("登录会员Id没有传入进来");
}
var loginUser = Ioc.Resolve<IUserService>().GetSingle(r => r.Id == modelInput.LoginUserId);
if (loginUser == null) {
return ApiResult.Failure("对应ID会员不存在");
}
var forUser = Ioc.Resolve<IUserService>().GetSingleByUserNameOrMobile(modelInput.Mobile);
if (forUser == null)
{
//forUser = new Core.User.Domain.Entities.User {
// UserName = modelInput.Mobile,
// Name = modelInput.Mobile,
// Mobile = modelInput.Mobile,
// Status = Domains.Enums.Status.Normal,
//};
//forUser.Detail = new Core.User.Domain.Entities.UserDetail {
// Password = "111111".ToMd5HashString(), //登录密码
// PayPassword = "222222".ToMd5HashString() //支付密码
//};
//var result = Resolve<IUserBaseService>().Reg(forUser, false);
//if (!result.Result.Succeeded) {
// return ApiResult.Failure("新建用户失败!");
//}
}
var loginUserIsAdmin = Resolve<IUserService>().IsAdmin(modelInput.LoginUserId);
if (!loginUserIsAdmin) {
return ApiResult.Failure("登录用户不是Admin, 不能执行端口赠送!");
}
var rightsConfigList = Resolve<IUserRightsService>().GetView(modelInput.LoginUserId);
var forUserExistRights = Resolve<IUserRightsService>().GetList(x => x.UserId == forUser.Id);
for (var i = 1; i <= 5; i++)
{
var forCount = 0L;
var forGradeId = "";
switch (i)
{
case 1:
forCount = modelInput.Grade1;
forGradeId = "72be65e6-3000-414d-972e-1a3d4a366001";
break;
case 2:
forCount = modelInput.Grade2;
forGradeId = "6f7c8477-4d9a-486b-9fc7-8ce48609edfc";
break;
case 3:
forCount = modelInput.Grade3;
forGradeId = "72be65e6-3000-414d-972e-1a3d4a366002";
break;
case 4:
forCount = modelInput.Grade4;
forGradeId = "f2b8d961-3fec-462d-91e8-d381488ea972";
break;
case 5:
forCount = modelInput.Grade5;
forGradeId = "cc873faa-749b-449b-b85a-c7d26f626feb";
break;
}
if (forCount < 1) {
continue;
}
var rightItem = forUserExistRights.FirstOrDefault(x => x.GradeId == Guid.Parse(forGradeId));
if (rightItem == null)
{
rightItem = new UserRights
{
GradeId = rightsConfigList[i - 1].GradeId,
TotalCount = forCount,
UserId = forUser.Id
};
var rs = Resolve<IUserRightsService>().Add(rightItem);
}
else
{
rightItem.TotalCount += forCount;
var rs = Resolve<IUserRightsService>().Update(rightItem);
}
}
return ApiResult.Success("赠送端口成功!");
}
/// <summary>
/// 是否登记区域
/// </summary>
[HttpGet]
public ApiResult IsRegion(long UserId)
{
var model = Resolve<IUserDetailService>().GetSingle(u => u.UserId == UserId);
if (model == null) {
return ApiResult.Failure("未找到用户");
}
if (model.RegionId <= 0) {
return ApiResult.Failure("未登记区域");
}
return ApiResult.Success();
}
/// <summary>
/// 补登会员区域数据
/// </summary>
/// <param name="view"></param>
/// <returns></returns>
[HttpGet]
public ApiResult UserRightsAddRegion(UserRightsRegion view)
{
if (view == null) {
return ApiResult.Failure("传入数据为空");
}
if (view.RegionId <= 0) {
return ApiResult.Failure("请选择所属区域");
}
var model = Resolve<IUserDetailService>().GetSingle(u => u.UserId == view.UserId);
if (model == null) {
return ApiResult.Failure("用户不存在");
}
model.RegionId = view.RegionId;
var result = Resolve<IUserDetailService>().Update(model);
if (!result) {
return ApiResult.Failure("修改失败");
}
return ApiResult.Success();
}
}
} |
using System;
using ex2_DAL.Models;
using ex2_DAL.EF;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ex2_DAL.Repository
{
public class PersonRepository
{
private DalContext _context;
public PersonRepository()
{
_context = new DalContext();
}
public int Add(Person person)
{
if ((person.LastName != string.Empty) && (person.FirstName != string.Empty))
{
person.Id = Guid.NewGuid();
using (var context = new DalContext())
{
context.Person.Add(person);
return context.SaveChanges();
}
}
else return 0;
}
public IEnumerable<Person> GetByLastName(string filter)
{
return this._context.Person.Where(x => x.LastName.ToLower().Contains(filter.ToLower()));
}
public IEnumerable<Person> GetByFirstName(string filter)
{
return this._context.Person.Where(x => x.FirstName.ToLower().Contains(filter.ToLower()));
}
public Person Get(Guid id)
{
return this._context.Person.Where(x => x.Id == id).SingleOrDefault();
}
public int Update(Person person)
{
using (var context = new DalContext())
{
context.Person.Update(person);
return context.SaveChanges();
}
}
public int Delete(Person person)
{
using (var context = new DalContext())
{
context.Person.Remove(person);
return context.SaveChanges();
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.