text stringlengths 13 6.01M |
|---|
using System.Threading;
using System.Threading.Tasks;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
using OmniSharp.Extensions.JsonRpc;
namespace OmniSharp.Extensions.DebugAdapter.Protocol.Server
{
/// <summary>
/// Gives your class or handler an opportunity to interact with
/// the <see cref="InitializeRequestArguments" /> before it is processed by the server
/// </summary>
public interface IOnDebugAdapterServerInitialize : IEventingHandler
{
Task OnInitialize(IDebugAdapterServer server, InitializeRequestArguments request, CancellationToken cancellationToken);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using GetLogsClient.ListBoxContent;
using GetLogsClient.Models;
using GetLogsClient.NetServices;
using NetCom;
using NetCom.Helpers;
using NetComModels;
using ZipExtension;
using Msg = GetLogsClient.ListBoxContent.Msg;
namespace GetLogsClient.ViewModels
{
public class MainWindowViewModel : ViewModelBase, IMainWindowViewModel
{
private bool _radioButtonIlogsChecked;
private bool _radioButtonLogsChecked;
private DateTime _fromDateTime;
private DateTime _toDateTime;
private string _saveDirectory;
private int _accIdIndex;
private string _accIdText;
private LastState _lastState = new LastState();
private LoaderFile _loaderFile;
private CancellationTokenSource _cts;
private string _accIdSelected;
private int _selectedPatternIndex;
private string _patternText;
private bool _buttonLoadLogsEnabled;
private bool _buttonGiveGlanceEnabled;
private Msg _selectedMsg;
private List<PreparedArchive> _preparedArchives;
private PackageQueue _packageQueue;
private UdpListener _udpListener;
private AboutLogsOnList _aboutLogsOnList;
private AboutILogsOnList _aboutILogsOnList;
private bool _isDownload;
public bool RadioButtonIlogsChecked
{
get => _radioButtonIlogsChecked;
set => SetProperty(ref _radioButtonIlogsChecked, value, nameof(RadioButtonIlogsChecked), () =>
{
ButtonGiveGlanceEnabled = true;
ButtonLoadLogsEnabled = false;
}, () => true);
}
public bool RadioButtonLogsChecked
{
get => _radioButtonLogsChecked;
set => SetProperty(ref _radioButtonLogsChecked, value, nameof(RadioButtonLogsChecked), () =>
{
ButtonGiveGlanceEnabled = true;
ButtonLoadLogsEnabled = false;
}, () => true);
}
public bool ButtonGiveGlanceEnabled
{
get => _buttonGiveGlanceEnabled;
set => SetProperty(ref _buttonGiveGlanceEnabled, value, nameof(ButtonGiveGlanceEnabled));
}
public bool ButtonLoadLogsEnabled
{
get => _buttonLoadLogsEnabled;
set => SetProperty(ref _buttonLoadLogsEnabled, value, nameof(ButtonLoadLogsEnabled));
}
public DateTime FromDateTime
{
get => _fromDateTime;
set => SetProperty(ref _fromDateTime, value, nameof(FromDateTime), SaveState, () => _lastState.FromDateTime != value);
}
public DateTime ToDateTime
{
get => _toDateTime;
set => SetProperty(ref _toDateTime, value, nameof(ToDateTime), SaveState, () => _lastState.ToDateTime != value);
}
public string SaveDirectory
{
get => _saveDirectory;
set => SetProperty(ref _saveDirectory, value, nameof(SaveDirectory), SaveState, () => _lastState.SavePath != value);
}
public ObservableCollection<string> AccIdList { get; set; }
public int AccIdIndex
{
get => _accIdIndex;
set => SetProperty(ref _accIdIndex, value, nameof(AccIdIndex), SaveState, () => value > -1 && _lastState.AccIdIndex != value);
}
public string AccIdText
{
get => _accIdText;
set => SetProperty(ref _accIdText, value, nameof(AccIdText), () =>
{
AccIdList.Add(value);
SaveState();
}, () => !string.IsNullOrEmpty(value) && !AccIdList.Contains(value));
}
public string AccIdSelected
{
get => _accIdSelected;
set => SetProperty(ref _accIdSelected, value);
}
public ObservableCollection<string> PatternList { get; set; }
public int SelectedPatternIndex
{
get => _selectedPatternIndex;
set => SetProperty(ref _selectedPatternIndex, value, nameof(SelectedPatternIndex),
SaveState,() => value > -1 && _lastState.SelectedPatternIndex != value);
}
public string PatternText
{
get => _patternText;
set => SetProperty(ref _patternText, value, nameof(PatternText), () =>
{
PatternList.Add(value);
SaveState();
}, () => !PatternList.Contains(value));
}
private string GetLogsClientPath { get; set; }
private string LastStateJsonFilePath { get; set; }
public ObservableCollection<Msg> MsgList { get; set; }
public Msg SelectedMsg
{
get => _selectedMsg;
set => SetProperty(ref _selectedMsg, value);
}
public MainWindowViewModel()
{
_cts = new CancellationTokenSource();
GetLogsClientPath = Environment.GetEnvironmentVariable("APPDATA") + "\\GetLogsClient";
LastStateJsonFilePath = Environment.GetEnvironmentVariable("APPDATA") + "\\GetLogsClient\\LastState.json";
AccIdList = new ObservableCollection<string>();
PatternList = new ObservableCollection<string>();
ButtonLoadLogsEnabled = false;
ButtonGiveGlanceEnabled = true;
RadioButtonLogsChecked = true;
MsgList = new ObservableCollection<Msg>();
}
public void ExternalInitializer()
{
ReadLastState();
InitializeNetworkServices();
}
public void ViewFileInExternalEditor()
{
if (SelectedMsg != null && SelectedMsg is FileLogMsg fileLog && File.Exists(fileLog.Path))
{
var ext = Path.GetExtension(fileLog.Path);
if (ext == ".txt")
{
var pathToNotepad = "C:\\Program Files (x86)\\Notepad++\\notepad++.exe";
if (File.Exists(pathToNotepad) == false)
{
MessageBox.Show($"Notepad++ не найден по пути: {pathToNotepad}");
return;
}
var filePath = "\"" + fileLog.Path.Replace("/", "\\") + "\"";
Process.Start(pathToNotepad, filePath);
}
if (ext == ".ilog")
{
var pathToIlogPlayer = "c:\\Program Files (x86)\\IlogPlayer\\IlogPlayer.exe";
if (File.Exists(pathToIlogPlayer) == false)
{
MessageBox.Show($"IlogPlayer не найден по пути: {pathToIlogPlayer}");
return;
}
var filePath = "\"" + fileLog.Path.Replace("/", "\\") + "\"";
var argument = "--path=" + filePath;
Process.Start(pathToIlogPlayer, argument);
}
}
}
public async void DownloadArchive()
{
AddMsg("Подготовка загрузки ...");
try
{
if (string.IsNullOrEmpty(SaveDirectory))
{
AddMsg("Не задан путь сохранения");
return;
}
_packageQueue.Clear();
if (_preparedArchives.Count > 0)
{
foreach (var preparedArchive in _preparedArchives)
{
var archNameWithoutExt = Path.GetFileNameWithoutExtension(preparedArchive.Name);
var archDir = Path.Combine(SaveDirectory, archNameWithoutExt ?? throw new InvalidOperationException());
var archPath = Path.Combine(archDir, preparedArchive.Name);
Directory.CreateDirectory(archDir);
await _loaderFile.FileRequestAsync(preparedArchive.FullPath, archPath, preparedArchive.Source);
AddMsg($"Извлечение архива: {archPath}");
var files = Zip.ExtractToArchiveDirectory(archPath);
foreach (var file in files)
{
AddMsg(new FileLogMsg(file));
}
}
}
else
{
ButtonGiveGlanceEnabled = false;
AddMsg("Нечего загружать повторите поиск");
}
}
catch (Exception ex)
{
AddMsg($"Ошибка: {ex.Message}");
}
}
public async void GiveGlanceLogFiles()
{
try
{
ButtonGiveGlanceEnabled = false;
AddMsg("Ждемс ...");
var pattern = "";
if (!string.IsNullOrEmpty(PatternText))
{
pattern = PatternText;
}
var accId = AccIdSelected;
if (string.IsNullOrEmpty(accId))
{
AddMsg($"AccId не задан");
return;
}
ButtonLoadLogsEnabled = false;
_packageQueue.Clear();
if (RadioButtonLogsChecked)
{
_preparedArchives = await _aboutLogsOnList.CheckExistLogsAsync(pattern, accId, FromDateTime, ToDateTime);
}
if (RadioButtonIlogsChecked)
{
_preparedArchives = await _aboutILogsOnList.CheckExistILogsAsync(accId, FromDateTime, ToDateTime);
}
if (_preparedArchives.Count > 0)
{
foreach (var preparedArchive in _preparedArchives)
{
foreach (var file in preparedArchive.Files)
{
AddMsg(new FileLogMsg(file));
}
var totalSizeMb = preparedArchive.TotalSize / 1024 / 1024;
if (string.IsNullOrEmpty(pattern))
AddMsg($"{preparedArchive.Source} : Найдено файл(ов): {preparedArchive.Files.Count}, Размер = {totalSizeMb} Mb, From = {FromDateTime}, To = {ToDateTime}");
else
AddMsg($"{preparedArchive.Source} : Найдено файл(ов): {preparedArchive.Files.Count}, Размер = {totalSizeMb} Mb, Pattern = {pattern}, From = {FromDateTime}, To = {ToDateTime}");
}
ButtonLoadLogsEnabled = true;
}
else
{
AddMsg($"Не удалось найти логи: Pattern = {pattern}, From = {FromDateTime}, To = {ToDateTime}");
_preparedArchives = null;
}
}
catch (Exception ex)
{
AddMsg(ex.Message);
}
finally
{
ButtonGiveGlanceEnabled = true;
}
}
public void Dispose()
{
SaveState();
_cts?.Dispose();
_loaderFile?.Dispose();
_packageQueue?.Dispose();
}
private void ReadLastState()
{
if (File.Exists(LastStateJsonFilePath) == false)
{
AddMsg($"Не удалось загрузить последнее состояние, файл не найден {LastStateJsonFilePath}");
return;
}
var lastState = JsonSerializer.Deserialize<LastState>(File.ReadAllText(LastStateJsonFilePath));
if (lastState.AccIdList != null)
{
foreach (var item in lastState.AccIdList)
{
AccIdList.Add(item);
}
}
AccIdIndex = lastState.AccIdIndex < 0 ? 0 : lastState.AccIdIndex;
if (lastState.PatternList != null)
{
foreach (var item in lastState.PatternList)
{
PatternList.Add(item);
}
}
SelectedPatternIndex = lastState.SelectedPatternIndex < 0 ? 0 : lastState.SelectedPatternIndex;
FromDateTime = lastState.FromDateTime;
ToDateTime = lastState.ToDateTime;
SaveDirectory = string.IsNullOrEmpty(lastState.SavePath) ? "" : lastState.SavePath;
UpdateLastStateConfig();
}
private void SaveState()
{
if (_lastState == null)
{
return;
}
UpdateLastStateConfig();
var json = JsonSerializer.Serialize(_lastState);
if (!Directory.Exists(GetLogsClientPath))
Directory.CreateDirectory(GetLogsClientPath);
File.WriteAllText(LastStateJsonFilePath, json);
}
private void InitializeNetworkServices()
{
_udpListener = new UdpListener(GlobalProperties.ClientMsgPort, _cts.Token);
_packageQueue = new PackageQueue(_udpListener, _cts.Token);
var srcMsgEndPoint = new IPEndPoint(IPAddress.Any, GlobalProperties.ClientMsgPort);
var srcFileEndPoint = new IPEndPoint(IPAddress.Any, NetHelper.GetRandomServerPort());
List<TwoEndPoints> _twoEndPointsList = new List<TwoEndPoints>();
//string[] ipList = { "10.99.132.100", "255.255.255.255", "10.100.16.100", "10.100.23.100", "10.100.45.100" };
//string[] ipList = {"10.99.132.100", "10.11.193.84" };
string[] ipList = {
"10.99.122.100",
"10.99.123.100",
"10.99.124.100",
"10.99.125.100",
"10.99.126.100",
"10.99.127.100",
"10.99.128.100",
"10.99.129.100",
"10.99.130.100",
"10.99.131.100",
"10.99.132.100",
"10.99.133.100",
"10.99.134.100",
"10.99.135.100",
"10.99.136.100",
"10.99.137.100",
"10.99.138.100",
"10.99.139.100",
"10.99.140.100",
"10.99.141.100",
"10.99.142.100",
"10.99.143.100",
"10.99.144.100",
"10.99.145.100",
"10.99.146.100",
"10.99.147.100",
"10.99.99.16",
"10.99.149.100",
"10.99.150.100",
"10.99.151.100",
"10.99.152.100",
"10.99.153.100",
"10.99.154.100",
"10.99.155.100",
"10.99.156.100",
"10.99.159.100",
"10.99.160.100",
"10.100.2.100",
"10.100.3.100",
"10.100.4.100",
"10.100.5.100",
"10.100.6.100",
"10.100.7.100",
"10.100.8.100",
"10.100.9.100",
"10.100.10.100",
"10.100.11.100",
"10.100.12.100",
"10.100.13.100",
"10.100.14.100",
"10.100.15.100",
"10.100.16.100",
"10.100.17.100",
"10.100.18.100",
"10.100.19.100",
"10.100.20.100",
"10.100.21.100",
"84.38.185.129",
"10.100.23.100",
"10.100.24.100",
"31.184.215.62",
"84.38.185.111",
"10.100.27.100",
"10.100.29.100",
"10.100.33.100",
"10.100.34.100",
"10.100.35.100",
"10.100.36.100",
"10.100.37.100",
"10.100.38.100",
"10.100.39.100",
"10.100.40.100",
"10.100.41.100",
"10.100.44.100",
"10.100.45.100",
"10.100.46.100",
"10.100.48.100",
"10.100.59.100",
"10.100.60.100",
"10.100.61.100",
"10.100.62.100",
"10.100.63.100",
"10.100.64.100",
"10.100.65.100",
"10.100.66.100",
"10.100.67.100",
"10.100.68.100",
"10.100.70.100",
"10.100.71.100",
"10.100.72.100",
"10.100.73.100",
"10.100.74.100",
"10.100.75.100",
"10.100.76.100",
"10.100.77.100",
"10.100.78.100",
"10.100.79.100",
"10.100.80.100",
"10.100.81.100",
"10.100.82.100",
"10.100.83.100",
"10.100.84.100",
"10.100.85.100",
"10.100.86.100",
"10.100.87.100",
"10.100.88.100"
};
foreach (var ip in ipList)
{
var destBroadcastEndPoint = new IPEndPoint(IPAddress.Parse(ip), GlobalProperties.ServerMsgPort);
_twoEndPointsList.Add(new TwoEndPoints(srcMsgEndPoint, destBroadcastEndPoint));
}
_aboutLogsOnList = new AboutLogsOnList(_twoEndPointsList, _packageQueue);
_aboutLogsOnList.ProcessMsgEvent += (sender, str) => AddMsg(str);
_aboutILogsOnList = new AboutILogsOnList(_twoEndPointsList, _packageQueue);
_aboutILogsOnList.ProcessMsgEvent += (sender, str) => AddMsg(str);
_loaderFile = new LoaderFile(srcMsgEndPoint, srcFileEndPoint, _packageQueue, _cts.Token);
_loaderFile.BeginDownloadEvent += (sender, str) => AddMsg(str);
_loaderFile.EndDownloadEvent += (sender, str) => AddMsg(str);
_loaderFile.ErrorEvent += (sender, str) => AddMsg(str);
_loaderFile.GeneralMsgEvent += (sender, str) => AddMsg(str);
int maxpercent = 0;
_loaderFile.ProgressEvent += (sender, received, totalBytes) =>
{
int percent = (int)(received / (float) totalBytes * 100);
if (percent > 0 && percent % 10 == 0 && percent > maxpercent)
{
maxpercent = percent;
AddMsg($"Загружено: {(int)percent}%");
}
};
}
private void UpdateLastStateConfig()
{
_lastState.AccIdList = AccIdList.ToArray();
_lastState.AccIdIndex = AccIdIndex;
_lastState.PatternList = PatternList.ToArray();
_lastState.SelectedPatternIndex = SelectedPatternIndex;
_lastState.FromDateTime = _fromDateTime;
_lastState.ToDateTime = _toDateTime;
_lastState.SavePath = SaveDirectory;
}
private void AddMsg(Msg msg)
{
Application.Current.Dispatcher.Invoke(() => { MsgList.Insert(0, msg); });
}
private void AddMsg(string msg)
{
AddMsg(new Msg($"[{DateTime.Now:T}] : {msg}"));
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GridManager : MonoBehaviour
{
//static objects
//if you added a ramp
//no way to make the player respect the navigation
//need a navmesh !obstacle
[SerializeField]
private GameObject _gridPrefab;
public int rows;
public int cols;
List<GameObject> _gridList = new List<GameObject>();
[ContextMenu("Generate Grids")]
public void GenerateGrids()
{
float width = _gridPrefab.GetComponent<BoxCollider>().size.x;
float height = _gridPrefab.GetComponent<BoxCollider>().size.y;
float xPos = 0;
float yPos = 0;
float zPos = 0;
//z value
for (int i = 0; i < rows; i++)
{
zPos = i * width;
//x value
for (int j = 0; j < cols; j++)
{
xPos = j * width;
yPos = 0;
Vector3 newPos = new Vector3(xPos, yPos, zPos);
GameObject go = Instantiate(_gridPrefab, newPos, Quaternion.identity) as GameObject;
go.name = "Grid " + "[" + j + "]" + "[" + i + "]";
go.transform.parent = transform;
_gridList.Add(go);
}
}
}
[ContextMenu("Destroy Grid")]
public void DestroyGrid()
{
if (_gridList.Count == 0)
{
foreach (Transform t in transform)
{
_gridList.Add(t.gameObject);
}
foreach (GameObject go in _gridList)
{
DestroyImmediate(go);
}
}
else
{
foreach (GameObject go in _gridList)
{
DestroyImmediate(go);
}
}
_gridList = new List<GameObject>();
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace GenericTypes
{
class Program
{
static void Main(string[] args)
{
var list = new List<int>();
list.Add(10);
var list2 = new ArrayList();
list2.Add(1);
list2.Add("Dve");
list2.Add(true);
Console.WriteLine(list2[0]);
Console.WriteLine(list2[1]);
Console.WriteLine(list2[2]);
var type = list2[1].GetType().Name;
Console.WriteLine(type);
list2[1].ToString().IndexOf('v');
Console.WriteLine();
Bag<int> bagOfIntegers = new Bag<int>();
bagOfIntegers.AddItem(1);
bagOfIntegers.AddItem(2);
bagOfIntegers.AddItem(3);
Console.WriteLine("Index at 1: " + bagOfIntegers.GetEmenementAtIndex(1));
bagOfIntegers.RemoveItem(3);
Console.WriteLine("All INTEGER items: " + bagOfIntegers);
Console.WriteLine();
Bag<string> bagOfStrings = new Bag<string>();
bagOfStrings.AddItem("One");
bagOfStrings.AddItem("Two");
bagOfStrings.AddItem("Tri");
Console.WriteLine("Index at 1: " + bagOfStrings.GetEmenementAtIndex(1));
bagOfStrings.RemoveItem("Tri");
Console.WriteLine("All STRING items: " + bagOfStrings);
Console.WriteLine();
Bag<bool> bagOfBoolean = new Bag<bool>();
bagOfBoolean.AddItem(true);
bagOfBoolean.AddItem(false);
bagOfBoolean.AddItem(true);
bagOfBoolean.AddItem(false);
Console.WriteLine("Index at 1: " + bagOfBoolean.GetEmenementAtIndex(1));
bagOfBoolean.RemoveItem(true);
Console.WriteLine("All BOOLEAN items: " + bagOfBoolean);
Console.WriteLine();
Bag<Cat> bagOfCats = new Bag<Cat>();
bagOfCats.AddItem(new Cat("Sisa", 15));
bagOfCats.AddItem(new Cat("Garfild", 10));
bagOfCats.AddItem(new Cat("Spaiky", 5));
Console.WriteLine("Cat at index 1: " + bagOfCats.GetEmenementAtIndex(1));
Console.WriteLine();
var bagDict = new BagDictionary();
bagDict.Add("Nasko", 25);
bagDict.Add("Asi", 26);
var tuple = (22, "Gosho", 5.55);
(int age, string name, double grade) = tuple;
Console.WriteLine();
var pickleJar = new PickleJar();
pickleJar.Add(new Pickle());
pickleJar.Add(new Pickle());
pickleJar.Add(new Pickle());
foreach (var pickle in pickleJar.Items)
{
Console.WriteLine(pickle.Freshness);
}
Console.WriteLine();
var cucumberJar = new CucumberJar();
cucumberJar.Add(new Cucumber());
cucumberJar.Add(new Cucumber());
cucumberJar.Add(new Cucumber());
foreach (var cucumber in cucumberJar.Items)
{
Console.WriteLine(cucumber.Freshness);
}
Console.WriteLine();
var intList = CreateList<int>();
intList.Add(1);
intList.Add(2);
intList.Add(3);
intList.RemoveAt(0);
Console.WriteLine(string.Join(", ", intList));
Console.WriteLine();
var referenceCollection = new ReferenceTypeCollections<string>();
var valueCollection = new ValueTypeCollections<int>();
var dictionaryCollection = new DictionaryTypeCollections<Dictionary<string, int>>();
var catTypeCollection = new CatTypeCollections<Cat>();
catTypeCollection.AddCat(new Cat("Gafy", 5));
catTypeCollection.AddCat(new Cat("Asi", 25));
catTypeCollection.AddCat(new Cat("Baba", 45));
catTypeCollection.PrintInfo();
}
public static List<T> CreateList<T>()
{
return new List<T>();
}
}
public class ReferenceTypeCollections<T>
where T : class
{}
public class ValueTypeCollections<T>
where T : struct
{}
public class CatTypeCollections<T>
where T : Cat
{
private List<Cat> BagOfCats { get; } = new List<Cat>();
public void AddCat(Cat cat)
{
this.BagOfCats.Add(cat);
}
public void PrintInfo() {
foreach (Cat cat in this.BagOfCats)
{
Console.WriteLine($"Name: {cat.Name} / Age: {cat.Age}");
}
}
}
public class DictionaryTypeCollections<T>
where T : IDictionary<string, int>
{}
} |
using Puzzle.Interfaces;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Puzzle
{
public class ImagePositionSearch: IImagePositionSearch
{
private int _width;
private int _height;
private int _id;
private Image _image;
private List<Image> _imgSide = new List<Image>(4);
public bool KnownPosition { get; set; }
public int Width { get => _width; }
public int Height { get => _height; }
public int Id { get => _id; }
public Image Image { get => _image;}
public List<Image> ImgSide { get => _imgSide;}
public ImagePositionSearch() { }
public ImagePositionSearch(int width, int height)
{
_width = width;
_height = height;
}
public ImagePositionSearch(Image img, int id)
{
KnownPosition = false;
_image = img;
_id = id;
for (int i = 1; i < 5; i++)
ImgSide.Add(GetSideImage(i));
}
public void SetXY(int width, int height)
{
_width = width;
_height = height;
KnownPosition = true;
}
private Image GetSideImage(int position)
{
var input = new Bitmap(Image);
var pixel = new UInt32();
Bitmap output;
if (position == 1 || position == 3)
{
output = new Bitmap(1, Image.Height);
}
else output = new Bitmap(Image.Width, 1);
for (int i = 0; i < output.Width; i++)
{
for (int j = 0; j < output.Height; j++)
{
switch (position)
{
case 1:
pixel = (UInt32)(input.GetPixel(0, j).ToArgb());
break;
case 2:
pixel = (UInt32)(input.GetPixel(i, 0).ToArgb());
break;
case 3:
pixel = (UInt32)(input.GetPixel(input.Width - 1, j).ToArgb());
break;
case 4:
pixel = (UInt32)(input.GetPixel(i, input.Height - 1).ToArgb());
break;
}
output.SetPixel(i, j, Color.FromArgb((int)pixel));
}
}
return output;
}
}
}
|
namespace Weapons.Dynamite.Code
{
public class DynamitesActive
{
public bool IsDynamiteActive;
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nodes
{
public class Nodes<TKey, TValue> : IEnumerable<Nodes<TKey, TValue>>, IEquatable<Nodes<TKey, TValue>>
where TKey : IComparable<TKey>
{
public Nodes(TKey key, TValue value) : this(key, value, null)
{
}
public Nodes(TKey key, TValue value, Nodes<TKey, TValue> parent)
{
Key = key;
Value = value;
Parent = parent;
}
public Nodes<TKey, TValue> Parent { get; set; }
public Nodes<TKey, TValue> Left { get; set; }
public Nodes<TKey, TValue> Right { get; set; }
public TKey Key { get; set; }
public TValue Value { get; set; }
public int Balance { get; set; }
public bool Equals(Nodes<TKey, TValue> other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
return Key.CompareTo(other.Key) == 0;
}
public override bool Equals(object other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other.GetType() != GetType())
{
return false;
}
return Equals(other as Nodes<TKey, TValue>);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<Nodes<TKey, TValue>> GetEnumerator()
{
throw new NotImplementedException();
}
}
}
|
using UnityEngine;
using System.Collections;
using System;
using System.Linq;
using System.Collections.Generic;
public class GameManager : MonoBehaviour {
/**
* GAME STATES:
* GAME_INTRO
* ENEMY_SPAWN
* PLAYER_TURN
* ENEMY_TURN
* BATTLE_END
*
*/
StateMachine<GameManager> fsm;
public event Action enemyDeadEvent;
public int battleCount;
public GameObject slime;
public GameObject[] enemyType;
List<GameObject> enemies;
public bool enemyCleared = false;
public float timer;
private GameObject enemy;
public BattleManager battleManager;
public GameObject gameOverScreen;
// Use this for initialization
void Start () {
battleManager = FindObjectOfType<BattleManager>();
fsm = new StateMachine<GameManager>(this);
fsm.setState(new IntroState());
battleManager.battleEndedEvent += OnBattleEnded;
battleManager.playerDefeatedEvent += OnPlayerDefeated;
timer = 3.0f;
enemy = GameObject.FindGameObjectWithTag("Enemy");
battleManager.StartBattle();
}
void OnPlayerDefeated()
{
gameOverScreen.SetActive(true);
}
void OnBattleEnded()
{
battleCount += 1;
if (battleCount <= 5)
{
StartCoroutine(pause());
}
}
IEnumerator pause() { yield return new WaitForSeconds(4.1f); battleManager.StartBattle(); }
void SpawnEnemy()
{
}
void Update ()
{
HandleController HandleScript = FindObjectOfType<HandleController>();
ReelController ReelScript = FindObjectOfType<ReelController>();
}
public void PlayAgainOnClick()
{
Application.LoadLevel(Application.loadedLevel);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class chargingHandleSpawn : MonoBehaviour
{
//charging Handle
public GameObject chargeGO;
public Transform chargeJoint;
public GameObject chargeJointGO;
private bool chargeHandleSpawn = false;
// Use this for initialization
void Start()
{
chargingHandleStandardSpawn();
}
// Update is called once per frame
void Update()
{
}
public void chargingHandleStandardSpawn()
{
if (!chargeHandleSpawn)
{
chargeJointGO = Instantiate(chargeGO, chargeJoint.position, chargeJoint.rotation);
chargeJointGO.transform.parent = transform;
chargeHandleSpawn = true;
}
}
public void othersOFFCH()
{
if (chargeHandleSpawn)
{
Destroy(GameObject.Find("chargingHandle(Clone)"));
chargeHandleSpawn = false;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(AudioSource))]
public class CubeController : MonoBehaviour
{
public bool isRotating = false;
public float rotAngle = 1.0f;
public Material colorSuccess;
AudioSource chime;
Rigidbody body;
// Start is called before the first frame update
void Start()
{
chime = GetComponent<AudioSource>();
body = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (isRotating)
{
transform.Rotate(Vector3.up, rotAngle);
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
chime.Play();
body.useGravity = true;
isRotating = false;
gameObject.GetComponent<MeshRenderer>().material = colorSuccess;
}
}
}
|
using UnityEngine;
using System;
public class CharacterInfo : MonoBehaviour
{
private CharacterMovement movement;
private CharacterAnimation anim;
private TeamManager team;
public GameObject graphic;
public GameObject sprite;
public event Action OnLead;
private bool active = true;
private bool canInteract = false;
private bool isQuitting = false;
private void Awake()
{
team = TeamManager.instance;
if (graphic == null)
{
graphic = gameObject;
}
if (sprite == null && transform.GetChild(0) != null)
{
sprite = transform.GetChild(0).gameObject;
}
team.Add(gameObject);
}
private void OnApplicationQuit()
{
isQuitting = true;
}
private void OnDestroy()
{
if (!isQuitting)
{
//Remove gameobject from list on destroy to prevent duplicates
team.Remove(gameObject);
}
}
// Sets the character to active or inactive state
public bool Active
{
get
{
return active;
}
set
{
active = value;
anim = graphic.GetComponent<CharacterAnimation>();
movement = GetComponent<CharacterMovement>();
if (movement != null)
{
movement.CanMove = value;
}
if (anim != null)
{
if (active)
{
anim.SetSpriteColor(Color.white);
}
else
{
anim.SetSpriteColor(Color.gray);
anim.PlayIdle(true);
}
}
}
}
// Determines if the character can interact with things
public bool CanInteract
{
get
{
return canInteract;
}
set
{
canInteract = value;
}
}
// Returns the transform of the sprite GameObject
public Transform SpriteTransform
{
get
{
if (sprite != null)
{
return sprite.transform;
}
else
{
Debug.LogError("Sprite is not set in inspector");
return null;
}
}
}
// Returns the transform of the graphic GameObject
public Transform GraphicTransform
{
get
{
if (graphic != null)
{
return graphic.transform;
}
else
{
Debug.LogError("Graphic is not set in inspector");
return null;
}
}
}
public void TriggerOnLead()
{
if (OnLead != null)
{
OnLead();
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_LightRenderMode : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.LightRenderMode");
LuaObject.addMember(l, 0, "Auto");
LuaObject.addMember(l, 1, "ForcePixel");
LuaObject.addMember(l, 2, "ForceVertex");
LuaDLL.lua_pop(l, 1);
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Yeasca.Metier;
using Yeasca.Mongo;
namespace Yeasca.TestsUnitaires.Persistance
{
[TestClass]
public class TestEntrepotMongo
{
[TestMethod]
public void TestEntrepotMongo_peutCréerUnEntrepotAvecUnFournisseurDeTest()
{
ModuleInjection paramètresDeTest = EntrepotMongo.obtenirLesParamètresParDéfaut();
paramètresDeTest.lier<IFournisseur>().à<FournisseurTest>();
EntrepotMongo.paramétrer(paramètresDeTest);
IEntrepotConstat entrepotDemandé = EntrepotMongo.fabriquerEntrepot<IEntrepotConstat>();
Assert.IsNotNull(entrepotDemandé);
Constat unConstat = new Constat();
entrepotDemandé.ajouter(unConstat);
Assert.IsNotNull(unConstat.Id);
}
[TestMethod]
public void TestEntrepotMongo_tousLesEntrepotsSontFabricables()
{
ModuleInjection paramètresDeTest = EntrepotMongo.obtenirLesParamètresParDéfaut();
paramètresDeTest.lier<IFournisseur>().à<FournisseurTest>();
EntrepotMongo.paramétrer(paramètresDeTest);
IEntrepotConstat entrepotConstat = EntrepotMongo.fabriquerEntrepot<IEntrepotConstat>();
IEntrepotProfile entrepotPartie = EntrepotMongo.fabriquerEntrepot<IEntrepotProfile>();
IEntrepotUtilisateur entrepotUtilisateur = EntrepotMongo.fabriquerEntrepot<IEntrepotUtilisateur>();
IEntrepotParametrage entrepotParametrage = EntrepotMongo.fabriquerEntrepot<IEntrepotParametrage>();
IEntrepotJeton entrepotJeton = EntrepotMongo.fabriquerEntrepot<IEntrepotJeton>();
Assert.IsNotNull(entrepotConstat);
Assert.IsNotNull(entrepotPartie);
Assert.IsNotNull(entrepotUtilisateur);
Assert.IsNotNull(entrepotParametrage);
Assert.IsNotNull(entrepotJeton);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Steamworks;
public class LeaderBoard : MonoBehaviour {
void Start ()
{
//EasySteamLeaderboards.Instance.GetLeaderboard("");
}
}
|
using System;
using DependencyInjectionExample.Classes;
using DependencyInjectionExample.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace DependencyInjectionExample
{
class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<ICalculator, Calculator>();
serviceCollection.AddScoped<ICommand, AddCommand>();
serviceCollection.AddScoped<ICommand, MultiplyCommand>();
serviceCollection.AddScoped<ICommand, WriteFileCommand>();
serviceCollection.AddScoped<ICommandProcessor, CommandProcessor>();
serviceCollection.AddScoped<IFileWriter, FileWriter>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var processor = serviceProvider.GetRequiredService<ICommandProcessor>();
var input = string.Empty;
while (input != "exit")
{
Console.WriteLine("Please input a command.");
input = Console.ReadLine();
try
{
processor.Process(input);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
} |
public class Solution {
public bool IsPowerOfFour(int num) {
return (num > 0 && (int) (Math.Log10(num) / Math.Log10(4)) - Math.Log10(num) / Math.Log10(4) == 0);
}
}
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && !(num & amp;
(num - 1)) && (num - 1) % 3 == 0;
}
};
class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && !(num & amp;
(num - 1)) && (num & amp; 0x55555555) == num;
}
}; |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoreComponents.Text
{
public static class Strings
{
public static string Combine(string string1, string string2)
{
StringBuilder SB = new StringBuilder();
SB.Append(string1).Append(string2);
return SB.ToString();
}
public static string Combine(string string1, string string2, string string3)
{
StringBuilder SB = new StringBuilder();
SB.Append(string1).Append(string2).Append(string3);
return SB.ToString();
}
public static string Combine(string string1, string string2, string string3, string string4)
{
StringBuilder SB = new StringBuilder();
SB.Append(string1).Append(string2).Append(string3).Append(string4);
return SB.ToString();
}
public static string Combine(params string[] strings)
{
StringBuilder SB = new StringBuilder();
foreach(var item in strings)
SB.Append(item);
return SB.ToString();
}
public static StringBuilder StartCombine(string string1, string string2)
{
StringBuilder SB = new StringBuilder();
SB.Append(string1).Append(string2);
return SB;
}
public static StringBuilder StartCombine(string string1, string string2, string string3)
{
StringBuilder SB = new StringBuilder();
SB.Append(string1).Append(string2).Append(string3);
return SB;
}
public static StringBuilder StartCombine(string string1, string string2, string string3, string string4)
{
StringBuilder SB = new StringBuilder();
SB.Append(string1).Append(string2).Append(string3).Append(string4);
return SB;
}
public static StringBuilder StartCombine(params string[] strings)
{
StringBuilder SB = new StringBuilder();
foreach(var item in strings)
SB.Append(item);
return SB;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HomeController.cs" company="">
//
// </copyright>
// <summary>
// The home controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConsoleWebServer.Application.Controllers
{
using ConsoleWebServer.Framework;
using ConsoleWebServer.Framework.Actions;
using ConsoleWebServer.Framework.Http;
/// <summary>
/// The home controller.
/// </summary>
public class HomeController : Controller
{
/// <summary>
/// The no cache message.
/// </summary>
private const string NoCacheAndCorsMessage = "Live page with no caching and CORS";
/// <summary>
/// The no cache message.
/// </summary>
private const string NoCacheMessage = "Live page with no caching";
/// <summary>
/// The home page message.
/// </summary>
private const string HomePageMessage = "Home page :)";
/// <summary>
/// Initializes a new instance of the <see cref="HomeController"/> class.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
public HomeController(IHttpRequest request)
: base(request)
{
}
/// <summary>
/// The index.
/// </summary>
/// <param name="param">
/// The param.
/// </param>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
public IActionResult Index(string param)
{
return this.Content(HomePageMessage);
}
/// <summary>
/// The live page.
/// </summary>
/// <param name="param">
/// The param.
/// </param>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
public IActionResult LivePage(string param)
{
return new ContentActionResultWithoutCaching(this.Request, NoCacheMessage);
}
/// <summary>
/// The live page for ajax.
/// </summary>
/// <param name="param">
/// The param.
/// </param>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
public IActionResult LivePageForAjax(string param)
{
return new ContentActionResultWithCorsWithoutCaching(this.Request, NoCacheAndCorsMessage, "*");
}
/// <summary>
/// The forum.
/// </summary>
/// <param name="param">
/// The param.
/// </param>
/// <returns>
/// The <see cref="IActionResult"/>.
/// </returns>
public IActionResult Forum(string param)
{
return new RedirectActionResultWithCors(this.Request, @"https://telerikacademy.com/Forum/Home");
}
}
} |
using System.Collections.Generic;
namespace HCL.Academy.Model
{
public class ProjectData
{
public List<Project> projects { get; set; }
public List<ProjectSkill> projectSkills { get; set; }
public List<ProjectSkillResource> projectSkillResources { get; set; }
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
public class GenRoom {
// ---Internal for generation only---
// TODO make them package protected please
public RectInt bounds = new RectInt();
public HashSet<Vector2Int> doorsDown = new HashSet<Vector2Int>();
public HashSet<Vector2Int> doorsUp = new HashSet<Vector2Int>();
public HashSet<Vector2Int> doorsLeft = new HashSet<Vector2Int>();
public HashSet<Vector2Int> doorsRight = new HashSet<Vector2Int>();
// --- The final room genration result ---
// The position of the anchor of the room in world space. This should be the top left corner of the room, but may be any point in the world.
public Vector2Int roomPosition;
// All positions are in room space relative to the room's anchor
public Dictionary<Vector2Int, GenTile> tiles = new Dictionary<Vector2Int, GenTile>();
public HashSet<Vector2Int> spawnpoints = new HashSet<Vector2Int>();
public Objective objective = null;
public float Distance(GenRoom r) {
return Math.Abs(GetCenter().x - r.GetCenter().x) + Math.Abs(GetCenter().y - r.GetCenter().y);
//float power = 2;
//float dist = (float) Math.Pow(
// Math.Pow(GetCenter().x - r.GetCenter().x, power)
// + Math.Pow(GetCenter().y - r.GetCenter().y, power),
// 1 / power);
//Debug.Log(bounds.center + " " + bounds + " " + dist);
//return dist;
}
public Vector2Int GetCenter() {
return new Vector2Int(( int ) bounds.center.x, ( int ) bounds.center.y);
}
public HashSet<Vector2Int> AllDoors() {
HashSet<Vector2Int> ret = new HashSet<Vector2Int>();
ret.UnionWith(doorsDown);
ret.UnionWith(doorsUp);
ret.UnionWith(doorsLeft);
ret.UnionWith(doorsRight);
return ret;
}
} |
using System.Threading.Tasks;
using VehicleManagement.Domain.Entities;
namespace VehicleManagement.Application.Common.Interfaces
{
public interface IBrandRepository : IRepository<Brand>
{
Task<Brand> AddModelInBrand(Brand brand, Model model);
}
} |
using System;
namespace JqD.Common
{
public class CurrentTimeProvider : ICurrentTimeProvider
{
public DateTime CurrentTime()
{
return DateTime.Now;
}
}
} |
namespace _6.CompanyRoster
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Startup
{
public static void Main(string[] args)
{
var listOfEmployees = new List<Employee>();
var numberOfEmplyees = int.Parse(Console.ReadLine());
for (int i = 0; i < numberOfEmplyees; i++)
{
var tokens = Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var name = tokens[0];
var salary = decimal.Parse(tokens[1]);
var position = tokens[2];
var department = tokens[3];
var employee = new Employee(name, salary, position, department);
if (tokens.Length > 4 )
{
var ageOrEmail = tokens[4];
if (ageOrEmail.Contains("@"))
{
employee.Email = ageOrEmail;
}
else
{
employee.Age = int.Parse(ageOrEmail);
}
}
if (tokens.Length > 5)
{
employee.Age = int.Parse(tokens[5]);
}
listOfEmployees.Add(employee);
}
var result = listOfEmployees.GroupBy(x => x.Department)
.Select(x => new
{
Department = x.Key,
AverageSalary = x.Average(emp => emp.Salary),
Employees = x.OrderByDescending(emp => emp.Salary)
})
.OrderByDescending(x => x.AverageSalary)
.FirstOrDefault();
Console.WriteLine($"Highest Average Salary: {result.Department}");
foreach (var employee in result.Employees)
{
Console.WriteLine($"{employee.Name} {employee.Salary:f2} {employee.Email} {employee.Age}");
}
}
}
}
|
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections;
using Ayende.NHibernateQueryAnalyzer.ProjectLoader;
using MbUnit.Framework;
namespace Ayende.NHibernateQueryAnalyzer.Tests.Remote
{
/// <summary>
/// Summary description for HqlResultGraphTests.
/// </summary>
[TestFixture]
public class HqlResultGraphTests
{
[Test]
public void RemoteGraph()
{
ArrayList list = new ArrayList();
list.AddRange(new string[] {"First", "Second", "Third"});
HqlResultGraph hrg = new HqlResultGraph(list, null);
IList remote = hrg.RemoteGraph;
Assert.AreEqual(list[0], ((RemoteObject) remote[0]).Value);
Assert.AreEqual(list[1], ((RemoteObject) remote[1]).Value);
Assert.AreEqual(list[2], ((RemoteObject) remote[2]).Value);
}
}
} |
using PeliculasAPI.DTOs;
using System.Threading.Tasks;
namespace PeliculasAPI.Services
{
public interface IRatingService
{
Task<RatingDto> Rate(RatingDto newRating, string email);
Task<int> GetUserRating(int peliculaId, string email);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Room : MonoBehaviour
{
public bool closeWhenEntered;
public GameObject[] doors;
public bool roomActive;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OpenDoors()
{
roomActive=false;
foreach(GameObject door in doors)
{
door.SetActive(false);
}
closeWhenEntered=false;
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
roomActive=true;
//CameraControl.instance.ChangeTarget(transform);
if(closeWhenEntered)
{
foreach(GameObject door in doors)
{
door.SetActive(true);
}
}
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.tag == "Player")
{
roomActive=false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
public class DomesticStudent:Student
{
DomesticStudent ds = new DomesticStudent();
public override void displayStudent()
{
base.displayStudent();
}
public override void setData(int rno, string sname, string add, string cou, int cFees, double schamo)
{
base.setData(rno, sname, add, cou, cFees, (0.1*cFees));
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using MvvmCross.Core.ViewModels;
using Newtonsoft.Json;
using Tekstomania.Mobile.Core.Models;
using Tekstomania.Mobile.Core.Models.Enums;
using Tekstomania.Mobile.Core.Services;
using Tekstomania.Mobile.Core.Services.Interfaces;
namespace Tekstomania.Mobile.Core.ViewModels
{
[Android.Runtime.Preserve(AllMembers = true)]
public class SearchArtistViewModel : MvxViewModel
{
private string _query;
private string _oldQuery;
private bool _firstRun;
private bool _isLoading;
private SearchArtistResult _searchArtistResult;
private readonly IHttpService _httpService;
private readonly IDataService _dataService;
private IMvxAsyncCommand _searchArtistCommand;
private IMvxAsyncCommand _nextPageCommand;
private IMvxAsyncCommand _previousPageCommand;
private IMvxCommand _clickCommand;
protected override void ReloadFromBundle(IMvxBundle state)
{
base.ReloadFromBundle(state);
SearchArtistResult = JsonConvert.DeserializeObject<SearchArtistResult>(state.Data["SearchArtistResult"]);
Query = state.Data["Query"];
FirstRun = false;
}
protected override void SaveStateToBundle(IMvxBundle bundle)
{
bundle.Data["SearchArtistResult"] = JsonConvert.SerializeObject(_searchArtistResult);
bundle.Data["Query"] = _oldQuery;
base.SaveStateToBundle(bundle);
}
public SearchArtistViewModel(IHttpService httpService, IDataService dataService)
{
_httpService = httpService;
_dataService = dataService;
_query = string.Empty;
_oldQuery = string.Empty;
_firstRun = true;
}
public async Task SearchArtist()
{
//prepare
FirstRun = false;
IsLoading = true;
SearchArtistResult = null;
_oldQuery = _query;
//run
_dataService.AddLastSearchedItem(new LastSearchedItem(_query.Trim(), ItemType.Artist));
SearchArtistResult = await _httpService.SearchArtist(_query);
//after
IsLoading = false;
}
private async Task SearchArtist(int page)
{
//prepare
FirstRun = false;
IsLoading = true;
SearchArtistResult = null;
Query = _oldQuery;
//run
SearchArtistResult = await _httpService.SearchArtist(_oldQuery, page);
//after
IsLoading = false;
}
private async Task NextPage()
{
await SearchArtist(_searchArtistResult.ActualPage + 1);
}
private async Task PreviousPage()
{
await SearchArtist(_searchArtistResult.ActualPage - 1);
}
private void Click(Artist artist)
{
ShowViewModel<ArtistViewModel>(artist);
}
public IMvxAsyncCommand SearchArtistCommand
{
get
{
_searchArtistCommand = _searchArtistCommand ?? new MvxAsyncCommand(SearchArtist);
return _searchArtistCommand;
}
}
public IMvxAsyncCommand NextPageCommand
{
get
{
_nextPageCommand = _nextPageCommand ?? new MvxAsyncCommand(NextPage);
return _nextPageCommand;
}
}
public IMvxAsyncCommand PreviousPageCommand
{
get
{
_previousPageCommand = _previousPageCommand ?? new MvxAsyncCommand(PreviousPage);
return _previousPageCommand;
}
}
public IMvxCommand ClickCommand
{
get
{
_clickCommand = _clickCommand ?? new MvxCommand<Artist>(Click);
return _clickCommand;
}
}
public SearchArtistResult SearchArtistResult
{
get
{
return _searchArtistResult;
}
set
{
_searchArtistResult = value;
RaisePropertyChanged(() => SearchArtistResult);
RaisePropertyChanged(() => IsEmpty);
}
}
public bool FirstRun
{
get
{
return _firstRun;
}
set
{
_firstRun = value;
RaisePropertyChanged(() => FirstRun);
}
}
public string Query
{
get
{
return _query;
}
set
{
_query = value;
RaisePropertyChanged(() => Query);
}
}
public bool IsLoading
{
get { return _isLoading; }
set
{
_isLoading = value;
RaisePropertyChanged(() => IsLoading);
}
}
public async Task Init(LastSearchedItem item)
{
if (item.Query != null && item.Type != ItemType.NotSet && item.ID != 0)
{
Query = item.Query;
await SearchArtist();
}
}
public bool IsEmpty => _searchArtistResult != null && (!_searchArtistResult.Artists.Any() && !_firstRun);
public bool CanGoBackward => !IsEmpty && _searchArtistResult != null && _searchArtistResult.ActualPage > 1;
public bool CanGoForeward => !IsEmpty && _searchArtistResult != null && _searchArtistResult.ActualPage < _searchArtistResult.MaxPage;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeliverPad : MonoBehaviour, Interactable
{
ClientManager clients;
public enum Status {
Empty,
Cup
}
public Status currentState = Status.Empty;
// Start is called before the first frame update
void Start()
{
clients = GameObject.Find("Level Manager").GetComponent<ClientManager>();
}
// Update is called once per frame
void Update()
{
}
public void OnInteract () {
switch (currentState) {
case Status.Empty:
GameObject obj = GameObject.Find("Player").GetComponent<PlayerBehaviour>().GetHeldObject();
clients.posOrder[0].GetComponent<Client>().ReceiveOrder(obj.GetComponent<Cup>());
GameObject.Find("Level Manager").GetComponent<ClientManager>().posOrder.RemoveAt(0);
clients.UpdateQueuesPositions();
break;
}
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* 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 JetBrains.ReSharper.Feature.Services.CodeCompletion.Infrastructure.LookupItems;
using JetBrains.ReSharper.Feature.Services.CSharp.CodeCompletion.Infrastructure;
using JetBrains.ReSharper.Features.Intellisense.CodeCompletion.CSharp.Rules;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.Xaml.DeclaredElements;
using JetBrains.UI.RichText;
using Moq;
namespace KaVE.RS.Commons.Tests_Integration.Utils
{
[Language(typeof(CSharpLanguage))]
public class TestProposalProvider : CSharpItemsProviderBasic
{
public static bool Enabled { get; set; }
protected override bool IsAvailable(CSharpCodeCompletionContext context)
{
return Enabled;
}
protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector)
{
collector.Add(CreateXamlLookupItem());
return true;
}
private static IDeclaredElementLookupItem CreateXamlLookupItem()
{
var xamlDeclaredElement = new Mock<IXamlDeclaredElement>();
var xamlDeclaredElementInstance = new DeclaredElementInstance(xamlDeclaredElement.Object);
var xamlLookupItem = new Mock<IDeclaredElementLookupItem>();
xamlLookupItem.Setup(li => li.DisplayName).Returns(new RichText("XamlLookupItem"));
xamlLookupItem.Setup(li => li.PreferredDeclaredElement).Returns(xamlDeclaredElementInstance);
xamlLookupItem.Setup(li => li.Placement).Returns(new LookupItemPlacement(""));
return xamlLookupItem.Object;
}
}
} |
using PurificationPioneer.Const;
using ReadyGamerOne.View;
using UnityEngine;
namespace PurificationPioneer.View
{
public class WakeUpPanelScript : MonoBehaviour
{
public void BeginGame()
{
PanelMgr.PushPanel(PanelName.WelcomePanel);
}
}
} |
// GIMP# - A C# wrapper around the GIMP Library
// Copyright (C) 2004-2009 Maurits Rijk
//
// FileEntry.cs
//
// 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 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., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
using System;
using System.Runtime.InteropServices;
using GLib;
using Gtk;
namespace Gimp
{
public class FileEntry : HBox
{
public FileEntry(string title, string filename, bool dir_only,
bool checkValid) :
base(gimp_file_entry_new(title, filename, dir_only, checkValid))
{
}
public string FileName
{
get {return gimp_file_entry_get_filename(Handle);}
set {gimp_file_entry_set_filename(Handle, value);}
}
[GLib.Signal("filename_changed")]
public event EventHandler FilenameChanged {
add {
var sig = GLib.Signal.Lookup(this, "filename_changed");
sig.AddDelegate (value);
}
remove {
var sig = GLib.Signal.Lookup(this, "filename_changed");
sig.RemoveDelegate (value);
}
}
[DllImport("libgimpwidgets-2.0-0.dll")]
extern static IntPtr gimp_file_entry_new(string title, string filename,
bool dir_only, bool check_valid);
[DllImport("libgimpwidgets-2.0-0.dll")]
extern static string gimp_file_entry_get_filename(IntPtr entry);
[DllImport("libgimpwidgets-2.0-0.dll")]
extern static void gimp_file_entry_set_filename(IntPtr entry,
string filename);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using MvvmCross.Core.ViewModels;
using MvvmCross.Droid.Platform;
using EsMo.Sina.SDK.Model;
using MvvmCross.Platform.IoC;
using MvvmCross.Droid.Views;
using MvvmCross.Platform;
using System.Reflection;
using MvvmCross.Plugins.Visibility;
using System.Collections;
using MvvmCross.Platform.Droid.Platform;
using EsMo.Android.WeiBo.Entity;
using EsMo.MvvmCross.Android.Support.Converter;
using MvvmCross.Droid.Support.V7.AppCompat;
namespace EsMo.Android.WeiBo
{
public class Setup : MvxAndroidSetup
{
public Setup(Context applicationContext) : base(applicationContext)
{
}
protected override IMvxApplication CreateApp()
{
this.CreatableTypes(typeof(App).Assembly)
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
this.CreatableTypes(typeof(Setup).Assembly)
.EndingWith("Element")
.AsInterfaces()
.RegisterAsLazySingleton();
return new App();
}
protected override IMvxAndroidViewPresenter CreateViewPresenter()
{
var mvxFragmentsPresenter = new MvxAppCompatViewPresenter(AndroidViewAssemblies);
Mvx.RegisterSingleton<IMvxAndroidViewPresenter>(mvxFragmentsPresenter);
mvxFragmentsPresenter.AddPresentationHintHandler<MvxPanelPopToRootPresentationHint>(hint =>
{
var activity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity;
var fragmentActivity = activity as global::Android.Support.V4.App.FragmentActivity;
for (int i = 0; i < fragmentActivity.SupportFragmentManager.BackStackEntryCount; i++)
{
fragmentActivity.SupportFragmentManager.PopBackStack();
}
return true;
});
Mvx.RegisterSingleton<MvxPresentationHint>(() => new MvxPanelPopToRootPresentationHint());
return mvxFragmentsPresenter;
}
protected override IEnumerable<Assembly> ValueConverterAssemblies
{
get
{
var toReturn = base.ValueConverterAssemblies as IList;
toReturn.Add(typeof(MvxVisibilityValueConverter).Assembly);
toReturn.Add(typeof(StreamBitmapConverter).Assembly);
toReturn.Add(typeof(NullGoneConverter).Assembly);
return (IEnumerable<Assembly>)toReturn;
}
}
//protected override IDictionary<string, string> ViewNamespaceAbbreviations
//=> new Dictionary<string, string>
//{
// {
// "Mvx", "MvvmCross.Binding.Droid.Views"
// }
//};
protected override IEnumerable<Assembly> AndroidViewAssemblies
=> new List<Assembly>(base.AndroidViewAssemblies)
{
typeof(global::MvvmCross.Binding.Droid.Views.MvxImageView).Assembly,
//typeof(global::MvvmCross.Binding.Droid.Views.MvxListItemView).Assembly
};
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using PackageActionsContrib.Helpers;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.packager.standardPackageActions;
using umbraco.DataLayer;
using umbraco.interfaces;
namespace PackageActionsContrib
{
/// <summary>
/// Grants a user access to an Umbraco app
/// </summary>
public class GrantPermissionForApp : IPackageAction
{
#region Constants
private const string REVOKE_SQL = "DELETE umbracoUser2app FROM umbracoUser2app JOIN umbracoUser ON umbracoUser2App.[user] = umbracoUser.id WHERE umbracoUser.userLogin = @UserLogin AND umbracoUser2App.app = @AppName";
private const string GRANT_SQL = "INSERT INTO umbracoUser2app ([user], app) SELECT id, @AppName FROM umbracoUser WHERE userLogin = @UserLogin";
#endregion
#region Implementation of IPackageAction
public bool Execute(string packageName, XmlNode xmlData)
{
//Execute revoke first to clear existing permissions app/user relationships
Revoke(packageName, xmlData);
return Grant(packageName, xmlData);
}
public string Alias()
{
return "GrantPermissionForApp";
}
public bool Undo(string packageName, XmlNode xmlData)
{
return Revoke(packageName, xmlData);
}
public XmlNode SampleXml()
{
string sample = "<Action runat=\"install\" undo=\"false\" alias=\"GrantPermissionForApp\" userLogin=\"$CurrentUser\" appName=\"uCommerce\"/>";
return helper.parseStringToXmlNode(sample);
}
#endregion
#region Supporting methods
protected virtual string GetAppNameFromXml(XmlNode xmlData)
{
return GetAttributeValue(xmlData, "appName");
}
protected virtual string GetUserLoginFromXml(XmlNode xmlData)
{
return GetAttributeValue(xmlData, "userLogin");
}
internal string GetAttributeValue(XmlNode xmlData, string attributeName)
{
return XmlHelper.GetAttributeValueFromNode(xmlData, attributeName);
}
/// <summary>
/// Grants persmission to app for user login
/// </summary>
/// <param name="userLogin">Login of the user</param>
/// <param name="appName">Application name</param>
/// <returns></returns>
protected virtual bool Grant(string packageName, XmlNode xmlData)
{
return ExecutePermissionSql(packageName, xmlData, GRANT_SQL);
}
/// <summary>
/// Revokes persmission to app for user login
/// </summary>
/// <param name="userLogin">Login of the user</param>
/// <param name="appName">Application name</param>
/// <returns></returns>
protected virtual bool Revoke(string packageName, XmlNode xmlData)
{
return ExecutePermissionSql(packageName, xmlData, REVOKE_SQL);
}
private bool ExecutePermissionSql(string packageName, XmlNode xmlData, string sql)
{
string appName = GetAppNameFromXml(xmlData);
string userLogin = GetUserLoginFromXml(xmlData);
if (UserLoginIsCurrentUserPlaceHolder(userLogin))
userLogin = GetUserLoginOfCurrentUser();
IParameter userNameParam = Application.SqlHelper.CreateParameter("@UserLogin", userLogin);
IParameter appNameParam = Application.SqlHelper.CreateParameter("@AppName", appName);
try
{
Application.SqlHelper.ExecuteNonQuery(sql, userNameParam, appNameParam);
return true;
}
catch (SqlHelperException sqlException)
{
Log.Add(LogTypes.Error, -1, string.Format("Error in Grant User Permission for App action for package {0} error:{1} ", packageName, sqlException.ToString()));
}
return false;
}
/// <summary>
/// Returns the user name of the user currently logged in
/// </summary>
/// <remarks>
/// If no user is logged in "admin" is returned as as default
/// </remarks>
/// <returns></returns>
public string GetUserLoginOfCurrentUser()
{
return UmbracoEnsuredPage.CurrentUser.LoginName;
}
/// <summary>
/// Determines whether to lookup the user login of the current user
/// </summary>
/// <param name="login"></param>
/// <returns></returns>
private bool UserLoginIsCurrentUserPlaceHolder(string login)
{
return login == "$CurrentUser";
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using AutoMapper;
using SaleShop.Common;
using SaleShop.Model.Models;
using SaleShop.Service;
using SaleShop.Web.Models;
namespace SaleShop.Web.Controllers
{
public class HomeController : Controller
{
private IProductCategoryService _productCategoryService;
private IProductService _productService;
private ICommonService _commonService;
public HomeController(IProductCategoryService productCategoryService,IProductService productService,ICommonService commonService)
{
_productCategoryService = productCategoryService;
_productService = productService;
_commonService = commonService;
}
[OutputCache(Duration = 60,Location = OutputCacheLocation.Client)]
public ActionResult Index()
{
var slideModel = _commonService.GetSlides();
var slideViewModel = Mapper.Map<IEnumerable<Slide>, IEnumerable<SlideViewModel>>(slideModel);
var lastestProductModel = _productService.GetLastest(3);
var topSaleProductModel = _productService.GetHotProduct(3);
var lastestProductViewModel = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(lastestProductModel);
var topSaleProductViewModel = Mapper.Map<IEnumerable<Product>, IEnumerable<ProductViewModel>>(topSaleProductModel);
var homeViewModel = new HomeViewModel();
homeViewModel.Slides = slideViewModel;
homeViewModel.LastestProducts = lastestProductViewModel;
homeViewModel.TopSaleProducts = topSaleProductViewModel;
homeViewModel.Title = _commonService.GetSystemConfig(CommonConstants.HomeTitle).ValueString;
homeViewModel.MetaDescription = _commonService.GetSystemConfig(CommonConstants.HomeMetaDescription).ValueString;
homeViewModel.MetaKeyword = _commonService.GetSystemConfig(CommonConstants.HomeMetaKeyword).ValueString;
return View(homeViewModel);
}
[ChildActionOnly]
[OutputCache(Duration = 3600)] //lưu server khi cache dùng chung cho nhiều client => lưu trên RAM, lưu client khi cache chỉ lưu cho từng user riêng biệt (như login)
public ActionResult Footer()
{
var footerModel = _commonService.GetFooter();
var footerViewModel = Mapper.Map<Footer, FooterViewModel>(footerModel);
return PartialView(footerViewModel); // PartialView("Footer"); chỉ ra đúng tên view khi action và view không trùng tên
}
[ChildActionOnly]
public ActionResult Header()
{
return PartialView(); // PartialView("Header"); chỉ ra đúng tên view khi action và view không trùng tên
}
[ChildActionOnly]
[OutputCache(Duration = 3600)]
public ActionResult Category()
{
var model = _productCategoryService.GetAll();
var listProductCategoryViewModel = Mapper
.Map<IEnumerable<ProductCategory>, IEnumerable<ProductCategoryViewModel>>(model);
return PartialView(listProductCategoryViewModel);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4.AverageGrades
{
class Program
{
static void Main(string[] args)
{
int numbersOfStudent = int.Parse(Console.ReadLine());
List<Student> students = new List<Student>();
for (int i = 0; i < numbersOfStudent; i++)
{
string[] inputTokens = Console.ReadLine().Split();
string studentName = inputTokens[0];
List<double> grades = new List<double>();
for (int j = 1; j < inputTokens.Length; j++)
{
double grade = double.Parse(inputTokens[j]);
grades.Add(grade);
}
Student student = new Student();
student.Name = studentName;
student.Grades = grades;
students.Add(student);
foreach (Student studen in students.Where(s => s.AverageGrade >= 5)
.OrderBy(s => s.Name).ThenByDescending(s => s.AverageGrade))
{
Console.WriteLine("{0} -> {1:f2}",studen.Name, studen.AverageGrade);
}
}
}
}
public class Student
{
public string Name { get; set;}
public List<double> Grades { get; set;}
public double AverageGrade
{
get { return Grades.Average(); }
}
}
}
|
namespace SoftwareDeveloperIO.Collections.Generic
{
public class LinkedListNode<T> : ILinkedListNode<T>
{
public LinkedList<T> List { get; }
public LinkedListNode<T> Next { get; set; }
public LinkedListNode<T> Previous { get; set; }
public T Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CarRacing.Models.Cars
{
public class TunedCar : Car
{
public TunedCar(string make, string model, string VIN, int horsePower) : base(make, model, VIN, horsePower, 65, 7.5)
{
}
public override void Drive()
{
base.Drive();
HorsePower = (int)Math.Round(HorsePower * 0.7);
}
}
}
|
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class CharacterAnimation : MonoBehaviour
{
public SpriteRenderer characterSprite;
public GameObject root;
private Animator anim;
private GameManager game;
private void Awake()
{
anim = GetComponent<Animator>();
game = GameManager.instance;
CheckIfEnemy();
}
private void CheckIfEnemy()
{
EnemyAnimation enemyAnim = GetComponent<EnemyAnimation>();
if (enemyAnim != null)
{
characterSprite = enemyAnim.spriteRend;
characterSprite.material = new Material(enemyAnim.defaultMat);
}
}
public void PlayWalk(float xAxis, float yAxis)
{
// Not sure why but blend tree seems to have trouble picking the right animation
// when the float value is less than 1, so heres a hack
xAxis *= 10;
yAxis *= 10;
anim.SetFloat("moveX", xAxis);
anim.SetFloat("moveY", yAxis);
if (!IsJumping() && !IsAttacking())
{
anim.Play("Walk");
}
}
public void PlayIdle(bool force)
{
if ((!IsJumping() && !IsAttacking()) || force)
{
anim.Play("Idle");
}
}
public void PlayJump()
{
if (!IsAttacking() && !IsJumping())
{
anim.Play("Jump");
game.Height.ChangeHeight(1);
}
}
public void PlayAttack()
{
if (!IsJumping())
{
anim.Play("Attack");
}
}
public void SetCombo(int combo)
{
anim.SetFloat("combo", (combo % 3));
}
public void SetMousePosition()
{
anim.SetFloat("mouseX", (game.MousePosition.x - transform.position.x));
anim.SetFloat("mouseY", (game.MousePosition.y - transform.position.y));
}
public void SetSpriteColor(Color color)
{
if (characterSprite != null)
{
characterSprite.color = color;
}
}
public bool IsJumping()
{
return AnimationUtil.AnimationIsPlaying(anim, 0, "Jump");
}
private bool IsAttacking()
{
return AnimationUtil.AnimationIsPlaying(anim, 0, "Attack");
}
public void ResetHeight()
{
game.Height.ChangeHeight(0);
}
}
|
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System;
using Requestrr.WebApi.config;
using Requestrr.WebApi.RequestrrBot.ChatClients.Discord;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Ombi;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Radarr;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Sonarr;
using Requestrr.WebApi.RequestrrBot;
using Requestrr.WebApi.RequestrrBot.TvShows;
using Microsoft.Extensions.FileProviders;
using System.IO;
using Requestrr.WebApi.RequestrrBot.DownloadClients.Overseerr;
using Microsoft.AspNetCore.Authentication;
using Requestrr.WebApi.Controllers.Configuration;
using Requestrr.WebApi.Controllers.DownloadClients;
using Requestrr.WebApi.Controllers.ChatClients;
using Requestrr.WebApi.Controllers.Authentication;
using Requestrr.WebApi.RequestrrBot.Movies;
namespace Requestrr.WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
private ChatBot _requestrrBot;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddHttpClient();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
var authenticationSettings = Configuration.GetSection("Authentication");
var applicationSettings = Configuration.Get<ApplicationSettings>();
if (applicationSettings.DisableAuthentication)
{
services.AddAuthentication("Disabled")
.AddScheme<AuthenticationSchemeOptions, DisabledAuthenticationHandler>("Disabled", options => { });
}
else
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
ValidateIssuerSigningKey = true,
ValidIssuer = "Requestrr",
ValidAudience = "Requestrr",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.GetValue<string>("PrivateKey"))),
};
});
}
services.AddSingleton<OmbiClient, OmbiClient>();
services.AddSingleton<RadarrClient, RadarrClient>();
services.AddSingleton<DiscordSettingsProvider>();
services.AddSingleton<TvShowsSettingsProvider>();
services.AddSingleton<MoviesSettingsProvider>();
services.AddSingleton<OmbiSettingsProvider>();
services.AddSingleton<OverseerrSettingsProvider>();
services.AddSingleton<BotClientSettingsProvider>();
services.AddSingleton<ChatClientsSettingsProvider>();
services.AddSingleton<DownloadClientsSettingsProvider>();
services.AddSingleton<ApplicationSettingsProvider>();
services.AddSingleton<AuthenticationSettingsProvider>();
services.AddSingleton<RadarrSettingsProvider>();
services.AddSingleton<SonarrSettingsProvider>();
services.AddSingleton<RequestrrBot.ChatBot>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "ClientApp/build")),
RequestPath = !string.IsNullOrWhiteSpace(Program.BaseUrl) ? Program.BaseUrl : string.Empty
}); ;
if (!string.IsNullOrWhiteSpace(Program.BaseUrl))
{
app.UsePathBase(Program.BaseUrl);
}
app.UseRouting();
app.UseSpaStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "ClientApp/build/static")),
RequestPath = "/static"
});
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
_requestrrBot = (RequestrrBot.ChatBot)app.ApplicationServices.GetService(typeof(RequestrrBot.ChatBot));
_requestrrBot.Start();
}
}
} |
using Cinema.Data.Contracts;
using Cinema.Data.Models;
using NUnit.Framework;
using System;
namespace Cinema.Tests.Data.Repositories.GenericRepository
{
[TestFixture]
public class ConstructorShould
{
[Test]
public void ThrowWhenParameterDbContextHasNullValue()
{
ICinemaDbContext nullContext = null;
Assert.That(()=>
new Cinema.Data.Repositories.GenericRepository<Movie>(nullContext),
Throws.InstanceOf<ArgumentNullException>());
}
}
}
|
using System;
using System.Threading;
namespace CSharp.DesignPatterns.Proxy
{
class Program
{
static void Main(string[] args)
{
//Proxy Design Pattern Structural'dir.
//Structural nesneler arasındaki yapıları ifade eder.
//Bol bol kaynak tüketen bir objeye sahipsek.
//Bu sebeble objeyi kullanmadan önce initialize etmek istemiyorsak.
//Kullanım oranı %80
/*
* Proxy tasarım deseni çalışma maliyeti yüksek işlemlerin olduğu yapılarda,
* web servisi kullanılan yapılarda, remoting uygulamalarında,
* operasyonun gerçekleştirilmesinden önce hazırlık yapılması veya ön işlem yapılması durumlarında kullanılır.
*/
//Proxy Design Pattern Instance
//CreditManager manager = new CreditManager();
//Console.WriteLine(manager.Calculate());
//Console.WriteLine(manager.Calculate());
CreditBase managerProxy = new CrediManagerProxy();
Console.WriteLine(managerProxy.Calculate());
Console.WriteLine(managerProxy.Calculate());
Console.ReadLine();
}
internal abstract class CreditBase
{
public abstract int Calculate();
}
internal class CreditManager : CreditBase
{
public override int Calculate()
{
int result = 1;
for (int i = 1; i < 5; i++)
{
result *= i;
Thread.Sleep(1000);
}
return result;
}
}
internal class CrediManagerProxy : CreditBase
{
private CreditManager _creditManager;
private int _cachedValue;
public override int Calculate()
{
if (_creditManager == null)
{
_creditManager = new CreditManager();
_cachedValue = _creditManager.Calculate();
}
return _cachedValue;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace market_takip
{
public partial class Form3 : Form
{
public Form1 frm1;
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
frm1.musteriListele();
try
{
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.Columns[0].HeaderText = "Müşteri Adı";
dataGridView1.Columns[1].HeaderText = "Müşteri Soyadı";
dataGridView1.Columns[2].HeaderText = "Tc Kimlik";
dataGridView1.Columns[3].HeaderText = "Cep Tel";
dataGridView1.Columns[4].HeaderText = "Ev Tel";
dataGridView1.Columns[5].HeaderText = "Adres";
}
catch
{
;
}
}
private void ekle_Click(object sender, EventArgs e)
{
frm1.frm2.ShowDialog();
}
private void kapat_Click(object sender, EventArgs e)
{
Close();
}
private void sil_Click(object sender, EventArgs e)
{
try
{
DialogResult cevap;
cevap = MessageBox.Show("Kaydı silmek istediğinizden eminmisiniz", "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (cevap == DialogResult.Yes && dataGridView1.CurrentRow.Cells[0].Value.ToString().Trim() != "")
{
frm1.bag.Open();
frm1.kmt.Connection = frm1.bag;
frm1.kmt.CommandText = "DELETE from musteribil WHERE tcKimlik='" + dataGridView1.CurrentRow.Cells[2].Value.ToString() + "'";
frm1.kmt.ExecuteNonQuery();
frm1.kmt.Dispose();
frm1.bag.Close();
frm1.musteriListele();
}
}
catch
{
;
}
}
private void btnAra_Click(object sender, EventArgs e)
{
SqlDataAdapter adtr = new SqlDataAdapter("select musteriAdi,musteriSoyadi,tcKimlik,cepTel,evTel,adres From musteribil", frm1.bag);
string alan = "";
if (comboBox1.Text == "Müşteri Adı") alan = "musteriAdi";
else if (comboBox1.Text == "Müşteri Soyadı") alan = "musteriSoyadi";
else if (comboBox1.Text == "Tc Kimlik") alan = "tcKimlik";
else if (comboBox1.Text == "Cep Tel") alan = "cepTel";
else if (comboBox1.Text == "Ev Tel") alan = "evTel";
else if(comboBox1.Text == "Adres") alan = "adres";
if (comboBox1.Text == "Tümü")
{
frm1.bag.Open();
frm1.tabloMusteri.Clear();
frm1.kmt.Connection = frm1.bag;
frm1.kmt.CommandText = "Select musteriAdi,musteriSoyadi,tcKimlik,cepTel,evTel,adres from musteribil";
adtr.SelectCommand = frm1.kmt;
adtr.Fill(frm1.tabloMusteri);
frm1.bag.Close();
}
if (alan != "")
{
frm1.bag.Open();
adtr.SelectCommand.CommandText = " Select musteriAdi,musteriSoyadi,tcKimlik,cepTel,evTel,adres From musteribil" + " where(" + alan + " like '%" + textBox1.Text + "%' )";
frm1.tabloMusteri.Clear();
adtr.Fill(frm1.tabloMusteri);
frm1.bag.Close();
}
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
frm1.frm4.textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
frm1.frm4.textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
frm1.frm4.textBox3.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
frm1.frm4.textBox4.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
frm1.frm4.textBox5.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
frm1.frm4.textBox6.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
frm1.frm4.ShowDialog();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsultingManager.Infra.Database.Models
{
public class CityPoco
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string State { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ContactManagementApplication
{
public partial class Default1 : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
// instructions say to let anything in!
Session["UserID"] = 1;
Response.Redirect("ContactsList.aspx");
}
}
} |
using MediatR;
using Publicon.Infrastructure.DTOs;
using System.Collections.Generic;
namespace Publicon.Infrastructure.Commands.Models.Category
{
public class CreateCategoryCommand : IRequest<CategoryDTO>
{
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<FieldToAddDTO> Fields { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Pex.Framework;
using PexAPIWrapper;
//using System.Diagnostics.Contracts;
namespace CodeContractBenchmark
{
public class CodeContractBenchmark
{
public int[] GTZero(int x)
{
// Should infer x >= 0
//NotpAssume.IsTrue(x >= 0);
return new int[x];
}
public int z; // dummy field to make the C# compiler happy
public int[] GTZeroAfterCondition(bool b, int x)
{
// Should infer x >= 0
// With Forward propagation we get x >= 0, and prove it is checked in each path
if (b )
{
z = 122;
}
else
{
z = -123;
}
//NotpAssume.IsTrue(x >= 0);
return new int[x];
}
public int[] GTZeroInConditional(bool b, int x)
{
// Admissible preconditions are x >= -1 or (b ==> x >= 0 && !b ==> x >= -1)
// However, the preconditions all over the paths do not infer it (because it does syntactic propagation)
if (b)
{
//NotpAssume.IsTrue(x >=0);
return new int[x];
}
else
{
//NotpAssume.IsTrue(x >= -1 && x < int.MaxValue-1);
return new int[x + 1];
}
}
public void AssertInsideWhileLoop(int x)
{
// precondition should be Contract.Requires(x == 0 || x >= 0);
// but this is out of scope of the preconditions all over the paths
while (x != 0)
{
//NotpAssume.IsTrue(x > 0);
Debug.Assert(x > 0);
x--;
}
}
public int[] InsideWhileLoop(int x)
{
//Contract.Requires(x >= 0);
// Should infer x <= 100, but this is out of the capabilities of the preconditions all over the paths
int i;
for (i = 0; i < x; i++)
{
//NotpAssume.IsTrue(i < 100);
Debug.Assert(i < 100);
}
return null;
}
public void wrap(int xx, int zz)
{
AfterWhileLoop_ConditionAlwaysTrue(xx,zz);
}
public void AfterWhileLoop_ConditionAlwaysTrue(int x, int z)
{
// should infer x == 12, but this is out of the reach of the preconditions all over the paths
// as it does not use the information from the numerical state that z != 0 is unreached
//Contract.Requires( (z >= 0 && x ==12) );
while (z > 0)
{
z--;
}
// here z == 0;
//Contract.Assume(z <= 0);
if (z == 0)
{
//NotpAssume.IsTrue(x == 12);
Debug.Assert(x == 12);
}
}
public int[] AfterWhileLoop_Symbolic(int x)
{
//Contract.Requires(x >= 0);
// should infer x >= 1, but we do not use the numerical information
int i;
for (i = 0; i < x; i++)
{
// empty
}
//NotpAssume.IsTrue(i == x);
//here we know that i == x
Debug.Assert(i == x);
//NotpAssume.IsTrue(i > 1);
return new int[i - 1]; // cannot be read in pre-state immediately
}
static public void AssertGTZero(int x)
{
//NotpAssume.IsTrue(x > 0);
Debug.Assert(x > 0);
}
public static void AssertLTZero(int x)
{
//NotpAssume.IsTrue(x < 0);
Debug.Assert(x < 0);
}
public static void AssertGeqZero(int x)
{
//NotpAssume.IsTrue(x >= 0);
Debug.Assert(x >= 0);
}
public static void RepeatedPreconditionInference(int x, int z, int k)
{
if (x > 0)
{
NotpAssume.IsTrue(z >= k);
Debug.Assert(z >= k);
}
else if (x == 0)
{
NotpAssume.IsTrue(z >= k);
Debug.Assert(z >= k);
}
else
{
NotpAssume.IsTrue(z >= k);
Debug.Assert(z >= k);
}
}
public void Simplification1(int x)
{
int z = x + 1;
NotpAssume.IsTrue(z + 1 > 0);
Debug.Assert(z + 1 > 0);
}
public void Simplification2(int x)
{
int z = x + 1;
NotpAssume.IsTrue(z - 1 > 0);
Debug.Assert(z - 1 > 0);
}
public void Simplification3(int x)
{
int z = x - 1;
NotpAssume.IsTrue(z + 1 > 0);
Debug.Assert(z + 1 > 0);
}
public void Simplification4(int x)
{
int z = x - 1;
NotpAssume.IsTrue(z - 1 > 0);
Debug.Assert(z - 1 > 0);
}
public void RequiresAnInt(object s)
{
//NotpAssume.IsTrue(!(s is Int32));
if ((s is Int32))
{
throw new ArgumentException();
}
}
public void Loop(int input)
{
var j = 0;
for (; j < input; j++)
{
}
//NotpAssume.IsTrue(input == j);
Debug.Assert(input == j); ////Contract.Assert(input == j);
}
public void Loop2(int x)
{
while (x != 0)
{
NotpAssume.IsTrue(x > 0);
Debug.Assert(x > 0); ////Contract.Assert(x > 0);
x--;
}
}
public void Loop4(int m1, int f)
{
//Contract.Requires(m1 >= 0); // as we may have the equality, then we may never execute the loop
int i = 0;
while (i < m1)
{
NotpAssume.IsTrue(i < f);
Debug.Assert(i < f); ////Contract.Assert(i < f);
i++;
}
}
public void SrivastavaGulwaniPLDI09(int x, int y)
{
while (x < 0)
{
x = x + y;
y++;
}
NotpAssume.IsTrue(y > 0);
Debug.Assert(y > 0); ////Contract.Assert(y > 0);
}
public void Shuvendu(int x, int t)
{
var i = x;
var j = 0;
while (i > 0)
{
i--;
j++;
if (i == t)
break;
}
NotpAssume.IsTrue(j == x);
Debug.Assert(j == x);
}
}
}
|
using System;
using Toppler.Core;
using Xunit;
namespace Toppler.Tests.Unit.Core
{
public class KeyFactoryTest
{
[Fact]
public void KeyFactory_NoNs_ShouldReturnReturnKey()
{
var keyFactory = new DefaultKeyFactory(string.Empty);
Assert.Equal(string.Empty, keyFactory.Namespace);
Assert.Equal("1:2:3", keyFactory.NsKey("1", "2", "3"));
Assert.Equal("1:2:3", keyFactory.RawKey("1", "2", "3"));
}
[Fact]
public void KeyFactory_Ns_ShouldReturnReturnKey()
{
var keyFactory = new DefaultKeyFactory("ns");
Assert.Equal("ns", keyFactory.Namespace);
Assert.Equal("ns:1:2:3", keyFactory.NsKey("1", "2", "3"));
Assert.Equal("1:2:3", keyFactory.RawKey("1", "2", "3"));
}
[Fact]
public void KeyFactory_WhenInvalidNs_ShouldThrowExeption()
{
Assert.Throws<ArgumentException>(() => { new DefaultKeyFactory("ns:dfsdf:sdf"); });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Text;
using System.Threading.Tasks;
namespace Tests
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
}
|
using System;
using System.Windows.Input;
class RelayCommand : ICommand
{
/// <summary>
/// Class that describe a relay Command
/// </summary>
private Action function;
private Predicate<Object> canExec;
/// <summary>
/// Create a relay command who launch the function f
/// </summary>
/// <param name="f">Function to use when the command is called</param>
public RelayCommand(Action f)
{
this.function = f;
}
public RelayCommand(Action f, Predicate<Object> canExec)
{
this.function = f;
this.canExec = canExec;
}
public bool CanExecute(object parameter)
{
if (this.canExec == null)
return this.function != null;
else
return this.canExec(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
if (this.function != null)
{
this.function();
}
}
} |
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Claims;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Web;
namespace MeetingRoomBot.Helpers
{
public static class ActivityExtension
{
public static string AuthorizationToken(this Microsoft.Bot.Connector.Activity activity)
{
//var tokenEntity = activity.AsMessageActivity().Entities.Where(e => e.Type.Equals("AuthorizationToken")).SingleOrDefault();
//return tokenEntity != null;
//var token = tokenEntity.Properties.Value<string>("token");
if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
{
//Cortana channel uses Connected Service for authentication
var msg = activity as IMessageActivity;
//TimezoneOffset = msg.LocalTimestamp.HasValue ? msg.LocalTimestamp.Value.Offset : TimeSpan.FromHours(8); //LUIS set in UTC+8 timezone, we need to follow
//if (string.IsNullOrEmpty(Requestor))
{
var tokenEntity = msg.AsMessageActivity().Entities.Where(e => e.Type.Equals("AuthorizationToken")).SingleOrDefault();
if (tokenEntity == null)
{
//Debug mode
//Requestor = "michi@mycompany.com";
return string.Empty;
}
else
{
var token = tokenEntity?.Properties.Value<string>("token");
return token;
//Requestor = JWTTokenParser.GetUserEmail(token);
}
//Trace.TraceInformation($"Requestor:{Requestor}");
}
//Trace.TraceInformation($"Timezone:{TimezoneOffset.Value.TotalHours}");
}
else
{
return string.Empty;
}
}
public static string GetBookedRoomNumber(this Microsoft.Bot.Connector.Activity activity)
{
if(activity.Attachments?.Count > 0)
{
dynamic hero = activity.Attachments[0].Content;
return (string)hero.Title;
}
else
{
return null;
}
}
public static string GetUPN(this Microsoft.Bot.Connector.Activity activity)
{
var tokenEntity = activity.AsMessageActivity().Entities.Where(e => e.Type.Equals("AuthorizationToken")).SingleOrDefault();
var token = tokenEntity?.Properties.Value<string>("token");
if(token == null)
{
return null;
}
var jwt = new JwtSecurityToken(token);
var upn = jwt.Payload.Claims.Where(c => c.Type.Equals("upn", StringComparison.CurrentCultureIgnoreCase)).SingleOrDefault();
return upn?.Value;
}
public static Tuple<double, double> GetLocation(this Microsoft.Bot.Connector.Activity activity)
{
var userInfo = activity.AsMessageActivity().Entities.Where(e => e.Type.Equals("UserInfo")).SingleOrDefault();
if(userInfo == null)
{
return null;
}
dynamic location = userInfo.Properties.Value<JObject>("Location");
return new Tuple<double, double>(
(double)location.Hub.Latitude,
(double)location.Hub.Longitude);
}
public static IDictionary<string,string> GetClaims(this Microsoft.Bot.Connector.Activity activity)
{
var tokenEntity = activity.AsMessageActivity().Entities.Where(e => e.Type.Equals("AuthorizationToken")).SingleOrDefault();
if(tokenEntity == null)
{
return null;
}
var token = tokenEntity.Properties.Value<string>("token");
var jwt = new JwtSecurityToken(token);
var claims = jwt.Payload.Claims.Select(c => new { Key = c.Type, Value = c.Value }).ToArray();
Dictionary<string, string> ret = new Dictionary<string, string>();
foreach(var item in claims)
{
ret.Add(item.Key, item.Value);
}
return ret;
}
}
} |
using System;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Collections.Generic;
using System.Data;
using HadrBenchMark;
using System.Threading;
namespace HadrBenchMark
{
class Program
{
static void Main(string[] args)
{
HadrTestBase hadrTestBase = new HadrTestBase();
hadrTestBase.Setup();
hadrTestBase.ScanDBsFromEnvironment();
Run(hadrTestBase);
Console.ReadKey();
}
static void Run(HadrTestBase hadrTestBase)
{
bool Alive = true;
do
{
string command = Console.ReadLine();
// parse command
string[] param = command.Split(' ');
if (param != null)
{
switch (param[0])
{
case "AddDatabase":
string dbNumber = param[1];
int numberOfDB = 0;
if (Int32.TryParse(dbNumber, out numberOfDB))
{
hadrTestBase.AddDatabases(numberOfDB);
}
else
{
Console.WriteLine("invalid number.");
}
break;
case "AddReplica":
string arNumber = param[1];
int numberOfAR = 0;
if (Int32.TryParse(arNumber, out numberOfAR))
{
CreateReplica(numberOfAR);
}
else
{
Console.WriteLine("invalid number.");
}
break;
case "StartTraffic":
hadrTestBase.StartPartialTraffic();
break;
case "RefreshTraffic":
hadrTestBase.StartFullTraffic();
break;
case "DrainTraffic":
hadrTestBase.DrainTraffic();
break;
case "Cleanup":
Alive = false;
hadrTestBase.CleanUp();
break;
case "quit":
Alive = false;
break;
case "Check":
string str_cpuCount = param[1];
string str_workloadCount = param[2];
int cpuCount = 0;
int workloadCount = 0;
if (!Int32.TryParse(str_cpuCount, out cpuCount))
{
Console.WriteLine("invalid number.");
break;
}
if (!Int32.TryParse(str_workloadCount, out workloadCount))
{
Console.WriteLine("invalid number.");
break;
}
var t = new Thread(() => hadrTestBase.ExecuteQuery(cpuCount, workloadCount));
t.Start();
break;
default:
Console.WriteLine("No Valid parameter");
break;
}
}
} while (Alive);
}
static void CreateReplica(int num)
{
Console.WriteLine("Add {0} Replica into AG", num);
}
static void CleanupEnv()
{
Console.WriteLine("Clean up environment.");
}
}
}
|
using System.Collections;
namespace UserCollection
{
public class UserCollection : IEnumerable
{
private readonly int[] _array;
public UserCollection(params int[] array)
{
_array = array;
}
public IEnumerator GetEnumerator()
{
return new Iterator(_array);
}
}
public class Iterator : IEnumerator
{
private int[] _array;
private int _currentPosition = -1;
public object Current
{
get
{
return _array[_currentPosition];
}
}
public Iterator(int[] array)
{
_array = array;
}
public bool MoveNext()
{
if (_currentPosition < _array.Length - 1)
{
_currentPosition++;
return true;
}
return false;
}
public void Reset()
{
_currentPosition = -1;
}
}
} |
using System.Diagnostics;
using System.Collections.ObjectModel;
using StudyEspanol.Data.Models;
using StudyEspanol.Resources.Strings;
using StudyEspanol.Views.Screens;
namespace StudyEspanol.Data.Managers
{
public class OptionsManager : Manager<OptionsManager.OptionGroup>
{
#region Fields
OptionGroup group1;
OptionGroup group2;
#endregion
#region Construstors
private static OptionsManager instance;
public static OptionsManager Instance()
{
Debug.WriteLine("[Study Espanol] Retriving Options Manager Instance");
if (instance == null)
{
instance = new OptionsManager();
}
return instance;
}
private OptionsManager () : base()
{
Debug.WriteLine("[Study Espanol] Creating Options Manager");
group1 = new OptionGroup(Strings.Word, Strings.Word);
group2 = new OptionGroup(Strings.Other, Strings.Other);
LoadResource();
}
#endregion
#region Methods
private void LoadResource()
{
Debug.WriteLine("[Study Espanol] Adding Screens to Navigation List"); //do this for each side menu option
group1.Add(new Option(Strings.AddWordScreen, typeof(WordScreen)));
group1.Add(new Option(Strings.WordListScreen, typeof(SearchScreen), typeof(WordListScreen)));
group1.Add(new Option(Strings.FlashcardScreen, typeof(SearchScreen), typeof(FlashcardScreen)));
group1.Add(new Option(Strings.QuizConjugation, typeof(SearchScreen), typeof(QuizConjugationScreen)));
group1.Add(new Option(Strings.QuizVocab, typeof(SearchScreen), typeof(QuizVocabScreen)));
group2.Add(new Option(Strings.TeacherScreen, typeof(LoginScreen), typeof(TeacherScreen)));
group2.Add(new Option(Strings.StudentScreen, typeof(LoginScreen), typeof(StudentScreen)));
group2.Add(new Option(Strings.SettingsScreen, typeof(SettingsScreen)));
group2.Add(new Option(Strings.AboutScreen, typeof(AboutScreen)));
Objects.Add(group1);
Objects.Add(group2);
}
#endregion
#region SubClass
//Used in order to allow for a grouped list
//Needs to be turned into a generic class for reusability
public class OptionGroup : ObservableCollection<Option>
{
#region Properties
public string Name { get; private set; }
public string ShortName { get; private set; }
#endregion
#region Constructor
public OptionGroup(string name, string shortName)
{
Name = name;
ShortName = shortName;
}
#endregion
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Shooter
{
class Exit : IDrawable, IInteractable, ITileSpecial
{
bool _animation;
bool _drawn;
bool _reverse;
int _step;
int _delay;
UnitPlayer _player;
public Exit()
{
_reverse = _animation = _drawn = false;
_step = _delay = 0;
_player = null;
}
public void Draw(int x, int y)
{
if (!_drawn)
{
_drawn = true;
DrawStep("░");
}
else if (_animation)
{
_delay++;
if (_delay > 10)
{
if (_step % 2 == 0)
if (_reverse)
DrawStep(" ");
else
{
Console.BackgroundColor = ConsoleColor.Yellow;
_player.ForceDraw(x, y);
Console.BackgroundColor = ConsoleColor.Black;
}
else if (_step % 8 == 1)
DrawStep("░");
else if (_step % 8 == 3)
DrawStep("▒");
else if (_step % 8 == 5)
DrawStep("▓");
else if (_step % 8 == 7)
{
DrawStep("█");
_reverse = true;
}
if (_step == 0 && _reverse)
{
Game.MainGame.InCutSchene = false;
Game.MainGame.Won = true;
}
if (_reverse)
_step--;
else
_step++;
_delay = 0;
}
}
}
protected void DrawStep(string draw)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.SetCursorPosition(this.Index % Game.MainGame.Board.MaxWidth, this.Index / Game.MainGame.Board.MaxWidth);
Console.Write(draw);
Console.ForegroundColor = ConsoleColor.White;
}
public void Interact(UnitPlayer player)
{
_player = player;
Game.MainGame.InCutSchene = _animation = true;
}
public int Index { get; set; }
/// <summary>
/// Get or set the id of the object.
/// </summary>
public string NetworkId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Advanced_Combat_Tracker;
using Machina.FFXIV.Headers;
using System.IO;
namespace OpCodeReflect
{
public class OpCodeReflect : UserControl, IActPluginV1
{
private static OpCodeReflectUI PluginUI;
private Label _lblStatus; // The status label that appears in ACT's Plugin tab
public Dictionary<string, ushort> CurrentOpcodes { get; set; }
public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText) {
pluginScreenSpace.Text = "OpCodeReflect";
PluginUI = new OpCodeReflectUI();
PluginUI.InitializeComponent(pluginScreenSpace);
if (PluginUI.OpCodePath == "") {
var selfPluginData = ActGlobals.oFormActMain.PluginGetSelfData(this);
var path = selfPluginData.pluginFile.DirectoryName;
var txtPath = path + "\\OpCodes.txt";
PluginUI.OpCodePath = txtPath;
}
Dock = DockStyle.Fill; // Expand the UserControl to fill the tab's client space
_lblStatus = pluginStatusText; // Hand the status label's reference to our local var
PluginUI.ButtonStart.Click += ButtonStart_Click;
PluginUI.ButtonLoad.Click += ButtonLoad_Click;
if (PluginUI.AutoStart) {
GetOpcodesFromTxt(PluginUI.OpCodePath);
SetOpcodes();
GetOpcodes();
}
}
private void ButtonLoad_Click(object sender, EventArgs e) {
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
dialog.Title = "请选择文件";
dialog.Filter = "所有文件(*.txt)|*.txt";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string file = dialog.FileName;
PluginUI.SetPath(file);
GetOpcodesFromTxt(file);
SetOpcodes();
GetOpcodes();
}
}
private void ButtonStart_Click(object sender, EventArgs e) {
GetOpcodesFromTxt(PluginUI.OpCodePath);
SetOpcodes();
GetOpcodes();
}
public void GetOpcodesFromTxt(string txtPath) {
//https://github.com/ravahn/machina/blob/master/Machina.FFXIV/Headers/Opcodes/OpcodeManager.cs#L55
//PluginUI.Log(txtPath);
if (!File.Exists(txtPath)) {
PluginUI.Log($"{txtPath}不存在!");
return;
}
using (StreamReader sr = new StreamReader(txtPath)) {
string[][] data = sr.ReadToEnd()
.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
var dict = data.ToDictionary(
x => x[0].Trim(),
x => Convert.ToUInt16(x[1].Trim(), 16));
CurrentOpcodes = dict;
}
PluginUI.Log($"已载入{CurrentOpcodes.Count}个OpCode");
//foreach (KeyValuePair<string, ushort> kvp in CurrentOpcodes) {
// PluginUI.Log($"{kvp.Key}={kvp.Value:X4}");
//}
}
public void Test() {
private static IAbilityResource Abilities;
}
public void GetOpcodes() {
PluginUI.Log("获取OpCode...");
FieldInfo[] opcodes = typeof(Server_MessageType).GetFields();
Type type = typeof(Server_MessageType);
object obj1 = type.Assembly.CreateInstance(type.FullName);
foreach (var opcode in opcodes) {
PluginUI.Log($"{opcode.Name}={(ushort)(Server_MessageType)opcode.GetValue(obj1):X4}");
}
}
public void SetOpcodes() {
PluginUI.Log("设置OpCode...");
FieldInfo[] opcodes = typeof(Server_MessageType).GetFields();
Type type = typeof(Server_MessageType);
object obj1 = type.Assembly.CreateInstance(type.FullName);
foreach (var opcode in opcodes) {
ushort newOpCode = 0;
if (CurrentOpcodes.TryGetValue(opcode.Name, out newOpCode))
opcode.SetValue(obj1, (Server_MessageType)newOpCode);
else
PluginUI.Log($"没找到{opcode.Name}");
}
PluginUI.Log("设置OpCode成功");
}
public void DeInitPlugin() {
PluginUI.SaveSettings();
}
}
}
|
using System;
using ApplicationCore.Interfaces;
using System.Collections.Generic;
//using ApplicationCore.Entities.DoctorAggregate;
namespace ApplicationCore.Entities.DoctorAggregate
{
public class Doctor : IAggregateRoot
{
public string DoctorId{get; set;}
public string DoctorName{get; set;}
public System.DateTime Birthday{get; set;}
public string Phone{get; set;}
// private List<DocAppointment> _appointment = new List<DocAppointment>();
// IEnumerable<DocAppointment> appointment => _appointment.AsReadOnly();
public Doctor(string id, string name, DateTime birthday, string phone)
{
DoctorId = id;
DoctorName = name;
Birthday = birthday;
Phone = phone;
}
}
} |
using AutoMapper;
using ImmedisHCM.Services.Core;
using ImmedisHCM.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ImmedisHCM.Web.Controllers
{
[Authorize]
[Route("[controller]/[action]")]
public class AjaxController : Controller
{
private readonly INomenclatureService _nomenclatureService;
private readonly IAdminService _adminService;
private readonly IMapper _mapper;
public AjaxController(INomenclatureService nomenclatureService,
IMapper mapper,
IAdminService adminService)
{
_nomenclatureService = nomenclatureService;
_mapper = mapper;
_adminService = adminService;
}
[HttpGet]
public async Task<IActionResult> GetCitiesForCountry(string Id)
{
var cities = await _nomenclatureService.GetCitiesByCountryId(new Guid(Id));
var model = _mapper.Map<List<CityViewModel>>(cities);
return new JsonResult(model);
}
[HttpGet]
public async Task<IActionResult> GetDepartmentsForCompany(string Id)
{
var cities = await _adminService.GetDepartmentsByCompanyId(new Guid(Id));
var model = _mapper.Map<List<DepartmentViewModel>>(cities);
return new JsonResult(model);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SampleEntityCore.Models
{
public class Product
{
public string ProductID { get; set; }
public int CategoryID { get; set; }
public string ProductName { get; set; }
public string Stock { get; set; }
public string BuyPrice { get; set; }
public string SellPrice { get; set; }
public DateTime ArrivalDate { get; set; }
public Category Category { get; set; }
}
}
|
using FacialRecognitionLogical;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
namespace FacialRecognition
{
public class Camera
{
private CaptureElement _webcamFeed;
private MediaCapture _mediaCapture;
public MediaCapture MediaCapture
{
get { return _mediaCapture; }
set
{
_mediaCapture = value;
}
}
public Camera(CaptureElement webcamFeed)
{
_webcamFeed = webcamFeed;
}
public async void InitializingCamera()
{
MediaCapture = new MediaCapture();
await MediaCapture.InitializeAsync();
_webcamFeed.Source = MediaCapture;
await MediaCapture.StartPreviewAsync();
}
public async Task<Stream> Capture()
{
StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync($"{Helpers.GenerateTimeStamp()}.jpg");
await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);
return File.OpenRead(file.Path);
return await file.OpenStreamForReadAsync();
}
}
}
|
using System;
using System.Collections;
using System.Diagnostics;
using UnityEngine;
namespace RO
{
[CustomLuaClass]
public class CircleDrawerSmooth : MonoBehaviour
{
public CircleDrawer drawer;
public float duration = 1f;
public float radius;
private float velocity;
private bool smoothing;
private Coroutine smoothCoroutine;
private void DoSet(float r)
{
if (null == this.drawer)
{
return;
}
this.drawer.radius = r;
this.drawer.Draw();
}
public void Set()
{
this.DoSet(this.radius);
this.smoothing = false;
}
public void SmoothSet()
{
if (this.smoothing || null == this.drawer || this.drawer.radius == this.radius)
{
return;
}
this.velocity = 0f;
this.smoothing = true;
if (this.smoothCoroutine == null)
{
this.smoothCoroutine = base.StartCoroutine(this.StartSmooth());
}
}
private void SmoothStep()
{
if (null == this.drawer)
{
return;
}
if (0.001f > Mathf.Abs(this.drawer.radius - this.radius))
{
this.DoSet(this.radius);
this.smoothing = false;
}
else
{
this.DoSet(Mathf.SmoothDamp(this.drawer.radius, this.radius, ref this.velocity, this.duration));
if (this.drawer.radius == this.radius)
{
this.smoothing = false;
}
}
}
[DebuggerHidden]
private IEnumerator StartSmooth()
{
CircleDrawerSmooth.<StartSmooth>c__Iterator30 <StartSmooth>c__Iterator = new CircleDrawerSmooth.<StartSmooth>c__Iterator30();
<StartSmooth>c__Iterator.<>f__this = this;
return <StartSmooth>c__Iterator;
}
}
}
|
namespace Swiddler.NetworkSniffer
{
class UDPParser : PacketParserBase
{
public override bool ParseHeader(RawPacket packet)
{
if (packet.DataLength < 8)
return false; // too small
var raw = packet.Buffer;
var p = packet.HeaderLength; // IP header
packet.Source.Port = (raw[p++] << 8) | raw[p++];
packet.Destination.Port = (raw[p++] << 8) | raw[p++];
p += 2; // ignore Length field
packet.Checksum = (raw[p++] << 8) + raw[p++];
packet.HeaderLength += 8;
packet.DataLength -= 8;
return true;
}
}
}
|
namespace DependencyInjectionExample.Interfaces
{
public interface ICommand
{
bool ShouldProcess(string input);
void Process(string input);
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace Serialization.Binary
{
class Binario
{
List<Produto> produtos;
BinaryFormatter binaryFormatter;
public Binario()
{
produtos = ObterDados();
binaryFormatter = new BinaryFormatter();
}
private static List<Produto> ObterDados()
{
return new List<Produto>()
{
new Produto { Id = 1, Nome = "PC", Preco = 150 },
new Produto { Id = 2, Nome = "Celular", Preco = 90 }
};
}
public void Serialize()
{
using (var fileStream = new FileStream("produto.bin", FileMode.Create, FileAccess.Write))
{
binaryFormatter.Serialize(fileStream, produtos);
}
}
public void Deserialize()
{
using (var fileStream = new FileStream("produto.bin", FileMode.Open, FileAccess.Read))
{
var produtosDeserializados = binaryFormatter.Deserialize(fileStream) as List<Produto>;
foreach (Produto produto in produtosDeserializados)
{
Console.WriteLine(produto.Nome);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Adneom.CoffeMachine.Domain.Entities
{
public partial class OperateurService
{
public OperateurService()
{
ServiceMachine = new HashSet<ServiceMachine>();
}
public int Id { get; set; }
public string Operateur { get; set; }
public virtual ICollection<ServiceMachine> ServiceMachine { get; set; }
}
}
|
using SimpleInjectorTest.Model;
using System.Collections.Generic;
namespace SimpleInjectorTest.Data
{
class ProdutoDao : IProdutoDao
{
public List<Produto> GetProdutos()
{
var list = new List<Produto>()
{
{ new Produto() { Nome = "TV", Preco = 12.50} },
{ new Produto() { Nome = "PC", Preco = 15.50} }
};
return list;
}
}
}
|
using System;
using System.Linq;
using System.Xml.Linq;
using Emanate.Core;
using Emanate.Core.Configuration;
using Emanate.Core.Input;
using Emanate.Core.Output;
using Serilog;
namespace Emanate.Delcom
{
public class DelcomDevice : IOutputDevice
{
private const string key = "delcom";
private const string defaultName = "Delcom";
private BuildState lastCompletedState;
private DateTimeOffset lastUpdateTime; // TODO: This should be used for device reconnection to discover decay level
//private const int minutesTillFullDim = 24 * 60; // 1 full day
public string Key { get; } = key;
public Guid Id { get; private set; } = Guid.NewGuid();
public string Name { get; set; } = defaultName;
public string PhysicalDeviceId { get; set; }
public string Type { get { return key; } }
public Guid ProfileId { get; private set; }
private MonitoringProfile profile;
public IProfile Profile
{
get { return profile; }
set { profile = value as MonitoringProfile; }
}
public PhysicalDevice PhysicalDevice { get; set; }
public bool IsAvailable { get { return PhysicalDevice != null; } }
public void UpdateStatus(BuildState state, DateTimeOffset timeStamp)
{
Log.Information("=> DelcomDevice.UpdateStatus");
Log.Information("New state is '{0}'", state);
if (profile.HasRestrictedHours)
{
var currentTime = DateTime.Now;
if (currentTime.Hour < profile.StartTime || currentTime.Hour > profile.EndTime)
{
Log.Information("Outside restricted hours");
lock (PhysicalDevice)
{
if (PhysicalDevice.IsOpen)
{
Log.Information("Turning off device");
PhysicalDevice.Close();
}
else
Log.Information("Ignoring update");
return;
}
}
}
lock (PhysicalDevice)
{
if (!PhysicalDevice.IsOpen)
{
Log.Information("Turning on device");
PhysicalDevice.Open();
}
}
Log.Information("Finding profile for state '{0}'", state);
var profileState = profile.States.SingleOrDefault(p => p.BuildState == state);
if (profileState == null)
{
Log.Warning("No profile found for state '{0}'", state);
PhysicalDevice.Flash(Color.Red);
return;
}
if (profileState.Buzzer && lastCompletedState != state)
{
// TODO: Make actual buzzer sound configurable
Log.Information("Sounding buzzer");
PhysicalDevice.StartBuzzer(100, 2, 20, 20);
}
switch (state)
{
case BuildState.Unknown:
SetColorBasedOnProfile(profileState, Color.Green, timeStamp);
SetColorBasedOnProfile(profileState, Color.Yellow, timeStamp);
SetColorBasedOnProfile(profileState, Color.Red, timeStamp);
break;
case BuildState.Succeeded:
SetColorBasedOnProfile(profileState, Color.Green, timeStamp);
SetColorBasedOnProfile(profileState, Color.Yellow, timeStamp);
SetColorBasedOnProfile(profileState, Color.Red, timeStamp);
Log.Information("Setting last completed state to '{0}'", state);
lastCompletedState = state;
break;
case BuildState.Error:
case BuildState.Failed:
SetColorBasedOnProfile(profileState, Color.Green, timeStamp);
SetColorBasedOnProfile(profileState, Color.Yellow, timeStamp);
SetColorBasedOnProfile(profileState, Color.Red, timeStamp);
Log.Information("Setting last completed state to '{0}'", state);
lastCompletedState = state;
break;
case BuildState.Running:
SetColorBasedOnProfile(profileState, Color.Green, timeStamp);
SetColorBasedOnProfile(profileState, Color.Yellow, timeStamp);
SetColorBasedOnProfile(profileState, Color.Red, timeStamp);
break;
}
lastCompletedState = state != BuildState.Running ? state : lastCompletedState;
Log.Information("Setting last update time to '{0}'", timeStamp);
lastUpdateTime = timeStamp;
}
private void SetColorBasedOnProfile(ProfileState profileState, Color color, DateTimeOffset timeStamp)
{
Log.Information("=> DelcomDevice.SetColorBasedOnProfile");
var isColorTurnedOn = color == Color.Green && profileState.Green ||
color == Color.Yellow && profileState.Yellow ||
color == Color.Red && profileState.Red;
if (isColorTurnedOn)
{
var intensity = GetColorIntensity(color, timeStamp);
if (profileState.Flash)
{
Log.Information("Flashing '{0}' at intensity '{1}'", color.Name, intensity);
PhysicalDevice.Flash(color, intensity);
}
else
{
Log.Information("Turning on '{0}' at intensity '{1}'", color.Name, intensity);
PhysicalDevice.TurnOn(color, intensity);
}
}
else
{
Log.Information("Turning off '{0}'", color.Name);
PhysicalDevice.TurnOff(color);
}
}
private byte GetColorIntensity(Color color, DateTimeOffset timeStamp)
{
Log.Information("=> DelcomDevice.GetColorIntensity");
if (profile.Decay <= 0)
return color.MaxPower;
var minutesSinceLastBuild = (DateTimeOffset.Now - timeStamp).TotalMinutes;
if (minutesSinceLastBuild > profile.Decay * 60)
return color.MinPower;
var power = color.MaxPower - (minutesSinceLastBuild / profile.Decay * 60) * (color.MaxPower - color.MinPower);
return (byte)power;
}
public XElement CreateMemento()
{
var deviceElement = new XElement("device");
deviceElement.Add(new XAttribute("id", Id));
deviceElement.Add(new XAttribute("name", Name));
deviceElement.Add(new XAttribute("physical-device-id", PhysicalDeviceId));
deviceElement.Add(new XAttribute("profile-id", ProfileId));
return deviceElement;
}
public void SetMemento(XElement deviceElement)
{
Id = Guid.Parse(deviceElement.GetAttributeString("id"));
Name = deviceElement.GetAttributeString("name");
PhysicalDeviceId = deviceElement.GetAttributeString("physical-device-id");
ProfileId = deviceElement.GetAttributeGuid("profile-id");
}
}
} |
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Apidemo2.Controllers
{
[Route("api/[controller]")]
public class TokenController : Controller
{
private readonly TokenProviderOptions _options;
public TokenController(IOptions<TokenProviderOptions> options)
{
_options = options.Value;
}
/// <summary>
/// 用户登录
/// </summary>
/// <param name="user">用户登录信息</param>
/// <param name="audience">要访问的网站</param>
/// <returns></returns>
[HttpPost("{audience}")]
public IActionResult Post(string username, string password)
{
if (username == "czs" && password == "123456")
{
return Json(new { Token = CreateToken(username) });
}
else
{
return Json(new { Error = "用户名或密码错误" });
}
}
private string CreateToken(string username)
{
//计算机上的当前日期和时间,表示为协调世界时 (UTC)。通俗点就是格林威治时间的当前时间。以英国格林威治 天文台旧址为标准的零度经线算的时间
var now = DateTime.UtcNow;
var claims = new Claim[]
{
//jwt所面向的用户
new Claim(JwtRegisteredClaimNames.Sub, username),
//jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
//jwt的签发时间
new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(),
ClaimValueTypes.Integer64),
//用户名
new Claim(ClaimTypes.Name,username),
//角色
new Claim(ClaimTypes.Role,"a")
};
//JwtSecurityToken 类生成jwt
var jwt = new JwtSecurityToken(
issuer: _options.Issuer, //签发者
audience: _options.Audience, //接收者
claims: claims, //identity 详情请看上面
notBefore: now, //如果在之前没有jwt 则添加 { nbf, 'value' } claim
expires: now.Add(_options.Expiration), //过期时间
signingCredentials: _options.SigningCredentials //加密数字签名证书
);
//JwtSecurityTokenHandler将jwt编码
//WriteToken 将jwt编码并序列化
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var response = new
{
Status = true,
access_token = encodedJwt,
expires_in = (int)_options.Expiration.TotalSeconds,
token_type = "Bearer"
};
//对象的json化 Formatting : 设置序列化时key为驼峰样式
return JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented });
}
}
} |
using System;
using Entity;
using System.Data.SqlClient;
using System.Data;
namespace DataAccess
{
public class PhieuDA
{
public static PhieuEntity SelectByMaPhieu(Int64 maphieu)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_SelectByMaPhieu]";
SqlParameter param = new SqlParameter("@MaPhieu", SqlDbType.BigInt, 8);
param.Value = maphieu;
command.Parameters.Add(param);
PhieuEntity phieu = new PhieuEntity();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
phieu.MaPhieu = maphieu;
phieu.MaKhachHang = reader["MaKhachHang"] == DBNull.Value ? 0 : (Int64)reader["MaKhachHang"];
phieu.NgayLap = (DateTime)reader["NgayLap"];
phieu.NgayHenTra = (DateTime)reader["NgayHenTra"];
if (reader["GiamGia"] != DBNull.Value)
phieu.GiamGia = Convert.ToInt32(reader["GiamGia"]);
phieu.DaThanhToan = (Boolean)reader["DaThanhToan"];
phieu.DaTraDo = (Boolean)reader["DaTraDo"];
if (reader["GhiChu"] != DBNull.Value)
phieu.GhiChu = reader["GhiChu"].ToString();
phieu.UserName = reader["UserName"].ToString();
phieu.TongTien = DUtils.ReadInt64(reader["TongTien"]);
phieu.SoLanIn = DUtils.ReadInt32(reader["SoLanIn"]);
phieu.PhiGiaoNhan = DUtils.ReadInt32(reader["PhiGiaoNhan"]);
}
reader.Close();
}
command.Connection.Close();
return phieu;
}
public static ListPhieuEntity SelectNangCao(Boolean tatca, Boolean datrado, Int64 maphieu, String dienthoai,
String tenkhachhang, Boolean timtheongay, DateTime tungay, DateTime denngay)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_SearchNangCao]";
if (!tatca)
{
SqlParameter param = new SqlParameter("@DaTraDo", SqlDbType.Bit, 1);
param.Value = datrado;
command.Parameters.Add(param);
if (maphieu != 0)
{
param = new SqlParameter("@MaPhieu", SqlDbType.BigInt, 8);
param.Value = maphieu;
command.Parameters.Add(param);
}
if (!String.IsNullOrEmpty(dienthoai))
{
param = new SqlParameter("@DienThoai", SqlDbType.VarChar, 20);
param.Value = dienthoai;
command.Parameters.Add(param);
}
if (!String.IsNullOrEmpty(tenkhachhang))
{
param = new SqlParameter("@TenKhachHang", SqlDbType.NVarChar, 100);
param.Value = tenkhachhang;
command.Parameters.Add(param);
}
if (timtheongay)
{
param = new SqlParameter("@tungay", SqlDbType.DateTime);
param.Value = tungay;
command.Parameters.Add(param);
param = new SqlParameter("@denngay", SqlDbType.DateTime);
param.Value = denngay;
command.Parameters.Add(param);
}
}
ListPhieuEntity kq = new ListPhieuEntity();
using (SqlDataReader reader = command.ExecuteReader())
{
PhieuEntity phieu = null;
while (reader.Read())
{
phieu = new PhieuEntity();
phieu.MaPhieu = (Int64)reader["MaPhieu"];
phieu.MaKhachHang = DUtils.ReadInt64(reader["MaKhachHang"]);
phieu.TenKhachHang = reader["TenKhachHang"].ToString();
phieu.NgayLap = (DateTime)reader["NgayLap"];
phieu.NgayHenTra = (DateTime)reader["NgayHenTra"];
phieu.GiamGia = DUtils.ReadInt32(reader["GiamGia"]);
phieu.DaThanhToan = (Boolean)reader["DaThanhToan"];
phieu.DaTraDo = (Boolean)reader["DaTraDo"];
phieu.TongTien = DUtils.ReadInt64(reader["TongTien"]);
phieu.GhiChu = DUtils.ReadString(reader["GhiChu"]);
phieu.UserName = DUtils.ReadString(reader["UserName"]);
phieu.PhiGiaoNhan = DUtils.ReadInt32(reader["PhiGiaoNhan"]);
phieu.IsPhieuHuy = DUtils.ReadBoolean(reader["IsPhieuHuy"]);
kq.Add(phieu);
}
reader.Close();
}
command.Connection.Close();
kq.Sort(delegate (PhieuEntity p1, PhieuEntity p2)
{
return p1.MaPhieu.CompareTo(p2.MaPhieu);
});
return kq;
}
public static ListPhieuEntity SelectByNgayLap(DateTime tungay, DateTime denngay)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "sp_Phieu_SelectByNgayLap";
SqlParameter param = new SqlParameter("@TuNgay", SqlDbType.DateTime);
param.Value = tungay;
command.Parameters.Add(param);
param = new SqlParameter("@DenNgay", SqlDbType.DateTime);
param.Value = denngay;
command.Parameters.Add(param);
ListPhieuEntity kq = new ListPhieuEntity();
using (SqlDataReader reader = command.ExecuteReader())
{
PhieuEntity phieu = null;
while (reader.Read())
{
phieu = new PhieuEntity();
phieu.MaPhieu = Convert.ToInt64(reader["MaPhieu"]);
phieu.MaKhachHang = reader["MaKhachHang"] == DBNull.Value ? 0 : (Int64)reader["MaKhachHang"];
phieu.TenKhachHang = reader["TenKhachHang"].ToString();
phieu.NgayLap = (DateTime)reader["NgayLap"];
phieu.NgayHenTra = (DateTime)reader["NgayHenTra"];
if (reader["GiamGia"] != DBNull.Value)
phieu.GiamGia = Convert.ToInt32(reader["GiamGia"]);
phieu.DaThanhToan = (Boolean)reader["DaThanhToan"];
phieu.DaTraDo = (Boolean)reader["DaTraDo"];
phieu.TongTien = DUtils.ReadInt64(reader["TongTien"]);
if (reader["GhiChu"] != DBNull.Value)
phieu.GhiChu = reader["GhiChu"].ToString();
phieu.UserName = reader["UserName"].ToString();
phieu.PhiGiaoNhan = DUtils.ReadInt32(reader["PhiGiaoNhan"]);
phieu.IsPhieuHuy = DUtils.ReadBoolean(reader["IsPhieuHuy"]);
kq.Add(phieu);
}
reader.Close();
}
command.Connection.Close();
return kq;
}
public static ListPhieuEntity SelectByTuPhieuDenPhieu(Int64 tuphieu, Int64 denphieu)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_SelectBy_TuPhieu_DenPhieu]";
SqlParameter param = new SqlParameter("@tuphieu", SqlDbType.BigInt);
param.Value = tuphieu;
command.Parameters.Add(param);
param = new SqlParameter("@denphieu", SqlDbType.BigInt);
param.Value = denphieu;
command.Parameters.Add(param);
ListPhieuEntity kq = new ListPhieuEntity();
using (SqlDataReader reader = command.ExecuteReader())
{
PhieuEntity phieu = null;
while (reader.Read())
{
phieu = new PhieuEntity();
phieu.MaPhieu = Convert.ToInt64(reader["MaPhieu"]);
phieu.MaKhachHang = reader["MaKhachHang"] == DBNull.Value ? 0 : (Int64)reader["MaKhachHang"];
phieu.TenKhachHang = reader["TenKhachHang"].ToString();
phieu.NgayLap = (DateTime)reader["NgayLap"];
phieu.NgayHenTra = (DateTime)reader["NgayHenTra"];
if (reader["GiamGia"] != DBNull.Value)
phieu.GiamGia = Convert.ToInt32(reader["GiamGia"]);
phieu.DaThanhToan = (Boolean)reader["DaThanhToan"];
phieu.DaTraDo = (Boolean)reader["DaTraDo"];
phieu.TongTien = DUtils.ReadInt64(reader["TongTien"]);
if (reader["GhiChu"] != DBNull.Value)
phieu.GhiChu = reader["GhiChu"].ToString();
phieu.UserName = reader["UserName"].ToString();
phieu.PhiGiaoNhan = DUtils.ReadInt32(reader["PhiGiaoNhan"]);
phieu.IsPhieuHuy = DUtils.ReadBoolean(reader["IsPhieuHuy"]);
kq.Add(phieu);
}
reader.Close();
}
command.Connection.Close();
return kq;
}
public static ListPhieuEntity SelectOrderNotSync()
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = @"SELECT
dbo.Phieu.*,
dbo.KhachHang.TenKhachHang
FROM dbo.Phieu LEFT OUTER JOIN dbo.KhachHang ON dbo.Phieu.MaKhachHang = dbo.KhachHang.MaKhachHang
WHERE dbo.Phieu.[IsSynced] IS NULL OR dbo.Phieu.[IsSynced] = 0
ORDER BY dbo.Phieu.MaPhieu";
ListPhieuEntity kq = new ListPhieuEntity();
using (SqlDataReader reader = command.ExecuteReader())
{
PhieuEntity phieu = null;
while (reader.Read())
{
phieu = new PhieuEntity();
phieu.MaPhieu = Convert.ToInt64(reader["MaPhieu"]);
phieu.MaKhachHang = reader["MaKhachHang"] == DBNull.Value ? 0 : (Int64)reader["MaKhachHang"];
phieu.TenKhachHang = reader["TenKhachHang"].ToString();
phieu.NgayLap = (DateTime)reader["NgayLap"];
phieu.NgayHenTra = (DateTime)reader["NgayHenTra"];
if (reader["GiamGia"] != DBNull.Value)
phieu.GiamGia = Convert.ToInt32(reader["GiamGia"]);
phieu.DaThanhToan = (Boolean)reader["DaThanhToan"];
phieu.DaTraDo = (Boolean)reader["DaTraDo"];
phieu.TongTien = DUtils.ReadInt64(reader["TongTien"]);
if (reader["GhiChu"] != DBNull.Value)
phieu.GhiChu = reader["GhiChu"].ToString();
phieu.UserName = reader["UserName"].ToString();
phieu.PhiGiaoNhan = DUtils.ReadInt32(reader["PhiGiaoNhan"]);
phieu.IsPhieuHuy = DUtils.ReadBoolean(reader["IsPhieuHuy"]);
kq.Add(phieu);
}
reader.Close();
}
command.Connection.Close();
return kq;
}
public static Int64 SelectSumTongTienByMaPhieu(Int64 tuphieu, Int64 denphieu)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = @"SELECT SUM (TongTien) FROM dbo.Phieu
WHERE (IsPhieuHuy IS NULL OR IsPhieuHuy=0)
AND
MaPhieu >= @TuPhieu
AND
MaPhieu <= @DenPhieu";// "[dbo].[sp_Phieu_SelectTongTienByMaPhieu]";
SqlParameter param = new SqlParameter("@TuPhieu", SqlDbType.BigInt);
param.Value = tuphieu;
command.Parameters.Add(param);
param = new SqlParameter("@DenPhieu", SqlDbType.BigInt);
param.Value = denphieu;
command.Parameters.Add(param);
Int64 kq = 0;
Int64.TryParse(command.ExecuteScalar().ToString(), out kq);
command.Connection.Close();
return kq;
}
public static string SelectMaPhieuHuy(Int64 tuphieu, Int64 denphieu)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = @"SELECT maphieu FROM dbo.Phieu
WHERE IsPhieuHuy=1
AND
MaPhieu >= @TuPhieu
AND
MaPhieu <= @DenPhieu";
SqlParameter param = new SqlParameter("@TuPhieu", SqlDbType.BigInt);
param.Value = tuphieu;
command.Parameters.Add(param);
param = new SqlParameter("@DenPhieu", SqlDbType.BigInt);
param.Value = denphieu;
command.Parameters.Add(param);
string kq = string.Empty;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
kq += reader[0] + ", ";
}
reader.Close();
}
command.Connection.Close();
return kq.TrimEnd(',', ' ');
}
public static Int64 SelectMaxMaPhieu()
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_SelectByMaxMaPhieu]";
Int64 kq = 0;
Int64.TryParse(command.ExecuteScalar().ToString(), out kq);
command.Connection.Close();
return kq;
}
public static Int64 Insert(PhieuEntity phieu)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "sp_Phieu_Insert";
SqlParameter param = new SqlParameter("@NgayLap", SqlDbType.DateTime);
param.Value = phieu.NgayLap;
command.Parameters.Add(param);
if (phieu.MaKhachHang != 0)
{
param = new SqlParameter("@MaKhachHang", SqlDbType.BigInt, 8);
param.Value = phieu.MaKhachHang;
command.Parameters.Add(param);
}
param = new SqlParameter("@NgayHenTra", SqlDbType.DateTime);
param.Value = phieu.NgayHenTra;
command.Parameters.Add(param);
param = new SqlParameter("@GiamGia", SqlDbType.Int, 4);
param.Value = phieu.GiamGia;
command.Parameters.Add(param);
param = new SqlParameter("@DaThanhToan", SqlDbType.Bit, 1);
param.Value = phieu.DaThanhToan;
command.Parameters.Add(param);
param = new SqlParameter("@UserName", SqlDbType.VarChar, 50);
param.Value = phieu.UserName;
command.Parameters.Add(param);
param = new SqlParameter("@TongTien", SqlDbType.BigInt, 8);
param.Value = phieu.TongTien;
command.Parameters.Add(param);
if (!String.IsNullOrEmpty(phieu.GhiChu))
{
param = new SqlParameter("@GhiChu", SqlDbType.NVarChar, 200);
param.Value = phieu.GhiChu;
command.Parameters.Add(param);
}
if (phieu.PhiGiaoNhan > 0)
{
param = new SqlParameter("@PhiGiaoNhan", SqlDbType.Int, 4);
param.Value = phieu.PhiGiaoNhan;
command.Parameters.Add(param);
}
return Convert.ToInt64(command.ExecuteScalar());
}
public static Int32 Delete(Int64 maphieu, Boolean dathanhtoan, Boolean datrado)
{
SqlCommand command = DUtils.GetCommand();
if (dathanhtoan && datrado)
{
command.CommandType = System.Data.CommandType.Text;
command.CommandText = @"DELETE FROM ChiTietPhieu WHERE MaPhieu=" + maphieu;
command.ExecuteNonQuery();
}
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_Delete]";
SqlParameter param = new SqlParameter("@MaPhieu", SqlDbType.BigInt, 8);
param.Value = maphieu;
command.Parameters.Add(param);
return command.ExecuteNonQuery();
}
public static Int32 UpdateDaTraDo(Int64 maphieu) // update datrado=1, dathanhtoan=1
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_UpdateDaTraDo]";
SqlParameter param = new SqlParameter("@MaPhieu", SqlDbType.BigInt, 8);
param.Value = maphieu;
command.Parameters.Add(param);
param = new SqlParameter("@DaTraDo", SqlDbType.Bit, 1);
param.Value = true;
command.Parameters.Add(param);
Int32 result = command.ExecuteNonQuery();
UpdateIsSync(maphieu, false);
return result;
}
public static Int32 UpdateDaHuyPhieu(Int64 maphieu)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "update phieu set isphieuhuy=1 where maphieu=" + maphieu;
Int32 result = command.ExecuteNonQuery();
UpdateIsSync(maphieu, false);
return result;
}
public static Int32 UpdateIsSync(Int64 maphieu, bool isSynced)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = @"UPDATE dbo.Phieu SET IsSynced=" + (isSynced ? 1 : 0) + " WHERE MaPhieu=" + maphieu;
return command.ExecuteNonQuery();
}
public static Int32 UpdateUnSyncedAll()
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = @"UPDATE dbo.Phieu SET IsSynced=0";
return command.ExecuteNonQuery();
}
public static Int32 UpdateSoLanIn(Int64 maphieu, Int32 solanin)
{
SqlCommand command = DUtils.GetCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "[dbo].[sp_Phieu_UpdateSoLanIn]";
SqlParameter param = new SqlParameter("@MaPhieu", SqlDbType.BigInt, 8);
param.Value = maphieu;
command.Parameters.Add(param);
param = new SqlParameter("@SoLanIn", SqlDbType.Int);
param.Value = solanin;
command.Parameters.Add(param);
return command.ExecuteNonQuery();
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="SmartComponentExampleMessages.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using Mlos.SettingsSystem.Attributes;
using Mlos.SettingsSystem.StdTypes;
namespace ExternalIntegrationExample
{
/// <summary>
/// An enum describing the request type for this component.
/// </summary>
public enum ComponentRequestType
{
/// <summary>
/// A Get request type.
/// </summary>
Get,
/// <summary>
/// A Put request type.
/// </summary>
Put,
/// <summary>
/// A Delete request type.
/// </summary>
Delete,
}
/// <summary>
/// An enum describing the response type for the request.
/// </summary>
public enum ComponentResponseType
{
/// <summary>
/// A Success response type.
/// </summary>
Success,
/// <summary>
/// A Failure response type.
/// </summary>
Failure,
}
/// <summary>
/// A message to ask optimizer for the new configuration.
/// </summary>
/// <remarks>
/// Note: This message contains no members to detail the request.
/// It's very existence on the channel is signal enough of its intent.
/// </remarks>
[CodegenMessage]
public partial struct RequestConfigUpdateExampleMessage
{
}
/// <summary>
/// A telemetry message to inform the agent of the smart component's activity/state.
/// </summary>
/// <remarks>
/// Messages can be combined/aggregated by the agent in various ways before being passed to the optimizer.
/// </remarks>
[CodegenMessage]
public partial struct SmartComponentExampleTelemetryMessage
{
/// <summary>
/// The key for the Request.
/// </summary>
[ScalarSetting]
internal long RequestKey;
/// <summary>
/// What type of request it was.
/// </summary>
[ScalarSetting]
internal ComponentRequestType RequestType;
/// <summary>
/// The size of the request (or response in the case of Get).
/// </summary>
[ScalarSetting]
internal long RequestSize;
/// <summary>
/// The duration of the request.
/// </summary>
[ScalarSetting]
internal double RequestDuration;
/// <summary>
/// The status of the response.
/// </summary>
[ScalarSetting]
internal ComponentResponseType ResponseType;
/// <summary>
/// The size of the component.
/// </summary>
[ScalarSetting]
internal long Size;
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace ExternalApps.UnitTests
{
[TestClass]
public class CustomerTests
{
public Mock<Mail> _MockMail;
[TestInitialize]
public void SetUp()
{
_MockMail = new Mock<Mail>();
}
[TestMethod]
public void AddCustomer_Always_ReturnsTrue()
{
_MockMail.Setup(x => x.Send("smtp.gmail.com", "from@gmail.com", "jasdjasd93003endd=", "to@gmail.com", "subject", "body", 25));
Customer c1 = new Customer();
bool IsInserted = c1.AddCustomer(_MockMail.Object);
Assert.IsTrue(IsInserted);
Assert.AreEqual(IsInserted, true);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AIScript : MonoBehaviour {
public int myNumber;
public int commandWait;
private Engine myEngine;
private GameObject[] states;
void Awake () {
myEngine = GameObject.Find("GameEngine").GetComponent<Engine>();
states = GameObject.FindGameObjectsWithTag("Province");
StartCoroutine(runAI());
}
IEnumerator runAI(){
yield return new WaitForSeconds(commandWait);
int r = Random.Range(0, 38);
GameObject curState = states[r];
//grab the game engine object
GameObject tempEngine = GameObject.FindGameObjectWithTag("Engine");
//grab the script of the object
Engine tempEngineScript = tempEngine.GetComponent<Engine>();
for (int i = 2; i < 5; i++)
{
List<GameObject> myStates = tempEngineScript.stateOf(i);
//if the player has no states left, continue
if (myStates.Count == 0) { continue; }
//if the player has at least one state left
if (myStates.Count != 0)
{
//foreach state do a check if they are under attack
for (int j = 0; j < tempEngineScript.stateOf(i).Count; j++)
{
behaviour temp = myStates[j].GetComponent<behaviour>();
if (temp.listOfLocallyOwnedLocalVoters().Count > temp.garrisonValue)
{
//attack neighbour based on probability?
}
}
}
}
}
}
|
using MetroFramework;
using MetroFramework.Forms;
using NFe.Classes.Informacoes.Pagamento;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Custom;
using PDV.DAO.DB.Utils;
using PDV.DAO.Entidades;
using PDV.DAO.Entidades.Financeiro;
using PDV.UTIL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Cadastro.Financeiro.Modulo
{
public partial class FCAFIN_BaixaRecebimento : DevExpress.XtraEditors.XtraForm
{
public BaixaRecebimento BaixaRec = null;
private ContaReceber ContaRecebimento = null;
public bool Salvou = false;
public bool botaoSalvar = false;
private List<ContaBancaria> Contas = null;
private List<HistoricoFinanceiro> Historicos = null;
private List<FormaDePagamento> Formas = null;
public DataTable Cheques = null;
public decimal valorInicial;
public FCAFIN_BaixaRecebimento(ContaReceber _ContaRecebimento, BaixaRecebimento _BaixaRec)
{
InitializeComponent();
ContaRecebimento = _ContaRecebimento;
BaixaRec = _BaixaRec;
Contas = FuncoesContaBancaria.GetContasBancarias();
Historicos = FuncoesHistoricoFinanceiro.GetHistoricosFinanceiros();
Formas = FuncoesFormaDePagamento.GetFormasPagamento();
ovCMB_ContaBancaria.DataSource = Contas;
ovCMB_ContaBancaria.ValueMember = "idcontabancaria";
ovCMB_ContaBancaria.DisplayMember = "nome";
ovCMB_ContaBancaria.SelectedItem = null;
ovCMB_HistoricoFinanceiro.DataSource = Historicos;
ovCMB_HistoricoFinanceiro.ValueMember = "idhistoricofinanceiro";
ovCMB_HistoricoFinanceiro.DisplayMember = "descricao";
ovCMB_HistoricoFinanceiro.SelectedItem = null;
ovCMB_FormaPagamento.DataSource = Formas;
ovCMB_FormaPagamento.ValueMember = "idformadepagamento";
ovCMB_FormaPagamento.DisplayMember = "identificacaodescricaoformabandeira";
ovCMB_FormaPagamento.SelectedItem = null;
PreencherTela();
valorInicial = BaixaRec.Valor;
metroTabControl2.SelectedTab = metroTabPage5;
ovTXT_Valor.AplicaAlteracoes();
ovTXT_Multa.AplicaAlteracoes();
ovTXT_Juros.AplicaAlteracoes();
ovTXT_Desconto.AplicaAlteracoes();
ovTXT_Total.AplicaAlteracoes();
ovTXT_ValorRec.AplicaAlteracoes();
ovTXT_MultaRec.AplicaAlteracoes();
ovTXT_JurosRec.AplicaAlteracoes();
ovTXT_DescontoRec.AplicaAlteracoes();
ovTXT_TotalRec.AplicaAlteracoes();
ovTXT_SaldoRec.AplicaAlteracoes();
}
private void PreencherTela()
{
ovTXT_ValorRec.Value = ContaRecebimento.Valor;
ovTXT_MultaRec.Value = ContaRecebimento.Multa;
ovTXT_JurosRec.Value = ContaRecebimento.Juros;
ovTXT_DescontoRec.Value = ContaRecebimento.Desconto;
ovTXT_SaldoRec.Value = ContaRecebimento.Saldo;
ovTXT_TotalRec.Value = (ContaRecebimento.Valor - ContaRecebimento.Desconto) + ContaRecebimento.Multa + ContaRecebimento.Juros;
ovTXT_Valor.Value = BaixaRec.Valor != 0 ? BaixaRec.Valor : ContaRecebimento.Saldo;
ovTXT_Multa.Value = BaixaRec.Multa;
ovTXT_Juros.Value = BaixaRec.Juros;
ovTXT_Desconto.Value = BaixaRec.Desconto;
ovTXT_Total.Value = (BaixaRec.Valor - BaixaRec.Desconto) + BaixaRec.Juros + BaixaRec.Multa;
ovTXT_Baixa.Value = BaixaRec.Baixa;
ovCMB_ContaBancaria.SelectedItem = Contas.Where(o => o.IDContaBancaria == BaixaRec.IDContaBancaria).FirstOrDefault();
ovCMB_FormaPagamento.SelectedItem = Formas.Where(o => o.IDFormaDePagamento == BaixaRec.IDFormaDePagamento).FirstOrDefault();
ovCMB_HistoricoFinanceiro.SelectedItem = Historicos.Where(o => o.IDHistoricoFinanceiro == BaixaRec.IDHistoricoFinanceiro).FirstOrDefault();
ovTXT_Complemento.Text = BaixaRec.ComplmHisFin;
CarregarCheques(true);
}
private void metroButton5_Click(object sender, EventArgs e)
{
Salvou = false;
Close();
}
private void metroButton4_Click(object sender, EventArgs e)
{
try
{
if (!Validar())
return;
BaixaRec.Valor = ovTXT_Valor.Value;
BaixaRec.Multa = ovTXT_Multa.Value;
BaixaRec.Juros = ovTXT_Juros.Value;
BaixaRec.Desconto = ovTXT_Desconto.Value;
BaixaRec.Baixa = ovTXT_Baixa.Value;
BaixaRec.IDContaBancaria = (ovCMB_ContaBancaria.SelectedItem as ContaBancaria).IDContaBancaria;
BaixaRec.IDFormaDePagamento = (ovCMB_FormaPagamento.SelectedItem as FormaDePagamento).IDFormaDePagamento;
BaixaRec.IDHistoricoFinanceiro = (ovCMB_HistoricoFinanceiro.SelectedItem as HistoricoFinanceiro).IDHistoricoFinanceiro;
BaixaRec.ComplmHisFin = ovTXT_Complemento.Text;
Salvou = true;
Close();
botaoSalvar = true;
}
catch (Exception Ex)
{
Salvou = false;
MessageBox.Show(this, Ex.Message, "BAIXA DE RECEBIMENTO");
}
}
private bool Validar()
{
if (ovCMB_ContaBancaria.SelectedItem == null)
throw new Exception("Selecione o Portador.");
if (ovCMB_FormaPagamento.SelectedItem == null)
throw new Exception("Selecione a Forma de Pagamento.");
if (ovCMB_HistoricoFinanceiro.SelectedItem == null)
throw new Exception("Selecione o Histórico Financeiro.");
if(ovTXT_Valor.Value > ovTXT_SaldoRec.Value + valorInicial)
throw new Exception("O Valor Inserido Ultrapassa o Saldo.");
return true;
}
private bool ValidaFormaPagamento()
{
if (ovCMB_FormaPagamento.SelectedItem == null)
{
MessageBox.Show(this, "Selecione a Forma de Pagamento.", "BAIXA DE RECEBIMENTO");
return false;
}
if (((FormaPagamento)Enum.Parse(typeof(FormaPagamento), (ovCMB_FormaPagamento.SelectedItem as FormaDePagamento).Codigo.ToString())) != FormaPagamento.fpCheque)
{
MessageBox.Show(this, "A Forma de Pagamento não é Cheque.", "BAIXA DE RECEBIMENTO");
return false;
}
return true;
}
private void metroButton1_Click(object sender, EventArgs e)
{
if (!ValidaFormaPagamento())
return;
FCAFIN_ChequeRecebimento Form = new FCAFIN_ChequeRecebimento(new ChequeContaReceber());
Form.ShowDialog(this);
if (Form.Salvou)
{
DataRow dr = Cheques.NewRow();
dr["IDCHEQUECONTARECEBER"] = Sequence.GetNextID("CHEQUECONTARECEBER", "IDCHEQUECONTARECEBER");
dr["NUMERO"] = Form.ChequeRecebimento.Numero;
dr["EMISSAO"] = Form.ChequeRecebimento.Emissao;
dr["VENCIMENTO"] = Form.ChequeRecebimento.Vencimento;
dr["VALOR"] = Form.ChequeRecebimento.Valor;
dr["CRUZADO"] = Form.ChequeRecebimento.Cruzado;
dr["COMPENSADO"] = Form.ChequeRecebimento.Compensado;
dr["REPASSE"] = Form.ChequeRecebimento.Repasse;
dr["DEVOLVIDO"] = Form.ChequeRecebimento.Devolvido;
dr["DATACOMPENSACAO"] = DBNull.Value;
if (Form.ChequeRecebimento.DataCompensacao.HasValue)
dr["DATACOMPENSACAO"] = Form.ChequeRecebimento.DataCompensacao;
dr["DATADEVOLUCAO"] = DBNull.Value;
if (Form.ChequeRecebimento.DataDevolucao.HasValue)
dr["DATADEVOLUCAO"] = Form.ChequeRecebimento.DataDevolucao;
dr["DATAREPASSE"] = DBNull.Value;
if (Form.ChequeRecebimento.DataRepasse.HasValue)
dr["DATAREPASSE"] = Form.ChequeRecebimento.DataRepasse;
dr["OBSREPASSE"] = Form.ChequeRecebimento.ObsRepasse;
dr["IDBAIXARECEBIMENTO"] = BaixaRec.IDBaixaRecebimento;
Cheques.Rows.Add(dr);
}
CarregarCheques(false);
}
private void CarregarCheques(bool Banco)
{
if (Banco)
Cheques = FuncoesChequesCtaReceber.GetChequeContaReceber(BaixaRec.IDBaixaRecebimento);
gridControl1.DataSource = Cheques;
gridView.OptionsBehavior.Editable = false;
gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
gridView.BestFitColumns();
AjustaTextHeaderCheques();
}
private void AjustaTextHeaderCheques()
{
gridView.Columns[0].Visible = false;
gridView.Columns[1].Caption = "NÚMERO";
gridView.Columns[2].Caption = "EMISSÃO";
gridView.Columns[3].Caption = "VENCIMENTO";
gridView.Columns[4].Caption = "VALOR";
for (int i = 5; i < 14; i++)
{
gridView.Columns[i].Visible = false;
}
}
private void metroButton2_Click(object sender, EventArgs e)
{
if (!ValidaFormaPagamento())
return;
try
{
Cheques.DefaultView.RowFilter = "[IDCHEQUECONTARECEBER] = " + decimal.Parse(gridView.GetRowCellValue(gridView.FocusedRowHandle, "idchequecontareceber").ToString());
FCAFIN_ChequeRecebimento Form = new FCAFIN_ChequeRecebimento(EntityUtil<ChequeContaReceber>.ParseDataRow(Cheques.DefaultView[0].Row));
Form.ShowDialog(this);
if (Form.Salvou)
{
foreach (DataRowView drView in Cheques.DefaultView)
{
drView.BeginEdit();
drView["NUMERO"] = Form.ChequeRecebimento.Numero;
drView["EMISSAO"] = Form.ChequeRecebimento.Emissao;
drView["VENCIMENTO"] = Form.ChequeRecebimento.Vencimento;
drView["VALOR"] = Form.ChequeRecebimento.Valor;
drView["CRUZADO"] = Form.ChequeRecebimento.Cruzado;
drView["COMPENSADO"] = Form.ChequeRecebimento.Compensado;
drView["REPASSE"] = Form.ChequeRecebimento.Repasse;
drView["DEVOLVIDO"] = Form.ChequeRecebimento.Devolvido;
drView["DATACOMPENSACAO"] = DBNull.Value;
if (Form.ChequeRecebimento.DataCompensacao.HasValue)
drView["DATACOMPENSACAO"] = Form.ChequeRecebimento.DataCompensacao;
drView["DATADEVOLUCAO"] = DBNull.Value;
if (Form.ChequeRecebimento.DataDevolucao.HasValue)
drView["DATADEVOLUCAO"] = Form.ChequeRecebimento.DataDevolucao;
drView["DATAREPASSE"] = DBNull.Value;
if (Form.ChequeRecebimento.DataRepasse.HasValue)
drView["DATAREPASSE"] = Form.ChequeRecebimento.DataRepasse;
drView["OBSREPASSE"] = Form.ChequeRecebimento.ObsRepasse;
drView["IDBAIXARECEBIMENTO"] = BaixaRec.IDBaixaRecebimento;
drView.EndEdit();
}
}
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, "BAIXA RECEBIMENTO");
}
finally
{
Cheques.DefaultView.RowFilter = string.Empty;
CarregarCheques(false);
}
}
private void metroButton3_Click(object sender, EventArgs e)
{
if (!ValidaFormaPagamento())
return;
if (MessageBox.Show(this, "Deseja remover o Cheque selecionado?", "BAIXA RECEBIMENTO", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
try
{
Cheques.DefaultView.RowFilter = "[IDCHEQUECONTARECEBER] = " + decimal.Parse(gridView.GetRowCellValue(gridView.FocusedRowHandle, "idchequecontareceber").ToString());
foreach (DataRowView drView in Cheques.DefaultView)
drView.Delete();
}
catch (Exception Ex)
{
MessageBox.Show(this, Ex.Message, "BAIXA RECEBIMENTO", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
Cheques.DefaultView.RowFilter = string.Empty;
CarregarCheques(false);
}
}
}
private void ovTXT_Valor_ValueChanged(object sender, EventArgs e)
{
CalculaTotal();
}
private void CalculaTotal()
{
ovTXT_Total.Value = (ovTXT_Valor.Value - ovTXT_Desconto.Value) + ovTXT_Multa.Value + ovTXT_Juros.Value;
}
private void FCAFIN_BaixaRecebimento_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
this.Close();
break;
}
}
private void metroButton7_Click(object sender, EventArgs e)
{
}
private void metroButton8_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Data;
using System.Linq;
using AtmDb.Data;
using AtmDb.Model;
namespace AtmDb.ConsoleClient
{
public class ConsoleClient
{
public static IAtmDbData atmData = new AtmDbData();
public static void RetrieveMoneyFromAccount(CardAccount account, decimal amount)
{
using (var transaction = atmData.BeginTransaction(IsolationLevel.RepeatableRead))
{
try
{
var checkAccount = atmData.CardAccounts.Find(x => x.ID == account.ID).FirstOrDefault();
if (checkAccount == null)
{
throw new ArgumentException("No such account found.");
}
if (checkAccount.CardNumber != account.CardNumber || checkAccount.CardPin != account.CardPin)
{
throw new ArgumentException("Invalid card number or pin.");
}
if (checkAccount.CardCash <= amount)
{
throw new ArgumentException("Insufficient funds.");
}
checkAccount.CardCash -= amount;
atmData.SaveChanges();
transaction.Commit();
Console.WriteLine("Transaction successfull.");
UpdateTransactionLog(account, amount, MoneyTransactionType.Withdraw);
}
catch (Exception ex)
{
transaction.Rollback();
Console.WriteLine("Transaction failed: {0}", ex.Message);
}
}
}
private static void UpdateTransactionLog(CardAccount account, decimal amount, MoneyTransactionType transactionType)
{
using (var transaction = atmData.BeginTransaction())
{
try
{
var currentTransactionLog = new TransactionHistory()
{
CardNumber = account.CardNumber,
Amount = amount,
Action = transactionType
};
atmData.TransactionHistory.Add(currentTransactionLog);
atmData.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Console.WriteLine("Failed to add entry to transaction log: {0}", ex.Message);
}
}
}
public static void Main()
{
//var firstAccountToModify = atmData.CardAccounts.GetAll().FirstOrDefault();
//RetrieveMoneyFromAccount(firstAccountToModify, 50034m);
//var secondAccountToModify = new CardAccount()
//{
// ID = 10000001,
// CardNumber = firstAccountToModify.CardNumber,
// CardPin = firstAccountToModify.CardPin,
// CardCash = firstAccountToModify.CardCash
//};
//RetrieveMoneyFromAccount(secondAccountToModify, 100m);
//var thirdAccountToModify = new CardAccount()
//{
// ID = firstAccountToModify.ID,
// CardNumber = "asdfqwerzx",
// CardPin = firstAccountToModify.CardPin,
// CardCash = firstAccountToModify.CardCash
//};
//RetrieveMoneyFromAccount(thirdAccountToModify, 1000m);
//var fourthAccountToModify = new CardAccount()
//{
// ID = firstAccountToModify.ID,
// CardNumber = firstAccountToModify.CardNumber,
// CardPin = "asdf",
// CardCash = firstAccountToModify.CardCash
//};
//RetrieveMoneyFromAccount(fourthAccountToModify, 100m);
//firstAccountToModify.CardCash = 50m;
//RetrieveMoneyFromAccount(firstAccountToModify, 100m);
//var evenRecordsInCollection = atmData.CardAccounts.GetAll().Where(account => account.ID % 2 == 0).ToList();
//foreach (var account in evenRecordsInCollection)
//{
// RetrieveMoneyFromAccount(account, 50m);
//}
for (int i = 0; i < 10; i++)
{
var cardAccount = new CardAccount()
{
CardNumber = "123456789" + i
};
atmData.CardAccounts.Add(cardAccount);
}
}
}
}
|
using be.belgium.eid;
using GalaSoft.MvvmLight.CommandWpf;
using Newtonsoft.Json;
using nmct.ba.cashlessproject.model.WPF;
using nmct.ba.cashlessproject.organisation.customerApp.ViewModel.General;
using nmct.ba.cashlessproject.organisation.employeeApp.Helper;
using nmct.ba.cashlessproject.organisation.employeeApp.ViewModel.General;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace nmct.ba.cashlessproject.organisation.employeeApp.ViewModel.EmployeeApp
{
public class ServiceVM : ObservableObject, IPage
{
#region Properties
public string Name
{
get { return "Bediening"; }
}
private ObservableCollection<Tuple<Sale, String>> _bill;
public ObservableCollection<Tuple<Sale, String>> Bill
{
get
{
if (_bill == null)
_bill = new ObservableCollection<Tuple<Sale, String>>();
return _bill;
}
set
{
_bill = value;
OnPropertyChanged("Bill");
CheckButtonsEnabledDisabled();
}
}
private Tuple<Sale, String> _selectedBillProduct;
public Tuple<Sale, String> SelectedBillProduct
{
get
{
if (_selectedBillProduct == null)
_selectedBillProduct = new Tuple<Sale, String>(new Sale(), "");
return _selectedBillProduct;
}
set
{
_selectedBillProduct = value;
OnPropertyChanged("SelectedBillProduct");
CheckButtonsEnabledDisabled();
}
}
private List<Product> _products;
public List<Product> Products
{
get
{
if (_products == null)
_products = new List<Product>();
return _products;
}
set
{
_products = value;
OnPropertyChanged("Products");
}
}
private Product _selectedProduct;
public Product SelectedProduct
{
get
{
if (_selectedProduct == null)
_selectedProduct = new Product();
return _selectedProduct;
}
set
{
_selectedProduct = value;
OnPropertyChanged("SelectedProduct");
CheckButtonsEnabledDisabled();
}
}
private double _totalAmount;
public double TotalAmount
{
get { return _totalAmount; }
set
{
_totalAmount = value;
OnPropertyChanged("TotalAmount");
}
}
private double _temporaryAmount;
public double TemporaryAmount
{
get { return _temporaryAmount; }
set
{
_temporaryAmount = value;
OnPropertyChanged("TemporaryAmount");
}
}
private int _temporaryNumberOfProducts;
public int TemporaryNumberOfProducts
{
get { return _temporaryNumberOfProducts; }
set
{
_temporaryNumberOfProducts = value;
OnPropertyChanged("TemporaryNumberOfProducts");
CheckButtonsEnabledDisabled();
}
}
private Boolean _isAddProductEnabled;
public Boolean IsAddProductEnabled
{
get { return _isAddProductEnabled; }
set
{
_isAddProductEnabled = value;
OnPropertyChanged("IsAddProductEnabled");
}
}
private Boolean _isDeleteProductEnabled;
public Boolean IsDeleteProductEnabled
{
get { return _isDeleteProductEnabled; }
set
{
_isDeleteProductEnabled = value;
OnPropertyChanged("IsDeleteProductEnabled");
}
}
private Boolean _isCheckOutEnabled;
public Boolean IsCheckOutEnabled
{
get { return _isCheckOutEnabled; }
set
{
_isCheckOutEnabled = value;
OnPropertyChanged("IsCheckOutEnabled");
}
}
private Boolean _isLoginEnabled;
public Boolean IsLoginEnabled
{
get { return _isLoginEnabled; }
set
{
_isLoginEnabled = value;
OnPropertyChanged("IsLoginEnabled");
}
}
private Boolean _isLogoutEnabled;
public Boolean IsLogoutEnabled
{
get { return _isLogoutEnabled; }
set
{
_isLogoutEnabled = value;
OnPropertyChanged("IsLogoutEnabled");
}
}
private Customer _eIDCustromer;
public Customer EIDCustomer
{
get { return _eIDCustromer; }
set
{
_eIDCustromer = value;
OnPropertyChanged("EIDCustomer");
}
}
private Customer _currentCustomer;
public Customer CurrentCustomer
{
get
{
if (_currentCustomer == null)
_currentCustomer = new Customer();
return _currentCustomer;
}
set
{
_currentCustomer = value;
OnPropertyChanged("CurrentCustomer");
CheckButtonsEnabledDisabled();
}
}
private BitmapImage _currentCustomerPicture;
public BitmapImage CurrentCustomerPicture
{
get { return _currentCustomerPicture; }
set
{
_currentCustomerPicture = value;
OnPropertyChanged("CurrentCustomerPicture");
}
}
private Boolean _showServerMessage;
public Boolean ShowServerMessage
{
get { return _showServerMessage; }
set
{
_showServerMessage = value;
OnPropertyChanged("ShowServerMessage");
}
}
private String _serverMessage;
public String ServerMessage
{
get { return _serverMessage; }
set
{
_serverMessage = value;
OnPropertyChanged("ServerMessage");
}
}
private DispatcherTimer _timer;
public DispatcherTimer Timer
{
get { return _timer; }
set
{
_timer = value;
OnPropertyChanged("Timer");
}
}
#endregion
#region Constructor
public ServiceVM()
{
GetProducts();
CheckButtonsEnabledDisabled();
}
#endregion
#region Methods
/*
* Method to get all products from datbase.
*/
private async void GetProducts()
{
using (HttpClient client = new HttpClient())
{
String url = "http://localhost:49534/api/product";
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.GetAsync(url);
if(response.IsSuccessStatusCode)
{
String json = await response.Content.ReadAsStringAsync();
Products = JsonConvert.DeserializeObject<List<Product>>(json);
}
}
}
/*
* Method to get all products ordered alphabetically.
*/
private void OrderProductsAlphabetically()
{
Products = Products.OrderBy(p => p.ProductName).ToList();
}
/*
* Method to add an amount to a product.
*/
private void AddAmount(String amount)
{
TemporaryNumberOfProducts = Convert.ToInt32(amount);
}
/*
* Add a new item to the bill.
*/
private void AddToBill()
{
double testAmount = TemporaryAmount + (TemporaryNumberOfProducts * SelectedProduct.Price);
if(testAmount <= TotalAmount)
{
ShowServerMessage = false;
TemporaryAmount += (TemporaryNumberOfProducts * SelectedProduct.Price);
int registerID = Convert.ToInt32(ConfigurationManager.AppSettings["RegisterID"].ToString());
Sale sale = new Sale()
{
Amount = TemporaryNumberOfProducts,
CustomerID = CurrentCustomer.ID,
RegisterID = Convert.ToInt32(ConfigurationManager.AppSettings["RegisterID"].ToString()),
ProductID = SelectedProduct.ID,
//TimeStamp = ToUnixTimestamp(DateTime.Now),
TotalPrice = (TemporaryNumberOfProducts * SelectedProduct.Price)
};
Bill.Add(new Tuple<Sale, String>(sale, SelectedProduct.ProductName));
TemporaryNumberOfProducts = 0;
SelectedProduct = new Product();
}
else
{
ShowServerMessage = true;
ServerMessage = "Het saldo is ontoereikend.";
String message = "Een gebruiker plaatste een bestelling waardoor hij over zijn limiet zou gaan. Naam: " + CurrentCustomer.CustomerName + ", Rijksregisternummer: " + CurrentCustomer.NationalNumber + ".";
String stacktrace = System.Environment.StackTrace;
SendServerLog(message, stacktrace);
}
}
/*
* Delete an item from the bill.
*/
private void DeleteFromBill()
{
List<Product> deleteProduct = (List<Product>)from product in Products where product.ID.Equals(SelectedBillProduct.Item1.ProductID) select product;
TemporaryAmount -= (SelectedBillProduct.Item1.Amount * deleteProduct[0].Price);
Bill.Remove(SelectedBillProduct);
SelectedBillProduct = new Tuple<Sale, String>(new Sale(), "");
}
/*
* Check if buttons should be enabled or disabled.
*/
private void CheckButtonsEnabledDisabled()
{
if(SelectedProduct.ID > 0 && TemporaryNumberOfProducts > 0)
IsAddProductEnabled = true;
else
IsAddProductEnabled = false;
if (SelectedBillProduct.Item1.ProductID > 0)
IsDeleteProductEnabled = true;
else
IsDeleteProductEnabled = false;
if (Bill.Count > 0 && CurrentCustomer.ID > 0)
IsCheckOutEnabled = true;
else
IsCheckOutEnabled = false;
if (CurrentCustomer.ID > 0)
{
IsLogoutEnabled = true;
IsLoginEnabled = false;
}
else
{
IsLoginEnabled = true;
IsLogoutEnabled = false;
IsAddProductEnabled = false;
IsDeleteProductEnabled = false;
}
}
/*
* Get eID data of customer.
*/
private async void GetEIDData()
{
try
{
BEID_ReaderSet.initSDK(true);
BEID_ReaderSet readerSet = BEID_ReaderSet.instance();
BEID_ReaderContext reader = readerSet.getReader();
if(reader.isCardPresent())
{
BEID_EIDCard card = reader.getEIDCard();
BEID_EId doc = card.getID();
EIDCustomer = new Customer();
EIDCustomer.CustomerName = (doc.getFirstName() + " " + doc.getSurname());
EIDCustomer.NationalNumber = doc.getNationalNumber();
await LoginCustomer();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/*
* Login customer.
*/
private async Task LoginCustomer()
{
Boolean isCustomer = await IsCustomerInDatabase();
if (isCustomer)
ShowBalance();
else
Console.WriteLine("Post errorlog");
}
/*
* Check if customer is in database.
*/
private async Task<Boolean> IsCustomerInDatabase()
{
using (HttpClient client = new HttpClient())
{
String tempUrl = "http://localhost:49534/api/customer?nationalNumber=";
String url = String.Format("{0}{1}", tempUrl, EIDCustomer.NationalNumber);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
String json = await response.Content.ReadAsStringAsync();
CurrentCustomer = JsonConvert.DeserializeObject<Customer>(json);
AddCurrentCustomerPicture();
ShowServerMessage = false;
return true;
}
else
{
ShowServerMessage = true;
ServerMessage = "De gebruiker kon niet gevonden worden in de database.";
String message= "Er kon een gebruiker niet gevonden worden in de database. Naam: " + EIDCustomer.CustomerName + ", Rijksregisternummer: " + EIDCustomer.NationalNumber + ".";
String stacktrace = System.Environment.StackTrace;
SendServerLog(message, stacktrace);
CurrentCustomer = new Customer();
return false;
}
}
}
/*
* Show the current balance of the customer
*/
private void ShowBalance()
{
TotalAmount = CurrentCustomer.Balance;
}
/*
* Convert picture of current customer.
* Via: http://stackoverflow.com/a/9564425
*/
private void AddCurrentCustomerPicture()
{
if (CurrentCustomer.Picture == null || CurrentCustomer.Picture.Length == 0)
{
CurrentCustomerPicture = new BitmapImage();
return;
}
BitmapImage image = new BitmapImage();
using (MemoryStream mem = new MemoryStream(CurrentCustomer.Picture))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
CurrentCustomerPicture = image;
}
/*
* Check out.
*/
private async void CheckOut()
{
CurrentCustomer.Balance -= TemporaryAmount;
Boolean isSalesSaved = await SaveSales();
Boolean isCustomerSaved = false;
if (isSalesSaved)
isCustomerSaved = await SaveCustomerBalance();
if(isCustomerSaved && isSalesSaved)
{
CurrentCustomer = new Customer();
EIDCustomer = new Customer();
CurrentCustomerPicture = new BitmapImage();
Bill.Clear();
SelectedBillProduct = new Tuple<Sale, String>(new Sale(), "");
SelectedProduct = new Product();
TotalAmount = 0;
TemporaryAmount = 0;
TemporaryNumberOfProducts = 0;
ShowServerMessage = true;
ServerMessage = "De bestelling werd succesvol uitgevoerd.";
Timer = new DispatcherTimer();
Timer.Interval = TimeSpan.FromSeconds(5);
Timer.Tick += Timer_Tick;
Timer.Start();
}
}
/*
* Code for timer event.
*/
void Timer_Tick(object sender, EventArgs e)
{
ShowServerMessage = false;
Timer.Stop();
}
/*
* Save customer balance to database.
*/
private async Task<Boolean> SaveCustomerBalance()
{
using (HttpClient client = new HttpClient())
{
String url = "http://localhost:49534/api/customer";
String json = JsonConvert.SerializeObject(CurrentCustomer);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.PutAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
return true;
else
{
String message = "De volgende saldocorrectie kon niet opgeslagen worden: Naam:" + CurrentCustomer.CustomerName + ", Nieuw saldo: " + CurrentCustomer.Balance + ".";
String stacktrace = System.Environment.StackTrace;
SendServerLog(message, stacktrace);
return false;
}
}
}
/*
* Save sales list to the database.
*/
private async Task<Boolean> SaveSales()
{
using (HttpClient client = new HttpClient())
{
String url = "http://localhost:49534/api/sale";
List<Sale> temporaryBill = new List<Sale>();
foreach(Tuple<Sale, String> sale in Bill)
{
sale.Item1.TimeStamp = UnixTimestampConverter.ToUnixTimestamp(DateTime.Now);
temporaryBill.Add(sale.Item1);
}
String json = JsonConvert.SerializeObject(temporaryBill);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
return true;
else
{
String message = "De volgende verkoopsactie kon niet opgeslagen worden: " + "ProductID: " + Bill[0].Item1.ProductID + ", CustomerID: " + Bill[0].Item1.CustomerID + ", RegisterID: " + Bill[0].Item1.RegisterID + ", Aantal:" + Bill[0].Item1.Amount;
for (int i = 1; i < Bill.Count; i++)
{
message += " && ProductID: " + Bill[0].Item1.ProductID + ", CustomerID: " + Bill[0].Item1.CustomerID + ", RegisterID: " + Bill[0].Item1.RegisterID + ", Aantal:" + Bill[0].Item1.Amount;
}
String stacktrace = System.Environment.StackTrace;
SendServerLog(message, stacktrace);
return false;
}
}
}
/*
* Send server log.
*/
private async void SendServerLog(String message, String stackTrace)
{
Errorlog errorlog = new Errorlog()
{
RegisterID = Convert.ToInt32(ConfigurationManager.AppSettings["RegisterID"].ToString()),
TimeStamp = UnixTimestampConverter.ToUnixTimestamp(DateTime.Now),
Message = message,
StackTrace = stackTrace
};
using (HttpClient client = new HttpClient())
{
String url = "http://localhost:49534/api/errorlog";
String json = JsonConvert.SerializeObject(errorlog);
client.SetBearerToken(ApplicationVM.token.AccessToken);
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
Console.WriteLine("Errorlog written to database.");
else
Console.WriteLine("Errorog not written to database.");
}
}
private void LogoutCustomer()
{
CurrentCustomer = new Customer();
CurrentCustomerPicture = new BitmapImage();
EIDCustomer = new Customer();
TemporaryAmount = 0;
TotalAmount = 0;
Bill = new ObservableCollection<Tuple<Sale, String>>();
}
#endregion
#region Actions
public ICommand OrderProductsAlphabeticallyCommand
{
get { return new RelayCommand(OrderProductsAlphabetically); }
}
public ICommand AddAmountCommand
{
get { return new RelayCommand<String>(AddAmount); }
}
public ICommand AddToBillCommand
{
get { return new RelayCommand(AddToBill); }
}
public ICommand DeleteFromBillCommand
{
get { return new RelayCommand(DeleteFromBill); }
}
public ICommand ScanCardCommand
{
get { return new RelayCommand(GetEIDData); }
}
public ICommand CheckOutCommand
{
get { return new RelayCommand(CheckOut); }
}
public ICommand LogoutCustomerCommand
{
get { return new RelayCommand(LogoutCustomer); }
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; //A fájlkezeléshez kell
namespace Érettségi_felkeszítő
{
internal class Program
{
static void Main(string[] args)
{
//Változó típusok
int x = 2; //Egész szám
x++; // x = x + 1
x--; // x = x - 1
x += 3; // x = x + 3
x -= 3; // x = x - 3
double y = 3.14; //Tört
char z = 'a'; //Karakter
String a = "Alma"; //Szöveg
a += "beka"; // "Alma" + "beka" = "Almabeka"
a += z; // "Almabeka" + 'a' = "Almabekaa"
int[] tomb = new int[10]; //10 elemű tömb
List<int> list = new List<int>(); //Lista
int tomb1 = tomb[0]; //tomb 1. eleme
char alma1 = a[0]; //String 1. eleme
Console.WriteLine("alma"); //Kiírja azt hogy alma
String s = Console.ReadLine(); //Bekér egy szöveget és elmenti az s változóba
int szam = Convert.ToInt32(Console.ReadLine()); //Bekér egy számot
StreamWriter sw = new StreamWriter("file.txt"); //Megnyitjuk a file.txt-t íráshoz
sw.WriteLine("Egy sor"); //Beleír egy sort
sw.Close(); //Elmenti, majd bezárja a file.txt-t
StreamReader sr = new StreamReader("file.txt"); //Megnyitja a file.txt-t olvasáshoz
String sor = sr.ReadLine(); //Kiolvassuk az első sorát
sr.Close(); //Bezárjuk a file.txt-t
//Ciklus ami 10szer fut le
for (int i = 0; i < 10; i++)
{
}
//Ciklus ami addig fut amíg az i2 nem egyenlő 3-al
int i2 = 0;
while (i2!=3)
{
i2++;
}
//Ciklus ami egyszer mindenképp lefut, majd minden futás végén megnézi, hogy az i2 egyenlő e -3-al. Ha igen kilép
do
{
i2--;
} while (i2!=-3);
Random random = new Random(); //Random változó
for (int i = 0; i < tomb.Length; i++)
{
tomb[i] = random.Next(0, 11); //tömb elemeinek feltöltése 0-tól 10-ig random egeész számokkal
list.Add(random.Next(-3, 101)); //Adjunk a listához -3 és 100 közötti számokat
}
list.RemoveAt(2); //Töröljük a lista 3. elemét
//Legnagyobb/legkisebb elem kiválasztása
int max=tomb[0];
int min=tomb[0];
for(int i=0;i<tomb.Length;i++){
if(max<tomb[i]){
max=tomb[i];
}
if(min>tomb[i]){
min=tomb[i];
}
}
//Sorbarendezés növekvő sorrendbe
for (int i = 0; i < tomb.Length; i++)
{
for (int d = i; d < tomb.Length; d++)
{
if (tomb[i] > tomb[d])
{
int buff = tomb[i];
tomb[i] = tomb[d];
tomb[d] = buff;
}
}
}
//Írjuk ki a tömböt
for (int i = 0; i < tomb.Length; i++)
{
Console.WriteLine(tomb[i]);
}
//Jó ha tudod, de érettségin csak vész esetben használd!!
list.Sort();
list.Reverse();
list.Max();
list.Min();
tomb.Max();
tomb.Min();
//Várjunk egy billentyű lemonyásra a program kilépéséhez
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Garage.Aircrafts
{
class Aircraft : Vehicles.Vehicle
{
public string FuelCapacity { get; set; }
//public string PassengerOccupancy { get; set; }
//public string Color { get; set; }
public override void Refuel()
{
Console.WriteLine("I'm refueling. Going to make sure to delay the flight by 6 hours.");
}
public void Flying()
{
Console.WriteLine("We're literally flying right now");
}
public void Landing()
{
Console.WriteLine("I don't know how to land a plane...");
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
namespace DotNetNuke.ExtensionPoints
{
public interface IUserControlExtensionPoint : IExtensionPoint
{
string UserControlSrc { get; }
bool Visible { get; }
}
}
|
using System;
class MainClass
{
public static void Main ()
{
Console.WriteLine ("enter an integer:");
int n = int.Parse (Console.ReadLine ());
for (int i = 1; i <= n; i++) {
Console.WriteLine (i);
}
}
}
|
public static class Storage
{
public static float BusHealth { get; set; } = 100;
public enum GameState
{
Coffee,
Bus
}
public static GameState CurrentGameState { get; set; } = GameState.Bus;
}
|
using UnityEngine;
using System.Collections;
public class GUIScript : MonoBehaviour {
public float timeToWin;
MovementScript player;
// Use this for initialization
void Start () {
player = GameObject.Find("playerShip").GetComponent<MovementScript>();
}
// Update is called once per frame
void Update () {
if(player.life > 0 && timeToWin > 0)
{
timeToWin -= Time.deltaTime;
}
}
void OnGUI()
{
string minutes = Mathf.Floor(timeToWin / 60).ToString("00");
string seconds = (timeToWin % 60).ToString("00");
GUI.Label(new Rect(10, 10, 100, 20),"Time: "+minutes+":"+seconds);
if(player.life > 0 && timeToWin <= 0)
{
GUI.Label(new Rect(Screen.width / 2, Screen.height / 2 - 60f, 90f , 60f),"You win! :D");
if(GUI.Button(new Rect(Screen.width / 2, Screen.height / 2 + 30f, 90f , 60f),"Play Again!"))
{
Application.LoadLevel("GameScene");
}
}
if(player.life <= 0 && timeToWin > 0)
{
GUI.Label(new Rect(Screen.width / 2, Screen.height / 2 - 60f, 90f , 60f),"You lost! :(");
if(GUI.Button(new Rect(Screen.width / 2, Screen.height / 2 + 30f, 90f , 60f),"Play Again!"))
{
Application.LoadLevel("GameScene");
}
}
}
}
|
using AutoMapper;
namespace Athena.Data.Borrowings {
public class BorrowingProfile : Profile {
public BorrowingProfile() {
CreateMap<Borrowing, BorrowingView>().ReverseMap();
}
}
} |
using System;
using System.Globalization;
namespace Projeto_caixa {
class Program {
static void Main(string[] args) {
Conta conta;
Console.Write("Entre com o numero da conta: ");
int numero = int.Parse(Console.ReadLine());
Console.Write("Entre com titular da conta: ");
string titular = Console.ReadLine();
Console.WriteLine("Havera deposito inicial? [s/n]? ");
char resp = char.Parse(Console.ReadLine());
if (resp == 's' || resp == 'S') {
Console.Write("Entre com o valor do deposito: ");
double depositoInicial = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
conta = new Conta(numero, titular, depositoInicial);
}
else {
conta = new Conta(numero, titular);
}
Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
Console.WriteLine("Dados da conta " + conta);
Console.WriteLine("Entre com o valor para deposito: ");
double quantia = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
conta.Deposito(quantia);
Console.WriteLine("Dados da conta Atualizados: ");
Console.WriteLine(conta);
Console.WriteLine("Entre com o valor para saque: ");
quantia = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
conta.Saque(quantia);
Console.WriteLine("Dados da conta Atualizados: ");
Console.WriteLine(conta);
Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
Console.Write("Quer continuar? [s/n] ");
resp = char.Parse(Console.ReadLine());
while (resp == 's' || resp == 'S') {
Console.WriteLine("Aguarde! ATUALIZANDO DADOS DA CONTA...");
Console.WriteLine("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
Console.Write("Para deposito pressione [1] , Saque [2] SAIR [3] : ");
char resp1 = char.Parse(Console.ReadLine());
if (resp1 == '1') {
Console.Write("Entre com valor para depositar novamente: ");
quantia = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
conta.Deposito(quantia);
Console.WriteLine("Dados da conta Atualizados: ");
Console.WriteLine(conta);
}
else if (resp1 == '2') {
Console.Write("Entre com valor para sacar novamente: ");
quantia = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
conta.Saque(quantia);
Console.WriteLine("Dados da conta Atualizados: ");
Console.WriteLine(conta);
}
else if(resp1 == 'n' || resp1 == '3') {
break;
}
if (conta.Saldo <= -5 && conta.Saldo >= -10) {
Console.WriteLine(">>>>> Você vai se dar mal, controle-se<<<<<");
}
if (conta.Saldo <= -10) {
Console.WriteLine(">>>>> CUIDADO! O SPC VAI TE CAÇAR !!! <<<<<");
}
}
Console.WriteLine("Dados da conta Atualizados: ");
Console.WriteLine(conta);
Console.WriteLine("****************************");
Console.WriteLine("Dica: Não gaste além do que você ganha. Até LOGO ! ");
}
}
}
|
using System;
using HaloSharp.Model.Stats.CarnageReport;
namespace HaloHistory.Business.Entities.Stats
{
public class ArenaMatchData : BaseDataEntity<string, ArenaMatch>
{
public ArenaMatchData()
{
}
public ArenaMatchData(Guid id, ArenaMatch data) : base(id.ToString(), data)
{
}
}
}
|
using DAL.Repo;
using Entities.Models;
using System.Collections.Generic;
using System.Data.Entity;
using MoreLinq;
namespace BL.Services
{
public class ServiceSemaine
{
static public void addSemaine(Semaine semaine)
{
using (SemaineRepository semainerepo = new SemaineRepository())
{
semainerepo.Add(semaine);
semainerepo.Save();
semainerepo.context.Entry(semaine).State = EntityState.Detached;
}
}
static public void updateSemaine(Semaine semaine)
{
using (SemaineRepository semainerepo = new SemaineRepository())
{
semainerepo.Update(semaine);
semainerepo.Save();
semainerepo.context.Entry(semaine).State = EntityState.Detached;
}
}
static public List<Semaine> getAllsem()
{
List<Semaine> allsem;
using (SemaineRepository semainerepo = new SemaineRepository())
{
allsem = (List<Semaine>) semainerepo.GetAll();
foreach (var item in allsem)
{
semainerepo.context.Entry(item).State = EntityState.Detached;
}
}
return allsem;
}
static public Semaine getCurrentSemaine()
{
//List<Semaine> lists;
Semaine semaine;
using (SemaineRepository semainerepo = new SemaineRepository())
{
//lists = (List<Semaine>)semainerepo.GetAll();
//foreach (var item in lists)
//{
// semainerepo.context.Entry(item).State = EntityState.Detached;
//}
semaine = semainerepo.GetCurrent();
semainerepo.context.Entry(semaine).State = EntityState.Detached;
}
//return lists.MaxBy(s => s.SemaineId);
return semaine;
}
static public Semaine getCurrentSemaineWD()
{
Semaine semaine;
using (SemaineRepository semainerepo = new SemaineRepository())
{
semaine = semainerepo.GetCurrent();
}
return semaine;
}
static public Semaine getLastSemaine()
{
Semaine semaine;
using (SemaineRepository semainerepo = new SemaineRepository())
{
semaine = semainerepo.GetLast();
semainerepo.context.Entry(semaine).State = EntityState.Detached;
}
return semaine;
}
static public Semaine getLastSemaineWD()
{
Semaine semaine;
using (SemaineRepository semainerepo = new SemaineRepository())
{
semaine = semainerepo.GetLast();
}
return semaine;
}
}
}
|
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Webcorp.lib.onedcut
{
public class Beams : ReactiveList<BeamToCut>
{
public Beams():base()
{
}
public Beams(IEnumerable<BeamToCut> e):base(e)
{
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fighter : MonoBehaviour
{
[SerializeField] Weapon weaponPrefab;
[SerializeField] Transform leftHandTransform;
[SerializeField] Transform rightHandTransform;
[SerializeField] float attackAnimationSpeedMult = 1f;
//CACHE REFERENCES
Health health;
//PROPERTIES
public int TargetLayerIndex { get; private set; }
public int TargetLayerMask { get { return 1 << TargetLayerIndex; } }
public bool IsMelee { get
{
if (weaponPrefab is MeleeWeapon) return true; //Check weapon type
else return false;
}
}
public MeleeWeapon MeleeWeapon { get; private set; }
public RangeWeapon RangeWeapon { get; private set; }
private void Awake()
{
health = GetComponent<Health>();
//Modify attack animation speed
GetComponent<Animator>().SetFloat("attackSpeed", attackAnimationSpeedMult);
Setup();
}
//Set target layer so weapons damage enemies of this entity
private void Setup()
{
int enemyLayer = LayerMask.NameToLayer("Enemy");
int playerLayer = LayerMask.NameToLayer("Player");
if (gameObject.layer == playerLayer) TargetLayerIndex = enemyLayer;
else TargetLayerIndex = playerLayer;
AttachWeapon();
}
//Instantiates weapon prefab to correct hand on the character
private void AttachWeapon()
{
Transform weaponParent; //Weapon parented to hand
if (weaponPrefab.IsRightHanded) weaponParent = rightHandTransform;
else weaponParent = leftHandTransform;
Weapon weaponInstance = Instantiate(weaponPrefab, weaponParent);
weaponInstance.TargetLayerMask = TargetLayerMask;
if (weaponInstance is MeleeWeapon) MeleeWeapon = (MeleeWeapon)weaponInstance;
else RangeWeapon = (RangeWeapon)weaponInstance;
}
public void Attack()
{
if (IsMelee) MeleeWeapon.UseWeapon();
else RangeWeapon.UseWeapon();
}
//Called by attack animation event
void Hit()
{
if (health.IsDead) return; //Must be alive to cause damage
MeleeWeapon.Hit();
}
//Called by attack animation event
void Shoot()
{
if (health.IsDead) return;
RangeWeapon.Shoot();
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Application.Core;
using Application.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Persistence;
using System.Linq;
namespace Application.Photos
{
public class Delete
{
public class Command: IRequest<Result<Unit>>
{
public string Id { get; set; }
}
public class Handler : IRequestHandler<Command, Result<Unit>>
{
DataContext _context;
IPhotoAccessor _photoAccessor;
IUserAccessor _userAccessor;
public Handler(DataContext context, IPhotoAccessor photoAccessor, IUserAccessor userAccessor)
{
_context = context;
_photoAccessor = photoAccessor;
_userAccessor = userAccessor;
}
public async Task<Result<Unit>> Handle(Command request, CancellationToken cancellationToken)
{
var user = await _context.Users.Include(p=>p.Photos).FirstOrDefaultAsync(x=>x.UserName==_userAccessor.GetUserName());
if(user == null) return null;
var photo = user.Photos.FirstOrDefault(x=>x.Id ==request.Id);
if(photo == null) return null;
if(photo.IsMain) return Result<Unit>.Faliure("You cannot delete your main photo");
var result = await _photoAccessor.DeletePhoto(request.Id);
if(result == null) return Result<Unit>.Faliure("Problem deleting photo from cloud");
user.Photos.Remove(photo);
var sucess = await _context.SaveChangesAsync() > 0;
if(sucess) return Result<Unit>.Sucess(Unit.Value);
return Result<Unit>.Faliure("Problem deleting photo from API");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace OnSale.Web.Data.Entity
{
public class Currency
{
public int CurrencyID { get; set; }
[DisplayName("Codigo Divisa")]
[MaxLength(50)]
[Range(0, int.MaxValue, ErrorMessage = "Favor Digite un Numero Entero Valido")]
[Required]
public int CurrencyCode { get; set; }
[DisplayName("Nombre Divisa")]
[MaxLength(50)]
[StringLength(50, ErrorMessage = "Debe tener entre {2} y {1} Caracteres", MinimumLength = 3)]
[Required(ErrorMessage = "El Campo {0} es Requerido")]
public string CurrencyName { get; set; }
}
}
|
using System;
using Workout.Services;
using Workout.Services.Settings;
namespace Workout.Models
{
/// <summary>
/// Provides HRM related data.
/// </summary>
public class HeartRateMonitorModel
{
#region fields
/// <summary>
/// Constant from research of <see href="https://en.wikipedia.org/wiki/Heart_rate">Haskell & Fox</see>.
/// </summary>
private const int _haskellFoxConstant = 220;
/// <summary>
/// How many times maximum Bpm value is greater than minimum value.
/// </summary>
private const int _maxToMinRatio = 2;
/// <summary>
/// Number of Bpm ranges into which the scale is divided.
/// </summary>
private const int _bpmRanges = 6;
/// <summary>
/// An instance of the HeartRateMonitorService service.
/// </summary>
private readonly HeartRateMonitorService _service;
/// <summary>
/// Bpm scale start point value.
/// </summary>
private readonly int _maxBpm;
/// <summary>
/// Bpm scale end point value.
/// </summary>
private readonly int _minBpm;
/// <summary>
/// Flag indicating whether HRM measurement is paused or not.
/// </summary>
private bool _isMeasurementPaused;
/// <summary>
/// Array of Bpm range occurrences.
/// </summary>
private int[] _bpmRangeOccurrences;
#endregion
#region properties
/// <summary>
/// Updated event.
/// Notifies about heart rate value update.
/// </summary>
public event EventHandler<HeartRateMonitorUpdatedEventArgs> Updated;
/// <summary>
/// NotSupported event.
/// Notifies about lack of heart rate sensor.
/// </summary>
public event EventHandler NotSupported;
#endregion
#region methods
/// <summary>
/// Initializes value of _bpmRangeOccurrences field.
/// </summary>
private void InitializeBpmRangeOccurrences()
{
_bpmRangeOccurrences = new int[_bpmRanges];
}
/// <summary>
/// Handles "DataUpdated" of the HeartRateMonitorService object.
/// Invokes "Updated" to other application's modules.
/// </summary>
/// <param name="sender">The object that raised the event.</param>
/// <param name="bpm">Heart rate value.</param>
private void OnServiceDataUpdated(object sender, int bpm)
{
double normalizedBpm = Math.Clamp((bpm - _minBpm) / (double)(_maxBpm - _minBpm), 0, 1);
int bpmRange = bpm < _minBpm ? 0 : Math.Min((int)((normalizedBpm * (_bpmRanges - 1)) + 1), _bpmRanges - 1);
if (!_isMeasurementPaused)
{
_bpmRangeOccurrences[bpmRange]++;
}
Updated?.Invoke(this, new HeartRateMonitorUpdatedEventArgs(new HeartRateMonitorData
{
Bpm = bpm,
BpmRange = bpmRange,
BpmRangeOccurrences = _bpmRangeOccurrences,
NormalizedBpm = normalizedBpm
}));
}
/// <summary>
/// Handles "NotSupported" of the HeartRateMonitorService object.
/// Invokes "NotSupported" to other application's modules.
/// </summary>
/// <param name="sender">The object that raised the event.</param>
/// <param name="args">Event arguments. Not used.</param>
private void OnServiceNotSupported(object sender, EventArgs args)
{
NotSupported?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// HeartRateMonitorModel class constructor.
/// </summary>
public HeartRateMonitorModel()
{
_maxBpm = _haskellFoxConstant - SettingsService.Instance.Age;
_minBpm = _maxBpm / _maxToMinRatio;
_service = new HeartRateMonitorService();
_service.DataUpdated += OnServiceDataUpdated;
_service.NotSupported += OnServiceNotSupported;
InitializeBpmRangeOccurrences();
_service.Init();
}
/// <summary>
/// Starts notification about changes of heart rate value.
/// </summary>
public void Start()
{
_isMeasurementPaused = false;
_service.Start();
}
/// <summary>
/// Stops notification about changes of heart rate value.
/// </summary>
public void Stop()
{
_service.Stop();
}
/// <summary>
/// Pauses HRM measurement.
/// </summary>
public void Pause()
{
_isMeasurementPaused = true;
}
/// <summary>
/// Resets HRM measurement.
/// </summary>
public void Reset()
{
InitializeBpmRangeOccurrences();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Darek_kancelaria.Models
{
public class CaseModel
{
public int Id { get; set; }
[Required]
[Display(Name ="Rodzaj sprawy")]
public string Type { get; set; }
[Required]
[Display(Name = "Instancja")]
public string Instance { get; set; }
[Display(Name = "Sygnatura akt")]
public string ActSignature { get; set; }
[Required]
[Display(Name ="Cena")]
public string PriceAll { get; set; }
public string UserId { get; set; }
public string Result { get; set; }
public bool Status { get; set; }
public DateTime AddDate { get; set; }
public virtual ICollection<EvidenceModel> EvidenceModels { get; set; }
public virtual ICollection<DocumentModel> DocumentsModels { get; set; }
public virtual ICollection<Termcs> Terms { get; set; }
public virtual ICollection<Price> Price { get; set; }
public Dictionary<string, string> CaseType = new Dictionary<string, string>();
public CaseModel()
{
CaseType.Add("C", "Cywilna - tryb dla wszczętych przed tym sądem na skutek pozwu lub skargi o uchylenie wyroku sądu polubownego spraw cywilnych rozpoznawanych w procesie");
CaseType.Add("GC", "Gospodarcza - tryb dla wszczętych przed tym sądem spraw gospodarczych rozpoznawanych w procesie na skutek pozwu lub skargi o uchylenie wyroku sądu polubownego");
CaseType.Add("GNs", "Gospodarcza - tryb nieprocesowy");
CaseType.Add("GNc", "Gospodarcza - tryb postępowania nakazowy lub upominawczy");
CaseType.Add("GNo", "Gospodarcza - tryb spraw rozpoznawanych według przepisów o procesie i o sądzie polubownym");
CaseType.Add("GCps", "Gospodarcza - tryb w którym rejestruje się wnioski o udzielenie pomocy sądowej w sprawach gospodarczych");
CaseType.Add("Ga", "Gospodarcza - tryb spraw gospodarczych przedstawionych z apelacjami od orzeczeń sądów rejonowych");
CaseType.Add("Gz", "Gospodarcza - tryb spraw gospodarczych przedstawionych z zażaleniami na postanowienia rejonowych sądów rejonowych i zarządzenia wydane w postępowaniu przed tymi sądami");
CaseType.Add("GU", "Gospodarcza - tryb spraw o ogłoszenie upadłości, dla spraw o wtórne postępowanie upadłościowe oraz o uznanie zagranicznego postępowania upadłościowego, a także o uchylenie i zmianę orzeczenia o uznaniu");
CaseType.Add("GUp", "Gospodarcza - tryb spraw upadłościowych po ogłoszeniu upadłości, w tym dla wtórnych postępowań upadłościowych");
CaseType.Add("GN", "Gospodarcza - tryb spraw z zakresu postępowania naprawczego");
CaseType.Add("Gzd", "Gospodarcza - tryb spraw o zakaz prowadzenia działalności gospodarczej");
CaseType.Add("GUu", "Gospodarcza - tryb spraw o zmianę i uchylenie układu zawartego w postępowaniu upadłościowym i naprawczym");
CaseType.Add("Ns", "Cywilna - tryb spraw cywilnych rozpoznawanych w trybie postępowania nieprocesowego");
CaseType.Add("Nc", "Cywilna - tryb spraw wszczętych przed tym sądem w postępowaniu nakazowym i upominawczym");
CaseType.Add("Nc-e", "Cywilna - tryb spraw wszczętych w Elektronicznym Postępowaniu Upominawczym");
CaseType.Add("Co", "Cywilna - dla innych spraw cywilnych rozpoznawanych według przepisów o procesie i o sądzie polubownym");
CaseType.Add("CG-G", "Cywilna - tryb dla spraw z zakresu prawa geologicznego i górniczego");
CaseType.Add("Cps", "Cywilna - tryb w którym rejestruje się wnioski o udzielenie pomocy sądowej w sprawach cywilnych");
CaseType.Add("Ca", "Cywilna - tryb dla spraw przedstawionych z apelacjami od orzeczeń sądów rejonowych");
CaseType.Add("Cz", "Cywilna - tryb spraw przedstawionych z zażaleniami na postanowienia sądów rejonowych i zarządzenia wydane w postępowaniu przed tymi sądami");
CaseType.Add("Cz-e", "Cywilna - tryb spraw przedstawionych z zażaleniami na postanowienia i zarządzenia wydane w Elektronicznym Postępowaniu Upominawczym");
CaseType.Add("GR", "Upadłościowa i restrukturyzacyjna - tryb spraw o otwarcie postępowania restrukturyzacyjnego");
CaseType.Add("GRz", "Upadłościowa i restrukturyzacyjna - tryb spraw restrukturyzacyjnych po wpłynięciu wniosku o zatwierdzenie układu w postępowaniu o zatwierdzenie układu");
CaseType.Add("GRu", "Upadłościowa i restrukturyzacyjna - tryb spraw restrukturyzacyjnych po otwarciu postępowania układowego");
CaseType.Add("GRs", "Upadłościowa i restrukturyzacyjna - tryb spraw restrukturyzacyjnych po otwarciu postępowania sanacyjnego");
CaseType.Add("GRo", "Upadłościowa i restrukturyzacyjna - tryb dla wszczętych przed sądem restrukturyzacyjnym spraw rozpoznawanych według przepisów k.p.c., w tym spraw z wniosku Ministra Sprawiedliwości złożonego na podstawie art. 18a ust. 1 ustawy o licencji doradcy restrukturyzacyjnego");
CaseType.Add("GUo", "Upadłościowa i restrukturyzacyjna - tryb dla wszczętych przed sądem upadłościowym spraw rozpoznawanych według przepisów k.p.c., w tym powództwa o wyłączenie z masy upadłości oraz spraw z wniosku Ministra Sprawiedliwości złożonego na podstawie art. 18a ust. 1 ustawy o licencji doradcy restrukturyzacyjnego");
}
}
public class Cases
{
public CaseModel Case { get; set; }
public PersonModel personelModel { get; set; }
public List<CaseModel> CasesList { get; set; }
}
} |
using System;
using System.Text;
namespace ShCore.Utility
{
/// <summary>
/// Thư viện
/// </summary>
public class Function : Singleton<Function>
{
private string abc = "abcdefghijklmnopqrstuvwxyz0123456789";
/// <summary>
/// Đối tượng tạo random
/// </summary>
private Random rnd = new Random();
/// <summary>
/// Tạo chuỗi Random
/// </summary>
/// <returns></returns>
public string Random(int length)
{
var ret = new StringBuilder();
for (int i = 0; i < length; i++)
ret.Append(abc.Substring(rnd.Next(abc.Length), 1));
return ret.ToString();
}
}
}
|
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Condition))]
public class ConditionEditor :Editor
{
} |
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd 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 Sensor.Tizen.Mobile;
using Sensor.Tizen.Mobile.Sensors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tizen.Sensor;
[assembly: Xamarin.Forms.Dependency(implementorType: typeof(SensorManager))]
namespace Sensor.Tizen.Mobile
{
/// <summary>
/// SensorManager Implementation class
/// </summary>
public class SensorManager : ISensorManager
{
private static Dictionary<string, ISensorAdapter> sensorList = new Dictionary<string, ISensorAdapter>();
/// <summary>
/// Initialize sensor list.
/// </summary>
private void Initialize()
{
if (Accelerometer.IsSupported)
{
sensorList.Add(SensorTypes.AccelerometerType, new AccelerometerAdapter());
}
if (FaceDownGestureDetector.IsSupported)
{
sensorList.Add(SensorTypes.FaceDownGestureDetectorType, new FaceDownGestureDetectorAdapter());
}
if (GravitySensor.IsSupported)
{
sensorList.Add(SensorTypes.GravitySensorType, new GravitySensorAdapter());
}
if (Gyroscope.IsSupported)
{
sensorList.Add(SensorTypes.GyroscopeType, new GyroscopeAdapter());
}
if (GyroscopeRotationVectorSensor.IsSupported)
{
sensorList.Add(SensorTypes.GyroscopeRotationVectorType, new GyroscopeRotationVectorSensorAdapter());
}
if (HeartRateMonitor.IsSupported)
{
sensorList.Add(SensorTypes.HeartRateMonitorType, new HeartRateMonitorAdapter());
}
if (HumiditySensor.IsSupported)
{
sensorList.Add(SensorTypes.HumiditySensorType, new HumiditySensorAdapter());
}
if (InVehicleActivityDetector.IsSupported)
{
sensorList.Add(SensorTypes.InVehicleActivityDetectorType, new InVehicleActivityDetectorAdapter());
}
if (LightSensor.IsSupported)
{
sensorList.Add(SensorTypes.LightSensorType, new LightSensorAdapter());
}
if (LinearAccelerationSensor.IsSupported)
{
sensorList.Add(SensorTypes.LinearAccelerationSensorType, new LinearAccelerationSensorAdapter());
}
if (Magnetometer.IsSupported)
{
sensorList.Add(SensorTypes.MagnetometerType, new MagnetometerAdapter());
}
if (MagnetometerRotationVectorSensor.IsSupported)
{
sensorList.Add(SensorTypes.MagnetometerRotationVectorType, new MagnetometerRotationVectorSensorAdapter());
}
if (OrientationSensor.IsSupported)
{
sensorList.Add(SensorTypes.OrientationSensorType, new OrientationSensorAdapter());
}
if (Pedometer.IsSupported)
{
sensorList.Add(SensorTypes.PedometerType, new PedometerAdapter());
}
if (PickUpGestureDetector.IsSupported)
{
sensorList.Add(SensorTypes.PickUpGestureDetectorType, new PickUpGestureDetectorAdapter());
}
if (PressureSensor.IsSupported)
{
sensorList.Add(SensorTypes.PressureSensorType, new PressureSensorAdapter());
}
if (ProximitySensor.IsSupported)
{
sensorList.Add(SensorTypes.ProximitySensorType, new ProximitySensorAdapter());
}
if (RotationVectorSensor.IsSupported)
{
sensorList.Add(SensorTypes.RotationVectorSensorType, new RotationVectorSensorAdapter());
}
if (RunningActivityDetector.IsSupported)
{
sensorList.Add(SensorTypes.RunningActivityDetectorType, new RunningActivityDetectorAdapter());
}
if (SleepMonitor.IsSupported)
{
sensorList.Add(SensorTypes.SleepMonitorType, new SleepMonitorAdapter());
}
if (StationaryActivityDetector.IsSupported)
{
sensorList.Add(SensorTypes.StationaryActivityDetectorType, new StationaryActivityDetectorAdapter());
}
if (TemperatureSensor.IsSupported)
{
sensorList.Add(SensorTypes.TemperatureSensorType, new TemperatureSensorAdapter());
}
if (UltravioletSensor.IsSupported)
{
sensorList.Add(SensorTypes.UltravioletSensorType, new UltravioletSensorAdapter());
}
if (UncalibratedGyroscope.IsSupported)
{
sensorList.Add(SensorTypes.UncalibratedGyroscopeType, new UncalibratedGyroscopeAdapter());
}
if (UncalibratedMagnetometer.IsSupported)
{
sensorList.Add(SensorTypes.UncalibratedMagnetometerType, new UncalibratedMagnetometerAdapter());
}
if (WalkingActivityDetector.IsSupported)
{
sensorList.Add(SensorTypes.WalkingActivityDetectorType, new WalkingActivityDetectorAdapter());
}
if (WristUpGestureDetector.IsSupported)
{
sensorList.Add(SensorTypes.WristUpGestureDetectorType, new WristUpGestureDetectorAdapter());
}
}
/// <summary>
/// Gets supported sensor types on the current device.
/// </summary>
/// <returns>Sensor types</returns>
public List<string> GetSensorTypeList()
{
List<string> sensorTypeList = new List<string>();
PrivacyChecker.CheckPermission("http://tizen.org/privilege/healthinfo");
Initialize();
foreach (var sensor in sensorList)
{
sensorTypeList.Add(sensor.Key);
}
return sensorTypeList;
}
/// <summary>
/// Gets sensor information.
/// </summary>
/// <param name="type">Sensor type</param>
/// <returns>Sensor Information</returns>
public SensorInfo GetSensorInfo(string type)
{
return sensorList[type].GetSensorInfo();
}
/// <summary>
/// Start sensor.
/// </summary>
/// <param name="type">Sensor type</param>
/// <param name="listener">Event handler</param>
public void StartSensor(string type, EventHandler<SensorEventArgs> listener)
{
sensorList[type].Start(listener);
}
/// <summary>
/// Stop sensor.
/// </summary>
/// <param name="type">Sensor type</param>
/// <param name="listener">Event handler</param>
public void StopSensor(string type, EventHandler<SensorEventArgs> listener)
{
sensorList[type].Stop(listener);
}
}
}
|
using System;
public struct TerraBasis {
public TerraVector3[] matrix;
public static TerraBasis InitEmpty () {
TerraVector3[] matrix = new TerraVector3[3];
matrix[0].x = 1;
matrix[0].y = 0;
matrix[0].z = 0;
matrix[1].x = 0;
matrix[1].y = 1;
matrix[1].z = 0;
matrix[2].x = 0;
matrix[2].y = 0;
matrix[2].z = 1;
return new TerraBasis (matrix);
}
public TerraBasis (float xx, float xy, float xz, float yx, float yy, float yz, float zx, float zy, float zz) {
matrix = new TerraVector3[3];
matrix[0].x = xx;
matrix[0].y = xy;
matrix[0].z = xz;
matrix[1].x = yx;
matrix[1].y = yy;
matrix[1].z = yz;
matrix[2].x = zx;
matrix[2].y = zy;
matrix[2].z = zz;
}
public TerraBasis (TerraVector3 axis, float radians) {
matrix = new TerraVector3[3];
TerraVector3 axisSQ = new TerraVector3 (axis.x * axis.x, axis.y * axis.y, axis.z * axis.z);
float cosine = (float) Math.Cos (radians);
float sine = (float) Math.Sin (radians);
matrix[0].x = axisSQ.x + cosine * (1.0f - axisSQ.x);
matrix[0].y = axis.x * axis.y * (1.0f - cosine) - axis.z * sine;
matrix[0].z = axis.z * axis.x * (1.0f - cosine) + axis.y * sine;
matrix[1].x = axis.x * axis.y * (1.0f - cosine) + axis.z * sine;
matrix[1].y = axisSQ.y + cosine * (1.0f - axisSQ.y);
matrix[1].z = axis.y * axis.z * (1.0f - cosine) - axis.x * sine;
matrix[2].x = axis.z * axis.x * (1.0f - cosine) - axis.y * sine;
matrix[2].y = axis.y * axis.z * (1.0f - cosine) + axis.x * sine;
matrix[2].z = axisSQ.z + cosine * (1.0f - axisSQ.z);
}
public TerraBasis (TerraVector3[] matrix) {
this.matrix = matrix;
}
public TerraBasis (TerraVector3 euler) {
matrix = new TerraVector3[3];
float c, s;
c = (float) Math.Cos (euler.x);
s = (float) Math.Sin (euler.x);
TerraBasis xmat = new TerraBasis (1.0f, 0.0f, 0.0f, 0.0f, c, -s, 0.0f, s, c);
c = (float) Math.Cos (euler.y);
s = (float) Math.Sin (euler.y);
TerraBasis ymat = new TerraBasis (c, 0.0f, s, 0.0f, 1.0f, 0.0f, -s, 0.0f, c);
c = (float) Math.Cos (euler.z);
s = (float) Math.Sin (euler.z);
TerraBasis zmat = new TerraBasis (c, -s, 0.0f, s, c, 0.0f, 0.0f, 0.0f, 1.0f);
//optimizer will optimize away all this anyway
this = ymat * xmat * zmat;
}
public static TerraBasis operator * (TerraBasis matrixA, TerraBasis matrixB) {
return new TerraBasis (matrixA.Tdotx (matrixB.matrix[0]), matrixA.Tdoty (matrixB.matrix[0]), matrixA.Tdotz (matrixB.matrix[0]),
matrixA.Tdotx (matrixB.matrix[1]), matrixA.Tdoty (matrixB.matrix[1]), matrixA.Tdotz (matrixB.matrix[1]),
matrixA.Tdotx (matrixB.matrix[2]), matrixA.Tdoty (matrixB.matrix[2]), matrixA.Tdotz (matrixB.matrix[2]));
}
public float Tdotx (TerraVector3 v) {
return matrix[0].x * v.x + matrix[1].x * v.y + matrix[2].x * v.z;
}
public float Tdoty (TerraVector3 v) {
return matrix[0].y * v.x + matrix[1].y * v.y + matrix[2].y * v.z;
}
public float Tdotz (TerraVector3 v) {
return matrix[0].z * v.x + matrix[1].z * v.y + matrix[2].z * v.z;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OldTimeRail
{
class Help
{
/// <summary>
/// Help File Class.
/// </summary>
public void HelpMe()
{
Console.Clear();
Console.WriteLine("_______________________________________________________________________");
Console.WriteLine("");
Console.WriteLine(" Welcome to the Old Time Rail Booking System ");
Console.WriteLine("_______________________________________________________________________");
Console.WriteLine("");
Console.WriteLine(" Help Section! ");
Console.WriteLine("_______________________________________________________________________");
Console.WriteLine("");
Console.WriteLine("Booking Questions");
Console.WriteLine("");
Console.WriteLine("How do i create a new booking?");
Console.WriteLine("");
Console.WriteLine("To book a passenger onto a new train press option 1 on the Main Menu, then follow the on screen instructions. ");
Console.WriteLine("");
Console.WriteLine("Is there a maximum number of passengers i can book at once?");
Console.WriteLine("");
Console.WriteLine("Yes! You can only book a maximum of 8 passengers onto a Compartment car and a maximum of 10 on a standard car.");
Console.WriteLine("");
Console.WriteLine("Will passengers be grouped together?");
Console.WriteLine("");
Console.WriteLine("Depending on the party size the system will ensure that when possible passengers will be grouped together.");
Console.WriteLine("");
Console.WriteLine("Why cant i book passengers onto Carriage D?");
Console.WriteLine("");
Console.WriteLine("The system will automatically book passengers onto Carriage C and group them together, Once Carriage C is full it will \nstart booking passengers onto Carriage D");
Console.WriteLine("");
Console.WriteLine("Report Questions");
Console.WriteLine("");
Console.WriteLine("To have access to the reports section select option 4 from the Main Menu");
Console.WriteLine("");
Console.WriteLine("");
}
}
}
|
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ZenHub.Pipeline
{
internal class ThrowOnErrorStatusPolicy : HttpPipelinePolicy
{
public override void Process(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
{
// no sync code.
}
public override async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
{
await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
if (message.ResponseClassifier.IsErrorResponse(message))
{
throw new RequestFailedException(message.Response.Status, message.ToString());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Intex.Models
{
public class TestMaterial
{
public Test Tests { get; set; }
public Material Materials { get; set; }
}
} |
//using System.Net.Sockets;
using System.Net;
using System.Threading;
using System;
public class AbstractBot
{
public const int SmallBlind = 20;
public string Name = string.Empty;
public string NameRoom = string.Empty;
public double[] Money = new double[6];
public bool[] Play = new bool[6];
public int GeneralBank = 0;
public int CountOfGamers = -1;
public double[] Bet = new double[6];
public double[] FullBet = new double[6];
public double MaxBet = 0;
public int MyPlace = -1;
public bool ConnectToServer = false, Auth = false, JoinRoom = false, Hold = false, Game = false;
public BotSocket Socket;
public string MyCards = string.Empty;
public string CardOnDesk = string.Empty;
public Thread Thread;
public string Answer = string.Empty;
public int TryHold = 0;
public int RisesNumber = 0;
public bool InGame = true;
public MonteCarloLogic MCLogic { get; set; }
public void ServerConnect()
{
if (!ConnectToServer)
try
{
Socket = new BotSocket(11000, IPAddress.Parse("127.0.0.1"));
Socket.Start();
ConnectToServer = true;
}
catch
{
ServerConnect();
}
}
public void Authorization()
{
Socket.SendMessage("botauthorization|" + Name + "|");
}
public void CreateRoom()
{
while (!Auth) { }
Socket.SendMessage("createnewgameroom|" + NameRoom + "|");
}
public void JoinInRoom()
{
while (!Auth) { }
Socket.SendMessage("connecttoroom|" + NameRoom + "|");
}
public void HoldPlace(int Index)
{
while (!JoinRoom) { }
Socket.SendMessage("hideplace|" + Index + "|");
MyPlace = Index;
}
public void ReadyToGame(bool Solution)
{
while (!Hold) { }
if (Solution) Socket.SendMessage("staketrue|");
else Socket.SendMessage("stakefalse|");
}
virtual public void MakeDecision() { }
public void Fold()
{
if (Game) Socket.SendMessage("fold|");
}
public void Call()
{
if (Game) Socket.SendMessage("call|");
}
public void Quit()
{
Socket.SendMessage("<TheEnd>|");
Thread.Abort();
}
public bool Receiver()
{
Answer = Socket.GetMessage();
if (Answer != null)
{
while (!string.IsNullOrEmpty(Answer))
{
string command = Parse.GetCommand(ref Answer);
if (command == "goodansw|")
{
Auth = true;
}
//Action with the room
else if (command == "startroom|")
{
JoinRoom = true;
}
else if (command == "truehold|")
{
Hold = true;
}
else if (command == "falsehold|")
{
Hold = false;
MyPlace = -1;
if (TryHold < 6)HoldPlace(TryHold++);
else
{
Quit();
Console.WriteLine(Name + ": все места занята насяйника:(");
}
}
else if (command == "readygame|")
{
Game = true;
}
else if (command == "notreadygame|")
{
Game = false;
}
//Warning actiocn room
else if (command == "youarenotconnected|")
{
Console.WriteLine(Name + ": Не смог подключиться к комнате - " + NameRoom);
}
else if (command == "wrongname|")
{
Console.WriteLine(Name + ": Такой комнаты не существует - " + NameRoom);
}
//Action with the game
else if (command == "endofgame|")
{
for (int i = 0; i < 6; ++i)
{
Bet[i] = 0;
FullBet[i] = 0;
Play[i] = false;
}
GeneralBank = 0;
MyCards = string.Empty;
CardOnDesk = string.Empty;
CountOfGamers = -1;
MaxBet = 0;
InGame = false;
}
else if (command == "inroom|")
{
GeneralBank = MessageToInt();
int index, _Money;
index = MessageToInt();
while (index != -1)
{
_Money = MessageToInt();
Bet[index] += _Money;
Money[index] -= _Money;
index = MessageToInt();
}
}
else if (command == "holdplace|")
{
int Index = MessageToInt();
while (Index != -1)
{
int NumberOfPlace = Index;
string NameOfGamer = MessageToString();
int MoneyOfGamer = MessageToInt();
Money[Index] = MoneyOfGamer;
Index = MessageToInt();
}
}
else if (command == "pig|")
{
int trash = -1;
CountOfGamers = MessageToInt();
for (int i = 0; i < CountOfGamers; i++)
{
trash = MessageToInt();
Play[trash] = true;
}
}
else if (command == "trade|") // глянь здесь Money
{
int index = MessageToInt();
int _Money = MessageToInt();
GeneralBank = MessageToInt();
if (_Money == 0) Console.WriteLine(Name + ": Money == 0");
if (_Money + Bet[index] > MaxBet) MaxBet = _Money + Bet[index];
Bet[index] += _Money;
FullBet[index] += _Money;
Money[index] -= _Money;
}
else if (command == "yourcards|")
{
InGame = true;
RisesNumber = 0;
MyCards = string.Empty;
for (int i = 0; i < 2; i++) MyCards += MessageToString();
}
else if (command == "flop|")
{
RisesNumber = 0;
MaxBet = 0;
CardOnDesk = string.Empty;
for (int i = 0; i < 3; i++)
{
CardOnDesk += MessageToString();
Bet[i] = 0;
Bet[i + 3] = 0;
}
}
else if (command == "turn|")
{
RisesNumber = 0;
MaxBet = 0;
CardOnDesk += MessageToString();
for (int i = 0; i < 6; i++)
Bet[i] = 0;
}
else if (command == "river|")
{
RisesNumber = 0;
MaxBet = 0;
CardOnDesk += MessageToString();
for (int i = 0; i < 6; i++)
Bet[i] = 0;
}
else if (command == "foldedman|")
{
int index = MessageToInt();
Bet[index] = 0;
FullBet[index] = 0;
Play[index] = false;
}
else if (command == "falsebet|")
{
int _bet = MessageToInt();
int _currBet = MessageToInt();
int _maxbet = MessageToInt();
Console.WriteLine(Name + ": falsebet _Bet: " + _bet + "; _currBet: " + _currBet + "; _maxbet: " + _maxbet);
}
else if (command == "currentgamer|")
{
int CurrentGamer = MessageToInt();
if (CurrentGamer == MyPlace)
{
MakeDecision();
}
}
}
}
else
{
Console.WriteLine(Name + ": Потерял соединение с сервером");
ConnectToServer = false;
Auth = false;
JoinRoom = false;
return false;
}
return true;
}
public void Listening()
{
while (Receiver()) { }
}
public string MessageToString()
{
int l = -1;
l = Answer.IndexOf("|");
string str = Answer.Substring(0, l);
Answer = Answer.Remove(0, l + 1);
return str;
}
public int MessageToInt()
{
int l = -1;
l = Answer.IndexOf("|");
int str = Convert.ToInt32(Answer.Substring(0, l));
Answer = Answer.Remove(0, l + 1);
return str;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Soko.Domain;
using Bilten.Dao;
using NHibernate;
using NHibernate.Context;
using Soko.Data;
using Soko.Exceptions;
namespace Soko.UI
{
public partial class MestaForm : EntityListForm
{
private const string ZIP = "Zip";
private const string NAZIV = "Naziv";
public MestaForm()
{
InitializeComponent();
initialize(typeof(Mesto));
sort(NAZIV);
}
protected override DataGridView getDataGridView()
{
return dataGridView1;
}
protected override void initUI()
{
base.initUI();
this.Size = new Size(Size.Width, 450);
this.Text = "Mesta";
}
protected override void addGridColumns()
{
AddColumn("Postanski broj", ZIP);
AddColumn("Naziv mesta", NAZIV, 150);
}
protected override List<object> loadEntities()
{
MestoDAO mestoDAO = DAOFactoryFactory.DAOFactory.GetMestoDAO();
return new List<Mesto>(mestoDAO.FindAll()).ConvertAll<object>(
delegate(Mesto m)
{
return m;
});
}
protected override EntityDetailForm createEntityDetailForm(Nullable<int> entityId)
{
return new MestoDialog(entityId);
}
private void btnDodaj_Click(object sender, System.EventArgs e)
{
addCommand();
}
private void btnPromeni_Click(object sender, System.EventArgs e)
{
editCommand();
}
private void btnBrisi_Click(object sender, System.EventArgs e)
{
deleteCommand();
}
protected override string deleteConfirmationMessage(DomainObject entity)
{
return String.Format("Da li zelite da izbrisete mesto \"{0}\"?", entity);
}
protected override bool refIntegrityDeleteDlg(DomainObject entity)
{
Mesto m = (Mesto)entity;
ClanDAO clanDao = DAOFactoryFactory.DAOFactory.GetClanDAO();
InstitucijaDAO instDao = DAOFactoryFactory.DAOFactory.GetInstitucijaDAO();
if (clanDao.existsClanMesto(m))
{
string msg = "Mesto '{0}' nije moguce izbrisati zato sto postoje " +
"clanovi iz datog mesta. \n\nDa bi neko mesto moglo da se izbrise, " +
"uslov je da ne postoje clanovi iz datog mesta. To znaci da morate " +
"najpre da pronadjete sve clanove iz datog mesta, i da zatim, u " +
"prozoru u kome " +
"se menjaju podaci o clanu, polje za mesto ostavite prazno. " +
"Nakon sto ste ovo uradili za sve " +
"clanove iz datog mesta, moci cete da izbrisete mesto. ";
MessageDialogs.showMessage(String.Format(msg, m), this.Text);
return false;
}
else if (instDao.existsInstitucijaMesto(m))
{
string msg = "Mesto '{0}' nije moguce izbrisati zato sto postoje " +
"institucije iz datog mesta. \n\nDa bi neko mesto moglo da se izbrise, " +
"uslov je da ne postoje institucije iz datog mesta. To znaci da morate " +
"najpre da pronadjete sve institucije iz datog mesta, i da zatim, u " +
"prozoru u kome " +
"se menjaju podaci o instituciji, polje za mesto ostavite prazno. " +
"Nakon sto ste ovo uradili za sve " +
"institucije iz datog mesta, moci cete da izbrisete mesto. ";
MessageDialogs.showMessage(String.Format(msg, m), this.Text);
return false;
}
return true;
}
protected override void delete(DomainObject entity)
{
MestoDAO mestoDAO = DAOFactoryFactory.DAOFactory.GetMestoDAO();
mestoDAO.MakeTransient((Mesto)entity);
}
protected override string deleteErrorMessage(DomainObject entity)
{
return "Greska prilikom brisanja mesta.";
}
private void btnZatvori_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.