text stringlengths 13 6.01M |
|---|
using System;
namespace SuncoastOverflowApi.ViewModels
{
public class NewQuestion
{
public string QuestionTitle { get; set; }
public string QuestionText { get; set; }
public int VoteValue { get; set; }
}
} |
using No8.Solution.Printers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace No8.Solution.Loggers
{
public interface ILogger
{
void Log(object sender, PrinterEventArgs args);
void Warn(string message);
void Register(Printer printer);
void Unregister(Printer printer);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.Entities.Enums
{
public enum EnumTipoLog
{
Erro = 0,
Informativo = 1
}
}
|
using UnityEngine;
using System.Linq;
using System.Collections.Generic;
public class BattleController : MonoBehaviour {
/*
* Gameplay
*/
public GameObject reportScreen;
public GameObject levelUpScreen;
public GameObject itemGained;
public SpriteRenderer itemGainedSprite;
public SpriteRenderer heroTitle;
public SpriteRenderer enemyTitle;
public TextMesh itemName;
private float[] positionList;
private bool[] positionAvailableList;
public List<Transform> listPrefab;
public GameObject skillShade;
public GameObject reportShade;
public GameObject pauseScreen;
public GameObject globalHeroHealthBar;
public GameObject globalEnemyHealthBar;
public List<GameObject> heroList;
public List<GameObject> enemyList;
public List<GameObject> skillList;
public List<GameObject> heroLevelUpSpriteList;
public SpriteRenderer bg;
public List<Skill> activeSkill;
public List<Unit> activeEnemyList;
public List<Unit> tempStats;
public TextMesh goldTextMesh;
public TextMesh diamondText;
public TextMesh expEarnedText;
public TextMesh winloseText;
public GameObject expBar;
// 0 => battle
// 1 => player win
// 3=> lose , kenapa 3? biar bisa dibuat pembagi sekalian
private int totalHero;
private int totalEnemy;
private int battleState = 0;
private int nextExp;
private float scaleX;
const float MaxExpBarScaleX = 0.85f;
/*
* Report
*/
private Vector3 ConstantHeroHealthLocalScale;
private Vector3 ConstantEnemyHealthLocalScale;
private float heroTotalHealth;
private float enemyTotalHealth;
private float ConstantHeroHealth; // untuk menghitung
private float ConstantEnemyHealth; // untuk menghitung
private int goldEarn;
private float expEarn;
private int diamondEarn;
private Mission mission;
private int isGetReward;
private const int itemChance = 60;
// Use this for initialization
void Start () {
DeactivateShade(0f,0f);
DeactivateSkillShade(0f,0f);
Debug.Log ("batltecontrol START");
heroTitle.sprite = GameData.titleSpriteList [GameData.profile.Title];
mission = GameData.missionList [GameData.currentMission];
enemyTitle.sprite = GameData.titleSpriteList [mission.Title];
battleState = 0;
if ( GameData.profile.TutorialState < 3 ){
SetPrefab();
}
MusicManager.play ("Music/royal2", 0.1f, 0.1f);
Sprite back = null;
back = (Sprite)Resources.Load ("Sprite/Background/"+mission.Place,typeof(Sprite));
bg.sprite = back;
// Debug.Log ("battle activate");
positionList = new float[12]{1.75f,3f,4.25f,5.5f,6.25f,7.5f,1.75f,3f,4.25f,5.5f,6.25f,7.5f};
positionAvailableList = new bool[12]{true,true,true,true,true,true,true,true,true,true,true,true};
isGetReward = 0;
activeEnemyList = mission.EnemyList;
Debug.Log ("Jumlah musuh " + activeEnemyList.Count);
activeSkill = new List<Skill> ();
int i = 0,j = 0;
totalHero = 0;
/*awal2 semua hero mati, kemudian dicek ada brp yang aktif*/
i = 0;
// if ( GameData.profile.TutorialState == 1 )
// GameData.gameState = GameConstant.GAMEPLAY_SCENE;
GameData.profile.RefreshFormation(); // refresh stats
for ( i = 0 ; i < 5 ; i ++ ) {
FormationUnit u = GameData.profile.formationList[i];// ambil unit di formation ke-i
activeSkill.Add(GameData.profile.skillList[0]); // tambahkan skill default
if ( u.IsUnlocked ){ // jika formation ke-i udah keunlock
if ( u.UnitHeroId != 99 ){ // jika bukan unit template
if ( GameData.profile.skillList[u.Unit.HeroId].IsUnlocked ){ // jika skill milik unit di form
// udah keunlock
activeSkill[i] = GameData.profile.skillList[u.Unit.HeroId];
skillList[i].SetActive(true);
}
u.Unit.Str += GameData.profile.Level;
u.Unit.Agi += GameData.profile.Level;
u.Unit.Vit += GameData.profile.Level;
if ( GameData.profile.TutorialState == 2 ){
u.Unit.Str += 5;
u.Unit.Agi += 5;
u.Unit.Vit += 5;
}
heroList[i].SetActive(true);
totalHero++;
Debug.Log("stas "+ u.Unit.Str + " " + u.Unit.Agi + " " + u.Unit.Vit);
u.Unit.SetStats();
Debug.Log("Hero ke " + i + " weapon lev " + u.Unit.Weapon.Rank);
heroTotalHealth += u.Unit.HealthPoint;
}
}
}
i = 0;
tempStats = new List<Unit> ();
for ( i = 0 ; i < activeEnemyList.Count ; i++) {
Unit s = activeEnemyList[i];
Debug.Log("enemy ke " + i + " " + s.Job);
s.Refresh();
enemyList[i].SetActive(true);
tempStats.Add(new Unit(s.HeroId,s.Job.Trim()));
int level = 0;
level = GameData.currentMission * 3 / 4;
if ( GameData.missionType == "Camp") //boss
level +=1;
else if ( GameData.missionType == "Fortress") //boss
level +=2;
else if ( GameData.missionType == "Castle") //boss
level += 3;
if ( GameData.profile.TutorialState == 3 ){
level += 2;
}
level += mission.Title;
for ( int l = 0 ; l < level ; l++ ){
s.LevelUp();
// Debug.Log("enemy job " + s.JobList[0] + " stas en"+ s.Str + " " + s.Agi + " " + s.Vit);
}
//Debug.Log("levl " + s.Level + " stas en"+ s.Str + " " + s.Agi + " " + s.Vit);
//for ( int r = 1 ; r < s.Weapon.Rank ; r++ ){
// s.Weapon.Upgrade(new UnitStatus());
//}
enemyTotalHealth += s.HealthPoint;
}
ConstantHeroHealthLocalScale = new Vector3(1f,globalHeroHealthBar.transform.localScale.y,globalHeroHealthBar.transform.localScale.z);
ConstantEnemyHealthLocalScale = new Vector3(1f,globalEnemyHealthBar.transform.localScale.y,globalEnemyHealthBar.transform.localScale.z);
totalEnemy = mission.EnemyList.Count;
ConstantHeroHealth = heroTotalHealth;
ConstantEnemyHealth = enemyTotalHealth;
ScaleExpBar ();
}
public float HeroTotalHealth {
get {
return heroTotalHealth;
}
set {
heroTotalHealth = value;
}
}
public float EnemyTotalHealth {
get {
return enemyTotalHealth;
}
set {
enemyTotalHealth = value;
}
}
// Update is called once per frame
void Update () {
//Debug.Log("range " + Mathf.Abs(heroList[0].transform.position.x - enemyList[0].transform.position.x));
if (Input.GetKeyDown (KeyCode.Escape) && GameData.gameState != "Paused") {
iTween.MoveTo ( pauseScreen,iTween.Hash("position",new Vector3(3.7f,-0.3f,-3f),"time", 0.1f,"onComplete","ReadyTween","onCompleteTarget",gameObject));
//sound.audio.PlayOneShot (sound.audio.clip);
GameData.gameState = "Paused";
GameData.readyToTween = false;
Debug.Log("pause");
ActivateShade(0f,0.1f);
}
else if (Input.GetKeyDown (KeyCode.Escape) && GameData.readyToTween && GameData.gameState == "Paused") {
pauseScreen.GetComponentInChildren<Unpause>().UnPause();
}
}
public void ReceiveDamage(string target,float damage){
if (target.Contains ("enemy")) {
UpdateEnemyHealthBar (damage);
} else {
UpdateHeroHealthBar (damage);
}
}
public int TotalHero {
get {
return totalHero;
}
set {
totalHero = value;
if ( totalHero == 0 ){
battleState = 5;
Lose();
}
}
}
public int TotalEnemy {
get {
return totalEnemy;
}
set {
totalEnemy = value;
if ( TotalEnemy == 0 ){
battleState = 1;
Win();
}
}
}
private void UpdateHeroHealthBar(float damage)
{
HeroTotalHealth -= damage;
if (heroTotalHealth <= 0)
heroTotalHealth = 0;
Vector3 temp = new Vector3(1.02f-(ConstantHeroHealthLocalScale * heroTotalHealth /
ConstantHeroHealth).x,
ConstantHeroHealthLocalScale.y,
ConstantHeroHealthLocalScale.z);
globalHeroHealthBar.transform.localScale = temp;
}
private void UpdateEnemyHealthBar(float damage){
enemyTotalHealth = Mathf.Floor(enemyTotalHealth- damage);
if (enemyTotalHealth <= 0) {
enemyTotalHealth = 0;
}
Vector3 temp2 = new Vector3((ConstantEnemyHealthLocalScale * enemyTotalHealth /
ConstantEnemyHealth).x - 1.02f,
ConstantEnemyHealthLocalScale.y,
ConstantEnemyHealthLocalScale.z);
globalEnemyHealthBar.transform.localScale = temp2;
}
// WIINNNN!!
void Win(){
winloseText.text = "Conquered!";
GetNonObjectReward();
GetObjectReward ();
// diamond kalau win doang + caslte + 1x doang dptnya
if (GameData.currentMission == GameData.profile.NextMission) {
diamondEarn = mission.DiamondReward;
GameData.profile.Diamond += diamondEarn;
if (GameData.missionType.Contains ("Fortress")){
var m = GameData.profile.questList.Where(x => x.Target.Contains("fortress")).ToList();
foreach( Quest q in m )
q.CurrentQuantity++;
}
else if (GameData.missionType.Contains ("Castle")){
var m = GameData.profile.questList.Where(x => x.Target.Contains("castle")).ToList();
foreach( Quest q in m )
q.CurrentQuantity++;
GameData.profile.Title++;
}
if ( GameData.profile.NextMission < 50 )
GameData.profile.NextMission++;
}
ShowOnReport ();
// Debug.Log ("win " + GameData.profile.DefeatedArmy);
}
void Lose(){
winloseText.text = "You Lose!";
GetNonObjectReward ();
ShowOnReport ();
// Debug.Log ("lose");
}
void GetNonObjectReward(){
goldEarn = mission.GoldReward / battleState;
GameData.profile.Gold += goldEarn;
}
void GetObjectReward(){
isGetReward = Random.Range (0, 99);
CheckTutorialState();
float getChance = itemChance - (GameData.currentMission/6);
// tiap battle chance 70. dikurangi tiap misi naik/6. misal 70 - misi 49/6 => 22
Debug.Log("Reward chance " + isGetReward + " mision chance " + getChance);
if (isGetReward < getChance && battleState == 1) {
int get = mission.GetReward;
itemGained.SetActive(true);
itemGainedSprite.sprite = GameData.gemSpriteList[get];
itemName.text = GameData.shopList[get].Name;
GameData.profile.inventoryList.Add(GameData.shopList[get]);
// Debug.Log("get reward");
}
}
public void ActivateShade(float delay,float time){
iTween.ColorTo (reportShade, iTween.Hash ("delay", delay, "a", 1f, "time", time, "EaseType", "linear"));
}
public void DeactivateShade(float delay,float time){
iTween.ColorTo (reportShade, iTween.Hash ("delay", delay, "a", 0f, "time", time, "EaseType", "linear"));
}
public void ActivateSkillShade(float delay,float time){
iTween.ColorTo (skillShade, iTween.Hash ("delay", delay, "a", 1f, "time", time, "EaseType", "linear"));
}
public void DeactivateSkillShade(float delay,float time){
iTween.ColorTo (skillShade, iTween.Hash ("delay", delay, "a", 0f, "time", time, "EaseType", "linear"));
}
void ShowOnReport(){
ScaleExpBar ();
GetExpReward ();
goldTextMesh.text ="+"+goldEarn.ToString ();
diamondText.text ="+"+diamondEarn.ToString ();
expEarnedText.text ="+"+expEarn.ToString ();
// Debug.Log ("report " + activeEnemyList.Count + " " + tempStats.Count);
for (int i = 0; i < activeEnemyList.Count; i++) {
activeEnemyList[i].CopyStats(tempStats[i]);
}
ActivateShade(2f,1f);
iTween.MoveTo (reportScreen, iTween.Hash ("position", new Vector3(0,0,reportScreen.transform.position.z), "time", 1.0f,"delay",3.0f));
GameData.SaveData ();
}
void ScaleExpBar(){
int gotExp = mission.ExpReward; // buat ngitung
scaleX = GameData.profile.CurrentExp * MaxExpBarScaleX / GameData.profile.NextExp; // cek awal2
//Debug.Log ("DI BATLE cur " + GameData.profile.CurrentExp + " got " + gotExp + " nesx " + GameData.profile.NextExp);
if ( battleState == 1 || battleState == 5 ){
gotExp /= battleState;
expEarn = gotExp;
if (GameData.profile.IsLevelUp(gotExp) ) {
//LEVELUP
GameData.profile.CurrentExp += gotExp;
scaleX = 0.85f;
// Debug.Log ("LEVEL UP");
iTween.MoveTo (levelUpScreen, iTween.Hash ("position", new Vector3(levelUpScreen.transform.position.x,1,
levelUpScreen.transform.position.z), "time", 1.0f,"delay",5.0f));
}
else{
// rescale
GameData.profile.CurrentExp += gotExp;
scaleX = GameData.profile.CurrentExp * MaxExpBarScaleX / GameData.profile.NextExp; // cek awal2
}
//Debug.Log("get exp");
}
// Debug.Log ("scale x" + scaleX);
Vector3 newScale = new Vector3 (scaleX,expBar.transform.localScale.y, expBar.transform.localScale.z);
iTween.ScaleTo (expBar, iTween.Hash("scale", newScale,
"time", 1.5f,
"delay",4.0f,"oncomplete","ReadyTween","oncompletetarget",gameObject));
}
void ReadyTween(){
GameData.readyToTween = true;
}
void GetExpReward(){
// untuk unit
int reward = mission.ExpReward / battleState;
int i = 0;
foreach (Unit u in GameData.profile.unitList) {
if ( u.IsActive ){
u.CurrentExp += reward;
i++;
}
}
for (int j = 0 ; j < GameData.profile.formationList.Count ; j++) {
FormationUnit u = GameData.profile.formationList[j];
if ( u.UnitHeroId != 99 ){
if ( u.Unit.IsLevelUp(reward)){
GameObject spr = heroLevelUpSpriteList[j];
iTween.MoveTo(spr,iTween.Hash("position",new Vector3(spr.transform.position.x,-5f,-3.3f),
"time",0.5f,"delay",4.5f));
}
}
}
//GameData.profile.RefreshFormation ();
mission = null;
}
void CheckTutorialState(){
if ( GameData.profile.TutorialState < 3 )
isGetReward = 100;
}
public void SetPrefab(){
Debug.Log("set tutorial state " + GameData.profile.TutorialState);
iTween.MoveTo ( this.gameObject,iTween.Hash("time",3.5f,"onComplete","ShowPrefab","onCompleteTarget",gameObject));
}
void ShowPrefab(){
if ( GameData.profile.TutorialState < GameConstant.TOTAL_TUTORIAL ){
//battleState = 6;// tutorialstate
Transform t = listPrefab [GameData.profile.TutorialState-2];
Instantiate (t, new Vector3(t.position.x,t.position.y,t.position.z), Quaternion.identity);
}
}
public void DestoryPrefab(){
GameObject temp = GameObject.FindGameObjectWithTag ("Tutorial");
Debug.Log ("at tutor destroy " + temp);
Destroy (temp);
}
public int BatlleState {
get {
return battleState;
}
set {
battleState = value;
}
}
public float[] PositionList {
get {
return positionList;
}
set {
positionList = value;
}
}
public bool[] PositionAvailableList {
get {
return positionAvailableList;
}
set {
positionAvailableList = value;
}
}
}
|
using GameLoanManager.Domain.Interfaces;
using GameLoanManager.Service;
using Microsoft.Extensions.DependencyInjection;
namespace GameLoanManager.Helpers.DependencyInjection
{
public class ServicesConfiguration
{
public static void ConfigureDependencies(IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<IUserService, UserService>();
serviceCollection.AddTransient<IGameService, GameService>();
serviceCollection.AddTransient<ILoanedGameService, LoanedGameService>();
serviceCollection.AddTransient<ITokenService, TokenService>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace лаба_8
{
interface Interface<T>
{
void Add(params T[] item);
void RemoveEl(T item);
void Print();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
private static readonly Joycon.Button[] m_buttons =
Enum.GetValues(typeof(Joycon.Button)) as Joycon.Button[];
public List<GameObject> player = new List<GameObject>();
public List<GameObject> bloom = new List<GameObject>();
public List<ResultData> resultArray = new List<ResultData>();
private bool[] finishTrigger = { false, false, false, false };
public mainManager mm;
public GameObject ex;
private List<Joycon> m_joycons;
private Joycon m_joycon1;
private Joycon m_joycon2;
private Joycon.Button? m_pressedButtonL; //null 許容型
private Joycon.Button? m_pressedButtonR;
int gameOverCount = 0;
private void Start()
{
mm = this.GetComponent<mainManager>();
m_joycons = JoyconManager.Instance.j;
if (m_joycons == null || m_joycons.Count <= 0) return;
m_joycon1 = m_joycons.Find(c => c.isLeft);
m_joycon2 = m_joycons.Find(c => !c.isLeft);
}
private void Update()
{
m_pressedButtonL = null;
m_pressedButtonR = null;
if (m_joycons == null || m_joycons.Count <= 0) return;
//ボタン判定
foreach (var button in m_buttons)
{
if (m_joycon1.GetButton(button))
{
m_pressedButtonL = button;
}
if (m_joycon2.GetButton(button))
{
m_pressedButtonR = button;
}
}
//回転・移動とってるとこ
for (int i = 0; i < m_joycons.Count; i++)
{
if (player[i] == null) continue;
player[i].transform.rotation = m_joycons[i].GetVector();
if (mm.startTrigger)
{
player[i].transform.position += new Vector3(m_joycons[i].GetStick()[0] / 2, m_joycons[i].GetStick()[1] / 2, 0);
}
}
if (finishTrigger[0])
{
if (m_joycons.Count == 1)
{
//Resultへ
mm.FinishGame();
}
else if (finishTrigger[1])
{
if (m_joycons.Count == 2)
{
//Resultへ
mm.FinishGame();
}
else if (finishTrigger[2])
{
if (m_joycons.Count == 3)
{
//Resultへ
mm.FinishGame();
}
else if (finishTrigger[3])
{
//Resultへ
mm.FinishGame();
}
}
}
}
for (int i = 0; i < bloom.Count; i++)
{
if (bloom[i] == null) continue;
Debug.Log(Mathf.Abs(90 - bloom[i].transform.localEulerAngles.x));
//if (Vector3.Dot(bloom[i].transform.position, player[i].transform.position) <= 110f)
if (Mathf.Abs(90 - bloom[i].transform.localEulerAngles.x) <= 60)
{
Destroy(bloom[i].GetComponent<HingeJoint>());
}
if (bloom[i].transform.position.z > 30)
{
Instantiate(ex, bloom[i].transform.position, bloom[i].transform.rotation);
//m_joycons[i].SetRumble(160, 320, 0.6f, 50);
int rank = player.Count - gameOverCount;
gameOverCount++;
var resultData = new ResultData(i+1, mm.time, rank);
resultArray.Add(resultData);
Destroy(bloom[i]);
Destroy(player[i]);
finishTrigger[i] = true;
}
}
//バイブレーション
// if ( Input.GetKeyDown( KeyCode.Z ) )
// {
// m_joycon1.SetRumble( 160, 320, 0.6f, 200 );
// }
// if ( Input.GetKeyDown( KeyCode.X ) )
// {
// m_joycon2.SetRumble( 160, 320, 0.6f, 200 );
// }
}
public void Score()
{
for (int i = player.Count; i >= 0; i--)
{
if(player[i-1] != null){
var resultData = new ResultData(i, 60, 1);
resultArray.Add(resultData);
}
}
}
private void OnGUI()
{
var style = GUI.skin.GetStyle("label");
style.fontSize = 24;
if (m_joycons == null || m_joycons.Count <= 0)
{
GUILayout.Label("Joy-Con が接続されていません");
return;
}
if (!m_joycons.Any(c => c.isLeft))
{
GUILayout.Label("Joy-Con (L) が接続されていません");
return;
}
if (!m_joycons.Any(c => !c.isLeft))
{
GUILayout.Label("Joy-Con (R) が接続されていません");
return;
}
GUILayout.BeginHorizontal(GUILayout.Width(960));
// foreach (var joycon in m_joycons)
// {
// var isLeft = joycon.isLeft;
// var name = isLeft ? "Joy-Con (L)" : "Joy-Con (R)";
// var key = isLeft ? "Z キー" : "X キー";
// var button = isLeft ? m_pressedButtonL : m_pressedButtonR;
// var stick = joycon.GetStick();
// var gyro = joycon.GetGyro();
// var accel = joycon.GetAccel();
// var orientation = joycon.GetVector();
// GUILayout.BeginVertical(GUILayout.Width(480));
// GUILayout.Label(name);
// GUILayout.Label(key + ":振動");
// GUILayout.Label("押されているボタン:" + button);
// GUILayout.Label(string.Format("スティック:({0}, {1})", stick[0], stick[1]));
// GUILayout.Label("ジャイロ:" + gyro);
// GUILayout.Label("加速度:" + accel);
// GUILayout.Label("傾き:" + orientation);
// GUILayout.EndVertical();
// }
// GUILayout.EndHorizontal();
}
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: entry_data.proto
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Etg.Data.Entry {
public static class EntryDataService
{
static readonly string __ServiceName = "etg.data.entry.EntryDataService";
static readonly Marshaller<global::Etg.Data.Entry.GetEntryStatusRequest> __Marshaller_GetEntryStatusRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Etg.Data.Entry.GetEntryStatusRequest.Parser.ParseFrom);
static readonly Marshaller<global::Etg.Data.Entry.GetEntryStatusResponse> __Marshaller_GetEntryStatusResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Etg.Data.Entry.GetEntryStatusResponse.Parser.ParseFrom);
static readonly Method<global::Etg.Data.Entry.GetEntryStatusRequest, global::Etg.Data.Entry.GetEntryStatusResponse> __Method_GetEntryStatus = new Method<global::Etg.Data.Entry.GetEntryStatusRequest, global::Etg.Data.Entry.GetEntryStatusResponse>(
MethodType.DuplexStreaming,
__ServiceName,
"GetEntryStatus",
__Marshaller_GetEntryStatusRequest,
__Marshaller_GetEntryStatusResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Etg.Data.Entry.EntryDataReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of EntryDataService</summary>
public abstract class EntryDataServiceBase
{
public virtual global::System.Threading.Tasks.Task GetEntryStatus(IAsyncStreamReader<global::Etg.Data.Entry.GetEntryStatusRequest> requestStream, IServerStreamWriter<global::Etg.Data.Entry.GetEntryStatusResponse> responseStream, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for EntryDataService</summary>
public class EntryDataServiceClient : ClientBase<EntryDataServiceClient>
{
/// <summary>Creates a new client for EntryDataService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public EntryDataServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for EntryDataService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public EntryDataServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected EntryDataServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected EntryDataServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual AsyncDuplexStreamingCall<global::Etg.Data.Entry.GetEntryStatusRequest, global::Etg.Data.Entry.GetEntryStatusResponse> GetEntryStatus(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetEntryStatus(new CallOptions(headers, deadline, cancellationToken));
}
public virtual AsyncDuplexStreamingCall<global::Etg.Data.Entry.GetEntryStatusRequest, global::Etg.Data.Entry.GetEntryStatusResponse> GetEntryStatus(CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_GetEntryStatus, null, options);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override EntryDataServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new EntryDataServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(EntryDataServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetEntryStatus, serviceImpl.GetEntryStatus).Build();
}
}
}
#endregion
|
using System;
using Xamarin.Forms;
namespace Workout.Models.Workout
{
/// <summary>
/// Details header data class.
/// </summary>
public class DetailsHeaderData : BindableObject
{
#region properties
/// <summary>
/// Bindable property definition for local time.
/// </summary>
public static readonly BindableProperty LocalTimeProperty =
BindableProperty.Create("LocalTime", typeof(DateTime), typeof(DetailsHeaderData), default(DateTime));
/// <summary>
///Header title.
/// </summary>
public string Title
{
get;
set;
}
/// <summary>
///Start time.
/// </summary>
public DateTime StartTime
{
get;
set;
}
/// <summary>
/// Local time.
/// </summary>
public DateTime LocalTime
{
get => (DateTime)GetValue(LocalTimeProperty);
set => SetValue(LocalTimeProperty, value);
}
#endregion
}
}
|
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using MonoGame.Extended.Tiled;
public static class EntityManager
{
public static List<IGameEntity> AllEntities = new List<IGameEntity>();
public static IGameEntity Create(string TypeName, Vector2 Position, TiledMapProperties Props)
{
IGameEntity created = null;
switch (TypeName)
{
case "ball":
created = new Ball();
break;
case "rat":
created = new Rat();
break;
case "bat":
// do nothing
break;
case "light":
var color = Props.Where(x => x.Key == "color").FirstOrDefault().Value;
var radius = Props.Where(x => x.Key == "radius").FirstOrDefault().Value;
var _color = new Color(0,0,0);
if (!String.IsNullOrEmpty(color))
{
var fromhex = System.Drawing.ColorTranslator.FromHtml(color);
_color = new Color(fromhex.R, fromhex.G, fromhex.B);
}
var _radius = 3000f;
if (!String.IsNullOrEmpty(radius))
{
float.TryParse(radius, System.Globalization.NumberStyles.Any, null, out _radius);
}
created = new WorldLight(Position, _radius, _color);
break;
default:
throw new NotImplementedException();
}
if (created != null) {
created.Position = Position;
AllEntities.Add(created);
}
return created;
}
public static void Remove(IGameEntity toRemove)
{
AllEntities.Remove(toRemove);
}
public static IEnumerable<IGameEntity> GetPlayers()
{
return AllEntities.Where(x => x is Player);
}
public static IGameEntity GetClosestPlayer(Vector2 position)
{
return GetPlayers().OrderBy(x => (x.Position - position).Length()).FirstOrDefault();
}
} |
using SoSmartTv.VideoService.Dto;
namespace SoSmartTv.VideoPlayer.ViewModels
{
public interface IVideoDetailsViewModel
{
VideoItem Details { get; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace Sbidu.ViewModels
{
public class RegisterViewModel
{
[Required]
[MaxLength(100)]
public string FullName { get; set; }
[Required]
[MaxLength(100)]
public string UserName { get; set; }
[Required()]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class MenuControllerScript : MonoBehaviour
{
public int index;
public int maxIndex;
public AudioSource audioSource;
float prevKeyDown;
GraphicRaycaster graphicRaycaster;
MenuButtonScript selectedButton;
private void Awake()
{
graphicRaycaster = GetComponent<GraphicRaycaster>();
}
private void Start()
{
audioSource = GetComponent<AudioSource>();
}
private void Update()
{
// Mouse Selection Input
PointerEventData pointerData = new PointerEventData(EventSystem.current);
List<RaycastResult> raycastResults = new List<RaycastResult>();
pointerData.position = Input.mousePosition;
this.graphicRaycaster.Raycast(pointerData, raycastResults);
if (selectedButton)
selectedButton.mouseHovering = false;
foreach (RaycastResult result in raycastResults)
{
MenuButtonScript resultScript = result.gameObject.GetComponentInParent<MenuButtonScript>();
if (resultScript)
{
index = resultScript.GetIndex();
resultScript.mouseHovering = true;
selectedButton = resultScript;
}
}
// Keyboard Selection Input
if (Input.GetAxis("Vertical") != 0 && prevKeyDown == 0)
{
if(Input.GetAxis("Vertical") < 0)
{
index = index + 1;
if (index > maxIndex)
index = 0;
}
else if(Input.GetAxis("Vertical") > 0)
{
index -= 1;
if (index < 0)
index = maxIndex;
}
}
prevKeyDown = Input.GetAxis("Vertical");
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web.Mvc;
using iTemplate.Web.Models.Data.Core;
namespace iTemplate.Web.Models.Data
{
[Table("SiteNavigationRole")]
public class SiteNavigationRole: CoreEntity
{
[Key]
[Required]
[ScaffoldColumn(false)]
[HiddenInput(DisplayValue = false)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual int MenuId { get; set; }
public virtual string RoleId { get; set; }
private ICollection<int> NavigationRoles { get; set; }
public SiteNavigationRole()
{
ApplicationDbContext db = new ApplicationDbContext();
this.NavigationRoles = new HashSet<int>();
}
private void GetNavigationRoles()
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var navigationRoles = db.SiteNavigationRoles.Where(x => x.IsPublished);
if (navigationRoles.Any())
{
foreach (var role in navigationRoles)
{
NavigationRoles.Add(role.Id);
}
}
}
}
/// <summary>
/// Single role check
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public bool IsAuthorised(int Id)
{
foreach (var roleId in NavigationRoles)
{
if (roleId == Id) { return true; }
}
return false;
}
}
}
|
using UnityEngine;
using System.Collections;
public class ICanTalk : MonoBehaviour {
public int WhichThingToSay;
public string[] Messages;
public GUISkin Skin;
public bool IsCloseEnough = false;
void OnTriggerEnter() {
WhichThingToSay += 1;
IsCloseEnough = true;
}
void OnTriggerExit() {
IsCloseEnough = false;
}
void Update() {
if(WhichThingToSay > Messages.Length) {
IsCloseEnough = false;
}
if(Input.GetKeyDown(KeyCode.Escape)) {
Application.LoadLevel(0);
}
}
void OnGUI() {
GUI.skin = Skin;
if(IsCloseEnough) {
GUI.Label(new Rect(30, 360, 560, 250), Messages[WhichThingToSay]);
}
GUI.Label(new Rect(-160, 0, 500, 250), "Press escape to leave");
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Okta.Auth.Sdk;
using Okta.Sdk.Abstractions.Configuration;
namespace Test_Form_Manipulation
{
public partial class login : Form
{
public login()
{
InitializeComponent();
File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "cookies.dat"));
//string userName = "";
if (!Properties.Settings.Default.cloudLoginOnly)
{
//Use windows login and autologin
//userName = WindowsIdentity.GetCurrent().Name;
//string toBeSearched = "\\";
////userName = "test\\test";
//int ix = userName.IndexOf(toBeSearched);
//if (ix != -1)
//{
// userName = userName.Substring(ix + toBeSearched.Length);
//}
//Properties.Settings.Default.localusername = userName;
//this.Hide();
//var form2 = new Form1();
//form2.Closed += (s, args) => this.Close();
//form2.Show();
}
}
public static string PostMessageToURL(string url, string parameters)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
wc.Headers[HttpRequestHeader.Accept] = "application/json";
string HtmlResult = wc.UploadString(url, "POST", parameters);
return HtmlResult;
}
}
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
private void buttonLogin_Click(object sender, EventArgs e)
{
try
{
string body = "";
if (username1.Text == "" || password1.Text == "")
{
MessageBox.Show("Username or Password Cannot be blank", "Login Error");
return;
}
else
{
body = "{\"username\": \"" + username1.Text + "\",\"password\": \"" + password1.Text + "\"}";
}
string response1 = PostMessageToURL("https://" + Properties.Settings.Default.oktatenant + "/api/v1/authn", body);
JObject rss = JObject.Parse(response1);
string status = (string)rss["status"];
Properties.Settings.Default.oktastate = (string)rss["stateToken"];
Properties.Settings.Default.oktauserid = (string)rss["_embedded"]["user"]["id"];
if (status == "MFA_REQUIRED")
{
loginpanel.Hide();
smspanel.Hide();
mfapanel.Show();
int mfacount = rss["_embedded"]["factors"].Count();
for (int i = 0; i < mfacount; i++)
{
string nfactor = (string)rss["_embedded"]["factors"][i]["factorType"];
switch (nfactor)
{
//Coming Soon!
//case "push":
// ComboboxItem item = new ComboboxItem();
// item.Text = "Okta Verify";
// item.Value = (string)rss["_embedded"]["factors"][i]["id"];
// mfalist.Items.Add(item);
// break;
//case "token:software:totp":
// ComboboxItem item2 = new ComboboxItem();
// item2.Text = "OTP";
// item2.Value = (string)rss["_embedded"]["factors"][i]["id"];
// mfalist.Items.Add(item2);
// break;
case "sms":
ComboboxItem item3 = new ComboboxItem();
item3.Text = "SMS";
item3.Value = (string)rss["_embedded"]["factors"][i]["id"];
mfalist.Items.Add(item3);
break;
}
}
}
else
{
Properties.Settings.Default.oktasession = (string)rss["sessionToken"];
Properties.Settings.Default.email = username1.Text;
this.Hide();
var form2 = new Dashboard();
form2.Closed += (s, args) => this.Close();
form2.Show();
}
}
catch (Exception Ex1)
{
MessageBox.Show(Ex1.Message, "Login Error");
return;
}
}
private void mfalist_SelectedIndexChanged(object sender, EventArgs e)
{
ComboboxItem sitem = (ComboboxItem)mfalist.SelectedItem;
try
{
if (sitem.Text == "SMS")
{
mfalist.Enabled = false;
smspanel.Visible = true;
string body = "{\"stateToken\": \"" + Properties.Settings.Default.oktastate + "\"}";
string response1 = PostMessageToURL("https://" + Properties.Settings.Default.oktatenant + "/api/v1/authn/factors/" + sitem.Value.ToString() + "/verify", body);
JObject rss = JObject.Parse(response1);
string status = (string)rss["status"];
Properties.Settings.Default.oktastate = (string)rss["stateToken"];
Properties.Settings.Default.oktafactorid = sitem.Value.ToString();
}
}
catch (Exception ex)
{
}
}
private void submitSMS_Click(object sender, EventArgs e)
{
try
{
string body = "{\"stateToken\": \"" + Properties.Settings.Default.oktastate + "\", \"passCode\":\"" + smsTextbox.Text + "\"}";
string response1 = PostMessageToURL("https://" + Properties.Settings.Default.oktatenant + "/api/v1/authn/factors/" + Properties.Settings.Default.oktafactorid + "/verify", body);
JObject rss = JObject.Parse(response1);
string status = (string)rss["status"];
if (status == "SUCCESS")
{
Properties.Settings.Default.oktasession = (string)rss["sessionToken"];
this.Hide();
var form2 = new Dashboard();
form2.Closed += (s, args) => this.Close();
form2.Show();
}
else
{
smsError.Visible = true;
}
}
catch (Exception ex)
{
}
}
private void password1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
buttonLogin.PerformClick();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace Restoran.Models
{
public class OrderModel
{
public int IdOrder { get; set; }
public string MejaId { get; set; }
public string MenuId { get; set; }
public int JumlahMenu { get; set; }
public string Nama { get; set; }
public string Images { get; set; }
public int Harga { get; set; }
public int Stok { get; set; }
public int NoMeja { get; set; }
public int Status { get; set; }
//Buat dropdown
public IEnumerable<SelectListItem> tMejas { get; set; }
public IEnumerable<SelectListItem> tMenus { get; set; }
public OrderModel()
{
tMejas = new List<SelectListItem>();
tMenus = new List<SelectListItem>();
}
//buat checkbox
public List<CheckBoxes> DaftarMenu { get; set; }
public class CheckBoxes
{
public string Text { get; set; }
public string Value { get; set; }
public bool Checked { get; set; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.ComponentModel;
namespace CG
{
class Erosion : MatrixFilter
{
public Erosion()
{
kernel = new float[3, 3];
kernel[0, 0] = 0.0f; kernel[0, 1] = 1.0f; kernel[0, 2] = 0.0f;
kernel[1, 0] = 1.0f; kernel[1, 1] = 1.0f; kernel[1, 2] = 1.0f;
kernel[2, 0] = 0.0f; kernel[2, 1] = 1.0f; kernel[2, 2] = 0.0f;
}
public Erosion(float[,] kernel)
{
this.kernel = kernel;
}
protected override System.Drawing.Color calculateNewPixelColor(System.Drawing.Bitmap sourceImage, int x, int y)
{
// определяем радиус действия фильтра по оси X
int radiusX = kernel.GetLength(0) / 2;
// определяем радиус действия фильтра по оси Y
int radiusY = kernel.GetLength(1) / 2;
Color resultColor = Color.White;
byte min = 255;
for (int l = -radiusY; l <= radiusY; l++)
for (int k = -radiusX; k <= radiusX; k++)
{
int idX = Clamp(x + k, 0, sourceImage.Width - 1);
int idY = Clamp(y + l, 0, sourceImage.Height - 1);
Color color = sourceImage.GetPixel(idX, idY);
int intensity = color.R;
if (color.R != color.G || color.R != color.B || color.G != color.B)
{
intensity = (int)(0.36 * color.R + 0.53 * color.G + 0.11 * color.R);
}
if (kernel[k + radiusX, l + radiusY] > 0 && intensity < min)
{
min = (byte)intensity;
resultColor = color;
}
}
return resultColor;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace Yelemani.Database
{
class user
{
MySqlConnection con;
MySqlCommand cmd;
public user()
{
try
{
con = new MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=yelemani;");
con.Close();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
public DataTable checkuser(string str1, string str2)
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select Nom,Admin,Rappel from user where username='" + str1 + "' and password='" + str2 + "'",con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
public bool chechusername(string str1)
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select nom from user where username='" + str1+"'" , con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (dt.Rows.Count != 0)
return true;
else
return false;
}
public void add(string str1, string str2, string str3, string str4, string str5, string str6, string str7)
{
cmd = new MySqlCommand("insert into user (nom, prenom, username, password, rappel, admin,telephone) values('" + str1.ToUpper() + "','" + str2.ToUpper() + "','" + str3.ToUpper() + "','" + str4 + "','" + str6 + "','" + str5.ToUpper() + "','" + str7.Trim() + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public void clear(string str1)
{
cmd = new MySqlCommand("delete from user where username='" + str1.ToUpper() + "'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public DataTable refresh()
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select Nom,Prenom,Telephone,Username,Password,Rappel,Admin from user ", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
public DataTable refresh(string username, string password)
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select Nom,Prenom,Telephone,Username,Password,Rappel,Admin from user where username='"+username+"' and password='"+password+"' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
public void update(string nom, string prenom, string telephone, string username, string password,string rappel,string statut,string selectedName, string selectedtelephone)
{
cmd = new MySqlCommand("update user set nom='" + nom + "',prenom='"+prenom+"',telephone='"+telephone+ "',username='" + username + "',password='" + password + "',rappel='" + rappel + "',admin='"+statut+"' where nom='" + selectedName+"' and telephone='"+selectedtelephone+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public void update(string nom, string prenom, string telephone, string username, string password, string rappel, string selectedUser, string selectedpassword)
{
try
{
cmd = new MySqlCommand("update user set nom='" + nom + "',prenom='" + prenom + "',telephone='" + telephone + "',username='" + username + "',password='" + password + "',rappel='" + rappel + "' where username='" + selectedUser + "' and password='" + selectedpassword + "'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Compte mis à jour avec succès");
}
catch
{
MessageBox.Show("Echec");
}
}
public string getrappel(string str)
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("select rappel from user where username='"+str+"'", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (dt.Rows.Count != 0)
return dt.Rows[0].ItemArray[0].ToString();
else
return null;
}
}
}
|
using System;
namespace SpiralFramework.Konsoru.Imperator
{
class ImperatorParser
{
public ImperatorParser()
{
}
}
}
|
using System;
namespace GomokuEngine
{
public enum BothPlayerEvaluation : byte
{
overline_defending,
four_attacking,
four_defending_vct,
four_defending,
o3_attacking,
o3_defending,
o3_defending_vct,
c3xc3_attacking,
c3xc3_defending,
c3xc3_defending_vct,
c3xo2_attacking,
c3xo2_defending,
c3xo2_defending_vct,
c3xo1_attacking,
c3xo1_defending,
s3_attacking,
s3_defending,
c3_attacking,
c3_defending,
o2xo2_attacking,
o2xo2_defending,
o2xo1_attacking,
o2xo1_defending,
double1_both,
o2p_attacking,
o2_attacking,
o2p_defending,
o2_defending,
tripple1_attacking,
tripple1_defending,
double1_attacking,
double1_defending,
o1_both,
o1p_attacking,
o1_attacking,
o1p_defending,
o1_defending,
rest,
forbidden,
occupied,
unknown,
};
public class BothData
{
public int hash;
public BothPlayerEvaluation evaluationBlackOnMove;
public BothPlayerEvaluation evaluationWhiteOnMove;
}
class EvaluateBoth
{
BothPlayerEvaluation[] lookupTableBlack;
BothPlayerEvaluation[] lookupTableWhite;
int boardSize;
BothData[] bothData;
public EvaluateBoth(int boardSize)
{
this.boardSize = boardSize;
//compute number of squares of board
int numberOfSquares = boardSize * boardSize;
bothData = new BothData[numberOfSquares];
for (int square = 0; square < numberOfSquares; square++)
{
bothData[square] = new BothData();
bothData[square].hash = -1;
}
InitializeEvaluationTable();
}
void InitializeEvaluationTable()
{
int nbPlayerEvaluations = Enum.GetValues(typeof(FourDirectionsEvaluation)).Length;
lookupTableBlack = new BothPlayerEvaluation[0x400]; //2^5 * 2^5 = 32 * 32 = 1024 entries
lookupTableWhite = new BothPlayerEvaluation[0x400]; //2^5 * 2^5 = 32 * 32 = 1024 entries
/* initialize evaluationArray */
for (int evaluationBlack = 0; evaluationBlack < nbPlayerEvaluations; evaluationBlack++)
{
for (int evaluationWhite = 0; evaluationWhite < nbPlayerEvaluations; evaluationWhite++)
{
int index = evaluationBlack << 5 | evaluationWhite;
lookupTableBlack[index] = GetBothPlayerEvaluation((FourDirectionsEvaluation)evaluationBlack, (FourDirectionsEvaluation)evaluationWhite);
lookupTableWhite[index] = GetBothPlayerEvaluation((FourDirectionsEvaluation)evaluationWhite, (FourDirectionsEvaluation)evaluationBlack);
}
}
}
BothPlayerEvaluation GetBothPlayerEvaluation(FourDirectionsEvaluation attacker, FourDirectionsEvaluation defender)
{
if (attacker <= FourDirectionsEvaluation.overline) return BothPlayerEvaluation.forbidden;
if (attacker <= FourDirectionsEvaluation.four) return BothPlayerEvaluation.four_attacking;
if (defender <= FourDirectionsEvaluation.overline) return BothPlayerEvaluation.overline_defending;
if (defender <= FourDirectionsEvaluation.four && attacker <= FourDirectionsEvaluation.o2xo1) return BothPlayerEvaluation.four_defending_vct;
if (defender <= FourDirectionsEvaluation.four) return BothPlayerEvaluation.four_defending;
if (attacker <= FourDirectionsEvaluation.o3) return BothPlayerEvaluation.o3_attacking;
if (attacker <= FourDirectionsEvaluation.c3xc3) return BothPlayerEvaluation.c3xc3_attacking;
if (attacker <= FourDirectionsEvaluation.c3xo2) return BothPlayerEvaluation.c3xo2_attacking;
if (attacker <= FourDirectionsEvaluation.c3xo1) return BothPlayerEvaluation.c3xo1_attacking;
if (attacker <= FourDirectionsEvaluation.s3) return BothPlayerEvaluation.s3_attacking;
if (defender <= FourDirectionsEvaluation.o3 && attacker <= FourDirectionsEvaluation.o2xo1) return BothPlayerEvaluation.o3_defending_vct;
if (defender <= FourDirectionsEvaluation.o3) return BothPlayerEvaluation.o3_defending;
if (attacker <= FourDirectionsEvaluation.c3) return BothPlayerEvaluation.c3_attacking;
if (defender <= FourDirectionsEvaluation.c3xc3 && attacker <= FourDirectionsEvaluation.o2xo1) return BothPlayerEvaluation.c3xc3_defending_vct;
if (defender <= FourDirectionsEvaluation.c3xc3) return BothPlayerEvaluation.c3xc3_defending;
if (defender <= FourDirectionsEvaluation.c3xo2 && attacker <= FourDirectionsEvaluation.o2xo1) return BothPlayerEvaluation.c3xo2_defending_vct;
if (defender <= FourDirectionsEvaluation.c3xo2) return BothPlayerEvaluation.c3xo2_defending;
if (defender <= FourDirectionsEvaluation.c3xo1) return BothPlayerEvaluation.c3xo1_defending;
if (defender <= FourDirectionsEvaluation.s3) return BothPlayerEvaluation.s3_defending;
if (attacker <= FourDirectionsEvaluation.o2xo2) return BothPlayerEvaluation.o2xo2_attacking;
if (attacker <= FourDirectionsEvaluation.o2xo1) return BothPlayerEvaluation.o2xo1_attacking;
if (defender <= FourDirectionsEvaluation.c3) return BothPlayerEvaluation.c3_defending;
if (defender <= FourDirectionsEvaluation.o2xo2) return BothPlayerEvaluation.o2xo2_defending;
if (defender <= FourDirectionsEvaluation.o2xo1) return BothPlayerEvaluation.o2xo1_defending;
if (attacker <= FourDirectionsEvaluation.double1 && defender <= FourDirectionsEvaluation.double1) return BothPlayerEvaluation.double1_both;
if (attacker <= FourDirectionsEvaluation.o2p) return BothPlayerEvaluation.o2p_attacking;
if (attacker <= FourDirectionsEvaluation.o2) return BothPlayerEvaluation.o2_attacking;
if (defender <= FourDirectionsEvaluation.o2p) return BothPlayerEvaluation.o2p_defending;
if (defender <= FourDirectionsEvaluation.o2) return BothPlayerEvaluation.o2_defending;
if (attacker <= FourDirectionsEvaluation.tripple1) return BothPlayerEvaluation.tripple1_attacking;
if (attacker <= FourDirectionsEvaluation.double1) return BothPlayerEvaluation.double1_attacking;
if (defender <= FourDirectionsEvaluation.tripple1) return BothPlayerEvaluation.tripple1_defending;
if (defender <= FourDirectionsEvaluation.double1) return BothPlayerEvaluation.double1_defending;
if (attacker <= FourDirectionsEvaluation.o1 && defender <= FourDirectionsEvaluation.o1) return BothPlayerEvaluation.o1_both;
if (attacker <= FourDirectionsEvaluation.o1p) return BothPlayerEvaluation.o1p_attacking;
if (attacker <= FourDirectionsEvaluation.o1) return BothPlayerEvaluation.o1_attacking;
if (defender <= FourDirectionsEvaluation.o1p) return BothPlayerEvaluation.o1p_defending;
if (defender <= FourDirectionsEvaluation.o1) return BothPlayerEvaluation.o1_defending;
return BothPlayerEvaluation.rest;
}
public BothData Modify(int square, FourDirectionsEvaluation evaluationBlack, FourDirectionsEvaluation evaluationWhite)
{
// get hash code
int hash = (int)evaluationBlack << 5 | (int)evaluationWhite;
//test if something changed
BothData actualData = bothData[square];
if (actualData.hash == hash) return actualData;
actualData.hash = hash;
actualData.evaluationBlackOnMove = lookupTableBlack[hash];
actualData.evaluationWhiteOnMove = lookupTableWhite[hash];
return actualData;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using ServicesLibrary.Models;
namespace ServicesLibrary.Helpers
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<LocalDto> Locals { get; set; }
public DbSet<ServiceDto> Services { get; set; }
public DbSet<StoreDto> Stores { get; set; }
public DbSet<BusinessDto> Business { get; set; }
public DbSet<CityDto> Cities { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsultingManager.Dto
{
public class UserDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public Guid UserTypeId { get; set; }
public UserTypeDto UserType { get; set; }
public Guid? CustomerId { get; set; }
}
}
|
using Assets.Scripts.Units;
using UnityEngine;
namespace Assets.Scripts.Selection
{
public interface ISelectable
{
string Name { get; }
IDestroyable Destroyable { get; }
void InteractWithMapPoint(Vector3 point, bool force = false);
void InteractWithObject(IInteractableObject interactable, bool force = false);
void CancelActionPrepare();
void SetSelected(bool selected);
}
} |
/** MIT LICENSE
* Copyright (c) 2017 Koudura Ninci @True.Inc
*
* 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.
*
***/
using System;
using System.Diagnostics;
using System.Text;
namespace Fornax.Net.Util.Collections
{
/// <summary>
/// Functions for manipulation of Arrays
/// </summary>
public static class Arrays
{
/// <summary>
/// Maximum length for an array; set to a bit less than <see cref="int.MaxValue"/>.
/// </summary>
public static readonly int MaxLength = int.MaxValue - 256;
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="characters"></param>
/// <returns></returns>
public static string ValueOf<T>(T[] characters) where T : struct {
if (characters == null) throw new ArgumentNullException(nameof(characters));
StringBuilder value = new StringBuilder(characters.Length);
for (int i = 0; i < characters.Length; i++) {
value.Append(value: characters);
}
return value.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="characters"></param>
/// <returns></returns>
public static string ValueOf(object[] characters) {
if (characters == null) throw new ArgumentNullException(nameof(characters));
StringBuilder value = new StringBuilder(characters.Length);
for (int i = 0; i < characters.Length; i++) {
value.Append(value: characters);
}
return value.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="sourceString"></param>
/// <param name="sourceStart"></param>
/// <param name="sourceEnd"></param>
/// <param name="destination"></param>
/// <param name="destinationStart"></param>
/// <returns></returns>
public static bool CopyInTo(string sourceString, int sourceStart, int sourceEnd, ref char[] destination, int destinationStart) {
try {
int sourceCounte = sourceStart;
int destcounter = destinationStart;
while (sourceCounte < sourceEnd) {
destination[destcounter] = sourceString[sourceCounte];
sourceCounte++;
destcounter++;
}
return true;
} catch (ArgumentNullException) { return false; }
}
/// <summary>
///
/// </summary>
/// <param name="chars"></param>
/// <returns></returns>
public static int ParseInt32(char[] chars) {
return ParseInt32(chars, 0, chars.Length, 10);
}
/// <summary>
///
/// </summary>
/// <param name="chars"></param>
/// <param name="offset"></param>
/// <param name="len"></param>
/// <returns></returns>
public static int ParseInt32(char[] chars, int offset, int len) {
return ParseInt32(chars, offset, len, 10);
}
/// <summary>
///
/// </summary>
/// <param name="chars"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <param name="radix"></param>
/// <returns></returns>
public static int ParseInt32(char[] chars, int offset, int length, int radix) {
int minRadix = 2, maxRadix = 36;
if (chars == null || radix < minRadix || radix > maxRadix) throw new FormatException();
int i = 0;
if (length == 0) throw new FormatException($"Length of {nameof(chars)} is 0");
bool negate = chars[offset + 1] == '-';
if (negate && (++i == length)) throw new FormatException($"Cannot convert {nameof(chars)} to an Integer.");
if (negate) { offset++; length--; }
return Parse(chars, offset, length, radix, negate);
}
private static int Parse(char[] chars, int offset, int length, int radix, bool negate) {
int max = int.MinValue / radix;
int result = 0;
for (int i = 0; i < length; i++) {
int digit = (int)Char.GetNumericValue(chars[i + offset]);
if (digit == -1) throw new FormatException($"Unable to parse {nameof(chars)}.");
if (max > result) throw new FormatException($"Unable to parse {nameof(chars)}.");
int next = result * radix - digit;
if (next > result) throw new FormatException($"Unable to parse {nameof(chars)}.");
result = next;
}
if (!negate) {
result = -result;
if (result < 0) throw new FormatException($"Unable to parse {nameof(chars)}.");
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="currentSize"></param>
/// <param name="targetSize"></param>
/// <param name="bytesPerElement"></param>
/// <returns></returns>
public static int GetShrinkSize(int currentSize, int targetSize, int bytesPerElement) {
int newSize = Oversize(targetSize, bytesPerElement);
return (newSize < currentSize / 2) ? newSize : currentSize;
}
/// <summary>
///
/// </summary>
/// <param name="minTargetSize"></param>
/// <param name="bytesPerElement"></param>
/// <returns></returns>
public static int Oversize(int minTargetSize, int bytesPerElement) {
if (minTargetSize < 0) {
// catch usage that accidentally overflows int
throw new ArgumentException("invalid array size " + minTargetSize);
}
if (minTargetSize == 0) {
// wait until at least one element is requested
return 0;
}
// asymptotic exponential growth by 1/8th, favors
// spending a bit more CPU to not tie up too much wasted
// RAM:
int extra = minTargetSize >> 3;
if (extra < 3) {
// for very small arrays, where constant overhead of
// realloc is presumably relatively high, we grow
// faster
extra = 3;
}
int newSize = minTargetSize + extra;
// add 7 to allow for worst case byte alignment addition below:
if (newSize + 7 < 0) {
// int overflowed -- return max allowed array size
return int.MaxValue;
}
// round up to 8 byte alignment in 64bit env
switch (bytesPerElement) {
case 4:
// round up to multiple of 2
return (newSize + 1) & 0x7ffffffe;
case 2:
// round up to multiple of 4
return (newSize + 3) & 0x7ffffffc;
case 1:
// round up to multiple of 8
return (newSize + 7) & 0x7ffffff8;
case 8:
// no rounding
default:
// odd (invalid?) size
return newSize;
}
}
public static short[] Grow(short[] array) {
return Grow(array, 1 + array.Length);
}
public static float[] Grow(float[] array ,int minSize) {
Debug.Assert(minSize >= 0, $"size {nameof(minSize)} = {minSize} must be positive : likely Integer Overflow? ");
if(array.Length < minSize) {
float[] newArray = new float[Oversize(minSize, 4)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
}
return array;
}
public static short[] Grow(short[] array, int minSize) {
Debug.Assert(minSize >= 0, $"size {nameof(minSize)} = {minSize} must be positive : likely Integer Overflow? ");
if (array.Length < minSize) {
short[] newArray = new short[Oversize(minSize, 2)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
} else {
return array;
}
}
public static double[] Grow(double[] array, int minSize) {
Debug.Assert(minSize >= 0, $"size {nameof(minSize)} = {minSize} must be positive : likely Integer Overflow? ");
if (array.Length < minSize) {
double[] newArray = new double[Oversize(minSize, 8)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
} else {
return array;
}
}
public static double[] Grow(double[] array) {
return Grow(array, 1 + array.Length);
}
public static short[] Shrink(short[] array, int targetSize) {
Debug.Assert(targetSize >= 0, $"size {nameof(targetSize)} = {targetSize} must be positive : likely Integer Overflow? ");
int newSize = GetShrinkSize(array.Length, targetSize,2);
if (newSize != array.Length) {
short[] newArray = new short[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
} else {
return array;
}
}
public static int[] Grow(int[] array, int minSize) {
Debug.Assert(minSize >= 0, $"size {nameof(minSize)} = {minSize} must be positive : likely Integer Overflow? ");
if (array.Length < minSize) {
int[] newArray = new int[Oversize(minSize,4)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
} else {
return array;
}
}
public static int[] Grow(int[] array) {
return Grow(array, 1 + array.Length);
}
public static int[] Shrink(int[] array, int targetSize) {
Debug.Assert(targetSize >= 0, $"size {nameof(targetSize)} = {targetSize} must be positive : likely Integer Overflow? ");
int newSize = GetShrinkSize(array.Length, targetSize, 4);
if (newSize != array.Length) {
int[] newArray = new int[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
} else {
return array;
}
}
public static long[] Grow(long[] array, int minSize) {
Debug.Assert(minSize >= 0, $"size {nameof(minSize)} = {minSize} must be positive : likely Integer Overflow? ");
if (array.Length < minSize) {
long[] newArray = new long[Oversize(minSize, 8)];
Array.Copy(array, 0, newArray, 0, array.Length);
return newArray;
} else {
return array;
}
}
public static long[] Grow(long[] array) {
return Grow(array, 1 + array.Length);
}
public static long[] Shrink(long[] array, int targetSize) {
Debug.Assert(targetSize >= 0, "size must be positive (got " + targetSize + "): likely integer overflow?");
int newSize = GetShrinkSize(array.Length, targetSize, 8);
if (newSize != array.Length) {
long[] newArray = new long[newSize];
Array.Copy(array, 0, newArray, 0, newSize);
return newArray;
} else {
return array;
}
}
}
}
|
using Prototype.NetworkLobby;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
public class LobbyMan : LobbyManager {
public override void OnServerSceneChanged(string sceneName)
{
if (sceneName == playScene)
{
Orientation[] orientations = FindObjectOfType<GameManager>().orientations;
int orientationIndex = Random.Range(0, orientations.Length);
Orientation selectedOrientation = orientations[orientationIndex];
GameObject obj = Instantiate(selectedOrientation.gameObject);
obj.SetActive(true);
NetworkServer.Spawn(obj);
base.OnServerSceneChanged(sceneName);
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using System;
namespace NMoSql
{
public static class NMoSqlExtensions
{
/// <summary>
/// Registers the default NMoSql services in the DI container.
/// </summary>
/// <param name="services">The services collection.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddNMoSql(this IServiceCollection services)
{
if (services == null)
throw new ArgumentNullException(nameof(services));
return services.AddSingleton<IQueryBuilder, QueryBuilder>()
.AddQueryTypes()
.AddQueryHelpers()
.AddConditionalHelpers();
}
/// <summary>
/// Registers the NMoSql helpers.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <returns>The <see cref="IServiceProvider"/>.</returns>
public static IServiceProvider UseNMoSql(this IServiceProvider serviceProvider)
{
if (serviceProvider == null)
throw new ArgumentNullException(nameof(serviceProvider));
return serviceProvider
.UseQueryTypes()
.UseQueryHelpers()
.UseConditionalHelpers();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
public class CharacterInformationUIController : MonoBehaviour
{
public CanvasGroup CharacterInformationPanel;
public Text NameAgeText;
public Text LocationText;
public Text TitleText;
public Text SkillPRGText;
public Text SkillUIXText;
public Text SkillDBSText;
public Text SkillNTWText;
public Text SkillWEBText;
public CharacterAvatar CharacterAvatar;
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
CloseCharacterInformationForm();
}
public void OpenCharacterInformationForm()
{
NameAgeText.text = string.Format("{0} ({1})",
Character.MyCharacter.Name, Character.MyCharacter.Age);
LocationText.text = Character.MyCharacter.CurrentLocation.Name;
TitleText.text = Company.MyCompany == null
? "Freelancer"
: string.Format("Founder of {0}", Company.MyCompany.Name);
SkillPRGText.text = Character.MyCharacter.Skills[Skill.Programming].Level.ToString();
SkillUIXText.text = Character.MyCharacter.Skills[Skill.UserInterfaces].Level.ToString();
SkillDBSText.text = Character.MyCharacter.Skills[Skill.Databases].Level.ToString();
SkillNTWText.text = Character.MyCharacter.Skills[Skill.Networking].Level.ToString();
SkillWEBText.text = Character.MyCharacter.Skills[Skill.WebDevelopment].Level.ToString();
CharacterAvatar.LoadAvatar(Character.MyCharacter);
SDTUIController.Instance.OpenCanvas(CharacterInformationPanel, false, false);
}
public void CloseCharacterInformationForm()
{
SDTUIController.Instance.CloseCanvas(CharacterInformationPanel);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test3enums
{
class eprac
{
#below two new lists that are made of strings are created for the naughty and nice list
List<string> behaviors;
List<string> behaviors2;
public eprac()
{
# behaviors and behaviors2 are assinged to the new lists
behaviors = new List<string>();
behaviors2 = new List<string>();
}
public void NaughtyNice(categories jak) #method for the adding names to each of the lists
{
if (jak == categories.nice)# if the user choice is nice code runs a try catch to add names to the nice list
{
Console.WriteLine("Add names to the nice list:"); #prints statement to the console for user to add names
try
{
string nice = Console.ReadLine();#uses the enums from categories as a string
behaviors.Add(nice); #adds the user input to the nice list
}
catch
{
Console.WriteLine("Enter in something valid"); #runs in case the user input is invalid
}
}
if (jak == categories.naughty) # if the user choice is naughty, code runs a try catch to add names to the naughty list
{
Console.WriteLine("Add names to the naughty list:");
try
{
string naughty = Console.ReadLine(); #uses the enums from categories as a string
behaviors2.Add(naughty);#adds the user input to the naughty list
}
catch
{
Console.WriteLine("Enter in something valid");#runs in case the user input is invalid
}
}
}
public void ShowNiceKids() #method for showing the strings in the nice list
{
foreach(string nice in behaviors) #loops through the list using foreach
{
Console.Write($"{nice}"); #writes out each of the string to the console
}
}
public void ShowNauhghtyKids()#method for showing the strings in the naughty list
{
foreach(string naughty in behaviors2 )#loops through the list using foreach
{
Console.Write($"{naughty}");#writes out each of the string to the console
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HardwareInventoryManager;
using HardwareInventoryManager.Models;
using HardwareInventoryManager.HIResources;
using HardwareInventoryManager.Filters;
namespace HardwareInventoryManager.Controllers
{
[CustomAuthorize]
public class LookupTypesController : AppController
{
private CustomApplicationDbContext db = new CustomApplicationDbContext();
// GET: LookupTypes
public ActionResult Index()
{
return View(db.LookupTypes.ToList());
}
// GET: LookupTypes/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LookupType lookupType = db.LookupTypes.Find(id);
if (lookupType == null)
{
return HttpNotFound();
}
return View(lookupType);
}
// GET: LookupTypes/Create
public ActionResult Create()
{
return View();
}
// POST: LookupTypes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "LookupTypeId,Description,CreatedDate,UpdatedDate")] LookupType lookupType)
{
if (ModelState.IsValid)
{
db.LookupTypes.Add(lookupType);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(lookupType);
}
// GET: LookupTypes/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LookupType lookupType = db.LookupTypes.Find(id);
if (lookupType == null)
{
return HttpNotFound();
}
return View(lookupType);
}
// POST: LookupTypes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "LookupTypeId,Description,CreatedDate,UpdatedDate")] LookupType lookupType)
{
if (ModelState.IsValid)
{
db.Entry(lookupType).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(lookupType);
}
// GET: LookupTypes/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LookupType lookupType = db.LookupTypes.Find(id);
if (lookupType == null)
{
return HttpNotFound();
}
return View(lookupType);
}
// POST: LookupTypes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
try
{
LookupType lookupType = db.LookupTypes.Find(id);
db.LookupTypes.Remove(lookupType);
db.SaveChanges();
Alert(Helpers.EnumHelper.Alerts.Success, Strings.Change_Success);
}
catch(System.Data.Entity.Infrastructure.DbUpdateException)
{
Alert(Helpers.EnumHelper.Alerts.Error, Strings.Delete_Lookup_Type_Error);
}
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using FastSQL.Core;
using FastSQL.Sync.Core.Enums;
using FastSQL.Sync.Core.Models;
using System;
namespace FastSQL.Sync.Core.Pusher
{
public interface IPusher: IOptionManager, IDisposable
{
PushState Create(out string destinationId);
PushState Remove(string destinationId = null);
PushState Update(string destinationId = null);
string GetDestinationId();
IPusher OnReport(Action<string> reporter);
IPusher SetItem(IndexItemModel item);
IPusher SetIndex(IIndexModel model);
}
public interface IEntityPusher: IPusher
{
bool IsImplemented(string processorId, string providerId);
}
public interface IAttributePusher: IPusher
{
bool IsImplemented(string attributeProcessorId, string entityProcessorId, string providerId);
}
}
|
namespace DpiConverter.Presenters
{
using System;
using System.ComponentModel;
using System.Windows.Forms;
using Properties;
public partial class SettingsPresenter : Form
{
public SettingsPresenter()
{
this.InitializeComponent();
Settings.Default.PropertyChanged += new PropertyChangedEventHandler(this.EnableSaveButton);
this.inputFileValidationCheckBox.DataBindings.Add("Checked", Settings.Default, "ValidateInputFile", true, DataSourceUpdateMode.OnPropertyChanged);
this.exportBacksightObservationsCheckBox.DataBindings.Add("Checked", Settings.Default, "ExportBacksightObservations", true, DataSourceUpdateMode.OnPropertyChanged);
this.exportTraverseObservationsCheckBox.DataBindings.Add("Checked", Settings.Default, "ExportTraverseObservations", true, DataSourceUpdateMode.OnPropertyChanged);
this.exportSideshotObservationsCheckBox.DataBindings.Add("Checked", Settings.Default, "ExportSideshotObservations", true, DataSourceUpdateMode.OnPropertyChanged);
this.addPointOffsetCheckBox.DataBindings.Add("Checked", Settings.Default, "AddOffsetToSideshotPoints", true, DataSourceUpdateMode.OnPropertyChanged);
this.pointOffsetTextBox.DataBindings.Add("Text", Settings.Default, "SideshotPointNumberOffset", true, DataSourceUpdateMode.OnPropertyChanged);
this.usePredefinedCodesCheckBox.DataBindings.Add("Checked", Settings.Default, "UsePredefinedPointCodes", true, DataSourceUpdateMode.OnPropertyChanged);
}
private void CloseForm(object sender, EventArgs e)
{
this.Close();
}
private void AddOffsetToSideshotPointsState(object sender, EventArgs e)
{
this.pointOffsetTextBox.ReadOnly = this.addPointOffsetCheckBox.Checked ? false : true;
}
private void EnableSaveButton(object sender, PropertyChangedEventArgs e)
{
this.saveSettingsButton.Enabled = true;
}
private void SaveSettings(object sender, EventArgs e)
{
Properties.Settings.Default.Save();
this.saveSettingsButton.Enabled = false;
}
}
}
|
using NewMediaRave.Models;
using NewMediaRave.ViewModels;
using NewMediaRave.Views.Menu;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
/*
Note: Most of our code comes from a tutorial put together by YouTube creator, Bert Bosch. --K
Citation: APA format
Bosch, B. (Creator). (2017, December 31). Xamarin tutorials [Video playlist]. Retrieved February 26, 2021, from
https://www.youtube.com/playlist?list=PLV916idiqLvcKS1JY3S3jHWx9ELGJ1cJB
*/
namespace NewMediaRave.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
StyleColors();
this.BindingContext = new LoginViewModel();
}
void StyleColors() //references colors contained in the Constants class. --K
{
BackgroundColor = Constants.BackdropColor;
Lbl_UserName.TextColor = Constants.MainTextColor;
Lbl_Password.TextColor = Constants.MainTextColor;
Btn_Signin.BackgroundColor = Constants.ButtonColor;
App.StartCheckIfInternet(lbl_NoInternet, this);
}
async Task SignInProcedure(object sender, EventArgs e)
{
User user = new User(Entry_Username.Text, Entry_Password.Text);
if (user.CheckInformation())
{
DisplayAlert("Login", "Success!", "Okay");
var result = await App.RestService.Login(user);
//dummy token
if (result != null)
{
// login page to dashboard
await Navigation.PushAsync(new Dashboard());
if (Device.OS == TargetPlatform.Android)
{
Application.Current.MainPage = new NavigationPage(new Dashboard());
}
else if (Device.OS == TargetPlatform.iOS)
{
await Navigation.PushModalAsync(new NavigationPage(new Dashboard()));
}
}
}
else
{
DisplayAlert("Login", "Error: Please enter a username and password.", "Okay");
}
}
}
} |
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Waffles
{
public partial class WBrowser : UserControls.Generic
{
public string icons_count = "0 icons", javascript_variables = "";
public override void Build()
{
WContext.Current.StyleSheetAdd("FontAwesome");
WContext.Current.StyleSheetAdd("Bootstrap");
WContext.Current.AdminDisable = true;
string[] selected_icons =
WContext.Current.REQUEST.ContainsKey("selected") && WContext.Current.REQUEST["selected"] != "none" ?
WContext.Current.REQUEST["selected"].Split(',') :
new string[0];
if (selected_icons.Length > 0)
{
string iconsHTML = IconsLiteral.Text;
foreach (string selected_icon in selected_icons)
iconsHTML = iconsHTML.Replace(
"data-icon=\"" + selected_icon + "\"",
"data-icon=\"" + selected_icon + "\" class=\"selected\""
);
IconsLiteral.Text = iconsHTML;
icons_count = selected_icons.Length + " icon" + (selected_icons.Length != 1 ? "s" : "");
}
javascript_variables = "var selected_icons = " +
WContext.JSONSerialize(selected_icons) + ", fieldID = '" +
WContext.Current.REQUEST["field"] + "';";
WContext.Current.JavaScriptAdd("WIcons", JavaScriptLiteral.Text.ToString(), null, "jQuery");
JavaScriptLiteral.Text = "";
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Beamore.DAL.Contents.Models
{
[Table("SurvayOptionTable")]
public class SurvayOption : BaseModel
{
public string Option { get; set; }
public int NumberOfSelected { get; set; }
public int SurvayId { get; set; }
[ForeignKey("SurvayId")]
public virtual Survay Survay { get; set; }
}
}
|
using LightwaveRFLinkPlusSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightwaveDaemon
{
internal static class DeviceNameExtensions
{
public static string ToRealName(this DeviceName deviceName)
{
return Configuration.DeviceRealNameLookup[deviceName];
}
public static Device ToDevice(this DeviceName deviceName, Device[] devices)
{
string realDeviceName = deviceName.ToRealName();
return devices.Single(x => x.Name == realDeviceName);
}
}
}
|
using Logs.Authentication.Managers;
using Logs.Models;
using Logs.Providers.Contracts;
using Microsoft.AspNet.Identity;
using Moq;
using NUnit.Framework;
namespace Logs.Authentication.Tests.AuthenticationProviderTests
{
[TestFixture]
public class RemoveFromRoleTests
{
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", "user")]
[TestCase("99ae8dd3-1067-4141-9675-62e94bb6caaa", "admin")]
public void TestRemoveFromRole_ShouldCallUserManagerRemoveFromRole(string userId, string role)
{
// Arrange
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedUserStore = new Mock<IUserStore<User>>();
var mockedUserManager = new Mock<ApplicationUserManager>(mockedUserStore.Object);
var mockedHttpContextProvider = new Mock<IHttpContextProvider>();
mockedHttpContextProvider.Setup(p => p.GetUserManager<ApplicationUserManager>()).Returns(mockedUserManager.Object);
var provider = new AuthenticationProvider(mockedDateTimeProvider.Object, mockedHttpContextProvider.Object);
// Act
provider.RemoveFromRole(userId, role);
// Assert
mockedUserManager.Verify(m => m.RemoveFromRoleAsync(userId, role), Times.Once);
}
}
}
|
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
namespace Diyseed.Core
{
public class WriterGenerator
{
private PdfDocument document;
private int currentPageNumber;
private XGraphics gfx;
private GeneratorParameters parameters;
public WriterGenerator(GeneratorParameters parameters)
{
this.parameters = parameters;
}
public PdfDocument Generate()
{
document = new PdfDocument();
currentPageNumber = 0;
for (int i = 1; i <= parameters.Copies; i++)
{
RenderSet(i);
}
gfx?.Dispose();
return document;
}
public void RenderSet(int set)
{
for (int i = 1; i <= parameters.EffectiveCardCount; i++)
{
var origin = GetOriginForCard(i + (set - 1) * parameters.EffectiveCardCount, GetCardSafeAreaSize(parameters.CardSize));
if (origin.Item1 > currentPageNumber)
{
AddPage();
}
var state = gfx.Save();
gfx.TranslateTransform(origin.Item2.X, origin.Item2.Y);
RenderCard(parameters.GetCardParameters(i));
gfx.Restore(state);
}
}
public XSize GetCardSafeAreaSize(XSize sizeOfCard)
{
return new XSize(sizeOfCard.Width + Configuration.CARD_MARGIN, sizeOfCard.Height + Configuration.CARD_MARGIN);
}
private (int, XPoint) GetOriginForCard(int cardNumber, XSize sizeOfCard)
{
int cardsPerLine = (int)((Configuration.EFFECTIVE_PAGE_SIZE.Width + Configuration.CARD_MARGIN) / sizeOfCard.Width);
int linesPerPage = (int)((Configuration.EFFECTIVE_PAGE_SIZE.Height + Configuration.CARD_MARGIN) / sizeOfCard.Height);
int cardsPerPage = cardsPerLine * linesPerPage;
int page = ((cardNumber - 1) / cardsPerPage) + 1;
int numberOnPage = ((cardNumber - 1) % cardsPerPage) + 1;
int lineOnPage = ((numberOnPage - 1) / cardsPerLine) + 1;
int numberOnLine = ((numberOnPage - 1) % cardsPerLine) + 1;
var positionX = sizeOfCard.Width * (numberOnLine - 1);
var positionY = sizeOfCard.Height * (lineOnPage - 1);
var point = new XPoint(positionX, positionY);
return (page, point);
}
private void AddPage()
{
var page = document.AddPage();
page.Size = Configuration.DOCUMENT_FORMAT;
//
currentPageNumber++;
//
gfx?.Dispose();
gfx = XGraphics.FromPdfPage(page);
gfx.TranslateTransform(Configuration.DOCUMENT_MARGIN_H, Configuration.DOCUMENT_MARGIN_TOP);
}
public void RenderCard(CardParameters card)
{
DrawCardOutline(card);
gfx.TranslateTransform(card.Padding, card.Padding);
foreach (var section in card.Sections)
{
var sectionSize = DrawSection(section);
gfx.TranslateTransform(0, sectionSize.Height);
}
}
private void DrawCardOutline(CardParameters card)
{
XRect rect = new XRect(card.Size);
var ellipseSize = new XSize(card.Radius * 2, card.Radius * 2);
gfx.DrawRoundedRectangle(Configuration.DOCUMENT_PEN_NORMAL, rect, ellipseSize);
}
private XSize DrawSection(CardSectionParameters section)
{
DrawWords(section);
return section.Size;
}
public void DrawWords(CardSectionParameters section)
{
var state = gfx.Save();
var i = 0;
foreach (var wordNumber in section.WordNumbers)
{
//iterate over section words
if ((section.Number + i) % 2 == 0)
{
//draw shadow if it is odd word
DrawShadow(section.WordSize);
}
DrawWordOutline(section.WordSize);
DrawWordNumber(section.WordSize, wordNumber);
DrawWordHorizontalLines(section.WordSize, section.CellSize, section.Encoding);
DrawWordVerticalLines(section.WordSize, section.CellSize);
DrawWordCellCharacters(section.CellSize, section.Encoding);
gfx.TranslateTransform(section.WordSize.Width, 0);
i++;
}
gfx.Restore(state);
}
private void DrawWordOutline(XSize size)
{
var rect = new XRect(size);
gfx.DrawRectangle(Configuration.DOCUMENT_PEN_NORMAL, rect);
}
private void DrawShadow(XSize size)
{
var rect = new XRect(size);
gfx.DrawRectangle(null, Configuration.WORD_CELL_SHADE_BRUSH, rect);
}
private void DrawWordNumber(XSize size, int number)
{
var font = gfx.GetFontForBox(
fontName: Configuration.DOCUMENT_FONT_FAMILY,
style: Configuration.WORD_NR_FONT_STYLE,
fontSizeRange: Configuration.WORD_NR_FONT_SIZE_RANGE,
increaseStep: 1,
sampleText: "42.",
maxSize: size);
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Center;
format.LineAlignment = XLineAlignment.Near;
XRect rect = new XRect(size);
gfx.DrawString(number.ToString(), font, Configuration.WORD_NR_FONT_BRUSH, rect, format);
}
private void DrawWordHorizontalLines(XSize size, XSize cellSize, EncodingType encoding)
{
var state = gfx.Save();
XUnit x1 = 0;
XUnit x2 = size.Width;
XUnit y12 = cellSize.Height;
for (int row = 1; row < (int)encoding; row++)
{
//iterate over word lines
gfx.DrawLine(Configuration.DOCUMENT_PEN_THIN, x1, y12, x2, y12);
y12 += cellSize.Height;
}
gfx.Restore(state);
}
private void DrawWordVerticalLines(XSize size, XSize cellSize)
{
var state = gfx.Save();
XUnit x12 = cellSize.Width;
XUnit y1 = 0;
XUnit y2 = size.Height;
for (int row = 1; row < 4; row++)
{
//iterate over word lines
gfx.DrawLine(Configuration.DOCUMENT_PEN_THIN, x12, y1, x12, y2);
x12 += cellSize.Width;
}
gfx.Restore(state);
}
private void DrawWordCellCharacters(XSize cellSize, EncodingType encoding)
{
var state = gfx.Save();
var currentChar = encoding == EncodingType.Alphabet ? 'a' : '0';
for (int i = 0; i < (int)encoding; i++)
{
DrawLineCells($"{currentChar++}");
gfx.TranslateTransform(0, cellSize.Height);
}
void DrawLineCells(string text)
{
var state = gfx.Save();
var font = gfx.GetFontForBox(
fontName: Configuration.DOCUMENT_FONT_FAMILY,
style: Configuration.CELL_FONT_STYLE,
fontSizeRange: Configuration.CELL_FONT_SIZE_RANGE,
increaseStep: 0.2,
sampleText: "M",
maxSize: parameters.CellSize);
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Center;
format.LineAlignment = XLineAlignment.Center;
for (int cell = 0; cell < 4; cell++)
{
var rect = new XRect(cellSize);
gfx.DrawString(text, font, Configuration.CELL_FONT_BRUSH, rect, format);
gfx.TranslateTransform(cellSize.Width, 0);
}
gfx.Restore(state);
}
gfx.Restore(state);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonsInLobby : MonoBehaviour
{
public static ButtonsInLobby instance;
[SerializeField]
private Text txtGold;
[Header("Create Table")]
public GameObject createTable;
public Text txtTableOwner;
public Toggle togTwoPlayer;
public Toggle togFourPlayer;
public Slider slider;
public Image light10K;
public Image light20K;
public Image light50K;
public Image light100K;
private long betLevel = Parameters.Bet10K;
public Image avatar;
public Sprite[] listAvar;
private void Awake()
{
instance = this;
}
private void Start()
{
light10K.color = Color.white;
}
public void ProcessToggle()
{
if (slider.value > 10 && slider.value < 25)
{
//Bật ligh10
BrightLights(Color.white, Color.black, Color.black, Color.black);
slider.value = 10;
betLevel = Parameters.Bet10K;
}
if (slider.value > 25 && slider.value < 55)
{
//Bật ligh20
BrightLights(Color.black, Color.white, Color.black, Color.black);
slider.value = 40;
betLevel = Parameters.Bet20K;
}
if (slider.value >= 55 && slider.value < 85)
{
//Bật ligh50
BrightLights(Color.black, Color.black, Color.white, Color.black);
slider.value = 70;
betLevel = Parameters.Bet50K;
}
if (slider.value >= 85)
{
//Bật ligh100
BrightLights(Color.black, Color.black, Color.black, Color.white);
slider.value = 100;
betLevel = Parameters.Bet100K;
}
}
private void BrightLights(Color light10, Color light20, Color light50, Color light100)
{
light10K.color = light10;
light20K.color = light20;
light50K.color = light50;
light100K.color = light100;
}
public void ShowGold(string gold)
{
txtGold.text = gold;
}
public void ShowCreateTable()
{
createTable.SetActive(true);
txtTableOwner.text = UserProfile.Instance.NickName;
}
public void ClickPlayNow()
{
LobbyManager.instance.RequestJoinRoomRandom();
}
public void HideCreateTable()
{
createTable.SetActive(false);
}
public long GetBetLevel()
{
return betLevel;
}
public string GetTableOwner()
{
return UserProfile.Instance.UserName;
}
public int GetMaxPlayerOfRoom()
{
if (togFourPlayer.isOn)
{
return 4;
}
return 2;
}
public void UpdateAvatar(int id)
{
var sprite = listAvar[id];
avatar.sprite = sprite;
}
}
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Json
{
/// <summary>
/// Класс, содержащий данные о человеке.
/// </summary>
class Person
{
/// <summary>
/// Имя.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Фамилия.
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Возраст.
/// </summary>
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Создаём JSON объект и добавляем ему свойства в виде пары ключ-значение.
var jObj = new JObject();
jObj.Add("name", "Ivan Ivanov");
jObj.Add("age", 18);
// Создаём JSON массив и добавляем элементы массива.
var jArray = new JArray();
jArray.Add("Nikolay");
jArray.Add("Fedor");
// Добавляем массив как свойство объека.
jObj.Add("childs", jArray);
// Печатаем полученный результат.
Console.WriteLine(jObj.ToString());
Console.WriteLine();
// Разбор входной JSON строки.
var parsedObj = JObject.Parse("{\"manufacturer\": \"BMW\", \"model\": \"X5\"}");
// Печать результата.
Console.WriteLine($"Manufacturer: {parsedObj.GetValue("manufacturer")}, Model: {parsedObj.GetValue("model")}");
Console.WriteLine();
// Создаём коллекцию с данными о некоторых людях.
var persons = new List<Person>
{
new Person { FirstName = "Ivan", LastName = "Ivanov", Age = 40 },
new Person { FirstName = "Andrey", LastName = "Ivanov", Age = 18 },
new Person { FirstName = "Zahar", LastName = "Plushkin", Age = 22 },
new Person { FirstName = "Alexey", LastName = "Petrov", Age = 36 },
};
// Сериализуем и печатаем первый элемент списка.
Console.WriteLine(JsonConvert.SerializeObject(persons[0]));
Console.WriteLine();
// Сериализуем и печатаем всю коллекцию.
Console.WriteLine(JsonConvert.SerializeObject(persons));
Console.WriteLine();
// Сначала сериализуем объект в JSON строку.
var personJson = JsonConvert.SerializeObject(persons[1]);
// Затем преобразуем строку в объект.
var personObj = JsonConvert.DeserializeObject<Person>(personJson);
// Убеждаемся, что получили объект с такими же значениями свойств.
if (persons[1].FirstName == personObj.FirstName &&
persons[1].LastName == personObj.LastName &&
persons[1].Age == personObj.Age)
{
Console.WriteLine("Persons are equal!");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class ObjectSpline: MonoBehaviour
{
[SerializeField]
private BezierSpline spline;
[SerializeField,Range(3,100)]
private int frequency = 3;
[Space(10)]
[SerializeField]
private Transform start;
[SerializeField]
private Transform mid_1;
[SerializeField]
private Transform mid_2;
[SerializeField]
private Transform end;
public List<Transform> objects;
public bool update;
#if UNITY_EDITOR
private void OnEnable()
{
UpdateObjects();
}
private void Update()
{
UpdateObjects();
}
#endif
private void UpdateObjects()
{
if (spline)
{
if (objects.Count != frequency + 1 || update)
{
update = false;
for (int i = 0; i < objects.Count; i++)
if (objects[i]) DestroyImmediate(objects[i].gameObject);
objects = new List<Transform>();
for (int i = 0; i < frequency + 1; i++)
objects.Add(null);
if (!spline.Loop)
{
setUpObject(Instantiate(start), 0);
setUpObject(Instantiate(end), frequency);
for (int i = 1; i < objects.Count - 1; i++)
setUpObject(Instantiate(mid_1), Instantiate(mid_2), i);
}
else
{
for (int i = 0; i < objects.Count; i++)
setUpObject(Instantiate(mid_1), Instantiate(mid_2), i);
}
}
}
}
private void setUpObject(Transform obj, int index)
{
Vector3 position = spline.GetPoint((float)index / frequency);
obj.transform.position = position;
obj.transform.LookAt(position + spline.GetDirection(index / frequency));
obj.transform.parent = transform;
objects[index] = obj;
}
private void setUpObject(Transform obj1, Transform obj2, int index)
{
Vector3 position = spline.GetPoint((float)index / frequency);
obj1.transform.position = position;
obj1.transform.LookAt(position + spline.GetDirection(index / frequency));
obj1.transform.parent = transform;
objects[index] = obj1;
obj2.transform.position = position;
obj2.transform.LookAt(position - spline.GetDirection(index / frequency));
obj2.transform.parent = obj1;
}
}
|
namespace Methods
{
using System;
public class ArrayExtensions
{
public static T FindMax<T>(params T[] elements)
where T : IComparable
{
if (elements == null || elements.Length == 0)
{
throw new ArgumentException("Input is empty!");
}
for (int i = 1; i < elements.Length; i++)
{
if (elements[i].CompareTo(elements[0]) > 0)
{
elements[0] = elements[i];
}
}
return elements[0];
}
}
} |
using mTransport.Methodes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mTransport.Models
{
public partial class Depense: ICRUD
{
public string Designation
{
get
{
return TypeDepense.Designation;
}
}
public string Panne
{
get
{
return HistoriquePanne.Description;
}
}
public string UnVoyage
{
get
{
return Voyage.Designation;
}
}
public void Insert()
{
using (DB db = new DB())
{
db.Depenses.Add(this);
db.SaveChanges();
}
}
public void Update()
{
using (DB db = new DB())
{
db.Entry(this).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
//Méthode ne necessitant pas la création d'un objet est a déclarée static
public static List<Depense> getAll(int id, string value)
{
switch (value)
{
case "v": //Voyage
using (DB db = new DB())
{
var l = db.Depenses.Where(i => i.Supprime == false).ToList();
//On récupère la liste des dépenses liées au véhicule
var m = l.Where(i => i.IdVoyage == id).ToList();
foreach (var item in m)
{
item.TypeDepense = TypeDepense.getTypeDepense(item.IdTypeDepense);
item.Voyage = Voyage.getVoyage(item.IdVoyage.Value);
}
return m;
}
//break;
case "h": //Historique panne
using (DB db = new DB())
{
var l = db.Depenses.Where(i => i.Supprime == false).ToList();
//On récupère la liste des dépenses liées au matériel
var m = l.Where(i => i.IdHistoriquePanne == id).ToList();
foreach (var item in m)
{
item.HistoriquePanne = HistoriquePanne.getHistoriquePanne(item.IdHistoriquePanne.Value);
item.TypeDepense = TypeDepense.getTypeDepense(item.IdTypeDepense);
item.Voyage = Voyage.getVoyage(item.IdVoyage.Value);
}
return m;
}
//break;
default:
break;
}
return null;
}
public static Depense getDepense(int Id)
{
using (DB db = new DB())
{
Depense c = new Depense();
c = db.Depenses.SingleOrDefault(i => i.Id == Id);
return c;
}
}
public void Delete()
{
Update();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DCDC_Manager
{
/// <summary>
/// Idicates type of power source
/// </summary>
public enum SourceType
{
/// <summary>
/// No source selected
/// </summary>
None,
/// <summary>
/// Battery selected
/// </summary>
Battery,
/// <summary>
/// Line selected
/// </summary>
Line
}
} |
using Caliburn.Micro;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GliderSchool
{
[ImplementPropertyChanged]
public class ViewModelBase : Screen, IActivate, IDeactivate
{
}
}
|
using UnityEngine;
using System.Collections;
public class StateHandler : MonoBehaviour {
public double idleTime;
public bool control;
double timer;
Animator anim;
MethodHandler methodHandler;
HitPointManager hitPointManager;
// Use this for initialization
void Start () {
timer = 0;
anim = GetComponent<Animator>();
methodHandler = GetComponent<MethodHandler>();
hitPointManager = GetComponent<HitPointManager>();
}
// Update is called once per frame
void Update () {
if (control && !hitPointManager.isDead() && anim.GetCurrentAnimatorStateInfo(0).IsName("idle")) // Idle
{
if (timer < idleTime)
{
timer += Time.deltaTime;
} else
{
timer = 0;
methodHandler.generateAttack();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Steamworks;
public class ResetAchivment : MonoBehaviour
{
// Update is called once per frame
void Update ()
{
// Todo: Dev Stuff
//if(Input.GetKeyDown(KeyCode.Space))
// {
// if (SteamManager.Initialized == true)
// {
// SteamUserStats.ResetAllStats(true);
// SteamUserStats.StoreStats();
// }
// }
}
}
|
using System;
namespace TechTalk.JiraRestClient
{
public class IssueRef
{
public string id { get; set; }
public string key { get; set; }
public string JiraIdentifier
{
get { return key; }
set { key = value; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using test1.DAL;
using test1.Interfaces.BLL;
using test1.Interfaces.DAL;
using test1.Models;
namespace test1.BLL
{
public class TraineeManager : ITraineeManager
{
private ITraineeRepository _repository;
public TraineeManager()
{
_repository = new TraineeRepository();
}
public bool Add(Trainee entity)
{
return _repository.Add(entity);
}
public bool Update(Trainee entity)
{
return _repository.Update(entity);
}
public bool Remove(Trainee entity)
{
return _repository.Remove(entity);
}
public Trainee GetById(int? id)
{
if (id == null)
{
return null;
}
return _repository.GetById((int)id);
}
public ICollection<Trainee> GetAll()
{
return _repository.GetAll();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace HotelWCF
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ServicioConsumo" in both code and config file together.
public class ServicioConsumo : IServicioConsumo
{
hotelproEntities1 MiHotel = new hotelproEntities1();
public bool ActualizarConsumoReserva(ConsumoBE objConsumoBE)
{
Boolean retorno = false;
try
{
//Buscamos Consumo en la base de datos
Consumo consumo = MiHotel.Consumo.Find(objConsumoBE.IdConsumo);
//Si encuentra consumo entra al if
if (consumo != null)
{
//asigna todo los datos nuestro objeto "ConsumoBE" a "Consumo" de la base de datos
consumo.id_Estado_Consumo = objConsumoBE.IdEstadoConsumo;
consumo.id_Producto = objConsumoBE.IdProducto;
consumo.Fecha = objConsumoBE.Fecha;
consumo.cantidad = objConsumoBE.Cantidad;
consumo.id_Reserva = objConsumoBE.IdReserva;
//Guardamos cambios
MiHotel.SaveChanges();
retorno = true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return retorno;
}
public bool InsertarConsumoReserva(ConsumoBE objConsumoBE)
{
Boolean retorno = false;
try
{
//creamos nueva instancia del objeto "Consumo" de la base de datos y se asigna los datos de nuetro objeto "ConsumoBE"
Consumo consumo = new Consumo();
consumo.id_Estado_Consumo = 1;
consumo.id_Producto = objConsumoBE.IdProducto;
consumo.Fecha = objConsumoBE.Fecha;
consumo.cantidad = objConsumoBE.Cantidad;
consumo.id_Reserva = objConsumoBE.IdReserva;
MiHotel.Consumo.Add(consumo);
MiHotel.SaveChanges();
retorno = true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return retorno;
}
public List<ConsumoBE> ListarConsumoReserva(short IdReserva)
{
//Creamos una lista de Consumos
List<ConsumoBE> objListaConsumo = new List<ConsumoBE>();
try
{
//Buscamos todos los consumo por el IdReserva que recibe como parametro
var query = (from c in MiHotel.Consumo
where c.id_Reserva == IdReserva
select c);
//Recorre el resultado
foreach (var resultado in query)
{
//Crea un nuevo objeto de nuestra clase "ConsumoBE" y agrega los datos del resultado
ConsumoBE objConsumoBE = new ConsumoBE();
objConsumoBE.IdConsumo = resultado.id_Consumo;
objConsumoBE.IdEstadoConsumo = resultado.id_Estado_Consumo;
objConsumoBE.DescripcionEstado = objConsumoBE.DevuelveDescripcionEstado(objConsumoBE.IdEstadoConsumo);
objConsumoBE.IdProducto = resultado.id_Producto;
objConsumoBE.Fecha = resultado.Fecha;
objConsumoBE.Cantidad = resultado.cantidad;
objConsumoBE.IdReserva = resultado.id_Reserva;
objListaConsumo.Add(objConsumoBE);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return objListaConsumo;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookSys.DataAccess;
using BookSys.Model;
namespace BookSys
{
public partial class Alterar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLimpar_Click(object sender, EventArgs e)
{
try
{
//limpa todos os TextBox
txtNome.Text = "";
txtAutor.Text = "";
txtEditora.Text = "";
txtGenero.Text = "";
txtLingua.Text = "";
txtPaginas.Text = "";
txtAno.Text = "";
txtEdicao.Text = "";
txtIsbn.Text = "";
}
catch (Exception)
{
throw;
}
}
protected void btnCadastrar_Click(object sender, EventArgs e)
{
try
{
Livro l = new Livro();//instancia de um novo livro
//obtem valores dos TextBox
l.Nome = txtNome.Text;
l.Autor = txtAutor.Text;
l.Editora = txtEditora.Text;
l.Genero = txtGenero.Text;
l.Lingua = txtLingua.Text;
l.Paginas = Convert.ToInt32(txtPaginas.Text);
l.Ano = Convert.ToInt32(txtAno.Text);
l.Edicao = Convert.ToInt32(txtEdicao.Text);
l.Isbn = Convert.ToInt32(txtIsbn.Text);
//grava no banco
LivroDAL d = new LivroDAL();
d.Alterar(l);
//mensagem de confirmação
lblMensagem.Text = "Livro Atualizado com Sucesso";
}
catch (Exception ex)
{
throw new Exception("Erro" + ex.Message);
}
}
}
} |
using strange.extensions.command.impl;
namespace Client.Commands
{
public class LoadGameDataCommand : Command
{
/// <summary>
/// Server connector service
/// </summary>
[Inject] public ServerConnectorService ServerConnectorService { get; set; }
/// <summary>
/// Execute
/// </summary>
public override void Execute()
{
ServerConnectorService.Connect();
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using ReadyGamerOne.Common;
using UnityEngine;
namespace ReadyGamerOne.Script
{
public class MessageToActive : MonoBehaviour
{
public bool defaultState = true;
public string messageToEnactive;
public string messageToDisactive;
// Start is called before the first frame update
private void Start()
{
gameObject.SetActive(defaultState);
}
private void Awake()
{
if(!string.IsNullOrEmpty(messageToDisactive))
CEventCenter.AddListener(messageToDisactive,OnDisactive);
if(!string.IsNullOrEmpty(messageToEnactive))
CEventCenter.AddListener(messageToEnactive,OnEnactive);
}
private void OnDestroy()
{
if(!string.IsNullOrEmpty(messageToDisactive))
CEventCenter.RemoveListener(messageToDisactive,OnDisactive);
if(!string.IsNullOrEmpty(messageToEnactive))
CEventCenter.RemoveListener(messageToEnactive,OnEnactive);
}
private void OnEnactive()
{
print("激活物体:"+gameObject.name);
gameObject.SetActive(true);
}
private void OnDisactive()
{
print("关闭物体:"+gameObject.name);
gameObject.SetActive(false);
}
}
}
|
namespace MMSCAN.intrnl
{
public class PersonalizationParametersMetaData
: Sybase.Reflection.ClassMetaData
{
/// <summary>
/// Sybase internal use only.
/// <summary>
public PersonalizationParametersMetaData()
{
_init();
}
protected void _init()
{
SetId(61);
SetAttributes(new Sybase.Reflection.AttributeMetaDataList());
SetOperations(new Sybase.Reflection.OperationMetaDataList());
SetAttributeMap(new Sybase.Reflection.AttributeMap());
SetOperationMap(new Sybase.Reflection.OperationMap());
Sybase.Reflection.AttributeMetaData listClientPK_attribute = AddAttributeWithParams(0, "listClientPK", "MMSCAN.ClientPersonalization*", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData listSessionPK_attribute = AddAttributeWithParams(1, "listSessionPK", "MMSCAN.SessionPersonalization*", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKUsername_attribute = AddAttributeWithParams(2, "PKUsername", "string", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKUsernameUserDefined_attribute = AddAttributeWithParams(3, "PKUsernameUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKUserpass_attribute = AddAttributeWithParams(4, "PKUserpass", "string", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKUserpassUserDefined_attribute = AddAttributeWithParams(5, "PKUserpassUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKZposition_attribute = AddAttributeWithParams(6, "PKZposition", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKZpositionUserDefined_attribute = AddAttributeWithParams(7, "PKZpositionUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKZzbarcode_attribute = AddAttributeWithParams(8, "PKZzbarcode", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKZzbarcodeUserDefined_attribute = AddAttributeWithParams(9, "PKZzbarcodeUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKTestRun_attribute = AddAttributeWithParams(10, "PKTestRun", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKTestRunUserDefined_attribute = AddAttributeWithParams(11, "PKTestRunUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKBwart_attribute = AddAttributeWithParams(12, "PKBwart", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKBwartUserDefined_attribute = AddAttributeWithParams(13, "PKBwartUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKDtyp_attribute = AddAttributeWithParams(14, "PKDtyp", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKDtypUserDefined_attribute = AddAttributeWithParams(15, "PKDtypUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKDocNum_attribute = AddAttributeWithParams(16, "PKDocNum", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKDocNumUserDefined_attribute = AddAttributeWithParams(17, "PKDocNumUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKJahr_attribute = AddAttributeWithParams(18, "PKJahr", "string?", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PKJahrUserDefined_attribute = AddAttributeWithParams(19, "PKJahrUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_DM_DATA_attribute = AddAttributeWithParams(20, "PK_DM_DATA", "MMSCAN.ZFM_MOB_MMS_DM_SET_RFC_T_DM_DATA*", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_DM_DATAUserDefined_attribute = AddAttributeWithParams(21, "PK_DM_DATAUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_DM_FIELDS_attribute = AddAttributeWithParams(22, "PK_DM_FIELDS", "MMSCAN.ZFM_MOB_MMS_DM_SET_RFC_T_DM_FIELDS*", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_DM_FIELDSUserDefined_attribute = AddAttributeWithParams(23, "PK_DM_FIELDSUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_TMC_DATA_attribute = AddAttributeWithParams(24, "PK_TMC_DATA", "MMSCAN.ZFM_MOB_MMS_TMC_SET_RFC_T_TMC_DATA*", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_TMC_DATAUserDefined_attribute = AddAttributeWithParams(25, "PK_TMC_DATAUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_TMC_FIELDS_attribute = AddAttributeWithParams(26, "PK_TMC_FIELDS", "MMSCAN.ZFM_MOB_MMS_TMC_SET_RFC_T_TMC_FIELDS*", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData PK_TMC_FIELDSUserDefined_attribute = AddAttributeWithParams(27, "PK_TMC_FIELDSUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData username_attribute = AddAttributeWithParams(28, "username", "string", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData usernameUserDefined_attribute = AddAttributeWithParams(29, "usernameUserDefined", "boolean", -1, false, false, true, false, false, false);
Sybase.Reflection.AttributeMetaData password_attribute = AddAttributeWithParams(30, "password", "string", -1, false, false, true, false, false, true);
Sybase.Reflection.AttributeMetaData passwordUserDefined_attribute = AddAttributeWithParams(31, "passwordUserDefined", "boolean", -1, false, false, true, false, false, false);
InitAttributeMapFromAttributes();
Sybase.Reflection.OperationMetaData Load0_operation = AddOperationWithParams(1214, "load", "void", false);
Sybase.Reflection.OperationMetaData Save1_operation = AddOperationWithParams(1231, "save", "void", false);
Sybase.Reflection.OperationMetaData SaveUserNamePassword2_operation = AddOperationWithParams(1248, "saveUserNamePassword", "void", false);
InitOperationMapFromOperations();
SetName("PersonalizationParameters");
}
/// <summary>
/// Sybase internal use only.
/// <summary>
public override bool IsEntity()
{
return false;
}
/// <summary>
/// Sybase internal use only.
/// <summary>
public override bool IsService()
{
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharpUtil
{
static class ListenInfo
{
static string ListenPassword(string prompt)
{
Console.Write(prompt);
var input = new StringBuilder();
for (; ; )
{
var keyinfo = Console.ReadKey(true);
switch (keyinfo.Key)
{
case ConsoleKey.Escape:
// Cancell
Console.WriteLine();
return null;
case ConsoleKey.Enter:
// Confirm
Console.WriteLine();
return input.ToString();
case ConsoleKey.Backspace:
// Back
if (0 < input.Length)
input.Length -= 1;
else
Console.Beep();
break;
default:
if (char.IsLetter(keyinfo.KeyChar))
{
// Not shift
if ((keyinfo.Modifiers & ConsoleModifiers.Shift) == 0)
{
input.Append(keyinfo.KeyChar);
}
// shift
else
{
// caps lock
if (Console.CapsLock)
input.Append(char.ToLower(keyinfo.KeyChar));
else
input.Append(char.ToUpper(keyinfo.KeyChar));
}
}
else if (!char.IsControl(keyinfo.KeyChar))
{
input.Append(keyinfo.KeyChar);
}
else
{
Console.Beep();
}
break;
}
}
}
}
}
|
using Swiddler.MarkupExtensions;
using Swiddler.Security;
using System;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Data;
using System.Windows.Markup;
namespace Swiddler.Converters
{
public class CertificateThumbprintConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string thumbprint && !string.IsNullOrEmpty(thumbprint))
{
var cert = X509.MyCurrentUserX509Store.Certificates
.Find(X509FindType.FindByThumbprint, thumbprint, false)
.OfType<X509Certificate2>()
.Where(c => c.HasPrivateKey).FirstOrDefault();
return (object)cert ?? thumbprint;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string str)
return str;
if (value is X509Certificate2 cert)
return cert.Thumbprint;
return null;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
|
using System;
using NLog;
namespace Crowswood.CbusLogger
{
class LoggingGridConnectProcessor :
GridConnectProcessor
{
#region Members
/// <summary>
/// Logger for recording incoming messages.
/// </summary>
private static readonly Logger msglog = LogManager.GetLogger("Message.GridConnect");
/// <summary>
/// The settings used to control the current instance.
/// </summary>
private readonly ISettings settings;
#endregion
#region Constructors
public LoggingGridConnectProcessor(ISettings settings, ISerialPortAdapter serialPortAdapter)
: base(serialPortAdapter)
{
if (settings is null)
throw new ArgumentNullException(nameof(settings));
this.settings = settings;
}
#endregion
#region Support routines
/// <summary>
/// Raise an event for the specified <paramref name="message"/>.
/// </summary>
/// <param name="message">A string containing the message.</param>
protected override void OnMessageReceived(string message)
{
if (this.settings.LoggingGridConnect)
msglog.Info(() => message);
base.OnMessageReceived(message);
}
#endregion
}
}
|
//Problem 12. Null Values Arithmetic
// Create a program that assigns null values to an integer and to a double variable.
// Try to print these variables at the console.
// Try to add some number or the null literal to these variables and print the result.
using System;
namespace Problem12NullValuesArithmetic
{
class NullValuesArithmetic
{
static void Main()
{
int? nullableIntValue = null;
Nullable<double> nullableDaubleValue = null;
Console.WriteLine("Assign null to both variables");
Console.WriteLine("nullableIntValue = " + nullableIntValue);
Console.WriteLine("nullableDaubleValue = " + nullableDaubleValue);
nullableIntValue = 1;
nullableDaubleValue = 2;
Console.WriteLine("Assign some value to both variables");
Console.WriteLine("nullableIntValue = " + nullableIntValue);
Console.WriteLine("nullableDaubleValue = " + nullableDaubleValue);
nullableIntValue = null;
nullableDaubleValue = null;
Console.WriteLine("Assign null to both variables");
Console.WriteLine("nullableIntValue = " + nullableIntValue);
Console.WriteLine("nullableDaubleValue = " + nullableDaubleValue);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace advent_of_code_2018
{
class Day05
{
public string React(string input)
{
int numDeletions = 0;
do
{
numDeletions = 0;
StringBuilder sb = new StringBuilder(input);
for (int i=1; i<sb.Length; i++)
{
int a = (int)sb[i];
int b = (int)sb[i-1];
if ( (a==(b-32)) || (a==(b+32)) )
{
numDeletions += 1;
sb.Remove(i-1, 2);
}
}
input = sb.ToString();
} while (numDeletions > 0);
return input;
}
public void SolveA()
{
string text = File.ReadAllText("05_input.txt").Trim();
text = React(text);
Console.WriteLine("Day 05 A: " + text.Length); //= 10972
}
public void SolveB()
{
string text = File.ReadAllText("05_input.txt").Trim();
int n = text.Length;
string alphabet = "abcdefghijklmnopqrstuvwxyz";
foreach (var c in alphabet)
{
char uc = (char)((int)c - 32);
string s = text.Replace(c.ToString(), string.Empty).Replace(uc.ToString(), string.Empty);
s = React(s);
n = Math.Min(n, s.Length);
}
Console.WriteLine("Day 05 B: " + n); //= 5278
}
}
}
|
using HaloSharp.Model.Metadata;
namespace HaloHistory.Business.Entities.Metadata
{
public class MedalData : BaseDataEntity<long, Medal>
{
public MedalData()
{
}
public MedalData(long id, Medal data) : base(id, data)
{
}
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// The base item component, filled with properties that are generally useful to know in any item request or that don't feel worthwhile to put in their own component.
/// </summary>
[DataContract]
public partial class DestinyEntitiesItemsDestinyItemComponent : IEquatable<DestinyEntitiesItemsDestinyItemComponent>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyEntitiesItemsDestinyItemComponent" /> class.
/// </summary>
/// <param name="ItemHash">The identifier for the item's definition, which is where most of the useful static information for the item can be found..</param>
/// <param name="ItemInstanceId">If the item is instanced, it will have an instance ID. Lack of an instance ID implies that the item has no distinct local qualities aside from stack size..</param>
/// <param name="Quantity">The quantity of the item in this stack. Note that Instanced items cannot stack. If an instanced item, this value will always be 1 (as the stack has exactly one item in it).</param>
/// <param name="BindStatus">If the item is bound to a location, it will be specified in this enum..</param>
/// <param name="Location">An easy reference for where the item is located. Redundant if you got the item from an Inventory, but useful when making detail calls on specific items..</param>
/// <param name="BucketHash">The hash identifier for the specific inventory bucket in which the item is located..</param>
/// <param name="TransferStatus">If there is a known error state that would cause this item to not be transferable, this Flags enum will indicate all of those error states. Otherwise, it will be 0 (CanTransfer)..</param>
/// <param name="Lockable">If the item can be locked, this will indicate that state..</param>
/// <param name="State">A flags enumeration indicating the states of the item: whether it's tracked or locked for example..</param>
public DestinyEntitiesItemsDestinyItemComponent(uint? ItemHash = default(uint?), long? ItemInstanceId = default(long?), int? Quantity = default(int?), DestinyItemBindStatus BindStatus = default(DestinyItemBindStatus), DestinyItemLocation Location = default(DestinyItemLocation), uint? BucketHash = default(uint?), DestinyTransferStatuses TransferStatus = default(DestinyTransferStatuses), bool? Lockable = default(bool?), DestinyItemState State = default(DestinyItemState))
{
this.ItemHash = ItemHash;
this.ItemInstanceId = ItemInstanceId;
this.Quantity = Quantity;
this.BindStatus = BindStatus;
this.Location = Location;
this.BucketHash = BucketHash;
this.TransferStatus = TransferStatus;
this.Lockable = Lockable;
this.State = State;
}
/// <summary>
/// The identifier for the item's definition, which is where most of the useful static information for the item can be found.
/// </summary>
/// <value>The identifier for the item's definition, which is where most of the useful static information for the item can be found.</value>
[DataMember(Name="itemHash", EmitDefaultValue=false)]
public uint? ItemHash { get; set; }
/// <summary>
/// If the item is instanced, it will have an instance ID. Lack of an instance ID implies that the item has no distinct local qualities aside from stack size.
/// </summary>
/// <value>If the item is instanced, it will have an instance ID. Lack of an instance ID implies that the item has no distinct local qualities aside from stack size.</value>
[DataMember(Name="itemInstanceId", EmitDefaultValue=false)]
public long? ItemInstanceId { get; set; }
/// <summary>
/// The quantity of the item in this stack. Note that Instanced items cannot stack. If an instanced item, this value will always be 1 (as the stack has exactly one item in it)
/// </summary>
/// <value>The quantity of the item in this stack. Note that Instanced items cannot stack. If an instanced item, this value will always be 1 (as the stack has exactly one item in it)</value>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; }
/// <summary>
/// If the item is bound to a location, it will be specified in this enum.
/// </summary>
/// <value>If the item is bound to a location, it will be specified in this enum.</value>
[DataMember(Name="bindStatus", EmitDefaultValue=false)]
public DestinyItemBindStatus BindStatus { get; set; }
/// <summary>
/// An easy reference for where the item is located. Redundant if you got the item from an Inventory, but useful when making detail calls on specific items.
/// </summary>
/// <value>An easy reference for where the item is located. Redundant if you got the item from an Inventory, but useful when making detail calls on specific items.</value>
[DataMember(Name="location", EmitDefaultValue=false)]
public DestinyItemLocation Location { get; set; }
/// <summary>
/// The hash identifier for the specific inventory bucket in which the item is located.
/// </summary>
/// <value>The hash identifier for the specific inventory bucket in which the item is located.</value>
[DataMember(Name="bucketHash", EmitDefaultValue=false)]
public uint? BucketHash { get; set; }
/// <summary>
/// If there is a known error state that would cause this item to not be transferable, this Flags enum will indicate all of those error states. Otherwise, it will be 0 (CanTransfer).
/// </summary>
/// <value>If there is a known error state that would cause this item to not be transferable, this Flags enum will indicate all of those error states. Otherwise, it will be 0 (CanTransfer).</value>
[DataMember(Name="transferStatus", EmitDefaultValue=false)]
public DestinyTransferStatuses TransferStatus { get; set; }
/// <summary>
/// If the item can be locked, this will indicate that state.
/// </summary>
/// <value>If the item can be locked, this will indicate that state.</value>
[DataMember(Name="lockable", EmitDefaultValue=false)]
public bool? Lockable { get; set; }
/// <summary>
/// A flags enumeration indicating the states of the item: whether it's tracked or locked for example.
/// </summary>
/// <value>A flags enumeration indicating the states of the item: whether it's tracked or locked for example.</value>
[DataMember(Name="state", EmitDefaultValue=false)]
public DestinyItemState State { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyEntitiesItemsDestinyItemComponent {\n");
sb.Append(" ItemHash: ").Append(ItemHash).Append("\n");
sb.Append(" ItemInstanceId: ").Append(ItemInstanceId).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" BindStatus: ").Append(BindStatus).Append("\n");
sb.Append(" Location: ").Append(Location).Append("\n");
sb.Append(" BucketHash: ").Append(BucketHash).Append("\n");
sb.Append(" TransferStatus: ").Append(TransferStatus).Append("\n");
sb.Append(" Lockable: ").Append(Lockable).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyEntitiesItemsDestinyItemComponent);
}
/// <summary>
/// Returns true if DestinyEntitiesItemsDestinyItemComponent instances are equal
/// </summary>
/// <param name="input">Instance of DestinyEntitiesItemsDestinyItemComponent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyEntitiesItemsDestinyItemComponent input)
{
if (input == null)
return false;
return
(
this.ItemHash == input.ItemHash ||
(this.ItemHash != null &&
this.ItemHash.Equals(input.ItemHash))
) &&
(
this.ItemInstanceId == input.ItemInstanceId ||
(this.ItemInstanceId != null &&
this.ItemInstanceId.Equals(input.ItemInstanceId))
) &&
(
this.Quantity == input.Quantity ||
(this.Quantity != null &&
this.Quantity.Equals(input.Quantity))
) &&
(
this.BindStatus == input.BindStatus ||
(this.BindStatus != null &&
this.BindStatus.Equals(input.BindStatus))
) &&
(
this.Location == input.Location ||
(this.Location != null &&
this.Location.Equals(input.Location))
) &&
(
this.BucketHash == input.BucketHash ||
(this.BucketHash != null &&
this.BucketHash.Equals(input.BucketHash))
) &&
(
this.TransferStatus == input.TransferStatus ||
(this.TransferStatus != null &&
this.TransferStatus.Equals(input.TransferStatus))
) &&
(
this.Lockable == input.Lockable ||
(this.Lockable != null &&
this.Lockable.Equals(input.Lockable))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.ItemHash != null)
hashCode = hashCode * 59 + this.ItemHash.GetHashCode();
if (this.ItemInstanceId != null)
hashCode = hashCode * 59 + this.ItemInstanceId.GetHashCode();
if (this.Quantity != null)
hashCode = hashCode * 59 + this.Quantity.GetHashCode();
if (this.BindStatus != null)
hashCode = hashCode * 59 + this.BindStatus.GetHashCode();
if (this.Location != null)
hashCode = hashCode * 59 + this.Location.GetHashCode();
if (this.BucketHash != null)
hashCode = hashCode * 59 + this.BucketHash.GetHashCode();
if (this.TransferStatus != null)
hashCode = hashCode * 59 + this.TransferStatus.GetHashCode();
if (this.Lockable != null)
hashCode = hashCode * 59 + this.Lockable.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using MyCashFlow.Web.ViewModels.Shared;
using Rsx = MyCashFlow.Resources.Localization.Views;
using System.Collections.Generic;
namespace MyCashFlow.Web.ViewModels.TransactionType
{
public class TransactionTypeIndexViewModel : BaseViewModel
{
public TransactionTypeIndexViewModel()
: base(title: Rsx.TransactionType._Shared.Title,
header: string.Format(Rsx.Shared.Index.Header, Rsx.TransactionType._Shared.Title.ToLower() + "s")) { }
public IList<TransactionTypeIndexItemViewModel> Items { get; set; }
}
} |
using API.Persistence.Services;
using Microsoft.AspNetCore.Mvc;
using API.Shared.Request;
using System;
using System.Collections.Generic;
using System.Linq;
using API.Shared.Models;
namespace API.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class DocumentoController: BaseController
{
private readonly IDocumentoService _documentoService;
public DocumentoController(IDocumentoService documentoService)
{
_documentoService = documentoService;
}
[HttpGet]
public IActionResult Obter(int skip, int take)
=> _documentoService
.Obter(skip, take)
.Match(
response => Ok(response) as IActionResult,
falha => TratarFalha(falha,
(Processo.NaoEncontrado, () => NotFound(new Response(falha.Erros.Mensagem, 404)) as IActionResult),
(Processo.ErroNoBanco, () => new StatusCodeResult(500) as IActionResult)
) as IActionResult
);
[HttpPost]
public IActionResult Incluir([FromBody] IncluirDocumentoRequest request)
=> _documentoService
.Incluir(request)
.Match(
response => Ok(response) as IActionResult,
falha => TratarFalha(falha,
(Processo.Validacao, () => BadRequest(new Response(falha.Erros.Mensagem, 400)) as IActionResult),
(Processo.ErroNoBanco, () => new StatusCodeResult(500) as IActionResult)
) as IActionResult
);
}
} |
using System;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Gui.Controls
{
public enum Dock
{
Left, Right, Top, Bottom
}
public class DockPanel : LayoutControl
{
public override Size GetContentSize(IGuiContext context)
{
var size = new Size();
for (var i = 0; i < Items.Count; i++)
{
var control = Items[i];
var actualSize = control.CalculateActualSize(context);
if (LastChildFill && i == Items.Count - 1)
{
size.Width += actualSize.Width;
size.Height += actualSize.Height;
}
else
{
var dock = control.GetAttachedProperty(DockProperty) as Dock? ?? Dock.Left;
switch (dock)
{
case Dock.Left:
case Dock.Right:
size.Width += actualSize.Width;
break;
case Dock.Top:
case Dock.Bottom:
size.Height += actualSize.Height;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
return size;
}
protected override void Layout(IGuiContext context, Rectangle rectangle)
{
for (var i = 0; i < Items.Count; i++)
{
var control = Items[i];
if (LastChildFill && i == Items.Count - 1)
{
PlaceControl(context, control, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
}
else
{
var actualSize = control.CalculateActualSize(context);
var dock = control.GetAttachedProperty(DockProperty) as Dock? ?? Dock.Left;
switch (dock)
{
case Dock.Left:
PlaceControl(context, control, rectangle.Left, rectangle.Top, actualSize.Width, rectangle.Height);
rectangle.X += actualSize.Width;
rectangle.Width -= actualSize.Width;
break;
case Dock.Right:
PlaceControl(context, control, rectangle.Right - actualSize.Width, rectangle.Top, actualSize.Width, rectangle.Height);
rectangle.Width -= actualSize.Width;
break;
case Dock.Top:
PlaceControl(context, control, rectangle.Left, rectangle.Top, rectangle.Width, actualSize.Height);
rectangle.Y += actualSize.Height;
rectangle.Height -= actualSize.Height;
break;
case Dock.Bottom:
PlaceControl(context, control, rectangle.Left, rectangle.Bottom - actualSize.Height, rectangle.Width, actualSize.Height);
rectangle.Height -= actualSize.Height;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
public const string DockProperty = "Dock";
public override Type GetAttachedPropertyType(string propertyName)
{
if (string.Equals(DockProperty, propertyName, StringComparison.OrdinalIgnoreCase))
return typeof(Dock);
return base.GetAttachedPropertyType(propertyName);
}
public bool LastChildFill { get; set; } = true;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Kalcium
{
public static class Event
{
public static void Raise(this EventHandler me, object sender)
{
if (me != null)
me(sender, EventArgs.Empty);
}
public static void Raise(this Action me)
{
if (me != null)
me();
}
public static void Raise<T>(this Action<T> me, T argument)
{
if (me != null)
me(argument);
}
public static void Raise(this PropertyChangedEventHandler me, string property, object sender)
{
if (me != null)
me(sender, new PropertyChangedEventArgs(property));
}
}
}
|
using JabberPoint.Domain.Content.Behaviours;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JabberPoint.Domain.Content
{
/// <summary>
/// Visitor pattern interface for communication with behaviours without typechecks
/// </summary>
public interface IContentBehaviourVisitor
{
/// <summary>
/// function that is called from a behaviour, passing itself as an argument.
/// </summary>
/// <param name="behaviour">the behaviour that called this function</param>
void Visit(TextBehaviour behaviour);
/// <summary>
/// function that is called from a behaviour, passing itself as an argument.
/// </summary>
/// <param name="behaviour">the behaviour that called this function</param>
void Visit(MediaBehaviour behaviour);
/// <summary>
/// function that is called from a behaviour, passing itself as an argument.
/// </summary>
/// <param name="behaviour">the behaviour that called this function</param>
void Visit(LevelledBehaviour behaviour);
/// <summary>
/// function that is called from a behaviour, passing itself as an argument.
/// </summary>
/// <param name="behaviour">the behaviour that called this function</param>
void Visit(ListBehaviour behaviour);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Misc
{
public static int[] createSeq(String seq)
{
int[] arr = new int[seq.Length + 1];
for (int i = arr.Length; i >= 1; i--)
{
arr[arr.Length - i] = i;
}
int j = arr.Length - 1;
for (int i = seq.Length - 1; i >= 0; i--)
{
if (seq[i] == 'I')
{
swap(j, j - 1, arr);
}
j--;
}
return arr;
}
private static void swap(int i, int j, int[] a)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void PrintNumbers(string str)
{
if (str.Length == 0)
{
return;
}
int dCount = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == 'D')
{
dCount++;
}
}
List<int> nums = new List<int>();
for (int i = 0; i <= str.Length; i++)
{
nums.Add(i + 1);
}
Console.WriteLine(nums[dCount].ToString() + " ");
nums[dCount] = -1;
int iCount = dCount + 1;
dCount--;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == 'I')
{
Console.WriteLine(nums[iCount].ToString() + " ");
nums[iCount++] = -1;
}
else {
Console.WriteLine(nums[dCount].ToString() + " ");
nums[dCount--] = -1;
}
}
}
public static String findPattern(String logicalPattern)
{
String pattern = "";
int numOfIncrements = countNumOfInc(logicalPattern);
int i = 1, j = logicalPattern.Length + 1;
char[] arr = logicalPattern.ToCharArray();
for (int n = 0; n < logicalPattern.Length; n++)
{
if (arr[n] == 'I')
{
pattern += i;
i = setI(i, pattern, j);
n++;
--numOfIncrements;
}
else {
int temp = j - numOfIncrements;
while (arr[n] == 'D')
{
pattern += temp--;
n++;
}
}
}
while (pattern.Length < logicalPattern.Length + 1)
{
pattern += i++;
}
return pattern;
}
private static int setI(int i, String pattern, int j)
{
while (pattern.Contains(i + "") && i <= j) ++i;
return i;
}
private static int countNumOfInc(String logicalPattern)
{
int count = 0;
foreach (char c in logicalPattern.ToCharArray())
{
if (c == 'I') ++count;
}
return count;
}
}
}
|
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
#endregion
namespace ContactsManager.API.Models
{
public class ContactDetailRequestModel
{
/// <summary>
/// Identifies FirstName of Customer
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Identifies LastName of Customer
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Identifies Email Address of Customer
/// </summary>
public string Email { get; set; }
/// <summary>
/// Identifies Phone Number of Customer. (Only 10 digit mobile number with country code is accepted. e.g. +919730823490)
/// </summary>
public string PhoneNumber { get; set; }
/// <summary>
/// Identifies if respective Contact Information is Active or Not
/// </summary>
public string Status { get; set; }
/// <summary>
/// Validation of Request
/// </summary>
public void ValidateRequest()
{
if (string.IsNullOrEmpty(FirstName))
throw new ArgumentNullException("FirstName");
if (FirstName.Length > 20)
throw new ArgumentException("FirstName length can not be greater than 20");
var isValidFirstName = Regex.IsMatch(FirstName, "^[a-z0-9 ]+$", RegexOptions.IgnoreCase);
if (!isValidFirstName)
throw new ArgumentException("Special Characters are not allowed in FirstName");
if (string.IsNullOrEmpty(LastName))
throw new ArgumentNullException("LastName");
if (LastName.Length > 20)
throw new ArgumentException("LastName length can not be greater than 20");
var isValidLastName = Regex.IsMatch(LastName, "^[a-z0-9 ]+$", RegexOptions.IgnoreCase);
if (!isValidLastName)
throw new ArgumentException("Special Characters are not allowed in LastName");
if (string.IsNullOrEmpty(Email))
throw new ArgumentNullException("Email");
var isValidEmail = Regex.IsMatch(Email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
if (!isValidEmail)
throw new ArgumentException("Invalid Email");
if (string.IsNullOrEmpty(PhoneNumber))
throw new ArgumentNullException("PhoneNumber");
/* Supported Phone Number formats are:
* "xxxxxxxxxx", "+xx xx xxxxxxxx", "xxx-xxxx-xxxx"
*/
var isValidPhoneNumber = Regex.IsMatch(PhoneNumber, @"(^[0-9]{10}$)|(^\+[0-9]{2}\s+[0-9]{2}[0-9]{8}$)|(^[0-9]{3}-[0-9]{4}-[0-9]{4}$)", RegexOptions.IgnoreCase);
if (!isValidPhoneNumber)
throw new ArgumentException("Invalid PhoneNumber");
}
}
} |
using NUnit.Framework;
using nuru.IO.NUI.Cell.Color;
namespace nuru.Unit.Tests
{
public class ColorTests
{
[TestCase(0, 1, ExpectedResult = "0, 1")]
[TestCase(255, 0, ExpectedResult = "255, 0")]
[TestCase(125, 200, ExpectedResult = "125, 200")]
public string TestToString(byte fg, byte bg)
{
return new ColorData(fg, bg).ToString();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class BaseClass {
public string CharacterClassName { get; set; }
public string CharacterClassDescription { get; set; }
public int Life { get; set; }
public int Mana { get; set; }
public int Experience { get; set; }
public int Level { get; set; }
public int Endurance { get; set; }
public int Strength { get; set; }
public int Intellect { get; set; }
public int Speed { get; set; }
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GravityController : MonoBehaviour {
public float xpos;
public float ypos;
public Vector3 mousepos;
public float gravpower =10f;
// Use this for initialization
void Start () {
gravpower = 10f;
Physics.gravity = new Vector3(0, 10.0F, 0);
}
// Update is called once per frame
void FixedUpdate () {
mousepos = Input.mousePosition;
mousepos.x = mousepos.x / Screen.width;
mousepos.y = mousepos.y / Screen.height;
mousepos = mousepos * 2;
mousepos.x = mousepos.x - 1;
mousepos.y = mousepos.y - 1;
mousepos = mousepos * gravpower;
Physics.gravity = mousepos;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EDU_Rent.business_layer;
using Microsoft.VisualBasic;
namespace EDU_Rent.presentation_layer.controls
{
public partial class MainControl : UserControl
{
User user = new User();
Book book = new Book();
Address address = new Address();
BookLine bookline = new BookLine();
Order order = new Order();
OrderLine orderline = new OrderLine();
User currentUser;
NotificationControl notcont;
Rate rate = new Rate();
Email email = new Email();
string currentUserRole;
// load up the form for the first time
public MainControl(MainForm mainForm, String usernameStr)
{
InitializeComponent();
LoadUserData(usernameStr);
LoadAddBookData();
LoadAddressData();
LoadNotCenter();
}
private void LoadNotCenter()
{
//create and add the notification center.
notcont = new NotificationControl(currentUser.userName);
notcont.Dock = DockStyle.Fill;
notAttPanel.Controls.Add(notcont);
}
// load up the address data
private void LoadAddressData()
{
addressCb.Sorted = true;
addressCb.Items.Clear();
foreach (Address a in address.GetAllAddressesByUsername(currentUser.userName))
{
addressCb.Items.Add(a.AddressID + " " + a.AddressL1 + " " + a.AddressL2 + " " + a.AddressCity + " " + a.AddressState + " " + a.AddressZip);
}
addressCb.Text = "Select an address!";
}
// Pull down userdata and populate all needed fields
internal void LoadUserData(string usernameStr)
{
// populate fields for the user here
currentUser = user.GetUserByUserName(usernameStr);
currentUserRole = user.GetRoleByUserName(usernameStr);
// Account details
userFirstNameTxt.Text = currentUser.userFirstName;
userLastNameTxt.Text = currentUser.userLastName;
userEmailTxt.Text = currentUser.userEmail;
userPhoneTxt.Text = currentUser.userPhone;
// Profile details
userAboutMeTxt.Text = currentUser.userProfDesc;
userWebsiteTxt.Text = currentUser.userWebsite;
tabLoactionTxt.Text = "http://www.EDU-Rent.com/" + tabControl1.SelectedTab.Text + "/Username?=" + currentUser.userName;
welcomeUserLbl.Text = "Welcome: " + currentUser.userName;
// Role code
// Are we a mod?
if (currentUserRole != null)
if (currentUserRole.Equals("Mod"))
{
TabPage tp;
// reports
tp = new TabPage();
tp.Text = "Reports";
tp.Controls.Add(new ReportControl());
tabControl1.Controls.Add(tp);
// Database utility
tp = new TabPage();
tp.Text = "Database Utils";
tp.Controls.Add(new DatabaseUtilityControl());
tabControl1.Controls.Add(tp);
}
// Update the rates
Label lbl;
double total = 0.0;
int i = 0;
Boolean ratingsFound = false;
foreach(Rate r in rate.GetAllRates())
{
if (r.RatedUser.Equals(currentUser.userName))
{
ratingsFound = true;
lbl = new Label();
lbl.Text = "User: " + r.RatingUser + " gave you: " + new string('*', r.Rating) + " (" + r.Rating + ") stars";
lbl.AutoSize = true;
i++;
total += r.Rating;
ratingsFlp.Controls.Add(lbl);
}
}
if (ratingsFound == true)
{
ratingGb.Text = "Average Rating: " + (total / i);
}
else
{
lbl = new Label();
lbl.Text = "No one has rated you yet!";
lbl.AutoSize = true;
ratingsFlp.Controls.Add(lbl);
}
}
// Load needed datata for the add book field
public void LoadAddBookData()
{
List<int> maxQTY = new List<int>();
for (int i = 1; i < 100; i++)
{
maxQTY.Add(i);
}
maxQTY.Sort();
foreach(int li in maxQTY)
{
// DEBUG MessageBox.Show("Adding: " + li + "!");
bookQTYCb.Items.Add(li);
}
bookQTYCb.Text = "1";
}
// Load the books
private void MainControl_Load(object sender, EventArgs e)
{
populateBookLines();
}
private void populateBookLines()
{
booksGridView.Rows.Clear();
foreach (BookLine bl in bookline.GetAllBookLine())
{
// dont show books being sold by the current user
if (!bl.UserName.Equals(currentUser.userName))
{
// Dont show books that are out of stock
if (bl.BookQTY > 0)
{
// dont show books already in an orderline ( Possible issue here with QTY )
//if(!bl.CheckBookInCartByISBNAndSeller(bl.BookISBN, bl.UserName))
{
booksGridView.Rows.Add(book.GetBookNameByISBN(bl.BookISBN), book.GetBookAuthorByISBN(bl.BookISBN), bl.BookISBN,
bl.UserName, bl.BookPrice, bl.BookRentPrice, bl.UploadedOn, bl.BookQTY);
}
}
}
}
}
private void iconLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.icons8.com/");
}
// DEBUG CODE (UNREACHABLE)
// This is how you would create new tabs on the fly and add stuff
private void button4_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage();
tp.Text = "Bookname (R-Click to close)";
tabControl1.Controls.Add(tp);
}
// DEBUG CODE (UNREACHABLE)
// This is how you would delete tabs on the fly
private void close_Click(object sender, MouseEventArgs e)
{
MessageBox.Show("Tab clicked!");
if (e.Button == MouseButtons.Right)
{
tabControl1.SelectedTab.Dispose();
}
}
// Tab changed/clicked
private void tabControl1_MouseDown(object sender, MouseEventArgs e)
{
tabLoactionTxt.Text = ("http://www.EDU-Rent.com/" + tabControl1.SelectedTab.Text + "/Username?=" + currentUser.userName).Replace(" ", "%20");
// Did they just try to close a tab?
if (e.Button == MouseButtons.Right)
{
if (
tabControl1.SelectedTab.Text.Equals("Books") ||
tabControl1.SelectedTab.Text.Equals("Home") ||
tabControl1.SelectedTab.Text.Equals("Add Book") ||
tabControl1.SelectedTab.Text.Equals("My Cart") ||
tabControl1.SelectedTab.Text.Equals("My Order") ||
tabControl1.SelectedTab.Text.Equals("Users") ||
tabControl1.SelectedTab.Text.Equals("Database Utils") ||
tabControl1.SelectedTab.Text.Equals("Books I Am Selling") ||
tabControl1.SelectedTab.Text.Equals("Notification Center")
)
{
MessageBox.Show("\"" + tabControl1.SelectedTab.Text + "\" is not allowed to be closed.\nSelect the tab first, then right click.", "Not allowed.");
}
else
{
tabControl1.SelectedTab.Controls.Clear();
tabControl1.SelectedTab.Dispose();
}
}
// Refresh books im selling when clicked
if (tabControl1.SelectedTab.Text.Equals("Books I Am Selling"))
{
PopulateBooksSelling();
}
// Refresh book lines when clicked
if (tabControl1.SelectedTab.Text.Equals("Books"))
{
populateBookLines();
}
if (tabControl1.SelectedTab.Text.Equals("Notification Center"))
{
notcont.Reload();
}
if (tabControl1.SelectedTab.Text.Equals("Users"))
{
populateUsers();
}
// Refresh the cart
if (tabControl1.SelectedTab.Text.Equals("My Cart"))
{
cartDataGV.Rows.Clear();
// Check if there are any order lines
if (order.OrderExists())
{
// add them to the grid
foreach (OrderLine ol in orderline.GetAllOrderLine())
{
// but only if they are associtaed with an order that isnt in the cart
if (order.IsOrderLineConnectedToInCartOrder(ol.ID))
{
cartDataGV.Rows.Add(ol.ID, book.GetBookNameByISBN(ol.BookISBN), ol.BookISBN, ol.Rent, bookline.GetTotalByISBN(ol.BookISBN, ol.Rent));
}
}
}
// if yes then add them to the grids on the cart AND add them to lists so we can pass all the lists to an order control
}
}
private void populateUsers()
{
usersGv.Rows.Clear();
// Get all the users usernames and first names
foreach(User ur in user.GetAllUsersUNaF())
{
if (!ur.userName.Equals(currentUser.userName))
{
usersGv.Rows.Add(ur.userName, ur.userFirstName, user.GetAmountOfBooksSellingByUserName(ur.userName));
}
}
}
private void PopulateBooksSelling()
{
booksSellingGV.Rows.Clear();
if (bookline.GetAllBooksSelling(currentUser).Count() > 0)
{
foreach (BookLine bl in bookline.GetAllBooksSelling(currentUser))
{
booksSellingGV.Rows.Add(bl.BookISBN, book.GetBookNameByISBN(bl.BookISBN), bl.BookISBN);
}
}
}
// Save profile details
private void userProfUpdateBtn_Click(object sender, EventArgs e)
{
user.SaveProfileDetailsForUserName(currentUser.userName, userAboutMeTxt.Text, userWebsiteTxt.Text);
MessageBox.Show("Profile updated!");
}
// Add a new book!
private void addBookBtn_Click(object sender, EventArgs e)
{
book = new Book();
decimal numberDecimal = 0.0m;
// Does the book exists in Books?
if (book.GetBookExistsByISBN(bookISBNTxt.Text))
{
// Does the book already exist in the users for sale bin?
if (bookline.BookExistsByISBNandUsername(currentUser.userName, bookISBNTxt.Text))
{
MessageBox.Show("You are already renting/selling a book with that ISBN!\nPlease delete your book and relist it.", "Duplicate book!");
return;
}
// Does the user want to rent a book that already exists?
DialogResult dialogResult = MessageBox.Show("That book exists! \n Would you like to add another one like it with these details?\n Book price: $" +
bookPriceTxt.Text + "\n Book rent price: $" + bookRentPriceTxt.Text,"Book already exists.",MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
if (!bookPriceTxt.Text.Equals("")) { book.BookPrice = decimal.TryParse(bookPriceTxt.Text, out numberDecimal) ? numberDecimal : 0.0m; }
if (!bookRentPriceTxt.Text.Equals("")) { book.BookRentPrice = decimal.TryParse(bookRentPriceTxt.Text, out numberDecimal) ? numberDecimal : 0.0m; }
bookline = new BookLine();
bookline.UserName = currentUser.userName;
bookline.BookISBN = bookISBNTxt.Text;
bookline.BookPrice = book.BookPrice;
bookline.BookRentPrice = book.BookRentPrice;
bookline.BookQTY = Convert.ToInt32(bookQTYCb.Text);
if (bookline.addExistingBook().Equals(""))
{
MessageBox.Show("Book added!");
BlankBookAddedFields();
}
else
{
MessageBox.Show("Error: " + bookline.addExistingBook(), "Error in new book data");
}
BlankBookAddedFields();
return;
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
book.BookName = bookNameTxt.Text;
book.BookUserName = currentUser.userName;
book.BookAuthor = bookAuthorTxt.Text;
book.BookPublisher = bookPubTxt.Text;
book.BookCondition = bookConditionTxt.Text;
book.BookEdition = bookEditionTxt.Text;
if (!bookPriceTxt.Text.Equals("")) {book.BookPrice = decimal.TryParse(bookPriceTxt.Text, out numberDecimal) ? numberDecimal : 0.0m; }
if (!bookRentPriceTxt.Text.Equals("")) {book.BookRentPrice = decimal.TryParse(bookRentPriceTxt.Text, out numberDecimal) ? numberDecimal : 0.0m; }
book.BookISBN = bookISBNTxt.Text;
book.BookISBNThirt = bookISBNThirtTxt.Text;
book.BookDesc = bookDescTxt.Text;
book.BookPubDate = dateTimePicker1.Value;
book.BookQTY = Convert.ToInt32(bookQTYCb.Text);
if (book.AddBook().Equals(""))
{
MessageBox.Show("Book added!");
email.SendEmail(currentUser, "<p style=\"color: blue;\">We have added your book!</p> Thanks for uploading \"" + book.BookName + "\". We will notify you the second it sells <br /> - EDU-Rent", "Thanks for contributing!");
BlankBookAddedFields();
}
else
{
MessageBox.Show("Error: " + book.AddBook(), "Error in new book data");
}
}
// Add a book
private void booksGridView_CellContentDoubleClick_1(object sender, DataGridViewCellEventArgs e)
{
var cellindex = booksGridView.SelectedCells[0].RowIndex;
// Get the ISBN
var isbncellcollection = booksGridView.Rows[cellindex].Cells[2];
// Get the title
var titlecellcollection = booksGridView.Rows[cellindex].Cells[0];
var bookuploadercellcollection = booksGridView.Rows[cellindex].Cells[3];
// Create the new tab
TabPage tp = new TabPage();
// Create the new control, pass the selected book to it
BookControl bcontrol = new BookControl(isbncellcollection.Value.ToString(), currentUser.userName, bookuploadercellcollection.Value.ToString());
// Add the book control to the tab
tp.Controls.Add(bcontrol);
// Size the book control
bcontrol.Dock = DockStyle.Fill;
// Create the tab text
tp.Text = titlecellcollection.Value.ToString() + ": (R-Click to close)";
// Add the tab
tabControl1.Controls.Add(tp);
// Select the tab
tabControl1.SelectedTab = tp;
/** YES NO EXAMPLE
DialogResult dialogResult = MessageBox.Show("Would you like to add: " + titlecellcollection.Value.ToString() +
" to your cart?", "Add book to cart? ISBN: " + isbncellcollection.Value.ToString(), MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
}
else if (dialogResult == DialogResult.No)
{
}
**/
}
// Add a new address
private void addAddressBtn_Click(object sender, EventArgs e)
{
address = new Address();
address.AddressL1 = addLine1Txt.Text;
address.AddressL2 = addLine2Txt.Text;
address.AddressCity = addCityTxt.Text;
address.AddressState = addStateTxt.Text;
address.AddressZip = addZipTxt.Text;
address.UserName = currentUser.userName;
if (address.AddAddress().Equals(""))
{
MessageBox.Show("Address added!");
BlankAddressAddedFields();
LoadAddressData();
}
else
{
MessageBox.Show("Error: " + address.AddAddress(), "Error in new address data");
}
}
// Delete an address
private void deleteAddressBtn_Click(object sender, EventArgs e)
{
if (addressCb.Text.Equals("Select an address!"))
{
MessageBox.Show("Please select an address!","No address selected!");
return;
}
string addressIDStr = String.Empty;
addressIDStr = addressCb.Text;
string[] addressArr = new string[(addressIDStr.Length - addressIDStr.Replace(" ", "").Length) + 1];
addressArr = addressIDStr.Split(' ');
address.DeleteAddressByID(Convert.ToInt32(addressArr[0]));
MessageBox.Show("Address deleted!", "Success.");
LoadAddressData();
}
// Blank out fields
private void BlankBookAddedFields()
{
bookNameTxt.Text = "";
bookAuthorTxt.Text = "";
bookPubTxt.Text = "";
bookConditionTxt.Text = "";
bookPriceTxt.Text = "";
bookRentPriceTxt.Text = "";
bookISBNTxt.Text = "";
bookISBNThirtTxt.Text = "";
bookDescTxt.Text = "";
bookEditionTxt.Text = "1";
dateTimePicker1.Value = dateTimePicker1.Value.Date;
bookQTYCb.Text = "1";
}
private void clearBookBtn_Click(object sender, EventArgs e)
{
bookNameTxt.Text = "";
bookAuthorTxt.Text = "";
bookPubTxt.Text = "";
bookConditionTxt.Text = "";
bookPriceTxt.Text = "";
bookRentPriceTxt.Text = "";
bookISBNTxt.Text = "";
bookISBNThirtTxt.Text = "";
bookDescTxt.Text = "";
bookEditionTxt.Text = "1";
dateTimePicker1.Value = dateTimePicker1.Value.Date;
}
private void BlankAddressAddedFields()
{
addLine1Txt.Text = "";
addLine2Txt.Text = "";
addCityTxt.Text = "";
addStateTxt.Text = "";
addZipTxt.Text = "";
}
private void completeOrderBtn_Click(object sender, EventArgs e)
{
// Create the new tab
TabPage tp = new TabPage();
// Create the new control, pass the needed info in
OrderControl ordercontrol = new OrderControl(currentUser);
// Add the control to the tab
tp.Controls.Add(ordercontrol);
// Size the control
ordercontrol.Dock = DockStyle.Fill;
// Create the tab text
tp.Text = "My Order: (R-Click to close)";
// Add the tab
tabControl1.Controls.Add(tp);
//Select the tab
tabControl1.SelectedTab = tp;
}
private void deleteSelectedBtn_Click(object sender, EventArgs e)
{
}
private void booksSellingGV_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var cellindex = booksSellingGV.SelectedCells[0].RowIndex;
// Get the ISBN
var isbncellcollection = booksSellingGV.Rows[cellindex].Cells[0];
//get the title
var titlecellcollection = booksSellingGV.Rows[cellindex].Cells[1];
// Do we want to delete the book?
DialogResult dialogResult = MessageBox.Show("Would you like to remove: " + titlecellcollection .Value.ToString()+ " book from the public listings?", "Remove from selling?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
bookline.DeleteBookByISBNAndCurrentUser(isbncellcollection.Value.ToString(), currentUser.userName);
PopulateBooksSelling();
return;
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
private void purgeOrderBtn_Click(object sender, EventArgs e)
{
// Do we want to delete the order?
DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete all items from your cart?", "Delete the current order?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
order.DeleteCartsByUserName(currentUser.userName);
cartDataGV.Rows.Clear();
return;
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
// Color tabs
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
{
TabPage page = tabControl1.TabPages[e.Index];
// Color admin report red
if (tabControl1.TabPages[e.Index].Text.Equals("Reports"))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
}
// Color admin report red
if (tabControl1.TabPages[e.Index].Text.Equals("Database Utils"))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), e.Bounds);
}
// color order green
if (tabControl1.TabPages[e.Index].Text.Equals("My Order: (R-Click to close)"))
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGreen), e.Bounds);
}
// color cart orange
if (tabControl1.TabPages[e.Index].Text.Equals("My Cart"))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Orange), e.Bounds);
}
else
e.Graphics.FillRectangle(new SolidBrush(Color.Gold), e.Bounds);
Rectangle paddedBounds = e.Bounds;
int yOffset = (e.State == DrawItemState.Selected) ? -2 : 1;
paddedBounds.Offset(1, yOffset);
TextRenderer.DrawText(e.Graphics, page.Text, new Font("Arial", 8.0f, FontStyle.Bold), paddedBounds, page.ForeColor);
}
private void updateAccBtn_Click(object sender, EventArgs e)
{
if (user.UpdateUser(userFirstNameTxt.Text, userLastNameTxt.Text, userEmailTxt.Text, userPhoneTxt.Text, currentUser.userName).Equals(""))
{
MessageBox.Show("User updated!");
}
else
{
MessageBox.Show("Error: " + user.UpdateUser(userFirstNameTxt.Text, userLastNameTxt.Text, userEmailTxt.Text, userPhoneTxt.Text, currentUser.userName), "Error in new user data");
}
}
private void usersGv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var cellindex = usersGv.SelectedCells[0].RowIndex;
// Get the UserName
var usernamecellcollection = usersGv.Rows[cellindex].Cells[0];
// Create the new tab
TabPage tp = new TabPage();
// Create the new control, pass the selected user to it
UserViewControl uvControl = new UserViewControl(usernamecellcollection.Value.ToString(), currentUser);
// Add the book control to the tab
tp.Controls.Add(uvControl);
// Size the book control
uvControl.Dock = DockStyle.Fill;
// Create the tab text
tp.Text = usernamecellcollection.Value.ToString() + ": (R-Click to close)";
// Add the tab
tabControl1.Controls.Add(tp);
// Select the tab
tabControl1.SelectedTab = tp;
}
private void changePassBtn_Click(object sender, EventArgs e)
{
string newPassStr = Interaction.InputBox("Please enter your new password", "New password", string.Empty, -1, -1);
if (newPassStr.Length > 6)
{
newPassStr = Interaction.InputBox("Please enter your new password again.", "New password", string.Empty, -1, -1);
user.ChangePassword(newPassStr, currentUser.userName);
MessageBox.Show("Your password has successfully been changed.");
}
else
{
MessageBox.Show("Invalid entry for password! Your password is not longer than 6 chars.","Invalid entry");
}
}
}
}
|
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Checks for enabled privileges in a token.</para>
/// <para type="description">This cmdlet does a privilege check for a token. The default it to pass a boolean indicating the privilege enable state.
/// You can specify PassResult to get the full result information.</para>
/// </summary>
/// <example>
/// <code>Test-NtTokenPrivilege SeTcbPrivilege</code>
/// <para>Checks if the current effective token has SeTcbPrivilege enabled.</para>
/// </example>
/// <example>
/// <code>Test-NtTokenPrivilege SeTcbPrivilege,SeDebugPrivilege</code>
/// <para>Checks if the current effective token has either SeTcbPrivilege or SeDebugPrivilege enabled.</para>
/// </example>
/// <example>
/// <code>Test-NtTokenPrivilege SeTcbPrivilege,SeDebugPrivilege -All</code>
/// <para>Checks if the current effective token has SeTcbPrivilege and SeDebugPrivilege enabled.</para>
/// </example>
/// <example>
/// <code>Test-NtTokenPrivilege SeTcbPrivilege,SeDebugPrivilege -PassResult</code>
/// <para>Checks if the current effective token has SeTcbPrivilege and SeDebugPrivilege enabled and pass on a result rather than just a boolean.</para>
/// </example>
[Cmdlet(VerbsDiagnostic.Test, "NtTokenPrivilege")]
[OutputType(typeof(bool), typeof(PrivilegeCheckResult))]
public sealed class TestNtTokenPrivilegeCmdlet : PSCmdlet
{
/// <summary>
/// <para type="description">Specify the token to test. If not specified uses the current effective token.</para>
/// </summary>
[Parameter]
public NtToken Token { get; set; }
/// <summary>
/// <para type="description">Specify an optional thread to test on.</para>
/// </summary>
[Parameter(Position = 0, ParameterSetName = "FromPrivilegeValue")]
public TokenPrivilegeValue[] PrivilegeValue { get; set; }
/// <summary>
/// <para type="description">Specify that all the privileges are required.</para>
/// </summary>
[Parameter]
public SwitchParameter All { get; set; }
/// <summary>
/// <para type="description">Specify to pass through the full check result, otherwise just return a boolean which indicates
/// whether the check succeeded.</para>
/// </summary>
[Parameter]
public SwitchParameter PassResult { get; set; }
private NtToken GetToken()
{
if (Token != null)
{
if (Token.IsPseudoToken)
return Token;
return Token.Duplicate(TokenAccessRights.Query);
}
return NtToken.OpenEffectiveToken();
}
/// <summary>
/// Overridden ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
using (var token = GetToken())
{
var result = token.PrivilegeCheck(PrivilegeValue, All);
if (PassResult)
WriteObject(result);
else
WriteObject(result.AllPrivilegesHeld);
}
}
}
}
|
/*
* cmd line param:
* /ActualStation:true -> real weather data
* /ActualStation:false -> simulated weather data
*/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Threading;
using IWx_Station;
/*
using Wx_Station; // requires reference to the assy
using Wx_Station_Sim; // requires reference to the assy
*/
using System.Reflection; // Assembly; compilation reqs ref to Microsoft.CSharp
namespace Wx_Client_Extended
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string[] m_cmdArgs = null;
ManualResetEvent m_mreRun = null;
// no longer need the IWxStation m_station decl. we have removed the prj ref.
dynamic m_station = null;
/* testing is now much easier because we swap in the simulator with a cmd line option */
public MainWindow()
{
InitializeComponent();
m_cmdArgs = Environment.GetCommandLineArgs();
if ((m_cmdArgs[1].Split(new char[]{ ':'})[1].Equals("true")))
{
/*
m_station = new WxStation(); // concrete instantiation; must consider thrown exceptions
*/
// using dynamics reqs that the build dir for the client have the needed dlls
// by default, VS copies any ref'd dlls to the build dir, typically \debug\bin.
// with dynamics, there is no longer any ref to the dll, so they are NOT copied to the \bin\debug dir.
Assembly dynamicAssembly = Assembly.LoadFrom("Wx_Station.dll");
Type type = dynamicAssembly.GetType("Wx_Station.WxStation");
m_station = Activator.CreateInstance(type);
}
else if ((m_cmdArgs[1].Split(new char[] { ':' })[1].Equals("false")))
{
/*
m_station = new WxStationSim(); // concrete instantiation; must consider thrown exceptions
*/
// we can remove the hard-coded strings by loading the desired dlls from a config file, cmd line param or data source.
Assembly dynamicAssembly = Assembly.LoadFrom("Wx_Station_Sim.dll");
Type type = dynamicAssembly.GetType("Wx_Station_Sim.WxStationSim");
m_station = Activator.CreateInstance(type);
}
// no intellisense on type dynamic; debugger won't step in unless there is a breakpoint there
m_station.Initialize();
// must cast because += operator can not be applied to type dynamic and method group
((IWxStation)m_station).ChangedTemperature += m_station_ChangedTemperature;
((IWxStation)m_station).ChangedWindDirection += m_station_ChangedWindDirection;
((IWxStation)m_station).ChangedWindSpeed +=m_station_ChangedWindSpeed;
((IWxStation)m_station).ChangedSetting += m_station_ChangedSetting;
// ManualResetEvent is a good way to avoid the bool bContinue = true; while (bContinue) { ... } snippet.
// WaitOne(int msec) returns false if reset/unsignaled and true if set/signaled.
m_mreRun = new ManualResetEvent(false);
}
/// <summary>
/// Wx Station raises event for this handler.
/// </summary>
/// <param name="setting"></param>
/// <param name="value"></param>
void m_station_ChangedSetting(string setting, string value)
{
string val = value.Substring(0, value.IndexOf('.') + 2);
switch (setting)
{
case "Temperature":
lblTemperature.Dispatcher.BeginInvoke((Action)(() => { lblTemperature.Content = val; }));
break;
case "WindSpeed":
lblWindSpeed.Dispatcher.BeginInvoke((Action)(() => { lblWindSpeed.Content = val; }));
break;
case "WindDirection":
lblWindDirection.Dispatcher.BeginInvoke((Action)(() => { lblWindDirection.Content = val; }));
break;
}
}
/// <summary>
/// Wx Station raises event for this handler.
/// </summary>
/// <param name="direction"></param>
void m_station_ChangedWindDirection(float direction)
{
lblWindDirection.Dispatcher.BeginInvoke((Action)(() => { lblWindDirection.Content = direction.ToString("0.0"); }));
}
/// <summary>
/// Wx Station raises event for this handler.
/// </summary>
/// <param name="speed"></param>
void m_station_ChangedWindSpeed(float speed)
{
lblWindSpeed.Dispatcher.BeginInvoke((Action)(() => { lblWindSpeed.Content = speed.ToString("0.0"); }));
}
/// <summary>
/// Wx Station raises event for this handler.
/// </summary>
/// <param name="temperature"></param>
void m_station_ChangedTemperature(float temperature)
{
lblTemperature.Dispatcher.BeginInvoke((Action)(() => { lblTemperature.Content = temperature.ToString("0.0"); }));
}
/// <summary>
/// tell the server that we are ready to receive data updates
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmdStart_Click(object sender, RoutedEventArgs e)
{
m_mreRun.Reset();
// Intellisense can not resolve dynamic types
(new Thread(new ThreadStart(() => { m_station.Run(); }))).Start();
cmdStop.IsEnabled = true;
cmdStart.IsEnabled = false;
}
/// <summary>
/// no longer interested in wx data
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cmdStop_Click(object sender, RoutedEventArgs e)
{
Stopping();
cmdStop.IsEnabled = false;
cmdStart.IsEnabled = true;
}
/// <summary>
/// client shutting down
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void WxClient_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Stopping();
}
/// <summary>
/// handle whether the program is shutting down or simply not interested in updated wx data
/// </summary>
private void Stopping()
{
// Intellisense can not resolve dynamic types
m_station.Quit();
m_mreRun.Set();
}
} // public partial class MainWindow : Window
} // namespace Wx_Client_Extended
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SignalR.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
services.AddHttpContextAccessor();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:63891", "http://localhost:50963").AllowCredentials();
}));
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticHttpContext();
app.UseCookiePolicy();
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<myHub>("/myHub");
});
}
}
public static class HttpContext
{
public static IHttpContextAccessor _accessor;
public static Microsoft.AspNetCore.Http.HttpContext Current => _accessor.HttpContext;
public static void Configure(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
}
}
|
//
// Node.cs:
//
//
// Author:
// Alexander Corrado (alexander.corrado@gmail.com)
// Andreia Gaita (shana@spoiledcat.net)
// Zoltan Varga <vargaz@gmail.com>
//
// Copyright (C) 2011 Novell Inc.
//
// 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.
using System;
using System.Collections.Generic;
//
// This class represents an XML node read from the output of gccxml
//
class Node {
// The XML element type
public string Type {
get; set;
}
// The value of the 'id' attribute
public string Id {
get; set;
}
// The value of the 'name' attribute or null
public string Name {
get; set;
}
// Attributes
public Dictionary<string, string> Attributes {
get; set;
}
// The children nodes of this node
public List<Node> Children {
get; set;
}
public string this [string key] {
get {
return Attributes [key];
}
}
// Maps ids to nodes
public static Dictionary<string, Node> IdToNode = new Dictionary <string, Node> ();
// For an attribute which contains an id, return the corresponding Node
public Node NodeForAttr (string attr) {
return IdToNode [Attributes [attr]];
}
public bool IsTrue (string key) {
return Attributes.ContainsKey (key) && Attributes[key] == "1";
}
public bool HasValue (string key) {
return Attributes.ContainsKey (key) && Attributes[key] != "";
}
public bool CheckValue (string key, string name) {
return Attributes.ContainsKey (key) && Attributes[key] == name;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FilmProjesi.Models
{
public class Film
{
public int Id { get; set; }
public string FilmName { get; set; }
public int? Year { get; set; }
public int? Duration { get; set; }
public double? IMDB { get; set; }
public string Content { get; set; }
public string Banner { get; set; }
public string Fragman { get; set; }
public int? CategoryId { get; set; }
public Category Category { get; set; }
public int? Lang_Id { get; set; }
public Language Language { get; set; }
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Business.Helper;
using eIVOGo.Helper;
using Model.InvoiceManagement;
using Model.Security.MembershipManagement;
using Utility;
using Uxnet.Web.WebUI;
using eIVOGo.Module.Common;
using Model.DataEntity;
namespace eIVOGo.Module.EIVO
{
public partial class ImportInvoiceCancellationPreview : ImportInvoicePreview
{
protected override void btnAddCode_Click(object sender, EventArgs e)
{
try
{
//檢核成功寫入資料庫
if (_mgr is GoogleInvoiceCancellationUploadManager && _mgr.Save())
{
//((GoogleInvoiceCancellationUploadManager)_mgr).ItemList.Where(i => i.Invoice.InvoiceBuyer.IsB2C()).Select(i => i.Invoice.InvoiceID).SendGoogleInvoiceCancellationMail();
((GoogleInvoiceCancellationUploadManager)_mgr).ItemList.Select(i => i.Invoice.InvoiceID).SendGoogleInvoiceCancellationMail();
Response.Redirect(NextAction.RedirectTo);
}
else
{
this.AjaxAlert("匯入失敗!!");
}
}
catch (Exception ex)
{
Logger.Error(ex);
this.AjaxAlert("匯入失敗,錯誤原因:" + ex.Message);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.IO;
using System.Configuration;
using System.Data;
using System.Collections;
using Leads;
using System.Data.Entity;
using System.Data.SqlClient;
using Leads.Models;
using System.Globalization;
namespace Leads.Models
{
public class Helper
{
public static List<GetAuthorizationForLeads_Result> GetAuthorizationforLeads<T>(string username, int appid)
where T : class
{
var db = new Cust_SilcoEntities();
List<GetAuthorizationForLeads_Result> authorizations = db.GetAuthorizationForLeads(username, appid).ToList();
return authorizations;
}
public static List<GetADGroups_Result> GetAD_Groups<T>(int appid) where T : class
{
var db = new Cust_SilcoEntities();
List<GetADGroups_Result> groups = db.GetADGroups(appid).ToList();
//foreach (var grp in groups)
//{
// grp.adsecuritygroupallowed
//}
// List<GetAuthorizationForLeads_Result> groups = db.GetAuthorizationForLeads(appid).ToList();
return groups;
}
public static List<GetYTDLeadsByDept_Result> GetYTDLeadsByDept<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetYTDLeadsByDept_Result> deptleadsYTD = sb.GetYTDLeadsByDept().ToList();
return deptleadsYTD;
}
public static List<GetYTDLeadsByEmp_Result> GetYTDLeadsByEmp<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetYTDLeadsByEmp_Result> empleadsYTD = sb.GetYTDLeadsByEmp().ToList();
return empleadsYTD;
}
public static List<GetYTDProspectsByEmp_Result> GetYTDProspectsByEmp<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetYTDProspectsByEmp_Result> empleadsYTD = sb.GetYTDProspectsByEmp().ToList();
return empleadsYTD;
}
public static List<GetTypesCustomer_Result> GetCustomerType1<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetTypesCustomer_Result> custtype = sb.GetTypesCustomer("N").ToList();
return custtype;
}
public static List<GetBranch_Result> GetBranch<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetBranch_Result> branch = sb.GetBranch("N").ToList();
return branch;
}
public static List<GetTaxGroups_Result> GetTaxGroups<T>(string branchid) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetTaxGroups_Result> taxgroup = sb.GetTaxGroups("N", branchid).ToList();
return taxgroup;
}
public static List<GetSilcoSystemsServices_Result> GetSilcoSystemServices<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetSilcoSystemsServices_Result> systems = sb.GetSilcoSystemsServices("1").ToList();
return systems;
}
public static List<GetSilcoSystemsServicesExistCust_Result> GetSilcoSystemServicesExistCust<T>(string customernumber, string sitenumber, string strsystems, int strstatus)
where T : class
{
var sb = new Cust_SilcoEntities();
List<GetSilcoSystemsServicesExistCust_Result> existsystems = sb.GetSilcoSystemsServicesExistCust(customernumber, sitenumber, strsystems, strstatus).ToList();
return existsystems;
}
// public static List<InsLeadsHdr_Result> InsLeadsHdr <T>(string pfillLead, string pcustname, string pcustaddress) where T : class
public static List<InsLeadsHdr_Result> InsLeadsHdr<T>(LeadViewModel lead) where T : class
{
//string pfillLead = "";
// string pcustomercode = "";
//int pcustomerid = 0;
//string pcustaddress = "";
//string pcustname = "";
var sb = new Cust_SilcoEntities();
List<InsLeadsHdr_Result> inslead = sb.InsLeadsHdr(lead.FillLead, "", 0, lead.CustName, lead.CustAddress, lead.CustCity, lead.CustState, lead.CustZip, 0, "", lead.SiteName,
lead.SiteAddress, lead.SiteCity, lead.SiteState, lead.SiteZip, lead.ContactPersonName, lead.ContactEmail, lead.ContactCellPhone, lead.ContactOfficePhone, lead.CustTypeId, lead.createdby, lead.leadNotes, lead.BranchId, lead.TaxId
, lead.ldcustsystem1, lead.ldcustsystem2, lead.ldcustsystem3, lead.ldcustsystem4, lead.ldcustsystem5, lead.ldcustsystem6, lead.ldcustsystem7, lead.ldcustsystem8, lead.ldcustsystem9, lead.leadno, lead.sscompcode, lead.ldcustsystem10, lead.ldcustsystem11, lead.ldcustsystem12, lead.displayname).ToList();
//List<GetSilcoSystemsServices_Result> systems = sb.GetSilcoSystemsServices("1").ToList();
//
return inslead;
}
public static List<InsExistLeadsHdr_Result> InsExistLeadsHdr<T>(LeadCustExistViewModel lead) where T : class
{
var sb = new Cust_SilcoEntities();
//List<InsLeadsHdr_Result> inslead = sb.InsLeadsHdr(lead.FillLead, "", 0, lead.CustName, lead.CustAddress, lead.CustCity, lead.CustState, lead.CustZip, 0, "", lead.SiteName,
// lead.SiteAddress, lead.SiteCity, lead.SiteState, lead.SiteZip, lead.ContactPersonName, lead.ContactEmail, lead.ContactCellPhone, lead.ContactOfficePhone, lead.CustTypeId, "", lead.leadNotes, lead.BranchId, lead.TaxId
// , lead.ldcustsystem1, lead.ldcustsystem2, lead.ldcustsystem3, lead.ldcustsystem4, lead.ldcustsystem5, lead.ldcustsystem6, lead.ldcustsystem7, lead.ldcustsystem8, lead.ldcustsystem9, lead.leadno).ToList();
lead.leadno = "1";
// List<InsExistLeadsHdr_Result> inslead = sb.InsExistLeadsHdr(lead.CustomerCode, lead.CustName, lead.sitenumber, lead.SiteName, lead.leadno).ToList();
List<InsExistLeadsHdr_Result> inslead = sb.InsExistLeadsHdr(lead.CustomerCode, lead.CustName, lead.sitenumber, lead.SiteName, lead.leadno, lead.FillLead, lead.ContactPersonName, lead.ContactEmail, lead.ContactCellPhone, lead.ContactOfficePhone, lead.createdby, lead.leadNotes, lead.ldcustsystem1,
lead.ldcustsystem2, lead.ldcustsystem3, lead.ldcustsystem4, lead.ldcustsystem5, lead.ldcustsystem6, lead.ldcustsystem7, lead.ldcustsystem8, lead.ldcustsystem9, lead.sscompcode, lead.ldcustsystem10, lead.ldcustsystem11, lead.ldcustsystem12, lead.displayname).ToList();
//lead.FillLead,
// lead.CustomerCode, lead.CustName,
// lead.SiteCode, lead.SiteName
// // lead.ContactPersonName, lead.ContactEmail, lead.ContactCellPhone, lead.ContactOfficePhone,
//// "",lead.leadNotes,
// // lead.ldcustsystem1, lead.ldcustsystem2, lead.ldcustsystem3, lead.ldcustsystem4, lead.ldcustsystem5, lead.ldcustsystem6, lead.ldcustsystem7, lead.ldcustsystem8, lead.ldcustsystem9
// , lead.leadno).ToList();
return inslead;
}
public static List<SilcoCustomerSrch_Result> SilcoCustomerSrch<T>(string searchtext, int searchcode) where T : class
{
// var sl = new Silco_FinalEntities();
var sb = new Cust_SilcoEntities();
List<SilcoCustomerSrch_Result> srch = sb.SilcoCustomerSrch(searchtext, searchcode, null, "N", null, null, "Y", "N").ToList();
// List<SilcoCustomerSrch_Result> srch = sl.Customer_Search(searchtext, searchcode, null, "N", null, null, "Y", "N").ToList();
return srch;
}
public static List<GetLeads_Result> SavedLeadSearch<T>(string pstatus, string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetLeads_Result> svld = sb.GetLeads(puser, pstatus).ToList();
return svld;
}
public static List<UpdateLeadHdr_Result> UpdateLeadHdr<T>(SaveViewModel lead) where T : class
{
var sb = new Cust_SilcoEntities();
List<UpdateLeadHdr_Result> updlead = sb.UpdateLeadHdr(lead.FillLead, lead.CustomerCode, Convert.ToInt16(lead.CustomerID), lead.CustName, lead.CustAddress, lead.CustCity,
lead.CustState, lead.CustZip, lead.SiteID, lead.SiteCode, lead.SiteName, lead.SiteAddress, lead.SiteCity, lead.SiteState, lead.SiteZip, lead.ContactPersonName,
lead.ContactEmail, lead.ContactCellPhone, lead.ContactOfficePhone, lead.CustTypeId, lead.createdby, lead.leadNotes, lead.BranchId, lead.TaxId, lead.ldcustsystem1,
lead.ldcustsystem2, lead.ldcustsystem3, lead.ldcustsystem4, lead.ldcustsystem5, lead.ldcustsystem6, lead.ldcustsystem7, lead.ldcustsystem8, lead.ldcustsystem9,
lead.leadno, lead.leadhdrid, lead.sscompcode, lead.ldcustsystem10, lead.ldcustsystem11, lead.ldcustsystem12).ToList();
return updlead;
}
public static List<GetSilcoSystemsServicesSavedLead_Result> GetSilcoSystemsServicesSavedLead<T>(int leadhdrid, string customernumber, string sitenumber, string strsystems, int strstatus)
where T : class
{
var sb = new Cust_SilcoEntities();
List<GetSilcoSystemsServicesSavedLead_Result> existsystems = sb.GetSilcoSystemsServicesSavedLead(leadhdrid, customernumber, sitenumber, strsystems, strstatus).ToList();
return existsystems;
}
public static List<GetSilcoSystemsSubmitted_Result> GetSilcoSystemsSubmitted<T>(int leadhdrid, string customernumber, string sitenumber, string strsystems, int strstatus)
where T : class
{
var sb = new Cust_SilcoEntities();
List<GetSilcoSystemsSubmitted_Result> existsystems = sb.GetSilcoSystemsSubmitted(leadhdrid, customernumber, sitenumber, strsystems, strstatus).ToList();
return existsystems;
}
//public static List<GetSilcoSystemsServicesSavedLead_Result> GetSilcoSystemsServicesSLead<T>(int leadhdrid, string customernumber, string sitenumber, string strsystems, int strstatus)
// where T : class
//{
// var sb = new Cust_SilcoEntities();
// List<GetSilcoSystemsServicesSavedLead_Result> existsystems = sb.GetSilcoSystemsServicesSavedLead(leadhdrid, customernumber, sitenumber, strsystems, strstatus).ToList();
// return existsystems;
//}
public static List<GetProspects_Result> ProspectList<T>(string pstatus, string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspects_Result> proplist = sb.GetProspects(puser, pstatus).ToList();
return proplist;
}
public static List<GetProspectsDtl_Result> ProspectDtlList<T>(string puser, int leadhdrid, string source, int prospectno) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid, source, prospectno).ToList();
return proplist;
}
public static List<GetProspectsRetired_Result> ProspectListRetired<T>(string pstatus, string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectsRetired_Result> proplist = sb.GetProspectsRetired(puser, pstatus).ToList();
return proplist;
}
public static List<GetCCLeadsEmail_Result> GetCCLeadsEmail<T>(int leadhdrid) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetCCLeadsEmail_Result> cc = sb.GetCCLeadsEmail(leadhdrid).ToList();
return cc;
}
public static List<GetProspectStatus_Result> GetProspectStatus<T>() where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectStatus_Result> propsts = sb.GetProspectStatus().ToList();
// List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid).ToList();
return propsts;
// public static List<GetBranch_Result> GetBranch<T>() where T : class
//
// {
// var sb = new Cust_SilcoEntities();
// List<GetBranch_Result> branch = sb.GetBranch("N").ToList();
// return branch;
// }
}
//public static List<UpdateProspect_Result> UpdateProspect<T>(int leadhdrid, int prospectno, int holdsystem, int prospstatus, int assgn) where T : class
//{
// var sb = new Cust_SilcoEntities();
// {
// List<UpdateProspect_Result> updprsp = sb.UpdateProspect(leadhdrid, prospectno, holdsystem, prospstatus, assgn).ToList();
// return updprsp;
// }
//}
public static List<UpdateProspect_Result> ProcessProspect(int leadhdrid, int prospectno, int prstatus, int assgn, string lastupdatedby, string note, int action, string actiondate, string source)
{
var sb = new Cust_SilcoEntities();
// bool success = false;
string oldassgnemail = "";
List<UpdateProspect_Result> updprsp = sb.UpdateProspect(leadhdrid, prospectno, prstatus, assgn, lastupdatedby, note, action, actiondate, oldassgnemail, source).ToList();
// success = true;
return updprsp;
}
public static List<UpdateProspectManual_Result> ProcessProspectManual(int leadhdrid, int prospectno, int prstatus, int assgn, string lastupdatedby, string note, int action, string actiondate, string source)
{
var sb = new Cust_SilcoEntities();
// bool success = false;
string oldassgnemail = "";
List<UpdateProspectManual_Result> updprspmanual = sb.UpdateProspectManual(leadhdrid, prospectno, prstatus, assgn, lastupdatedby, note, action, actiondate, oldassgnemail, source).ToList();
// success = true;
return updprspmanual;
}
public static List<GetProspectAssignment_Result> GetProspectAssignment<T>(string user, int branch) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectAssignment_Result> propsts = sb.GetProspectAssignment(user, branch).ToList();
// List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid).ToList();
return propsts;
// public static List<GetBranch_Result> GetBranch<T>() where T : class
//
// {
// var sb = new Cust_SilcoEntities();
// List<GetBranch_Result> branch = sb.GetBranch("N").ToList();
// return branch;
// }
}
public static List<GetSilcoSystemsForPay_Result> GetSilcoSystemsForPay<T>(string pdisplay) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetSilcoSystemsForPay_Result> paysys = sb.GetSilcoSystemsForPay(pdisplay).ToList();
// List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid).ToList();
return paysys;
// public static List<GetBranch_Result> GetBranch<T>() where T : class
//
// {
// var sb = new Cust_SilcoEntities();
// List<GetBranch_Result> branch = sb.GetBranch("N").ToList();
// return branch;
// }
}
public static List<GetLeadFee_Result> GetLeadFee<T>(decimal amount) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetLeadFee_Result> leadfee = sb.GetLeadFee(amount).ToList();
// List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid).ToList();
return leadfee;
}
public static List<InsertLeadPay_Result> InsertLeadPay<T>(int leadhdrid, string custsystemcode, decimal qualsalesamt, string ldpaynotes, decimal leadfeeamt, int prospectno, int leadno, string newjob, string jobno, string doubleleadfee, string user) where T : class
{
var sb = new Cust_SilcoEntities();
List<InsertLeadPay_Result> pay = sb.InsertLeadPay(leadhdrid, custsystemcode, qualsalesamt, ldpaynotes, leadfeeamt, prospectno, leadno, newjob, jobno, doubleleadfee, user).ToList();
// List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid).ToList();
return pay;
}
public static List<GetCCPayLeadsEmail_Result> GetCCPayLeadsEmail<T>(int ldpayid) where T : class
{
// string toEmail = "";
// string ccEmail = "";
var sb = new Cust_SilcoEntities();
var email = sb.GetCCPayLeadsEmail(ldpayid).ToList();
// List<InsertLeadPay_Result> pay = sb.InsertLeadPay(leadhdrid, custsystemcode, qualsalesamt, ldpaynotes, leadfeeamt, prospectno, leadno, newjob, jobno, doubleleadfee, user).ToList();
// List<GetProspectsDtl_Result> proplist = sb.GetProspectsDtl(puser, leadhdrid).ToList();
return email;
}
public static List<GetPayHistory_Result> GetPayHistory<T>(int leadhdrid, int prospectno) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetPayHistory_Result> proplist = sb.GetPayHistory(leadhdrid, prospectno).ToList();
return proplist;
}
public static List<GetProspectNotes_Result> GetProspectNotes<T>(int leadhdrid, int prospectno) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectNotes_Result> proplist = sb.GetProspectNotes(leadhdrid, prospectno).ToList();
return proplist;
}
public static List<GetProspectsSM_Result> ProspectSMList<T>(string pstatus, string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectsSM_Result> proplist = sb.GetProspectsSM(puser, pstatus).ToList();
return proplist;
}
public static List<GetProspectsDtlSM_Result> ProspectDtlSMList<T>(string puser, int leadhdrid, int prospectno) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetProspectsDtlSM_Result> proplist = sb.GetProspectsDtlSM(puser, leadhdrid, prospectno).ToList();
return proplist;
}
public static List<ProcessProspectHdr_Result> ProcessProspectHdr<T>(IndProspect prp) where T : class
{
// DateTime nwadate = DateTime.ParseExact(prp.nextactiondate, "yyyy-MMdd", CultureInfo.InvariantCulture);
var sb = new Cust_SilcoEntities();
List<ProcessProspectHdr_Result> updprop = sb.ProcessProspectHdr(prp.prospecthdrid, prp.CustName, prp.ContactPersonName, prp.createuser,
prp.nextactiondate, prp.BranchId, prp.ContactEmail, prp.ContactCellPhone, prp.ContactOfficePhone, prp.prospectstatusid, prp.CustAddress, prp.CustCity,
prp.CustState, prp.CustZip, prp.originid).ToList();
return updprop;
}
public static List<ProcessProspectSystems_Result> ProcessProspectSystems<T>(IndProspectSystems prsystem) where T : class
{
// DateTime nwadate = DateTime.ParseExact(prp.nextactiondate, "yyyy-MMdd", CultureInfo.InvariantCulture);
var sb = new Cust_SilcoEntities();
List<ProcessProspectSystems_Result> updprop = sb.ProcessProspectSystems(prsystem.createuser, prsystem.systems, prsystem.code, prsystem.month, prsystem.prospectno.ToString(), prsystem.prospecttype).ToList();
return updprop;
}
public static List<DeleteProspectSystems_Result> DeleteProspectSystems<T>(DelProspectSystems delsys)
{
// DateTime nwadate = DateTime.ParseExact(prp.nextactiondate, "yyyy-MMdd", CultureInfo.InvariantCulture);
var sb = new Cust_SilcoEntities();
List<DeleteProspectSystems_Result> delprop = sb.DeleteProspectSystems(delsys.prospectno, delsys.month, delsys.systems).ToList();
return delprop;
}
public static List<SelectSystemsforAddedProspects_Result> SelectSystemsforAddedProspects<T>(int prpprospectno) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSystemsforAddedProspects_Result> addprop = sb.SelectSystemsforAddedProspects(prpprospectno.ToString()).ToList();
return addprop;
}
public static List<GetOrigin_Result> GetOrigin<T>(string ptype) where T : class
{
var sb = new Cust_SilcoEntities();
List<GetOrigin_Result> origin = sb.GetOrigin(ptype).ToList();
return origin;
}
public static List<SelectSiteforMasterLookup_Result> SelectSiteforMasterLookup<T>(string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteforMasterLookup_Result> sitelookuplist = sb.SelectSiteforMasterLookup(puser).ToList();
return sitelookuplist;
}
public static List<SelectSiteDtlsforMasterLookup_Result> SelectSiteDtlsforMasterLookup<T>(int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteDtlsforMasterLookup_Result> dtls = sb.SelectSiteDtlsforMasterLookup(siteid, customerid).ToList();
return dtls;
}
public static List<SelectSiteDtlsforMasterLookupInsp_Result> SelectSiteDtlsforMasterLookupInsp<T>(int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteDtlsforMasterLookupInsp_Result> insps = sb.SelectSiteDtlsforMasterLookupInsp(siteid, customerid).ToList();
return insps;
}
public static List<SelectSiteDtlsforMasterLookupRMR_Result> SelectSiteDtlsforMasterLookupRMR<T>(int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteDtlsforMasterLookupRMR_Result> rmrs = sb.SelectSiteDtlsforMasterLookupRMR(siteid, customerid).ToList();
return rmrs;
}
public static List<SelectSiteDtlsforMasterLookupContact_Result> SelectSiteDtlsforMasterLookupContact<T>(int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteDtlsforMasterLookupContact_Result> contacts = sb.SelectSiteDtlsforMasterLookupContact(siteid, customerid).ToList();
return contacts;
}
public static List<UpdateSiteLog_Result> UpdateSiteLog<T>(string account, int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<UpdateSiteLog_Result> updlog = sb.UpdateSiteLog(account, siteid, customerid).ToList();
return updlog;
}
public static List<SelectSiteforMasterLookupGeneralManager_Result> SelectSiteforMasterLookupGeneralManager<T>(string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteforMasterLookupGeneralManager_Result> sitelookuplist = sb.SelectSiteforMasterLookupGeneralManager(puser).ToList();
return sitelookuplist;
}
public static List<SelectSiteforMasterLookupKitchen_Result> SelectSiteforMasterLookupKitchen<T>(string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteforMasterLookupKitchen_Result> sitelookuplist = sb.SelectSiteforMasterLookupKitchen(puser).ToList();
return sitelookuplist;
}
public static List<SelectSiteforMasterLookupServManager_Result> SelectSiteforMasterLookupServManager<T>(string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteforMasterLookupServManager_Result> sitelookuplist = sb.SelectSiteforMasterLookupServManager(puser).ToList();
return sitelookuplist;
}
public static List<SelectSiteforPRLookupServManager_Result> SelectSiteforPRLookupServManager<T>(string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteforPRLookupServManager_Result> PRlist = sb.SelectSiteforPRLookupServManager(puser).ToList();
return PRlist;
}
public static List<SelectSiteforPRLookupGeneralManager_Result> SelectSiteforPRLookupGeneralManager<T>(string puser) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteforPRLookupGeneralManager_Result> PRlookuplist = sb.SelectSiteforPRLookupGeneralManager(puser).ToList();
return PRlookuplist;
}
public static List<UpdatePRListLog_Result> UpdatePRListLog<T>(string account, int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<UpdatePRListLog_Result> updlog = sb.UpdatePRListLog(account, siteid, customerid).ToList();
return updlog;
}
public static List<FindSecurity_Result> FindSecurity<T>(int appid, string title, string dept, string account) where T : class
{
var sb = new Cust_SilcoEntities();
List<FindSecurity_Result> seclist = sb.FindSecurity(appid, title, dept, account).ToList();
return seclist;
}
public static List<SelectSiteDtlsforMasterLookupInv_Result> SelectSiteDtlsforMasterLookupInv<T>(int siteid, int customerid) where T : class
{
var sb = new Cust_SilcoEntities();
List<SelectSiteDtlsforMasterLookupInv_Result> invlist = sb.SelectSiteDtlsforMasterLookupInv(siteid, customerid).ToList();
return invlist;
}
public static List<UpdateProspectDetailsUsingHome_Result> UpdateProspectDetailUsingHome( int leadhdrid, int prospectno, int assgn, string lastupdatedby, int status, string rsgnprospcustname, string rsgnprospcustaddress,
string rsgnprospcustcity, string rsgnprospcuststate, string rsgnprospcustzip, string rsgnprospcontact, string rsgnprospemail, string rsgnprospofficephone, string rsgnprospcellphone,
string rsgnprospsitename, string rsgnprospsiteaddress, string rsgnprospsitecity, string rsgnprospsitestate, string rsgnprospsitezip, string rsgnprosptype)
{
var sb = new Cust_SilcoEntities();
// bool success = false;
//string oldassgnemail = "";
List<UpdateProspectDetailsUsingHome_Result> updprspmanual = sb.UpdateProspectDetailsUsingHome(leadhdrid, prospectno, status, assgn, lastupdatedby, " ", rsgnprospcustname, rsgnprospcustaddress,
rsgnprospcustcity, rsgnprospcuststate, rsgnprospcustzip, rsgnprospcontact, rsgnprospemail, rsgnprospofficephone, rsgnprospcellphone, rsgnprospsitename, rsgnprospsiteaddress, rsgnprospsitecity, rsgnprospsitestate, rsgnprospsitezip, rsgnprosptype).ToList();
//
return updprspmanual;
}
public static List<UpdateLeadDetailsUsingHome_Result> UpdateLeadDetailsUsingHome(int leadhdrid, int prospectno, int assgn, string lastupdatedby, int status, string rsgnprospcustname, string rsgnprospcustaddress,
string rsgnprospcustcity, string rsgnprospcuststate, string rsgnprospcustzip, string rsgnprospcontact, string rsgnprospemail, string rsgnprospofficephone, string rsgnprospcellphone,
string rsgnprospsitename, string rsgnprospsiteaddress, string rsgnprospsitecity, string rsgnprospsitestate, string rsgnprospsitezip , string rsgnprosptype)
{
var sb = new Cust_SilcoEntities();
// bool success = false;
string oldassgnemail = "";
List<UpdateLeadDetailsUsingHome_Result> updprsp = sb.UpdateLeadDetailsUsingHome (leadhdrid, prospectno, status, assgn, lastupdatedby, oldassgnemail, rsgnprospcustname, rsgnprospcustaddress,
rsgnprospcustcity, rsgnprospcuststate, rsgnprospcustzip, rsgnprospcontact, rsgnprospemail, rsgnprospofficephone, rsgnprospcellphone, rsgnprospsitename, rsgnprospsiteaddress, rsgnprospsitecity, rsgnprospsitestate, rsgnprospsitezip, rsgnprosptype).ToList();
return updprsp;
}
// pr.leadhdrid, pr.prospectno, pr.status, pr.lastupdatedby, pr.prospectnote, pr.prospaction, pr.source, pr.actiondate
public static List<UpdateLeadActionUsingHome_Result> UpdateLeadActionUsingHome(int leadhdrid, int prospectno, string lastupdatedby, int prstatus, string note, int action, string actiondate)
{
var sb = new Cust_SilcoEntities();
List<UpdateLeadActionUsingHome_Result> updleadnote = sb.UpdateLeadActionUsingHome(leadhdrid, prospectno, lastupdatedby, prstatus, note, action, actiondate ).ToList();
return updleadnote;
}
public static List<UpdateProspectActionUsingHome_Result> UpdateProspectActionUsingHome( int leadhdrid, int prospectno, string lastupdatedby, int prstatus, string note, int action, string actiondate)
{
var sb = new Cust_SilcoEntities();
// bool success = false;
// string oldassgnemail = "";
List<UpdateProspectActionUsingHome_Result> updprospnote = sb.UpdateProspectActionUsingHome(leadhdrid, prospectno, lastupdatedby, prstatus, note, action, actiondate).ToList();
return updprospnote;
}
public static List<UpdateLeadUsingDept_Result> UpdateLeadUsingDept(string leadhdrid, string prospectno , int status, int assgn, string puser , string source)
{
var sb = new Cust_SilcoEntities();
List<UpdateLeadUsingDept_Result> upddept = sb.UpdateLeadUsingDept( leadhdrid, prospectno, status, assgn, puser, source).ToList();
return upddept;
}
}
}
//}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Application.Command;
using Application.DTO;
using Application.Exceptions;
using EFDataAccess;
using Microsoft.EntityFrameworkCore;
namespace EFCommands
{
public class EfGetPostCommand : EfBaseCommand, IGetPostCommand
{
public EfGetPostCommand(BlogContext context) : base(context)
{
}
public PostDto Execute(int request)
{
var post = Context.Posts.Find(request); //mvc nece da napravi normalan action link, tj ne prosledjuje id iako je genericki...
if (post == null)
throw new EntityNotFoundException("Wanted post not found!");
if (post.IsDeleted == true)
throw new EntityNotFoundException("Wanted post is long time no see!");
var ptag = Context.PostTags.Find(request);
var tagovi = Context.Tag.Find(ptag.Tag);
var t = tagovi.Content.AsQueryable();
var tengovi = Context.Tag.AsQueryable();
//tengovi = tengovi.Include(pt => pt.PostTags).ThenInclude(p => p.Post).Where(t=> t.PostTags == p=> p.Post.PosTags)
return new PostDto
{
id = post.Id,
Name = post.Name,
Description = post.Description
//TagsName = t
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SolidPrinciples.OCP
{
public interface IDiscountCalculate
{
bool Rule(string ruleName);
double Calculate(int amount);
}
}
|
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.IO;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Text;
using Microsoft.Extensions.Configuration;
namespace WebApplication.Web.Utilities
{
public static class Utility
{
#region Get App Settings
/// <summary>
/// Gets the application settings.
/// </summary>
/// <param name="keyName">Name of the key.</param>
/// <returns></returns>
public static string GetAppSettings(string keyName)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
// Add "appsettings.json" to bootstrap EF config.
.AddJsonFile("appsettings.json")
// Add the EF configuration provider, which will override any
// config made with the JSON provider.
.Build();
var returnvalues = config[string.Format("{0}:{1}", "KeySettings", keyName)];
return returnvalues;
}
#endregion
#region Convert to bool
public static bool GetBool(object value)
{
bool result = false;
if (value != null)
{
bool.TryParse(value.ToString(), out result);
}
return result;
}
#endregion
#region Get Nullable bool
public static bool? GetNullablebool(object value)
{
bool? nullableResult = null;
bool result;
if (value != null && !string.IsNullOrEmpty(value.ToString()))
{
nullableResult = bool.TryParse(value.ToString(), out result) ? result : (bool?)null;
}
return nullableResult;
}
#endregion
#region Convert to Long
public static long GetLong(this object value)
{
long result = 0;
if (value != null)
{
long.TryParse(value.ToString(), out result);
}
return result;
}
#endregion
#region Convert to Int
public static int GetInt(object value)
{
int result = 0;
if (value != null)
{
int.TryParse(value.ToString(), out result);
}
return result;
}
#endregion
#region Convert to Byte
public static byte GetByte(object value)
{
byte result = 0;
if (value != null)
{
byte.TryParse(value.ToString(), out result);
}
return result;
}
#endregion
#region Convert To Guid
public static Guid ConvertToGuid(object p)
{
Guid _retValue = Guid.Empty;
if (p != null)
{
Guid.TryParse(p.ToString(), out _retValue);
}
return _retValue;
}
#endregion
#region Convert to Short
public static short GetShort(object value)
{
short result = 0;
if (value != null)
{
short.TryParse(value.ToString(), out result);
}
return result;
}
#endregion
#region Convert to DateTime
/// <summary>
/// Convert to double.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static DateTime GetDateTime(object value)
{
DateTime result = new DateTime();
if (value != null)
{
DateTime.TryParse(value.ToString(), out result);
}
return result;
}
#endregion
#region Create Salt
/// <summary>
/// Creates the salt.
/// </summary>
/// <param name="saltSize">Size of the salt.</param>
/// <returns></returns>
public static string CreateSalt(int saltSize)
{
var rng = RandomNumberGenerator.Create();
var buff = new byte[saltSize];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
#endregion
#region EncryptPassword
/// <summary>
/// Encrypts the password.
/// </summary>
/// <param name="pPassword">The password.</param>
/// <param name="pSalt">The salt.</param>
/// <returns></returns>
public static string EncryptPassword(string pPassword, string pSalt)
{
return string.Join("", SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(string.Concat(pPassword, pSalt))).Select(x => x.ToString("X2"))).ToLower();
}
#endregion
#region Get Content Type by Extension
/// <summary>
/// Returns the extension.
/// </summary>
/// <param name="fileExtension">The file extension.</param>
/// <returns></returns>
public static string GetContentTypeByExtension(string fileExtension)
{
switch (fileExtension)
{
case "htm":
case "html":
case "log":
return "text/HTML";
case "txt":
return "text/plain";
case "docx":
case "doc":
return "application/ms-word";
case "tiff":
case "tif":
return "image/tiff";
case "asf":
return "video/x-ms-asf";
case "avi":
return "video/avi";
case "zip":
return "application/zip";
case "xlsx":
case "xls":
return "application/xls";
case "csv":
return "application/vnd.ms-excel";
case "gif":
return "image/gif";
case "jpg":
return "image/jpg";
case "jpeg":
return "image/jpeg";
case "bmp":
return "image/bmp";
case "png":
return "image/png";
case "pjpeg":
return "image/pjpeg";
case "wav":
return "audio/wav";
case "mp3":
return "audio/mpeg3";
case "mpg":
case "mpeg":
return "video/mpeg";
case "rtf":
return "application/rtf";
case "asp":
return "text/asp";
case "pdf":
return "application/pdf";
case "fdf":
return "application/vnd.fdf";
case "pps":
case "pptx":
case "ppt":
return "application/mspowerpoint";
case "dwg":
return "image/vnd.dwg";
case "msg":
return "application/msoutlook";
case "xml":
case "sdxl":
return "application/xml";
case "xdp":
return "application/vnd.adobe.xdp+xml";
default:
return "application/octet-stream";
}
}
#endregion
#region Convert to decimal 2 Digits
public static decimal GetDecimal2Digits(object Value)
{
decimal result = decimal.MinValue;
if (Value != null)
{
decimal.TryParse(Value.ToString(), out result);
result = Math.Round(result, 2, MidpointRounding.AwayFromZero);
decimal.TryParse(result.ToString("#.00"), out result);
}
return result;
}
#endregion
#region Convert to decimal 3 Digits
public static decimal GetDecimal3Digits(object Value)
{
decimal result = decimal.MinValue;
if (Value != null)
{
decimal.TryParse(Value.ToString(), out result);
result = Math.Round(result, 3, MidpointRounding.AwayFromZero);
decimal.TryParse(result.ToString("#.000"), out result);
}
return result;
}
#endregion
#region Convert Time Zone
public static DateTime ConvertTimeZone(DateTime value, string timezone)
{
TimeZoneInfo _estTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timezone);
DateTime _timeTobeConverted = DateTime.SpecifyKind(value, DateTimeKind.Unspecified);
DateTime _time = TimeZoneInfo.ConvertTime(_timeTobeConverted, _estTimeZone);
return _time;
}
#endregion
#region Get Is Checked
/// <summary>
/// Get Is Checked
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool GetIsChecked(object value)
{
bool result = false;
if (value != null)
{
result = value.ToString().Contains("true");
}
return result;
}
#endregion
#region Remove special Characters from string
public static string RemoveSpecialCharactersForTitle(string stringName)
{
if (!string.IsNullOrEmpty(stringName))
{
stringName = stringName.Replace("#", "");
stringName = stringName.Replace("@", "");
stringName = stringName.Replace("$", "");
stringName = stringName.Replace("/", "");
stringName = stringName.Replace(",", "");
stringName = stringName.Replace("(", "");
stringName = stringName.Replace(")", "");
stringName = stringName.Replace(".", "");
stringName = stringName.Replace("'", "");
stringName = stringName.Replace("’", "");
stringName = stringName.Replace("-", "");
stringName = stringName.Replace("*", "");
stringName = stringName.Replace("+", "");
stringName = stringName.Replace("[", "");
stringName = stringName.Replace("]", "");
stringName = stringName.Replace("\\", "");
stringName = stringName.Replace("\"", "");
stringName = stringName.Replace("!", "");
stringName = stringName.Replace("|", "");
stringName = stringName.Replace("^", "");
stringName = stringName.Replace("&", "");
stringName = stringName.Replace("_", "");
stringName = stringName.Replace("=", "");
stringName = stringName.Replace("?", "");
stringName = stringName.Replace("~", "");
stringName = stringName.Replace("`", "");
stringName = stringName.Replace(";", "");
stringName = stringName.Replace(":", "");
}
return stringName;
}
#endregion
#region Get Tax Year value for DropDown
/// <summary>
/// Get Tax Year value for DropDown
/// </summary>
/// <returns></returns>
public static List<SelectListItem> GetTaxYearsForDropDown()
{
var currentTaxyear = GetInt("2016");
var dropdownitems = new List<SelectListItem>();
for (int year = currentTaxyear; year >= currentTaxyear - 1; year--)
{
dropdownitems.Add(new SelectListItem { Text = year.ToString(), Value = year.ToString(), Selected = (2016 == year) });
}
return dropdownitems;
}
#endregion
#region Create Random Number
/// <summary>
/// Creating the Random Number
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static int RandomNumber(int min, int max)
{
var random = new Random();
//returns the generated Number
return random.Next(min, max);
}
#endregion
#region Remove Hiphen And Brackets
/// <summary>
/// Removes the hiphen.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static string RemoveSpecialChars(string value)
{
if (!string.IsNullOrEmpty(value))
{
value = value.Replace("-", "");
value = value.Replace("(", "");
value = value.Replace(")", "");
value = value.Replace(" ", "");
}
return value;
}
#endregion
#region Get Full Name
public static string GetFullName(string FirstName, string MiddleIntial, string LastName, string Suffix)
{
string fullName = string.Empty;
if (!string.IsNullOrWhiteSpace(FirstName))
{
fullName = FirstName.Trim();
}
if (!string.IsNullOrWhiteSpace(MiddleIntial))
{
fullName += (" " + MiddleIntial.Trim());
}
if (!string.IsNullOrWhiteSpace(LastName))
{
fullName += (" " + LastName.Trim());
}
if (!string.IsNullOrWhiteSpace(Suffix))
{
fullName += (" " + Suffix.Trim());
}
return !string.IsNullOrWhiteSpace(fullName) ? fullName.Trim() : string.Empty;
}
#endregion
#region To Trim and Lower
public static string ToLowerTrim(this string str)
{
if (str != null)
{
return str.Trim().ToLower();
}
return string.Empty;
}
#endregion
#region Remove special Characters from string
/// <summary>
/// Remove special Characters from string
/// </summary>
/// <param name="stringName"></param>
/// <returns></returns>
public static string RemoveSpecialCharactersAndTrim(string stringName)
{
if (!string.IsNullOrEmpty(stringName))
{
stringName = stringName.Replace("#", "");
stringName = stringName.Replace("@", "");
stringName = stringName.Replace("$", "");
stringName = stringName.Replace("/", "");
stringName = stringName.Replace(",", "");
stringName = stringName.Replace("(", "");
stringName = stringName.Replace(")", "");
stringName = stringName.Replace(".", "");
stringName = stringName.Replace("'", "");
stringName = stringName.Replace("’", "");
stringName = stringName.Replace("-", "");
stringName = stringName.Replace("*", "");
stringName = stringName.Replace("+", "");
stringName = stringName.Replace("[", "");
stringName = stringName.Replace("]", "");
stringName = stringName.Replace("\\", "");
stringName = stringName.Replace("\"", "");
stringName = stringName.Replace("!", "");
stringName = stringName.Replace("|", "");
stringName = stringName.Replace("^", "");
stringName = stringName.Replace("&", "");
stringName = stringName.Replace("_", "");
stringName = stringName.Replace("=", "");
stringName = stringName.Replace("?", "");
stringName = stringName.Replace("~", "");
stringName = stringName.Replace("`", "");
stringName = stringName.Replace("%", "");
stringName = stringName.Replace("{", "");
stringName = stringName.Replace("}", "");
stringName = stringName.Replace(":", "");
stringName = stringName.Replace("<", "");
stringName = stringName.Replace(">", "");
stringName = stringName.Trim();
}
return stringName;
}
#endregion
#region Get FullAddress With State
/// <summary>
/// Get FullAddress With State
/// </summary>
/// <param name="address1"></param>
/// <param name="address2"></param>
/// <param name="city"></param>
/// <param name="statecode"></param>
/// <param name="zipcode"></param>
/// <returns></returns>
public static string GetFullAddressWithState(string address1, string address2, string city, string statecode, string zipcode)
{
string Fulladdress = string.Empty;
if (!string.IsNullOrWhiteSpace(address1))
{
Fulladdress = address1;
}
if (!string.IsNullOrWhiteSpace(address2))
{
Fulladdress += ", " + address2;
}
string citystatezip = string.Empty;
if (!string.IsNullOrWhiteSpace(city) && !string.IsNullOrWhiteSpace(statecode) && !string.IsNullOrWhiteSpace(zipcode))
{
citystatezip = city + ", " + statecode + " " + zipcode;
}
if (!string.IsNullOrEmpty(Fulladdress) && !string.IsNullOrEmpty(citystatezip))
Fulladdress = Fulladdress + ", " + citystatezip;
return Fulladdress;
}
#endregion
#region Check Empty String
/// <summary>
/// Compare string for empty value
/// </summary>
/// <param name="value">string to check empty</param>
/// <returns>bool status</returns>
public static bool IsStringEmpty(string value)
{
return string.IsNullOrEmpty(value);
}
#endregion
#region Stream to Byte
/// <summary>
/// Stream to Byte
/// </summary>
/// <param name="st"></param>
/// <returns></returns>
public static byte[] GetByteFormStream(Stream st)
{
var app = new byte[0];
if (st != null)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = st.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
app = ms.ToArray();
}
}
return app;
}
#endregion
#region Convert to EIN Format
public static string GetEINFormattedString(string value)
{
if (!string.IsNullOrEmpty(value))
{
value = RemoveSpecialChars(value);
if (value.Length == 9)
{
string _string1 = value.Substring(0, 2);
string _string2 = value.Substring(2, 7);
value = _string1 + "-" + _string2;
}
else
{
return value;
}
}
return value;
}
#endregion
#region Convert to SSN Format
public static string GetSSNFormattedString(string value)
{
if (!string.IsNullOrEmpty(value))
{
value = RemoveSpecialChars(value);
string _string1 = value.Substring(0, 3);
string _string2 = value.Substring(3, 2);
string _string3 = value.Substring(5, 4);
value = _string1 + "-" + _string2 + "-" + _string3;
}
return value;
}
#endregion
#region Convert to Phone Format
public static string GetPhoneorFaxFormattedString(string value)
{
if (!string.IsNullOrEmpty(value))
{
value = RemoveSpecialChars(value);
if (value.Length == 10)
{
string _string1 = value.Substring(0, 3);
string _string2 = value.Substring(3, 3);
string _string3 = value.Substring(6, 4);
value = "(" + _string1 + ") " + _string2 + "-" + _string3;
}
else
{
return value;
}
}
return value;
}
#endregion
#region Name Separation
/// <summary>
/// Name Separation
/// </summary>
/// <param name="FullName"></param>
/// <returns></returns>
public static string[] NameSeparation(string FullName)
{
var names = new string[4];
if (!string.IsNullOrWhiteSpace(FullName))
{
string[] employeeName = FullName.Split(' ');
if (employeeName != null && employeeName.Length > 0)
{
switch (employeeName.Length)
{
case 1:
names[2] = employeeName[0];
break;
case 2:
names[0] = employeeName[0];
names[2] = employeeName[1];
break;
case 3:
names[0] = employeeName[0];
string suffix = employeeName[2] != null ? employeeName[2].ToLower().Trim() : string.Empty;
if (suffix == "jr" || suffix == "sr" || suffix == "ii" || suffix == "iii"
|| suffix == "iv" || suffix == "v" || suffix == "vi" || suffix == "vii")
{
names[3] = suffix.ToUpper();
names[2] = employeeName[1];
}
else
{
names[1] = employeeName[1];
names[2] = employeeName[2];
}
break;
case 4:
names[0] = employeeName[0];
names[1] = employeeName[1];
names[2] = employeeName[2];
string suffix4 = employeeName[3].ToLower().Trim().Replace(".", "").Replace(",", "");
if (suffix4 == "jr" || suffix4 == "sr" || suffix4 == "ii" || suffix4 == "iii"
|| suffix4 == "iv" || suffix4 == "v" || suffix4 == "vi" || suffix4 == "vii")
{
names[3] = suffix4.ToUpper();
}
else
{
names[2] += " " + suffix4;
}
break;
default:
names[0] = employeeName[0];
names[1] = employeeName[1];
names[2] = employeeName[2];
string suffixD = employeeName[3].ToLower().Trim().Replace(".", "").Replace(",", "");
if (suffixD == "jr" || suffixD == "sr" || suffixD == "ii" || suffixD == "iii"
|| suffixD == "iv" || suffixD == "v" || suffixD == "vi" || suffixD == "vii")
{
names[3] = suffixD.ToUpper();
}
else
{
names[2] += " " + suffixD;
}
break;
}
}
}
return names;
}
#endregion
#region Get Client IP Address
/// <summary>
/// Get Client IP Address
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetClientIPAddress(HttpContext context)
{
string ipAddress = string.Empty;
if (context.Connection.RemoteIpAddress != null)
{
ipAddress = context.Connection.RemoteIpAddress.ToString();
}
//map IP client address
ipAddress = context.Request.Headers["X-Forwarded-For"].ToString();
return ipAddress;
}
#endregion
#region Get String
/// <summary>
/// Get String
/// </summary>
/// <param name="value"></param>
public static string GetString(object value)
{
var result = string.Empty;
if (value != null)
{
result = value.ToString();
}
return result;
}
#endregion
}
}
|
using GrpcFarstRepo;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GrpcFarstService.Extensions
{
public static class RepositoryExtension
{
public static void ConfigureDBContext(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<GrpcFarstContext>(opts =>
opts.UseSqlServer(config.GetConnectionString("GrpcFarst")));
}
}
}
|
using UnityEngine;
namespace Player.Code
{
public class PlayerModel
{
private readonly Rigidbody2D _rigidBody;
private readonly SpriteRenderer _spriteRenderer;
public PlayerModel(
Rigidbody2D rigidbody2D,
SpriteRenderer spriteRenderer)
{
_rigidBody = rigidbody2D;
_spriteRenderer = spriteRenderer;
}
public bool IsSpawning { get; set; }
public bool IsReady { get; private set; }
public bool IsMoving { get; set; }
public bool IsFlying { get; set; }
public bool IsRunning { get; set; }
public bool IsGrounded { get; set; }
public bool IsDead { get; set; }
public Vector2 Position
{
get { return _rigidBody.position; }
private set { _rigidBody.position = value; }
}
public bool IsFacingLeft { get; private set; }
public void PlayerReady()
{
IsReady = true;
}
public void AddForce(Vector2 force)
{
_rigidBody.AddForce(force);
}
public void FaceLeft(bool isPlayerMovingToTheLeft)
{
_spriteRenderer.flipX = isPlayerMovingToTheLeft;
IsFacingLeft = isPlayerMovingToTheLeft;
}
}
} |
using ExtMeth.Extensions;
using System;
namespace ExtMeth
{
class Program
{
static void Main(string[] args)
{
DateTime dt = new DateTime(2020, 11, 07, 8, 10, 45);
Console.WriteLine(dt.ElapsedTime());
string s1 = "Bom dia, você tem novos emails ainda não lidos!";
Console.WriteLine(s1.Cut(20));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ApplicationVersionTracking.Data;
using ApplicationVersionTracking.Models;
namespace ApplicationVersionTracking.Pages.Events
{
public class IndexModel : PageModel
{
private readonly ApplicationVersionTracking.Data.ApplicationContext _context;
public IndexModel(ApplicationVersionTracking.Data.ApplicationContext context)
{
_context = context;
}
public IList<Event> Event { get;set; }
public async Task OnGetAsync(string applicationName, int? Env)
{
var res = from m in _context.Events
.Include(a => a.Application)
.Include(a => a.EnvironmentType)
.Include(a => a.EventType)
.Include(a => a.Server)
.OrderByDescending(a => a.EventDate)
select m;
if (!String.IsNullOrEmpty(applicationName))
{
res = res.Where(s => s.Application.Name.Contains(applicationName));
}
if (Env > 0)
{
res = res.Where(s => s.EnvironmentTypeID == Env);
}
Event = await res.ToListAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ShadowAPI.Models;
namespace ShadowAPI.Repositories
{
public class RunnerRepo : BaseRepository<Runner, long>
{
public RunnerRepo(DbContext context) : base(context)
{
}
public override void Create(Runner runner)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SFP.SIT.SERV.Model.ADM
{
public class SIT_ADM_MODULO
{
public string modmetodo { set; get; }
public int? modpadre { set; get; }
public DateTime modfecbaja { set; get; }
public int? modconsecutivo { set; get; }
public string modcontrol { set; get; }
public string moddescripcion { set; get; }
public int modclave { set; get; }
public SIT_ADM_MODULO () {}
}
}
|
using Apache.Ignite.Core;
using System;
namespace IgniteDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Ignition.Start();
}
catch(Exception ex)
{
Console.WriteLine("Suree Connected Server"+ex.Message);
}
Console.ReadLine();
}
}
}
|
using BPiaoBaoTPos.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBaoTPos.Domain.Services
{
public interface IPosStatClientProxy
{
/// <summary>
/// 账户统计
/// </summary>
/// <param name="code"></param>
/// <param name="key"></param>
/// <returns></returns>
AccountStat GetAccountStat(string code, string key);
/// <summary>
/// 收益统计
/// </summary>
/// <param name="code"></param>
/// <param name="key"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
IEnumerable<TradeStat> GainStat(string code, string key, DateTime startTime, DateTime endTime);
/// <summary>
/// 交易明细
/// </summary>
/// <param name="code"></param>
/// <param name="key"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="posNo"></param>
/// <param name="startIndex"></param>
/// <param name="count"></param>
/// <returns></returns>
Tuple<IEnumerable<TradeDetail>, int> GetTradeDetail(string code, string key, DateTime? startTime, DateTime? endTime, string posNo, int startIndex, int count);
/// <summary>
/// Pos商户报表
/// </summary>
/// <param name="code"></param>
/// <param name="key"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
BusinessmanReport GetBusinessmanReport(string code, string key, DateTime startTime, DateTime endTime);
}
}
|
using System.Threading.Tasks;
using GetLogsClient.ViewModels;
namespace GetLogsClient.Commands
{
public class ViewLogsCommand : CommandBase<ViewLogsCommand>
{
public override void Execute(object parameter)
{
if (parameter is IMainWindowViewModel viewModel)
{
Task.Run(() => { viewModel.GiveGlanceLogFiles(); });
}
}
}
} |
using System;
using Autofac;
using SSW.DataOnion.Core;
using SSW.DataOnion.Core.Initializers;
using SSW.DataOnion.Interfaces;
using Module = Autofac.Module;
namespace SSW.DataOnion.DependencyResolution.Autofac
{
public class DataModule : Module
{
private readonly DbContextConfig[] dbContextConfigs;
public DataModule(string connectionString, Type dbContextType)
{
this.dbContextConfigs = new[]
{
new DbContextConfig(connectionString, dbContextType, new MigrateToLatestVersion())
};
}
public DataModule(params DbContextConfig[] dbContextConfigs)
{
this.dbContextConfigs = dbContextConfigs;
}
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<DbContextFactory>()
.As<IDbContextFactory>()
.WithParameter("dbContextConfigs", this.dbContextConfigs);
builder.RegisterType<DbContextScope>().As<IDbContextScope>();
builder.RegisterType<UnitOfWorkFactory>().As<IUnitOfWorkFactory>().InstancePerLifetimeScope();
builder.RegisterType<DbContextReadOnlyScope>().As<IDbContextReadOnlyScope>();
builder.RegisterType<AutofacRepositoryResolver>().As<IRepositoryResolver>();
builder.RegisterType<DbContextScopeFactory>().As<IDbContextScopeFactory>().InstancePerLifetimeScope();
builder.RegisterType<RepositoryLocator>().As<IRepositoryLocator>().InstancePerLifetimeScope();
builder.RegisterType<AmbientDbContextLocator>().As<IAmbientDbContextLocator>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<ReadOnlyUnitOfWork>().As<IReadOnlyUnitOfWork>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PacketData
{
public static class Helper
{
public static byte[] ForePlay(Packet PacketToSend)
{
int PacketLength = PacketToSend.ToBytes().Length;
List<byte> PacketLenthByte = BitConverter.GetBytes(PacketLength).ToList();
PacketLenthByte.AddRange(PacketToSend.ToBytes());
return PacketLenthByte.ToArray();
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.EntityFrameworkCore.Tools.Commands
{
// ReSharper disable once ArrangeTypeModifiers
internal partial class DatabaseUpdateCommand
{
protected override int Execute(string[] args)
{
using var executor = CreateExecutor(args);
executor.UpdateDatabase(_migration!.Value, _connection!.Value(), Context!.Value());
return base.Execute(args);
}
}
}
|
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Univariate
{
using System;
using Accord.Math;
using Accord.Statistics.Distributions.Fitting;
using AForge;
/// <summary>
/// Inverse chi-Square (χ²) probability distribution
/// </summary>
///
/// <remarks>
/// <para>
/// In probability and statistics, the inverse-chi-squared distribution (or
/// inverted-chi-square distribution) is a continuous probability distribution
/// of a positive-valued random variable. It is closely related to the
/// <see cref="ChiSquareDistribution">chi-squared distribution</see> and its
/// specific importance is that it arises in the application of Bayesian
/// inference to the normal distribution, where it can be used as the
/// prior and posterior distribution for an unknown variance.</para>
///
/// <para>
/// The inverse-chi-squared distribution (or inverted-chi-square distribution) is
/// the probability distribution of a random variable whose multiplicative inverse
/// (reciprocal) has a <see cref="ChiSquareDistribution">chi-squared distribution</see>.
/// It is also often defined as the distribution of a random variable whose reciprocal
/// divided by its degrees of freedom is a chi-squared distribution. That is, if X has
/// the chi-squared distribution with <c>v</c> degrees of freedom, then according to
/// the first definition, 1/X has the inverse-chi-squared distribution with <c>v</c>
/// degrees of freedom; while according to the second definition, <c>v</c>X has the
/// inverse-chi-squared distribution with <c>v</c> degrees of freedom. Only the first
/// definition is covered by this class.
/// </para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Inverse-chi-squared_distribution">
/// Wikipedia, The Free Encyclopedia. Inverse-chi-square distribution. Available on:
/// http://en.wikipedia.org/wiki/Inverse-chi-squared_distribution </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <para>
/// The following example demonstrates how to create a new inverse
/// χ² distribution with the given degrees of freedom. </para>
///
/// <code>
/// // Create a new inverse χ² distribution with 7 d.f.
/// var invchisq = new InverseChiSquareDistribution(degreesOfFreedom: 7);
/// double mean = invchisq.Mean; // 0.2
/// double median = invchisq.Median; // 6.345811068141737
/// double var = invchisq.Variance; // 75
///
/// double cdf = invchisq.DistributionFunction(x: 6.27); // 0.50860033566176044
/// double pdf = invchisq.ProbabilityDensityFunction(x: 6.27); // 0.0000063457380298844403
/// double lpdf = invchisq.LogProbabilityDensityFunction(x: 6.27); // -11.967727146795536
///
/// double ccdf = invchisq.ComplementaryDistributionFunction(x: 6.27); // 0.49139966433823956
/// double icdf = invchisq.InverseDistributionFunction(p: cdf); // 6.2699998329362963
///
/// double hf = invchisq.HazardFunction(x: 6.27); // 0.000012913598625327002
/// double chf = invchisq.CumulativeHazardFunction(x: 6.27); // 0.71049750196765715
///
/// string str = invchisq.ToString(); // "Inv-χ²(x; df = 7)"
/// </code>
/// </example>
///
/// <seealso cref="ChiSquareDistribution"/>
///
[Serializable]
public class InverseChiSquareDistribution : UnivariateContinuousDistribution
{
// Distribution parameters
private int degreesOfFreedom;
/// <summary>
/// Constructs a new Inverse Chi-Square distribution
/// with the given degrees of freedom.
/// </summary>
///
/// <param name="degreesOfFreedom">The degrees of freedom for the distribution.</param>
///
public InverseChiSquareDistribution([PositiveInteger] int degreesOfFreedom)
{
if (degreesOfFreedom <= 0)
{
throw new ArgumentOutOfRangeException("degreesOfFreedom",
"The number of degrees of freedom must be higher than zero.");
}
this.degreesOfFreedom = degreesOfFreedom;
}
/// <summary>
/// Gets the Degrees of Freedom for this distribution.
/// </summary>
///
public int DegreesOfFreedom
{
get { return degreesOfFreedom; }
}
/// <summary>
/// Gets the probability density function (pdf) for
/// the χ² distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <remarks>
/// <para>
/// The Probability Density Function (PDF) describes the
/// probability that a given value <c>x</c> will occur.</para>
/// </remarks>
///
/// <returns>
/// The probability of <c>x</c> occurring
/// in the current distribution.</returns>
///
public override double ProbabilityDensityFunction(double x)
{
if (x <= 0 || Double.IsPositiveInfinity(x))
return 0;
double v = degreesOfFreedom;
double a = Math.Pow(2, -v / 2);
double b = Math.Pow(x, -v / 2 - 1);
double c = Math.Exp(-1 / (2 * x));
double d = Gamma.Function(v / 2);
return (a * b * c) / d;
}
/// <summary>
/// Gets the cumulative distribution function (cdf) for
/// the χ² distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <remarks>
/// <para>
/// The Cumulative Distribution Function (CDF) describes the cumulative
/// probability that a given value or any value smaller than it will occur.</para>
/// </remarks>
///
public override double DistributionFunction(double x)
{
if (x < 0)
return 0;
if (Double.IsPositiveInfinity(x))
return 1;
double cdf = Gamma.UpperIncomplete(degreesOfFreedom / 2.0, x / 2.0);
return cdf;
}
/// <summary>
/// Gets the support interval for this distribution.
/// </summary>
///
/// <value>
/// A <see cref="DoubleRange" /> containing
/// the support interval for this distribution.
/// </value>
///
public override DoubleRange Support
{
get { return new DoubleRange(0, Double.PositiveInfinity); }
}
/// <summary>
/// Gets the mean for this distribution.
/// </summary>
///
public override double Mean
{
get
{
if (degreesOfFreedom > 2)
return 1.0 / (degreesOfFreedom - 2.0);
return Double.NaN;
}
}
/// <summary>
/// Gets the variance for this distribution.
/// </summary>
///
public override double Variance
{
get
{
double v = degreesOfFreedom;
if (v > 4)
return (v - 2) * (v - 2) * (v - 4);
return Double.NaN;
}
}
/// <summary>
/// Gets the mode for this distribution.
/// </summary>
///
/// <value>
/// The distribution's mode value.
/// </value>
///
public override double Mode
{
get { return 1.0 / (degreesOfFreedom + 2); }
}
/// <summary>
/// Gets the entropy for this distribution.
/// </summary>
///
public override double Entropy
{
get
{
double v = degreesOfFreedom;
return v / 2
+ Math.Log(0.5 * Gamma.Function(v / 2))
- (1 - v / 2) * Gamma.Digamma(v / 2);
}
}
/// <summary>
/// This method is not supported.
/// </summary>
///
public override void Fit(double[] observations, double[] weights, IFittingOptions options)
{
throw new NotSupportedException();
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
///
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
///
public override object Clone()
{
return new InverseChiSquareDistribution(degreesOfFreedom);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
///
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
///
public override string ToString(string format, IFormatProvider formatProvider)
{
return String.Format(formatProvider, "Inv-χ²(x; df = {0})",
degreesOfFreedom.ToString(format, formatProvider));
}
}
} |
namespace Switch.Devices
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Identity;
using Packets;
using Parameters;
/// <summary>
/// Interaction logic for Wire.xaml
/// </summary>
public partial class Wire : UserControl
{
private readonly Storyboard storyboard = new Storyboard();
private readonly Queue<PacketQueueItem> packetQueue = new Queue<PacketQueueItem>();
private readonly List<Path> inAnimation = new List<Path>();
private int cost;
private bool busy;
private EllipseGeometry circle;
public Wire(Canvas canvas)
{
this.InitializeComponent();
this.Canvas = canvas;
this.Cost = BroadbandSpeed.DefaultCost;
this.circle = new EllipseGeometry
{
Center = new Point(this.X1, this.Y1),
RadiusX = 5.0,
RadiusY = 5.0
};
this.RegisterName("Circle", this.circle);
}
public enum PortState
{
Opened,
Blocked
}
public static MainWindow Window
{
get; set;
}
public Canvas Canvas
{
get;
set;
}
public Device D1
{
get;
set;
}
public Device D2
{
get;
set;
}
public Brush Stroke
{
get
{
return Line.Stroke;
}
set
{
Line.Stroke = value;
}
}
public Stretch Stretch
{
get
{
return Line.Stretch;
}
set
{
Line.Stretch = value;
Highlight.Stretch = value;
}
}
public double X1
{
get
{
return Line.X1;
}
set
{
Line.X1 = value;
Highlight.X1 = value;
}
}
public double X2
{
get
{
return Line.X2;
}
set
{
Line.X2 = value;
Highlight.X2 = value;
}
}
public double Y1
{
get
{
return Line.Y1;
}
set
{
Line.Y1 = value;
Highlight.Y1 = value;
}
}
public double Y2
{
get
{
return Line.Y2;
}
set
{
Line.Y2 = value;
Highlight.Y2 = value;
}
}
public PortState P1
{
get;
private set;
}
public PortState P2
{
get;
private set;
}
public bool Busy
{
get
{
return this.busy;
}
private set
{
this.busy = value;
if (value)
{
this.WireBorder.Visibility = Visibility.Visible;
}
else
{
this.WireBorder.Visibility = Visibility.Hidden;
}
}
}
public int Cost
{
get
{
return this.cost;
}
set
{
this.cost = value;
}
}
public bool GetBlocked(Device caller)
{
if (this.D1 == caller)
{
return this.P1 == PortState.Blocked;
}
if (this.D2 == caller)
{
return this.P2 == PortState.Blocked;
}
return false;
}
public void SetBlocked(Device caller, bool value)
{
if (value)
{
if (this.D1 == caller)
{
this.P1 = PortState.Blocked;
}
if (this.D2 == caller)
{
this.P2 = PortState.Blocked;
}
if (this.P1 == PortState.Blocked || this.P2 == PortState.Blocked)
{
this.Line.Stroke = Brushes.Khaki;
}
}
else
{
if (this.D1 == caller)
{
this.P1 = PortState.Opened;
}
if (this.D2 == caller)
{
this.P2 = PortState.Opened;
}
if (this.P1 == PortState.Opened && this.P2 == PortState.Opened)
{
this.Line.Stroke = Brushes.DarkSeaGreen;
}
}
}
public Device GetPairedDevice(Device caller)
{
if (this.D1 == caller)
{
return this.D2;
}
if (this.D2 == caller)
{
return this.D1;
}
return null;
}
public void SendPacket(Device caller, Packet packet, Func<Wire, bool> relevant = null)
{
PacketQueueItem item = new PacketQueueItem
{
Packet = packet,
Sender = caller,
Receiver = this.GetPairedDevice(caller),
Relevant = relevant
};
if (item.Receiver != null)
{
item.AnimationPath = new Path();
item.AnimationPath.Fill = packet.Brush ?? Brushes.LightBlue;
item.AnimationPath.Stroke = Brushes.DarkGray;
item.AnimationPath.StrokeThickness = 1;
item.AnimationPath.Data = this.circle;
this.packetQueue.Enqueue(item);
this.SendPacketFromQueue();
}
}
public void StopTransmission()
{
this.packetQueue.Clear();
foreach (var item in this.inAnimation)
{
this.storyboard.Stop(item);
}
this.inAnimation.Clear();
this.Busy = false;
}
public void PauseTransmission()
{
foreach (var item in this.inAnimation)
{
this.storyboard.Pause(item);
}
}
public void ResumeTransmission()
{
foreach (var item in this.inAnimation)
{
this.storyboard.Resume(item);
}
}
public void UpdateLocation(Device device, double x, double y)
{
if (this.D1 == device)
{
this.X1 = x;
this.Y1 = y;
}
else if (this.D2 == device)
{
this.X2 = x;
this.Y2 = y;
}
Canvas.SetTop(this.WireBorder, (this.Y1 + this.Y2 - this.WireBorder.Height) / 2);
Canvas.SetLeft(this.WireBorder, (this.X1 + this.X2 - this.WireBorder.Width) / 2);
}
public void Remove(object sender = null, RoutedEventArgs e = null)
{
this.StopTransmission();
if (this.D1 != null && this.D1 != sender)
{
this.D1.RemoveWire(false, this);
}
if (this.D2 != null && this.D2 != sender)
{
this.D2.RemoveWire(false, this);
}
if (this.Canvas != null)
{
this.Canvas.Children.Remove(this);
}
Window.Modified = true;
}
private void SendPacketFromQueue()
{
if (this.Busy == false && this.packetQueue.Count > 0)
{
PacketQueueItem item = this.packetQueue.Dequeue();
if (item.Relevant == null || item.Relevant(this))
{
PointAnimation animation = new PointAnimation();
if (item.Sender == this.D1)
{
animation.From = new Point(this.X1, this.Y1);
animation.To = new Point(this.X2, this.Y2);
}
else
{
animation.To = new Point(this.X1, this.Y1);
animation.From = new Point(this.X2, this.Y2);
}
animation.Duration = new Duration(TimeSpan.FromMilliseconds(Window.AnimationTime.Value));
animation.AutoReverse = false;
animation.Completed += (object sender, EventArgs e) =>
{
WireCanvas.Children.Remove(item.AnimationPath);
storyboard.Children.Remove(animation);
inAnimation.Remove(item.AnimationPath);
if (item.Packet.Destination == MacAddress.Multicast || !this.GetBlocked(item.Receiver))
{
item.Receiver.ReceivePacket(this, item.Packet);
}
Busy = false;
SendPacketFromQueue();
};
Storyboard.SetTargetName(animation, "Circle");
Storyboard.SetTargetProperty(animation, new PropertyPath(EllipseGeometry.CenterProperty));
this.Busy = true;
this.WireLabel.Content = item.Packet.Label;
this.WireBorder.BorderBrush = item.Packet.Brush;
this.circle.RadiusX = this.circle.RadiusY = item.Packet.Radius;
this.WireCanvas.Children.Add(item.AnimationPath);
this.storyboard.Children.Add(animation);
this.inAnimation.Add(item.AnimationPath);
this.storyboard.Begin(item.AnimationPath, true);
if (!Window.TransmissionIsEnabled)
{
this.PauseTransmission();
}
}
}
}
private class PacketQueueItem
{
public Path AnimationPath { get; set; }
public Device Sender { get; set; }
public Device Receiver { get; set; }
public Packet Packet { get; set; }
public Func<Wire, bool> Relevant { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace ExperianOfficeArrangement.ViewModels
{
public interface IStateContext : INotifyPropertyChanged
{
ICommand SetStateCommand { get; }
IStateViewModel CurrentState { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Models
{
/// <summary>
/// 部门实体类
/// </summary>
public class tb_branch
{
public tb_branch()
{ }
#region Model
private int _id;
private string _branchnum;
private string _branchname;
private string _tel;
private string _person;
private string _branchinfo;
private int _parentid;
/// <summary>
///
/// </summary>
public int id
{
set { _id = value; }
get { return _id; }
}
/// <summary>
///
/// </summary>
public string branchNum
{
set { _branchnum = value; }
get { return _branchnum; }
}
/// <summary>
///
/// </summary>
public string branchName
{
set { _branchname = value; }
get { return _branchname; }
}
public string tel
{
set { _tel = value; }
get { return _tel; }
}
public string person
{
set { _person = value; }
get { return _person; }
}
/// <summary>
///
/// </summary>
public string branchInfo
{
set { _branchinfo = value; }
get { return _branchinfo; }
}
public int parentid
{
set { _parentid = value; }
get { return _parentid; }
}
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace WS_PosData_PMKT.Models.Request
{
[DataContract]
public class RegisterCheckinRequest
{
[DataMember]
public string Email { get; set; }
[DataMember]
public string IdRoute { get; set; }
[DataMember]
public string IdPromo { get; set; }
[DataMember]
public string IdStore { get; set; }
[DataMember]
public string IdDay { get; set; }
[DataMember]
public string IdSync { get; set; }
[DataMember]
public string IdMotive { get; set; }
[DataMember]
public bool ValidCheckin { get; set; }
[DataMember]
public string Latitude { get; set; }
[DataMember]
public string Longitude { get; set; }
[DataMember]
public DateTime DateCheckin { get; set; }
[DataMember]
public DateTime TimeCheckin { get; set; }
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_TextAsset : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
TextAsset o = new TextAsset();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_text(IntPtr l)
{
int result;
try
{
TextAsset textAsset = (TextAsset)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, textAsset.get_text());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_bytes(IntPtr l)
{
int result;
try
{
TextAsset textAsset = (TextAsset)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, textAsset.get_bytes());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.TextAsset");
LuaObject.addMember(l, "text", new LuaCSFunction(Lua_UnityEngine_TextAsset.get_text), null, true);
LuaObject.addMember(l, "bytes", new LuaCSFunction(Lua_UnityEngine_TextAsset.get_bytes), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_TextAsset.constructor), typeof(TextAsset), typeof(Object));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.