text
stringlengths 13
6.01M
|
|---|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Grasshopper.Kernel;
using PterodactylCharts;
using PterodactylEngine;
using Rhino.Geometry;
namespace Pterodactyl
{
public class GraphGH : GH_Component
{
public GraphGH()
: base("Graph", "Graph",
"Create graph, if you want to generate Report Part - set Path",
"Pterodactyl", "Advanced Graph")
{
}
public override bool IsBakeCapable => false;
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddGenericParameter("Graph Elements", "Graph Elements", "Add graph elements", GH_ParamAccess.item);
pManager.AddGenericParameter("Graph Settings", "Graph Settings", "Add graph settings", GH_ParamAccess.item);
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddParameter(new PterodactylGrasshopperBitmapParam(), "Report Part", "Report Part", "Created part of the report (Markdown text with referenced Image)", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
GraphElements graphElements = null;
GraphSettings graphSettings = null;
DA.GetData(0, ref graphElements);
DA.GetData(1, ref graphSettings);
Graph graphObject = new Graph();
dialogImage = graphObject;
PterodactylGrasshopperBitmapGoo GH_bmp = new PterodactylGrasshopperBitmapGoo();
graphObject.GraphData(true, graphElements, graphSettings, GH_bmp.ReferenceTag);
using (Bitmap b = graphObject.ExportBitmap())
{
GH_bmp.Value = b.Clone(new Rectangle(0, 0, b.Width, b.Height), b.PixelFormat);
GH_bmp.ReportPart = graphObject.Create();
DA.SetData(0, GH_bmp);
}
}
private Graph dialogImage;
public override void AppendAdditionalMenuItems(ToolStripDropDown menu)
{
base.AppendAdditionalMenuItems(menu);
Menu_AppendItem(menu, "Show Graph", ShowChart, this.Icon, (dialogImage != null), false);
}
private void ShowChart(object sender, EventArgs e)
{
if (dialogImage != null) dialogImage.ShowDialog();
}
protected override System.Drawing.Bitmap Icon
{
get
{
return Properties.Resources.PterodactylGraph;
}
}
public override Guid ComponentGuid
{
get { return new Guid("32ea2490-6ab7-4090-9de2-e2414d0932c0"); }
}
}
}
|
using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace BartlettGenesisLogFileParser
{
internal class Program
{
private static void Main(string[] args)
{
if (!File.Exists(args[0]))
{
throw new Exception("Source file does not exist: " + args[0]);
}
if (args[1] == null || args[1].Length < 1)
{
throw new Exception("Please provide a destination file.");
}
List<BartlettLogRecordRaw> logRecords;
using (var reader = new StreamReader(args[0]))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.MissingFieldFound = null;
var records = csv.GetRecords<BartlettLogRecordRaw>();
logRecords = records.ToList();
//var startTime = DateTime.Parse(GetStart(logRecords).DateTime);
var info = GetStartAndStopInfo(logRecords);
var program = GetBartlettProgram(logRecords);
var segments = GetSegmentsFromRawLogRecords(logRecords, info[0].DateTime);
var reportLines = new List<BartlettReportLine>();
foreach (var segment in segments)
{
foreach (var tempRecord in segment.TempRecords)
{
var report = GetReportMeta(info, program);
report = GetSegmentMeta(segment, report);
report.TempDate = tempRecord.Time.ToString();
report.Setpoint = tempRecord.Setpoint.ToString();
report.Temp = tempRecord.TempAvg.ToString();
reportLines.Add(report);
}
}
using (var writer = new StreamWriter(args[1]))
using (var report = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
report.Configuration.ShouldQuote = (field, context) => true;
report.WriteHeader<BartlettReportLine>();
report.NextRecord();
foreach (var line in reportLines)
{
report.WriteRecord(line);
report.NextRecord();
}
}
}
}
private static BartlettReportLine GetReportMeta(List<BartlettInfo> info, BartlettProgram program)
{
var reportRow = new BartlettReportLine();
reportRow.FiringName = program.Name;
reportRow.FiringDate = info[0].DateTime.ToString();
reportRow.FiringCost = info[0].Cost.ToString();
reportRow.FirmwareVersion = info[0].FirmwareVersion;
reportRow.CircuitBoardStartTemp = info[0].BoardTemp.ToString();
reportRow.CircuitBoardEndTemp = info[1].BoardTemp.ToString();
return reportRow;
}
private static BartlettReportLine GetSegmentMeta(BartlettSegment segment, BartlettReportLine reportRow)
{
reportRow.SegmentNumber = segment.Number;
reportRow.SegmentStart = segment.StartTime.ToString();
reportRow.SegmentEnd = segment.EndTime.ToString();
reportRow.SegmentTargetTemp = segment.TargetTemp.ToString();
reportRow.SegmentStartTemp = segment.StartTemp.ToString();
reportRow.SegmentEndTemp = segment.EndTemp.ToString();
reportRow.SegmentHoldTime = segment.HoldTime;
reportRow.SegmentClimbRate = segment.ClimbRate.ToString();
return reportRow;
}
private static List<BartlettInfo> GetStartAndStopInfo(List<BartlettLogRecordRaw> logRecords)
{
List<BartlettLogRecordRaw> records = new List<BartlettLogRecordRaw>();
BartlettInfo start = new BartlettInfo();
BartlettInfo end = new BartlettInfo();
BartlettInfo current = start;
foreach (var record in logRecords)
{
if (record.Event.Equals("info"))
{
if (record.DateTime.Length > 0)
{
current = start.DateTime == DateTime.MinValue ? start : end;
current.DateTime = DateTime.Parse(record.DateTime.Replace("Z", ""));
}
if (record.EventName.Equals("cost"))
{
current.Cost = Decimal.Parse(record.EventValue);
}
if (record.EventName.Equals("board temp"))
{
current.BoardTemp = Int32.Parse(record.EventValue);
}
if (record.EventName.Equals("fw"))
{
current.FirmwareVersion = record.EventValue;
}
}
}
return new List<BartlettInfo> { start, end };
}
private static BartlettProgram GetBartlettProgram(List<BartlettLogRecordRaw> logRecords)
{
var program = new BartlettProgram();
foreach (var record in logRecords)
{
if (record.Event.Equals("program"))
{
if (record.EventName.Equals("name"))
{
program.Name = record.EventValue;
}
if (record.EventName.Equals("cone"))
{
program.Cone = record.EventValue;
}
if (record.EventName.Equals("segments"))
{
program.Segments = Int32.Parse(record.EventValue);
}
}
}
return program;
}
/// <summary>
/// ent
/// </summary>
/// <param name="logRecords"></param>
/// <param name="startTime"></param>
/// <returns></returns>
private static List<BartlettSegment> GetSegmentsFromRawLogRecords(List<BartlettLogRecordRaw> logRecords, DateTime startTime)
{
var segments = new List<BartlettSegment>();
var lastSegment = 0;
BartlettSegment segment = null;
foreach (var record in logRecords)
{
if (record.Event.Equals("block continue")) continue;
if (record.Event.Equals("start ramp"))
{
if (segment != null && segment.TempRecords.Count > 0)
{
segment.EndTime = DateTime.Parse(record.DateTime.Replace("Z", ""));
segments.Add(segment);
segment = null;
}
if (segment == null) segment = new BartlettSegment();
if (record.DateTime != null && record.DateTime.Length > 0)
{
segment.StartTime = DateTime.Parse(record.DateTime.Replace("Z", ""));
}
if (record.EventName.Equals("segment"))
{
segment.Number = Int32.Parse(record.EventValue);
}
if (record.EventName.Equals("rate"))
{
segment.ClimbRate = Int32.Parse(record.EventValue);
}
if (record.EventName.Equals("temp"))
{
segment.TargetTemp = Int32.Parse(record.EventValue);
}
}
if (record.TimeOffset != null && !record.TimeOffset.Equals(""))
{
segment.TempRecords.Add(new BartlettTempRecord()
{
Time = startTime.AddSeconds(Int32.Parse(record.TimeOffset) * 30),
Setpoint = Int32.Parse(record.SetPoint),
TempAvg = Int32.Parse(record.Temp2),
OutAvg = Int32.Parse(record.Out2)
});
}
if (record.Event.Equals("start hold"))
{
if (record.EventName.Equals("hold time"))
{
segment.HoldTime = record.EventValue;
}
if (record.DateTime != null && record.DateTime.Length > 0)
{
segment.EndTime = DateTime.Parse(record.DateTime.Replace("Z", ""));
}
if (record.EventName.Equals("temp"))
{
segment.EndTemp = Int32.Parse(record.EventValue);
if (segment.TempRecords != null && segment.TempRecords[0] != null)
{
segment.StartTemp = segment.TempRecords[0].TempAvg;
}
if (segment.HoldTime.Equals("0h0m"))
{
segments.Add(segment);
segment = null;
}
continue;
}
}
if (record.Event.Equals("manual stop firing") || record.Event.Equals("firing complete"))
{
if (record.DateTime != null && record.DateTime.Length > 0)
{
segment.EndTime = DateTime.Parse(record.DateTime.Replace("Z", ""));
}
if (segment.TempRecords != null && segment.TempRecords[0] != null)
{
segment.StartTemp = segment.TempRecords[0].TempAvg;
segment.EndTemp = segment.TempRecords.TakeLast(1).ToList()[0].TempAvg;
}
if (segment.HoldTime == null || segment.HoldTime.Length < 1)
{
segment.HoldTime = "0h0m";
}
segments.Add(segment);
segment = null;
continue;
}
}
return segments;
}
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using System.Diagnostics;
using S7PROSIMLib;
using System.ComponentModel;
using Лифт_PLCSim.Model;
namespace Лифт_PLCSim
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
//Позиция лифта
public double LiftPosition
{
get
{
return liftPosition;
}
set
{
liftPosition = value;
//Ограничения
if (value > 514) liftPosition = 514;
if (value < 0) liftPosition = 0;
//Передаем позицию в концевик
LS_2_0.Position = LS_2_1.Position = LS_2_2.Position = liftPosition;
//Пересчитываем высоту в значение энкодера
PIW256 = (short)(LiftPosition * 53);
//Извещаем модель представления
OnPropertyChanged("LiftPosition");
}
}
double liftPosition = 36;
//Значение энкодера положения кабины лифта
public short PIW256
{
get
{
return piw256;
}
set
{
piw256 = value;
SIMULATOR.WriteInputWord(256, piw256);
OnPropertyChanged("PIW256");
}
}
short piw256 = 0;
public MainWindow()
{
InitializeComponent();
}
//Подключение к симулятору
private void Connect_Click(object sender, RoutedEventArgs e)
{
SIMULATOR.PLCSim.Connect();
SIMULATOR.PLCSim.SetState("RUN");
SIMULATOR.PLCSim.SetScanMode(ScanModeConstants.ContinuousScan);
}
private void Step7_Click(object sender, RoutedEventArgs e)
{
Process.Start("S7tgtopx.exe");
}
private void PLCSim_Click(object sender, RoutedEventArgs e)
{
Process.Start("s7wsvapx.exe");
}
#region Реализация интерфейса INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using OnlineClinic.Core.DTOs;
using OnlineClinic.Core.Services;
namespace BlazorUI.Pages.People.List
{
public partial class PersonList: ComponentBase
{
[Inject]
protected NavigationManager NavigationManager { get; set; }
[Inject]
protected IPersonService PersonService { get; set; }
private IEnumerable<PersonGetDto> People { get; set; }
protected override void OnInitialized() => People = PersonService.GetAll();
private void GoToEditPage(int id) => NavigationManager.NavigateTo($"people/{id}/edit");
}
}
|
using System;
using System.Text;
using WinterIsComing.Contracts;
using WinterIsComing.Models.CombatHandlers;
namespace WinterIsComing.Models.Units
{
public abstract class Unit : IUnit
{
protected Unit(int x, int y, string name, int range, int attackPoints, int healthPoints, int defensePoints, int energyPoints )
{
this.X = x;
this.Y = y;
this.Name = name;
this.Range = range;
this.AttackPoints = attackPoints;
this.HealthPoints = healthPoints;
this.DefensePoints = defensePoints;
this.EnergyPoints = energyPoints;
this.CombatHandler = new CombatHandler(this);
}
public int X { get; set; }
public int Y { get; set; }
public string Name { get; private set; }
public int Range { get; private set; }
public int AttackPoints { get; set; }
public int HealthPoints { get; set; }
public int DefensePoints { get; set; }
public int EnergyPoints { get; set; }
public ICombatHandler CombatHandler { get; private set; }
/*>{name} - {type} at ({x},{y})
-Health points = {..}
-Attack points = {..}
-Defense points = {..}
-Energy points = {..}
-Range = {..}
*/
public override string ToString()
{
StringBuilder sbOut = new StringBuilder();
sbOut.AppendLine(String.Format(">{0} - {1} at ({2},{3})",this.Name, GetType().Name,this.X, this.Y));
if (this.HealthPoints <= 0)
{
sbOut.Append("(Dead)");
}
else
{
sbOut.AppendLine(String.Format("-Health points = {0}",this.HealthPoints));
sbOut.AppendLine(String.Format("-Attack points = {0}", this.AttackPoints));
sbOut.AppendLine(String.Format("-Defense points = {0}", this.DefensePoints));
sbOut.AppendLine(String.Format("-Energy points = {0}", this.EnergyPoints));
sbOut.Append(String.Format("-Range = {0}", this.Range));
}
return sbOut.ToString();
}
}
}
|
using UnityEngine;
namespace Pathfinding
{
[RequireComponent(typeof(SpriteRenderer)), System.Serializable]
public class DijkstraNode : Node
{
public int DistanceFromStart { get; set; }
}
}
|
using EddiDataDefinitions;
using System;
using System.Collections.Generic;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class RingHotspotsEvent : Event
{
public const string NAME = "Ring hotspots detected";
public const string DESCRIPTION = "Triggered when hotspots are detected in a ring";
public const string SAMPLE = @"{ ""timestamp"":""2019-08-19T00:24:53Z"", ""event"":""SAASignalsFound"", ""BodyName"":""Oponner 6 A Ring"", ""SystemAddress"":3721345878371, ""BodyID"":29, ""Signals"":[ { ""Type"":""Bromellite"", ""Count"":3 }, { ""Type"":""Grandidierite"", ""Count"":5 }, { ""Type"":""LowTemperatureDiamond"", ""Type_Localised"":""Low Temperature Diamonds"", ""Count"":1 } ] }";
[PublicAPI("The ring where hotspots were detected")]
public string bodyname { get; private set; }
[PublicAPI("A list of ring hotspots (as objects with properties 'commodity' and 'amount')")]
public List<CommodityAmount> hotspots { get; private set; }
// Not intended to be user facing
public ulong? systemAddress { get; private set; }
public long bodyId { get; private set; }
public RingHotspotsEvent(DateTime timestamp, ulong? systemAddress, string bodyName, long bodyId, List<CommodityAmount> hotspots) : base(timestamp, NAME)
{
this.systemAddress = systemAddress;
this.bodyname = bodyName;
this.bodyId = bodyId;
this.hotspots = hotspots;
}
}
}
|
using System;
namespace gView.Interoperability.GeoServices.Extensions
{
static class StringExtensions
{
static public string UrlEncodePassword(this string password)
{
if (password != null && password.IndexOfAny("+/=&".ToCharArray()) > 0)
{
password = System.Web.HttpUtility.UrlEncode(password);
}
return password;
}
static public string UrlEncodeWhereClause(this string whereClause)
{
if (String.IsNullOrWhiteSpace(whereClause))
{
return String.Empty;
}
return whereClause.Replace("%", "%25")
.Replace("+", "%2B")
.Replace("/", "%2F")
//.Replace(@"\", "%5C") // Darf man nicht ersetzen!! Sonst geht beim Kunden der Filter für Usernamen nicht mehr!!!!!!
.Replace("&", "%26");
}
}
}
|
using System;
using System.ComponentModel;
using System.Windows.Forms;
using DevExpress.XtraEditors.DXErrorProvider;
using Phenix.Core.Data;
using Phenix.Core.Windows;
namespace Phenix.Windows.Helper
{
/// <summary>
/// DXErrorProvider扩展
/// </summary>
public static class DXErrorProviderExtentions
{
#region 方法
/// <summary>
/// 校验控件容器内编辑控件的失效数据
/// </summary>
/// <param name="errorProvider">DXErrorProvider</param>
/// <param name="container">控件容器</param>
/// <param name="source">数据源</param>
/// <param name="toFocused">聚焦失效控件</param>
/// <returns>失效数据事件数据</returns>
public static DataInvalidEventArgs CheckRules(this DXErrorProvider errorProvider, Control container, BindingSource source, bool toFocused)
{
if (container == null)
return null;
foreach (Control item in ControlHelper.FindEditControls(container, source))
{
DataInvalidEventArgs result = CheckRule(errorProvider, item, toFocused);
if (result != null)
return result;
}
return null;
}
/// <summary>
/// 校验编辑控件的失效数据
/// </summary>
/// <param name="errorProvider">DXErrorProvider</param>
/// <param name="control">控件</param>
/// <param name="toFocused">聚焦失效控件</param>
/// <returns>失效数据事件数据</returns>
public static DataInvalidEventArgs CheckRule(this DXErrorProvider errorProvider, Control control, bool toFocused)
{
if (control == null)
return null;
ErrorType oldErrorType = errorProvider.GetErrorType(control);
foreach (Binding item in control.DataBindings)
{
if (String.IsNullOrEmpty(item.BindingMemberInfo.BindingField))
continue;
BindingSource bindingSource = item.DataSource as BindingSource;
if (bindingSource == null)
continue;
object obj = BindingSourceHelper.GetDataSourceCurrent(bindingSource);
IDataInvalidInfo dataInvalidInfo = obj as IDataInvalidInfo;
if (dataInvalidInfo != null)
if (dataInvalidInfo.ErrorCount > 0)
{
string errorMessage = dataInvalidInfo.GetFirstErrorMessage(item.BindingMemberInfo.BindingField);
if (String.IsNullOrEmpty(errorMessage))
goto Label;
if (toFocused && oldErrorType != ErrorType.Default)
ControlHelper.InvokeSetFocus(control);
InvokeSetError(errorProvider, control, errorMessage, ErrorType.Default);
return new DataInvalidEventArgs(bindingSource, bindingSource.Position, control, errorMessage);
}
else if (dataInvalidInfo.WarningCount > 0)
{
string warningMessage = dataInvalidInfo.GetFirstWarningMessage(item.BindingMemberInfo.BindingField);
if (String.IsNullOrEmpty(warningMessage))
goto Label;
if (toFocused && oldErrorType != ErrorType.Warning)
ControlHelper.InvokeSetFocus(control);
InvokeSetError(errorProvider, control, warningMessage, ErrorType.Warning);
return new DataInvalidEventArgs(bindingSource, bindingSource.Position, control, warningMessage);
}
else if (dataInvalidInfo.InformationCount > 0)
{
string informationMessage = dataInvalidInfo.GetFirstInformationMessage(item.BindingMemberInfo.BindingField);
if (String.IsNullOrEmpty(informationMessage))
goto Label;
InvokeSetError(errorProvider, control, informationMessage, ErrorType.Information);
return new DataInvalidEventArgs(bindingSource, bindingSource.Position, control, informationMessage);
}
IDataErrorInfo dataErrorInfo = obj as IDataErrorInfo;
if (dataErrorInfo != null)
{
string errorMessage = dataErrorInfo[item.BindingMemberInfo.BindingField];
if (String.IsNullOrEmpty(errorMessage))
goto Label;
if (toFocused && oldErrorType != ErrorType.Default)
ControlHelper.InvokeSetFocus(control);
InvokeSetError(errorProvider, control, errorMessage, ErrorType.Default);
return new DataInvalidEventArgs(bindingSource, bindingSource.Position, control, errorMessage);
}
}
Label:
if (oldErrorType != ErrorType.None)
InvokeSetError(errorProvider, control, String.Empty, ErrorType.None);
return null;
}
/// <summary>
/// 显示失效数据信息(线程安全)
/// </summary>
/// <param name="errorProvider">DXErrorProvider</param>
/// <param name="control">控件</param>
/// <param name="errorMessage">信息</param>
/// <param name="errorType">类型</param>
public static void InvokeSetError(this DXErrorProvider errorProvider, Control control, string errorMessage, ErrorType errorType)
{
if (control == null)
return;
if (control.InvokeRequired)
control.BeginInvoke(new Action<Control, string, ErrorType>(errorProvider.SetError), new object[] { control, errorMessage, errorType });
else
errorProvider.SetError(control, errorMessage, errorType); ;
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
using UnityEditor;
public class CombineTagAndLayer : AssetPostprocessor
{
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string s in importedAssets)
{
if (s.Equals("Assets/CombineTagAndLayer.cs"))
{
//增加一个叫momo的tag
AddTag("momo");
//增加一个叫ruoruo的layer
AddLayer("ruoruo");
return;
}
}
}
static void AddTag(string tag)
{
if (!isHasTag(tag))
{
SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty it = tagManager.GetIterator();
while (it.NextVisible(true))
{
if (it.name == "tags")
{
for (int i = 0; i < it.arraySize; i++)
{
SerializedProperty dataPoint = it.GetArrayElementAtIndex(i);
if (string.IsNullOrEmpty(dataPoint.stringValue))
{
dataPoint.stringValue = tag;
tagManager.ApplyModifiedProperties();
return;
}
}
}
}
}
}
static void AddLayer(string layer)
{
if (!isHasLayer(layer))
{
SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty it = tagManager.GetIterator();
while (it.NextVisible(true))
{
if (it.name.StartsWith("User Layer"))
{
if (it.type == "string")
{
if (string.IsNullOrEmpty(it.stringValue))
{
it.stringValue = layer;
tagManager.ApplyModifiedProperties();
return;
}
}
}
}
}
}
static bool isHasTag(string tag)
{
for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.tags.Length; i++)
{
if (UnityEditorInternal.InternalEditorUtility.tags[i].Contains(tag))
return true;
}
return false;
}
static bool isHasLayer(string layer)
{
for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.layers.Length; i++)
{
if (UnityEditorInternal.InternalEditorUtility.layers[i].Contains(layer))
return true;
}
return false;
}
}
|
namespace Funding.Services.Models.AdminViewModels.Projects
{
using Funding.Data.Models;
using Funding.Services.Mapping;
using System;
public class ProjectsListingViewModel : IMapFrom<Project>
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public decimal Goal { get; set; }
public decimal MoneyCollected { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string CreatorId { get; set; }
public User Creator { get; set; }
public bool isApproved { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Accounts.Domain.Events.Private;
using Accounts.Domain.Events;
using Linedata.Foundation.EventPublisher;
namespace EventPublisher
{
public class EventToMessageTranslator : IEventTranslator
{
public bool Translate(object eventToTranslate, out object message)
{
Console.WriteLine("EventPublisher received event to translate: ", eventToTranslate);
try
{
switch (eventToTranslate)
{
case AccountCreated evt:
{
message = evt.ToPublic();
return true;
}
case AccountCredited evt:
{
message = evt.ToPublic();
return true;
}
case AccountDebited evt:
{
message = evt.ToPublic();
return true;
}
default:
{
message = null;
return false;
}
}
}
catch (Exception e)
{
Console.WriteLine("Could not translate Event from Private to Public: ", e);
throw;
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class isoDestoryTime : MonoBehaviour {
public bool isStatus;
public float time;
float lifeTime;
// Use this for initialization
void Awake () {
isStatus = false;
lifeTime = 0.0f;
if(time != 0) {
isStatus = true;
}
}
// Update is called once per frame
void Update () {
if(isStatus == false)
return;
if(lifeTime > time) {
NGUITools.Destroy(this.gameObject);
}
lifeTime += Time.deltaTime;
}
public void SET_DESTROY_TIMER(float t) {
this.time = t;
isStatus = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xamarin.Forms;
namespace ResonateXamarin.Models
{
public static class ResonateManager
{
#region Spotify Api
public static async Task<SpotifyUser> GetSpotifyUserAsync()
{
using (HttpClient client = new HttpClient())
{
string url = "https://api.spotify.com/v1/me";
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Application.Current.Properties["bearer"].ToString());
String result = await client.GetStringAsync(url);
SpotifyUser user = JsonConvert.DeserializeObject<SpotifyUser>(result);
Debug.WriteLine(user);
return user;
}
catch (Exception ex)
{
throw ex;
}
}
}
public static async Task<SpotifyData> GetSpotifyUserDataAsync()
{
using (HttpClient client = new HttpClient())
{
string url = "https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=3";
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Application.Current.Properties["bearer"].ToString());
String result = await client.GetStringAsync(url);
SpotifyData data = JsonConvert.DeserializeObject<SpotifyData>(result);
Debug.WriteLine(data);
return data;
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion
#region Resonate Api
#region User
public static async Task<Boolean> RegisterUser(SpotifyUser user)
{
using (HttpClient client = new HttpClient())
{
string url = "https://resonateapi.azurewebsites.net/api/user";
try
{
string json = JsonConvert.SerializeObject(user);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
return Convert.ToBoolean(result);
}
catch (Exception ex)
{
throw ex;
}
}
}
public static async Task<SpotifyUser> GetUser(string userId)
{
using (HttpClient client = new HttpClient())
{
string url = $"https://resonateapi.azurewebsites.net/api/user/{userId}";
try
{
String result = await client.GetStringAsync(url);
SpotifyUser data = JsonConvert.DeserializeObject<SpotifyUser>(result);
return data;
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion
#region Genre en Artiesten
public static async Task<List<String>> GetGenres()
{
using (HttpClient client = new HttpClient())
{
string url = "https://resonateapi.azurewebsites.net/api/genre";
try
{
String result = await client.GetStringAsync(url);
List<String> data = JsonConvert.DeserializeObject<List<String>>(result);
return data;
}
catch (Exception ex)
{
throw ex;
}
}
}
public static async Task<List<Artist>> GetArists()
{
using (HttpClient client = new HttpClient())
{
string url = "https://resonateapi.azurewebsites.net/api/artist";
try
{
List<Artist> data = JsonConvert.DeserializeObject<List<Artist>>(await client.GetStringAsync(url));
return data;
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion
#region Matches
public static async Task<ObservableCollection<SpotifyUser>> GetPotMatches(int matchLevel, String name)
{
using (HttpClient client = new HttpClient())
{
string url = $"https://resonateapi.azurewebsites.net/api/match/{(Application.Current.Properties["user_id"].ToString())}/{matchLevel}/{name.ToLower()}";
try
{
ObservableCollection<SpotifyUser> data = JsonConvert.DeserializeObject<ObservableCollection<SpotifyUser>>(await client.GetStringAsync(url));
return data;
}
catch (Exception ex)
{
throw ex;
}
}
}
public static async Task<Boolean> AddMatch(SpotifyUser user2)
{
using (HttpClient client = new HttpClient())
{
const string currentUser = "koen.vanhecke";
string url = $"https://resonateapi.azurewebsites.net/api/match/{currentUser}/{user2.id}";
try
{
string json = JsonConvert.SerializeObject(user2);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
SpotifyUser user = JsonConvert.DeserializeObject<SpotifyUser>(await response.Content.ReadAsStringAsync());
return true;
}
catch (Exception ex)
{
throw ex;
}
}
}
#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DemoRaspberryPiConsumerMobileApp.Models
{
public class BarometerSensor
{
public DateTime DateTime { get; set; }
public float Temperature { get; set; }
public float Humidity { get; set; }
public float Pressure { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class AudioManager : MonoBehaviour
{
public AudioMixer audioMixer;
private float masterVol = 0;
public void SetMasterVol(float vol)
{
audioMixer.SetFloat("Master", vol);
masterVol = vol;
}
public void SetMusicVol(float vol) => audioMixer.SetFloat("Music", vol);
public void SetFXVol(float vol) => audioMixer.SetFloat("FX", vol);
public void UnmuteMasterVol(bool unmute)
{
audioMixer.SetFloat("Master", unmute ? masterVol : -80);
}
}
|
using System;
using System.Collections.Generic;
using DataAccess;
using DataAccess.Repositories;
namespace Tests
{
public class MockProductRepository : IProductRepository
{
private readonly List<IProduct> m_products = new List<IProduct>();
public MockProductRepository()
{
var p1 = new Product
{
Name = "LG 19\"",
Category = "Monitors",
Description = "Description for LG 19\" monitor",
Price = new decimal(299.00),
ProductId = 1
};
var p2 = new Product
{
Name = "Samsung 22\"",
Category = "Monitors",
Description = "Description for Samsung 22\" monitor",
Price = new decimal(499.00),
ProductId = 2
};
var p3 = new Product
{
Name = "Green Apple",
Category = "Fruits",
Description = "Description for green apple",
Price = new decimal(0.75),
ProductId = 3
};
var p4 = new Product
{
Name = "Orange",
Category = "Fruits",
Description = "Description for orange orange",
Price = new decimal(1.23),
ProductId = 4
};
m_products.Add(new ProductFactory().Create(p1));
m_products.Add(new ProductFactory().Create(p2));
m_products.Add(new ProductFactory().Create(p3));
m_products.Add(new ProductFactory().Create(p4));
}
public List<IProduct> GetEntities
{
get { return m_products; }
}
public IProduct GetById(int id)
{
return m_products[id];
}
public void Insert(IProduct entity)
{
m_products.Add(entity);
}
public void Save()
{
throw new NotImplementedException();
}
public void Delete(IProduct entity)
{
m_products.Remove(entity);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Reviews.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using HotChocolate;
namespace Reviews.Resolvers
{
public class UserResolver
{
private readonly IMongoCollection<User> _users;
public UserResolver(IOptions<DatabaseConfiguration> config)
{
var configMongo = config.Value;
var client = new MongoClient(configMongo.ConnectionString);
var database = client.GetDatabase(configMongo.DatabaseName);
_users = database.GetCollection<User>(configMongo.UsersCollectionName);
}
public List<User> Get()
{
Console.WriteLine("The request to the mongo DB for all Users is done");
return _users.Find(User => true).ToList();
}
public User GetUserById([Parent]Review review) => _users.Find<User>(user => user.UserId == review.AuthorId).FirstOrDefault();
public User Create(User user)
{
_users.InsertOne(user);
return user;
}
public void Update(string id, User userIn) => _users.ReplaceOne(user => user.UserId == id, userIn);
public void Remove(string id) => _users.DeleteOne(user => user.UserId == id);
}
}
|
using _5tg_at_mediaPlayer_desktop.connection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.VisualBasic.FileIO;
using System.IO;
using _5tg_at_mediaPlayer_desktop.Popup;
using System.Windows.Input;
using _5tg_at_mediaPlayer_desktop.All_Songs;
namespace _5tg_at_mediaPlayer_desktop.Playlist
{
/// <summary>
/// Interaction logic for Playlist.xaml
/// </summary>
public partial class Playlist : UserControl
{
public OrderStatus status;
public Playlist()
{
InitializeComponent();
loadPlaylist();
LoadAllSong();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (Global_Log.connectionClass == null)
{
Global_Log.connectionClass = new ConnectionClass();
}
{ }
string query = "select * from playlists";
DataTable dt = Global_Log.connectionClass.retriveData(query, "playlists");
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
{ }
Playlist_picker.Items.Add(dr.ItemArray[1].ToString());
}
//String var = Playlist_picker.SelectedItem.ToString();
//ComboBoxItem item = (ComboBoxItem)Playlist_picker.SelectedItem;
//String value1 = item.Content.ToString();
//Console.WriteLine(value1);
}
public void loadPlaylist()
{
if (Global_Log.playBack == null)
{
Global_Log.playBack = new PlayBack();
}
List<Playlists> list_Playlists = new List<Playlists>();
try
{
if (Global_Log.connectionClass == null)
{
Global_Log.connectionClass = new ConnectionClass();
}
DataTable dt = Global_Log.connectionClass.retriveData("select PID,name,CAST(Schedule as date), TotalSong from playlists", "playlists");
//createdDate = Schedule
int count = dt.Rows.Count;
Playlists playlists = new Playlists();
for (int i = 0; i < count; i++)
{
DataRow dr = dt.Rows[i];
try
{
list_Playlists.Add(new Playlists()
{
PID = Convert.ToInt32(dr.ItemArray[0]),
Name = dr.ItemArray[1].ToString(),
Date = dr.ItemArray[2].ToString(),
TotalSong = Convert.ToInt32(dr.ItemArray[3])
});
}
catch (Exception ex)
{ }
}
//if (allPlaylist != null)
// allPlaylist.ItemsSource = list_Playlists;
}
catch (Exception ex)
{ }
}
public static int currentPlaylist = 0;
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var image = e.AddedItems[0] as ComboBoxItem;
string currentOperation = image.Content.ToString();
var ttp = sender as ComboBox;
Playlists playlists = null;
if (image != null && ttp.Tag is Playlists)
{
playlists = (Playlists)ttp.Tag;
}
if (playlists != null)
{
Create_Playlist create_Playlist = new Create_Playlist();
Global_Log.pID = playlists.PID;
Global_Log.playlistName = playlists.Name;
if (currentOperation == "Update")
{
create_Playlist.SetProperty(playlists.Name.ToString());
}
else if (currentOperation == "Delete")
{
create_Playlist.deletePlaylist(playlists.PID);
}
else if (currentOperation == "View")
{
currentPlaylist = playlists.PID;
loadPlaylistSong(playlists.SortId, Global_Log.pID);
}
else if (currentOperation == "Schedule")
{
currentPlaylist = playlists.PID;
Schedular schedular = new Schedular();
schedular.ShowDialog();
//loadPlaylistSong(Global_Log.pID, playlists.SortId);
}
}
loadPlaylist();
}
private List<PlaylistAudio> loadPlaylistSong(int Sorts, int playlistID = 0, bool isSort = false, String playlistName = "")
{
List<PlaylistAudio> playlistAudio = new List<PlaylistAudio>();
string query = "";
if (playlistName == "")
{
///query = "select ID, title, duration, track from Audio where ID in(select AID from playlist where PID = " + playlistID + ")";
//query = "select a.ID, a.title, a.duration, a.track from Audio a inner join playlist p on a.ID=p.AID where p.PID =" + playlistID;
query = "select a.ID, ps.Schedule, a.title, a.duration, a.track, a.trimIn, a.trimOut from Audio a inner join playlist p on " +
"a.ID=p.AID inner join playlists ps on ps.PID = p.PID where p.PID =" + playlistID;
}
else
{
//query = "select ID, title, duration, track from Audio where ID in(select AID from playlist where PID = " + playlistID + ")";
//query = "select a.ID, a.title, a.duration, a.track from Audio a inner join playlist p on a.ID=p.AID where p.PID =" + playlistID;
query = "select a.ID, ps.Schedule, a.title, a.duration, a.track, a.trimIn, a.trimOut from Audio a inner join playlist p on a.ID " +
"= p.AID inner join playlists ps on ps.PID = p.PID where ps.name = '" + playlistName + "'";
}
DataTable dt = Global_Log.connectionClass.retriveData(query, "Audio");
int count = dt.Rows.Count;
Playlists playlists = new Playlists();
string time = "";
if (dt != null)
{
if (count != 0)
{
time = dt.Rows[0][1].ToString();
}
}
for (int i = 0; i < count; i++)
{
DataRow dr = dt.Rows[i];
try
{
DateTime date1 = DateTime.Now;
try
{
date1 = (DateTime)dr[1];
}
catch { }
TimeSpan time1 = (TimeSpan)dr[3];
if (time == null)
{
time = time1.ToString();
}
playlistAudio.Add(new PlaylistAudio()
{
AID = Convert.ToInt32(dr[0]),
AirTime = time,
PID = playlistID,
SortId = Sorts,
Name = dr[2].ToString(),
track = dr[4].ToString(),
Duration = (TimeSpan)dr[3],
Trim_Start = (TimeSpan)dr[5],
Trim_End = (TimeSpan)dr[6]
});
DateTime combined = date1.Add(time1);
time = combined.ToString();
}
catch (Exception ex)
{ }
}
PlaylistSong.ItemsSource = null;
PlaylistSong.Items.Clear();
PlaylistSong.ItemsSource = playlistAudio;
return playlistAudio;
}
private void PlaylistSongEdit_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var sa = this.LogicalChildren;
{ }
var image = e.AddedItems[0] as ComboBoxItem;
string currentOperation = image.Content.ToString();
var ttp = sender as ComboBox;
PlaylistAudio PlaylistAudio = null;
if (image != null && ttp.Tag is PlaylistAudio)
{
PlaylistAudio = (PlaylistAudio)ttp.Tag;
}
if (PlaylistAudio != null)
{
Create_Playlist create_Playlist = new Create_Playlist();
Global_Log.pID = PlaylistAudio.PID;
Global_Log.playlistName = PlaylistAudio.Name;
selectedIndexValue = 0;
plays = new List<PlaylistAudio>();
foreach (PlaylistAudio item in PlaylistSong.Items)
{
plays.Add(item);
}
if (currentOperation == "Play")
{
//PlaylistSong
Global_Log.allSongTrack = false;
if (Global_Log.bottom_Media_Control == null)
{
Global_Log.bottom_Media_Control = new Bottom_Media_Control.Bottom_Media_Control();
}
Global_Log.bottom_Media_Control.playSong(PlaylistAudio.track, PlaylistAudio.Name,
PlaylistAudio.Trim_Start, PlaylistAudio.Trim_End, PlaylistAudio.Intro, PlaylistAudio.EOM);
}
else if (currentOperation == "Delete")
{
string query = "delete playlist where PID =" + PlaylistAudio.PID + "and AID = " + PlaylistAudio.AID;
Global_Log.connectionClass.insertData(query);
}
//else if (currentOperation == "Update Sort ID")
//{
// Global_Log.playlistAudio = PlaylistAudio;
// Sorting sorting = new Sorting();
// sorting.ShowDialog();
//}
else if (currentOperation == "Update")
{
Track_Metadata addMusic = new Track_Metadata();
addMusic.updateSong();
}
}
loadPlaylistSong(PlaylistAudio.SortId, PlaylistAudio.PID);
Playlist_picker_SelectionChanged(null, null);
}
private void Create_Click(object sender, RoutedEventArgs e)
{
Create_Playlist createPlaylist = new Create_Playlist();
createPlaylist.ShowDialog();
loadPlaylist();
}
private void btnExport_Click(object sender, RoutedEventArgs e)
{
//string query = " select distinct A.Title, ps.name from playlist p inner join Audio A on p.AID = A.ID," +
// " playlist p1 inner join playlists ps on ps.PID = p1.PID where ps.PID = " + currentPlaylist;
string query = " select p.ID,p.AID,A.Title, p.PID, PS.name FROM " +
"playlist p inner join Audio A on p.AID = A.ID inner join playlists pS on ps.PID = P.PID WHERE P.PID =" + currentPlaylist;
DataTable dt = Global_Log.connectionClass.retriveData(query, "playlist");
List<AudioIE> writeCsvData = new List<AudioIE>();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
try
{
writeCsvData.Add(new AudioIE()
{
ID = Convert.ToInt32(dr[0]),
AID = Convert.ToInt32(dr[1]),
AName = dr[2].ToString(),
PID = Convert.ToInt32(dr[3]),
PName = dr[4].ToString()
});
}
catch (Exception ex)
{ }
}
string strFilePath = Global_Log.ActiveDir + "\\playlist.csv";
string strSeperator = ",";
StringBuilder sbOutput = new StringBuilder();
for (int i = 0; i < dt.Rows.Count; i++)
{
string s1 = writeCsvData[i].ID.ToString();
string s2 = writeCsvData[i].AID.ToString();
string s3 = writeCsvData[i].AName.ToString();
string s4 = writeCsvData[i].PID.ToString();
string s5 = writeCsvData[i].PName.ToString();
String s = s1 + "," + s2 + "," + s3 + "," + s4 + "," + s5 + Environment.NewLine;
File.AppendAllText(strFilePath, s);
}
MessageBox.Show("All Songs Export");
}
private void btnImport_Click(object sender, RoutedEventArgs e)
{
string strFilePath = Global_Log.ActiveDir + "\\playlist.csv";
List<AudioIE> writeCsvData = new List<AudioIE>();
using (TextFieldParser csvReader = new TextFieldParser(strFilePath))
{
csvReader.CommentTokens = new string[] { "#" };
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvReader.ReadLine();
while (!csvReader.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvReader.ReadFields();
writeCsvData.Add(new AudioIE()
{
ID = Convert.ToInt32(fields[0]),
AID = Convert.ToInt32(fields[1]),
AName = fields[2],
PID = Convert.ToInt32(fields[3]),
PName = fields[4],
});
}
}
}
private void ComboSorts_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var image = e.AddedItems[0] as ComboBoxItem;
string currentOperation = image.Content.ToString();
var ttp = sender as ComboBox;
//Sort ID
{ }
//loadPlaylistSong(int playlistID, int Sorts, true)
}
public static int selectedIndexValue = 0;
public static List<PlaylistAudio> plays;
public static List<Audio> playAllSong;
public void nextSong()
{
PlaylistAudio track;
Audio track1;
selectedIndexValue += 1;
if (Global_Log.allSongTrack)
{
if (selectedIndexValue >= playAllSong.Count)
{
selectedIndexValue = 0;
track1 = playAllSong[0];
}
else
{
track1 = playAllSong[selectedIndexValue];
}
if (Global_Log.bottom_Media_Control == null)
{
Global_Log.bottom_Media_Control = new Bottom_Media_Control.Bottom_Media_Control();
}
Global_Log.bottom_Media_Control.playSong(track1.Track, track1.Title, track1.Trim_Start, track1.Trim_End, track1.Intro, track1.EOM);
}
else if (Global_Log.allSongTrack == false)
{
try
{
if (selectedIndexValue >= plays.Count)
{
selectedIndexValue = 0;
track = plays[0];
}
else
{
track = plays[selectedIndexValue];
}
if (Global_Log.bottom_Media_Control == null)
{
Global_Log.bottom_Media_Control = new Bottom_Media_Control.Bottom_Media_Control();
}
Global_Log.bottom_Media_Control.playSong(track.track, track.Name, track.Trim_Start, track.Trim_End, track.Intro, track.EOM);
}
catch(Exception ex)
{ }
}
}
internal void previousSong()
{
PlaylistAudio track;
Audio track1;
selectedIndexValue -= 1;
if (Global_Log.allSongTrack)
{
if (selectedIndexValue >= playAllSong.Count)
{
selectedIndexValue = 0;
track1 = playAllSong[0];
}
else
{
if (selectedIndexValue == -1)
{
selectedIndexValue = playAllSong.Count - 1;
}
track1 = playAllSong[selectedIndexValue];
}
if (Global_Log.bottom_Media_Control == null)
{
Global_Log.bottom_Media_Control = new Bottom_Media_Control.Bottom_Media_Control();
}
Global_Log.bottom_Media_Control.playSong(track1.Track, track1.Title, track1.Trim_Start, track1.Trim_End, track1.Intro, track1.EOM);
}
else if (Global_Log.allSongTrack == false)
{
selectedIndexValue -= 1;
if (selectedIndexValue >= plays.Count)
{
track = plays[0];
}
else
{
track = plays[selectedIndexValue];
}
if (Global_Log.bottom_Media_Control == null)
{
Global_Log.bottom_Media_Control = new Bottom_Media_Control.Bottom_Media_Control();
}
Global_Log.bottom_Media_Control.playSong(track.track, track.Name, track.Trim_Start, track.Trim_End, track.Intro, track.EOM);
}
}
/// All Songs datagrid Code
///
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
}
//public object ConfigurationManager { get; private set; }
//Track track = null;
List<Audio> audioList = null;
private void View_all_playlist_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//Track_Metadata addMusic = new Track_Metadata();
//addMusic.ShowDialog();
LoadAllSong();
/*
* //SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\MiniProject\MiniProject\MiniProject\Persons.mdf;Integrated Security=True");
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\shubh\Documents\Visual Studio 2017\Projects\5tg_at_mediaPlayer_desktop\5tg_at_mediaPlayer_desktop\Database1.mdf;Integrated Security=True;");
try
{
if (con.State == System.Data.ConnectionState.Closed)
{
con.Open();
}
string CmdString = "SELECT * FROM Playlist_Name";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
System.Data.DataTable dt = new System.Data.DataTable("Playlist_Name");
sda.Fill(dt);
playlistnames.ItemsSource = dt.DefaultView;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}*/
}
public void LoadAllSong()
{
if (Global_Log.playBack == null)
{
Global_Log.playBack = new PlayBack();
}
List<Audio> audioList = new List<Audio>();
try
{
DataTable dt = Global_Log.playBack.getAllSong();
if (dt != null)
{
int count = dt.Rows.Count;
Audio info = new Audio();
for (int i = 0; i < count; i++)
{
DataRow dr = dt.Rows[i];
try
{
audioList.Add(new Audio()
{
ID = Convert.ToInt32(dr.ItemArray[0]),
UID = dr.ItemArray[1].ToString(),
Title = dr.ItemArray[2].ToString(),
FileName = dr.ItemArray[3].ToString(),
Filesize = Convert.ToInt32(dr.ItemArray[4]),
Filetype = dr.ItemArray[5].ToString(),
Filepath = dr.ItemArray[6].ToString(),
Duration = (TimeSpan)dr.ItemArray[7],
Chain = dr.ItemArray[8].ToString(),
Track = dr.ItemArray[9].ToString(),
Trim_Start = (TimeSpan)dr.ItemArray[10],
Trim_End = (TimeSpan)dr.ItemArray[11],
Intro = (TimeSpan)dr.ItemArray[12],
EOM = (TimeSpan)dr.ItemArray[13],
});
}
catch (Exception ex)
{
Global_Log.EXC_WriteIn_LOGfile(ex.StackTrace);
}
}
}
}
catch (Exception ex)
{ }
//playlistnames.ItemsSource = audioList;
datagrid.ItemsSource = audioList;
}
private void Playlistnames_LoadingRowDetails(object sender, DataGridRowDetailsEventArgs e)
{
/*DataTable dt = new DataTable();
dt.Columns.Add("Sr. No.", typeof(String));
dt.Columns.Add("ID", typeof(String));
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Count",typeof(String));
dt.Columns.Add("Controls",typeof(String));
dt.Rows.Add("1","PLS1","PLNAME","15","-");
dt.Rows.Add("2", "PLS1", "PLNAME", "15", "-");
//Dictionary<string, string, string, string, string> dictMapping = new Dictionary<>();
playlistnames.ItemsSource = dt.DefaultView;
foreach (DataGridViewColumn col in playlistnames.Columns)
{
}*/
}
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
var image = e.AddedItems[0] as ComboBoxItem;
string currentOperation = image.Content.ToString();
{ }
var ttp = sender as ComboBox;
Audio audio = null;
if (image != null && ttp.Tag is Audio)
{
//cartID = (image.Tag as Audio).UID;
audio = (Audio)ttp.Tag;
}
if (audio != null)
{
Global_Log.audio = audio;
selectedIndexValue = datagrid.SelectedIndex;
{ }
playAllSong = new List<Audio>();
foreach (Audio item in datagrid.Items)
{
playAllSong.Add(item);
}
if (currentOperation == "Update")
{
Track_Metadata addMusic = new Track_Metadata();
//Global_Log.audio = audio;
addMusic.updateSong();
}
else if (currentOperation == "Delete")
{
Global_Log.playBack.DeleteSong(audio.ID);
}
else if (currentOperation == "Add to Playlist")
{
//Add_To_Playlist add_To_Playlist = new Add_To_Playlist();
//add_To_Playlist.ShowDialog();
AddToPlaylistWindow add_To_Playlist = new AddToPlaylistWindow();
add_To_Playlist.ShowDialog();
}
else if (currentOperation == "Play")
{
//datagrid
Global_Log.allSongTrack = true;
int listcount = datagrid.Items.Count - 1;
int selectedtrackIndex = datagrid.SelectedIndex;
if (Global_Log.bottom_Media_Control == null)
{
Global_Log.bottom_Media_Control = new Bottom_Media_Control.Bottom_Media_Control();
}
Global_Log.bottom_Media_Control.playSong(audio.Track, audio.Title, audio.Trim_Start, audio.Trim_End, audio.Intro, audio.EOM);
}
}
LoadAllSong();
}
private void AddTrack_Click(object sender, RoutedEventArgs e)
{
Track_Metadata addMusic = new Track_Metadata();
addMusic.insertSong();
LoadAllSong();
}
private void AddSong_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Track_Metadata addMusic = new Track_Metadata();
addMusic.ShowDialog();
LoadAllSong();
}
public void Playlist_picker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string obj = Playlist_picker.SelectedValue.ToString();
{ }
List<PlaylistAudio> obj1 = loadPlaylistSong(0, 0, false, obj);
{ }
PlaylistSong.ItemsSource = obj1;
}
}
}
|
using Alabo.Data.People.PartnerCompanies.Domain.Entities;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories;
using Alabo.Domains.Services;
using MongoDB.Bson;
namespace Alabo.Data.People.PartnerCompanies.Domain.Services {
public class PartnerCompanyService : ServiceBase<PartnerCompany, ObjectId>,IPartnerCompanyService {
public PartnerCompanyService(IUnitOfWork unitOfWork, IRepository<PartnerCompany, ObjectId> repository) : base(unitOfWork, repository){
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsolePiano.InstrumentalNote
{
public class StreamAudioBuilder
{
private const int sampleRate = 44100;
private const int bitDepth = 16;
//only Singleton so far
private static StreamAudioBuilder streamAudioBuilderSingleton;
public static StreamAudioBuilder GetInstance()
{
return streamAudioBuilderSingleton ?? (streamAudioBuilderSingleton = new StreamAudioBuilder());
}
private StreamAudioBuilder() { }
/// <summary>
/// Scheme : //values var is equivalent to Samples
// attack decay sustain release
//--------- ---- ----- -----> t
// -
// - -
// - -
// - ------
// - -
// - -
/// </summary>
/// <param name="frequency"></param>
public int GetSampleSize(double Duration)
{
return (int)(sampleRate * Duration / 1000.0);
}
public MemoryStream GenerateTone(List<double> preparedTone, double frequency)
{
//TODO DEBUG envelope values
File.Delete("debug.txt");
using (StreamWriter streamwriter = new StreamWriter("debug.txt", true, System.Text.Encoding.UTF8))
{ preparedTone.ForEach(x => streamwriter.WriteLine(x.ToString())); }
Int16[] rawAudioStream = GenerateRawAudioSequence(preparedTone, frequency);
MemoryStream memoryStream = GenerateAudioStream(rawAudioStream);
//DEBUG
System.IO.File.WriteAllBytes("lastTone.wav", memoryStream.ToArray());
return memoryStream;
}
private Int16[] GenerateRawAudioSequence(List<double> preparedTone, double frequency)
{
double deltaFT = GetDeltaFT(frequency);
var rawAudioStream = new Int16[preparedTone.Count];
for (int T = 0; T < preparedTone.Count; T++)
rawAudioStream[T] = GetFinalSamples(preparedTone[T], deltaFT, T);
return rawAudioStream;
}
private MemoryStream GenerateAudioStream(Int16[] rawAudioStream)
{
int size = GetSize(rawAudioStream.Length);
MemoryStream memoryStream = CreateStream(size);
BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
int[] headerWav = GetHeader(size);
WriteHeader(headerWav, binaryWriter);
foreach (var convertedNote in rawAudioStream)
WriteActualToneToWriter(convertedNote, binaryWriter);
binaryWriter.Flush();
SetStreamToTheBegining(memoryStream);
return memoryStream;
}
/// AUDIO STREAM
private double GetDeltaFT(double frequency)
{
var lenghtOfCurve = 2 * Math.PI;
var deltaFT = lenghtOfCurve * frequency / sampleRate;
return deltaFT;
}
private static short GetFinalSamples(double amplitude, double deltaFT, double T)
{
var freqTime = Math.Sin(deltaFT * T);
var totalnote = amplitude * freqTime;
Int16 convertedNote;
try { convertedNote = System.Convert.ToInt16(totalnote); }
catch (OverflowException ex) { throw new Exception("Note value out of range( " + totalnote + " )", ex); }
return System.Convert.ToInt16(totalnote);
}
//WAV
private static int GetSize(int samplesSize)
{
return samplesSize * sizeof(int);
}
private MemoryStream CreateStream(int size)
{
return new MemoryStream(44 + size);
}
private static int[] GetHeader(int size)
{
int[] headerWav = { 0X46464952, 36 + size, 0X45564157, 0X20746D66, bitDepth, 0X20001, sampleRate, 176400, 0X100004, 0X61746164, size };
return headerWav;
}
private static void WriteHeader(int[] headerWav, BinaryWriter binaryWriter)
{
for (int I = 0; I < headerWav.Length; I++)
{
binaryWriter.Write(headerWav[I]);
}
}
private void WriteActualToneToWriter(short Sample, BinaryWriter binaryWriter)
{
binaryWriter.Write(Sample);
binaryWriter.Write(Sample);
}
private void SetStreamToTheBegining(MemoryStream stream)
{
stream.Seek(0, SeekOrigin.Begin);
}
}
}
|
using System;
namespace BLL.DLib
{
public class LibRecTags
{
public static string ExecuteTags(string body, string Keyword)
{
body = AddFootnotes("", 1, body);
body = AddPageA(body);
body = AddPageB(body);
body = AddPageC(body);
body = AddTitle(body);
body = AddCenter(body);
body = AddLeft(body);
body = AddQuran(body);
body = AddHadith(body);
body = AddSher(body);
body = AddComment(body);
body = AddNahj(body);
body = body.Replace(" ", " ");
body = body.Replace(" " + Keyword + " ", "<span style='color:red; font-weight:bold; background:yellow'>" + Keyword + "</span>");
return body;
}
public static string RemoveTag(string content, string start_tag, string end_tag)
{
int cnt = content.IndexOf(start_tag);
string content_new = "";
int len = start_tag.Length;
while (cnt > 0)
{
content_new = content_new + content.Substring(0, cnt);
content = content.Substring(cnt + len, content.Length - len - cnt);
cnt = content.IndexOf(end_tag);
content = content.Substring(cnt + len, content.Length - len - cnt);
cnt = content.IndexOf(start_tag);
}
content_new = content_new + content;
return content_new;
}
public static string AddTag(string content, string startTag, string endTag, string startTagHTML, string endTagHTML)
{
int cnt = content.IndexOf(startTag);
string content_new = "";
int len = startTag.Length;
while (cnt > 0 && content.IndexOf(endTag)>0)
{
content_new = content_new + content.Substring(0, cnt);
content = content.Substring(cnt + len, content.Length - len - cnt);
cnt = content.IndexOf(endTag);
content_new = content_new + startTagHTML + content.Substring(0, cnt) + endTagHTML;
content = content.Substring(cnt + len, content.Length - len - cnt);
cnt = content.IndexOf(startTag);
}
content_new = content_new + content;
return content_new;
}
public static string AddFootnotes(string footnote, int footnotes_num, string content)
{
string start_footnote = "{f";
string end_footnote = "f}";
int cnt = content.IndexOf(start_footnote);
string content_new = "";
while (cnt > 0)
{
content_new = content_new + content.Substring(0, cnt) + " <sup><a name='top_" + footnotes_num + "' href='#down_" + footnotes_num + "' class='footnote' style='text-decoration:none' title='";
content = content.Substring(cnt + 2, content.Length - 2 - cnt);
cnt = content.IndexOf(end_footnote);
content_new = content_new + (cnt > 0 ? content.Substring(0, cnt) : "") + "'> [" + footnotes_num + "] </a></sup>";
if (footnote == "")
footnote = "<table border=0 cellpadding=2 cellspacing=0 style='font-family:Tahoma; font-size:11px' width='100%'>";
footnote += "<tr><td width='25' valign='top'><a name='down_" + footnotes_num + "' href='#top_" + footnotes_num + "' class='footnote_' style='text-decoration:none'>" + footnotes_num + " - </a></td><td>" + (cnt > 0 ? content.Substring(0, cnt) : "") + "</td></tr>";
content = content.Substring(cnt + 2, content.Length - 2 - cnt);
cnt = content.IndexOf(start_footnote);
footnotes_num++;
}
if (footnote.Trim() != "")
content_new = content_new + content + "<br><br><table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td><b>پاورقی </b></td></tr></table>" + footnote + "</table>";
else
content_new = content_new + content;
return content_new;
}
public static string NormalPageTag(string content)
{
content = content.Replace("{Pa", "{pa").Replace("{PA", "{pa").Replace("{pA", "{pa");
content = content.Replace("Pa}", "pa}").Replace("PA}", "pa}").Replace("pA}", "pa}");
content = content.Replace("{Pb", "{pb").Replace("{PB", "{pb").Replace("{pB", "{pb");
content = content.Replace("Pb}", "pb}").Replace("PB}", "pb}").Replace("pB}", "pb}");
content = content.Replace("{Pc", "{pc").Replace("{PC", "{pc").Replace("{pC", "{pc");
content = content.Replace("Pc}", "pc}").Replace("PC}", "pc}").Replace("pC}", "pc}");
return content;
}
public static string AddPageA(string content)
{
string start_footnote = "{pa";
string end_footnote = "pa}";
content = NormalPageTag(content);
int cnt = content.IndexOf(start_footnote);
string content_new = "";
while (cnt > 0)
{
content_new = content_new + content.Substring(0, cnt);
content = content.Substring(cnt + 3, content.Length - 3 - cnt);
cnt = content.IndexOf(end_footnote);
int page_num = Convert.ToInt16(content.Substring(0, cnt));
content_new = content_new + "<br><table border=0 cellpading=0 cellspacing=0 align=center><tr><td valign=bottom><hr width=100></td><td><a name=\"page_" + page_num + "\"></a> <a title='صفحه بعدی' href='#page_" + (page_num + 1) + "' style='text-decoration:none;font-size:18px; color:#ff901e'>«</a></td><td style='font-family:Tahoma;font-size:12px;color:#969696;'> صفحه مجموعه آثار " + page_num + " </td><td><a title='صفحه قبلی' href='#page_" + (page_num - 1) + "' style='text-decoration:none; font-size:18px; color:#ff901e'>»</a></td><td valign=bottom><hr width=100></td></tr></table><br>";
content = content.Substring(cnt + 3, content.Length - 3 - cnt);
cnt = content.IndexOf(start_footnote);
}
content_new = content_new + content;
return content_new;
}
public static string AddPageB(string content)
{
string start_footnote = "{pb";
string end_footnote = "pb}";
content = NormalPageTag(content);
int cnt = content.IndexOf(start_footnote);
string content_new = "";
while (cnt > 0)
{
content_new = content_new + content.Substring(0, cnt);
content = content.Substring(cnt + 3, content.Length - 3 - cnt);
cnt = content.IndexOf(end_footnote);
int page_num = Convert.ToInt16(content.Substring(0, cnt));
content_new = content_new + "<br><table border=0 cellpading=0 cellspacing=0 align=center><tr><td valign=bottom><hr width=100></td><td><a name=\"page_" + page_num + "\"></a> <a title='صفحه بعدی' href='#page_" + (page_num + 1) + "' style='text-decoration:none;font-size:18px; color:#ff901e'>«</a></td><td style='font-family:Tahoma;font-size:12px;color:#969696;'> صفحه " + page_num + " </td><td><a title='صفحه قبلی' href='#page_" + (page_num - 1) + "' style='text-decoration:none; font-size:18px; color:#ff901e'>»</a></td><td valign=bottom><hr width=100></td></tr></table><br>";
content = content.Substring(cnt + 3, content.Length - 3 - cnt);
cnt = content.IndexOf(start_footnote);
}
content_new = content_new + content;
return content_new;
}
public static string AddPageC(string content)
{
string start_footnote = "{pc";
string end_footnote = "pc}";
content = NormalPageTag(content);
int cnt = content.IndexOf(start_footnote);
string content_new = "";
while (cnt > 0)
{
content_new = content_new + content.Substring(0, cnt);
content = content.Substring(cnt + 3, content.Length - 3 - cnt);
cnt = content.IndexOf(end_footnote);
int page_num = Convert.ToInt16(content.Substring(0, cnt));
content_new = content_new + "<br><table border=0 cellpading=0 cellspacing=0 align=center><tr><td valign=bottom><hr width=100></td><td><a name=\"page_" + page_num + "\"></a> <a title='صفحه بعدی' href='#page_" + (page_num + 1) + "' style='text-decoration:none;font-size:18px; color:#ff901e'>«</a></td><td style='font-family:Tahoma;font-size:12px;color:#969696;'> صفحه " + page_num + " </td><td><a title='صفحه قبلی' href='#page_" + (page_num - 1) + "' style='text-decoration:none; font-size:18px; color:#ff901e'>»</a></td><td valign=bottom><hr width=100></td></tr></table><br>";
content = content.Substring(cnt + 3, content.Length - 3 - cnt);
cnt = content.IndexOf(start_footnote);
}
content_new = content_new + content;
return content_new;
}
public static string AddComment(string content)
{
return AddTag(content, "{g", "g}", " <div style='color:gray; padding:10px'>«", "»</div>");
}
public static string AddTitle(string content)
{
return AddTag(content, "{t", "t}", "<p><center><b>", "</b></center></p>");
}
public static string AddCenter(string content)
{
return AddTag(content, "{c", "c}", "<p align='center'>", "</p>");
}
public static string AddLeft(string content)
{
return AddTag(content, "{l", "l}", "<p align='left'>", "</p>");
}
public static string AddQuran(string content)
{
return AddTag(content, "{q", "q}", "<span style='font-weight:bold; color:green; font-familt:'Courier New'>", "</span>");
}
public static string AddNahj(string content)
{
return AddTag(content, "{n", "n}", " <span style='color:blue;'>", "</span>");
}
public static string AddHadith(string content)
{
return AddTag(content, "{h", "h}", "<span style='font-weight:bold; color:blue; font-familt:'Courier New'>", "</span>");
}
public static string AddSher(string content)
{
string startTag = "{s";
string endTag = "s}";
string startTagHTML = "<div style='text-align:center; color:Teal; font-weight:bold;'>";
string endTagHTML = "</div><br>";
int cnt = content.IndexOf(startTag);
string content_new = "";
int len = startTag.Length;
while (cnt > 0)
{
content_new = content_new + content.Substring(0, cnt);
content = content.Substring(cnt + len, content.Length - len - cnt);
cnt = content.IndexOf(endTag);
content_new = content_new + startTagHTML + content.Substring(0, cnt).Replace("\r\n", " <br>") + endTagHTML;
content = content.Substring(cnt + len, content.Length - len - cnt);
cnt = content.IndexOf(startTag);
}
content_new = content_new + content;
return content_new;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
namespace EpisodeRenaming {
class OnlineSearchTrakt {
private static string ClientID = "96bd1d3f62624c5603f5df37b07a2180d747ef691e5ebd635844cc76b92c5537";
private static Uri baseAddress = new Uri( "https://api-v2launch.trakt.tv/" );
private static Uri mockBaseAddress = new Uri( "https://private-anon-9796605bd-trakt.apiary-mock.com/" );
public static async Task<string> getTvShowSearchResult ( string query, string type, string year = "" ) {
string responseData = String.Empty;
using ( var httpClient = new HttpClient() ) {
httpClient.BaseAddress = baseAddress;
httpClient.DefaultRequestHeaders.TryAddWithoutValidation( "trakt-api-version", "2" );
httpClient.DefaultRequestHeaders.TryAddWithoutValidation( "trakt-api-key", ClientID );
if ( year == "" ) {
using ( var response = await httpClient.GetAsync( "search?query=" + query + "&" + "type=" + type ) ) {
responseData = await response.Content.ReadAsStringAsync();
}
} else {
using ( var response = await httpClient.GetAsync( "search?query=" + query + "&" + "type=" + type + "&year=" + year ) ) {
responseData = await response.Content.ReadAsStringAsync();
}
}
}
return responseData;
}
public static async Task<string> getSeasonSearchResult ( string TVshowId ) {
string responseData = String.Empty;
using ( var httpClient = new HttpClient() ) {
httpClient.BaseAddress = baseAddress;
httpClient.DefaultRequestHeaders.TryAddWithoutValidation( "trakt-api-version", "2" );
httpClient.DefaultRequestHeaders.TryAddWithoutValidation( "trakt-api-key", ClientID );
using ( var response = await httpClient.GetAsync( "shows/" + TVshowId + "/seasons" ) ) {
responseData = await response.Content.ReadAsStringAsync();
}
}
return responseData;
}
}
}
|
using Library.Appenders.Contracts;
using Library.Layouts.Contracts;
using Library.Loggers.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Library.Appenders
{
public class FileAppender : IAppender
{
private const string Path = @"..\..\..\log.txt";
private ILayout layout;
private ILogFile logFile;
public FileAppender(ILayout layout, ILogFile logFile)
{
this.layout = layout;
this.logFile = logFile;
}
public void Append(string dateTime, string reportLevel, string message)
{
string content = string.Format(this.layout.Format, dateTime, reportLevel, message) + Environment.NewLine;
File.AppendAllText(Path,content );
}
}
}
|
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
public class PhotoManager : MonoBehaviour
{
WebCamTexture webCamTexture;
private SpriteRenderer sr;
int numberPhotos = 50;
int numberPhoto = 0;
public int process = 0;
public GameObject image;
public GameObject alignSquare;
public GameObject background;
public GameObject textAlign;
public GameObject textManager;
Texture2D photo;
void Start ()
{
sr = gameObject.AddComponent<SpriteRenderer>() as SpriteRenderer;
sr.color = new Color(0.9f, 0.9f, 0.9f, 1.0f);
transform.position = new Vector3(1.5f, 1.5f, 0.0f);
webCamTexture = new WebCamTexture();
GetComponent<Renderer>().material.mainTexture = webCamTexture;
webCamTexture.Play();
photo = new Texture2D(webCamTexture.width, webCamTexture.height);
}
void Update()
{
if (process == 1)
{
StartCoroutine(PositionTarget());
process = 2;
}
if (process == 4)
{
image.GetComponent<Image>().enabled = true;
StartCoroutine(TakePhotos());
process = 0;
}
}
IEnumerator PositionTarget()
{
while (process == 1 || process == 2)
{
yield return new WaitForEndOfFrame();
photo.SetPixels(webCamTexture.GetPixels());
photo.Apply();
// photo = rotateTexture(photo, true);
// Show image
alignSquare.GetComponent<Image>().sprite = Sprite.Create(photo, new Rect(0.0f, 0.0f, photo.width, photo.height), new Vector2(0.5f, 0.5f), 100.0f);
yield return new WaitForSeconds(0.1f);
}
alignSquare.GetComponent<Image>().enabled = false;
background.GetComponent<Image>().enabled = false;
textAlign.GetComponent<Text>().enabled = false;
}
IEnumerator TakePhotos()
{
for (numberPhoto = 0; numberPhoto < numberPhotos; numberPhoto++)
{
yield return new WaitForEndOfFrame();
photo.SetPixels(webCamTexture.GetPixels());
photo.Apply();
// photo = rotateTexture(photo, true);
image.GetComponent<Image>().sprite = Sprite.Create(photo, new Rect(0.0f, 0.0f, photo.width, photo.height), new Vector2(0.5f, 0.5f), 100.0f);
//Encode to a PNG
byte[] bytes = photo.EncodeToPNG();
//Write out the PNG
File.WriteAllBytes(Application.persistentDataPath + "/photo" + Random.Range(1,100) + numberPhoto.ToString() + ".png", bytes);
yield return new WaitForSeconds(textManager.GetComponent<TextManager>().timeBetweenPhotographs);
}
image.transform.parent.GetChild(1).GetComponentInChildren<Image>().enabled = true;
image.transform.parent.GetComponentInChildren<Text>().enabled = true;
image.transform.parent.GetChild(1).GetChild(2).GetComponent<Text>().enabled = true;
}
Texture2D rotateTexture(Texture2D originalTexture, bool clockwise)
{
Color32[] original = originalTexture.GetPixels32();
Color32[] rotated = new Color32[original.Length];
int w = originalTexture.width;
int h = originalTexture.height;
int iRotated, iOriginal;
for (int j = 0; j < h; ++j)
{
for (int i = 0; i < w; ++i)
{
iRotated = (i + 1) * h - j - 1;
iOriginal = clockwise ? original.Length - 1 - (j * w + i) : j * w + i;
rotated[iRotated] = original[iOriginal];
}
}
Texture2D rotatedTexture = new Texture2D(h, w);
rotatedTexture.SetPixels32(rotated);
rotatedTexture.Apply();
return rotatedTexture;
}
}
|
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.Internal.Cache;
using Microsoft.Identity.Client.Internal.Instance;
using Microsoft.Identity.Client.Internal.OAuth2;
using Microsoft.Identity.Client.Internal.Requests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Test.MSAL.NET.Unit.Mocks;
namespace Test.MSAL.NET.Unit.CacheTests
{
[TestClass]
public class TokenCacheTests
{
public static long ValidExpiresIn = 3600;
// Passing a seed to make repro possible
private static readonly Random Rand = new Random(42);
TokenCache cache;
[TestInitialize]
public void TestInitialize()
{
cache = new TokenCache();
}
[TestCleanup]
public void TestCleanup()
{
cache.TokenCacheAccessor.AccessTokenCacheDictionary.Clear();
cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Clear();
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetExactScopesMatchedAccessTokenTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ScopeSet = TestConstants.Scope,
Scope = TestConstants.Scope.AsSingleString(),
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
RawClientInfo = MockHelpers.CreateClientInfo(),
};
atItem.IdToken = IdToken.Parse(atItem.RawIdToken);
atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);
// create key out of access token cache item and then
// set it as the value of the access token.
AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();
atItem.AccessToken = atKey.ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
AccessTokenCacheItem item = cache.FindAccessToken(new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
User = TestConstants.User
});
Assert.IsNotNull(item);
Assert.AreEqual(atKey.ToString(), item.AccessToken);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetSubsetScopesMatchedAccessTokenTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ScopeSet = TestConstants.Scope,
Scope = TestConstants.Scope.AsSingleString(),
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
RawClientInfo = MockHelpers.CreateClientInfo(),
};
atItem.IdToken = IdToken.Parse(atItem.RawIdToken);
atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);
// create key out of access token cache item and then
// set it as the value of the access token.
AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();
atItem.AccessToken = atKey.ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
var param = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = new SortedSet<string>(),
User = TestConstants.User
};
param.Scope.Add("r1/scope1");
AccessTokenCacheItem item = cache.FindAccessToken(param);
Assert.IsNotNull(item);
Assert.AreEqual(atKey.ToString(), item.AccessToken);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetIntersectedScopesMatchedAccessTokenTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ScopeSet = TestConstants.Scope,
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
};
// create key out of access token cache item and then
// set it as the value of the access token.
AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();
atItem.AccessToken = atKey.ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
var param = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = new SortedSet<string>(),
User =
new User()
{
DisplayableId = TestConstants.DisplayableId,
Identifier = TestConstants.UserIdentifier
}
};
param.Scope.Add(TestConstants.Scope.First());
param.Scope.Add("non-existant-scopes");
AccessTokenCacheItem item = cache.FindAccessToken(param);
//intersected scopes are not returned.
Assert.IsNull(item);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetExpiredAccessTokenTest()
{
cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem item = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
RawClientInfo = MockHelpers.CreateClientInfo(),
ScopeSet = TestConstants.Scope
};
item.IdToken = IdToken.Parse(item.RawIdToken);
item.ClientInfo = ClientInfo.CreateFromJson(item.RawClientInfo);
item.AccessToken = item.GetAccessTokenItemKey().ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
JsonHelper.SerializeToJson(item);
cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
JsonHelper.SerializeToJson(item);
Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
User =
new User()
{
DisplayableId = TestConstants.DisplayableId,
Identifier = TestConstants.UserIdentifier
}
}));
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetAccessTokenExpiryInRangeTest()
{
cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
ScopeSet = TestConstants.Scope,
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
TokenType = "Bearer",
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromMinutes(4))
};
atItem.AccessToken = atItem.GetAccessTokenItemKey().ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atItem.GetAccessTokenItemKey().ToString()] =
JsonHelper.SerializeToJson(atItem);
Assert.IsNull(cache.FindAccessToken(new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
User =
new User()
{
DisplayableId = TestConstants.DisplayableId,
Identifier = TestConstants.UserIdentifier
}
}));
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetRefreshTokenTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
RefreshTokenCacheItem rtItem = new RefreshTokenCacheItem()
{
Environment = TestConstants.ProductionEnvironment,
ClientId = TestConstants.ClientId,
RefreshToken = "someRT",
RawClientInfo = MockHelpers.CreateClientInfo(),
DisplayableId = TestConstants.DisplayableId,
IdentityProvider = TestConstants.IdentityProvider,
Name = TestConstants.Name
};
rtItem.ClientInfo = ClientInfo.CreateFromJson(rtItem.RawClientInfo);
RefreshTokenCacheKey rtKey = rtItem.GetRefreshTokenItemKey();
cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtKey.ToString()] = JsonHelper.SerializeToJson(rtItem);
var authParams = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
User = TestConstants.User
};
Assert.IsNotNull(cache.FindRefreshToken(authParams));
// RT is stored by environment, client id and userIdentifier as index.
// any change to authority (within same environment), uniqueid and displyableid will not
// change the outcome of cache look up.
Assert.IsNotNull(cache.FindRefreshToken(new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant + "more", false),
Scope = TestConstants.Scope,
User = TestConstants.User
}));
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetRefreshTokenDifferentEnvironmentTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
RefreshTokenCacheItem rtItem = new RefreshTokenCacheItem()
{
Environment = TestConstants.SovereignEnvironment,
ClientId = TestConstants.ClientId,
RefreshToken = "someRT",
RawClientInfo = MockHelpers.CreateClientInfo(),
DisplayableId = TestConstants.DisplayableId,
IdentityProvider = TestConstants.IdentityProvider,
Name = TestConstants.Name
};
RefreshTokenCacheKey rtKey = rtItem.GetRefreshTokenItemKey();
cache.TokenCacheAccessor.RefreshTokenCacheDictionary[rtKey.ToString()] = JsonHelper.SerializeToJson(rtItem);
var authParams = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
User = TestConstants.User
};
Assert.IsNull(cache.FindRefreshToken(authParams));
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetAppTokenFromCacheTest()
{
cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem item = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ExpiresOnUnixTimestamp =
MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)),
RawIdToken = null,
RawClientInfo = null,
User = null,
Scope = TestConstants.Scope.AsSingleString(),
ScopeSet = TestConstants.Scope
};
item.AccessToken = item.GetAccessTokenItemKey().ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] =
JsonHelper.SerializeToJson(item);
AccessTokenCacheItem cacheItem = cache.FindAccessToken(new AuthenticationRequestParameters()
{
IsClientCredentialRequest = true,
RequestContext = new RequestContext(Guid.Empty, null),
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId,
ClientCredential = TestConstants.CredentialWithSecret,
Scope = TestConstants.Scope
});
Assert.IsNotNull(cacheItem);
Assert.AreEqual(item.GetAccessTokenItemKey().ToString(), cacheItem.GetAccessTokenItemKey().ToString());
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetAccessTokenNoUserAssertionInCacheTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ScopeSet = TestConstants.Scope,
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
};
// create key out of access token cache item and then
// set it as the value of the access token.
AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();
atItem.AccessToken = atKey.ToString();
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
var param = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
UserAssertion = new UserAssertion(CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString()))
};
AccessTokenCacheItem item = cache.FindAccessToken(param);
//cache lookup should fail because there was no userassertion hash in the matched
//token cache item.
Assert.IsNull(item);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetAccessTokenUserAssertionMismatchInCacheTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ScopeSet = TestConstants.Scope,
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
};
// create key out of access token cache item and then
// set it as the value of the access token.
AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();
atItem.AccessToken = atKey.ToString();
atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString());
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
var param = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
UserAssertion = new UserAssertion(atItem.UserAssertionHash + "-random")
};
AccessTokenCacheItem item = cache.FindAccessToken(param);
// cache lookup should fail because there was userassertion hash did not match the one
// stored in token cache item.
Assert.IsNull(item);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void GetAccessTokenMatchedUserAssertionInCacheTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
AccessTokenCacheItem atItem = new AccessTokenCacheItem()
{
Authority = TestConstants.AuthorityHomeTenant,
ClientId = TestConstants.ClientId,
TokenType = "Bearer",
ScopeSet = TestConstants.Scope,
Scope = TestConstants.Scope.AsSingleString(),
ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)),
RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId)
};
// create key out of access token cache item and then
// set it as the value of the access token.
AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();
atItem.AccessToken = atKey.ToString();
atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString());
cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);
var param = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = TestConstants.Scope,
UserAssertion = new UserAssertion(atKey.ToString())
};
cache.AfterAccess = AfterAccessNoChangeNotification;
AccessTokenCacheItem item = cache.FindAccessToken(param);
Assert.IsNotNull(item);
Assert.AreEqual(atKey.ToString(), item.AccessToken);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void SaveAccessAndRefreshTokenWithEmptyCacheTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenResponse response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.AccessToken = "access-token";
response.ClientInfo = MockHelpers.CreateClientInfo();
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token";
response.Scope = TestConstants.Scope.AsSingleString();
response.TokenType = "Bearer";
AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId
};
cache.SaveAccessAndRefreshToken(requestParams, response);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void SaveAccessAndRefreshTokenWithMoreScopesTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenResponse response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token";
response.Scope = TestConstants.Scope.AsSingleString();
response.TokenType = "Bearer";
RequestContext requestContext = new RequestContext(Guid.NewGuid(), null);
AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
{
RequestContext = requestContext,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId,
TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant
};
cache.SaveAccessAndRefreshToken(requestParams, response);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token-2";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token-2";
response.Scope = TestConstants.Scope.AsSingleString() + " another-scope";
response.TokenType = "Bearer";
cache.SaveAccessAndRefreshToken(requestParams, response);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
Assert.AreEqual("refresh-token-2", cache.GetAllRefreshTokensForClient(requestContext).First().RefreshToken);
Assert.AreEqual("access-token-2", cache.GetAllAccessTokensForClient(requestContext).First().AccessToken);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void SaveAccessAndRefreshTokenWithLessScopesTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenResponse response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token";
response.Scope = TestConstants.Scope.AsSingleString();
response.TokenType = "Bearer";
RequestContext requestContext = new RequestContext(Guid.NewGuid(), null);
AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
{
RequestContext = requestContext,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId,
TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant
};
cache.SaveAccessAndRefreshToken(requestParams, response);
response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token-2";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token-2";
response.Scope = TestConstants.Scope.First();
response.TokenType = "Bearer";
cache.SaveAccessAndRefreshToken(requestParams, response);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
Assert.AreEqual("refresh-token-2", cache.GetAllRefreshTokensForClient(requestContext).First().RefreshToken);
Assert.AreEqual("access-token-2", cache.GetAllAccessTokensForClient(requestContext).First().AccessToken);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void SaveAccessAndRefreshTokenWithIntersectingScopesTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenResponse response = new TokenResponse
{
IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
AccessToken = "access-token",
ClientInfo = MockHelpers.CreateClientInfo(),
ExpiresIn = 3599,
CorrelationId = "correlation-id",
RefreshToken = "refresh-token",
Scope = TestConstants.Scope.AsSingleString(),
TokenType = "Bearer"
};
RequestContext requestContext = new RequestContext(Guid.NewGuid(), null);
AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
{
RequestContext = requestContext,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId,
TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant
};
cache.SaveAccessAndRefreshToken(requestParams, response);
response = new TokenResponse
{
IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
ClientInfo = MockHelpers.CreateClientInfo(),
AccessToken = "access-token-2",
ExpiresIn = 3599,
CorrelationId = "correlation-id",
RefreshToken = "refresh-token-2",
Scope = TestConstants.Scope.First() + " random-scope",
TokenType = "Bearer"
};
cache.SaveAccessAndRefreshToken(requestParams, response);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
Assert.AreEqual("refresh-token-2", cache.GetAllRefreshTokensForClient(requestContext).First().RefreshToken);
Assert.AreEqual("access-token-2", cache.GetAllAccessTokensForClient(requestContext).First().AccessToken);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void SaveAccessAndRefreshTokenWithDifferentAuthoritySameUserTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenResponse response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token";
response.Scope = TestConstants.Scope.AsSingleString();
response.TokenType = "Bearer";
RequestContext requestContext = new RequestContext(Guid.NewGuid(), null);
AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
{
RequestContext = requestContext,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId,
TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant
};
cache.SaveAccessAndRefreshToken(requestParams, response);
response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token-2";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token-2";
response.Scope = TestConstants.Scope.AsSingleString() + " another-scope";
response.TokenType = "Bearer";
requestContext = new RequestContext(Guid.NewGuid(), null);
requestParams = new AuthenticationRequestParameters()
{
RequestContext = requestContext,
Authority = Authority.CreateAuthority(TestConstants.AuthorityGuestTenant, false),
ClientId = TestConstants.ClientId,
TenantUpdatedCanonicalAuthority = TestConstants.AuthorityGuestTenant
};
cache.SetAfterAccess(AfterAccessChangedNotification);
cache.SaveAccessAndRefreshToken(requestParams, response);
Assert.IsFalse(cache.HasStateChanged);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
Assert.AreEqual("refresh-token-2", cache.GetAllRefreshTokensForClient(requestContext).First().RefreshToken);
}
private void AfterAccessChangedNotification(TokenCacheNotificationArgs args)
{
Assert.IsTrue(args.TokenCache.HasStateChanged);
}
private void AfterAccessNoChangeNotification(TokenCacheNotificationArgs args)
{
Assert.IsFalse(args.TokenCache.HasStateChanged);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void SerializeDeserializeCacheTest()
{
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenResponse response = new TokenResponse();
response.IdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId);
response.ClientInfo = MockHelpers.CreateClientInfo();
response.AccessToken = "access-token";
response.ExpiresIn = 3599;
response.CorrelationId = "correlation-id";
response.RefreshToken = "refresh-token";
response.Scope = TestConstants.Scope.AsSingleString();
response.TokenType = "Bearer";
RequestContext requestContext = new RequestContext(Guid.NewGuid(), null);
AuthenticationRequestParameters requestParams = new AuthenticationRequestParameters()
{
RequestContext = requestContext,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
ClientId = TestConstants.ClientId,
TenantUpdatedCanonicalAuthority = TestConstants.AuthorityHomeTenant
};
cache.SaveAccessAndRefreshToken(requestParams, response);
byte[] serializedCache = cache.Serialize();
cache.TokenCacheAccessor.AccessTokenCacheDictionary.Clear();
cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Clear();
Assert.AreEqual(0, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(0, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
cache.Deserialize(serializedCache);
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
serializedCache = cache.Serialize();
cache.Deserialize(serializedCache);
//item count should not change because old cache entries should have
//been overriden
Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
AccessTokenCacheItem atItem = cache.GetAllAccessTokensForClient(requestContext).First();
Assert.AreEqual(response.AccessToken, atItem.AccessToken);
Assert.AreEqual(TestConstants.AuthorityHomeTenant, atItem.Authority);
Assert.AreEqual(TestConstants.ClientId, atItem.ClientId);
Assert.AreEqual(response.TokenType, atItem.TokenType);
Assert.AreEqual(response.Scope, atItem.ScopeSet.AsSingleString());
Assert.AreEqual(response.IdToken, atItem.RawIdToken);
RefreshTokenCacheItem rtItem = cache.GetAllRefreshTokensForClient(requestContext).First();
Assert.AreEqual(response.RefreshToken, rtItem.RefreshToken);
Assert.AreEqual(TestConstants.ClientId, rtItem.ClientId);
Assert.AreEqual(TestConstants.UserIdentifier, rtItem.GetUserIdentifier());
Assert.AreEqual(TestConstants.ProductionEnvironment, rtItem.Environment);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void FindAccessToken_ScopeCaseInsensitive()
{
var tokenCache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
TokenCacheHelper.PopulateCache(tokenCache.TokenCacheAccessor);
var param = new AuthenticationRequestParameters()
{
RequestContext = new RequestContext(Guid.Empty, null),
ClientId = TestConstants.ClientId,
Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false),
Scope = new SortedSet<string>(),
User = TestConstants.User
};
var scopeInCache = TestConstants.Scope.FirstOrDefault();
var upperCaseScope = scopeInCache.ToUpper();
param.Scope.Add(upperCaseScope);
var item = tokenCache.FindAccessToken(param);
Assert.IsNotNull(item);
Assert.IsTrue(item.ScopeSet.Contains(scopeInCache));
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void DeserializeCacheItemWithNoVersion()
{
string noVersionCacheEntry = "{\"client_id\":\"client_id\",\"client_info\":\"eyJ1aWQiOiJteS1VSUQiLCJ1dGlkIjoibXktVVRJRCJ9\",\"access_token\":\"access-token\",\"authority\":\"https:\\\\/\\\\/login.microsoftonline.com\\\\/home\\\\/\",\"expires_on\":1494025355,\"id_token\":\"someheader.eyJhdWQiOiAiZTg1NGE0YTctNmMzNC00NDljLWIyMzctZmM3YTI4MDkzZDg0IiwiaXNzIjogImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbS82YzNkNTFkZC1mMGU1LTQ5NTktYjRlYS1hODBjNGUzNmZlNWUvdjIuMC8iLCJpYXQiOiAxNDU1ODMzODI4LCJuYmYiOiAxNDU1ODMzODI4LCJleHAiOiAxNDU1ODM3NzI4LCJpcGFkZHIiOiAiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6ICJNYXJycnJyaW8gQm9zc3kiLCJvaWQiOiAidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjogImRpc3BsYXlhYmxlQGlkLmNvbSIsInN1YiI6ICJLNF9TR0d4S3FXMVN4VUFtaGc2QzFGNlZQaUZ6Y3gtUWQ4MGVoSUVkRnVzIiwidGlkIjogIm15LWlkcCIsInZlciI6ICIyLjAifQ.somesignature\",\"scope\":\"r1\\\\/scope1 r1\\\\/scope2\",\"token_type\":\"Bearer\",\"user_assertion_hash\":null}";
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
cache.AddAccessTokenCacheItem(JsonHelper.DeserializeFromJson<AccessTokenCacheItem>(noVersionCacheEntry));
ICollection<AccessTokenCacheItem> items = cache.GetAllAccessTokensForClient(new RequestContext(Guid.Empty, null));
Assert.AreEqual(1, items.Count);
AccessTokenCacheItem item = items.First();
Assert.AreEqual(0, item.Version);
}
[TestMethod]
[TestCategory("TokenCacheTests")]
public void DeserializeCacheItemWithDifferentVersion()
{
string differentVersionEntry = "{\"client_id\":\"client_id\",\"client_info\":\"eyJ1aWQiOiJteS1VSUQiLCJ1dGlkIjoibXktVVRJRCJ9\",\"ver\":5,\"access_token\":\"access-token\",\"authority\":\"https:\\\\/\\\\/login.microsoftonline.com\\\\/home\\\\/\",\"expires_on\":1494025355,\"id_token\":\"someheader.eyJhdWQiOiAiZTg1NGE0YTctNmMzNC00NDljLWIyMzctZmM3YTI4MDkzZDg0IiwiaXNzIjogImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbS82YzNkNTFkZC1mMGU1LTQ5NTktYjRlYS1hODBjNGUzNmZlNWUvdjIuMC8iLCJpYXQiOiAxNDU1ODMzODI4LCJuYmYiOiAxNDU1ODMzODI4LCJleHAiOiAxNDU1ODM3NzI4LCJpcGFkZHIiOiAiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6ICJNYXJycnJyaW8gQm9zc3kiLCJvaWQiOiAidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjogImRpc3BsYXlhYmxlQGlkLmNvbSIsInN1YiI6ICJLNF9TR0d4S3FXMVN4VUFtaGc2QzFGNlZQaUZ6Y3gtUWQ4MGVoSUVkRnVzIiwidGlkIjogIm15LWlkcCIsInZlciI6ICIyLjAifQ.somesignature\",\"scope\":\"r1\\\\/scope1 r1\\\\/scope2\",\"token_type\":\"Bearer\",\"user_assertion_hash\":null}";
TokenCache cache = new TokenCache()
{
ClientId = TestConstants.ClientId
};
cache.AddAccessTokenCacheItem(JsonHelper.DeserializeFromJson<AccessTokenCacheItem>(differentVersionEntry));
ICollection<AccessTokenCacheItem> items = cache.GetAllAccessTokensForClient(new RequestContext(Guid.Empty, null));
Assert.AreEqual(1, items.Count);
AccessTokenCacheItem item = items.First();
Assert.AreEqual(5, item.Version);
}
}
}
|
using NetApi;
using System;
using System.Threading;
namespace TraderApiTest
{
class Callback : XtTraderApiCallback
{
public int m_nRequestId;
public String m_strAddress;
public String m_strUserName;
public String m_strPassWord;
public String m_strAccountId;
public int m_nOrderNumPerSec;
public int m_nOrderTimeSecs;
public XtTraderApi m_client;
public Callback(String address, String username, String password, String accountid, int orderNum, int timeSec)
{
m_strAddress = address;
m_strUserName = username;
m_strPassWord = password;
m_strAccountId = accountid;
m_nOrderNumPerSec = orderNum;
m_nOrderTimeSecs = timeSec;
}
public bool init()
{
if (m_strAddress.Length == 0)
{
System.Console.WriteLine("server address is empty, exit");
return false;
}
m_client = XtTraderApi.createXtTraderApi(m_strAddress);
if (null == m_client)
{
System.Console.WriteLine("create traderapi client fails, exit");
return false;
}
m_client.setCallback(this);
return m_client.init();
}
public void join()
{
m_client.join();
}
public override void onConnected(bool success, String errorMsg)
{
System.Console.WriteLine("connect {0}", success);
if (success)
{
m_client.userLogin(m_strUserName, m_strPassWord, m_nRequestId++);
}
else
{
System.Console.WriteLine("connect failed! errorMsg: {0}", errorMsg);
}
}
public override void onUserLogin(String userName, String password, int nRequestId, XtError error)
{
if (error.isSuccess())
{
m_client.reqAccountDetail(m_strAccountId, m_nRequestId++);
m_client.reqOrderDetail(m_strAccountId, m_nRequestId++);
m_client.reqDealDetail(m_strAccountId, m_nRequestId++);
m_client.reqPositionDetail(m_strAccountId, m_nRequestId++);
m_client.reqPositionStatics(m_strAccountId, m_nRequestId++);
m_client.reqPriceData("SZ", "000002", m_nRequestId++);
System.Console.WriteLine("UserLogin Success username: {0}, password: {1}", userName, password);
}
else
{
System.Console.WriteLine("UserLogin fails, username: {0}, password: {1}, errorMsg: {2}", userName, password, error.errorMsg());
}
}
public override void onUserLogout(String userName, String password, int nRequestId, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onUserLogout] success");
}
else
{
System.Console.WriteLine("[onUserLogout] fails, errorId:{0},errorMsg:{1}", error.errorID(), error.errorMsg());
}
}
public override void onReqAccountDetail(String accountID, int nRequestId, CAccountDetail data, bool isLast, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onReqAccountDetail] accountid: {0}, m_dBalance: {1}, error id: {2}, error msg: {3}", data.m_strAccountID, data.m_dBalance, error.errorID(), error.errorMsg());
}
else
{
System.Console.WriteLine("[onReqAccountDetail] data is null. accountid: {0}, error id: {1}, error msg: {2}", accountID, error.errorID(), error.errorMsg());
}
}
public override void onReqOrderDetail(String accountID, int nRequestId, COrderDetail data, bool isLast, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onReqOrderDetail] accountid: {0}, ExchangeId: {1}, error id: {2}, error msg: {3}", data.m_strAccountID, data.m_strExchangeID, error.errorID(), error.errorMsg());
}
else
{
System.Console.WriteLine("[onReqOrderDetail] data is null. accountid: {0}, error id: {1}, error msg: {2}", accountID, error.errorID(), error.errorMsg());
}
}
public override void onReqDealDetail(String accountID, int nRequestId, CDealDetail data, bool isLast, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onReqDealDetail] accountid: {0}, OrderSysID: {1}, error id: {2}, error msg: {3}", accountID, data.m_strOrderSysID, error.errorID(), error.errorMsg());
}
else
{
System.Console.WriteLine("[onReqDealDetail] data is null. accountid: {0}, error id: {1}, error msg: {2}", accountID, error.errorID(), error.errorMsg());
}
}
public override void onReqPositionDetail(String accountID, int nRequestId, CPositionDetail data, bool isLast, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onReqPositionDetail] accountid: {0}, m_strExchangeID: {1}, error id: {2}, error msg: {3}", data.m_strAccountID, data.m_strExchangeID, error.errorID(), error.errorMsg());
}
else
{
System.Console.WriteLine("[onReqPositionDetail] data is null. accountid: {0}, error id: {1}, error msg: {2}", accountID, error.errorID(), error.errorMsg());
}
}
public override void onReqPositionStatics(String accountID, int nRequestId, CPositionStatics data, bool isLast, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onReqPositionStatics] accountid: {0}, m_strExchangeID: {1}, error id: {2}, error msg: {3}", data.m_strAccountID, data.m_strExchangeID, error.errorID(), error.errorMsg());
}
else
{
System.Console.WriteLine("[onReqPositionStatics] data is null. accountid: {0}, error id: {1}, error msg: {2}", accountID, error.errorID(), error.errorMsg());
}
}
public override void onReqPriceData(int nRequestId, CPriceData data, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onReqPriceData] nRequestId: {0}, m_dLastPrice: {1}, m_dAveragePrice: {2}, error id: {3}, error msg: {4}", nRequestId, data.m_dLastPrice, data.m_dAveragePrice, error.errorID(), error.errorMsg());
}
else
{
System.Console.WriteLine("[onReqPriceData] data is null. nRequestId: {0}, error id: {1}, error msg: {2}", nRequestId, error.errorID(), error.errorMsg());
}
}
public override void onRtnOrderDetail(COrderDetail data)
{
if (data.m_nErrorID == 0)
{
System.Console.WriteLine("[onRtnOrderDetail] OrderId: {0}, 委托状态:{1}, instrumentId:{2}", data.m_nOrderID, data.m_nOrderStatus, data.m_strInstrumentID);
}
else
{
System.Console.WriteLine("[onRtnOrderDetai] Failure. {0} ErrorID: {1}, ErrorMsg:{2}", data.m_nOrderID, data.m_nErrorID, data.m_strErrorMsg);
}
}
public override void onRtnDealDetail(CDealDetail data)
{
System.Console.WriteLine("[onRtnDealDetail] orderId: {0}, orderSysId:{1}, m_nVolume:{2}, m_dTradeAmount:{3}", data.m_nOrderID, data.m_strOrderSysID, data.m_nVolume, data.m_dTradeAmount);
}
public override void onRtnOrderError(COrderError data)
{
System.Console.WriteLine("[onRtnOrderError] orderId:{0}", data.m_nOrderID);
}
public override void onRtnCancelError(CCancelError data)
{
System.Console.WriteLine("[onRtnCancelError] orderId:{0} ", data.m_nOrderID);
}
public override void onRtnLoginStatus(String accountID, EBROKER_LOGIN_STATUS status, String errorMsg)
{
String loginStatus = "";
switch (status)
{
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_INALID: loginStatus = "无效状态"; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_OK: loginStatus = "可用,初始化完成"; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_WAITING_LOGIN: loginStatus = "连接中"; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_LOGINING: loginStatus = "登录中"; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_FAIL: loginStatus = "失败"; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_INITING: loginStatus = "在初始化中 "; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_CORRECTING: loginStatus = "数据刷新校正中"; break;
case EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_CLOSED: loginStatus = "收盘后(休市中)"; break;
}
System.Console.WriteLine("[onRtnLoginStatus]{0} status:{1} ", accountID, loginStatus);
if (status == EBROKER_LOGIN_STATUS.BROKER_LOGIN_STATUS_OK && m_strAccountId == accountID)
{
System.Console.WriteLine("Main thread id is: {0}, start order thread", Thread.CurrentThread.ManagedThreadId);
Thread orderThread = new Thread(new ThreadStart(timeExpireSendOrder));
orderThread.Start();
//testOrdinaryOrder(m_strAccountId.StartsWith("3700"), m_strAccountId, m_nOrderNumPerSec);
}
}
public override void onRtnDeliveryStatus(String accountID, bool status, String errorMsg)
{
//System.Console.WriteLine("onRtnDeliveryStatus ID:" + accountID + (status? "OK" : " with Msg " + errorMsg));
}
public override void onRtnRCMsg(String accountID, String errorMsg)
{
//System.Console.WriteLine("onRtnRCMsg ID:" + accountID + " with Msg " + errorMsg);
}
public override void onRtnAccountDetail(String accountID, CAccountDetail accountDetail)
{
if (null != accountDetail)
{
System.Console.WriteLine("[onRtnAccountDetail] accountId: {0}, m_dBalance: {1}", accountID, accountDetail.m_dBalance);
}
else
{
System.Console.WriteLine("[onRtnAccountDetail] accountid: {0}, no content recv", accountID);
}
}
public override void onRtnNetValue(CNetValue data)
{
//System.Console.WriteLine("onRtnNetValue, productid: " + data.m_nProductId);
}
public void timeExpireSendOrder()
{
while (m_nOrderTimeSecs > 0)
{
Thread.Sleep(1000);
if (m_strAccountId.StartsWith("3700"))
{
testOrdinaryOrder(true, m_strAccountId, m_nOrderNumPerSec);
//testAlgorithmOrder(true, m_strAccountId, m_nOrderNumPerSec);
//testGroupOrder(m_strAccountId);
}
else
testOrdinaryOrder(false, m_strAccountId, m_nOrderNumPerSec);
System.Console.WriteLine("Current Thread id: {0}, orderSec remains: {1}", Thread.CurrentThread.ManagedThreadId, m_nOrderTimeSecs);
m_nOrderTimeSecs--;
}
}
void testOrdinaryOrder(bool isStock, String accountId, int times)
{
if (isStock)
{
for (int i = 0; i < times; ++i)
{
// 股票
COrdinaryOrder orderInfo = new COrdinaryOrder();
orderInfo.m_strAccountID = accountId;
orderInfo.m_dPrice = 11.93;
orderInfo.m_dSuperPrice = 0.5;
orderInfo.m_nVolume = 100;
orderInfo.m_strMarket = "SZ";
orderInfo.m_strInstrument = "000002";
orderInfo.m_ePriceType = EPriceType.PRTP_FIX;
orderInfo.m_eOperationType = EOperationType.OPT_BUY;
orderInfo.m_eHedgeFlag = EHedge_Flag_Type.HEDGE_FLAG_SPECULATION; // 不填这个字段,默认为“投机”
m_client.order(orderInfo, m_nRequestId++);
}
}
else
{
for (int i = 0; i < times; ++i)
{
// 期货
COrdinaryOrder orderInfo = new COrdinaryOrder();
orderInfo.m_strAccountID = accountId;
orderInfo.m_dSuperPrice = 100; // 百分比
orderInfo.m_nVolume = 1;
orderInfo.m_strInstrument = "CF509";
orderInfo.m_strMarket = "CZCE";
orderInfo.m_eOperationType = EOperationType.OPT_OPEN_LONG;
//orderInfo.m_dPrice = 12895;
orderInfo.m_ePriceType = EPriceType.PRTP_LATEST;
orderInfo.m_eHedgeFlag = EHedge_Flag_Type.HEDGE_FLAG_SPECULATION; // 不填这个字段,默认为“投机”
m_client.order(orderInfo, m_nRequestId++);
}
}
}
void testAlgorithmOrder(bool isStock, String accoundId, int times)
{
//算法单
if (isStock)
{
for (int i = 0; i < times; ++i)
{
CAlgorithmOrder orderInfo = new CAlgorithmOrder();
orderInfo.m_strAccountID = accoundId; // 股票 账号
orderInfo.m_strInstrument = "000002"; // 股票代码
orderInfo.m_strMarket = "SZ"; // 市场:股票有 SZ, SH
//orderInfo.m_dPrice = 13.10;
//// 单笔超价
//orderInfo.m_dSuperPrice = 100;
//// 波动区间,波动区间,基准价 必须在此区间内,否则无法报出单子
orderInfo.m_dPriceRangeMin = 12.20 - 0.50;
orderInfo.m_dPriceRangeMax = 12.20 + 0.8;
orderInfo.m_nVolume = 1000; // 委托量
// 单笔下单比率,委托总量*单笔下单比率 = 单笔下单量
// m_nVolume * m_dSingleVolumeRate = 单笔下单量
// 比如,下单总量1000 * 0.005 = 5 < 最小委托量100(限于股票),
// 1000拆分成10笔委托
orderInfo.m_dSingleVolumeRate = 0.005;
orderInfo.m_dPlaceOrderInterval = 30; // 下单间隔, 1秒(最小0.5s)
orderInfo.m_dWithdrawOrderInterval = 15; // 撤单间隔:15秒(最小0.5s)
// 单笔下单比率最小/大值 如果不填写,会按照每笔 100只来下委托
//orderInfo.m_nSingleNumMin = 100;
//// 单笔委托最大量
//// 如果 m_nVolume*m_dSingleVolumeRate > m_nMaxOrderCount,则以m_nMaxOrderCount为准
//orderInfo.m_nSingleNumMax = 1000;
//orderInfo.m_nMaxOrderCount = 100; // 最大下单次数, 与下单间隔对应
// 有效开始时间和有效结束时间不用填
orderInfo.m_eOperationType = EOperationType.OPT_BUY; // 股票 只有OPT_BUY、OPT_SELL
// 单笔基准:目标量、买1、买1+2、买1+2+3等
orderInfo.m_eSingleVolumeType = EVolumeType.VOLUME_FIX;
// 最新价、对手加、指定价、买1-5等
orderInfo.m_ePriceType = EPriceType.PRTP_LATEST;
// 套利标志, 支持 投机、套利、套保(不填则默认为“投机”)
orderInfo.m_eHedgeFlag = EHedge_Flag_Type.HEDGE_FLAG_SPECULATION;
//requestID,本地用于确定服务器返回的 OrderID
m_client.order(orderInfo, m_nRequestId++);
}
}
else
{
for (int i = 0; i < times; ++i)
{
CAlgorithmOrder orderInfo = new CAlgorithmOrder();
//strcpy(orderInfo.m_strAccountID, accoundId.c_str()); // 期货 账号
//orderInfo.m_strAccountID[accoundId.length()] = '\0';
orderInfo.m_strAccountID = accoundId;
orderInfo.m_strMarket = "CZCE"; // 市场:SZ, SH, CZCE等
orderInfo.m_strInstrument = "CF509"; // 期货代码
//orderInfo.m_dPrice = 68900.4; // 基准价(指定价报单时需要填)
//单笔超价:元,不是百分比
orderInfo.m_dSuperPrice = 500;
// 波动区间,波动区间,基准价在此范围之内
orderInfo.m_dPriceRangeMin = 13615 - 500;
orderInfo.m_dPriceRangeMax = 13615 + 500;
orderInfo.m_nVolume = 1; // 委托量
// 单笔下单比率,委托总量*单笔下单比率 = 单笔下单量
// m_nVolume * m_dSingleVolumeRate = 单笔下单量
orderInfo.m_dSingleVolumeRate = 0.005;
orderInfo.m_dPlaceOrderInterval = 1; // 下单间隔, 1秒(最小0.5s)
orderInfo.m_dWithdrawOrderInterval = 15; // 撤单间隔:15秒(最小0.5s)
// 单笔下单比率最小/大值 如果不填写,会按照每笔 100只来下委托
orderInfo.m_nSingleNumMin = 1;
// 单笔委托最大量
// 如果 m_nVolume*m_dSingleVolumeRate > m_nMaxOrderCount,则以m_nMaxOrderCount为准
orderInfo.m_nSingleNumMax = 100;
orderInfo.m_nMaxOrderCount = 1; // 最大下单次数, 与下单间隔对应
// 有效开始时间和有效结束时间不用填
orderInfo.m_eOperationType = EOperationType.OPT_OPEN_LONG; // 期货 有开多、平左多等10个选项
// 单笔基准:目标量、买1、买1+2、买1+2+3等
orderInfo.m_eSingleVolumeType = EVolumeType.VOLUME_FIX;
// 最新价、对手加、指定价、买1-5等
orderInfo.m_ePriceType = EPriceType.PRTP_LATEST;
// 套利标志, 支持 投机、套利、套保(不填则默认为“投机”)
orderInfo.m_eHedgeFlag = EHedge_Flag_Type.HEDGE_FLAG_SPECULATION;
//requestID,本地用于确定服务器返回的 OrderID
m_client.order(orderInfo, m_nRequestId++);
}
}
}
void testGroupOrder(String accoundId)
{
// 组合下单, 只支持股票
CGroupOrder orderInfo = new CGroupOrder();
// 价格范围(元,所有单子共用一个范围)
orderInfo.m_orderParam.m_dPriceRangeMin = 12.34;
orderInfo.m_orderParam.m_dPriceRangeMax = 100.3;
// 单笔超价(元)
orderInfo.m_orderParam.m_dSuperPrice = 0.10;
// 报价类型
orderInfo.m_orderParam.m_ePriceType = EPriceType.PRTP_LATEST;
// 下单类型
orderInfo.m_orderParam.m_eOperationType = EOperationType.OPT_BUY;
// 超价起始笔数
orderInfo.m_orderParam.m_nSuperPriceStart = 1;
// 下单间隔(秒)
orderInfo.m_orderParam.m_dPlaceOrderInterval = 30;
// 撤单间隔(秒)
orderInfo.m_orderParam.m_dWithdrawOrderInterval = 30;
// 单比下单比率(1 为一次全部下单)
orderInfo.m_orderParam.m_dSingleVolumeRate = 1;
// 单笔下单基准
orderInfo.m_orderParam.m_eSingleVolumeType = EVolumeType.VOLUME_FIX;
// 最大下单次数
orderInfo.m_orderParam.m_nMaxOrderCount = 100;
// 单笔下单量最大值,必须大于或等于 m_nVolume[i] * m_dSingleVolumeRate
// 否则,以单笔下单量最大值为准
orderInfo.m_orderParam.m_nSingleNumMax = 200;
// 单笔下单量最小值, 不能比100 再小了
orderInfo.m_orderParam.m_nLastVolumeMin = 100;
orderInfo.m_orderParam.m_strAccountID = accoundId;
orderInfo.m_nOrderNum = 2;
orderInfo.m_strInstrument[0] = "000002";
orderInfo.m_strInstrument[1] = "000004";
orderInfo.m_strMarket[0] = "SZ";
orderInfo.m_strMarket[1] = "SZ";
orderInfo.m_nVolume[0] = 1000;
orderInfo.m_nVolume[1] = 300;
m_client.order(orderInfo, m_nRequestId++);
}
public override void onOrder(int nRequestId, int orderID, XtError error)
{
if (error.isSuccess())
{
System.Console.WriteLine("[onOrder] success. orderId: {0}, requestID: {1}", orderID, nRequestId);
}
else
{
System.Console.WriteLine("[onOrder] failure. orderid: {0}, requestID: {1}, errormsg: {2}", orderID, nRequestId, error.errorMsg());
}
}
public override void onCancel(int nRequestId, XtError error)
{
System.Console.WriteLine("onCancel " + (error.isSuccess() ? " success" : (" ERR ID" + error.errorID() + " msg: " + error.errorMsg())));
}
}
}
|
using Bloodhound.Core.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace Bloodhound.Core.Tests
{
[TestClass]
public class OffenderGeoFenceIsInsideTests
{
[TestMethod]
public void InsideTests()
{
OffenderGeoFence fence = new OffenderGeoFence()
{
NorthEastLatitude = 35.843014M,
NorthEastLongitude = -83.340230M,
SouthWestLatitude = 35.575827M,
SouthWestLongitude = -83.815701M
};
Assert.IsTrue(fence.IsInside(35.702380M, -83.541691M));
Assert.IsTrue(fence.IsInside(fence.NorthEastLatitude, fence.NorthEastLongitude));
Assert.IsTrue(fence.IsInside(fence.SouthWestLatitude, fence.SouthWestLongitude));
Assert.IsFalse(fence.IsInside(36.496245M, -83.556681M));
Assert.IsFalse(fence.IsInside(34.613328M, -83.511595M));
Assert.IsFalse(fence.IsInside(35.719336M, -86.137600M));
Assert.IsFalse(fence.IsInside(35.724679M, -80.630775M));
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Docller.Core.Images
{
public abstract class ImgImageConverter : IImageConverter
{
public virtual void Convert(string inputFile, string outputPngfile)
{
File.Copy(inputFile,outputPngfile,true);
}
public abstract string Extension { get;}
}
public class JpegImageConverter : ImgImageConverter
{
public override string Extension
{
get { return ".jpeg"; }
}
}
public class BmpImageConverter : ImgImageConverter
{
public override string Extension
{
get { return ".bmp"; }
}
}
public class GifImageConverter : ImgImageConverter
{
public override string Extension
{
get { return ".gif"; }
}
}
public class PngImageConverter : ImgImageConverter
{
public override string Extension
{
get { return ".png"; }
}
}
public class JpgImageConverter : ImgImageConverter
{
public override string Extension
{
get { return ".jpg"; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MatrixExtension
{
public static class MatrixExtension
{
public static double[,] Multiply(this double[,] matrix1, double[,] matrix2)
{
if (matrix1.GetLength(1) != matrix2.GetLength(0))
{
throw new ArgumentException("Matrix sizes not correct.");
}
double[,] res = new double[matrix1.GetLength(0), matrix2.GetLength(1)];
for (int i = 0; i < matrix1.GetLength(0); i++)
{
for (int j = 0; j < matrix2.GetLength(1); j++)
{
for (int k = 0; k < matrix1.GetLength(1); k++)
{
res[i, j] += matrix1[i, k] * matrix2[k, j];
}
}
}
return res;
}
public static double[,] MultiplyMultithreading(this double[,] matrix1, double[,] matrix2, int N)
{
if (matrix1.GetLength(1) != matrix2.GetLength(0))
{
throw new ArgumentException("Matrix sizes not correct.");
}
double[,] res = new double[matrix1.GetLength(0), matrix2.GetLength(1)];
Thread[] threads = new Thread[N];
int step = (int)Math.Ceiling((double)matrix1.GetLength(0) / (double)N);
for (int i = 0; i < N; i++)
{
threads[i] = new Thread((object ind) => {
MultiplyPartial(matrix1, matrix2, res,
step * (int)ind,
step * ((int)ind + 1) > matrix1.GetLength(0) ? matrix1.GetLength(0) : step * ((int)ind + 1));
});
threads[i].Start(i);
}
for (int i = 0; i < N; i++)
{
threads[i].Join();
}
return res;
}
static void MultiplyPartial(double[,] matrix1, double[,] matrix2, double[,] res, int startI, int endI)
{
for (int i = startI; i < endI; i++)
{
for (int j = 0; j < matrix2.GetLength(1); j++)
{
for (int k = 0; k < matrix1.GetLength(1); k++)
{
res[i, j] += matrix1[i, k] * matrix2[k, j];
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MedicalEducation.Controls
{
public class CustomLabel: System.Windows.Forms.Label
{
private HeadingType _HeadingType;
public enum HeadingType
{
H1,
H2,
H3
};
public CustomLabel()
{
}
public HeadingType Heading
{
set
{
if (value == HeadingType.H1)
{
//FONT-WEIGHT: bold; FONT-SIZE: 13px; TEXT-ALIGN: center
float lpoints = 13 * 72 / 96;
this.Font = new System.Drawing.Font(this.Font.FontFamily, lpoints,System.Drawing.FontStyle.Bold);
this.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
}
else if (value == HeadingType.H2)
{
//FONT-WEIGHT: bold; FONT-SIZE: 11px
float lpoints = 11 * 72 / 96;
this.Font = new System.Drawing.Font(this.Font.FontFamily, lpoints,System.Drawing.FontStyle.Bold);
}
else if (value == HeadingType.H3)
{
//FONT-WEIGHT: bold; FONT-SIZE: 11px; MARGIN: 10px 0px 0px
float lpoints = 11 * 72 / 96;
this.Font = new System.Drawing.Font(this.Font.FontFamily, lpoints, System.Drawing.FontStyle.Bold);
this.Margin = new System.Windows.Forms.Padding(0, 10, 0, 0);
}
_HeadingType = value;
}
get
{
return _HeadingType;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using GeoAPI.Geometries;
using log4net;
using SharpMap.Converters.Geometries;
using SharpMap.Data.Providers;
using SharpMap.Layers;
using SharpMap.Rendering;
using SharpMap.Rendering.Thematics;
using SharpMap.Styles;
using SharpMap.UI.Editors;
using SharpMap.UI.Forms;
using SharpMap.UI.Helpers;
using GeoAPI.Extensions.Feature;
using System.ComponentModel;
using DelftTools.Utils;
using DelftTools.Utils.Collections;
namespace SharpMap.UI.Tools
{
public enum MultiSelectionMode
{
Rectangle = 0,
Lasso
}
/// <summary>
/// SelectTool enables users to select features in the map
/// The current implementation supports:
/// - single selection feature by click on feature
/// - multiple selection of feature by dragging a rectangle
/// - adding features to the selection (KeyExtendSelection; normally the SHIFT key)
/// - toggling selection of features (KeyToggleSelection; normally the CONTROL key)
/// if featues is not in selection it is added to selection
/// if feature is in selection it is removed from selection
/// - Selection is visible to the user via trackers. Features with an IPoint geometry have 1
/// tracker, based on ILineString and IPolygon have a tracker for each coordinate
/// - Trackers can have focus.
/// If a trackers has focus is visible to the user via another symbol (or same symbol in other color)
/// A tracker that has the focus is the tracker leading during special operation such as moving.
/// For single selection a feature with an IPoint geometry automatically get the focus to the
/// only tracker
/// - Multiple trackers with focus
/// - adding focus trackers (KeyExtendSelection; normally the SHIFT key)
/// - toggling focus trackers (KeyToggleSelection; normally the CONTROL key)
/// - Selection cycling, When multiple features overlap clicking on a selected feature will
/// result in the selection of the next feature. Compare behavior in Sobek Netter.
///
/// TODO
/// - functionality reasonably ok, but TOO complex : refactor using tests
/// - Selection cycling can be improved:
/// - for a ILineString the focus tracker is not set initially which can be set in the second
/// click. Thus a ILineString (and IPolygon) can eat a click
/// - if feature must be taken into account by selection cycling should be an option
/// (topology rule?)
/// </summary>
public class SelectTool : MapTool
{
private static readonly ILog log = LogManager.GetLogger(typeof(SelectTool));
public MultiSelectionMode MultiSelectionMode { get; set; }
// TODO: these feature editor-related fields are not at home in SelectTool.
public FeatureEditorCreationEventHandler FeatureEditorCreation;
public IList<IFeatureEditor> FeatureEditors { get; private set; }
private readonly Collection<ITrackerFeature> trackers = new Collection<ITrackerFeature>();
private ICoordinateConverter coordinateConverter;
/// <summary>
/// Current layer where features are being selected (branch, nodes, etc.)
/// </summary>
private VectorLayer TrackingLayer // will be TrackingLayer containing tracking geometries
{
get { return trackingLayer; }
}
public IList<int> SelectedTrackerIndices
{
get
{
List<int> indices = new List<int>();
return 1 == FeatureEditors.Count ? FeatureEditors[0].GetFocusedTrackerIndices() : indices;
}
}
public bool KeyToggleSelection
{
get { return ((Control.ModifierKeys & Keys.Control) == Keys.Control); }
}
public bool KeyExtendSelection
{
get { return ((Control.ModifierKeys & Keys.Shift) == Keys.Shift); }
}
public SelectTool()
{
orgClickTime = DateTime.Now;
FeatureEditors = new List<IFeatureEditor>();
Name = "Select";
trackingLayer.Name = "trackers";
FeatureCollection trackerProvider = new FeatureCollection { Features = trackers };
trackingLayer.DataSource = trackerProvider;
CustomTheme iTheme = new CustomTheme(GetTrackerStyle);
trackingLayer.Theme = iTheme;
}
private bool IsMultiSelect { get; set; }
public override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Render(e.Graphics, MapControl.Map);
}
public override void Render(Graphics graphics, Map map)
{
// Render the selectionLayer and trackingLayer
// Bypass ILayer.Render and call OnRender directly; this is more efficient
foreach (var tracker in trackers)
{
if (null != tracker.FeatureEditor.SourceFeature)
{
// todo optimize this; only necessary when map extent has changed.
tracker.FeatureEditor.UpdateTracker(tracker.FeatureEditor.SourceFeature.Geometry);
}
}
trackingLayer.OnRender(graphics, map);
}
public ITrackerFeature GetTrackerAtCoordinate(ICoordinate worldPos)
{
ITrackerFeature trackerFeature = null;
for (int i = 0; i < FeatureEditors.Count; i++)
{
trackerFeature = FeatureEditors[i].GetTrackerAtCoordinate(worldPos);
if (null != trackerFeature)
break;
}
return trackerFeature;
}
private ICoordinate orgMouseDownLocation;
private DateTime orgClickTime;
private bool clickOnExistingSelection;
private void SetClickOnExistingSelection(bool set, ICoordinate worldPosition)
{
clickOnExistingSelection = set;
if (clickOnExistingSelection)
{
orgMouseDownLocation = (ICoordinate)worldPosition.Clone();
}
else
{
orgMouseDownLocation = null;
}
}
private IFeatureEditor GetActiveMutator(IFeature feature)
{
for (int i = 0; i < FeatureEditors.Count; i++)
{
if (FeatureEditors[i].SourceFeature == feature)
return FeatureEditors[i];
}
return null;
}
public override void OnMouseDown(ICoordinate worldPosition, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
{
return;
}
var oldSelectedTrackerIndicesCount = SelectedTrackerIndices.Count;
var oldTrackerFeatureCount = trackers.Count;
IsBusy = true;
ILayer selectedLayer;
mouseDownLocation = worldPosition;
// Check first if an object is already selected and if the mousedown has occured at this object.
ITrackerFeature trackerFeature = GetTrackerAtCoordinate(worldPosition);
if (FeatureEditors.Count > 1)
{
// hack: if multiple selection toggle/select complete feature
trackerFeature = null;
}
SetClickOnExistingSelection(false, null);
if (null != trackerFeature)
{
if (1 == FeatureEditors.Count)
{
SetClickOnExistingSelection(true, worldPosition);
FocusTracker(trackerFeature);
MapControl.Refresh();
}
return;
}
// single selection. Find the nearest geometry and give
float limit = (float)MapHelper.ImageToWorld(Map, 4);
IFeature nearest = FindNearestFeature(worldPosition, limit, out selectedLayer, ol => ol.Visible);
if (null != nearest)
{
// Create or add a new FeatureEditor
if (FeatureEditors.Count > 0)
{
IFeatureEditor currentMutator = GetActiveMutator(nearest);
if (KeyExtendSelection)
{
if (null == currentMutator)
{
// not in selection; add
AddSelection(selectedLayer, nearest, -1, true);
} // else possibly set default focus tracker
}
else if (KeyToggleSelection)
{
if (null == currentMutator)
{
// not in selection; add
AddSelection(selectedLayer, nearest, -1, true);
}
else
{
// in selection; remove
RemoveSelection(nearest);
}
}
else
{
// no special key processing; handle as a single select.
Clear(false);
if (!StartSelection(selectedLayer, nearest, -1))
{
StartMultiSelect();
}
//AddSelection(selectedLayer, nearest, -1);
}
}
else
{
if (!StartSelection(selectedLayer, nearest, -1))
{
StartMultiSelect();
}
//AddSelection(selectedLayer, nearest, -1);
}
}
else
{
// We didn't find an object at the position of the mouse button -> start a multiple select
if (!KeyExtendSelection)
{
// we are not extending the current selection
Clear(false);
}
if (e.Button == MouseButtons.Left)
//if (IsActive)
{
StartMultiSelect();
}
}
if ((oldSelectedTrackerIndicesCount != SelectedTrackerIndices.Count
|| oldTrackerFeatureCount != trackers.Count) && trackingLayer.DataSource.Features.Count != 0)
{
MapControl.Refresh();
}
//NS, 2013-09-04
//Convert LineString to Curve: if numPoint = 2 then convert it...
//if ((null != nearest)&&(nearest.Geometry.NumPoints == 2))
//{
// // todo ?move to FeatureEditor and add support for polygon
// IFeatureEditor featureEditor = GetActiveMutator(nearest);
// if (featureEditor.SourceFeature.Geometry is ILineString)
// {
// featureEditor.EditableObject.BeginEdit(string.Format("Insert curvepoint into feature {0}",
// featureEditor.SourceFeature is DelftTools.Utils.INameable
// ? ((DelftTools.Utils.INameable)featureEditor.SourceFeature).Name
// : ""));
// //featureEditor.Stop(SnapResult);
// ConvertToCurve(featureEditor.SourceFeature, featureEditor.Layer);
// featureEditor.EditableObject.EndEdit();
// }
// featureEditor.Layer.RenderRequired = true;
// MapControl.Refresh();
// //return;
//}
}
/// <summary>
/// NS, 2013-09-04
/// add control point
/// </summary>
/// <param name="aFeature"></param>
//private void ConvertToCurve(IFeature aFeature, ILayer aLayer)
//{
// ICoordinate startPoint, endPoint, controlPoint1, controlPoint2;
// if ((aFeature != null) && (aFeature.Geometry is ILineString) && (aFeature.Geometry.NumPoints == 2))
// {
// GisSharpBlog.NetTopologySuite.Geometries.LineString line =
// aFeature.Geometry as GisSharpBlog.NetTopologySuite.Geometries.LineString;
// startPoint = GeometryFactory.CreateCoordinate(line.StartPoint.X, line.StartPoint.Y);
// endPoint = GeometryFactory.CreateCoordinate(line.EndPoint.X, line.EndPoint.Y);
// /*
// * control point didapat dengan cara (ref: FlexGraphics VCL):
// * controlPointA.x := startPoint.x + (endPoint.x - startPoint.x) div 3;
// * controlPointA.y := startPoint.y + (endPoint.y - startPoint.y) div 3;
// * controlPointB.x := endPoint.x - (endPoint.x - startPoint.x) div 3;
// * controlPointB.y := endPoint.y - (endPoint.y - startPoint.y) div 3;
// */
// double aX, aY, bX, bY;
// aX = startPoint.X + (endPoint.X - startPoint.X) / 3;
// aY = startPoint.Y + (endPoint.Y - startPoint.Y) / 3;
// bX = endPoint.X - (endPoint.X - startPoint.X) / 3;
// bY = endPoint.Y - (endPoint.Y - startPoint.Y) / 3;
// controlPoint1 = GeometryFactory.CreateCoordinate(aX, aY);
// controlPoint2 = GeometryFactory.CreateCoordinate(bX, bY);
// //Create new LineString as Curve
// List<ICoordinate> vertices = new List<ICoordinate>();
// vertices.Add(startPoint);
// vertices.Add(controlPoint1);
// vertices.Add(controlPoint2);
// vertices.Add(endPoint);
// ILineString newLineString = GeometryFactory.CreateLineString(vertices.ToArray());
// //SharpMap.UI.Tools.SelectTool selectTool = MapControl.SelectTool;
// //selectTool.FeatureEditors[0].SourceFeature.Geometry = newLineString;
// SharpMap.Layers.ILayer targetLayer = aLayer;
// //update geometry to curve...
// aFeature.Geometry = newLineString;
// Select(targetLayer, aFeature, 2);
// }
//}
private void StartMultiSelect()
{
IsMultiSelect = true;
selectPoints.Clear();
UpdateMultiSelection(mouseDownLocation);
StartDrawing();
}
private void StopMultiSelect()
{
IsMultiSelect = false;
StopDrawing();
}
/// <summary>
/// Returns styles used by tracker features.
/// </summary>
/// <param name="feature"></param>
/// <returns></returns>
private static VectorStyle GetTrackerStyle(IFeature feature)
{
var trackerFeature = (TrackerFeature)feature;
VectorStyle style;
// styles are stored in the cache for performance reasons
lock (stylesCache)
{
if (!stylesCache.ContainsKey(trackerFeature.Bitmap))
{
style = new VectorStyle { Symbol = trackerFeature.Bitmap };
stylesCache[trackerFeature.Bitmap] = style;
}
else
{
style = stylesCache[trackerFeature.Bitmap];
}
}
return style;
}
static IDictionary<Bitmap, VectorStyle> stylesCache = new Dictionary<Bitmap, VectorStyle>();
public void Clear()
{
Clear(true);
}
private void Clear(bool fireSelectionChangedEvent)
{
FeatureEditors.Clear();
if (trackingLayer.DataSource.GetFeatureCount() <= 0)
return;
trackers.Clear();
trackingLayer.RenderRequired = true;
UpdateMapControlSelection(fireSelectionChangedEvent);
}
private void SynchronizeTrackers()
{
trackers.Clear();
for (int i = 0; i < FeatureEditors.Count; i++)
{
foreach (ITrackerFeature trackerFeature in FeatureEditors[i].GetTrackers())
{
//NS, 2013-10-14, tambah kondisi jika feture tsb diedit baru render tracker pointnya
if (trackerFeature.FeatureEditor.SourceFeature.Attributes.Keys.Contains("Editing"))
{
if ((bool)trackerFeature.FeatureEditor.SourceFeature.Attributes["Editing"])
trackers.Add(trackerFeature);
}
}
}
trackingLayer.RenderRequired = true;
}
// TODO, HACK: what SelectTool has to do with FeatureEditor? Refactor it.
public IFeatureEditor GetFeatureEditor(ILayer layer, IFeature feature)
{
try
{
IFeatureEditor featureEditor = null;
if (FeatureEditorCreation != null)
{
// allow custom feature editor creation
featureEditor = FeatureEditorCreation(layer, feature,
(layer is VectorLayer) ? ((VectorLayer)layer).Style : null);
}
if (null == featureEditor)
{
// no custom feature editor; fall back to default editors.
featureEditor = FeatureEditorFactory.Create(coordinateConverter, layer, feature,
(layer is VectorLayer)
? ((VectorLayer)layer).Style
: null);
}
return featureEditor;
}
catch (Exception exception)
{
log.Error("Error creating feature editor: " + exception.Message);
return null;
}
}
private bool StartSelection(ILayer layer, IFeature feature, int trackerIndex)
{
IFeatureEditor featureEditor = GetFeatureEditor(layer, feature);
if (null == featureEditor)
return false;
if (featureEditor.AllowSingleClickAndMove())
{
// do not yet select, but allow MltiSelect
FeatureEditors.Add(featureEditor);
SynchronizeTrackers();
UpdateMapControlSelection();
return true;
}
return false;
}
public void AddSelection(IEnumerable<IFeature> features)
{
foreach (IFeature feature in features)
{
var layer = Map.GetLayerByFeature(feature);
AddSelection(layer, feature, 0, false);
}
UpdateMapControlSelection();
}
public void AddSelection(ILayer layer, IFeature feature)
{
AddSelection(layer, feature, 0, true);
}
public void AddSelection(ILayer layer, IFeature feature, int trackerIndex, bool synchronizeUI)
{
if (!layer.Visible)
{
return;
}
IFeatureEditor featureEditor = GetFeatureEditor(layer, feature);
if (null == featureEditor)
return;
FeatureEditors.Add(featureEditor);
if (synchronizeUI)
{
UpdateMapControlSelection();
}
}
public IEnumerable<IFeature> Selection
{
get
{
foreach (IFeatureEditor featureEditor in FeatureEditors)
{
yield return featureEditor.SourceFeature;
}
}
}
//public void UpdateSelection(IGeometry geometry) // HACK: select tool must select features, not edit them
//{
// FeatureEditors[0].SourceFeature.Geometry = geometry;
//}
private void RemoveSelection(IFeature feature)
{
for (int i = 0; i < FeatureEditors.Count; i++)
{
if (FeatureEditors[i].SourceFeature == feature)
{
FeatureEditors.RemoveAt(i);
break;
}
}
UpdateMapControlSelection();
}
/// <summary>
/// Sets the selected object in the selectTool. SetSelection supports also the toggling/extending the
/// selected trackers.
/// </summary>
/// <param name="feature"></param>
/// <param name="featureLayer"></param>
/// <param name="trackerIndex"></param>
/// <returns>A clone of the original object.</returns>
/// special cases
/// feature is ILineString or IPolygon and trackerIndex != 1 : user clicked an already selected
/// features -> only selected tracker changes.
private void SetSelection(IFeature feature, ILayer featureLayer, int trackerIndex)
{
if (null != feature)
{
// store selected trackers
IList<int> featureTrackers = new List<int>();
for (int i = 0; i < TrackingLayer.DataSource.Features.Count; i++)
{
TrackerFeature trackerFeature = (TrackerFeature)TrackingLayer.DataSource.Features[i];
if (trackerFeature == feature)
{
featureTrackers.Add(i);
}
}
// store selected objects
AddSelection(featureLayer, feature, trackerIndex, true);
}
}
private void FocusTracker(ITrackerFeature trackFeature)
{
if (null == trackFeature)
return;
if (!((KeyToggleSelection) || (KeyExtendSelection)))
{
for (int i = 0; i < FeatureEditors.Count; i++)
{
foreach (ITrackerFeature tf in FeatureEditors[i].GetTrackers())
{
FeatureEditors[i].Select(tf, false);
}
}
}
for (int i = 0; i < FeatureEditors.Count; i++)
{
foreach (TrackerFeature tf in FeatureEditors[i].GetTrackers())
{
if (tf == trackFeature)
{
if (KeyToggleSelection)
{
FeatureEditors[i].Select(trackFeature, !trackFeature.Selected);
}
else
{
FeatureEditors[i].Select(trackFeature, true);
}
}
}
}
}
private List<PointF> selectPoints = new List<PointF>();
//private bool lassoSelect = false;
private void UpdateMultiSelection(ICoordinate worldPosition)
{
if (MultiSelectionMode == MultiSelectionMode.Lasso)
{
selectPoints.Add(Map.WorldToImage(worldPosition));
}
else
{
WORLDPOSITION = worldPosition;
}
}
private IPolygon CreatePolygon(double left, double top, double right, double bottom)
{
var vertices = new List<ICoordinate>
{
GeometryFactory.CreateCoordinate(left, bottom),
GeometryFactory.CreateCoordinate(right, bottom),
GeometryFactory.CreateCoordinate(right, top),
GeometryFactory.CreateCoordinate(left, top)
};
vertices.Add((ICoordinate)vertices[0].Clone());
ILinearRing newLinearRing = GeometryFactory.CreateLinearRing(vertices.ToArray());
return GeometryFactory.CreatePolygon(newLinearRing, null);
}
private IPolygon CreateSelectionPolygon(ICoordinate worldPosition)
{
if (MultiSelectionMode == MultiSelectionMode.Rectangle)
{
if (0 == Math.Abs(mouseDownLocation.X - worldPosition.X))
{
return null;
}
if (0 == Math.Abs(mouseDownLocation.Y - worldPosition.Y))
{
return null;
}
return CreatePolygon(Math.Min(mouseDownLocation.X, worldPosition.X),
Math.Max(mouseDownLocation.Y, worldPosition.Y),
Math.Max(mouseDownLocation.X, worldPosition.X),
Math.Min(mouseDownLocation.Y, worldPosition.Y));
}
var vertices = new List<ICoordinate>();
foreach (var point in selectPoints)
{
vertices.Add(Map.ImageToWorld(point));
}
if (vertices.Count == 1)
{
// too few points to create a polygon
return null;
}
vertices.Add((ICoordinate)worldPosition.Clone());
vertices.Add((ICoordinate)vertices[0].Clone());
ILinearRing newLinearRing = GeometryFactory.CreateLinearRing(vertices.ToArray());
return GeometryFactory.CreatePolygon(newLinearRing, null);
}
private ICoordinate mouseDownLocation; // TODO: remove me
private ICoordinate WORLDPOSITION;
public override void OnDraw(Graphics graphics)
{
if (MultiSelectionMode == MultiSelectionMode.Lasso)
{
GraphicsHelper.DrawSelectionLasso(graphics, KeyExtendSelection ? Color.Magenta : Color.DeepSkyBlue, selectPoints.ToArray());
}
else
{
ICoordinate coordinate1 = GeometryFactory.CreateCoordinate(mouseDownLocation.X, mouseDownLocation.Y);
ICoordinate coordinate2 = GeometryFactory.CreateCoordinate(WORLDPOSITION.X, WORLDPOSITION.Y);
PointF point1 = Map.WorldToImage(coordinate1);
PointF point2 = Map.WorldToImage(coordinate2);
GraphicsHelper.DrawSelectionRectangle(graphics, KeyExtendSelection ? Color.Magenta : Color.DeepSkyBlue, point1, point2);
}
}
public override void OnMouseMove(ICoordinate worldPosition, MouseEventArgs e)
{
if (IsMultiSelect)
{
//WORLDPOSITION = worldPosition;
UpdateMultiSelection(worldPosition);
DoDrawing(false);
return;
}
Cursor cursor = null;
for (int i = 0; i < FeatureEditors.Count; i++)
{
ITrackerFeature trackerFeature = FeatureEditors[i].GetTrackerAtCoordinate(worldPosition);
if (null != trackerFeature)
{
cursor = FeatureEditors[i].GetCursor(trackerFeature);
}
}
if (null == cursor)
{
cursor = Cursors.Default;
}
MapControl.Cursor = cursor;
}
private void UpdateMapControlSelection()
{
UpdateMapControlSelection(true);
}
private void UpdateMapControlSelection(bool fireSelectionChangedEvent)
{
SynchronizeTrackers();
IList<IFeature> selectedFeatures = new List<IFeature>();
for (int i = 0; i < FeatureEditors.Count; i++)
{
selectedFeatures.Add(FeatureEditors[i].SourceFeature);
}
MapControl.SelectedFeatures = selectedFeatures;
if (fireSelectionChangedEvent && SelectionChanged != null)
{
SelectionChanged(this, null);
}
}
public override void OnMouseDoubleClick(object sender, MouseEventArgs e)
{
orgMouseDownLocation = null;
}
public override void OnMouseUp(ICoordinate worldPosition, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
if (IsMultiSelect)
{
HandleMultiSelectMouseUp(worldPosition);
}
else
{
HandleMouseUp(worldPosition, e);
}
IsBusy = false;
orgClickTime = DateTime.Now;
}
private void HandleMouseUp(ICoordinate worldPosition, MouseEventArgs e)
{
if ((null != orgMouseDownLocation) && (orgMouseDownLocation.X == worldPosition.X) &&
(orgMouseDownLocation.Y == worldPosition.Y) && (e.Button == MouseButtons.Left))
{
// check if mouse was pressed at a selected object without moving the mouse. The default behaviour
// should be to select 'the next' object
TimeSpan timeSpan = DateTime.Now - orgClickTime;
int dc = SystemInformation.DoubleClickTime;
if (dc < timeSpan.TotalMilliseconds)
{
if (1 == FeatureEditors.Count)
{
// check if selection exists; could be toggled
Layer outLayer;
IFeature nextFeature = GetNextFeatureAtPosition(worldPosition,
// set limit from 4 to 10: TOOLS-1499
(float)MapHelper.ImageToWorld(Map, 10),
out outLayer,
FeatureEditors[0].SourceFeature,
ol => ol.Visible);
if (null != nextFeature)
{
Clear(false);
SetSelection(nextFeature, outLayer, 0); //-1 for ILineString
//MapControl.Refresh();
}
}
}
}
UpdateMapControlSelection(true);
}
/// TODO: note if no features are selected the selection rectangle maintains visible after mouse up
/// ISSUE 2373
private void HandleMultiSelectMouseUp(ICoordinate worldPosition)
{
StopMultiSelect();
List<IFeature> selectedFeatures = null;
if (!KeyExtendSelection)
{
selectedFeatures = new List<IFeature>(FeatureEditors.Select(fe => fe.SourceFeature).ToArray());
Clear(false);
}
IPolygon selectionPolygon = CreateSelectionPolygon(worldPosition);
if (null != selectionPolygon)
{
foreach (ILayer layer in Map.GetAllLayers(false))
{
//make sure parent layer is selectable or null
var parentLayer = Map.GetGroupLayerContainingLayer(layer);
if ( (parentLayer == null || parentLayer.IsSelectable) && (layer.IsSelectable) && (layer is VectorLayer))
{
// do not use the maptool provider but the datasource of each layer.
var vectorLayer = (VectorLayer)layer;
IList multiFeatures = vectorLayer.DataSource.GetFeatures(selectionPolygon);
for (int i = 0; i < multiFeatures.Count; i++)
{
var feature = (IFeature)multiFeatures[i];
if ((null != selectedFeatures) && (selectedFeatures.Contains(feature)))
{
continue;
}
AddSelection(vectorLayer, feature, -1, false);
}
}
}
}
else
{
// if mouse hasn't moved handle as single select. A normal multi select uses the envelope
// of the geometry and this has as result that unwanted features will be selected.
ILayer selectedLayer;
float limit = (float)MapHelper.ImageToWorld(Map, 4);
IFeature nearest = FindNearestFeature(worldPosition, limit, out selectedLayer, ol => ol.Visible);
if (null != nearest) //&& (selectedLayer.IsVisible))
AddSelection(selectedLayer, nearest, -1, false);
}
selectPoints.Clear();
// synchronize with map selection, possible check if selection is already set; do not remove
UpdateMapControlSelection(true);
}
readonly VectorLayer trackingLayer = new VectorLayer(String.Empty);
public override IMapControl MapControl
{
get { return base.MapControl; }
set
{
base.MapControl = value;
trackingLayer.Map = MapControl.Map;
coordinateConverter = new CoordinateConverter(MapControl);
}
}
/// <summary>
/// Selects the given features on the map. Will search all layers for the features.
/// </summary>
/// <param name="featuresToSelect">The feature to select on the map.</param>
public bool Select(IEnumerable<IFeature> featuresToSelect)
{
if (featuresToSelect == null)
{
Clear(true);
return false;
}
Clear(false);
foreach (var feature in featuresToSelect)
{
var foundLayer = Map.GetLayerByFeature(feature);
if (foundLayer != null && foundLayer is VectorLayer)
{
AddSelection(foundLayer, feature, -1, feature == featuresToSelect.Last());
}
}
return true;
}
/// <summary>
/// Selects the given feature on the map. Will search all layers for the feature.
/// </summary>
/// <param name="featureToSelect">The feature to select on the map.</param>
public bool Select(IFeature featureToSelect)
{
if (null == featureToSelect)
{
Clear(true);
return false;
}
// Find the layer that this feature is on
ILayer foundLayer = MapControl.Map.GetLayerByFeature(featureToSelect);
if (foundLayer != null && foundLayer is VectorLayer)
{
// Select the feature
Select(foundLayer, featureToSelect, -1);
return true;
}
return false;
}
public void Select(ILayer vectorLayer, IFeature feature, int trackerIndex)
{
if (IsBusy)
{
return;
}
Clear(false);
SetSelection(feature, vectorLayer, trackerIndex);
UpdateMapControlSelection(true);
}
/// <summary>
/// Handles changes to the map (or bubbled up from ITheme, ILayer) properties.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public override void OnMapPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (sender is ILayer)
{
if (e.PropertyName == "Enabled")
{
// If a layer is enabled of disables and features of the layer are selected
// the selection is cleared. Another solution is to remove only features of layer
// from the selection, but this simple and effective.
ILayer layer = (ILayer)sender;
if (layer is GroupLayer)
{
GroupLayer layerGroup = (GroupLayer)layer;
foreach (ILayer layerGroupLayer in layerGroup.Layers)
{
HandleLayerStatusChanged(layerGroupLayer);
}
}
else
{
HandleLayerStatusChanged(layer);
}
}
}
}
private void HandleLayerStatusChanged(ILayer layer)
{
foreach (ITrackerFeature trackerFeature in trackers)
{
if (layer != trackerFeature.FeatureEditor.Layer)
continue;
Clear();
return;
}
}
public override void OnMapCollectionChanged(object sender, NotifyCollectionChangingEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangeAction.Remove:
{
if (sender is Map)
{
ILayer layer = (ILayer)e.Item;
if (layer is GroupLayer)
{
GroupLayer layerGroup = (GroupLayer)layer;
foreach (ILayer layerGroupLayer in layerGroup.Layers)
{
HandleLayerStatusChanged(layerGroupLayer);
}
}
else
{
HandleLayerStatusChanged(layer);
}
}
break;
}
case NotifyCollectionChangeAction.Replace:
throw new NotImplementedException();
}
}
/// <summary>
/// todo add cancel method to IMapTool
/// todo mousedown clears selection -> complex selection -> start multi select -> cancel -> original selection lost
/// </summary>
public override void Cancel()
{
if (IsBusy)
{
if (IsMultiSelect)
{
StopMultiSelect();
}
IsBusy = false;
}
Clear(true);
}
public event EventHandler SelectionChanged;
public override bool IsActive
{
get
{
return base.IsActive;
}
set
{
base.IsActive = value;
if (false == IsActive)
{
MultiSelectionMode = MultiSelectionMode.Rectangle;
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RisingText : MonoBehaviour {
// Local Variables
public bool hasFadeEffect;
public bool autoDestroy;
public float fadeSpeed = 0.5f;
public float textScrollSpeed = 20f;
public float distanceToRise = 50f;
private RectTransform rt;
private float newY;
private float opacityLevel = 1f;
private float destinationY;
private Text _text;
// Use this for initialization
void Awake () {
_text = this.GetComponent<Text>();
rt = _text.GetComponent<RectTransform>();
newY = rt.anchoredPosition.y;
destinationY = newY + distanceToRise;
}
// Update is called once per frame
void Update () {
rt.anchoredPosition = new Vector3(rt.anchoredPosition.x, newY);
newY += textScrollSpeed * Time.deltaTime;
if (hasFadeEffect)
{
opacityLevel -= Time.deltaTime * fadeSpeed;
_text.color = new Color(_text.color.r,
_text.color.g,
_text.color.b,
opacityLevel);
}
if (autoDestroy && newY >= destinationY)
{
Destroy(this.gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gMediaTools.Models.Muxer
{
public class MkvMergeMuxer : IMuxer
{
public string MuxerFileName { get; }
public string[] SupportedExtensions { get; } = new string[] { "mkv" };
public MkvMergeMuxer(string muxerFileName)
{
MuxerFileName = muxerFileName ?? throw new ArgumentNullException(nameof(muxerFileName));
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Game.UI
{
[RequireComponent(typeof(RectTransform))]
/// <summary>
/// 用于增强RectTransform管理子UI的行为:将这个脚本添加到对应的UI上,并设置《string,transform》,则RectTransform将可以获得对应string下的transform
/// </summary>
public class UIRectTransExtend : MonoBehaviour
{
[Tooltip("link to child with id")]
/// <summary>
/// 用于管理子物体的Dict
/// </summary>
[SerializeField]Dictionary<string, RectTransform> m_uiChildren = new Dictionary<string, RectTransform>();
/// <summary>
/// 获得用于管理子物体的Dict:只读
/// </summary>
public Dictionary<string, RectTransform> uiChildren { get { return m_uiChildren; } }
//为RectTransform增加一个扩展函数
/// <summary>
/// 根据id获得对应的rectTransform
/// </summary>
public RectTransform GetChildById(string childId)
{
RectTransform childGot = null;
//--尝试获取child
uiChildren.TryGetValue(childId, out childGot);
return childGot;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiEndpoints.TransferModels
{
public class DispensationsansoegningSpildevandTrappeskaktLyskasserGodkendteGetTM
{
public int Id { get; set; }
public string ExternalId { get; set; }
public DateTime AddedTimestamp { get; set; }
public Guid? MinEjendomSagId { get; set; }
public string EjerNavn { get; set; }
public string EjerVejnavn { get; set; }
public string EjerHusnummer { get; set; }
public string EjerPostnummer { get; set; }
public string EjerBy { get; set; }
public string EjendomVejnavn { get; set; }
public string EjendomHusnummer { get; set; }
public string EjendomPostnummer { get; set; }
public string EjendomBy { get; set; }
public string SagsbehandlerNavn { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreScript : MonoBehaviour
{
public Text playerScore;
public Player player;
public void Update()
{
playerScore.text = "Score: " + player.GetComponent<Player>().Points.ToString();
}
}
|
using ISE.Framework.Common.CommonBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.Common.DTO
{
public partial class SecuritySessionDto:BaseDto
{
public SecuritySessionDto()
{
this.PrimaryKeyName = "RowId";
}
public ApplicationDomainDto ApplicationDomainDto { get; set; }
public AccountDto AccountDto { get; set; }
}
}
|
namespace Com.Colin.Demo.OOP
{
partial class Animal
{
public string run()
{
return "Runing!";
}
}
}
|
//using System;
//using Microsoft.EntityFrameworkCore;
//using Microsoft.EntityFrameworkCore.Metadata;
//using Microsoft.Extensions.Configuration;
//namespace GoldenBoot.Api
//{
// public partial class GoldenBootContext : DbContext
// {
// public GoldenBootContext(DbContextOptions<GoldenBootContext> options) : base(options)
// {
// }
// protected override void OnModelCreating(ModelBuilder modelBuilder)
// {
// modelBuilder.Entity<Competition>(entity =>
// {
// entity.Property(e => e.Id).ValueGeneratedOnAdd();
// entity.Property(e => e.Code)
// .IsRequired()
// .HasMaxLength(50);
// entity.Property(e => e.Name)
// .IsRequired()
// .HasMaxLength(50);
// entity.HasOne(d => d.IdNavigation)
// .WithOne(p => p.InverseIdNavigation)
// .HasForeignKey<Competition>(d => d.Id)
// .OnDelete(DeleteBehavior.Restrict)
// .HasConstraintName("FK_Competition_Competition");
// });
// modelBuilder.Entity<Player>(entity =>
// {
// entity.Property(e => e.Club)
// .IsRequired()
// .HasMaxLength(50);
// entity.Property(e => e.Country)
// .IsRequired()
// .HasMaxLength(50);
// entity.Property(e => e.Name)
// .IsRequired()
// .HasMaxLength(50);
// entity.HasOne(d => d.Competition)
// .WithMany(p => p.Players)
// .HasForeignKey(d => d.CompetitionId)
// .OnDelete(DeleteBehavior.Restrict)
// .HasConstraintName("FK_Player_Competition");
// });
// }
// public virtual DbSet<Competition> Competition { get; set; }
// public virtual DbSet<Player> Player { get; set; }
// }
//}
|
using EddiCore;
using EddiDataDefinitions;
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
namespace EddiCrimeMonitor
{
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class ConfigurationWindow : UserControl
{
private CrimeMonitor crimeMonitor()
{
return (CrimeMonitor)EDDI.Instance.ObtainMonitor("Crime monitor");
}
public ConfigurationWindow()
{
InitializeComponent();
criminalRecord.ItemsSource = crimeMonitor()?.criminalrecord;
}
private void addRecord(object sender, RoutedEventArgs e)
{
FactionRecord record = new FactionRecord(Properties.CrimeMonitor.blank_faction);
lock (CrimeMonitor.recordLock)
{
crimeMonitor()?.criminalrecord.Add(record);
}
crimeMonitor()?.writeRecord();
}
private void removeRecord(object sender, RoutedEventArgs e)
{
FactionRecord record = (FactionRecord)((Button)e.Source).DataContext;
crimeMonitor()?._RemoveRecord(record);
crimeMonitor()?.writeRecord();
}
private void updateRecord(object sender, RoutedEventArgs e)
{
FactionRecord record = (FactionRecord)((Button)e.Source).DataContext;
if (record.faction != Properties.CrimeMonitor.blank_faction)
{
Button updateButton = (Button)sender;
updateButton.Foreground = Brushes.Red;
updateButton.FontWeight = FontWeights.Bold;
Thread factionStationThread = new Thread(() =>
{
Superpower Allegiance = Superpower.FromNameOrEdName(record.faction);
if (Allegiance == null)
{
crimeMonitor()?.GetFactionData(record, record.system);
}
else
{
record.Allegiance = Allegiance;
}
Dispatcher?.Invoke(() =>
{
updateButton.Foreground = Brushes.Black;
updateButton.FontWeight = FontWeights.Regular;
});
crimeMonitor()?.writeRecord();
})
{
IsBackground = true
};
factionStationThread.Start();
}
}
private void criminalRecordUpdated(object sender, DataTransferEventArgs e)
{
if (e.Source is DataGrid dataGrid && dataGrid.IsLoaded)
{
FactionRecord record = (FactionRecord)((DataGrid)e.Source).CurrentItem;
if (record != null)
{
int column = ((DataGrid)e.Source).CurrentColumn.DisplayIndex;
switch (column)
{
case 3: // Claims column
{
// All claims, including discrepancy report
long claims = record.factionReports
.Where(r => r.crimeDef == Crime.None || r.crimeDef == Crime.Claim)
.Sum(r => r.amount);
if (record.claims != claims)
{
// Create/modify 'discrepancy' report if total claims does not equal sum of claim reports
long amount = record.claims - claims;
var report = record.factionReports
.FirstOrDefault(r => r.crimeDef == Crime.Claim);
if (report == null)
{
report = new FactionReport(DateTime.UtcNow, false, Crime.Claim, null, 0);
record.factionReports.Add(report);
}
report.amount += amount;
if (report.amount == 0) { record.factionReports.Remove(report); }
}
}
break;
case 4: // Fines column
{
// All fines, including discrepancy report
long fines = record.factionReports
.Where(r => !r.bounty && r.crimeDef != Crime.None)
.Sum(r => r.amount);
if (record.fines != fines)
{
// Create/modify 'discrepancy' report if total fines does not equal sum of fine reports
long amount = record.fines - fines;
var report = record.factionReports.FirstOrDefault(r => r.crimeDef == Crime.Fine);
if (report == null)
{
report = new FactionReport(DateTime.UtcNow, false, Crime.Fine, null, 0);
record.factionReports.Add(report);
}
report.amount += amount;
if (report.amount == 0) { record.factionReports.Remove(report); }
}
}
break;
case 5: // Bounties column
{
// All bounties, including discrepancy report
long bounties = record.factionReports
.Where(r => r.bounty && r.crimeDef != Crime.None)
.Sum(r => r.amount);
if (record.bounties != bounties)
{
// Create/modify 'discrepancy' report if total bounties does not equal sum of bounty reports
long amount = record.bounties - bounties;
var report = record.factionReports
.FirstOrDefault(r => r.crimeDef == Crime.Bounty);
if (report == null)
{
report = new FactionReport(DateTime.UtcNow, true, Crime.Bounty, null, 0);
record.factionReports.Add(report);
}
report.amount += amount;
if (report.amount == 0) { record.factionReports.Remove(report); }
}
}
break;
}
}
}
// Update the crime monitor's information
crimeMonitor()?.writeRecord();
}
private void EnsureValidInteger(object sender, TextCompositionEventArgs e)
{
// Match valid characters
Regex regex = new Regex(@"[0-9]");
// Swallow the character doesn't match the regex
e.Handled = !regex.IsMatch(e.Text);
}
}
}
|
using ISE.Framework.Common.CommonBase;
using ISE.SM.Common.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISE.SM.Common.DTOContainer
{
public class ResourceTypeDtoContainer : DtoContainer
{
public ResourceTypeDtoContainer()
{
ResourceTypeDtoList = new List<ResourceTypeDto>();
}
public List<ResourceTypeDto> ResourceTypeDtoList { get; set; }
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;
namespace GlobalGoalGame.Models.Button
{
class SpriteButton
{
public String Name { get; set; }
public Texture2D Texture { get; set; }
public Vector2 BadLocation { get; set; }
public Vector2 Location { get; set; }
public float Cost { get; set; }
public int ID { get; set; }
public static List<SpriteButton> Buttons = new List<SpriteButton>();
public SpriteButton(String name, Texture2D texture, Vector2 location, int width, int height, float cost)
{
Name = name;
Texture = texture;
BadLocation = location;
Location = new Vector2(BadLocation.X + (width/2), BadLocation.Y + (height/2));
Random rand = new Random();
ID = rand.Next(0, 60000) + rand.Next(5, 53223);
Cost = cost;
}
public virtual void Update(GameTime gameTime, MouseState mState)
{
}
public virtual void DoStuff(GameTime gameTime, MouseState mState)
{
Console.Write(gameTime.TotalGameTime.ToString() + ": " + Name + " Pressed");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using Microsoft.Shell;
namespace WhatNEXTUI
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application, ISingleInstanceApp
{
private const string Unique = "WhatNEXT_YOUR_GOAL_IS";
[STAThread]
public static void Main()
{
//if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
//{
WhatNEXTUI.App app = new WhatNEXTUI.App();
app.InitializeComponent();
app.Run();
// Allow single instance code to perform cleanup operations
//SingleInstance<App>.Cleanup();
//}
}
public bool SignalExternalCommandLineArgs(IList<string> args)
{
// handle command line arguments of second instance
// ...
return true;
}
}
}
|
namespace PatternsCore.FrameWorkStyleFactory.AbstractFactory
{
public class NyVeggiePizza2 : Pizza2
{
private IPizzaIngredientsFactory _ingredientsFactory;
public NyVeggiePizza2(IPizzaIngredientsFactory ingredientsFactory)
{
_name = "Ny veggie pizza";
_ingredientsFactory = ingredientsFactory;
_dough = _ingredientsFactory.CreateDough();
_souce = ingredientsFactory.CreateSauce();
_toppings = ingredientsFactory.CreateVeggies();
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class AdministradorUI : MonoBehaviour {
public void CambiarEscena(string escena)
{
SceneManager.LoadScene(escena);
}
}
|
using Microsoft.AspNetCore.Mvc;
using TaxaJurosWebAPI.Models;
namespace TaxaJurosWebAPI.Controllers
{
[Route("[controller]")]
[ApiController]
public class taxajurosController : ControllerBase
{
[HttpGet("/taxaJuros")]
public Taxa Get()
{
Taxa tx = new Taxa();
tx.GetTaxa();
return tx;
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SpreedlyWebApp.Spreedly.SpreedlyModels
{
public class SpreedlyMetadata
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("another_key")]
public long AnotherKey { get; set; }
[JsonProperty("final_key")]
public bool FinalKey { get; set; }
}
}
|
//----------------------------------------------------------------------
// csMenu_Scene.cs
// Handles the main (and only) menu for the game.
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
//----------------------------------------------------------------------
// csMenu_Scene class for Unity3d MonoBehaviour
public class csMenu_Scene : MonoBehaviour
{
// Static globals available to other scripts
public static bool gameOver = false;
public static bool returnMenu = false;
public static bool mainMenu = true;
public static int currentCubes = 0;
public static int score;
public static int hiScore;
public GameObject scoreObj;
public Font menuFont;
GameObject loadingText;
// GUISkin CustomGUISkin;
// Private vars
private float fontSizeRatio = 0.8f;
private int fontSize;
private AudioSource[] myAudio;
private float _oldWidth;
private float _oldHeight;
private float ratio = 15;
//----------------------------------------------------------------------
// Start function
void Start()
{
SetupAudio();
currentCubes = 0;
}
//----------------------------------------------------------------------
// Pull in Audio sources
void SetupAudio()
{
int i;
AudioSource[] aSources = GetComponents<AudioSource>();
myAudio = new AudioSource[10];
for (i=0; i < aSources.Length; i++)
{
myAudio[i] = aSources[i];
}
}
// Update funtion
void Update()
{
if (! Application.isLoadingLevel)
{
// GameObject loadingMsg;
float mn;
if (_oldWidth != Screen.width || _oldHeight != Screen.height)
{
_oldWidth = Screen.width;
_oldHeight = Screen.height;
mn = Screen.width < Screen.height ? Screen.width : Screen.height;
fontSize = (int)(mn / ratio * fontSizeRatio);
}
if (Random.Range(1, (int)(25.0 + 1.0f / Time.deltaTime)) == 1)
{
myAudio[Random.Range(1,7)].Play();
}
}
}
void OnGUI ()
{
int screenHeight = Screen.height;
// int screenWidth = Screen.width;
int r = screenHeight / 10;
// GameObject loadingMsg;
// GUI.skin = CustomGUISkin;
GUI.skin.label.font = GUI.skin.button.font = GUI.skin.box.font = menuFont;
GUI.skin.label.fontSize = GUI.skin.box.fontSize = GUI.skin.button.fontSize = fontSize;
if (mainMenu)
{
// Make a group on the center of the screen
GUI.BeginGroup( new Rect(r*2, r*3, Screen.width-r*2, r*7));
if (score > hiScore)
{
hiScore = score;
}
GUI.Box( new Rect(0.0f, 0.0f, Screen.width-r*4.0f, r*6.5f), "");
if (gameOver)
{
// Make a box on GUI
GUI.Label( new Rect(r*1.5f, 0.0f, Screen.width-r*6.5f, r*2.0f), score + " points, most is " + hiScore);
}
// Start the scene
if (GUI.Button( new Rect(10, r*2.0f, Screen.width-r*10.0f, r), "start"))
{
myAudio[3].Play();
gameOver = false;
returnMenu = false;
score = 0;
currentCubes = 0;
//Application.LoadLevel("main_scene");
SceneManager.LoadScene("main_scene");
}
if (GUI.Button( new Rect(10.0f, r*3.0f, Screen.width-r*10.0f, r), "Rules&Rate"))
{
myAudio[5].Play();
Application.OpenURL("market://details?id=com.AwakeLand.fallleaftapgame");
}
if (GUI.Button( new Rect(10.0f, r*4.0f, Screen.width-r*10.0f, r), "end..."))
{
myAudio[3].Play();
Application.Quit();
}
// Row 2 - Social Links
if (GUI.Button( new Rect(Screen.width-r*9.0f, r*3.0f, r*4.8f, r), "@fb share"))
{
myAudio[2].Play();
Application.OpenURL("https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fplay.google.com%2Fstore%2Fapps%2Fdetails%3Fid%3Dcom.AwakeLand.fallleaftapgame");
}
if (GUI.Button( new Rect(Screen.width-r*9.0f, r*4.0f, r*4.8f, r), "devel. WWW"))
{
myAudio[6].Play();
Application.OpenURL("http://awakeland.com");
}
if (hiScore > 0 && GUI.Button( new Rect(10.0f, r*5.2f, Screen.width-r*6.0f, r), "@tweet points"))
{
myAudio[4].Play();
Application.OpenURL("http://twitter.com/home?status=I+scored+" + hiScore + "+in+%22Fall+Leaf+Tap%22%2C+a+%23freegame+for+%23Android+from+%40AwakeLandGames at https%3A%2F%2Fplay.google.com%2Fstore%2Fapps%2Fdetails%3Fid%3Dcom.AwakeLand.FallLeafTap");
}
// End of GUI
GUI.EndGroup();
}
}
}
|
using PL.Integritas.Domain.Entities;
using System.Collections.Generic;
namespace PL.Integritas.Domain.Interfaces.Repositories
{
public interface IShoppingCartRepository : IRepository<ShoppingCart>
{
}
}
|
using Alabo.Web.Mvc.Attributes;
namespace Alabo.Schedules.Enum {
[ClassProperty(Name = "任务计划状态")]
public enum TaskScheduleStatus : byte {
Running = 1,
Stoped,
Idle,
Suspend,
Unknown = 255
}
}
|
using System;
namespace EasyDev.PL
{
/// <summary>
/// 生成主键值的方法
/// </summary>
[Obsolete("此类已经过时,使用实现了IGenerator接口并通过GeneratorFactory创建的类")]
public class IdentityGenerator
{
/// <summary>
/// 生成GUID作为实体标识
/// </summary>
/// <returns></returns>
public static string GUIDIdentity()
{
return Guid.NewGuid().ToString();
}
/// <summary>
/// 生成ORACLE数据表对应的SEQUENCE
/// </summary>
/// <param name="session"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public static string GetNextSequenceId(GenericDBSession session, string tableName)
{
try
{
return Convert.ToString(
session.GetScalarObjectFromCommand(
string.Format(@"SELECT SEQ_{0}.nextval FROM dual", tableName)));
}
catch (Exception e)
{
throw e;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace KartLib
{
public class OrgInfoRecord : Entity
{
public override string FriendlyName
{
get { return "Запись об организации"; }
}
public string Name
{
get;
set;
}
public string INN
{
get;
set;
}
public string KPP
{
get;
set;
}
public string ZIPcode
{
get;
set;
}
public string RegionCode
{
get;
set;
}
public string Region
{
get;
set;
}
public string City
{
get;
set;
}
public string Street
{
get;
set;
}
public string House
{
get;
set;
}
public string Phone
{
get;
set;
}
public string Email
{
get;
set;
}
public string Director
{
get;
set;
}
public string Accountant
{
get;
set;
}
public DateTime DateReport
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrangeOffice
{
class Control
{
private int control = 0;
private int year = 0;
private int month = 0;
private int day = 0;
//0 all can add
//1 log_3
//2 reserve_3
//3 log_5
//4 reserve_5
//5 log_6
//6 reserve_6
//7 history_log_3
//8 history_reserve_3
//9 history_log_5
//10 history_reserve_5
//11 history_log_6
//12 history_reserve_6
public int changControl(string name)
{
switch (name)
{
case "log_3":
control = 1;
break;
case "reserve_3":
control = 2;
break;
case "log_5":
control = 3;
break;
case "reserve_5":
control = 4;
break;
case "log_6":
control = 5;
break;
case "reserve_6":
control = 6;
break;
case "history_log":
control = 7;
break;
case "history_reserve":
control = 8;
break;
case "sh_log":
control = 9;
break;
case "sh_reserve":
control = 10;
break;
case "sh_now_log":
control = 11;
break;
case "ac_name":
control = 12;
break;
case "ac_content":
control = 13;
break;
case "onlineState":
control = 14;
break;
case "add_recipe":
control = 15;
break;
case "modify_recipe_name":
control = 16;
break;
case "modify_recipe_content":
control = 17;
break;
case "modify_recipe_all_spice":
control = 18;
break;
case "modify_spice":
control = 19;
break;
case "directRecipe":
control = 20;
break;
case "directRecipeName":
control = 21;
break;
/*
case "history_log_3":
control = 7;
break;
case "history_reserve_3":
control = 8;
break;
case "history_log_5":
control = 9;
break;
case "history_reserve_5":
control = 10;
break;
case "history_log_6":
control = 11;
break;
case "history_reserve_6":
control = 12;
break;
*/
}
return control;
}
public int showControl()
{
return control;
}
//now show day
//
//
public void changDay(int year, int month, int day)
{
this.year = year;
this.month = month;
this.day = day;
}
public void plusDay()
{
day = day + 1;
}
public void minusDay()
{
day = day - 1;
}
public int nowYear()
{
return year;
}
public int nowMonth()
{
return month;
}
public int nowDay()
{
return day;
}
public string target()
{
string tar = null;
switch (control)
{
case 1:
tar = "WH_HISTORY 3";
break;
case 2:
tar = "WH_NOW 3";
break;
case 3:
tar = "WH_HISTORY 5";
break;
case 4:
tar = "WH_NOW 5";
break;
case 5:
tar = "WH_HISTORY 6";
break;
case 6:
tar = "WH_NOW 6";
break;
case 7:
tar = "WH_HISTORY 3";
break;
case 8:
tar = "WH_NOW 3";
break;
case 9:
tar = "WH_HISTORY 5";
break;
case 10:
tar = "WH_NOW 5";
break;
case 11:
tar = "WH_HISTORY 6";
break;
case 12:
tar = "WH_NOW 6";
break;
}
return tar;
}
}
}
|
using System.Collections.Generic;
using SuperRpgGame.Interfaces;
using SuperRpgGame.Items;
namespace SuperRpgGame
{
public class Player : Character, IPlayer
{
public Player(Position position, char objSymbol, string name, PlayerRace race)
: base(position, objSymbol, 0, 0, name)
{
this.Race = race;
this.SetPlayerStats();
}
private void SetPlayerStats()
{
switch (this.Race)
{
case PlayerRace.ArchAngel:
this.Damage = 200;
this.Health = 300;
break;
case PlayerRace.Elf:
this.Damage = 200;
this.Health = 400;
break;
case PlayerRace.Hulk:
this.Damage = 200;
this.Health = 500;
break;
case PlayerRace.Human:
this.Damage = 200;
this.Health = 600;
break;
}
}
public void Move()
{
throw new System.NotImplementedException();
}
public IEnumerable<Item> Inventory { get; private set; }
public void AddItemToInventory(Item item)
{
throw new System.NotImplementedException();
}
public void Heal()
{
throw new System.NotImplementedException();
}
public int Experience { get; private set; }
public void LevelUp()
{
throw new System.NotImplementedException();
}
public PlayerRace Race { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace WardrobeMVCVer1
{
[MetadataType(typeof(TopMetadata))]
public partial class Top
{
}
public class TopMetadata
{
public int TopID { get; set; }
[DisplayName("Item Name")]
public string Name { get; set; }
[DisplayName("Image")]
public string Photo { get; set; }
public string Type { get; set; }
public string Season { get; set; }
public string Occasion { get; set; }
}
}
|
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using Docller.Core.Models;
using Microsoft.SqlServer.Server;
namespace Docller.Core.Repository.Collections
{
public class FolderCollection : List<Folder>, IEnumerable<SqlDataRecord>
{
private readonly StringDictionary _dups;
public FolderCollection(IEnumerable<Folder> folders)
: base(folders)
{
_dups = new StringDictionary();
}
IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator()
{
SqlDataRecord dataRecord = new SqlDataRecord(new SqlMetaData("FolderId", SqlDbType.BigInt),
new SqlMetaData("FolderName", SqlDbType.NVarChar, 255),
new SqlMetaData("ParentFolderId", SqlDbType.NVarChar, 1000),
new SqlMetaData("FullPath", SqlDbType.NVarChar, 2000));
for (int i = 0; i < this.Count; i++)
{
Folder folder = this[i];
if (this.IsUnique(folder))
{
dataRecord.SetInt64(0, folder.FolderId);
dataRecord.SetString(1, folder.FolderName);
dataRecord.SetNullableLong(2, folder.ParentFolderId);
dataRecord.SetNullableString(3, folder.FullPath);
}
yield return dataRecord;
}
}
private bool IsUnique(Folder folder)
{
if(!this._dups.ContainsKey(folder.FolderName))
{
this._dups.Add(folder.FolderName, folder.FolderName);
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace z88dk_compile_options_helper_beta
{
public partial class quick_start : Form
{
public List<string> ListOptions = new List<string>();
public quick_start()
{
InitializeComponent();
}
//form global variables
//bool enableFloatingPoint = false;
//bool enableLNDOS = false;
//bool enableCreateApp = false;
string floatingPoint = "";
string fileName = "";
string outputFile = "";
string manualEntry = "";
string reserveRegsIY = "";
bool sdccCompilerlib = true;
bool compatableTargetforZXFloats = false;
int zorgValue = 32768;
//form global variables
public quick_start(string strTextBox)
{
InitializeComponent();
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(0, 0);
textBox1.Text = strTextBox;
string platform = strTextBox;
ListOptions.Add(platform);
//textBox1.ShortcutsEnabled = false;
textBox1.Enabled = false;
textBox5.Enabled = false;
#region Luxor ABC80
if (zccvariables.machine == "abc80")
{
label1.Text = "Luxor ABC80";
textBox2.Text = "zcc +abc80 -lm -o adventure -create-app program.c";
textBox3.Text = "zcc +abc80 -lm -subtype=wav -o program -create-app program.c";
compatableTargetforZXFloats = false;
zorgValue = 49200;
}
#endregion
#region Luxor ABC800
if (zccvariables.machine == "abc800")
{
label1.Text = "Luxor ABC800";
textBox2.Text = "zcc +abc800 -zorg=40000 -create-app program.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 40000;
}
#endregion
#region Jupiter ACE
if (zccvariables.machine == "ace")
{
label1.Text = "Jupiter ACE";
textBox2.Text = "zcc +ace -create-app program.c";
textBox3.Text = "zcc +ace -clib=ansi -create-app -Cz--audio -o program program.c";
compatableTargetforZXFloats = false;
zorgValue = 24000;
}
#endregion
#region Mattel Aquarius
if (zccvariables.machine == "aquarius")
{
label1.Text = "Mattel Aquarius";
textBox2.Text = "zcc +aquarius -lm -create-app -o program program.c";
textBox3.Text = "zcc +aquarius -subtype=ansi -lm -create-app -o program program.c";
compatableTargetforZXFloats = false;
zorgValue = 16384;
}
#endregion
#region Commodore 128
if (zccvariables.machine == "c128")
{
label1.Text = "Commodore C128";
textBox2.Text = "zcc +c128 -create-app program.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Philips Videopac C7420
if (zccvariables.machine == "c7420")
{
label1.Text = "Philips Videopac C7420";
textBox2.Text = "zcc +c7420 -create-app program.c";
textBox3.Text = "zcc +c7420-create-app -zorg=<location> program.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region CPC
if (zccvariables.machine == "cpc")
{
label1.Text = "Amstrad CPC";
textBox2.Text = "zcc +cpc -lndos -lm -create-app -o program adv_a.c";
textBox3.Text = "zcc +cpc -clib=ansi -lcpcfs -lmz -create-app -o program adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 1024;
}
#endregion
#region CP/M
if (zccvariables.machine == "cpm")
{
label1.Text = "CP/M";
textBox2.Text = "zcc +cpm -lm -o program.com program.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Embedded
if (zccvariables.machine == "embedded")
{
label1.Text = "Embedded";
textBox2.Text = "";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Enterprise 64/128 Platform
if (zccvariables.machine == "enterprise")
{
label1.Text = "Enterprise 64/128 Platform";
textBox2.Text = "zcc +enterprise -lm -create-app -o program program.c";
textBox3.Text = "zcc +enterprise -subtype=com -lm -o program.com program.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Galaksija
if (zccvariables.machine == "gal")
{
label1.Text = "Galaksija";
textBox2.Text = "zcc +gal -create-app -o adventure adv_a.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Lambda 8300
//Lambda 8300
//improved chinese clone of the ZX81
if (zccvariables.machine == "lambda")
{
label1.Text = "Lambda 8300";
textBox2.Text = "zcc +lambda -lzx81_math -create-app program.c";
textBox3.Text = "zcc +lambda -lm -create-app program.c";
compatableTargetforZXFloats = false;
zorgValue = 16389;
}
#endregion
#region Camputers Lynx
if (zccvariables.machine == "lynx")
{
label1.Text = "Camputers Lynx";
textBox2.Text = "zcc +lynx -lm -create-app adv_a.c";
textBox3.Text = "zcc +lynx -lm -o adventure.z80 adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 32768;
}
#endregion
#region Sord M5
if (zccvariables.machine == "m5")
{
label1.Text = "Sord M5";
textBox2.Text = "zcc +m5 -lm -create-app -Cz--audio program.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 29696;
}
#endregion
#region CCE MC-1000
if (zccvariables.machine == "mc1000")
{
label1.Text = "CCE MC-1000";
textBox2.Text = "zcc +mc1000 -create-app -Cz--audio program.c";
textBox3.Text = "zcc +mc1000 -clib=ansi -create-app -Cz--audio program.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region MSX
if (zccvariables.machine == "msx")
{
label1.Text = "MSX";
textBox2.Text = "zcc +msx -create-app program.c";
textBox3.Text = "zcc +msx -create-app -subtype=wav program.c";
compatableTargetforZXFloats = false;
zorgValue = 32768;
}
#endregion
#region Memotech MTX
if (zccvariables.machine == "mtx")
{
label1.Text = "Memotech MTX";
textBox2.Text = "zcc +mtx -lndos -create-app -Cz--audio -o program.bin program.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region NASCOM 1 & 2
if (zccvariables.machine == "nascom")
{
label1.Text = "NASCOM 1 & 2";
textBox2.Text = "zcc +nascom -lm -o adventure -create-app program.c";
textBox3.Text = "zcc +nascom -clib=ansi -lm -o program -create-app program.c";
compatableTargetforZXFloats = false;
}
#endregion
#region Amstrad NC
if (zccvariables.machine == "nc")
{
label1.Text = "Amstrad NC";
textBox2.Text = "zcc +nc -lm program.c";
textBox3.Text = "zcc +nc -subtype=ram -lm program.c";
compatableTargetforZXFloats = false;
zorgValue = 1024;
}
#endregion
#region Grundy Newbrain
if (zccvariables.machine == "newbrain")
{
label1.Text = "Grundy Newbrain";
textBox2.Text = "zcc +newbrain -lm -lndos -create-app program.c";
textBox3.Text = "zcc +newbrain -lm -lnbdrv -create-app program.c";
compatableTargetforZXFloats = false;
zorgValue = 20000;
}
#endregion
#region Old School Computer Architecture
if (zccvariables.machine == "osca")
{
label1.Text = "Old School Computer Architecture";
textBox2.Text = "zcc +osca -lm -lndos -o program.exe program.c";
textBox3.Text = "zcc +osca -lm -lflosdos -o program.exe program.c";
compatableTargetforZXFloats = false;
zorgValue = 32767;
}
#endregion
#region Sharp OZ-700
if (zccvariables.machine == "oz")
{
label1.Text = "Sharp OZ-700";
textBox2.Text = "zcc +oz -lm -o adv.bin adv_a.c";
textBox3.Text = "zcc +oz -O3 ansitest.c -pragma-define:ansicolumns=26";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Philips P2000
if (zccvariables.machine == "p2000")
{
label1.Text = "Philips P2000";
textBox2.Text = "zcc +p2000 -create-app -lm program.c";
textBox3.Text = "zcc +p2000 -subtype=ansi -create-app -lm program.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region NEC PC-6001
if (zccvariables.machine == "pc6001")
{
label1.Text = "NEC PC-6001";
textBox2.Text = "zcc +pc6001 -create-app -lm program.c";
textBox3.Text = "zcc +pc6001 -clib=ansi -subtype=32k -oprogram -create-app -lm program.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Peters Plus Sprinter
if (zccvariables.machine == "pps")
{
label1.Text = "Peters Plus Sprinter";
textBox2.Text = "zcc +pps -o adventure.exe adv_a.c";
textBox3.Text = "zcc +pps -clib=ansi -o adventure.exe adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region RCMX000
if (zccvariables.machine == "rcmx000")
{
label1.Text = "RCMX";
textBox2.Text = "";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Xircom REX 6000
if (zccvariables.machine == "rex")
{
label1.Text = "Xircom REX 6000";
textBox2.Text = "zcc +rex -create-app -lm hello.c";
textBox3.Text = "zcc +rex -subtype=lib -create-app -lm libcode.";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region SAM Coupe
if (zccvariables.machine == "sam")
{
label1.Text = "SAM Coupe";
textBox2.Text = "zcc +sam -lm application.c";
textBox3.Text = "zcc +sam -clib=ansi -lm application.c";
compatableTargetforZXFloats = false;
zorgValue = 32768;
}
#endregion
#region SEGA SC-3000
if (zccvariables.machine == "sc3000")
{
label1.Text = "SEGA SC-3000";
textBox2.Text = "zcc +sc3000 -create-app -Cz--audio -oadventure adv_a.c";
textBox3.Text = "zcc +sc3000 -create-app -subtype=sf7000 -Cz--audio -oadventure -zorg=40000 adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 40000;
}
#endregion
#region SMS
if (zccvariables.machine == "sms")
{
label1.Text = "SMS";
textBox2.Text = "";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region S-OS (The Sentinel)
if (zccvariables.machine == "sos")
{
label1.Text = "S-OS (The Sentinel)";
textBox2.Text = "zcc +sos -lndos -oadva -create-app adv_a.c";
textBox3.Text = "zcc +sos -lgendos -lmalloc -DAMALLOC -oadva -create-app adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 3000;
}
#endregion
#region Sorcerer Exidy
if (zccvariables.machine == "srr")
{
label1.Text = "Sorcerer Exidy";
textBox2.Text = "zcc +srr -lm -lndos -create-app dstar.c -Cz--audio";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Spectravideo SVI
if (zccvariables.machine == "svi")
{
label1.Text = "Spectravideo SVI";
textBox2.Text = "zcc +svi -lm -create-app program.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Texas Instruments TI8X
if (zccvariables.machine == "ti8x")
{
label1.Text = "Texas Instruments ti8x";
textBox2.Text = "zcc +ti8x -lm -o adv_a -create-app adv_a.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI82
if (zccvariables.machine == "ti82")
{
label1.Text = "Texas Instruments";
textBox2.Text = "zcc +ti82 -lm -o adv_a -create-app adv_a.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI83
if (zccvariables.machine == "ti83")
{
label1.Text = "Texas Instruments";
textBox2.Text = "zcc +ti83 -lm -o adv_a -create-app adv_a.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI85
if (zccvariables.machine == "ti85")
{
label1.Text = "Texas Instruments";
textBox2.Text = "zcc +ti85 -lm -o adv_a -create-app adv_a.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI86
if (zccvariables.machine == "ti86")
{
label1.Text = "Texas Instruments";
textBox2.Text = "zcc +ti86 -lm -o adv_a -create-app adv_a.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 24576;
}
#endregion
#region trs80 ** & EG2000
if (zccvariables.machine == "trs80")
{
label1.Text = "Tandy TRS-80";
textBox2.Text = "zcc +trs80 -lndos -lm -create-app -subtype=disk program.c";
textBox3.Text = "zcc +trs80 -lndos -lm -create-app program.c";
compatableTargetforZXFloats = false;
zorgValue = 20992;
}
#endregion
#region ts2068
if (zccvariables.machine == "ts2068")
{
label1.Text = "Timex Sinclair 2068";
textBox2.Text = "zcc +ts2068 -create-app program.c";
textBox3.Text = "zcc +ts2068 -clib=ansi -create-app program.c";
compatableTargetforZXFloats = true;
zorgValue = 32768;
}
#endregion
#region vg5k
//vg5000
if (zccvariables.machine == "vg5k")
{
label1.Text = "Philips VG-5000";
textBox2.Text = "zcc +vg5k -subtype=wav -create-app -lm program.c";
textBox3.Text = "zcc +vg5k -clib=ansi -subtype=wav -create-app -lm program.c";
compatableTargetforZXFloats = false;
zorgValue = 20480;
}
#endregion
#region vz
if (zccvariables.machine == "vz")
{
label1.Text = "VZ 200";
textBox2.Text = "zcc +vz -lm -o adventure.vz adv_a.c";
textBox3.Text = "zcc +vz -clib=ansi -lm -o adventure.vz adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region x1 **
if (zccvariables.machine == "x1")
{
label1.Text = "Sharp X1";
textBox2.Text = "zcc +x1 -lm -lndos adv_a.c";
textBox3.Text = "zcc +x1 -pragma-define:ansicolumns=80 -lndos vtstone.c";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region Canon X07 **
if (zccvariables.machine == "x07")
{
label1.Text = "Canon X-07";
textBox2.Text = "zcc +x07 -lndos -create-app program.c";
textBox3.Text = "zcc +x07 -lndos -create-app -Cz--audio program.c";
compatableTargetforZXFloats = false;
zorgValue = 1024;
}
#endregion
#region Cambridge z88 **
if (zccvariables.machine == "z88")
{
label1.Text = "Cambridge z88 ";
textBox2.Text = "zcc +z88 -create-app -oapp.bas -make-app app.c";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 16389;
}
#endregion
#region zcc **
if (zccvariables.machine == "zcc")
{
label1.Text = "ZCC";
textBox2.Text = "";
textBox3.Text = "";
compatableTargetforZXFloats = false;
zorgValue = 0;
}
#endregion
#region zx spectrum
if (zccvariables.machine == "zx")
{
label1.Text = "Sinclair ZX Spectrum";
textBox2.Text = "zcc +zx -lndos -create-app adv_a.c";
textBox3.Text = "zcc +zx -clib=ansi -lndos -create-app adv_a.c";
compatableTargetforZXFloats = true;
zorgValue = 32768;
}
#endregion
#region zx80
if (zccvariables.machine == "zx80")
{
label1.Text = "Sinclair ZX80";
textBox2.Text = "zcc +zx80 -lm -create-app -Cz–audio program.c";
textBox3.Text = "zcc +zx -clib=ansi -lndos -create-app adv_a.c";
compatableTargetforZXFloats = false;
zorgValue = 16389;
}
#endregion
#region zx81
if (zccvariables.machine == "zx81")
{
label1.Text = "Sinclair ZX81";
textBox2.Text = "zcc +zx81 -lzx81_math -create-app program.c";
textBox3.Text = "zcc +zx81 -lm -create-app program.c";
compatableTargetforZXFloats = false;
zorgValue = 16389;
}
#endregion
trackBar1.Value = zorgValue;
textBox7.Text = trackBar1.Value.ToString();
textBox8.Text = trackBar1.Value.ToString();
}
public bool machine_type_for_floating_point(bool type)
{
if (zccvariables.machine == "zx")
{
return true;
}
if (zccvariables.machine == "zx81")
{
return true;
}
if (zccvariables.machine == "ts2068")
{
return true;
}
//cpc
if (zccvariables.machine == "cpc")
{
return true;
}
//what about sam & ace & lambda
else
{
return false;
}
//return true;
}
private void quick_start_Load(object sender, EventArgs e)
{
}
/// <summary>
/// C Library Selection new/old
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void newLibrary_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
//disable fsigned on sdcc only
f_signed_char.Checked = false;
f_signed_char.Enabled = false;
//disable floating point options
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
// disable textbox for compiling string
textBox1.Enabled = false;
#endregion
#region if radio button is checked
if (newLibrary.Checked == true)
{
//indicates that you are using the new library
zccvariables.classicCompiler = false;
//enable new library options
library_sccZ80.Enabled = true;
library_sdccIX_no_reserve_IY.Enabled = true;
library_sdccIX_reserve_IY.Enabled = true;
library_sdccIY_reserve_IY.Enabled = true;
library_sccZ80.Checked = false;
library_sdccIX_no_reserve_IY.Checked = false;
library_sdccIX_reserve_IY.Checked = false;
library_sdccIY_reserve_IY.Checked = false;
//disable classic library options
library_sccZ80_classic.Enabled = false;
library_sdcc_classic.Enabled = false;
library_sccZ80_classic.Checked = false;
library_sdcc_classic.Checked = false;
sdccCompilerlib = true;
//disable and remove zorg
string zorg = "-zorg=";
ListOptions.Remove(zorg + zorgValue + " ");
//MessageBox.Show("Radio Button 2 off");
string zorgOption = string.Join("", ListOptions.ToArray());
textBox1.Text = zorgOption;
panel8.Enabled = false;
//remove and disable output file
string createApp = "-create-app ";
ListOptions.Remove(createApp);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
checkBox3.Checked = false;
textBox5.Text = "";
string file = "-o " + outputFile + " ";
ListOptions.Remove(file);
string uncreate = string.Join("", ListOptions.ToArray());
textBox1.Text = uncreate;
panel6.Enabled = false;
//remove input file
//manual entry
string remove_manual = manualEntry + " ";
ListOptions.Remove(remove_manual);
string bob = string.Join("", ListOptions.ToArray());
textBox1.Text = bob;
textBox6.Text = "";
textBox6.Enabled = true;
button15.Enabled = false;
button16.Enabled = true;
// remove input file
//browsed entry
button8.Enabled = false;
button9.Enabled = false;
textBox4.Text = "";
string file2 = fileName + " ";
ListOptions.Remove(file2);
string create2 = string.Join("", ListOptions.ToArray());
textBox1.Text = create2;
textBox4.Enabled = true;
button7.Enabled = false;//open file button
button8.Enabled = true;
button9.Enabled = false;
panel7.Enabled = false;
library_sccZ80_classic.BackColor = Color.Transparent;
library_sdcc_classic.BackColor = Color.Transparent;
//change color of panel box to indicate next choice
panel3.BackColor = Color.CadetBlue;
///reset panel colors floating point/zorg/output file/input file
panel2.BackColor = Color.LightBlue;
panel8.BackColor = Color.LightBlue;
panel6.BackColor = Color.LightBlue;
panel7.BackColor = Color.LightBlue;
panel5.BackColor = Color.LightBlue;
panel10.BackColor = Color.LightBlue;
}
#endregion
#region if radio button is cleared
if (newLibrary.Checked == false)
{
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
//disable floating point options until compiler library reset
}
#endregion
}
private void classicLibrary_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
//fsigned on sdcc only
f_signed_char.Checked = false;
f_signed_char.Enabled = false;
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
#endregion
#region if radio button is checked
if (classicLibrary.Checked == true)
{
//MessageBox.Show("classic");
//indicates that you are using the classic library
zccvariables.classicCompiler = true;
sdccCompilerlib = true;
textBox1.Enabled = false;
//reset all entrys on this form
library_sccZ80.Enabled = false;
library_sdccIX_no_reserve_IY.Enabled = false;
library_sdccIX_reserve_IY.Enabled = false;
library_sdccIY_reserve_IY.Enabled = false;
library_sccZ80.Checked = false;
library_sdccIX_no_reserve_IY.Checked = false;
library_sdccIX_reserve_IY.Checked = false;
library_sdccIY_reserve_IY.Checked = false;
library_sccZ80_classic.Enabled = true;
library_sdcc_classic.Enabled = true;
library_sccZ80_classic.Checked = false;
library_sdcc_classic.Checked = false;
//disable and remove zorg
string zorg = "-zorg=";
ListOptions.Remove(zorg + zorgValue + " ");
//MessageBox.Show("Radio Button 2 off");
string zorgOption = string.Join("", ListOptions.ToArray());
textBox1.Text = zorgOption;
panel8.Enabled = false;
//remove and disable output file
string createApp = "-create-app ";
ListOptions.Remove(createApp);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
checkBox3.Checked = false;
textBox5.Text = "";
string file = "-o " + outputFile + " ";
ListOptions.Remove(file);
string uncreate = string.Join("", ListOptions.ToArray());
textBox1.Text = uncreate;
panel6.Enabled = false;
//remove input file
//manual entry
string remove_manual = manualEntry + " ";
ListOptions.Remove(remove_manual);
string bob = string.Join("", ListOptions.ToArray());
textBox1.Text = bob;
textBox6.Text = "";
textBox6.Enabled = true;
button15.Enabled = false;
button16.Enabled = true;
// remove input file
//browsed entry
button8.Enabled = false;
button9.Enabled = false;
textBox4.Text = "";
string file2 = fileName + " ";
ListOptions.Remove(file2);
string create2 = string.Join("", ListOptions.ToArray());
textBox1.Text = create2;
textBox4.Enabled = true;
button7.Enabled = false;//open file button
button8.Enabled = true;
button9.Enabled = false;
panel7.Enabled = false;
//change color of panel box to indicate next choice
panel3.BackColor = Color.CadetBlue;
library_sccZ80.BackColor = Color.Transparent;
library_sdccIX_no_reserve_IY.BackColor = Color.Transparent;
library_sdccIX_reserve_IY.BackColor = Color.Transparent;
library_sdccIY_reserve_IY.BackColor = Color.Transparent;
//reset panel colors floating point/zorg/output file/input file
panel2.BackColor = Color.LightBlue;
panel8.BackColor = Color.LightBlue;
panel6.BackColor = Color.LightBlue;
panel7.BackColor = Color.LightBlue;
panel5.BackColor = Color.LightBlue;
panel10.BackColor = Color.LightBlue;
}
#endregion
#region if radio button is cleared
if (classicLibrary.Checked == false)
{
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
//disable floating point options until compiler library reset
}
#endregion
}
/// <summary>
/// C Library
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//new library -clib=new
private void library_sccZ80_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
checkBox3.Enabled = true;
media_device_LNDOS.Enabled = false;
media_device_DPLUS.Enabled = false;
media_device_LP3DOS.Enabled = false;
media_device_LNDOS.Checked = false;
media_device_DPLUS.Checked = false;
media_device_LP3DOS.Checked = false;
#endregion
#region if radio button is checked
if (library_sccZ80.Checked)
{
string assemblertype = "-clib=new ";
ListOptions.Add(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
sdccCompilerlib = false;
button7.Enabled = true;//open file button
//floating point options
panel2.Enabled = true;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = true;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = true;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Black;
lmFloatPoint.ForeColor = Color.Black;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//floating point options
f_signed_char.Enabled = false;
//turn on zorg
panel8.Enabled = true;
button18.Enabled = true;
button19.Enabled = false;
trackBar1.Enabled = true;
textBox7.Enabled = true;
//turn on input file
panel7.Enabled = true;
//turn on create app & output file
panel6.Enabled = true;
checkBox3.Enabled = true;
//fsigned on sdcc only
f_signed_char.Checked = false;
f_signed_char.Enabled = false;
//turn on floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.LightGray;
}
#endregion
#region if radio button is cleared
if (library_sccZ80.Checked == false)
{
string assemblertype = "-clib=new ";
ListOptions.Remove(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Gray;
lmFloatPoint.ForeColor = Color.Gray;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//disable floating point options until compiler library reset
//fsigned on sdcc only
f_signed_char.Checked = false;
f_signed_char.Enabled = false;
//turn off zorg
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
//reset panel colors floating point/zorg/output file/input file
panel2.BackColor = Color.LightBlue;
panel8.BackColor = Color.LightBlue;
panel6.BackColor = Color.LightBlue;
panel7.BackColor = Color.LightBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.LightGray;
}
#endregion
}
//new library -clib=sdcc_ix
private void library_sdccIX_no_reserve_IY_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
checkBox3.Enabled = true;
media_device_LNDOS.Enabled = false;
media_device_DPLUS.Enabled = false;
media_device_LP3DOS.Enabled = false;
media_device_LNDOS.Checked = false;
media_device_DPLUS.Checked = false;
media_device_LP3DOS.Checked = false;
#endregion
#region if radio button is checked
if (library_sdccIX_no_reserve_IY.Checked)
{
string assemblertype = "-clib=sdcc_ix ";
ListOptions.Add(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
if (compatableTargetforZXFloats == true)
{
sdccCompilerlib = true;
}
//floating point options
panel2.Enabled = true;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = true;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = true;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Black;
lmFloatPoint.ForeColor = Color.Black;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//floating point options
f_signed_char.Enabled = true;
//turn on zorg
panel8.Enabled = true;
button18.Enabled = true;
button19.Enabled = false;
trackBar1.Enabled = true;
textBox7.Enabled = true;
//turn on input file
panel7.Enabled = true;
//turn on create app & output file
panel6.Enabled = true;
checkBox3.Enabled = true;
//turn on fsigned
panel10.Enabled = true;
f_signed_char.Enabled = true;
f_signed_char.Checked = false;
//turn on floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.CadetBlue;
}
#endregion
#region if radio button is cleared
if (library_sdccIX_no_reserve_IY.Checked == false)
{
string assemblertype = "-clib=sdcc_ix ";
ListOptions.Remove(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Gray;
lmFloatPoint.ForeColor = Color.Gray;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//disable floating point options until compiler library reset
//turn off zorg
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
//turn off floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.LightGray;
}
#endregion
}
//new library -clib=sdcc_iy --reserve-regs-iy
private void library_sdccIY_reserve_IY_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
checkBox3.Enabled = true;
if (compatableTargetforZXFloats == true)
{
sdccCompilerlib = true;
}
media_device_LNDOS.Enabled = false;
media_device_DPLUS.Enabled = false;
media_device_LP3DOS.Enabled = false;
media_device_LNDOS.Checked = false;
media_device_DPLUS.Checked = false;
media_device_LP3DOS.Checked = false;
button7.Enabled = true;//open file button
#endregion
#region if radio button is checked
if (library_sdccIY_reserve_IY.Checked)
{
string assemblertype = "-clib=sdcc_iy ";
ListOptions.Add(assemblertype);
//MessageBox.Show("Radio Button 2 off");
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
sdccCompilerlib = true;
//floating point options
panel2.Enabled = true;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = true;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = true;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Black;
lmFloatPoint.ForeColor = Color.Black;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//floating point options
f_signed_char.Enabled = true;
//turn on zorg
panel8.Enabled = true;
button18.Enabled = true;
button19.Enabled = false;
trackBar1.Enabled = true;
textBox7.Enabled = true;
//turn on input file
panel7.Enabled = true;
//turn on create app & output file
panel6.Enabled = true;
checkBox3.Enabled = true;
//turn on fsigned
panel10.Enabled = true;
f_signed_char.Enabled = true;
f_signed_char.Checked = false;
//turn on floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.CadetBlue;
}
#endregion
#region if radio button is cleared
if (library_sdccIY_reserve_IY.Checked == false)
{
string assemblertype = "-clib=sdcc_iy ";
ListOptions.Remove(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Gray;
lmFloatPoint.ForeColor = Color.Gray;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//disable floating point options until compiler library reset
//turn off zorg
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
//turn off floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.LightGray;
}
#endregion
}
//new library -clib=sdcc_ix
private void library_sdccIX_reserve_IY_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
if (compatableTargetforZXFloats == true)
{
sdccCompilerlib = true;
}
if (compatableTargetforZXFloats == false)
{
}
media_device_LNDOS.Enabled = false;
media_device_DPLUS.Enabled = false;
media_device_LP3DOS.Enabled = false;
media_device_LNDOS.Checked = false;
media_device_DPLUS.Checked = false;
media_device_LP3DOS.Checked = false;
button7.Enabled = true;//open file button
//checkBox1.Enabled = true;
checkBox3.Enabled = true;
#endregion
#region if radio button is checked
if (library_sdccIX_reserve_IY.Checked)
{
string assemblertype = "-clib=sdcc_ix --reserve-regs-iy ";
ListOptions.Add(assemblertype);
//MessageBox.Show("Radio Button 2 off");
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
sdccCompilerlib = true;
//floating point options
panel2.Enabled = true;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = true;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = true;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Black;
lmFloatPoint.ForeColor = Color.Black;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//floating point options
//turn on zorg
panel8.Enabled = true;
button18.Enabled = true;
button19.Enabled = false;
trackBar1.Enabled = true;
textBox7.Enabled = true;
//turn on input file
panel7.Enabled = true;
//turn on create app & output file
panel6.Enabled = true;
checkBox3.Enabled = true;
//turn on fsigned
panel10.Enabled = true;
f_signed_char.Enabled = true;
f_signed_char.Checked = false;
//turn on floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.CadetBlue;
}
#endregion
#region if radio button is cleared
if (library_sdccIX_reserve_IY.Checked == false)
{
string assemblertype = "-clib=sdcc_ix --reserve-regs-iy ";
ListOptions.Remove(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//disable floating point options until compiler library reset
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
noFloatPoint.ForeColor = Color.Gray;
lmFloatPoint.ForeColor = Color.Gray;
lmzxFloatPoint.ForeColor = Color.Gray;
lmzxtinyFloatPoint.ForeColor = Color.Gray;
//disable floating point options until compiler library reset
//turn off zorg
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
//turn off floating point/zorg/output file/input file
panel2.BackColor = Color.CadetBlue;
panel8.BackColor = Color.CadetBlue;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
//disk device not needed, grey out
panel5.BackColor = Color.LightGray;
panel10.BackColor = Color.LightGray;
}
#endregion
}
//classic library
private void library_sdcc_classic_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
checkBox3.Enabled = false;
media_device_LNDOS.Enabled = true;
media_device_DPLUS.Enabled = true;
media_device_LP3DOS.Enabled = true;
media_device_LNDOS.Checked = false;
media_device_DPLUS.Checked = false;
media_device_LP3DOS.Checked = false;
button7.Enabled = false;//open file button
#endregion
//-compiler=sdcc
#region if radio button is checked
if (library_sdcc_classic.Checked)
{
zccvariables.sdcc_compiler = true;
string assemblertype = "-compiler=sdcc ";
ListOptions.Add(assemblertype);
//MessageBox.Show("Radio Button 2 off");
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
// floating point options, disable panel until media selected
panel2.Enabled = false;
panel2.BackColor = Color.LightBlue;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = true;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = true;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = true;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = true;
// floating point options, disable panel until media selected
//f_signed option
f_signed_char.Enabled = false;
panel10.Enabled = false;
panel10.BackColor = Color.LightBlue;
bool machineFloat = machine_type_for_floating_point(false);
if (machineFloat == true)
{
lmzxFloatPoint.Enabled = true;
lmzxtinyFloatPoint.Enabled = true;
}
//turn on floating point/zorg/output file/input file
//panel2.BackColor = Color.CadetBlue;
panel5.BackColor = Color.CadetBlue;
media_device_DPLUS.ForeColor = Color.Gray;
media_device_LP3DOS.ForeColor = Color.Gray;
f_signed_char.Enabled = false;
f_signed_char.Checked = false;
}
#endregion
#region if radio button is cleared
if (library_sdcc_classic.Checked == false)
{
string assemblertype = "-compiler=sdcc ";
ListOptions.Remove(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//disable floating point options until compiler library reset
panel2.Enabled = false;//problem?
panel2.BackColor = Color.LightBlue;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
//disable floating point options until compiler library reset
f_signed_char.Enabled = false;
media_device_DPLUS.ForeColor = Color.Black;
media_device_LP3DOS.ForeColor = Color.Black;
}
#endregion
}
//classic library
private void library_sccZ80_classic_CheckedChanged(object sender, EventArgs e)
{
#region to do whether checked or not
checkBox3.Enabled = false;
media_device_LNDOS.Enabled = true;
media_device_DPLUS.Enabled = true;
media_device_LP3DOS.Enabled = true;
media_device_LNDOS.Checked = false;
media_device_DPLUS.Checked = false;
media_device_LP3DOS.Checked = false;
button7.Enabled = false;//open file button
#endregion
//-compiler=sccz80
#region if radio button is checked
if (library_sccZ80_classic.Checked)
{
string assemblertype = "-compiler=sccz80 ";
ListOptions.Add(assemblertype);
//MessageBox.Show("Radio Button 2 off");
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//floating point options
panel2.Enabled = true;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = true;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = true;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = true;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = true;
panel2.Enabled = false;
panel2.BackColor = Color.LightBlue;
//floating point options
f_signed_char.Enabled = false;
panel10.BackColor = Color.LightGray;
bool machineFloat = machine_type_for_floating_point(false);
if (machineFloat == true)
{
lmzxFloatPoint.Enabled = true;
lmzxtinyFloatPoint.Enabled = true;
}
//turn on floating point/zorg/output file/input file
panel5.BackColor = Color.CadetBlue;
zccvariables.sdcc_compiler = false;
media_device_DPLUS.ForeColor = Color.Gray;
media_device_LP3DOS.ForeColor = Color.Gray;
f_signed_char.Enabled = false;
f_signed_char.Checked = false;
}
#endregion
#region if radio button is cleared
if (library_sccZ80_classic.Checked == false)
{
string assemblertype = "-compiler=sccz80 ";
ListOptions.Remove(assemblertype);
string assembler = string.Join("", ListOptions.ToArray());
textBox1.Text = assembler;
//disable floating point options until compiler library reset
panel2.Enabled = false;//problem
panel2.BackColor = Color.LightBlue;
noFloatPoint.Checked = false;
noFloatPoint.Enabled = false;
lmFloatPoint.Checked = false;
lmFloatPoint.Enabled = false;
lmzxFloatPoint.Checked = false;
lmzxFloatPoint.Enabled = false;
lmzxtinyFloatPoint.Checked = false;
lmzxtinyFloatPoint.Enabled = false;
//disable floating point options until compiler library reset
f_signed_char.Enabled = false;
panel10.BackColor = Color.LightGray;
media_device_DPLUS.ForeColor = Color.Black;
media_device_LP3DOS.ForeColor = Color.Black;
}
#endregion
}
/// <summary>
/// C Library
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//classic library
/// <summary>
/// No Floating Point Library
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void noFloatPoint_CheckedChanged(object sender, EventArgs e)
{
//no floating point
if (noFloatPoint.Checked)
{
floatingPoint = "";
ListOptions.Add(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
else if (noFloatPoint.Checked == false)
{
floatingPoint = "";
ListOptions.Remove(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
}
/// <summary>
/// LM Floating Point Library
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lmFloatPoint_CheckedChanged(object sender, EventArgs e)
{
if (lmFloatPoint.Checked)
{
floatingPoint = "-lm ";
ListOptions.Add(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
else if (lmFloatPoint.Checked == false)
{
floatingPoint = "-lm ";
ListOptions.Remove(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
}
/// <summary>
/// LMZX Floating Point Library
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lmzxFloatPoint_CheckedChanged(object sender, EventArgs e)
{
if (lmzxFloatPoint.Checked)
{
floatingPoint = "-lmzx ";
ListOptions.Add(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
else if (lmzxFloatPoint.Checked == false)
{
floatingPoint = "-lmzx ";
ListOptions.Remove(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
}
/// <summary>
/// LMZX Tiny Floating Point Library
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lmzxtinyFloatPoint_CheckedChanged(object sender, EventArgs e)
{
if (lmzxtinyFloatPoint.Checked)
{
floatingPoint = "-lmzx_tiny ";
ListOptions.Add(floatingPoint);
//MessageBox.Show("Radio Button 2 off");
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
else if (lmzxtinyFloatPoint.Checked == false)
{
floatingPoint = "-lmzx_tiny ";
ListOptions.Remove(floatingPoint);
string floatpoint = string.Join("", ListOptions.ToArray());
textBox1.Text = floatpoint;
}
}
private void radioButton5_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
//-create-app
if (checkBox3.Checked)
{
string createApp = "-create-app ";
ListOptions.Add(createApp);
//MessageBox.Show("Radio Button 2 off");
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
textBox5.Enabled = true;
button12.Enabled = true;
button13.Enabled = false;
}
else if (checkBox3.Checked == false)
{
string createApp = "-create-app ";
ListOptions.Remove(createApp);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
textBox5.Enabled = false;
}
}
//open file button
private void button7_Click(object sender, EventArgs e)
{
// Show the dialog and get result.
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//MessageBox.Show("holy moley");
//fileName = openFileDialog1.FileName;
fileName = openFileDialog1.SafeFileName;
textBox4.Text = fileName;
button8.Enabled = true;
}
}
private void button8_Click(object sender, EventArgs e)
{
//add file name
string file = fileName + " ";
ListOptions.Add(file);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
textBox4.Enabled = false;
textBox1.Enabled = true;
button7.Enabled = true;//open file button
button8.Enabled = false;
button9.Enabled = true;
}
private void button9_Click(object sender, EventArgs e)
{
//remove file name
button8.Enabled = false;
button9.Enabled = false;
textBox4.Text = "";
string file = fileName + " ";
ListOptions.Remove(file);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
textBox4.Enabled = true;
button7.Enabled = false;//open file button
button8.Enabled = true;
button9.Enabled = false;
//textBox1.Enabled = false;
}
private void button10_Click(object sender, EventArgs e)
{
zccvariables.restartForm1 = true;
Form1 startOver = (Form1)Application.OpenForms["Form1"];
startOver.Show();
this.Close();
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
button12.Enabled = true;
button13.Enabled = true;
/*
// Show the dialog and get result.
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//MessageBox.Show("holy moley");
//fileName = openFileDialog1.FileName;
fileName = openFileDialog1.SafeFileName;
textBox4.Text = fileName;
button8.Enabled = true;
button9.Enabled = true;
}
*/
}
private void button12_Click(object sender, EventArgs e)
{
if (textBox5.Text == "")
{
button12.Enabled = true;
button13.Enabled = false;
}
else
{
outputFile = textBox5.Text;
string file = "-o " + outputFile + " ";
ListOptions.Add(file);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
button12.Enabled = false;
button13.Enabled = true;
textBox4.Enabled = true;
textBox6.Enabled = true;
//button12.Enabled = false;
textBox5.Enabled = false;
button8.Enabled = true;
button7.Enabled = true;
}
}
private void button13_Click(object sender, EventArgs e)
{
textBox5.Text = "";
string file = "-o " + outputFile + " ";
ListOptions.Remove(file);
string create = string.Join("", ListOptions.ToArray());
textBox1.Text = create;
button12.Enabled = true;
button13.Enabled = false;
textBox5.Enabled = true;
}
private void radioButton12_CheckedChanged(object sender, EventArgs e)
{
}
private void media_device_LNDOS_CheckedChanged(object sender, EventArgs e)
{
if (media_device_LNDOS.Checked)
{
string nodosLibrary = "-lndos ";
ListOptions.Add(nodosLibrary);
//MessageBox.Show("Radio Button 2 off");
string nodos = string.Join("", ListOptions.ToArray());
textBox1.Text = nodos;
panel2.BackColor = Color.CadetBlue;
panel2.Enabled = true;
noFloatPoint.ForeColor = Color.Black;
lmFloatPoint.ForeColor = Color.Black;
lmzxFloatPoint.ForeColor = Color.Black;
lmzxtinyFloatPoint.ForeColor = Color.Black;
panel8.Enabled = false;
panel6.Enabled = true;
panel7.Enabled = true;
panel8.BackColor = Color.LightGray;
panel6.BackColor = Color.CadetBlue;
panel7.BackColor = Color.CadetBlue;
if (zccvariables.sdcc_compiler == true)
{
panel10.BackColor = Color.CadetBlue;
panel10.Enabled = true;
f_signed_char.Enabled = true;
f_signed_char.Checked = false;
}
if (zccvariables.sdcc_compiler == false)
{
panel10.BackColor = Color.LightGray;
panel10.Enabled = false;
f_signed_char.Enabled = false;
f_signed_char.Checked = false;
}
}
else if (media_device_LNDOS.Checked == false)
{
string nodosLibrary = "-lndos ";
ListOptions.Remove(nodosLibrary);
string nodos = string.Join("", ListOptions.ToArray());
textBox1.Text = nodos;
panel2.BackColor = Color.LightBlue;
panel2.Enabled = false;
panel6.BackColor = Color.LightBlue;
panel7.BackColor = Color.LightBlue;
panel5.BackColor = Color.LightBlue;
if (zccvariables.sdcc_compiler == true)
{
panel10.BackColor = Color.CadetBlue;
panel10.Enabled = true;
}
if (zccvariables.sdcc_compiler == false)
{
panel10.BackColor = Color.LightGray;
panel10.Enabled = false;
}
}
//textBox1.ShortcutsEnabled = true;
textBox1.Enabled = false;
checkBox3.Enabled = true;
checkBox3.Checked = false;
button7.Enabled = true;//open file button
if (newLibrary.Checked == true)
{
button18.Enabled = true;
button19.Enabled = false;
trackBar1.Enabled = true;
textBox7.Enabled = true;
}
if (newLibrary.Checked == false)
{
button18.Enabled = true;
button19.Enabled = false;
trackBar1.Enabled = true;
textBox7.Enabled = true;
}
}
private void media_device_DPLUS_CheckedChanged(object sender, EventArgs e)
{
if (media_device_DPLUS.Checked)
{
string nodosLibrary = "-DPLUS3 ";
ListOptions.Add(nodosLibrary);
MessageBox.Show("Not Yet Implemented. Sorry \nChoose another Media");
string nodos = string.Join("", ListOptions.ToArray());
textBox1.Text = nodos;
}
else if (media_device_DPLUS.Checked == false)
{
string nodosLibrary = "-DPLUS3 ";
ListOptions.Remove(nodosLibrary);
string nodos = string.Join("", ListOptions.ToArray());
textBox1.Text = nodos;
}
//textBox1.ShortcutsEnabled = true;
textBox1.Enabled = true;
checkBox3.Enabled = true;
checkBox3.Checked = false;
button7.Enabled = true;//open file button
if (newLibrary.Checked == true)
{
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
}
if (newLibrary.Checked == false)
{
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
}
}
private void media_device_LP3DOS_CheckedChanged(object sender, EventArgs e)
{
if (media_device_LP3DOS.Checked)
{
string nodosLibrary = "-lp3dos ";
ListOptions.Add(nodosLibrary);
MessageBox.Show("Not Yet Implemented. Sorry \nChoose another Media");
string nodos = string.Join("", ListOptions.ToArray());
textBox1.Text = nodos;
}
else if (media_device_LP3DOS.Checked == false)
{
string nodosLibrary = "-lp3dos ";
ListOptions.Remove(nodosLibrary);
string nodos = string.Join("", ListOptions.ToArray());
textBox1.Text = nodos;
}
//textBox1.ShortcutsEnabled = true;
textBox1.Enabled = true;
checkBox3.Enabled = true;
checkBox3.Checked = false;
button7.Enabled = true;//open file button
if (newLibrary.Checked == true)
{
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
}
if (newLibrary.Checked == false)
{
button18.Enabled = false;
button19.Enabled = false;
trackBar1.Enabled = false;
textBox7.Enabled = false;
}
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void button16_Click(object sender, EventArgs e)
{
if (textBox5.Text == "")
{
button16.Enabled = false;
button15.Enabled = false;
}
manualEntry = textBox6.Text;
string manual = manualEntry + " ";
string create = string.Join("", manual.ToArray());
ListOptions.Add(create);
string manualEntry1 = string.Join("", ListOptions.ToArray());
textBox1.Text = manualEntry1;
textBox1.Enabled = true;
button15.Enabled = true;
button16.Enabled = false;
textBox6.Enabled = false;
}
private void button15_Click(object sender, EventArgs e)
{
//textBox6
string remove_manual = manualEntry + " ";
ListOptions.Remove(remove_manual);
string bob = string.Join("", ListOptions.ToArray());
textBox1.Text = bob;
// form maintainence
textBox6.Text = "";
textBox6.Enabled = true;
button15.Enabled = false;
button16.Enabled = true;
//textBox1.Enabled = false;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
textBox7.Text = trackBar1.Value.ToString();
textBox8.Text = trackBar1.Value.ToString();
zorgValue = trackBar1.Value;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
int temp;
if (!int.TryParse(textBox7.Text, out temp))//check to see if letters
{
if (textBox7.TextLength > 0)
{
textBox7.Text = textBox7.Text.Substring(0, textBox7.Text.Length - 1);
textBox7.Focus();
textBox7.SelectionStart = textBox7.Text.Length;
}
}
//if (int.Parse(textBox7.Text, out number))
if (int.TryParse(textBox7.Text, out temp))
{
if (temp > 65535)
{
//too high
MessageBox.Show("The ZORG setting is too high");
temp = 65535;
textBox7.Text = "65535";
textBox7.Focus();
textBox7.SelectionStart = textBox7.Text.Length;
}
if (temp < 0)
{
//too low
MessageBox.Show("The ZORG setting is too low");
temp = 0;
textBox7.Text = "0";
textBox7.Focus();
textBox7.SelectionStart = textBox7.Text.Length;
}
else
{
// just right
temp = int.Parse(textBox7.Text);
trackBar1.Value = int.Parse(temp.ToString());
textBox8.Text = textBox7.Text;
zorgValue = temp;
}
}
}
private void button18_Click(object sender, EventArgs e)
{
string zorg = "-zorg=";
ListOptions.Add(zorg + zorgValue + " ");
//MessageBox.Show("Radio Button 2 off");
string zorgOption = string.Join("", ListOptions.ToArray());
textBox1.Text = zorgOption;
button18.Enabled = false;
button19.Enabled = true;
textBox7.Enabled = false;
trackBar1.Enabled = false;
reset_zorg.Enabled = false;
}
private void button19_Click(object sender, EventArgs e)
{
string zorg = "-zorg=";
ListOptions.Remove(zorg + zorgValue + " ");
//MessageBox.Show("Radio Button 2 off");
string zorgOption = string.Join("", ListOptions.ToArray());
textBox1.Text = zorgOption;
button18.Enabled = true;
button19.Enabled = false;
textBox7.Enabled = true;
trackBar1.Enabled = true;
reset_zorg.Enabled = true;
}
private void reset_zorg_Click(object sender, EventArgs e)
{
#region Luxor ABC80
if (zccvariables.machine == "abc80")
{
zorgValue = 49200;
}
#endregion
#region Luxor ABC800
if (zccvariables.machine == "abc800")
{
zorgValue = 40000;
}
#endregion
#region Jupiter ACE
if (zccvariables.machine == "ace")
{
zorgValue = 24000;
}
#endregion
#region Mattel Aquarius
if (zccvariables.machine == "aquarius")
{
zorgValue = 16384;
}
#endregion
#region Commodore 128
if (zccvariables.machine == "c128")
{
zorgValue = 0;
}
#endregion
#region Philips Videopac C7420
if (zccvariables.machine == "c7420")
{
zorgValue = 0;
}
#endregion
#region CPC
if (zccvariables.machine == "cpc")
{
zorgValue = 1024;
}
#endregion
#region CP/M
if (zccvariables.machine == "cpm")
{
zorgValue = 0;
}
#endregion
#region Embedded
if (zccvariables.machine == "embedded")
{
zorgValue = 0;
}
#endregion
#region Enterprise 64/128 Platform
if (zccvariables.machine == "enterprise")
{
zorgValue = 0;
}
#endregion
#region Galaksija
if (zccvariables.machine == "gal")
{
zorgValue = 0;
}
#endregion
#region Lambda 8300
//Lambda 8300
//improved chinese clone of the ZX81
if (zccvariables.machine == "lambda")
{
zorgValue = 16389;
}
#endregion
#region Camputers Lynx
if (zccvariables.machine == "lynx")
{
zorgValue = 32768;
}
#endregion
#region Sord M5
if (zccvariables.machine == "m5")
{
zorgValue = 29696;
}
#endregion
#region CCE MC-1000
if (zccvariables.machine == "mc1000")
{
zorgValue = 0;
}
#endregion
#region MSX
if (zccvariables.machine == "msx")
{
zorgValue = 32768;
}
#endregion
#region Memotech MTX
if (zccvariables.machine == "mtx")
{
zorgValue = 0;
}
#endregion
#region NASCOM 1 & 2
if (zccvariables.machine == "nascom")
{
zorgValue = 1024;
}
#endregion
#region Amstrad NC
if (zccvariables.machine == "nc")
{
zorgValue = 1024;
}
#endregion
#region Grundy Newbrain
if (zccvariables.machine == "newbrain")
{
zorgValue = 20000;
}
#endregion
#region Old School Computer Architecture
if (zccvariables.machine == "osca")
{
zorgValue = 32767;
}
#endregion
#region Sharp OZ-700
if (zccvariables.machine == "oz")
{
zorgValue = 0;
}
#endregion
#region Philips P2000
if (zccvariables.machine == "p2000")
{
zorgValue = 0;
}
#endregion
#region NEC PC-6001
if (zccvariables.machine == "pc6001")
{
zorgValue = 0;
}
#endregion
#region Peters Plus Sprinter
if (zccvariables.machine == "pps")
{
zorgValue = 0;
}
#endregion
#region RCMX000
if (zccvariables.machine == "rcmx000")
{
zorgValue = 0;
}
#endregion
#region Xircom REX 6000
if (zccvariables.machine == "rex")
{
zorgValue = 0;
}
#endregion
#region SAM Coupe
if (zccvariables.machine == "sam")
{
zorgValue = 32768;
}
#endregion
#region SEGA SC-3000
if (zccvariables.machine == "sc3000")
{
zorgValue = 40000;
}
#endregion
#region SMS
if (zccvariables.machine == "sms")
{
zorgValue = 0;
}
#endregion
#region S-OS (The Sentinel)
if (zccvariables.machine == "sos")
{
zorgValue = 3000;
}
#endregion
#region Sorcerer Exidy
if (zccvariables.machine == "srr")
{
zorgValue = 0;
}
#endregion
#region Spectravideo SVI
if (zccvariables.machine == "svi")
{
zorgValue = 0;
}
#endregion
#region Texas Instruments TI8X
if (zccvariables.machine == "ti8x")
{
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI82
if (zccvariables.machine == "ti82")
{
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI83
if (zccvariables.machine == "ti83")
{
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI85
if (zccvariables.machine == "ti85")
{
zorgValue = 24576;
}
#endregion
#region Texas Instruments TI86
if (zccvariables.machine == "ti86")
{
zorgValue = 24576;
}
#endregion
#region trs80 ** & EG2000
if (zccvariables.machine == "trs80")
{
zorgValue = 20992;
}
#endregion
#region ts2068
if (zccvariables.machine == "ts2068")
{
zorgValue = 32768;
}
#endregion
#region vg5k
//vg5000
if (zccvariables.machine == "vg5k")
{
zorgValue = 20480;
}
#endregion
#region vz
if (zccvariables.machine == "vz")
{
zorgValue = 0;
}
#endregion
#region x1 **
if (zccvariables.machine == "x1")
{
zorgValue = 0;
}
#endregion
#region Canon X07 **
if (zccvariables.machine == "x07")
{
zorgValue = 1024;
}
#endregion
#region Cambridge z88 **
if (zccvariables.machine == "z88")
{
zorgValue = 16389;
}
#endregion
#region zcc **
if (zccvariables.machine == "zcc")
{
zorgValue = 0;
}
#endregion
#region zx spectrum
if (zccvariables.machine == "zx")
{
zorgValue = 32768;
}
#endregion
#region zx80
if (zccvariables.machine == "zx80")
{
zorgValue = 16389;
}
#endregion
#region zx81
if (zccvariables.machine == "zx81")
{
zorgValue = 16389;
}
#endregion
trackBar1.Value = zorgValue;
textBox7.Text = zorgValue.ToString();
}
private void f_signed_char_CheckedChanged(object sender, EventArgs e)
{
if (f_signed_char.Checked)
{
string signed_char = "--fsigned-char ";
ListOptions.Add(signed_char);
string signed = string.Join("", ListOptions.ToArray());
textBox1.Text = signed;
}
else if (f_signed_char.Checked == false)
{
string signed_char = "--fsigned-char ";
ListOptions.Remove(signed_char);
string signed = string.Join("", ListOptions.ToArray());
textBox1.Text = signed;
}
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
if (textBox6.Text != "")
{
button16.Enabled = true;
}
else
{
button16.Enabled = false;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimeManager : MonoBehaviour
{
public float countdown = 3;
public static TimeManager Instance;
public delegate void CountdownAction(float count);
public CountdownAction countdownAction;
private void Awake()
{
Instance = this;
}
private void Update()
{
countdown -= Time.deltaTime;
countdownAction?.Invoke(countdown);
if (countdown <= 0)
{
switch (GameManager.Instance.gameState)
{
case GameState.Start:
GameStart();
break;
case GameState.Looping:
countdown = 25;
break;
case GameState.Counting:
GameEnd();
break;
}
}
}
private void GameStart()
{
GameManager.Instance.GameLoop();
}
private void GameEnd()
{
GameManager.Instance.GameEnd();
}
public void ResetEndTimer()
{
countdown = 3f;
}
}
|
using Newtonsoft.Json;
namespace Records.Units
{
public class UnitRecord
{
[JsonProperty("id")]
public int Id;
[JsonProperty("name")]
public string Name;
[JsonProperty("description")]
public string Description;
[JsonProperty("race")]
public int Race;
[JsonProperty("speed")]
public int Speed;
[JsonProperty("levels")]
public UnitLevelRecord[] Levels;
}
}
|
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Interfaces;
using Fingo.Auth.Domain.CustomData.Services.Interfaces;
using Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces;
namespace Fingo.Auth.Domain.CustomData.Factories.Implementation
{
public class AddProjectCustomDataToProjectFactory : IAddProjectCustomDataToProjectFactory
{
private readonly IEventBus _eventBus;
private readonly ICustomDataJsonConvertService _jsonConvertService;
private readonly IProjectRepository _projectRepository;
public AddProjectCustomDataToProjectFactory(IProjectRepository projectRepository ,
ICustomDataJsonConvertService jsonConvertService , IEventBus eventBus)
{
_eventBus = eventBus;
_jsonConvertService = jsonConvertService;
_projectRepository = projectRepository;
}
public IAddProjectCustomDataToProject Create()
{
return new AddProjectCustomDataToProject(_projectRepository , _jsonConvertService , _eventBus);
}
}
}
|
// --------------------------------------------------------------------
// © Copyright 2013 Hewlett-Packard Development Company, L.P.
//--------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using HP.LR.VuGen.Snapshots.WebSnapshotBrowserControl.ViewEditors;
using HP.LR.VuGen.XmlViewer;
using HP.Utt.Common;
using HP.Utt.UttCore;
using HP.Utt.UttDialog;
namespace HttpXmlViewAddin
{
public class HighlightCommand : UttBaseCommand
{
public override void Run()
{
string clipboardText = Clipboard.GetText();
if (clipboardText == null)
{
clipboardText = String.Empty;
}
InputDialog dialog = new InputDialog("Enter text", clipboardText, "Enter the value to search");
if (dialog.ShowDialog() == CustomDialogResult.Ok)
{
XmlEditor editor = this.Owner as XmlEditor;
if (editor == null)
return;
SingleDirectionData currentData = editor.SingleDirectionData;
currentData.ShowAttributes = true;
currentData.ShowValues = true;
string tempXPath = string.Format("//*[text() = \"{0}\"]", dialog.InputString);
if (XmlUtils.IsXPathValid(tempXPath))
{
XPathData xpath = new XPathData();
xpath.XPath = tempXPath;
currentData.HighlightedXPath = xpath;
}
}
}
}
}
|
using AutoMapper;
using GardenControlCore.Enums;
using GardenControlCore.Models;
using GardenControlCore.Scheduler;
using GardenControlRepositories.Entities;
using GardenControlRepositories.Interfaces;
using GardenControlServices.Interfaces;
using Innovative.SolarCalculator;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenControlServices
{
public class ScheduleService : IScheduleService
{
private IAppSettingsService _appSettingsService { get; init; }
private IControlDeviceRepository _controlDeviceRepository { get; init; }
private ILogger<ScheduleService> _logger { get; init; }
private IScheduleRepository _scheduleRepository { get; init; }
private IMapper _mapper { get; init; }
private RelayService _relayService { get; init; }
private DS18B20Service _ds18b20Service { get; init; }
private FloatSensorService _floatSensorService{ get; init; }
private IMeasurementService _measurementService { get; init; }
private List<TaskAction> _TaskActionsList { get; init; }
public ScheduleService(IAppSettingsService appSettingsService,
IControlDeviceRepository controlDeviceRepository,
ILogger<ScheduleService> logger,
IScheduleRepository scheduleRepository,
IMapper mapper,
RelayService relayService,
DS18B20Service dS18B20Service,
FloatSensorService floatSensorService,
IMeasurementService measurementService)
{
_appSettingsService = appSettingsService;
_controlDeviceRepository = controlDeviceRepository;
_logger = logger;
_scheduleRepository = scheduleRepository;
_mapper = mapper;
_relayService = relayService;
_ds18b20Service = dS18B20Service;
_floatSensorService = floatSensorService;
_measurementService = measurementService;
_TaskActionsList = new List<TaskAction>
{
new TaskAction
{
TaskActionId = TaskActionId.RelayOn,
Name = "Relay On",
DeviceType = DeviceType.Relay
},
new TaskAction
{
TaskActionId = TaskActionId.RelayOff,
Name = "Relay Off",
DeviceType = DeviceType.Relay
},
new TaskAction
{
TaskActionId = TaskActionId.RelayToggle,
Name = "Relay Toggle",
DeviceType = DeviceType.Relay
},
new TaskAction
{
TaskActionId = TaskActionId.DS18B20Reading,
Name = "DS18B20 Measurement",
DeviceType = DeviceType.DS18B20
},
new TaskAction
{
TaskActionId = TaskActionId.FloatSensorStateReading,
Name = "Float Sensor State",
DeviceType = DeviceType.FloatSensor
}
};
}
#region Schedule
public async Task DeleteScheduleAsync(int id)
{
await _scheduleRepository.DeleteScheduleAsync(id);
}
public async Task<IEnumerable<Schedule>> GetAllSchedulesAsync()
{
var scheduleEntities = await _scheduleRepository.GetAllSchedulesAsync();
return _mapper.Map<IEnumerable<Schedule>>(scheduleEntities);
}
public async Task<IEnumerable<Schedule>> GetDueSchedulesAsync()
{
return _mapper.Map<IEnumerable<Schedule>>(await _scheduleRepository.GetDueSchedulesAsync());
}
public async Task<Schedule> GetScheduleAsync(int id)
{
return _mapper.Map<Schedule>(await _scheduleRepository.GetScheduleByIdAsync(id));
}
public async Task<Schedule> InsertScheduleAsync(Schedule schedule)
{
if (schedule == null)
throw new ArgumentNullException(nameof(schedule));
// TODO: Return a useful validation message
if (!ScheduleIsValid(schedule))
throw new Exception();
var newScheduleEntity = new ScheduleEntity
{
Name = schedule.Name,
IsActive = schedule.IsActive,
TriggerTypeId = schedule.TriggerType,
TriggerTimeOfDay = schedule.TriggerTimeOfDay,
TriggerOffsetAmount = schedule.TriggerOffsetAmount,
TriggerOffsetAmountTimeIntervalUnitId = schedule.TriggerOffsetAmountTimeIntervalUnit,
IntervalAmount = schedule.IntervalAmount,
IntervalAmountTimeIntervalUnitId = schedule.IntervalAmountTimeIntervalUnit,
ScheduleTasks = new List<ScheduleTaskEntity>()
};
foreach (var task in schedule.ScheduleTasks)
{
var controlDevice = await _controlDeviceRepository.GetDeviceAsync(task.ControlDevice.ControlDeviceId);
newScheduleEntity.ScheduleTasks.Add(new ScheduleTaskEntity
{
Schedule = newScheduleEntity,
ControlDevice = controlDevice,
IsActive = task.IsActive,
TaskActionId = task.TaskAction.TaskActionId
});
}
newScheduleEntity.NextRunDateTime = await CalculateNextRunTime(schedule);
Schedule insertedSchedule;
try
{
newScheduleEntity = await _scheduleRepository.InsertScheduleAsync(newScheduleEntity);
insertedSchedule = _mapper.Map<Schedule>(newScheduleEntity);
}
catch (Exception ex)
{
_logger.LogError($"Error inserting Schedule: {ex.Message}");
throw;
}
return insertedSchedule;
}
public async Task<Schedule> UpdateScheduleAsync(Schedule schedule)
{
if (schedule == null)
throw new ArgumentNullException(nameof(schedule));
// TODO: Return a useful validation message
if (!ScheduleIsValid(schedule))
throw new Exception();
// get the existing schedule entity from the database, including tasks
var scheduleEntity = await _scheduleRepository.GetScheduleByIdAsync(schedule.ScheduleId);
//TODO: Better exception
if (scheduleEntity == null)
throw new Exception();
scheduleEntity.Name = schedule.Name;
scheduleEntity.IsActive = schedule.IsActive;
scheduleEntity.TriggerTypeId = schedule.TriggerType;
scheduleEntity.TriggerTimeOfDay = schedule.TriggerTimeOfDay;
scheduleEntity.TriggerOffsetAmount = schedule.TriggerOffsetAmount;
scheduleEntity.TriggerOffsetAmountTimeIntervalUnitId = schedule.TriggerOffsetAmountTimeIntervalUnit;
scheduleEntity.IntervalAmount = schedule.IntervalAmount;
scheduleEntity.IntervalAmountTimeIntervalUnitId = schedule.IntervalAmountTimeIntervalUnit;
scheduleEntity.NextRunDateTime = await CalculateNextRunTime(schedule);
// Update the schedule tasks
// remove any tasks from the entity that are not present in the schedule object as they've been deleted
foreach(var deletedTask in scheduleEntity.ScheduleTasks.Where(x => !schedule.ScheduleTasks.Select(y => y.ScheduleTaskId).ToList().Contains(x.ScheduleTaskId)).ToList())
{
scheduleEntity.ScheduleTasks.Remove(deletedTask);
}
// add any new tasks that are in the schedule but not in the scheduleEntity
foreach(var newTask in schedule.ScheduleTasks.Where(x => !scheduleEntity.ScheduleTasks.Select(y => y.ScheduleTaskId).ToList().Contains(x.ScheduleTaskId)).ToList())
{
scheduleEntity.ScheduleTasks.Add(new ScheduleTaskEntity
{
ControlDevice = await _controlDeviceRepository.GetDeviceAsync(newTask.ControlDevice.ControlDeviceId),
TaskActionId = newTask.TaskAction.TaskActionId,
IsActive = newTask.IsActive,
Schedule = scheduleEntity
});
}
// check each task which has an id match between object and entity, and update the values
foreach(var taskEntity in scheduleEntity.ScheduleTasks.Where(x => schedule.ScheduleTasks.Where(y => x.ScheduleTaskId == y.ScheduleTaskId).Any()))
{
var task = schedule.ScheduleTasks.Where(x => x.ScheduleTaskId == taskEntity.ScheduleTaskId).FirstOrDefault();
taskEntity.ControlDevice = await _controlDeviceRepository.GetDeviceAsync(task.ControlDevice.ControlDeviceId);
taskEntity.TaskActionId = task.TaskAction.TaskActionId;
taskEntity.IsActive = task.IsActive;
}
try
{
await _scheduleRepository.UpdateScheduleAsync(scheduleEntity);
}
catch (Exception ex)
{
_logger.LogError($"Error updating Schedule: {schedule.ScheduleId}, {ex.Message}");
throw;
}
return _mapper.Map<Schedule>(scheduleEntity);
}
public async Task UpdateScheduleNextRunTimeAsync(int id, DateTime nextRunDateTime)
{
await _scheduleRepository.UpdateScheduleNextRunTimeAsync(id, nextRunDateTime);
}
public async Task RunPendingSchedules()
{
var pendingSchedules = await GetDueSchedulesAsync();
if (!pendingSchedules.Any())
return;
foreach (var schedule in pendingSchedules)
{
await RunSchedule(schedule);
}
}
public async Task RunSchedule(Schedule schedule)
{
if (!schedule.ScheduleTasks.Where(x => x.IsActive).Any())
return;
foreach (var task in schedule.ScheduleTasks.Where(x => x.IsActive))
{
await PerformScheduleTaskAction(task.ScheduleTaskId);
}
// once tasks are completed, update the next run time value for the schedule
await UpdateScheduleNextRunTimeAsync(schedule.ScheduleId, await CalculateNextRunTime(schedule));
}
#endregion
#region Schedule Tasks
public async Task<ScheduleTask> InsertScheduleTaskAsync(ScheduleTask scheduleTask)
{
if (scheduleTask == null)
throw new ArgumentNullException(nameof(scheduleTask));
var scheduleEnity = await _scheduleRepository.GetScheduleByIdAsync(scheduleTask.ScheduleId);
if (scheduleEnity == null)
throw new InvalidOperationException();
var controlDeviceEntity = await _controlDeviceRepository.GetDeviceAsync(scheduleTask.ControlDevice.ControlDeviceId);
if (controlDeviceEntity == null)
throw new InvalidOperationException();
if (!_TaskActionsList.Select(ta => ta.TaskActionId).ToList().Contains(scheduleTask.TaskAction.TaskActionId))
throw new InvalidOperationException();
var scheduleTaskEntity = new ScheduleTaskEntity {
Schedule = scheduleEnity,
ControlDevice = controlDeviceEntity,
TaskActionId = scheduleTask.TaskAction.TaskActionId,
IsActive = scheduleTask.IsActive
};
try
{
await _scheduleRepository.InsertScheduleTaskAsync(scheduleTaskEntity);
}
catch (Exception)
{
throw;
}
return _mapper.Map<ScheduleTask>(scheduleTaskEntity);
}
public async Task<IEnumerable<ScheduleTask>> GetAllScheduleTasksAsync()
{
return _mapper.Map<IEnumerable<ScheduleTask>>(await _scheduleRepository.GetAllScheduleTasksAsync());
}
public async Task<IEnumerable<ScheduleTask>> GetScheduleTasksAsync(int scheduleId)
{
return _mapper.Map<IEnumerable<ScheduleTask>>(await _scheduleRepository.GetScheduleTasksAsync(scheduleId));
}
public async Task<ScheduleTask> GetScheduleTaskAsync(int id)
{
return _mapper.Map<ScheduleTask>(await _scheduleRepository.GetScheduleTaskByIdAsync(id));
}
public async Task<ScheduleTask> UpdateScheduleTaskAsync(ScheduleTask scheduleTask)
{
if (scheduleTask == null)
throw new ArgumentNullException(nameof(scheduleTask));
// get the existing schedule task entity from the database
var scheduleTaskEntity = await _scheduleRepository.GetScheduleTaskByIdAsync(scheduleTask.ScheduleTaskId);
if (scheduleTaskEntity == null)
throw new Exception();
scheduleTaskEntity.TaskActionId = scheduleTask.TaskAction.TaskActionId;
scheduleTaskEntity.IsActive = scheduleTask.IsActive;
return _mapper.Map<ScheduleTask>(scheduleTaskEntity);
}
public async Task DeleteScheduleTaskAsync(int id)
{
await _scheduleRepository.DeleteScheduleTaskAsync(id);
}
#endregion
#region Validate Schedule
private bool ScheduleIsValid(Schedule schedule)
{
var isValid = true;
switch (schedule.TriggerType)
{
case GardenControlCore.Enums.TriggerType.TimeOfDay:
if (!schedule.TriggerTimeOfDay.HasValue)
isValid = false;
break;
case GardenControlCore.Enums.TriggerType.Interval:
if (!schedule.IntervalAmount.HasValue)
isValid = false;
if (!schedule.IntervalAmountTimeIntervalUnit.HasValue)
isValid = false;
// Do not allow offsets for interval triggers
if (schedule.TriggerOffsetAmount.HasValue)
isValid = false;
break;
case GardenControlCore.Enums.TriggerType.Sunrise:
case GardenControlCore.Enums.TriggerType.Sunset:
// TODO: Check that a lat/long is set
break;
}
// trigger offset must have a specified interval unit
if (schedule.TriggerOffsetAmount.HasValue && !schedule.TriggerOffsetAmountTimeIntervalUnit.HasValue)
isValid = false;
// interval amount must have a specified interval unit
if (schedule.IntervalAmount.HasValue && !schedule.IntervalAmountTimeIntervalUnit.HasValue)
isValid = false;
return isValid;
}
#endregion
#region ScheduleActions
public async Task PerformScheduleTaskAction(int id)
{
var scheduleTask = await GetScheduleTaskAsync(id);
if (scheduleTask == null)
throw new Exception();
switch (scheduleTask.TaskAction.TaskActionId)
{
case TaskActionId.RelayOn:
await RelayOnTask(scheduleTask.ControlDevice.ControlDeviceId);
break;
case TaskActionId.RelayOff:
await RelayOffTask(scheduleTask.ControlDevice.ControlDeviceId);
break;
case TaskActionId.RelayToggle:
await RelayToggleTask(scheduleTask.ControlDevice.ControlDeviceId);
break;
case TaskActionId.DS18B20Reading:
await DS18B20ReadingTask(scheduleTask.ControlDevice.ControlDeviceId);
break;
case TaskActionId.FloatSensorStateReading:
await FloatSensorReadingTask(scheduleTask.ControlDevice.ControlDeviceId);
break;
}
}
/// <summary>
/// Caclulates the next runtime for a task. Should not be used to get the next planned task run time.
/// </summary>
/// <param name="schedule"></param>
/// <returns></returns>
public async Task<DateTime> CalculateNextRunTime(Schedule schedule)
{
if (schedule == null)
throw new ArgumentNullException();
var nextRunTime = new DateTime();
var currentDateTime = DateTime.Now;
AppSetting latitude = null;
AppSetting longitude = null;
SolarTimes solarTimes = null;
switch (schedule.TriggerType)
{
case TriggerType.TimeOfDay:
nextRunTime = currentDateTime.Date
.AddHours(schedule.TriggerTimeOfDay.Value.Hour)
.AddMinutes(schedule.TriggerTimeOfDay.Value.Minute);
if (nextRunTime < currentDateTime)
{
// Already passed trigger time for today, so set for tomorrow
nextRunTime = nextRunTime.AddDays(1);
}
break;
case TriggerType.Interval:
if(schedule.NextRunDateTime != DateTime.MinValue && schedule.NextRunDateTime <= currentDateTime)
{
nextRunTime = GetAdjustedTime(schedule.NextRunDateTime, schedule.IntervalAmount.Value, schedule.IntervalAmountTimeIntervalUnit.Value);
// next run time is still in the past, so set to now, plus interval amount
if (nextRunTime < currentDateTime)
nextRunTime = GetAdjustedTime(currentDateTime, schedule.IntervalAmount.Value, schedule.IntervalAmountTimeIntervalUnit.Value);
}
else if(schedule.NextRunDateTime > currentDateTime)
{
nextRunTime = schedule.NextRunDateTime;
}
else
{
nextRunTime = GetAdjustedTime(currentDateTime, schedule.IntervalAmount.Value, schedule.IntervalAmountTimeIntervalUnit.Value);
}
break;
case TriggerType.Sunrise:
latitude = await _appSettingsService.GetAppSettingByKeyAsync("LocationLatitude");
longitude = await _appSettingsService.GetAppSettingByKeyAsync("LocationLongitude");
if(string.IsNullOrWhiteSpace(latitude.Value) || string.IsNullOrWhiteSpace(longitude.Value))
{
return DateTime.Now;
}
// Get Sunrise for today
solarTimes = new SolarTimes(currentDateTime, double.Parse(latitude.Value), double.Parse(longitude.Value));
// If Sunrise today is in the past
// Get Sunrise for tomorrow and set that value
if (solarTimes.Sunrise < currentDateTime)
solarTimes = new SolarTimes(currentDateTime.AddDays(1), double.Parse(latitude.Value), double.Parse(longitude.Value));
nextRunTime = GetAdjustedTime(solarTimes.Sunrise, (schedule.TriggerOffsetAmount ?? 0), (schedule.TriggerOffsetAmountTimeIntervalUnit ?? TimeIntervalUnit.Seconds));
break;
case TriggerType.Sunset:
latitude = await _appSettingsService.GetAppSettingByKeyAsync("LocationLatitude");
longitude = await _appSettingsService.GetAppSettingByKeyAsync("LocationLongitude");
if (string.IsNullOrWhiteSpace(latitude.Value) || string.IsNullOrWhiteSpace(longitude.Value))
{
return DateTime.Now;
}
// Get Sunset for today
solarTimes = new SolarTimes(currentDateTime, double.Parse(latitude.Value), double.Parse(longitude.Value));
// If Sunset today is in the past
// Get Sunset for tomorrow and set that value
if (solarTimes.Sunset < currentDateTime)
solarTimes = new SolarTimes(currentDateTime.AddDays(1), double.Parse(latitude.Value), double.Parse(longitude.Value));
nextRunTime = GetAdjustedTime(solarTimes.Sunset, (schedule.TriggerOffsetAmount ?? 0), (schedule.TriggerOffsetAmountTimeIntervalUnit ?? TimeIntervalUnit.Seconds));
break;
}
// Adjust next run time for any offsets
if (schedule.TriggerOffsetAmount.HasValue)
{
nextRunTime = GetAdjustedTime(nextRunTime, schedule.TriggerOffsetAmount.Value, schedule.TriggerOffsetAmountTimeIntervalUnit.Value);
}
return nextRunTime;
}
private DateTime GetAdjustedTime(DateTime inTime, int interval, TimeIntervalUnit timeInterval)
{
var outTime = inTime;
switch (timeInterval)
{
case TimeIntervalUnit.Seconds:
outTime = outTime.AddSeconds(interval);
break;
case TimeIntervalUnit.Minutes:
outTime = outTime.AddMinutes(interval);
break;
case TimeIntervalUnit.Hours:
outTime = outTime.AddHours(interval);
break;
case TimeIntervalUnit.Days:
outTime = outTime.AddDays(interval);
break;
}
return outTime;
}
#endregion
#region Task Actions
private async Task RelayOnTask(int controlDeviceId)
{
await _relayService.SetRelayState(controlDeviceId, RelayState.On);
}
private async Task RelayOffTask(int controlDeviceId)
{
await _relayService.SetRelayState(controlDeviceId, RelayState.Off);
}
private async Task RelayToggleTask(int controlDeviceId)
{
await _relayService.ToggleRelayState(controlDeviceId);
}
private async Task DS18B20ReadingTask(int controlDeviceId)
{
var temperatureReading = await _ds18b20Service.GetTemperatureReading(controlDeviceId);
var measurement = new Measurement
{
ControlDeviceId = controlDeviceId,
MeasurementValue = temperatureReading.TemperatureC,
MeasurementDateTime = temperatureReading.ReadingDateTime,
MeasurementUnit = GardenControlCore.Enums.MeasurementUnit.Celcius
};
await _measurementService.InsertMeasurementAsync(measurement);
}
private async Task FloatSensorReadingTask(int controlDeviceId)
{
var floatStateReading = await _floatSensorService.GetFloatSensorState(controlDeviceId);
var measurement = new Measurement
{
ControlDeviceId = controlDeviceId,
MeasurementValue = (floatStateReading == FloatSensorState.High ? 1 : 0),
MeasurementDateTime = DateTime.Now,
MeasurementUnit = GardenControlCore.Enums.MeasurementUnit.Boolean
};
await _measurementService.InsertMeasurementAsync(measurement);
}
public List<TaskAction> GetTaskActions()
{
return _TaskActionsList;
}
#endregion
}
}
|
using System;
namespace CORE.Одномерные
{
public class Bolzano : OneDimMethod
{
public Bolzano(Function1D f, Function1D df, double eps = 1e-6, int maxIterations = 50) :
base(f, df, eps, "Метод БОЛЬЦАНО", maxIterations)
{
}
public override void Execute()
{
//Производная должна существовать для Больцано
if (Df == null) throw new ArgumentNullException(nameof(Df));
//Сбрасываем счетчик
IterationCount = 0;
//Начальный этап
var k = 1;
//Основной этап
double x, length;
do
{
x = (A + B)/2;
length = Math.Abs(B - A);
if (Df(x) > 0)
{
B = x;
}
else
{
A = x;
}
k++;
} while (((Math.Abs(Df(x)) > Eps) || (length > Eps)) && (k < MaxIterations));
x = (A + B)/2;
IterationCount += k;
Answer = x;
}
}
}
|
using ControleFinanceiro.Domain.Contracts.Repositories;
using ControleFinanceiro.Domain.Contracts.Services;
using ControleFinanceiro.Infra.Data.EF;
namespace ControleFinanceiro.Domain.Service.Services
{
public class ServicoBase<TEntity> : IServicoBase<TEntity> where TEntity : class
{
private readonly IRepositorioBase<TEntity> _repositorioBase;
private readonly EFContext _context;
public ServicoBase(IRepositorioBase<TEntity> repositorioBase, EFContext context)
{
_repositorioBase = repositorioBase;
_context = context;
}
public virtual TEntity Alterar(TEntity entity)
{
entity = _repositorioBase.Alterar(entity);
Commit();
return entity;
}
public virtual void Excluir(TEntity entity)
{
_repositorioBase.Excluir(entity);
Commit();
}
public virtual TEntity Incluir(TEntity entity)
{
entity = _repositorioBase.Incluir(entity);
Commit();
return entity;
}
public void Commit()
{
_context.SaveChanges();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Schip
{
class VideoModule
{
#region Declaracion de constantes
public enum VideoMode { Chip8Mode, SChipMode };
private const int HORZ_RES_CHIP8_MODE = 64;
private const int VERT_RES_CHIP8_MODE = 32;
private const int HORZ_RES_SCHIP_MODE = 128;
private const int VERT_RES_SCHIP_MODE = 64;
#endregion
#region Definicion de atributos
private VideoMode currentMode;
private VideoLine128[] display;
private int currentHorzRes;
private int currentVertRes;
#endregion
#region metodos getter
public VideoMode CurrentMode
{
get
{
return currentMode;
}
set
{
currentMode = value;
switch (value)
{
case VideoMode.Chip8Mode:
currentHorzRes = HORZ_RES_CHIP8_MODE;
currentVertRes = VERT_RES_CHIP8_MODE;
break;
case VideoMode.SChipMode:
currentHorzRes = HORZ_RES_SCHIP_MODE;
currentVertRes = VERT_RES_SCHIP_MODE;
break;
}
}
}
public int CurrentHorzRes { get { return currentHorzRes; } }
public int CurrentVertRes { get { return currentVertRes; } }
public VideoLine128[] Display { get { return display; } }
#endregion
#region Constructores
public VideoModule()
{
CurrentMode = VideoMode.Chip8Mode;
display = new VideoLine128[VERT_RES_SCHIP_MODE];
//Crear cada una de las lineas de video
for (int i = 0; i < display.Length; i++)
display[i] = new VideoLine128();
}
#endregion
#region Otros metodos
public byte Draw(MemoryModule memory, ushort memAddress, byte posx, byte posy, byte height)
{
byte collision = 0;
byte width = 8;
bool extendedSprite = false;
ushort mask = 0x80;
if (height == 0)
{
height = 16;
if (currentMode == VideoMode.SChipMode)
{
width = 16;
extendedSprite = true;
mask = 0x8000;
}
}
posx &= (byte)(currentHorzRes - 1);
posy &= (byte)(currentVertRes - 1);
for (int y = 0; y < height; y++)
{
if (posy + y >= currentVertRes)
continue;
//Extraer la informacion del sprite de memoria
uint sprLineAddress = (ushort)(memAddress + (y << (extendedSprite?1:0)) );
ushort sprLine = memory.ReadByte(sprLineAddress);
if(extendedSprite)
sprLine = (ushort)(sprLine << 8 | memory.ReadByte(sprLineAddress+1));
for (int x = 0; x < width; x++)
{
if (posx + x >= currentHorzRes)
continue;
if ((sprLine & (mask >> x)) != 0) {
if (collision == 0 && display[posy + y].IsPixelActive(posx + x))
collision = 1;
display[posy + y].XorPixel(posx + x, 1);
}
}
}
return collision;
}
public void ClearScreen()
{
for (int i = 0; i < currentVertRes; i++)
display[i].Erase();
}
public void Reset()
{
for (int i = 0; i < currentVertRes; i++)
display[i].Erase();
CurrentMode = VideoMode.Chip8Mode;
}
public void ScrollDown(uint lines)
{
if (lines >= currentVertRes)
ClearScreen();
else
{
//Desplazar las lineas Hacia abajo empezamos de abajo hacia arriba
for (int i = currentVertRes - 1; i >= 0; i--)
{
if (i < lines)
{
display[i] = new VideoLine128();
}
else{
display[i] = display[i-lines];
}
}
}
}
public void ScrollLeft(uint cols)
{
if(cols > currentHorzRes)
ClearScreen();
else{
for (int i = 0; i < currentVertRes; i++)
display[i].Shl((int)cols);
}
}
public void ScrollRight(uint cols)
{
if (cols > currentHorzRes)
ClearScreen();
else
{
for (int i = 0; i < currentVertRes; i++)
display[i].Shr((int)cols);
}
}
#endregion
}
}
|
using System.ComponentModel.DataAnnotations.Resources;
using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Validation attribute to indicate that a property field or parameter is required.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "We want users to be able to extend this class")]
public class RequiredAttribute : ValidationAttribute
{
/// <summary>
/// Default constructor.
/// </summary>
/// <remarks>This constructor selects a reasonable default error message for <see cref="ValidationAttribute.FormatErrorMessage"/></remarks>
public RequiredAttribute()
: base(() => DataAnnotationsResources.RequiredAttribute_ValidationError)
{
}
/// <summary>
/// Gets or sets a flag indicating whether the attribute should allow empty strings.
/// </summary>
public bool AllowEmptyStrings { get; set; }
/// <summary>
/// Override of <see cref="ValidationAttribute.IsValid(object)"/>
/// </summary>
/// <param name="value">The value to test</param>
/// <returns><c>false</c> if the <paramref name="value"/> is null or an empty string. If <see cref="RequiredAttribute.AllowEmptyStrings"/>
/// then <c>false</c> is returned only if <paramref name="vale"/> is null.</returns>
internal override bool IsValid(object value)
{
if (value == null)
{
return false;
}
// only check string length if empty strings are not allowed
var stringValue = value as string;
if (stringValue != null && !AllowEmptyStrings)
{
return stringValue.Trim().Length != 0;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Project.Errors;
using Project.Helpers;
using Project.Models;
using Project.Services;
namespace Project.Base {
public abstract class BaseApplication {
// Program variables
private bool running = false;
private readonly Dictionary<string, Service> services = new Dictionary<string, Service>();
private readonly Dictionary<string, BaseScreen> screens = new Dictionary<string, BaseScreen>();
private BaseScreen defaultScreen;
private BaseScreen currentScreen;
// Called on load/unload
protected abstract void Load();
protected abstract void Unload();
// Returns whether the application is running
public bool IsRunning() {
return running;
}
// Loads the application and its services
public void Start() {
if (IsRunning()) {
throw new Exception("Application is already running.");
}
// Set running to true
running = true;
// Load app
Load();
// Load services
foreach (Service service in services.Values) {
service.Load();
}
// Init screens
foreach (BaseScreen screen in screens.Values) {
screen.Init();
}
// Show default screen
if (defaultScreen == null) {
throw new Exception("No default screen could be found");
}
Application.EnableVisualStyles();
ShowScreen(defaultScreen);
Application.Run(defaultScreen);
}
// Unload all services and the application
public void Stop() {
if (!IsRunning()) {
throw new Exception("Application is not running.");
}
// Unload services
foreach (Service service in services.Values) {
service.Unload();
}
// Unload app
Unload();
// Set running to false to stop any running loops
running = false;
// Close all active forms
defaultScreen.Close();
}
// Register a service
public void RegisterService(Service service) {
services.Add(service.GetHandle(), service);
}
// Returns a service by its handle
public T GetService<T>(string handle) where T: Service {
// Return empty value if service does not exist
if (!services.TryGetValue(handle, out Service service)) {
return default;
}
// Cast service and return
return (T) Convert.ChangeType(service, typeof(T));
}
// Register a screen
public void RegisterScreen(BaseScreen screen) {
screens.Add(screen.GetHandle(), screen);
// Set as default if its the default screen
if(screen.IsDefault()) {
defaultScreen = screen;
}
}
// Returns a screen by its handle
public T GetScreen<T>(string handle) where T: BaseScreen {
// Return empty value if screen does not exist
if (!screens.TryGetValue(handle, out BaseScreen screen)) {
return default;
}
// Cast screen and return
return (T) Convert.ChangeType(screen, typeof(T));
}
public BaseScreen GetDefaultScreen() {
return defaultScreen;
}
public BaseScreen GetCurrentScreen() {
return currentScreen;
}
public void ShowScreen(BaseScreen screen) {
UserService userService = GetService<UserService>("users");
User user = userService.GetCurrentUser();
if(screen == null) {
throw new ArgumentException("Screen can't be null");
}
// Check user permissions
bool allowAuthCheck = !screen.IsDefault();
if((screen.RequireLogin() || screen.RequireAdmin()) && user == null && allowAuthCheck) {
GuiHelper.ShowError("Je moet ingelogd zijn om dit scherm te bekijken");
return;
}
if (screen.RequireAdmin() && !user.admin && allowAuthCheck) {
GuiHelper.ShowError("Je moet een admin zijn om dit scherm te bekijken");
return;
}
try {
screen.OnShow();
// Hide current screen
if (currentScreen != null) {
currentScreen.Hide();
}
// Show new screen
screen.Show();
currentScreen = screen;
} catch(PermissionException e) {
GuiHelper.ShowError(e.Message);
} catch(Exception e) {
GuiHelper.ShowError("Interne error: " + e.Message);
}
}
}
}
|
using Akka.Actor;
using AkkaOverview.Gateway;
using System;
namespace akkaTest
{
class Program
{
static void Main(string[] args)
{
//var system = ActorSystem.Create("Main");
//var actor = system.ActorOf<TestActor>("testActor");
//actor.Tell("hello");
//actor.Tell("world !!!");
//actor.Tell(new Message());
//var fsmactor = system.ActorOf<MyActor>("FSMActor");
//fsmactor.Tell(new TestStateOne());
ApiGateway apiGateway = new ApiGateway();
apiGateway.Candles("EUR_USD");
Console.ReadLine();
}
}
internal class TestActor : ReceiveActor, IWithUnboundedStash
{
public TestActor()
{
Receive<string>(x => Stash.Stash());
Receive<Message>(x =>
{
Stash.UnstashAll();
Become(Writing);
});
}
private void Writing(object message)
{
Console.WriteLine((string)message);
}
public IStash Stash { get; set; }
}
public class Message
{
public string Name { get; set; }
}
class MyActor : FSM<ITestState, ITestData>
{
public MyActor()
{
StartWith(TestStateOne.Instance, new TestData());
When(TestStateOne.Instance, EventTestStateOne());
When(TestStateTwo.Instance, EventTestsStateTwo());
Initialize();
}
private StateFunction EventTestsStateTwo()
{
return @event =>
{
Console.WriteLine("is state two");
return GoTo(TestStateOne.Instance);
};
}
private StateFunction EventTestStateOne()
{
return @event =>
{
bool isfromTestStateOne = @event.FsmEvent is TestStateOne;
if (isfromTestStateOne)
{
Console.WriteLine("Is in state one");
return GoTo(TestStateTwo.Instance);
}
return Stay();
};
}
}
internal interface ITestData
{
}
internal interface ITestState
{
}
public class TestStateOne : ITestState
{
public static readonly TestStateOne Instance = new TestStateOne();
}
class TestStateTwo : ITestState
{
public static readonly TestStateTwo Instance = new TestStateTwo();
}
public class TestData : ITestData
{
}
}
|
using System.Collections.Generic;
using System.IO.IsolatedStorage;
namespace StickFigure.Helpers
{
public static class Globals
{
public static string CurrentFolder { get; set; }
public static Dictionary<int, JointFile> Files { get; set; }
public static int CurrentShownNumber { get; set; }
public static int CurrentActionNumber { get; set; }
public static string LastUsedPath
{
get => PersistedStorage.Get(nameof(LastUsedPath));
set => PersistedStorage.Set(nameof(LastUsedPath), value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace CostumizeElementsAppConfig.Configs
{
public class SchoolConfig : ConfigurationSection
{
private static SchoolConfig _SchoolConfig = (SchoolConfig)ConfigurationManager.GetSection("school");
public static SchoolConfig Settings { get { return _SchoolConfig; } }
[ConfigurationProperty("name")]
public string Name { get { return (string)base["name"]; } }
[ConfigurationProperty("address")]
public AddressElement Adress { get { return (AddressElement)base["address"]; } }
[ConfigurationProperty("courses")]
public CourseElementCollection courses { get { return (CourseElementCollection)base["courses"]; } }
}
public class AddressElement: ConfigurationElement
{
[ConfigurationProperty("street",IsRequired=true)]
public string Street { get { return (string)base["street"]; } }
[ConfigurationProperty("city", IsRequired = true)]
public string City { get { return (string)base["city"]; } }
[ConfigurationProperty("state", IsRequired = true)]
public string State { get { return (string)base["state"]; } }
}
public class CourseElement : ConfigurationElement
{
[ConfigurationProperty("title", IsRequired = true)]
public string Title { get { return (string)base["title"]; } }
[ConfigurationProperty("instructor", IsRequired = false)]
public string Instructor { get { return (string)base["instructor"]; } }
}
[ConfigurationCollection(typeof(CourseElement), AddItemName = "course", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class CourseElementCollection : ConfigurationElementCollection
{
public ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } }
protected override string ElementName
{
get
{
return "course";
}
}
protected override ConfigurationElement CreateNewElement()
{
return new CourseElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return (element as CourseElement).Title;
}
public CourseElement this[int index]
{
get
{
return (CourseElement)base.BaseGet(index);
}
set
{
if(base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
base.BaseAdd(index, value);
}
}
public CourseElement this[string title]
{
get
{
return (CourseElement)base.BaseGet(title);
}
}
}
}
|
namespace ExtractMiddleElements
{
using System;
using System.Linq;
public class StartUp
{
public static void Main()
{
var array = Console.ReadLine()
.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
var length = array.Length;
if (length == 1)
{
Console.WriteLine($"{{ {array[0]} }}");
}
else if (array.Length % 2 == 0)
{
Console.WriteLine($"{{ {array[length / 2 - 1]}, {array[length / 2]} }}");
}
else
{
Console.WriteLine($"{{ {array[length / 2 - 1]}, {array[length / 2]}, {array[length / 2 + 1]} }}");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Alps.Web.Canteen.Model
{
public class BookRecord:EntityBase
{
#region 操作者信息
public Guid BookerID { get; set; }
public virtual CanteenUser Booker { get; set; }
public DateTime BookTime { get; set; }
#endregion
#region 用餐者信息
public Guid DinerID { get; set; }
public virtual Diner Diner { get; set; }
#endregion
#region 餐饭信息
public Guid DinnerID { get; set; }
public virtual Dinner Dinner { get; set; }
public DateTime DinnerDate{ get; set; }
#endregion
#region 用餐信息
public DateTime? TakeTime { get; set; }
#endregion
public static BookRecord CreateNewBookRecord(Guid dinerID, Guid dinnerID,DateTime dinnerDate,Guid bookerID)
{
var bookRecord = new BookRecord() { DinerID=dinerID,DinnerID=dinnerID,DinnerDate= dinnerDate, BookerID=bookerID,BookTime=DateTime.Now};
return bookRecord;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using HrdbWebServiceClient.Domain;
using Microsoft.Practices.ServiceLocation;
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Contracts.Tasks.Sources;
using Profiling2.Domain.Prf;
using Profiling2.Domain.Prf.Events;
using Profiling2.Domain.Prf.Sources;
using Profiling2.Infrastructure.Util;
using Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels;
namespace Profiling2.Web.Mvc.Areas.Hrdb.Controllers.ViewModels
{
public class HrdbCaseViewModel
{
public int Id { get; set; } // JhroCaseId
public int? EventId { get; set; }
public EventViewModel Event { get; set; }
public IList<HrdbPerpetratorViewModel> HrdbPerpetrators { get; set; }
public IList<SelectListItem> OrganizationResponsibilityTypes { get; set; }
public IList<SelectListItem> PersonResponsibilityTypes { get; set; }
// for display purposes
public HrdbCase HrdbCase { get; set; }
public HrdbCaseViewModel() { }
public HrdbCaseViewModel(JhroCase jc)
{
if (jc != null)
{
this.Id = jc.Id;
if (jc.Events != null && jc.Events.Any())
{
// currently assuming one Event (but data model can take multiple)
this.EventId = jc.Events[0].Id;
}
HrdbCase hc = (HrdbCase)StreamUtil.Deserialize(jc.HrdbContentsSerialized);
if (hc != null)
{
this.HrdbCase = hc;
this.HrdbPerpetrators = hc.Perpetrators.Select(x => new HrdbPerpetratorViewModel(x)).ToList();
// pre-populate new Event fields
this.Event = new EventViewModel();
this.Event.PopulateDropDowns(ServiceLocator.Current.GetInstance<IEventTasks>().GetAllEventVerifiedStatuses());
this.Event.ViolationIds = string.Join(",", this.HrdbPerpetrators.Select(x => x.GetViolationIds()).Aggregate(new List<int>(), (x, y) => x.Concat(y).ToList()));
this.Event.NarrativeEn = string.Join("\n\n", new string[] { "Summary", hc.Summary, "Analysis", hc.AnalysisDesc, "Facts", hc.FactAnalysis, "Legal", hc.LegalAnalysis, "Methodology", hc.Methodology });
if (hc.StartDate.HasValue)
{
this.Event.YearOfStart = hc.StartDate.Value.Year;
this.Event.MonthOfStart = hc.StartDate.Value.Month;
this.Event.DayOfStart = hc.StartDate.Value.Day;
}
if (hc.EndDate.HasValue)
{
this.Event.YearOfEnd = hc.EndDate.Value.Year;
this.Event.MonthOfEnd = hc.EndDate.Value.Month;
this.Event.DayOfEnd = hc.EndDate.Value.Day;
}
// location
Location loc = ServiceLocator.Current.GetInstance<ILocationTasks>().GetOrCreateLocation(hc.IncidentAddr, hc.TownVillage, hc.Subregion, hc.Region, hc.GetLatitude(), hc.GetLongitude());
if (loc != null)
this.Event.LocationId = loc.Id;
// notes
this.Event.EventVerifiedStatusId = ServiceLocator.Current.GetInstance<IEventTasks>().GetEventVerifiedStatus(
hc.IsComplaintCode() ? EventVerifiedStatus.ALLEGATION : EventVerifiedStatus.JHRO_VERIFIED).Id;
this.Event.JhroCaseIds = jc.Id.ToString();
}
}
this.OrganizationResponsibilityTypes = ServiceLocator.Current.GetInstance<IResponsibilityTasks>().GetOrgResponsibilityTypes()
.Select(x => new SelectListItem() { Text = x.OrganizationResponsibilityTypeName, Value = x.Id.ToString() })
.ToList();
this.PersonResponsibilityTypes = ServiceLocator.Current.GetInstance<IResponsibilityTasks>().GetPersonResponsibilityTypes()
.Select(x => new SelectListItem() { Text = x.PersonResponsibilityTypeName, Value = x.Id.ToString() })
.ToList();
}
}
}
|
using UnityEngine;
using UnityEngine.AddressableAssets;
public class AssetLoader : MonoBehaviour
{
private void Start()
{
Addressables.InstantiateAsync("Cube");
}
}
|
using System;
using OpenQA.Selenium;
using NUnit.Framework;
using FC_TestFramework.Core.Setup;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
namespace FC_TestFramework.Core.Utils
{
public class AssertUtils : IManager
{
private ElementUtils Elemento;
public AssertUtils(RemoteWebDriver Driver) : base (Driver) { Elemento = new ElementUtils(Driver); }
/**Compara o valor da tag <head><title> do elemento atual com o resultado esperado*/
public virtual void TituloIgual(String esperado)
{
try
{
Assert.AreEqual(esperado, Driver.Title);
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
/**Compara texto do elemento atual com o resultado esperado*/
public virtual void TextoIgual(String esperado, By seletor)
{
try
{
Assert.AreEqual(esperado, Elemento.PegarValorCampo(seletor));
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
public virtual void TextoIgual(String esperado, String atual)
{
try
{
Assert.AreEqual(esperado, atual);
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
/**Compara se texto do elemento atual difere do esperado*/
public virtual void TextoDiferente(String esperado, By seletor)
{
try
{
Assert.AreNotEqual(esperado, Elemento.PegarValorCampo(seletor));
}
catch (Exception e)
{
new Exception("Os valores correspondem. Motivo: " + e.Message);
}
}
public virtual void TextoDiferente(String esperado, String atual)
{
try
{
Assert.AreNotEqual(esperado, atual);
}
catch (Exception e)
{
new Exception("Os valores correspondem. Motivo: " + e.Message);
}
}
/**Compara partes do texto do elemento atual com o resultado esperado, o identificando*/
public virtual void TextoParcial(String esperado, By seletor)
{
try
{
StringAssert.Contains(esperado, Elemento.PegarValorCampo(seletor));
}
catch(Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
public virtual void TextoParcial(String esperado, String atual)
{
try
{
StringAssert.Contains(esperado, atual);
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
/**Compara o início do texto do elemento atual com o resultado esperado, o identificando*/
public virtual void TextoInicial(String esperado, By seletor)
{
try
{
StringAssert.StartsWith(esperado, Elemento.PegarValorCampo(seletor));
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
public virtual void TextoInicial(String esperado, String atual)
{
try
{
StringAssert.StartsWith(esperado, atual);
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
/**Compara o final do texto do elemento atual com o resultado esperado, o identificando*/
public virtual void TextoFinal(String esperado, By seletor)
{
try
{
StringAssert.EndsWith(esperado, Elemento.PegarValorCampo(seletor));
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
public virtual void TextoFinal(String esperado, String atual)
{
try
{
StringAssert.EndsWith(esperado, atual);
}
catch (Exception e)
{
new Exception("Os valores não correspondem. Motivo: " + e.Message);
}
}
/**Compara texto do elemento atual com o resultado esperado, o identificando, e
* segue para o próximo passo do teste, em caso negativo*/
public virtual void TextoElemento(String esperado, By seletor)
{
try
{
Assert.AreEqual(esperado, Elemento.PegarValorCampo(seletor));
}
catch (Exception e)
{
Console.WriteLine("Os valores não correspondem. Motivo: " + e.Message);
}
}
/**Verifica se a condição é verdadeira*/
public virtual void CondicaoVerdadeira(Boolean operacao)
{
try
{
Assert.IsTrue(operacao, "O valor não é Verdadeiro.");
}
catch (Exception e)
{
new Exception("A condição não é verdadeira. Motivo: " + e.Message);
}
}
public virtual void CondicaoVerdadeira(Boolean operacao, string mensagem)
{
try
{
Assert.IsTrue(operacao, mensagem);
}
catch (Exception e)
{
new Exception("A condição não é verdadeira. Motivo: " + e.Message);
}
}
/**Verifica se a condição é falsa*/
public virtual void CondicaoFalsa(Boolean operacao)
{
try
{
Assert.IsFalse(operacao, "O valor não é Falso.");
}
catch (Exception e)
{
new Exception("A condição não é falsa. Motivo: " + e.Message);
}
}
public virtual void CondicaoFalsa(Boolean operacao, string mensagem)
{
try
{
Assert.IsFalse(operacao, mensagem);
}
catch (Exception e)
{
new Exception("A condição não é falsa. Motivo: " + e.Message);
}
}
/**Aguarda a condição de apresentação de um alert*/
public virtual bool ValidarAlert()
{
IAlert alert = null;
try
{
alert = ExpectedConditions.AlertIsPresent().Invoke(Driver);
}
catch (Exception e)
{
new Exception("O alert não foi apresentado. Motivo " + e.Message);
}
return (alert != null);
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace FilmesAPI.Data.DTOs
{
public class CreateFilmeDTO
{
[Required(ErrorMessage = "O campo {0} é obrigatório.")]
public string Titulo { get; set; }
[Required(ErrorMessage = "O campo {0} é obrigatório.")]
public string Diretor { get; set; }
[Required(ErrorMessage = "O campo {0} é obrigatório.")]
public string Genero { get; set; }
[Range(1, 600, ErrorMessage = "A {0} deve ter no mínimo {1} e no máximo {2} minutos.")]
public int Duracao { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TutorialSection : MonoBehaviour
{
[SerializeField] GameObject[] screens;
int iter = 0;
public bool Complete { get; set; }
public void NextScreen()
{
for (int i = 0; i < screens.Length; i++)
{
if (i == iter)
{
screens[i].SetActive(true);
}
else
{
screens[i].SetActive(false);
}
}
if (iter >= screens.Length)
{
gameObject.SetActive(false);
TutorialManager.SectionDone.Invoke();
return;
}
iter++;
}
public void Reset()
{
iter = 0;
Complete = false;
NextScreen();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Allyn.Domain.Models.Basic
{
/// <summary>
/// 表示"菜单"聚合根类型.
/// </summary>
public class Menu : AggregateRoot
{
/// <summary>
/// 获取或设置菜单的父级.
/// </summary>
public Menu Parent { get; set; }
/// <summary>
/// 获取或设置菜单名称.
/// </summary>
public string Name { get; set; }
/// <summary>
/// 获取或设置菜单连接路径.
/// </summary>
public string Url { get; set; }
/// <summary>
/// 获取或设置图标Class.
/// </summary>
public string Ico { get; set; }
/// <summary>
/// 获取或设置备注信息.
/// </summary>
public string Description { get; set; }
/// <summary>
/// 获取或设置排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 获取或设置创建时间.
/// </summary>
public DateTime CreateDate { get; set; }
/// <summary>
/// 获取或设置更新时间.
/// </summary>
public DateTime? UpdateDate { get; set; }
/// <summary>
/// 获取或设置锁定标识.
/// </summary>
public bool Disabled { get; set; }
/// <summary>
/// 获取或设置创建人.
/// </summary>
public Guid Creater { get; set; }
/// <summary>
/// 获取或设置修改者.
/// </summary>
public Guid? Modifier { get; set; }
/// <summary>
/// 获取或设置子菜单.
/// </summary>
public List<Menu> Children { get; set; }
}
}
|
using System.Collections.Generic;
using Entitas;
using Entitas.CodeGeneration.Attributes;
[Config]
[Unique]
public sealed class ExsplosiveScoringTableComponent : IComponent
{
public List<int> value;
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace sendmessagec
{
public partial class FomSendMessage : Form
{
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern Int32 SendMessage(Int32 hWnd, Int32 Msg, Int32 wParam, Int32 lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint RegisterWindowMessage(string lpString);
private uint _myMessage = RegisterWindowMessage("MyMsg");
public const Int32 WM_COPYDATA = 0x4A;
public const Int32 WM_USER = 0x400;
//COPYDATASTRUCT構造体
public struct COPYDATASTRUCT
{
public IntPtr dwData; //送信する32ビット値
public uint cbData; //lpDataのバイト数
public IntPtr lpData; //送信するデータへのポインタ(0も可能)
}
public FomSendMessage()
{
InitializeComponent();
}
//送信ボタン押下
private void butSend_Click(object sender, EventArgs e)
{
Int32 result = 0;
//相手のウィンドウハンドルを取得します
IntPtr hWnd = FindWindow(null, txtName.Text);
if (hWnd == IntPtr.Zero)
{
//ハンドルが取得できなかった
MessageBox.Show("相手Windowのハンドルが取得できません");
return;
}
//文字列メッセージを送信します
if (txtMessage.Text != string.Empty)
{
string s = txtMessage.Text;
COPYDATASTRUCT cds;
cds.dwData = IntPtr.Zero;
cds.lpData = Marshal.StringToHGlobalUni(s);
cds.cbData = (uint)((s.Length + 1) * 2);
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(cds));
Marshal.StructureToPtr(cds, pnt, false);
SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, pnt);
//送信データをByte配列に格納
//byte[] bytearry = System.Text.Encoding.Default.GetBytes(txtMessage.Text);
// Int32 len = bytearry.Length;
// COPYDATASTRUCT cds;
// cds.dwData = 0; //使用しない
// cds.lpData = txtMessage.Text; //テキストのポインターをセット
// cds.cbData = len + 1; //長さをセット
// //文字列を送る
// result = SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
}
//数値メッセージを送信します
//if (txtInt1.Text != string.Empty && txtInt2.Text != string.Empty)
//{
// Int32 int1 = 0;
// Int32 int2 = 0;
// try
// {
// //数値に正しく変換出来るか?
// int1 = int.Parse(txtInt1.Text);
// int2 = int.Parse(txtInt2.Text);
// }
// catch
// {
// MessageBox.Show("入力された数値が正しく有りません");
// return;
// }
// //数値を送る
// result = SendMessage(hWnd, (int)_myMessage, int1, int2);
//}
}
}
}
|
// Copyright (c) Simple Injector Contributors. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
namespace SimpleInjector
{
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SimpleInjector.Integration.AspNetCore;
using SimpleInjector.Integration.ServiceCollection;
using SimpleInjector.Lifestyles;
/// <summary>
/// Extensions for configuring Simple Injector with ASP.NET Core using
/// <see cref="SimpleInjectorAddOptions"/>.
/// </summary>
public static class SimpleInjectorAddOptionsAspNetCoreExtensions
{
/// <summary>
/// Adds basic Simple Injector integration for ASP.NET Core and returns a builder object that allow
/// additional integration options to be applied. These basic integrations includes wrapping each web
/// request in an <see cref="AsyncScopedLifestyle"/> scope and making the nessesary changes that make
/// it possible for enabling the injection of framework components in Simple Injector-constructed
/// components when
/// <see cref="SimpleInjectorServiceCollectionExtensions.UseSimpleInjector(IServiceProvider, Container)"/>
/// is called.
/// </summary>
/// <param name="options">The options to which the integration should be applied.</param>
/// <returns>A new <see cref="SimpleInjectorAspNetCoreBuilder"/> instance that allows additional
/// configurations to be made.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="options"/> is null.</exception>
public static SimpleInjectorAspNetCoreBuilder AddAspNetCore(this SimpleInjectorAddOptions options)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
IServiceCollection services = options.Services;
var container = options.Container;
// Add the IHttpContextAccessor to allow Simple Injector cross wiring to work in ASP.NET Core.
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Replace the default IServiceProviderAccessor with on that can use IHttpContextAccessor to
// resolve instances that are scoped inside the current request.
options.ServiceProviderAccessor = new AspNetCoreServiceProviderAccessor(
new HttpContextAccessor(),
options.ServiceProviderAccessor);
services.UseSimpleInjectorAspNetRequestScoping(container);
return new SimpleInjectorAspNetCoreBuilder(options);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BeeManager;
namespace BeeWebApp
{
public partial class _Default : Page
{
List<Workerbee> workerBees = new List<Workerbee>();
List<QueenBee> QueenBees = new List<QueenBee>();
List<DroneBee> DroneBees = new List<DroneBee>();
public _Default()
{
CreateObjectOfBees();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
private void CreateObjectOfBees()
{
for (int i = 0; i < 10; i++)
{
Workerbee workerBee = new Workerbee()
{
WorkerBeeId = i + 1
};
workerBees.Add(workerBee);
QueenBee queenBee = new QueenBee()
{
QueenBeeId = i + 1
};
QueenBees.Add(queenBee);
DroneBee droneBee = new DroneBee()
{
DroneBeeId = i + 1
};
DroneBees.Add(droneBee);
}
}
private void BindData()
{
GridView1.DataSource = workerBees;
GridView1.DataBind();
}
protected void update(object sender, EventArgs e)
{
Button update = sender as Button;
if (update != null & !String.IsNullOrEmpty(update.CommandArgument))
{
int workerBeeId = int.Parse(update.CommandArgument);
Random rnd = new Random();
int randomNumber = rnd.Next(0, 100);
Workerbee workerBee = workerBees.Where(obj => obj.WorkerBeeId == workerBeeId).FirstOrDefault();
if (workerBee != null)
workerBee.Damage(randomNumber);
BindData();
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Models.Towers;
using UnityEngine;
using UnityEngine.Assertions;
namespace AI
{
public class TowerLogic : LogicBase
{
private readonly ITower _tower;
private readonly List<EnemyLogic> _enemies;
private readonly float _cellSize;
private readonly IGameLogic _gameLogic;
private readonly Vector3 _position;
private bool _isRecharged;
private readonly float _sqrRadius;
private readonly List<EnemyLogic> _accessibleEnemies = new List<EnemyLogic>();
private readonly List<ShotLogic> _shots = new List<ShotLogic>();
public TowerLogic(ITower tower, Vector3 position, float cellSize,
List<EnemyLogic> enemies, IGameLogic gameLogic)
{
_tower = tower;
_position = position;
_cellSize = cellSize;
_enemies = enemies;
_gameLogic = gameLogic;
Assert.IsNotNull(_tower.Weapon);
_sqrRadius = _tower.Weapon.Radius * cellSize;
_sqrRadius *= _sqrRadius;
}
public ITower Model
{
get { return _tower; }
}
public override void Update(float deltaTime)
{
base.Update(deltaTime);
for (var i = _shots.Count - 1; i >= 0; --i)
{
var shot = _shots[i];
shot.Update(deltaTime);
if (shot.IsHit)
{
_shots.RemoveAt(i);
}
}
if (_isRecharged) return;
GetAccessibleEnemies();
if (!_accessibleEnemies.Any()) return;
Attack(_accessibleEnemies[Random.Range(0, _accessibleEnemies.Count - 1)]);
}
private void GetAccessibleEnemies()
{
_accessibleEnemies.Clear();
_enemies.ForEach(enemy =>
{
if ((_position - enemy.GetPosition()).sqrMagnitude <= _sqrRadius)
{
_accessibleEnemies.Add(enemy);
}
});
}
private void Attack(EnemyLogic enemy)
{
var shot = new ShotLogic(_tower.Weapon, enemy, _cellSize, _position);
_shots.Add(shot);
_gameLogic.Shoot(shot);
Cooldown();
}
private void Cooldown()
{
_isRecharged = true;
DelayCall(_tower.Weapon.RechargeTime, () => _isRecharged = false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RD
{
class Program
{
static void Main(string[] args)
{
var now = double.PositiveInfinity;
var manyAsYouNeed = double.PositiveInfinity;
var youth = double.PositiveInfinity;
var billGatesMoney = 79000000000;
var age = 28;
double.PositiveInfinity = youth;
catch(Exception)
}
}
}
|
namespace TripDestination.Web.MVC.Hubs
{
using System.Linq;
using System.Threading.Tasks;
using Common.Infrastructure.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.SignalR;
using Services.Web.Services;
using Services.Web.Services.Contracts;
public class NotificationHub : Hub
{
private static readonly ConnectionMapping<string> Connections = new ConnectionMapping<string>();
public static void UpdateNotify(BaseSignalRModel model)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
if (model != null)
{
foreach (var userNotificationCounts in model.UsersNotificationCounts)
{
string userId = userNotificationCounts.Item1;
int notSeendNorificationCounts = userNotificationCounts.Item2;
context.Clients.Group(userId).addMessage(notSeendNorificationCounts);
}
}
}
public override Task OnConnected()
{
if (this.Context.User.Identity.IsAuthenticated)
{
string userId = this.Context.User.Identity.GetUserId();
this.Groups.Add(this.Context.ConnectionId, userId);
}
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string name = this.Context.User.Identity.Name;
Connections.Remove(name, this.Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
string name = this.Context.User.Identity.Name;
if (!Connections.GetConnections(name).Contains(this.Context.ConnectionId))
{
Connections.Add(name, this.Context.ConnectionId);
}
return base.OnReconnected();
}
}
}
|
using System.Windows;
namespace SC.WPFSamples
{
/// <summary>
/// Interaction logic for StyledButtonWindow.xaml
/// </summary>
public partial class StyledButtonWindow : Window
{
public StyledButtonWindow()
{
InitializeComponent();
button1.Content = new Country { Name = "Austria", ImagePath = "images/Austria.bmp" };
}
}
}
|
using System;
/**
* @author Chris Foulston
*/
namespace Malee.Hive.Events {
public delegate void EventMethod(object sender);
public delegate void EventMethod<T>(object sender, T args);
public delegate void EventMethod<T, U>(T sender, U args);
public static class EventManager {
public static bool Dispatch(EventMethod evt, object sender) {
if (evt != null) {
evt(sender);
return true;
}
return false;
}
public static bool Dispatch<T>(EventMethod<T> evt, object sender, T args) {
if (evt != null) {
evt(sender, args);
return true;
}
return false;
}
public static bool Dispatch<T, U>(EventMethod<T, U> evt, T sender, U args) {
if (evt != null) {
evt(sender, args);
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignPattern.Creational.Factory
{
public class NationalSavings : ISavings
{
public NationalSavings()
{
Balance = 2000;
}
}
}
|
namespace Organizer.Models.Contacts
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Phone
{
public int Id { get; set; }
public string Text { get; set; }
public int PersonId { get; set; }
public virtual Person Person { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SpaceBook.Models;
namespace SpaceBook.ViewModels
{
public class EditFacilityPhotoViewModel
{
public Facility facility { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
//score
public Text scoreTxt;
// Update is called once per frame
void Update()
{
scoreTxt.text = Spawn.score.ToString();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Alabo.Test.Base
{
/// <summary>
/// Http Client 的帮助函数
/// </summary>
public static class HttpHelper
{
/// <summary>
/// 使用Get方法获取字符串结果(没有加入Cookie)
/// </summary>
/// <param name="url"></param>
public static async Task<string> HttpGetAsync(string url, Encoding encoding = null)
{
var httpClient = new HttpClient();
var data = await httpClient.GetByteArrayAsync(url);
var ret = encoding.GetString(data);
return ret;
}
/// <summary>
/// Http Get 同步方法
/// </summary>
/// <param name="url"></param>
/// <param name="encoding"></param>
public static string HttpGet(string url)
{
HttpClient httpClient;
if (ClientAuthContainer.CurrentHandler != null) {
httpClient = new HttpClient(ClientAuthContainer.CurrentHandler);
} else {
httpClient = new HttpClient();
}
var t = httpClient.GetByteArrayAsync(url);
t.Wait();
var ret = Encoding.UTF8.GetString(t.Result);
return ret;
}
/// <summary>
/// 通过表单更新内容
/// </summary>
/// <param name="url"></param>
/// <param name="dictionary">字典数据</param>
public static Tuple<bool, string> Post(string url, Dictionary<string, string> dictionary)
{
HttpClient client;
if (ClientAuthContainer.CurrentHandler != null) {
client = new HttpClient(ClientAuthContainer.CurrentHandler);
} else {
client = new HttpClient();
}
var ms = new MemoryStream();
dictionary.FillFormDataStream(ms); //填充formData
HttpContent hc = new StreamContent(ms);
hc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/webp"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
hc.Headers.Add("UserAgent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
hc.Headers.Add("KeepAlive", "true");
var t = client.PostAsync($"{url}", hc);
t.Wait();
var t2 = t.Result.Content.ReadAsByteArrayAsync();
var result = HttpUtility.HtmlDecode(Encoding.UTF8.GetString(t2.Result));
var status = t.Result.StatusCode == HttpStatusCode.OK;
return Tuple.Create(status, result);
}
// <summary>
/// POST 异步
/// </summary>
/// <param name="url"></param>
/// <param name="postStream"></param>
/// <param name="encoding"></param>
/// <param name="timeOut"></param>
public static async Task<string> HttpPostAsync(string url, Dictionary<string, string> formData = null,
Encoding encoding = null, int timeOut = 10000)
{
HttpClient client;
if (ClientAuthContainer.CurrentHandler != null) {
client = new HttpClient(ClientAuthContainer.CurrentHandler);
} else {
client = new HttpClient();
}
var ms = new MemoryStream();
formData.FillFormDataStream(ms); //填充formData
HttpContent hc = new StreamContent(ms);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/webp"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
hc.Headers.Add("UserAgent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
hc.Headers.Add("Timeout", timeOut.ToString());
hc.Headers.Add("KeepAlive", "true");
var r = await client.PostAsync(url, hc);
var tmp = await r.Content.ReadAsByteArrayAsync();
return encoding.GetString(tmp);
}
/// <summary>
/// POST 同步
/// </summary>
/// <param name="url"></param>
/// <param name="postStream"></param>
/// <param name="encoding"></param>
/// <param name="timeOut"></param>
public static string HttpPost(string url, Dictionary<string, string> formData = null, int timeOut = 10000)
{
HttpClient client;
if (ClientAuthContainer.CurrentHandler != null) {
client = new HttpClient(ClientAuthContainer.CurrentHandler);
} else {
client = new HttpClient();
}
var ms = new MemoryStream();
formData.FillFormDataStream(ms); //填充formData
HttpContent hc = new StreamContent(ms);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/webp"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
hc.Headers.Add("UserAgent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
hc.Headers.Add("Timeout", timeOut.ToString());
hc.Headers.Add("KeepAlive", "true");
var t = client.PostAsync(url, hc);
t.Wait();
var t2 = t.Result.Content.ReadAsByteArrayAsync();
var result = Encoding.UTF8.GetString(t2.Result);
return result;
}
/// <summary>
/// 组装QueryString的方法
/// 参数之间用&连接,首位没有符号,如:a=1&b=2&c=3
/// </summary>
/// <param name="formData"></param>
public static string GetQueryString(this Dictionary<string, string> formData)
{
if (formData == null || formData.Count == 0) {
return "";
}
var sb = new StringBuilder();
var i = 0;
foreach (var kv in formData)
{
i++;
sb.AppendFormat("{0}={1}", kv.Key, kv.Value);
if (i < formData.Count) {
sb.Append("&");
}
}
return sb.ToString();
}
/// <summary>
/// 填充表单信息的Stream
/// </summary>
/// <param name="formData"></param>
/// <param name="stream"></param>
public static void FillFormDataStream(this Dictionary<string, string> formData, Stream stream)
{
var dataString = GetQueryString(formData);
var formDataBytes = formData == null ? new byte[0] : Encoding.UTF8.GetBytes(dataString);
stream.Write(formDataBytes, 0, formDataBytes.Length);
stream.Seek(0, SeekOrigin.Begin); //设置指针读取位置
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace FormTest
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//配置数据连接
CRL.SettingConfig.GetDbAccess = (type) =>
{
//可按type区分数据库
return Code.LocalSqlHelper.TestConnection;
};
CRL.CacheServerSetting.AddClientProxy("127.0.0.1", 1129);
CRL.CacheServerSetting.Init();
Application.Run(new ThreadForm());
CRL.CacheServerSetting.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SamOthellop.Model
{
[Flags]
public enum BoardStates : Byte
{
white = 0x10,
black = 0xef, //black = !white
empty = 0x00,
}
public class BoardBase
{
public const byte BOARD_SIZE = 8;
public byte MaxMoves { get; protected set; }
public byte FinalBlackTally { get; protected set; }
public byte FinalWhiteTally { get; protected set; }
public BoardStates FinalWinner { get; protected set; }
public BoardStates WhosTurn { get; protected set; }
public bool GameComplete { get; protected set; }
public BoardStates[,] Board { get; protected set; }
protected List<BoardStates[,]> BoardHistory;
public BoardBase()
{
SetupBoard();
}
public void ResetBoard()
{
SetupBoard();
}
private bool GameOver()
{
bool moveExists = false;
for (byte i = 0; i < BOARD_SIZE; i++)
{
for (byte j = 0; j < BOARD_SIZE; j++)
{
if(ValidMove(BoardStates.black, new byte[] { i, j }) ||
ValidMove(BoardStates.white, new byte[] { i, j }))
{
moveExists = true;
break;
}
}
}
if (!moveExists)
{
InitializeEndOfGameAttributes();
}
return !moveExists;
}
public bool MakeMove(BoardStates player, byte[] location)
{
bool moveMade = false;
List<byte[]> takenPeices;
bool valid = ValidMove(player, location, out takenPeices);
if (valid)
{
Board[location[0], location[1]] = player;
for (int i = 0; i < takenPeices.Count(); i++)
{
Board[takenPeices[i][0], takenPeices[i][1]] = player;
}
BoardStates opponent = ~player;
if (PlayerHasMove(opponent))
{
WhosTurn = opponent;//only switch whos turn it is if other player has moves avalible
}
BoardHistory.Add(GetBoardCopy(Board));
moveMade = true;
}
else
{
int debugLocation = 0;//to stop debugger on invalid move
}
GameOver();
return moveMade;
}
public bool MakeMove(byte[] location)
{
BoardStates player = WhosTurn;
return MakeMove(player, location);
}
public bool ValidMove(BoardStates player, byte[] location, out List<byte[]> takenPeices, bool playerTurn = false)
{
bool valid = true;
valid &= !GameComplete;
valid &= OnBoard(location);
if (!valid)
{
takenPeices = null;
return valid;
}
valid &= Board[location[0], location[1]] == BoardStates.empty;
if (playerTurn) valid &= (WhosTurn == player);
takenPeices = TakesPieces(player, location);
valid &= takenPeices.Count() > 0;
return valid;
}
public bool ValidMove(BoardStates player, byte[] location, bool playerTurn = false)
{
bool valid = true;
valid &= !GameComplete;
valid &= OnBoard(location);
if (!valid)
{
return valid;
}
valid &= Board[location[0], location[1]] == BoardStates.empty;
if (playerTurn) valid &= WhosTurn == player;
List<byte[]> takenPeices = TakesPieces(player, location);
valid &= takenPeices.Count() > 0;
return valid;
}
//*************************Static Methods**************************
public static BoardStates OpposingPlayer(BoardStates player)
{
if (player == BoardStates.empty) return BoardStates.empty;
return ~player;
}
public static BoardStates GetCurrentLeader(OthelloGame game)
{
BoardStates leader = BoardStates.empty;
leader = game.GetPieceCount(BoardStates.white) > game.GetPieceCount(BoardStates.black)
? BoardStates.white : BoardStates.black;
return leader;
}
//**************************Get Methods****************************
public BoardStates[,] GetBoardAtMove(int move)
{
try
{
return BoardHistory[move];
}
catch (Exception)
{
System.Console.WriteLine("Can't retreive board history");
return new BoardStates[8, 8];
}
}
public BoardStates[,] GetBoard() { return (BoardStates[,])Board.Clone(); }
public int GetMovesMade()
{
int playCount = -4; // Board Starts with 4 peices in play
foreach (BoardStates piece in Board)
{
if (piece != BoardStates.empty) playCount++;
}
return playCount;
}
public int GetMaxMovesLeft()
///Returns max moves left if all pieces are played
{
return (MaxMoves - GetMovesMade());
}
public bool PlayerHasMove(BoardStates player)
{
bool hasMove = false;
for (byte i = 0; i < BOARD_SIZE; i++)
{
for (byte j = 0; j < BOARD_SIZE; j++)
{
if (ValidMove(player, new byte[] { i, j }))
{
hasMove = true;
return hasMove;
}
}
}
return hasMove;
}
public int GetPieceCount(BoardStates bstate)
{
int count = 0;
foreach (BoardStates piece in Board)
{
if (piece == bstate) count++;
}
return count;
}
//**************************Private Methods****************************
protected bool[,] GetStateArray(BoardStates bstate)
///
///Returns bool array of bstate peices the size of the board,
///With 1 meaning a bstate peice is there, 0 meaning it is not
///
{
bool[,] bstates = new bool[BOARD_SIZE, BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
bstates[i, j] = (Board[i, j] == bstate) ? true : false;
}
}
return bstates;
}
protected bool[] GetStateList(BoardStates bstate)
///
///
///
{
bool[] bstates = new bool[BOARD_SIZE * BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
bstates[i + j] = (Board[i, j] == bstate) ? true : false;
}
}
return bstates;
}
protected bool OnBoard(byte[] location)
{
return (location[0] >= 0 && location[0] < BOARD_SIZE && location[1] >= 0 && location[1] < BOARD_SIZE);
}
protected bool OnBoard(sbyte[] location)
{
return (location[0] >= 0 && location[0] < BOARD_SIZE && location[1] >= 0 && location[1] < BOARD_SIZE);
}
protected static BoardStates[,] GetBoardCopy(BoardStates[,] board)
{
BoardStates[,] boardCopy = new BoardStates[BOARD_SIZE, BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
boardCopy[i, j] = board[i, j];
}
}
return boardCopy;
}
protected static List<BoardStates[,]> GetBoardHistoryCopy(List<BoardStates[,]> boardHistory)
{
List<BoardStates[,]> historyCopy = new List<BoardStates[,]>();
foreach (BoardStates[,] board in boardHistory)
{
historyCopy.Add(GetBoardCopy(board));
}
return historyCopy;
}
protected void InitializeEndOfGameAttributes()
{
byte wtally = 0;
byte btally = 0;
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
if (Board[i, j] == BoardStates.white)
{
wtally++;
}
else if (Board[i, j] == BoardStates.black)
{
btally++;
}
}
}
FinalWhiteTally = wtally;
FinalBlackTally = btally;
GameComplete = true;
if (wtally > btally)
{
FinalWinner = BoardStates.white;
}
else if (btally > wtally)
{
FinalWinner = BoardStates.black;
}
else
{
FinalWinner = BoardStates.empty;//tie
}
}
private List<byte[]> TakesPieces(BoardStates player, byte[] location)
{
List<byte[]> taken = new List<byte[]>();//array of all pieces to be flipped
byte minX = location[0] > 0 ? (byte)(location[0] - 1) : (byte)0;
byte minY = location[1] > 0 ? (byte)(location[1] - 1) : (byte)0;
byte maxX = location[0] + 2 < BOARD_SIZE ? (byte)(location[0] + 1) : (byte)(BOARD_SIZE - 1);
byte maxY = location[1] + 2 < BOARD_SIZE ? (byte)(location[1] + 1) : (byte)(BOARD_SIZE - 1);
for (byte x = minX; x <= maxX; x++)
{
for (byte y = minY; y <= maxY; y++)
{
// int subtakenCount = 0;
BoardStates opposingPlayer = ~player; //store to save some computing time
if (Board[x, y] == opposingPlayer && (x != location[0] || y != location[1]))
{
sbyte[] direction = new sbyte[] { (sbyte)(x - location[0]), (sbyte)(y - location[1]) };
byte[] searchedLocation = new byte[] { x, y };
List<byte[]> subTaken = new List<byte[]>();
while (OnBoard(searchedLocation) && Board[searchedLocation[0], searchedLocation[1]] == opposingPlayer)
{
subTaken.Add(searchedLocation);
searchedLocation = new byte[] { (byte)(searchedLocation[0] + direction[0]),
(byte)(searchedLocation[1] + direction[1]) };
}
if (OnBoard(searchedLocation) && Board[searchedLocation[0], searchedLocation[1]] == player)
{
taken = taken.Concat(subTaken).ToList();
}
}
}
}
return taken;
}
private void SetupBoard()
{
BoardHistory = new List<BoardStates[,]>();//60 moves + initial
Board = new BoardStates[BOARD_SIZE, BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
Board[i, j] = BoardStates.empty;
}
}
Board[BOARD_SIZE / 2 - 1, BOARD_SIZE / 2 - 1] = BoardStates.white;
Board[BOARD_SIZE / 2 - 1, BOARD_SIZE / 2] = BoardStates.black;
Board[BOARD_SIZE / 2, BOARD_SIZE / 2 - 1] = BoardStates.black;
Board[BOARD_SIZE / 2, BOARD_SIZE / 2] = BoardStates.white;
WhosTurn = BoardStates.black;
FinalWinner = BoardStates.empty;
GameComplete = false;
BoardHistory.Add(GetBoardCopy(this.Board));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
namespace NaverDictionary
{
public partial class NaverDic : Form
{
public NaverDic()
{
InitializeComponent();
}
private void NaverDic_Load(object sender, EventArgs e)
{
notifyIcon1.ContextMenuStrip = contextMenuStrip1;
notifyIcon1.Icon = Properties.Resources.icon1;
RegisterHotKey((int)this.Handle, 0, 0x0001 | 0x0002 | 0x0004, (int)Keys.Space); //(여기로가져와, 니 ID는 0이야, 조합키안써, 눌러지면)
// ALT = 0x0001,
// CTRL = 0x0002,
// SHIFT = 0x0004,
// WIN = 0x0008,
webBrowser1.ScriptErrorsSuppressed = true;
LoadWeb(1);
}
private void LoadWeb(int web)
{
string txtUrl = "";
string title = "";
int width = 0;
int height = 0;
//IniUtil ini = LoadINI();
switch (web)
{
case 1:
title = Properties.Settings.Default.title1;
txtUrl = Properties.Settings.Default.url1;
width = Properties.Settings.Default.width1;
height = Properties.Settings.Default.height1;
//MessageBox.Show("[" + txtUrl + "][" + width + "][" + height);
break;
case 2:
title = Properties.Settings.Default.title2;
txtUrl = Properties.Settings.Default.url2;
width = Properties.Settings.Default.width2;
height = Properties.Settings.Default.height2;
break;
}
this.Text = title;
this.Width = width;
this.Height = height;
webBrowser1.Navigate(new Uri(txtUrl));
}
//핫키등록
[DllImport("user32.dll")]
private static extern int RegisterHotKey(int hwnd, int id, int fsModifiers, int vk);
//핫키제거
[DllImport("user32.dll")]
private static extern int UnregisterHotKey(int hwnd, int id);
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(int hwnd);
//private bool isActived = true;
protected override void WndProc(ref Message m) //<span class="searchword">윈도우</span>프로시저 콜백함수
{
base.WndProc(ref m);
if (m.Msg == (int)0x312) //핫키가 눌러지면 312 정수 메세지를 받게됨
{
if (Form.ActiveForm == null/*isActived == false*/)
{
ShowDic();
} else
{
HideDic();
}
}
}
private void HideDic()
{
this.WindowState = FormWindowState.Minimized;
this.Visible = false;
}
private void ShowDic()
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
SetForegroundWindow((int)this.Handle);
webBrowser1.Focus();
webBrowser1.Document.Focus();
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDic();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
notifyIcon1.Visible = false;
Application.Exit();
//this.Close();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
ShowDic();
}
private void NaverDic_FormClosing(object sender, FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.UserClosing:
e.Cancel = true;
HideDic();
break;
case CloseReason.ApplicationExitCall:
case CloseReason.FormOwnerClosing:
case CloseReason.MdiFormClosing:
case CloseReason.None:
case CloseReason.TaskManagerClosing:
case CloseReason.WindowsShutDown:
default:
notifyIcon1.Visible = false;
break;
}
}
private void NaverDic_FormClosed(object sender, FormClosedEventArgs e)
{
UnregisterHotKey((int)this.Handle, 0); //이 폼에 ID가 0인 핫키 해제
}
private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
HideDic();
break;
case Keys.F1:
MessageBox.Show("Ctrl + Alt + Shift + Space : Show / Hide\r\n" +
"F1 : Shortcuts\r\n" +
"F2 : Naver Dictionary\r\n" +
"F3 : Google Translator");
break;
case Keys.F2:
LoadWeb(1);
break;
case Keys.F3:
LoadWeb(2);
break;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MICRUD.modelo
{
class persona
{
private string nombres;
private string direccion;
private string cedula;
private string telefono;
private string documento;
public persona()
{
this.nombres = "";
this.direccion = "";
this.cedula = "";
this.telefono = "";
this.documento = "";
}
public string Nombres { get => nombres; set => nombres = value; }
public string Direccion { get => direccion; set => direccion = value; }
public string Cedula { get => cedula; set => cedula = value; }
public string Telefono { get => telefono; set => telefono = value; }
public string Documento { get => documento; set => documento = value; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshRenderer))]
[DisallowMultipleComponent]
[ExecuteInEditMode]
public class TerrainSplatmapsV2 : MonoBehaviour {
public Texture2D[] splatMaps;
public TerrainData terrainData;
private void Update() {
this.SetMaterialWithTerrainData();
}
private void SetMaterialWithTerrainData() {
if(this.terrainData == null) {
Debug.Log("Can't find any terrain data");
return;
}
if(!IsShaderCorrect("SoFunny/Chicken-Terrain_v2")) {
Debug.Log("Shader is not Correct");
return;
}
Texture2D[] splatmaps = new Texture2D[this.terrainData.alphamapTextureCount];
//Debug.Log(splatmaps.Length);
}
private bool IsShaderCorrect(string shaderFullName) {
MeshRenderer mr = this.GetComponent<MeshRenderer>();
if(mr.sharedMaterial != null) {
if(mr.sharedMaterial.shader.name == shaderFullName) {
return true;
} else {
return false;
}
} else {
Debug.Log("Can't find the material.");
return false;
}
}
private void InitializeSplatmapsAndSetMaterial() {
if(this.splatMaps.Length == 2) {
if(this.splatMaps[0] != null && this.splatMaps[1] != null) {
MeshRenderer mr = this.GetComponent<MeshRenderer>();
if(mr.sharedMaterial.shader.name == "SoFunny/Chicken-Terrain_v2") {
this.SetSplatmapsForMaterials(mr.sharedMaterial, this.splatMaps);
}
} else {
Debug.Log("One of the splatmap is not set correctly.");
return;
}
} else {
Debug.Log("Two splatmps are needed.");
return;
}
}
private void SetSplatmapsForMaterials(Material material, Texture2D[] textures) {
material.SetTexture("_Control01", textures[0]);
material.SetTexture("_Control02", textures[1]);
}
}
|
using FBS.Domain.Booking.Events;
using FBS.Domain.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FBS.Domain.Booking.Aggregates
{
public class FlightAggregate : AggregateBase
{
public FlightAggregate()
{
}
public Seat[] Seats { get; set; }
public Location From { get; set; }
public Location To { get; set; }
public DateTime Date { get; set; }
public TimeSpan Duration { get; set; }
public DateTime Arrival => Date.Add(Duration);
public string Number { get; set; }
public string Gate { get; set; }
public string PlaneModel { get; set; }
/// <summary>
/// Flight has been released by the FlightControl
/// </summary>
/// <param name="event"></param>
public void Apply(FlightReleasedEvent @event)
{
this.Id = @event.AggregateId;
this.Seats = @event.Seats;
this.From = @event.From;
this.To = @event.To;
this.Date = @event.Date;
this.Duration = @event.Duration;
this.Gate = @event.Gate;
this.Number = @event.Number;
this.PlaneModel = @event.PlaneModel;
}
/// <summary>
/// A booking was successfull and the seat is now occupied
/// </summary>
/// <param name="event"></param>
public void Apply(SeatOccupiedEvent @event)
{
var seat = this.Seats?.FirstOrDefault(s => s.Number == @event.Number);
seat.IsOccupied = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace ChatAppSample.Views.Partials
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ChatEntryBar : ContentPage
{
public ChatEntryBar()
{
InitializeComponent();
}
private void chatInput_Completed(object sender, EventArgs e)
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.