text stringlengths 13 6.01M |
|---|
using RoadSimLib;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ViewModelLib;
namespace TestGUI.ViewModels
{
public class MapViewModel : ViewModel<IMap>
{
public static readonly DependencyProperty TilesProperty = DependencyProperty.Register("Tiles", typeof(TilesViewModel), typeof(MapViewModel));
public TilesViewModel Tiles
{
get { return (TilesViewModel)GetValue(TilesProperty); }
set { SetValue(TilesProperty, value); }
}
public MapViewModel()
{
}
public MapViewModel(IMap Model) : base(Model)
{
}
protected override void OnModelChanged(IMap OldValue, IMap NewValue)
{
base.OnModelChanged(OldValue, NewValue);
if (Model == null) Tiles = null;
else
{
Tiles = new TilesViewModel();
foreach(Tile tile in Model.Tiles)
{
Tiles.Add(new TileViewModel(tile));
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System
{
public static class BoolExtension
{
public static bool True(this bool b, Action action)
{
if (b) action?.Invoke();
return b;
}
public static bool False(this bool b, Action action)
{
if (!b) action?.Invoke();
return b;
}
}//end static class
}//end namespace
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
public class Soldier : MonoBehaviourPunCallbacks
{
public float health;
public float attack;
public float range;
public string soldierName;
public Dictionary<string, float> multipliers = new Dictionary<string, float>();
void TakeDamage()
{
}
void Hit()
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIHP : MonoBehaviour {
// Use this for initialization
void Start () {
h = GameObject.FindGameObjectWithTag("Player").GetComponent<Health>();
}
Health h;
// Update is called once per frame
void Update () {
if(h == null)
{
gameObject.SetActive(false);
return;
}
GetComponent<Text>().text = "LIFE: " + h.hitPoints + "/" + h.initialHitPoints;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Langium.PresentationLayer.ViewModels
{
public class WordAddDto
{
public string Lexeme { get; set; }
public string Transcription { get; set; }
public string Translation { get; set; }
public int CategoryId { get; set; }
}
}
|
using Shiftgram.Core.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Shiftgram.Core.Repository
{
public interface IPhoneRepository
{
Task<IEnumerable<Phone>> GetPhones();
}
}
|
using UnityEngine;
using System.Collections;
public class ResolutionLimiter : MonoBehaviour
{
public int h = 144;
public int w = 160;
public int multiplier = 10;
public void Start()
{
Screen.SetResolution(w*multiplier, h*multiplier, false);
Screen.fullScreen = true;
}
} |
using RemoteConnectionCore.LipSync.Infrastructure;
using Zenject;
namespace Example.Core.MorphDemo
{
public class MorphTransportInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.BindInterfacesTo<LocalLipDataTransponder>().AsCached();
}
}
} |
namespace CSSynth.Banks.Fm
{
public interface IFMComponent
{
double doProcess(double value);
}
}
|
using surfnsail.Views.CommonPages;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using Xamarin.Forms;
using surfnsail.Code;
namespace surfnsail.Views
{
public abstract class SportPage : TabbedPage
{
public static List<SportPage> _pages;
static SportPage()
{
_pages = new List<SportPage>();
var types = FindAllDerivedTypes();
foreach (var type in types)
_pages.Add(Activator.CreateInstance(type) as SportPage);
}
Dictionary<CommonPageType, Page> _commonPages;
public SportPage()
{
//_commonPages = new Dictionary<CommonPageType, Page>();
Children.Add(new TodayPage());
Children.Add(new PlaningPage());
Children.Add(new TrackingPage());
Children.Add(new MonitoringPage());
Children.Add(new HistoryPage());
Children.Add(new StartPage());
}
private int GetSportID()
{
var dnAttribute = GetType()
.GetCustomAttributes(typeof(SportAttribute), true)
.FirstOrDefault() as SportAttribute;
if (dnAttribute != null)
return dnAttribute.SportID;
return -1;
}
private static List<Type> FindAllDerivedTypes()
{
var derivesFrom = typeof(SportPage);
return Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t != derivesFrom && derivesFrom.IsAssignableFrom(t))
.ToList();
}
public static SportPage GetPage(int sportID)
{
return _pages.SingleOrDefault(e => e.GetSportID() == sportID);
}
}
} |
using MasterDetail;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using Xamarin.Forms;
namespace MasterDetail
{
public partial class Detail : ContentPage
{
EmpaqueModel empa = new EmpaqueModel();
public Detail(EmpaqueModel empaque)
{
this.empa = empaque;
InitializeComponent();
Bienvenido.Text = string.Format("Bienvenid@ : {0} {1}", empaque.FirstName, empaque.LastName);
}
private async void ListaTurnos(object sender, EventArgs e)
{
App.MasterD.IsPresented = false;
await App.MasterD.Detail.Navigation.PushAsync(new ListaTurnos(empa));
}
private void MisTurnos(object sender, EventArgs e)
{
Navigation.PushAsync(new MisTurnos(empa));
}
private void MiRendimiento(object sender, EventArgs e)
{
Navigation.PushAsync(new MiRendimiento());
}
private void MisNotificaciones(object sender, EventArgs e)
{
Navigation.PushAsync(new MisNotificaciones());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace EpisodeGrabber.Controls.Main {
/// <summary>
/// Interaction logic for TVForm.xaml
/// </summary>
public partial class TVForm : UserControl {
public TVForm() {
InitializeComponent();
}
}
}
|
using System.Reflection;
using NLog;
using Sandbox.Definitions;
using Sandbox.Game.Entities.Cube;
using Torch.Managers.PatchManager;
namespace DataValidateFix
{
[PatchShim]
public static class MyBeaconPatch
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private static FieldInfo _radius;
// ReSharper disable once InconsistentNaming
private static void InitPatch(MyBeacon __instance)
{
var definition = (MyBeaconDefinition) __instance.BlockDefinition;
_radius.GetSync<float>(__instance).ValueChangedInRange(1, definition.MaxBroadcastRadius);
}
public static void Patch(PatchContext patchContext)
{
Log.TryPatching(() =>
{
patchContext.PatchInit<MyBeacon>(InitPatch);
_radius = typeof(MyBeacon).GetPrivateFieldInfo("m_radius");
});
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class FDB
{
public List<F> Lista = new List<F>();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Weather_forecast.OriginalModels
{
public class HourlyWeather
{
public double dt;
public Main main;
public List<WeatherItem> weather;
public Clouds clouds;
public Wind wind;
public Sys sys;
public string dt_text;
}
public struct Main {
public double temp;
public double feels_like;
public double temp_min;
public double temp_max;
public int pressure;
public int sea_level;
public int grnd_level;
public int humidity;
public double temp_kf;
}
public struct WeatherItem
{
public int id;
public string main;
public string description;
public string icon;
}
public struct Clouds
{
public int all;
}
public struct Wind
{
public double speed;
public double deg;
}
public struct Sys
{
public string pod;
}
}
|
using System;
using UnityEngine;
using UnityAtoms.BaseAtoms;
namespace UnityAtoms.FSM
{
/// <summary>
/// Class representing a state in the FSM.
/// </summary>
[Serializable]
public class FSMState
{
public string Id { get => _id.Value; }
public FiniteStateMachine SubMachine { get => _subMachine; }
public float Timer { get; set; }
public float Cooldown { get => _cooldown.Value; }
[SerializeField]
private StringReference _id = default(StringReference);
[SerializeField]
private FloatReference _cooldown = new FloatReference(0f);
[SerializeField]
private FiniteStateMachine _subMachine = default(FiniteStateMachine);
}
} |
using System;
class Program{
static void Main(string[] args){
int i = Int32.Parse(args[0]);
int[] input = new int[i];
int answer = 0;
if(i <= 10 && i >= 1){
for(int j = 0; j < i; j++){
int val = Int32.Parse(Console.ReadLine());
if( val <= 100 && val >= 0 )
input[j] = val;
else
input[j] = 100;
}
for(int j = 0; j < i; j++)
answer = input[j] + answer;
Console.WriteLine("Total of {0} values is {1}", i, answer);
}else{
Console.WriteLine("Cannot Accept value larger than ten");
}
}
} |
using System;
using BikeDistributor.Shared.Interfaces;
namespace BikeDistributor.Interfaces.CommonServices
{
public interface ILogService
{
void Error(Exception ex, string additionalInfo = "");
void Error(string message);
void Info(string message);
void Info(IEntity entity);
void Warn(string message);
}
}
|
using System.Threading.Tasks;
using LoanAPound.Db.Model;
using System.Collections.Generic;
namespace LoanAPound.Db
{
public interface ILoanRepository
{
Task<Loan> GetAsync(int id);
Task CreateAsync(Loan loan);
Task UpdateAsync(Loan loan);
Task<IEnumerable<Loan>> ListOpenAsync();
}
} |
using PointTrans.Commands;
using PointTrans.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using PointTrans.Services;
// https://docs.microsoft.com/en-us/office/open-xml/how-to-get-all-the-text-in-all-slides-in-a-presentation
// https://docs.microsoft.com/en-us/office/open-xml/working-with-presentation-slides
// https://stackoverflow.com/questions/26372020/how-to-programmatically-create-a-powerpoint-from-a-list-of-images
// https://www.free-power-point-templates.com/articles/create-powerpoint-ppt-programmatically-using-c/
namespace PointTrans
{
/// <summary>
/// PointService
/// </summary>
public static class PointService
{
/// <summary>
/// The comment
/// </summary>
public static readonly string Comment = "^q|";
/// <summary>
/// The stream
/// </summary>
public static readonly string Stream = "^q=";
/// <summary>
/// The break
/// </summary>
public static readonly string Break = "^q!";
/// <summary>
/// Gets the pop frame.
/// </summary>
/// <value>
/// The pop frame.
/// </value>
public static string PopFrame => $"{Stream}{PointSerDes.Encode(new PopFrame())}";
/// <summary>
/// Gets the pop set.
/// </summary>
/// <value>
/// The pop set.
/// </value>
public static string PopSet => $"{Stream}{PointSerDes.Encode(new PopSet())}";
/// <summary>
/// Encodes the specified describe.
/// </summary>
/// <param name="describe">if set to <c>true</c> [describe].</param>
/// <param name="cmds">The CMDS.</param>
/// <returns></returns>
public static string Encode(bool describe, params IPointCommand[] cmds) => $"{(describe ? PointSerDes.Describe(Comment, cmds) : null)}{Stream}{PointSerDes.Encode(cmds)}";
/// <summary>
/// Encodes the specified describe.
/// </summary>
/// <param name="describe">if set to <c>true</c> [describe].</param>
/// <param name="cmds">The CMDS.</param>
/// <returns></returns>
public static string Encode(bool describe, IEnumerable<IPointCommand> cmds) => Encode(describe, cmds.ToArray());
/// <summary>
/// Encodes the specified CMDS.
/// </summary>
/// <param name="cmds">The CMDS.</param>
/// <returns></returns>
public static string Encode(params IPointCommand[] cmds) => $"{Stream}{PointSerDes.Encode(cmds)}";
/// <summary>
/// Encodes the specified CMDS.
/// </summary>
/// <param name="cmds">The CMDS.</param>
/// <returns></returns>
public static string Encode(IEnumerable<IPointCommand> cmds) => Encode(cmds.ToArray());
/// <summary>
/// Decodes the specified packed.
/// </summary>
/// <param name="packed">The packed.</param>
/// <returns></returns>
public static IPointCommand[] Decode(string packed) => PointSerDes.Decode(packed.Substring(Stream.Length));
/// <summary>
/// Transforms the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static (Stream stream, string, string path) Transform((Stream stream, string, string path) value)
{
using (var s1 = value.stream)
{
s1.Seek(0, SeekOrigin.Begin);
var s2 = new MemoryStream(Build(s1));
return (s2, "application/vnd.openxmlformats-officedocument.presentationml", value.path.Replace(".csv", ".pptx"));
}
}
static byte[] Build(Stream s)
{
using (var ctx = new PointContext())
{
CsvReader.Read(s, x =>
{
if (x == null || x.Count == 0 || x[0].StartsWith(Comment)) return true;
else if (x[0].StartsWith(Stream))
{
var r = ctx.ExecuteCmd(Decode(x[0]), out var action) != null;
action?.Invoke();
return r;
}
else if (x[0].StartsWith(Break)) return false;
//ctx.AdvanceRow();
//if (ctx.Sets.Count == 0) ctx.WriteRow(x);
//else ctx.Sets.Peek().Add(x);
return true;
}).Any(x => !x);
ctx.Flush();
ctx.Doc.Close();
return ((MemoryStream)ctx.Stream).ToArray();
}
}
internal static object ParseValue(this string v) =>
v == null ? null :
v.Contains("/") && DateTime.TryParse(v, out var vd) ? vd :
v.Contains(".") && double.TryParse(v, out var vf) ? vf :
long.TryParse(v, out var vl) ? vl :
(object)v;
internal static string SerializeValue(this object v, Type type) =>
type == null ? v.ToString() : type.IsArray
? string.Join("|^", ((Array)v).Cast<object>().Select(x => x?.ToString()))
: v.ToString();
internal static object DeserializeValue(this string v, Type type) =>
type == null ? v : type.IsArray && type.GetElementType() is Type elemType
? v.Split(new[] { "|^" }, StringSplitOptions.None).Select(x => Convert.ChangeType(x, elemType)).ToArray()
: Convert.ChangeType(v, type);
internal static T CastValue<T>(this object v, T defaultValue = default) => v != null
? typeof(T).IsArray && typeof(T).GetElementType() is Type elemType
? (T)(object)((Array)v).Cast<object>().Select(x => Convert.ChangeType(v, elemType)).ToArray()
: (T)Convert.ChangeType(v, typeof(T))
: defaultValue;
}
}
|
// Copyright 2013-2015 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Serilog.Core;
/// <summary>
/// Creates log event properties from regular .NET objects, applying policies as
/// required.
/// </summary>
public interface ILogEventPropertyFactory
{
/// <summary>
/// Construct a <see cref="LogEventProperty"/> with the specified name and value.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="value">The value of the property.</param>
/// <param name="destructureObjects">If <see langword="true"/>, and the value is a non-primitive, non-array type,
/// then the value will be converted to a structure; otherwise, unknown types will
/// be converted to scalars, which are generally stored as strings.</param>
/// <returns>Created <see cref="LogEventProperty"/> instance.</returns>
LogEventProperty CreateProperty(string name, object? value, bool destructureObjects = false);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
public partial class zlb : System.Web.UI.Page
{
//SQLServer数据库对象
SqlServerDataBase sdb = new SqlServerDataBase();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
oktoedit();
if (Session["zlzt"].ToString() == "xz")
{
//隐藏按钮
xiugai_id.Visible = false;
querenxg.Visible = false;
}
else if (Session["zlzt"].ToString() == "xg")
{
//隐藏按钮
btnOk.Visible = false;
//初始化数据
shuru();
}
if (Session["managertype"] == "董事长")
{
btnOk.Visible = false;
xiugai_id.Visible = false;
querenxg.Visible = false;
}
}
}
void shuru()
{
xiugai_id.Enabled = false;
DataSet ds = new DataSet();
string id = Request["ID"];
ds = sdb.Select("select * from zlsqdb where zlID='" + id + "'", null);
foreach (Control c in this.form1.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = ds.Tables[0].Rows[0][c.ID].ToString().Trim().Replace("0:00:00", "");
}
if (c is DropDownList)
{
((DropDownList)c).Text = ds.Tables[0].Rows[0][c.ID].ToString().Trim().Replace("0:00:00", "");
}
}
}
//新增
protected void qrxiugai(object sender, EventArgs e)
{
string bdID = Session["zlbdid"].ToString();
sdb.Insert("insert into zlsqdb(sqr, zlztmc, sblx, fmr, jslxr, szxy, bdID) values('" + sqr.Text.Trim() + "','" + zlztmc.Text.Trim() + "','" + sblx.Text.Trim() + "','" + fmr.Text.Trim() + "','" + jslxr.Text.Trim() + "','" + szxy.Text.Trim() + "','" + bdID + "' )", null);
Response.Write("<script>alert('保存数据成功!');</script>");
Response.Write("<script>opener.location.href='zlchakan.aspx';</script>");
Response.Write("<script>window.opener = null;window.close();</script>");
}
void oktoedit()
{
sqr.ReadOnly = false;
zlztmc.ReadOnly = false;
fmr.ReadOnly = false;
jslxr.ReadOnly = false;
szxy.ReadOnly = false;
}
void notoedit()
{
sqr.ReadOnly = true;
zlztmc.ReadOnly = true;
fmr.ReadOnly = true;
jslxr.ReadOnly = true;
szxy.ReadOnly = true;
}
//编辑
protected void xiugai(object sender, EventArgs e)
{
oktoedit();
}
//修改
protected void qrxiugai2(object sender, EventArgs e)
{
sdb.Update("update zlsqdb set sqr = '" + sqr.Text.Trim() + "', zlztmc = '" + zlztmc.Text.Trim() + "', sblx = '" + sblx.Text.Trim() + "', fmr = '" + fmr.Text.Trim() + "', jslxr = '" + jslxr.Text.Trim() + "', szxy = '" + szxy.Text.Trim() + "' where zlID = '" + Request["ID"].ToString() + "'", null);
Response.Write("<script>alert('保存数据成功!');</script>");
Response.Write("<script>opener.location.href='zlchakan.aspx';</script>");
Response.Write("<script>window.opener = null;window.close();</script>");
}
protected void zlDownload_Click(object sender, EventArgs e)
{
FileUtil zlfile = new FileUtil();
string fileID = "中索专利交底书示例";
try
{
zlfile.fileDownload(fileID);
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
} |
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MTB.GameHandler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TranslationTools
{
/// <summary>
/// CommandEditor.xaml 的交互逻辑
/// </summary>
public partial class CommandEditor : CustomDialog
{
public TreeDataGridItem Item;
public MapTranslator Translator;
public CommandEditor()
{
InitializeComponent();
}
public void SetCurrentItem(TreeDataGridItem item, MapTranslator translator)
{
Item = item;
Translator = translator;
original.Text = item.Original;
translated.Text = item.Translated;
}
private void Close(object sender, RoutedEventArgs e)
{
(Application.Current.MainWindow as MetroWindow).HideMetroDialogAsync(this);
}
private void Confirm(object sender, RoutedEventArgs e)
{
(Application.Current.MainWindow as MetroWindow).HideMetroDialogAsync(this);
Item.Translated = translated.Text;
Translator.DialogueClosed();
}
}
}
|
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace CODE.Framework.Wpf.Layout
{
/// <summary>
/// Special items presenter class that can natively scroll its own content
/// </summary>
public class ScrollAwareItemsPresenter : ItemsPresenter, IScrollInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="ScrollAwareItemsPresenter"/> class.
/// </summary>
public ScrollAwareItemsPresenter()
{
CanHorizontallyScroll = true;
CanVerticallyScroll = false;
Loaded += (s, e) =>
{
if (ScrollOwner != null)
{
ScrollOwner.InvalidateArrange();
ScrollOwner.InvalidateMeasure();
ScrollOwner.InvalidateScrollInfo();
}
};
}
private UIElement _childElement;
private IScrollInfo _childScrollInfo;
/// <summary>
/// Overrides the base class implementation of <see cref="M:System.Windows.FrameworkElement.MeasureOverride(System.Windows.Size)" /> to measure the size of the <see cref="T:System.Windows.Controls.ItemsPresenter" /> object and return proper sizes to the layout engine.
/// </summary>
/// <param name="constraint">Constraint size is an "upper limit." The return value should not exceed this size.</param>
/// <returns>The desired size.</returns>
protected override Size MeasureOverride(Size constraint)
{
if (_childElement == null) _childElement = (VisualTreeHelper.GetChildrenCount(this) > 0) ? VisualTreeHelper.GetChild(this, 0) as UIElement : null;
if (_childElement == null) return base.MeasureOverride(constraint);
_childElement.Measure(constraint);
if (_childScrollInfo == null)
{
_childScrollInfo = _childElement as IScrollInfo;
if (_childScrollInfo != null && _childScrollInfo.ScrollOwner == null && _scrollOwner != null)
{
_childScrollInfo.ScrollOwner = _scrollOwner;
_scrollOwner.InvalidateScrollInfo();
}
}
return _childElement.DesiredSize;
}
/// <summary>
/// Scrolls up within content by one logical unit.
/// </summary>
public void LineUp()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineUp();
}
/// <summary>
/// Scrolls down within content by one logical unit.
/// </summary>
public void LineDown()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineDown();
}
/// <summary>
/// Scrolls left within content by one logical unit.
/// </summary>
public void LineLeft()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineLeft();
}
/// <summary>
/// Scrolls right within content by one logical unit.
/// </summary>
public void LineRight()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineRight();
}
/// <summary>
/// Scrolls up within content by one page.
/// </summary>
public void PageUp()
{
if (_childScrollInfo == null) return;
_childScrollInfo.PageUp();
}
/// <summary>
/// Scrolls down within content by one page.
/// </summary>
public void PageDown()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineDown();
}
/// <summary>
/// Scrolls left within content by one page.
/// </summary>
public void PageLeft()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineLeft();
}
/// <summary>
/// Scrolls right within content by one page.
/// </summary>
public void PageRight()
{
if (_childScrollInfo == null) return;
_childScrollInfo.LineRight();
}
/// <summary>
/// Scrolls up within content after a user clicks the wheel button on a mouse.
/// </summary>
public void MouseWheelUp()
{
if (_childScrollInfo == null) return;
_childScrollInfo.MouseWheelUp();
}
/// <summary>
/// Scrolls down within content after a user clicks the wheel button on a mouse.
/// </summary>
public void MouseWheelDown()
{
if (_childScrollInfo == null) return;
_childScrollInfo.MouseWheelDown();
}
/// <summary>
/// Scrolls left within content after a user clicks the wheel button on a mouse.
/// </summary>
public void MouseWheelLeft()
{
if (_childScrollInfo == null) return;
_childScrollInfo.MouseWheelLeft();
}
/// <summary>
/// Scrolls right within content after a user clicks the wheel button on a mouse.
/// </summary>
public void MouseWheelRight()
{
if (_childScrollInfo == null) return;
_childScrollInfo.MouseWheelRight();
}
/// <summary>
/// Sets the amount of horizontal offset.
/// </summary>
/// <param name="offset">The degree to which content is horizontally offset from the containing viewport.</param>
public void SetHorizontalOffset(double offset)
{
if (_childScrollInfo == null) return;
_childScrollInfo.SetHorizontalOffset(offset);
}
/// <summary>
/// Sets the amount of vertical offset.
/// </summary>
/// <param name="offset">The degree to which content is vertically offset from the containing viewport.</param>
public void SetVerticalOffset(double offset)
{
if (_childScrollInfo == null) return;
_childScrollInfo.SetVerticalOffset(offset);
}
/// <summary>
/// Forces content to scroll until the coordinate space of a <see cref="T:System.Windows.Media.Visual" /> object is visible.
/// </summary>
/// <param name="visual">A <see cref="T:System.Windows.Media.Visual" /> that becomes visible.</param>
/// <param name="rectangle">A bounding rectangle that identifies the coordinate space to make visible.</param>
/// <returns>A <see cref="T:System.Windows.Rect" /> that is visible.</returns>
public Rect MakeVisible(Visual visual, Rect rectangle)
{
if (_childScrollInfo == null) return Rect.Empty;
return _childScrollInfo.MakeVisible(visual, rectangle);
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the vertical axis is possible.
/// </summary>
/// <value><c>true</c> if this instance can vertically scroll; otherwise, <c>false</c>.</value>
public bool CanVerticallyScroll
{
get
{
if (_childScrollInfo == null) return false;
return _childScrollInfo.CanVerticallyScroll;
}
set
{
if (_childScrollInfo == null) return;
_childScrollInfo.CanVerticallyScroll = value;
}
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the horizontal axis is possible.
/// </summary>
/// <value><c>true</c> if this instance can horizontally scroll; otherwise, <c>false</c>.</value>
public bool CanHorizontallyScroll
{
get
{
if (_childScrollInfo == null) return false;
return _childScrollInfo.CanHorizontallyScroll;
}
set
{
if (_childScrollInfo == null) return;
_childScrollInfo.CanHorizontallyScroll = value;
}
}
/// <summary>
/// Gets the horizontal size of the extent.
/// </summary>
/// <value>The width of the extent.</value>
public double ExtentWidth
{
get
{
if (_childScrollInfo == null) return 0d;
return _childScrollInfo.ExtentWidth;
}
}
/// <summary>
/// Gets the vertical size of the extent.
/// </summary>
/// <value>The height of the extent.</value>
public double ExtentHeight
{
get
{
if (_childScrollInfo == null) return 0d;
return _childScrollInfo.ExtentHeight;
}
}
/// <summary>
/// Gets the horizontal size of the viewport for this content.
/// </summary>
/// <value>The width of the viewport.</value>
public double ViewportWidth
{
get
{
if (_childScrollInfo == null) return 0d;
return _childScrollInfo.ViewportWidth;
}
}
/// <summary>
/// Gets the vertical size of the viewport for this content.
/// </summary>
/// <value>The height of the viewport.</value>
public double ViewportHeight
{
get
{
if (_childScrollInfo == null) return 0d;
return _childScrollInfo.ViewportHeight;
}
}
/// <summary>
/// Gets the horizontal offset of the scrolled content.
/// </summary>
/// <value>The horizontal offset.</value>
public double HorizontalOffset
{
get
{
if (_childScrollInfo == null) return 0d;
return _childScrollInfo.HorizontalOffset;
}
}
/// <summary>
/// Gets the vertical offset of the scrolled content.
/// </summary>
/// <value>The vertical offset.</value>
public double VerticalOffset
{
get
{
if (_childScrollInfo == null) return 0d;
return _childScrollInfo.VerticalOffset;
}
}
private ScrollViewer _scrollOwner;
/// <summary>
/// Gets or sets a <see cref="T:System.Windows.Controls.ScrollViewer" /> element that controls scrolling behavior.
/// </summary>
/// <value>The scroll owner.</value>
public ScrollViewer ScrollOwner
{
get
{
if (_childScrollInfo == null) return null;
return _childScrollInfo.ScrollOwner;
}
set
{
_scrollOwner = value;
InvalidateArrange();
InvalidateMeasure();
value.InvalidateArrange();
value.InvalidateMeasure();
value.InvalidateScrollInfo();
if (_childScrollInfo == null) return;
_childScrollInfo.ScrollOwner = value;
}
}
}
}
|
using System;
using System.Data;
using System.Data.OracleClient;
using System.Configuration;
using EasyDev.Util;
namespace EasyDev.PL
{
[Obsolete("此类已经过时")]
public class OracleSession : DBSessionBase, IDBSession
{
/// <summary>
/// 默认构造器
/// </summary>
public OracleSession()
{
this._adapter = new OracleDataAdapter();
this.dataSourceName = "OracleDataSource";
this.InitDataSource();
}
/// <summary>
/// 构造器
/// 根据数据源名称初始化数据库会话
/// </summary>
/// <param name="_dataSourceName">数据源名称</param>
public OracleSession(string _dataSourceName)
{
this.dataSourceName = _dataSourceName;
this.InitDataSourceByName(_dataSourceName);
}
/// <summary>
/// 数据库连接字符串
/// </summary>
public override string ConnectionString
{
get
{
//如果连接字符串为空则从配置文件中取
if (this.connectionString.Equals(""))
{
this.connectionString = ConvertUtil.ConvertToString(ConfigurationManager.ConnectionStrings[this.dataSourceName]);
}
//如果没有指定数据连接串配置名称,则默认取第一个
if (this.connectionString.Equals(""))
{
this.connectionString = ConvertUtil.ConvertToString(ConfigurationManager.ConnectionStrings[0]);
}
return this.connectionString;
}
set
{
this.ConnectionString = value;
}
}
#region IDBSession 成员
/// <summary>
/// 初始化数据源
/// </summary>
public override void InitDataSource()
{
try
{
this._connection = new OracleConnection(this.ConnectionString);
this._command = new OracleCommand();
}
catch (DALCoreException e)
{
throw e;
}
}
/// <summary>
/// 根据配置名称初始化数据源
/// </summary>
/// <param name="cfgName">数据源配置节名称</param>
public override void InitDataSourceByName(string cfgName)
{
try
{
string customConnectionString = System.Convert.ToString(ConfigurationManager.ConnectionStrings[cfgName]);
this._connection = new OracleConnection(customConnectionString);
this._command = new OracleCommand();
}
catch (DALCoreException e)
{
throw e;
}
}
/// <summary>
/// 根据SQL创建命令对象
/// </summary>
/// <param name="sqlCmdText">SQL命令文本</param>
public override IDbCommand CreateCommand(string sqlCmdText)
{
IDbCommand command = null;
try
{
if (null == command)
{
command = new OracleCommand(sqlCmdText, (OracleConnection)this._connection);
}
else
{
command.CommandText = sqlCmdText;
command.Connection = this._connection;
}
}
catch (DALCoreException e)
{
throw e;
}
return command;
}
#endregion
/// <summary>
/// 开启事务
/// </summary>
public override void BeginTransaction()
{
try
{
if (this._connection != null)
{
this._transaction = this._connection.BeginTransaction(IsolationLevel.Serializable);
if (this._command == null)
{
this._command = new OracleCommand();
}
this._command.Transaction = this._transaction; //初始化命令对象的事务属性
}
else
{
throw new DALCoreException("Failed_to_begin_transaction"); //开启事务失败,可能是数据库连接没有被初始化
}
}
catch (DALCoreException e)
{
throw e;
}
}
#region 待实现方法
//public override IDBCommandWrapper<> GetStoredProcCommandWrapper()
//{
// throw new Exception("The method or operation is not implemented.");
//}
//public override IDBCommandWrapper GetSqlCommandWithParametersWrapper(string sqlCmd, IDictionary<string, object> parameters)
//{
// throw new Exception("The method or operation is not implemented.");
//}
#endregion
}
} |
using Microsoft.Owin.Security.Infrastructure;
namespace ServerApi.OwinMiddleware.Authentication
{
public class SkautIsAuthenticationMiddleware : AuthenticationMiddleware<SkautIsAuthenticationOptions>
{
public SkautIsAuthenticationMiddleware(
Microsoft.Owin.OwinMiddleware next,
SkautIsAuthenticationOptions options) : base(next, options)
{
}
protected override AuthenticationHandler<SkautIsAuthenticationOptions> CreateHandler()
{
return new SkautIsAuthenticationHandler();
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using GameFrame;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System.Collections.Generic;
public class scrollTest : MonoBehaviour {
/// <summary>
/// 构造器实参可以为具有特点格式的委托,如:本处可以为委托
/// public delegate void UIEventHandleVector2( Vector2 v2 )的对象,
/// 即:UIEventHandleVector2 scroll;
/// </summary>
void Start ()
{
var trigger = transform.GetComponent<EventTrigger>();
if (trigger == null)
{
trigger = transform.gameObject.AddComponent<EventTrigger>();
}
trigger.triggers = new List<EventTrigger.Entry>();
EventTrigger.Entry entry1 = new EventTrigger.Entry();
entry1.eventID = EventTriggerType.PointerClick;
entry1.callback = new EventTrigger.TriggerEvent();
UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(Click);
entry1.callback.AddListener(callback);
trigger.triggers.Add(entry1);
EventTrigger.Entry entry2 = new EventTrigger.Entry();
entry2.eventID = EventTriggerType.PointerUp;
entry2.callback = new EventTrigger.TriggerEvent();
callback = new UnityAction<BaseEventData>(ClickUp);
entry1.callback.AddListener(callback);
trigger.triggers.Add(entry2);
UnityAction<Vector2> action = new UnityAction<Vector2>(Scroll);
ScrollRect scrollRect = transform.GetComponent<ScrollRect>();
if (scrollRect != null)
{
scrollRect.onValueChanged.AddListener(action);
}
}
public void Click(BaseEventData arg0)
{
Debug.Log("Test Click");
}
public void ClickUp(BaseEventData arg0)
{
Debug.Log("Test ClickUp");
}
public void Scroll(Vector2 v2)
{
Debug.Log("Scroll, v2 arg:" + v2.ToString());
}
public void LockScreen()
{
Tools.LockScreen();
GameObject ob = GameObject.Find("Cube");
GameObject.Destroy(ob);
}
public void UnLockScreen()
{
Tools.UnlockScreen();
}
public void CreateEmptyObject()
{
Tools.CreatEmptyGameObject();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cw3.DTOs.Requests;
using Cw3.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Cw3.Controllers
{
[ApiController]
[Route("api/enrollments")]
public class EnrollmentsController : ControllerBase
{
private IStudentDbService _service;
public EnrollmentsController(IStudentDbService service)
{
_service = service;
}
[Route("api/enrollments")]
[HttpPost]
[Authorize(Roles = "employee")]
public IActionResult EnrollStudent(EnrollStudentRequest request)
{
var response = _service.EnrollStudent(request);
//...
return Ok(response);
}
[Route("api/enrollments/promotions")]
[HttpPost]
[Authorize(Roles = "employee")]
public IActionResult PromoteStudent(PromotionRequest request)
{
var response = _service.PromoteStudent(request);
return Ok(response);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ball : MonoBehaviour
{
[Header("Set Dynamically")]
public Text scoreGT;
public Text winGT;
void Start()
{
GameObject scoreGO = GameObject.Find("ScoreCounter"); // b
// Get the Text Component of that GameObject
scoreGT = scoreGO.GetComponent<Text>(); // c
// Set the starting number of points to 0
GameObject winGO = GameObject.Find("Win");
winGT = winGO.GetComponent<Text>();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Goal"))
{
other.gameObject.SetActive(false);
int score = int.Parse(scoreGT.text); // d
// Add points for catching the apple
score += 1;
// Convert the score back to a string and display it
scoreGT.text = score.ToString();
if (score == 8)
{
winGT.text = ("You Win!");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CRL.FavoriteProduct
{
/// <summary>
/// 商品收藏
/// </summary>
public class FavoriteAction<TType> : BaseAction<TType, IFavoriteProduct> where TType : class
{
/// <summary>
/// 添加到收藏
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="product"></param>
public static void AddToFavorite<T>(T product) where T : IFavoriteProduct,new()
{
//Delete<IFavoriteProduct>(b => b.UserId == product.UserId && b.ProductId == product.ProductId);
if (QueryItem<T>(b => b.UserId == product.UserId && b.ProductId == product.ProductId) == null)
{
Add(product);
}
}
/// <summary>
/// 查询用户收藏
/// </summary>
/// <typeparam name="TProduct"></typeparam>
/// <param name="userId"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="count"></param>
/// <returns></returns>
//public List<Product.IProductBase> QueryUserFavorite<TProduct>(string userId, int pageIndex, int pageSize, out int count)
// where TProduct:Product.IProduct,new()
//{
// List<TProduct> products=new List<TProduct>();
// ParameCollection c = new ParameCollection();
// c.SetQueryPageIndex(pageIndex);
// c.SetQueryPageSize(pageSize);
// c["userId"] = userId;
// c.SetQuerySortField("AddTime");
// c.SetQuerySortDesc(true);
// //查询收藏
// List<IFavoriteProduct> list = QueryListByPage<IFavoriteProduct>(c,out count);
// if (list.Count == 0)
// return new List<Product.IProductBase>();
// Dictionary<int, DateTime> list2 = new Dictionary<int, DateTime>();
// ParameCollection c2 = new ParameCollection();
// string inStr = "";
// foreach (var item in list)
// {
// list2.Add(item.ProductId, item.AddTime);
// inStr += string.Format("{0},",item.ProductId);
// }
// inStr = inStr.Substring(0, inStr.Length - 1);
// c["$id"] = string.Format(" in({0})", inStr);
// c2.SetQueryFields("id,ProductName,SoldPrice,ProductImage");
// //关联出产品
// products = Product.ProductAction.QueryList<TProduct>(c2);
// foreach(TProduct item in products)
// {
// item.AddTime = list2[item.Id];//更新时间
// }
// return Base.CloneToSimple<Product.IProductBase, TProduct>(products);
//}
}
}
|
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json;
using Pobs.Comms;
using Pobs.Tests.Integration.Helpers;
using Pobs.Web.Helpers;
using Pobs.Web.Models.Account;
using Xunit;
namespace Pobs.Tests.Integration.Account
{
public class SignUpTests : IDisposable
{
private const string Url = "/api/account/signup";
private readonly string _username = "mary_coffeemug_" + Utils.GenerateRandomString(10);
[Fact]
public async Task ValidInputs_ShouldCreateUserAndGetToken()
{
var payload = new SignUpFormModel
{
Username = _username,
Password = "Password1",
};
LoggedInUserModel responseModel;
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response = await client.PostAsync(Url, payload.ToJsonContent());
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
responseModel = JsonConvert.DeserializeObject<LoggedInUserModel>(responseContent);
var decodedToken = new JwtSecurityTokenHandler().ReadJwtToken(responseModel.Token);
var identityClaim = decodedToken.Claims.Single(x => x.Type == "unique_name");
int.TryParse(identityClaim.Value, out int userId);
Assert.Equal(responseModel.Id, userId);
Assert.True((decodedToken.ValidTo - DateTime.UtcNow).TotalDays > 365);
var idTokenCookie = response.Headers.GetIdTokenCookie();
Assert.NotNull(idTokenCookie);
Assert.Equal(responseModel.Token, idTokenCookie.Value);
Assert.Equal("/", idTokenCookie.Path);
Assert.True(idTokenCookie.HttpOnly);
Assert.True(idTokenCookie.Expires.HasValue);
Assert.True((idTokenCookie.Expires.Value - DateTime.UtcNow).TotalDays > 365);
}
using (var dbContext = TestSetup.CreateDbContext())
{
var user = dbContext.Users.FirstOrDefault(x => x.Username == payload.Username);
Assert.NotNull(user);
Assert.Equal(payload.Username, user.Username);
Assert.True(user.CreatedAt > DateTime.UtcNow.AddMinutes(-1));
Assert.Null(user.Email);
Assert.Null(user.EmailVerificationToken);
// Also check responseModel
Assert.Equal(user.Id, responseModel.Id);
Assert.Equal(user.Username, responseModel.Username);
}
}
[Fact]
public async Task EmailIncluded_ShouldCreateUser()
{
var payload = new SignUpFormModel
{
Username = _username,
Password = "Password1",
Email = Utils.GenerateRandomString(10) + "💩@example.com",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response = await client.PostAsync(Url, payload.ToJsonContent());
response.EnsureSuccessStatusCode();
}
using (var dbContext = TestSetup.CreateDbContext())
{
var user = dbContext.Users.FirstOrDefault(x => x.Username == payload.Username);
Assert.NotNull(user);
Assert.Equal(payload.Email, user.Email);
Assert.NotNull(user.EmailVerificationToken);
Assert.True(AuthUtils.VerifyPasswordHash(payload.Password, user.PasswordHash, user.PasswordSalt));
string urlEncodedToken = WebUtility.UrlEncode($"{user.Id}-{user.EmailVerificationToken}");
string expectedVerificationUrl = $"{TestSetup.AppSettings.Domain}/account/verifyemail?token={urlEncodedToken}";
emailSenderMock.Verify(x => x.SendEmailVerification(payload.Email, payload.Username, expectedVerificationUrl));
}
}
[Fact]
public async Task UpperCaseEmail_ShouldStoreLowerCase()
{
var lowerCaseEmail = Utils.GenerateRandomString(10) + "💩@example.com".ToLowerInvariant();
var payload = new SignUpFormModel
{
Email = lowerCaseEmail.ToUpperInvariant(),
Username = _username,
Password = "Password1",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response = await client.PostAsync(Url, payload.ToJsonContent());
response.EnsureSuccessStatusCode();
}
using (var dbContext = TestSetup.CreateDbContext())
{
var user = dbContext.Users.FirstOrDefault(x => x.Username == payload.Username);
Assert.Equal(lowerCaseEmail, user.Email);
emailSenderMock.Verify(x => x.SendEmailVerification(lowerCaseEmail, payload.Username, It.IsAny<string>()));
}
}
[Fact]
public async Task ExistingEmail_ShouldError()
{
var payload = new SignUpFormModel
{
Email = Utils.GenerateRandomString(10) + "@example.com",
Username = _username,
Password = "Password1",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response1 = await client.PostAsync(Url, payload.ToJsonContent());
response1.EnsureSuccessStatusCode();
emailSenderMock.Reset();
var payload2 = new SignUpFormModel
{
// Also test case-sensitivity, white space
Email = " \t\r\n" + payload.Email.ToUpper() + " \t\r\n",
Username = "mary_coffeemug_" + Utils.GenerateRandomString(10),
Password = "Password1",
};
var response2 = await client.PostAsync(Url, payload2.ToJsonContent());
Assert.Equal(HttpStatusCode.BadRequest, response2.StatusCode);
var responseContent = await response2.Content.ReadAsStringAsync();
Assert.Equal($"An account already exists for '{payload.Email}'.", responseContent);
}
emailSenderMock.Verify(x => x.SendEmailVerification(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Theory]
[InlineData("invalidemail")]
[InlineData("invalidemail@")]
[InlineData("invalidemail@example@example.com")]
public async Task InvalidEmail_ShouldError(string email)
{
var payload = new SignUpFormModel
{
Email = email,
Username = _username,
Password = "Password1",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response = await client.PostAsync(Url, payload.ToJsonContent());
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal($"Invalid Email address: '{payload.Email}'.", responseContent);
}
emailSenderMock.Verify(x => x.SendEmailVerification(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Theory]
[InlineData("username@")]
[InlineData("username@example.com")]
[InlineData("@username")]
public async Task InvalidUsername_ShouldError(string username)
{
var payload = new SignUpFormModel
{
Email = Utils.GenerateRandomString(10) + "@example.com",
Username = username,
Password = "Password1",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response = await client.PostAsync(Url, payload.ToJsonContent());
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal($"Invalid Username, must not contain '@': '{payload.Username}'.", responseContent);
}
emailSenderMock.Verify(x => x.SendEmailVerification(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Fact]
public async Task ExistingUsername_ShouldError()
{
var payload = new SignUpFormModel
{
Email = Utils.GenerateRandomString(10) + "@example.com",
Username = _username,
Password = "Password1",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response1 = await client.PostAsync(Url, payload.ToJsonContent());
response1.EnsureSuccessStatusCode();
emailSenderMock.Reset();
var response2 = await client.PostAsync(Url, payload.ToJsonContent());
Assert.Equal(HttpStatusCode.BadRequest, response2.StatusCode);
var responseContent = await response2.Content.ReadAsStringAsync();
Assert.Equal($"Username '{_username}' is already taken.", responseContent);
}
emailSenderMock.Verify(x => x.SendEmailVerification(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Fact]
public async Task PasswordTooShort_ShouldError()
{
var payload = new SignUpFormModel
{
Email = Utils.GenerateRandomString(10) + "@example.com",
Username = _username,
Password = "123456",
};
var emailSenderMock = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(emailSenderMock.Object))
using (var client = server.CreateClient())
{
var response = await client.PostAsync(Url, payload.ToJsonContent());
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal("Password must be at least 7 characters.", responseContent);
}
emailSenderMock.Verify(x => x.SendEmailVerification(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
public void Dispose()
{
using (var dbContext = TestSetup.CreateDbContext())
{
var user = dbContext.Users.FirstOrDefault(x => x.Username == _username);
if (user != null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
}
}
|
namespace MySurveys.Route.Tests
{
using System.Net.Http;
using System.Web.Routing;
using MvcRouteTester;
using NUnit.Framework;
using Web;
using Web.Controllers;
[TestFixture]
public class Home
{
private RouteCollection routes;
[SetUp]
public void RoutesRegistration()
{
this.routes = new RouteCollection();
RouteConfig.RegisterRoutes(this.routes);
}
[Test]
public void IndexActionShoulMapCorrectly()
{
const string CreateUrl = "/";
this.routes
.ShouldMap(CreateUrl)
.To<HomeController>(HttpMethod.Get, x => x.Index());
}
[Test]
public void IndexActionShoulMapCorrectly2()
{
const string CcreateUrl = "/Home";
this.routes
.ShouldMap(CcreateUrl)
.To<HomeController>(HttpMethod.Get, x => x.Index());
}
[Test]
public void IndexActionShoulMapCorrectly3()
{
const string CreateUrl = "/Home/Index";
this.routes
.ShouldMap(CreateUrl)
.To<HomeController>(HttpMethod.Get, x => x.Index());
}
[Test]
public void HasRouteWithoutController()
{
RouteAssert.HasRoute(this.routes, "/foo/bar/1");
}
[Test]
public void DoesNotHaveOtherRoute()
{
RouteAssert.NoRoute(this.routes, "/foo/bar/fish/spon");
}
}
}
|
using System;
using System.Windows.Forms;
using UserNamespace;
namespace UNO__ {
public partial class PersonnalMessage : Form {
public void SetText(User user) {
textBox1.Text = user.Name;
textBox2.Text = user.Id;
}
public PersonnalMessage() {
InitializeComponent();
}
public delegate void ReturnUser(User ret);
public event ReturnUser ReturnEvent;
private void button1_Click(object sender, EventArgs e) {
User ret = new User(textBox1.Text, textBox2.Text);
ReturnEvent(ret);
Owner.Show();
this.Close();
}
private void PersonnalMessage_FormClosed(object sender, FormClosedEventArgs e) {
Owner.Show();
}
private void textBox2_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
User ret = new User(textBox1.Text, textBox2.Text);
ReturnEvent(ret);
Owner.Show();
this.Close();
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
User ret = new User(textBox1.Text, textBox2.Text);
ReturnEvent(ret);
Owner.Show();
this.Close();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
public partial class Admin_Orders : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
display();
}
private void display()
{
//SqlCommand cmd = new SqlCommand("SELECT COUNT(id),id FROM tborder GROUP BY mobile",
// con);
//con.Open();
//string st = "";
//SqlDataReader reader = cmd.ExecuteReader();
//if (reader.HasRows)
//{
// while (reader.Read())
// {
// st += reader.GetInt32(0).ToString()+",";
// }
//}
//st=st.Substring(0, st.Length-1);
//con.Close();
//cmd.Dispose();
string stm = Request.Cookies["mobile"].Value;
string stc = Request.Cookies["code"].Value;
string qry1 = "select id,Address,mobile as Mobile,status as Status from tborder where mobile='"+ stm + "' and code='"+stc+"'";
SqlDataAdapter adp = new SqlDataAdapter(qry1, con);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName== "Detail")
{
Response.Redirect("detialorder.aspx?id="+e.CommandArgument.ToString());
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossRock : Bullet
{
Rigidbody rigid;
float angularPower = 2;
float scaleValue = 0.1f;
bool isShoot;
void Awake() {
rigid = GetComponent<Rigidbody>();
StartCoroutine(GainPowerTimer());
StartCoroutine(GainPower());
}
IEnumerator GainPowerTimer() {
yield return new WaitForSeconds(2.2f);
isShoot = true;
}
IEnumerator GainPower() {
while (!isShoot) {
angularPower += 0.02f;
scaleValue += 0.005f;
transform.localScale = Vector3.one * scaleValue;
rigid.AddTorque(transform.right * angularPower, ForceMode.Acceleration);
yield return null;
}
}
}
|
using Domain.FixingDomain.Interfaces;
using FluentAssertions;
using Repositories.Repository;
using System;
using Xunit;
namespace KursatorTestProject
{
public class NbpProviderTests
{
private readonly Uri _uri;
public NbpProviderTests()
{
_uri = new Uri("http://api.nbp.pl/api/");
}
[Fact]
public void GetFixingsTest()
{
INbpProvider systemUnderTest = new NbpProvider(_uri);
var result = systemUnderTest.GetFixings().Result;
result.Should().NotBeNull();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GDS.Comon
{
public class DateHelper
{
//获取当前月最后一天
public DateTime CurrentLastDayOfMonth()
{
DateTime dt = DateTime.Now; //当前时间
DateTime startMonth = dt.AddDays(1 - dt.Day); //本月月初
DateTime endMonth = startMonth.AddMonths(1).AddDays(-1); //本月月末
return endMonth;
}
//获取当前双月最后一天
public DateTime CurrentLastDayOfDoubleMonth()
{
DateTime dt = DateTime.Now; //当前时间
DateTime startMonth = dt.AddDays(1 - dt.Day); //本月月初
int month = dt.Month % 2;
DateTime endMonth = startMonth.AddMonths(month + 1).AddDays(-1); //本月月末
return endMonth;
}
//获本季度末最后一天
public DateTime CurrentLastDayOfQuarter()
{
DateTime dt = DateTime.Now; //当前时间
DateTime startQuarter = dt.AddMonths(0 - (dt.Month - 1) % 3).AddDays(1 - dt.Day); //本季度初
DateTime endQuarter = startQuarter.AddMonths(3).AddDays(-1); //本季度末
return endQuarter;
}
//获本半年最后一天
public DateTime CurrentLastDayOfHalfYear()
{
DateTime dt = DateTime.Now; //当前时间
if (1 <= dt.Month && dt.Month <= 6)
{
return DateTime.Parse(dt.Year + "-06" + "-30");
}
return DateTime.Parse(dt.Year + "-12" + "-31");
}
//获取结算日期下月最后一天
public DateTime CurrentLastDayOfNextMonth(DateTime dt)
{
DateTime startMonth = dt.AddDays(1 - dt.Day); //本月月初
DateTime endMonth = startMonth.AddMonths(2).AddDays(-1); //本月月末
return endMonth;
}
}
}
|
using System;
using System.Collections.Generic;
namespace DemoApp.Entities
{
public partial class SchoolClasses
{
public SchoolClasses()
{
SchoolClassAllocations = new HashSet<SchoolClassAllocations>();
SchoolStaffSubjects = new HashSet<SchoolStaffSubjects>();
}
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<SchoolClassAllocations> SchoolClassAllocations { get; set; }
public virtual ICollection<SchoolStaffSubjects> SchoolStaffSubjects { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Common
{
public static class TaskUtility
{
public static ObjectAwaiter GetAwaiter(this Object obj) => new ObjectAwaiter(obj);
public static CoroutineAwaiter GetAwaiter(this IEnumerator coroutine) => new CoroutineAwaiter(coroutine);
public struct ObjectAwaiter : INotifyCompletion
{
private readonly Object obj;
public ObjectAwaiter(Object obj) =>
this.obj = obj;
public bool IsCompleted => obj;
public async void OnCompleted(Action continuation)
{
while (!IsCompleted)
await Task.Yield();
continuation?.Invoke();
}
public void GetResult() { }
}
public struct CoroutineAwaiter : INotifyCompletion
{
static readonly List<IEnumerator> completed = new List<IEnumerator>();
readonly IEnumerator coroutine;
public CoroutineAwaiter(IEnumerator coroutine) : this()
{
this.coroutine = coroutine;
Run().StartCoroutine();
}
IEnumerator Run()
{
yield return coroutine;
completed.Add(coroutine);
}
public bool IsCompleted
{
get
{
if (completed.Contains(coroutine))
{
completed.Remove(coroutine);
return true;
}
return false;
}
}
public async void OnCompleted(Action continuation)
{
while (!completed.Contains(coroutine))
await Task.Yield();
continuation?.Invoke();
}
public void GetResult() { }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;
using RestSharp.Authenticators;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Texter.Models
{
public class Message
{
public string To { get; set; }
public string From = "+19093216348";
public string Body { get; set; }
public string Status { get; set; }
public static List<Message> GetMessages()
{
var client = new RestClient("https://api.twilio.com/2010-04-01");
var request = new RestRequest("Accounts/" + EnvironmentVariables.AccountSid + "/Messages.json", Method.GET);
client.Authenticator = new HttpBasicAuthenticator(EnvironmentVariables.AccountSid, EnvironmentVariables.AuthToken);
var response = new RestResponse();
Task.Run(async () =>
{
response = await GetResponseContentAsync(client, request) as RestResponse;
}).Wait();
JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(response.Content);
var messageList = JsonConvert.DeserializeObject<List<Message>>(jsonResponse["messages"].ToString());
return messageList;
}
public void Send()
{
var client = new RestClient("https://api.twilio.com/2010-04-01");
var request = new RestRequest("Accounts/" + EnvironmentVariables.AccountSid + "/Messages", Method.POST);
var parsedTo = To.Replace("-", "").Replace(".", "").Replace(")", "").Replace("(", "").Replace(" ", "");
List<string> catFact = Message.GetCatFact();
request.AddParameter("To", "+1" + parsedTo);
request.AddParameter("From", From);
request.AddParameter("Body", Body + " Did you know: " + catFact[0]);
client.Authenticator = new HttpBasicAuthenticator(EnvironmentVariables.AccountSid, EnvironmentVariables.AuthToken);
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
}
public static Task<IRestResponse> GetResponseContentAsync(RestClient theClient, RestRequest theRequest)
{
var tcs = new TaskCompletionSource<IRestResponse>();
theClient.ExecuteAsync(theRequest, response => {
tcs.SetResult(response);
});
return tcs.Task;
}
public static List<String> GetCatFact()
{
//Client is the base of the api call
var client = new RestClient("http://catfacts-api.appspot.com/api/facts");
//Add parameters in request
var request = new RestRequest("", Method.GET);
var response = new RestResponse();
Task.Run(async () =>
{
response = await GetResponseContentAsync(client, request) as RestResponse;
}).Wait();
//Converts the json object to the return type you want
JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(response.Content);
//Looks for the key "facts" and returns list of values associated with that key
var messageList = JsonConvert.DeserializeObject<List<String>>(jsonResponse["facts"].ToString());
Console.WriteLine(messageList);
return messageList;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using TAiMStore.Domain;
using TAiMStore.Model;
using TAiMStore.Model.Classes;
using TAiMStore.Model.Repository;
using TAiMStore.Model.UnitOfWork;
using TAiMStore.Model.ViewModels;
namespace TAiMStore.WebUI.Controllers
{
public class CartController : Controller
{
private readonly IProductRepository _repository;
private readonly ICategoryRepository _categoryRepository;
private readonly IUserRepository _userRepository;
private readonly IPaymentRepository _paymentRepository;
private readonly IRoleRepository _roleRepository;
private readonly IContactsRepository _contactsRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IOrderRepository _orderRepository;
private readonly IOrderProductRepository _orderProductRepository;
//private IOrderProcessor _orderProcessor;
public CartController(IProductRepository productRepository, ICategoryRepository categoryRepository, IUserRepository userRepository,
IPaymentRepository paymentRepository, IRoleRepository roleRepository, IContactsRepository contactsRepository,
IOrderRepository orderRepository, IOrderProductRepository orderProductRepository, IUnitOfWork unitOfWork)
{
_repository = productRepository;
_categoryRepository = categoryRepository;
_userRepository = userRepository;
_paymentRepository = paymentRepository;
_roleRepository = roleRepository;
_contactsRepository = contactsRepository;
_orderRepository = orderRepository;
_orderProductRepository = orderProductRepository;
_unitOfWork = unitOfWork;
categoryRepository.GetAll();
}
public ViewResult Index(Cart cart, string returnUrl)
{
var masterPage = new MasterPageModel();
masterPage.CartView = new CartIndexViewModel
{
Cart = GetCart(),
ReturnUrl = returnUrl
};
var userManager = new UserManager(_userRepository, _roleRepository, _contactsRepository, _unitOfWork);
if (HttpContext.User.Identity.IsAuthenticated)
{
var user = userManager.GetUserViewModelByName(HttpContext.User.Identity.Name);
var userRole = string.Empty;
if (userManager.UserIsInRole(user.Name, ConstantStrings.AdministratorRole) ||
userManager.UserIsInRole(user.Name, ConstantStrings.ModeratorRole))
userRole = ConstantStrings.AdministratorRole;
else userRole = ConstantStrings.CustomerRole;
masterPage.UserModel = user;
masterPage.UserRole = userRole;
}
return View(masterPage);
}
public RedirectToRouteResult AddToCart(int Id, string returnUrl)
{
Product product = _repository.GetById(Id);
if (product != null)
{
GetCart().AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}
public RedirectToRouteResult RemoveFromCart(int Id, string returnUrl)
{
Product product = _repository.GetById(Id);
if (product != null)
{
GetCart().RemoveLine(product);
}
return RedirectToAction("Index", new { returnUrl });
}
public PartialViewResult Summary(Cart cart)
{
return PartialView(GetCart());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Checkout(string paymentType, decimal totalCost)
{
var userManager = new UserManager(_userRepository, _roleRepository, _contactsRepository, _unitOfWork);
var shipingManager = new ShipingManager(_orderRepository,_orderProductRepository,_repository,
_userRepository,_paymentRepository,_roleRepository,_contactsRepository, _unitOfWork);
var lines = GetCart().Lines;
if (HttpContext.User.Identity.IsAuthenticated)
{
var user = userManager.GetUserByName(HttpContext.User.Identity.Name);
shipingManager.CheckOut(lines, paymentType, totalCost, user);
}
return RedirectToAction("List", "Product"); ;
}
public Cart GetCart()
{
Cart cart = (Cart)Session["Cart"];
if (cart == null)
{
cart = new Cart();
Session["Cart"] = cart;
}
return cart;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Classes.Uteis
{
public static class InverterString
{
public static string Inverter(string Texto)
{
//Cria a partir do texto original um array de char
char[] ArrayChar = Texto.ToCharArray();
//Com o array criado invertemos a ordem do mesmo
Array.Reverse(ArrayChar);
//Agora basta criarmos uma nova String, ja com o array invertido.
return new string(ArrayChar);
}
}
}
|
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 FXB.Dialog;
using FXB.Data;
using FXB.Common;
using FXB.DataManager;
namespace FXB
{
public partial class main : Form
{
public main()
{
InitializeComponent();
//SortedSet<int> s = new SortedSet<int>();
//bool a = s.Add(1);
//a = s.Add(2);
//a = s.Add(1);
string at = TimeUtil.TimestampToDateTime(1505917148).ToString("yyyy-MM");
bool a = DoubleUtil.Equal(36.25, 36.25);
}
private void 员工档案ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("PersonnelDataDlg");
}
private void main_Load(object sender, EventArgs e)
{
// double a = 189.23;
// double b = (189.23 * 8000) / 10000;
//初始化操作
try
{
SqlMgr.Instance().Init();
DepartmentDataMgr.Instance().Load();
JobGradeDataMgr.Instance().Load();
ProjectDataMgr.Instance().Load();
EmployeeDataMgr.Instance().Load();
QtMgr.Instance().Load();
DxDuplicateMgr.Instance().Load();
AuthMgr.Instance().Load();
HYMgr.Instance().Init();
TDMgr.Instance().Load();
PayDataMgr.Instance().Load();
ImportSalaryMgr.Instance().Load();
LoginDlg loginDlg = new LoginDlg();
if (DialogResult.OK != loginDlg.ShowDialog())
{
System.Environment.Exit(0);
return;
}
//根据权限隐藏菜单
AuthData curLoginAuth = AuthMgr.Instance().CurLoginEmployee.AuthData;
if (!curLoginAuth.IfOwner)
{
//不是管理员
if (!curLoginAuth.ShowYuangongDanganMenu())
{
员工档案ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowZhijiDanganMenu())
{
职级档案ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowXiangmuDanganMenu())
{
项目档案ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowYonghuquanxianMenu())
{
用户权限ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowShuaXinShujuMenu())
{
刷新数据ToolStripMenuItem.Visible = false;
}
//if (!curLoginAuth.ShowKaiDanMenu())
//{
// 单据录入ToolStripMenuItem.Visible = false;
//}
//if (!curLoginAuth.ShowHuiYongMenu())
//{
// 回佣录入ToolStripMenuItem.Visible = false;
//}
//if (!curLoginAuth.ShowTuiDanMenu())
//{
// 退单录入ToolStripMenuItem.Visible = false;
//}
if (!curLoginAuth.ShowDixinLuruMenu())
{
底薪录入ToolStripMenuItem.Visible = false;
}
//if (!curLoginAuth.ShowGenerateDixinFubenMenu())
//{
生成底薪副本ToolStripMenuItem.Visible = false;
//}
if (!curLoginAuth.ShowGenerateQtGongziMenu())
{
生成QT工资ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowQtTaskMenu())
{
QT任务ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowTichengmingxibiaoMenu())
{
回佣总表ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowChengjiaobaogaoMenu())
{
成交报告ToolStripMenuItem.Visible = false;
}
if (!curLoginAuth.ShowZhuchangtichengMenu())
{
驻场提成表ToolStripMenuItem.Visible = false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
System.Environment.Exit(0);
}
}
private void 职级档案ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("JobGradeDataDlg");
}
private void 项目档案ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("ProjectDataDlg");
}
private void ShowDialog(string dlgName)
{
Form[] allMdiChildren = this.MdiChildren;
foreach (Form childDlg in allMdiChildren)
{
if (childDlg.Name == dlgName)
{
if (childDlg.WindowState == FormWindowState.Minimized)
{
childDlg.WindowState = FormWindowState.Maximized;
}
childDlg.Activate();
return;
}
}
if (dlgName == "PersonnelDataDlg")
{
PersonnelDataDlg dlg = new PersonnelDataDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "JobGradeDataDlg")
{
JobGradeDataDlg dlg = new JobGradeDataDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "ProjectDataDlg")
{
ProjectDataDlg dlg = new ProjectDataDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "QtTaskOperDlg")
{
QtTaskOperDlg dlg = new QtTaskOperDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "SalaryDuplicateOperDlg")
{
SalaryDuplicateOperDlg dlg = new SalaryDuplicateOperDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "OrderDataDlg")
{
OrderDataDlg dlg = new OrderDataDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "AuthDataDlg")
{
AuthDataDlg dlg = new AuthDataDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "PayDataDlg")
{
PayDataDlg dlg = new PayDataDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "SalaryImportDlg")
{
SalaryImportDlg dlg = new SalaryImportDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "HYSalaryViewDlg")
{
HYSalaryViewDlg dlg = new HYSalaryViewDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "HyTotalViewDlg")
{
HyTotalViewDlg dlg = new HyTotalViewDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "ZcTotalViewDlg")
{
ZcTotalViewDlg dlg = new ZcTotalViewDlg();
dlg.MdiParent = this;
dlg.Show();
}
else if (dlgName == "OrderTotalViewDlg")
{
OrderTotalViewDlg dlg = new OrderTotalViewDlg();
dlg.MdiParent = this;
dlg.Show();
}
else
{
MessageBox.Show("未知的窗口名字");
System.Environment.Exit(0);
}
}
private void QT任务ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("QtTaskOperDlg");
}
private void 生成底薪副本ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("SalaryDuplicateOperDlg");
}
//private void 开单录入ToolStripMenuItem_Click(object sender, EventArgs e)
//{
// ShowDialog("OrderDataDlg");
//}
private void 用户权限ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("AuthDataDlg");
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
}
private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
{
ChangePasswordDlg dlg = new ChangePasswordDlg();
dlg.ShowDialog();
}
private void 单据录入ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("OrderDataDlg");
}
private void 生成QT工资ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("PayDataDlg");
}
private void 底薪录入ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("SalaryImportDlg");
}
private void 工资查询ToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void 回佣明细表ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("HYSalaryViewDlg");
}
private void 回佣总表ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("HyTotalViewDlg");
}
private void 驻场提成表ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("ZcTotalViewDlg");
}
private void 成交报告ToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowDialog("OrderTotalViewDlg");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Visitors.DAO;
using Visitors.DAOImpl;
using Visitors.entity;
namespace Visitors.View
{
/// <summary>
/// Interaction logic for LoginPage.xaml
/// </summary>
public partial class LoginPage : Window
{
public LoginPage()
{
InitializeComponent();
}
private void submitBtn_Click(object sender, RoutedEventArgs e)
{
UserMaster usrmasterRef = new UserMaster();
usrmasterRef.mobileNo = mobileNotxt.Text.Trim();
if (passwordBoxsample.Password.Trim() == "")
MessageBox.Show("Please enter password !");
else
{
usrmasterRef.pwd = passwordBoxsample.Password.Trim();
UserMasterDAO usrmasterDAORef = new UserMasterDAOImpl();
int i = usrmasterDAORef.login(usrmasterRef);
if (i == 1)
{
radCarouse1 r = new radCarouse1();
r.Show();
Hide();
}
else if (i == 0)
{
mobileNotxt.Text = "";
passwordBoxsample.Password = "";
MessageBox.Show("invalid credential!");
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class DisablePowerUp : MonoBehaviour {
// Use this for initialization
void Start () {
}
public bool isDoing = true;
//research this
void OnTriggerEnter(Collider other) {
if (other.tag == "Player" && isDoing) {
//Debug.Log ("disable attack triggered");
StartCoroutine (GameManager.Instance.ExecuteDisablePlayersPowerUp (other.gameObject.GetComponent<Player> ()));
GameManager.Instance.powerUpInPlay = false;
//gameObject.SetActive (false);
StartCoroutine (DestroyMe ());
//Destroy (gameObject);
}
}
public IEnumerator DestroyMe() {
isDoing = false;
yield return new WaitForSeconds (6.0f);
Destroy (gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace radisutm.Models
{
public class GrantModel
{
public string REFERENCE_NO { get; set; }
public string COST_CENTER_CODE { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AttackDisplay : MonoBehaviour
{
private float attackCooldown;
public Text cdText;
void Update()
{
attackCooldown = PlayerAttack.timeBetweenAttack;
cdText.text = attackCooldown.ToString("F1") + "s";
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace momo.Entity.Premission
{
public class IdentityUser : EntityBase
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 账户
/// </summary>
public string Account { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 加密参数
/// </summary>
public Guid Salt { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayGameButton : MonoBehaviour
{
public void PlayGameButtonn()
{
SceneManager.LoadScene(sceneName: "Game");
}
}
|
using System;
namespace Phenix.TeamHub.Prober.Business
{
/// <summary>
/// 操作者
/// </summary>
public class Worker : Phenix.TeamHub.Prober.IWorker
{
/// <summary>
/// 注册
/// </summary>
public static void Register()
{
Phenix.TeamHub.Prober.AppHub.Worker = new Worker();
}
/// <summary>
/// 提交日志
/// </summary>
void Phenix.TeamHub.Prober.IWorker.SubmitLog(string message, System.Reflection.MethodBase method, Exception exception)
{
new SubmitLogCommand(message, method, exception).Execute();
}
}
}
|
using Sentry.Extensibility;
using Sentry.Internal.Extensions;
namespace Sentry;
/// <summary>
/// The Sentry Debug Meta interface.
/// </summary>
/// <see href="https://develop.sentry.dev/sdk/event-payloads/debugmeta"/>
internal sealed class DebugMeta : IJsonSerializable
{
public List<DebugImage>? Images { get; set; }
/// <inheritdoc />
public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? logger)
{
writer.WriteStartObject();
writer.WriteArrayIfNotEmpty("images", Images, logger);
writer.WriteEndObject();
}
/// <summary>
/// Parses from JSON.
/// </summary>
public static DebugMeta FromJson(JsonElement json)
{
var images = json.GetPropertyOrNull("images")?.EnumerateArray().Select(DebugImage.FromJson).ToList();
return new DebugMeta
{
Images = images
};
}
}
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using bdd;
namespace NUnitTests
{
[TestFixture]
public class CalculatorTests
{
[Test]
public void AddTwoSmallNumbers()
{
//Given
var calculator = new BoringCalculator();
var a = 5.0;
var b = 10.0;
//When
var sum = calculator.Add(a, b);
//Then
Assert.AreEqual(15.0, sum);
}
}
}
|
using System.Collections.Generic;
using System.Data.SqlClient;
using Dapper;
namespace ShowsTracker.Infrastructure
{
public interface IDataAccess
{
IEnumerable<T> Query<T>(string sql, dynamic param = null);
int Execute(string sql, dynamic param = null);
}
public class DataAccess : IDataAccess
{
private readonly string _connectionString;
public DataAccess(string connectionString)
{
_connectionString = connectionString;
}
public IEnumerable<T> Query<T>(string sql, dynamic param = null)
{
using (var conn = GetOpenConnection())
return SqlMapper.Query<T>(conn, sql, param);
}
public int Execute(string sql, dynamic param = null)
{
using (var conn = GetOpenConnection())
return SqlMapper.Execute(conn, sql, param);
}
private SqlConnection GetOpenConnection()
{
var conn = new SqlConnection(_connectionString);
conn.Open();
return conn;
}
}
} |
using Alabo.Domains.Entities;
using Alabo.Domains.Services;
namespace Alabo.Cloud.People.UserTree.Domain.Service
{
public interface ITreeUpdateService : IService
{
/// <summary>
/// 更新所有会员的组织架构图
/// </summary>
void UpdateAllUserMap();
/// <summary>
/// 检查所有的会员关系图是否正确
/// </summary>
ServiceResult CheckOutUserMap();
/// <summary>
/// 检查所有的会员关系图是否正确
/// </summary>
void ParentMapTaskQueue();
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PW.InternalMoney.Models
{
[Table("TRANSACTIONS")]
public class Transaction
{
[Column("TRANSACTION_ID")]
public int Id { get; set; }
[Column("TRANSACTION_DATE")]
public DateTime Date { get; set; }
[Column("TRANSACTION_FROM_ID")]
[ForeignKey("TransferFrom")]
public int TransferFromId { get; set; }
public BillingAccount TransferFrom { get; set; }
[Column("TRANSACTION_TO_ID")]
[ForeignKey("TransferTo")]
public int TransferToId { get; set; }
public BillingAccount TransferTo { get; set; }
[Column("TRANSACTION_AMOUNT")]
public Money TransactionAmount { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Repository.Repositorio;
using Interfaces.Interfaces;
using Dados.DAO;
namespace Business
{
public class TradeBS
{
public int insert(List<TradeDTO> pTrade)
{
int iReturn = 0;
TradeDAO oTrade = new TradeDAO();
try
{
foreach (TradeDTO pItem in pTrade)
{
if(pItem.tradeValue == 0)
{
throw new Exception("Valor do Trade não pode ser zero.");
}
iReturn = oTrade.insert(pItem);
if (iReturn == 0)
{
throw new Exception("Ocorreu um erro ao inserir o Trade");
}
}
}
catch (Exception ex)
{
throw ex;
}
finally { }
return iReturn;
}
public bool update(List<TradeDTO> pTrade)
{
bool bReturn = false;
TradeDAO oTrade = new TradeDAO();
try
{
foreach (TradeDTO pItem in pTrade)
{
if (pItem.tradeValue == 0)
{
throw new Exception("Valor do Trade não pode ser zero.");
}
bReturn = oTrade.update(pItem);
if (!bReturn)
{
throw new Exception("Ocorreu um erro ao atualizar o Trade");
}
}
}
catch (Exception ex)
{
throw ex;
}
finally { }
return bReturn;
}
public bool delete(int pIdTrade)
{
bool bReturn = false;
TradeDAO oTrade = new TradeDAO();
try
{
if (pIdTrade == 0)
{
throw new Exception("Código do Trade não informado.");
}
bReturn = oTrade.delete(pIdTrade);
if (!bReturn)
{
throw new Exception("Ocorreu um erro ao atualizar o Trade");
}
}
catch (Exception ex)
{
throw ex;
}
finally { }
return bReturn;
}
public List<TradeDTO> listTrade()
{
List<TradeDTO> oReturn = new List<TradeDTO>();
TradeDAO oTrade = new TradeDAO();
try
{
oReturn = oTrade.listTrade();
}
catch (Exception ex)
{
throw ex;
}
finally { }
return oReturn;
}
public List<TradeDTO> getTradeByID(int pIdTrade)
{
List<TradeDTO> oReturn = new List<TradeDTO>();
TradeDAO oTrade = new TradeDAO();
try
{
oReturn = oTrade.getTradeByID(pIdTrade);
}
catch (Exception ex)
{
throw ex;
}
finally { }
return oReturn;
}
public string getSectorTrade(List<TradeDTO>pTrade)
{
string sReturn = "";
TradeDAO oTrade = new TradeDAO();
List<TradeCategoryDTO> oReturn = new List<TradeCategoryDTO>();
try
{
foreach(TradeDTO pItem in pTrade)
{
oReturn = oTrade.getSectorTrade(pItem);
if(oReturn.Count > 0)
{
foreach (TradeCategoryDTO pRetorno in oReturn)
{
sReturn += pRetorno.dsCategory + ",";
}
}
}
if(sReturn.LastIndexOf(",")> -1)
{
sReturn = sReturn.Substring(0, (sReturn.Length - 1));
}
}
catch (Exception ex)
{
throw ex;
}
finally { }
return sReturn;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Uscale.Classes
{
/// <summary>
/// Node that can service requests made to a virtual Host.
/// </summary>
public class Node
{
#region Public-Members
/// <summary>
/// Node's hostname.
/// </summary>
public string Hostname { get; set; }
/// <summary>
/// The port on which the node is listening.
/// </summary>
public int Port { get; set; }
/// <summary>
/// Enable or disable SSL.
/// </summary>
public bool Ssl { get; set; }
/// <summary>
/// Heartbeat URL that the loadbalancer should poll to determine whether or not the Node is online.
/// </summary>
public string HeartbeatUrl { get; set; }
/// <summary>
/// The interval in milliseconds by which the loadbalancer should poll the Node.
/// </summary>
public int PollingIntervalMsec { get; set; }
/// <summary>
/// Timestamp for the last attempt made by the loadbalancer to inquire against the Node.
/// </summary>
public DateTime? LastAttempt { get; set; }
/// <summary>
/// Timestamp for the last successful attempt made by the loadbalancer inquiring against the Node.
/// </summary>
public DateTime? LastSuccess { get; set; }
/// <summary>
/// Timestamp for the last failed attempt made by the loadbalancer inquiring against the Node.
/// </summary>
public DateTime? LastFailure { get; set; }
/// <summary>
/// Maximum number of failures tolerated before the Node is removed from rotation for this Host.
/// </summary>
public int MaxFailures { get; set; }
/// <summary>
/// Number of failures that have been encountered consecutively without a successful inquiry.
/// </summary>
public int? NumFailures { get; set; }
/// <summary>
/// Indicates if the Node is marked as failed.
/// </summary>
public bool Failed { get; set; }
#endregion
#region Private-Members
#endregion
#region Constructors-and-Factories
/// <summary>
/// Instantiate the object.
/// </summary>
public Node()
{
}
#endregion
#region Public-Methods
#endregion
#region Private-Methods
#endregion
}
}
|
/* Author: Mitchell Spryn (mitchell.spryn@gmail.com)
* There is no warranty with this code. I provide it with the intention of being interesting/helpful, but make no
* guarantees about its correctness or robustness.
* This code is free to use as you please, as long as this header comment is left in all of the files and credit is attributed to me for the original content that I have created.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NNGen
{
/// <summary>
/// A representation of a layer in the Visualizer
/// </summary>
public partial class VisualizerLayer : UserControl
{
/// <summary>
/// The number of neurons in the network
/// </summary>
public int numNeurons { get; private set; }
/// <summary>
/// For asyncronous networks, the activation type of the layer
/// </summary>
public AsyncNeuron.NeuronActivationType asyncActivationType { get; private set; }
/// <summary>
/// For syncronous networks, the activatino type of the layer
/// </summary>
public TransferFunctionWrapper.MemoryActivationType syncActivationType { get; private set; }
/// <summary>
/// A human-readable string representation of the activation type
/// </summary>
public string activationType_string { get; private set; }
/// <summary>
/// The name of the layer
/// </summary>
public string layerName { get; private set; }
/// <summary>
/// Whether the layer is synchronous
/// </summary>
public bool isSynchronous { get; private set; }
/// <summary>
/// Whether the layer is the first layer in the network
/// </summary>
public bool isFirstLayer { get; private set; }
/// <summary>
/// A private formatting variable
/// </summary>
private int label_padding;
/// <summary>
/// Create a VisualizerLayer
/// </summary>
/// <param name="_numNeurons">The number of neurons in the layer</param>
/// <param name="_asyncActivationType">For an asynchronous network, the activation type. Ignored for synchronous networks</param>
/// <param name="_syncActivationType">For a synchronous network, the activation type. Ignored for asynchronous networks</param>
/// <param name="_isSynchronous">A flag determining whether the network is synchronous or not</param>
/// <param name="_layerName">The name of the layer</param>
/// <param name="_isFirstLayer">A flag representing whether this layer is the first layer in the network. Used to mask the activation type</param>
public VisualizerLayer(int _numNeurons, AsyncNeuron.NeuronActivationType _asyncActivationType, TransferFunctionWrapper.MemoryActivationType _syncActivationType, bool _isSynchronous, string _layerName, bool _isFirstLayer)
{
InitializeComponent();
/*Prevent resizing*/
this.MaximumSize = this.Size;
this.MinimumSize = this.Size;
this.numNeurons = _numNeurons;
this.asyncActivationType = _asyncActivationType;
this.syncActivationType = _syncActivationType;
this.isSynchronous = _isSynchronous;
this.layerName = _layerName;
this.isFirstLayer = _isFirstLayer;
if (!this.isFirstLayer)
{
if (!this.isSynchronous)
this.activationType_string = Utilities.GetDescription<AsyncNeuron.NeuronActivationType>(this.asyncActivationType);
else
this.activationType_string = Utilities.GetDescription<TransferFunctionWrapper.MemoryActivationType>(this.syncActivationType);
}
this.layerNameLabel.Text = String.Format("{0}", this.layerName);
this.numNeuronLabel.Text = String.Format("{0} neurons", this.numNeurons);
if (this.isSynchronous)
{
this.syncLabel.Text = "Synchronous";
}
else
{
this.syncLabel.Text = "Asynchronous";
}
if (this.isFirstLayer)
{
this.activationTypeLabel.Text = "";
}
else
{
this.activationTypeLabel.Text = String.Format("Activation type: {0}", this.activationType_string);
}
this.label_padding = this.Height - this.layerNameLabel.Height - this.numNeuronLabel.Height - this.activationTypeLabel.Height - this.syncLabel.Height;
this.label_padding /= 5;
return;
}
/// <summary>
/// Paints the form
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int centerX = this.Width / 2;
int yPos = this.label_padding;
this.layerNameLabel.Location = new Point(centerX - (this.layerNameLabel.Width / 2), yPos);
yPos += this.label_padding + this.layerNameLabel.Height;
this.numNeuronLabel.Location = new Point(centerX - (this.numNeuronLabel.Width / 2), yPos);
yPos += this.label_padding + this.numNeuronLabel.Height;
this.activationTypeLabel.Location = new Point(centerX - (this.activationTypeLabel.Width / 2), yPos);
yPos += this.label_padding + this.activationTypeLabel.Height;
this.syncLabel.Location = new Point(centerX - (this.syncLabel.Width / 2), yPos);
return;
}
}
}
|
// <copyright file="EnumExtensions.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
namespace SmartLibrary.Infrastructure
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// EnumExtensions
/// </summary>
public static class EnumExtensions
{
/// <summary>
/// GetDescription
/// </summary>
/// <param name="enumValue">enumValue</param>
/// <returns>type</returns>
public static string GetDescription(this Enum enumValue)
{
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return enumValue.ToString();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class serveur : Form
{
public serveur()
{
InitializeComponent();
}
private void Ajout_Load(object sender, EventArgs e)
{
string[] serveur = File.ReadAllLines(@"\serveur.txt"); //Déclartion d'un tableau nomée "serveur" remplie par le fichier serveur
dgv1.RowCount = serveur.Length; //Le dgv a un nb de lignes équivalent aux nb de lignes du tableau "serveur"
dgv1.ColumnCount = 1; //Le dgv a 1 colonne
dgv1.Columns[0].HeaderText = "Serveurs"; //La colonne a pour nom "Serveurs"
for (int i = 0; i < serveur.Length; i++) //Parcours le tableau
{
dgv1.Rows[i].Cells[0].Value = serveur[i]; //Rempli les lignes du dgv avec les lignes du tableau "serveur"
}
dgv1.RowHeadersVisible = false; //Cache la colonne d'entete du dgv
}
private void btnTer_Click(object sender, EventArgs e)
{
this.Close(); //Fermeture
}
private void btnSup_Click(object sender, EventArgs e)
{
try //Essaie
{
if (dgv1.RowCount - 1 == 0) //Si le dgv n'a plus de ligne
{
MessageBox.Show("Vous ne pouvez pas supprimmer tous les serveurs"); //Message d'erreur
return; //Sortie
}
}
catch
{}
foreach (DataGridViewCell oneCell in dgv1.SelectedCells) //Pour chaqu'une des cellule du dgv
{
if (oneCell.Selected) //Si une cellule est selectionnner
{
string temp = Convert.ToString(oneCell.Value); //Déclaration d'une variable temp qui prend la valeur de la cellule
dgv1.Rows.RemoveAt(oneCell.RowIndex); //Suppression de la cellule
string[] fichier = File.ReadAllLines(@"\serveur.txt"); //Déclaration d'un tableau "fichier" qui prend en valeur les lignes du fichier
for (int i = 0; i < fichier.Length; i++) //Parcours le tableau "fichier"
{
if (temp == fichier[i]) //Si le mot de la cellule est trouvé dans le fichier
{
List<String> lines = File.ReadAllLines(@"\serveur.txt").ToList(); //Déclaration d'une variable lines qui prend en valeur les lignes du fichier et qui les met en liste
lines.RemoveAt(i); //Efface le mot si il est trouvé
File.WriteAllLines(@"\serveur.txt", lines.ToArray()); //Réecrie les lignes du fichier sans la ligne du mot trouvé
}
}
(this.Owner as Form1).Controls["cbx1"].Text = ""; //Nettoyage du combobox
string[] fichier2 = File.ReadAllLines(@"\serveur.txt"); //Déclaration d'un tableau "fichier2" qui prend le contenue du fichier
for (int i = 0; i < fichier2.Length; i++) //Parcours le fichier
{
(this.Owner as Form1).Controls["cbx1"].Text= fichier2[i]; //Complete le cbx1
}
}
}
}
private void btnAj_Click(object sender, EventArgs e)
{
bool vide = true; //Déclaration
for (int i = 0; i < dgv1.RowCount; i++) //Parcours le datagridview
{
if (tbx1.Text == Convert.ToString(dgv1.Rows[i].Cells[0].Value)) //Comparaison de mots
{
MessageBox.Show("Serveur déjà enregistrer"); //Message d'erreur
tbx1.Text = null; //reset
vide = true; //Modification de booléen
break; //Sortie
}
}
if (tbx1.Text != "") //Si le champs destinataire n'est pas vide
{
dgv1.Rows.Add(tbx1.Text); //Ajout d'un ligne
File.AppendAllText(@"\serveur.txt", tbx1.Text); //Ajoute le contenue du champ destinataire au fichier en sautant une ligne
tbx1.Text = null; //reset le contenu
}
else //Sinon
{
if (vide == false) //Si il n'y a pas de doublon
{
MessageBox.Show("Entrez une valeur dans le champ"); //Message d'erreur
return; //Sortie
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Polymorphism
{
class TesSistemPenggajian
{
static void Main(string[] args)
{
var karyawanBergaji = new KaryawanGaji("John", "Smith", "111-11-1111", 800.00M);
var karyawanPerjam = new KerjaPerjam("Karen", "Price", "222-22-2222", 16.75M, 40.0M);
var komisiKaryawan = new KomisiKaryawan("Sue", "Jones", "333-33-3333", 10000.00M, .06M);
var komisiKaryawanDasarPlus = new DasarPlusKomisiKaryawan("Bob", "Lewis", "444-44-4444", 5000.00M, .04M, 300.00M);
Console.WriteLine("Karyawan diproses secara individual");
Console.WriteLine($"{karyawanBergaji}\nearned: " + $"{karyawanBergaji.Pendapatan():C}\n");
Console.WriteLine($"{karyawanPerjam}\nearned: {karyawanPerjam.Pendapatan():C}\n");
Console.WriteLine($"{komisiKaryawan}\nearned: " + $"{komisiKaryawan.Pendapatan():C}\n");
Console.WriteLine($"{komisiKaryawanDasarPlus}\nearned:" + $"{komisiKaryawanDasarPlus.Pendapatan():C}\n");
var karyawan = new List<Karyawan>() { karyawanBergaji, karyawanPerjam, komisiKaryawan, komisiKaryawanDasarPlus };
Console.WriteLine("Karyawan diproses secara polimorfik");
foreach (var karyawanSekarang in karyawan)
{
Console.WriteLine(karyawanSekarang);
if (karyawanSekarang is DasarPlusKomisiKaryawan)
{
var karyawan1 = (DasarPlusKomisiKaryawan)karyawanSekarang;
karyawan1.GajiPokok *= 1.10M;
Console.WriteLine("Gaji pokok baru dengan kenaikan 10% adalah: " + $"{karyawan1.GajiPokok:C}\n");
}
for (int j = 0; j < karyawan.Count; j++)
{
Console.WriteLine($"Karyawan {j} adalah {karyawan[j].GetType()}");
}
}
}
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Remotes Config", menuName = "Overlook/Remote Config Object")]
public class RemoteConfigObject : ScriptableObject
{
public List<Remote> remotes;
[Serializable]
public class Remote
{
public string remoteName;
public List<Instrument> instruments;
[Serializable]
public class Instrument
{
[Header("After entering a name and selecting a type, only fill out ONE of the parameter fields.\n")]
[Header("NAME")]
public string instrumentName;
[Header("TYPE")] public bool isWasd;
public bool isSlider;
public bool isButton;
public bool isJoystick;
public bool isThreeColumn;
[Header("WASD PARAMETERS")] public string wOnChange_gameObject;
public string wOnChange_method;
public string aOnChange_gameObject;
public string aOnChange_method;
public string sOnChange_gameObject;
public string sOnChange_method;
public string dOnChange_gameObject;
public string dOnChange_method;
[Header("SLIDER PARAMETERS")] public int slider_min;
public int slider_max;
public float slider_step;
public string slider_onChange_gameObject;
public string slider_onChange_method;
[Header("BUTTON PARAMETERS")] public string button_buttonText;
public string button_onChange_gameObject;
public string button_onChange_method;
[Header("JOYSTICK PARAMETERS")] public int joystick_throttle;
public string joystick_onChange_gameObject;
public string joystick_onChange_method;
[Header("THREE COLUMN PARAMETERS")] public string threeColumn_left_buttonText;
public string threeColumn_center_buttonText;
public string threeColumn_right_buttonText;
public string threeColumn_left_onChange_gameObject;
public string threeColumn_center_onChange_gameObject;
public string threeColumn_right_onChange_gameObject;
public string threeColumn_left_onChange_method;
public string threeColumn_center_onChange_method;
public string threeColumn_right_onChange_method;
}
}
/*
public Instrument wasd;
public Instrument slider;
public Instrument button;
public Instrument joystick;
public Instrument threeColumn;
public Instrument()
{
if (isWasd)
{
instrumentName = "wasd";
wasd = new Wasd(
new OnChange(wOnChange_method, wOnChange_gameObject),
new OnChange(aOnChange_method, aOnChange_gameObject),
new OnChange(sOnChange_method, sOnChange_gameObject),
new OnChange(dOnChange_method, dOnChange_gameObject)
);
}
if (isSlider)
{
instrumentName = "slider";
slider = new Slider(
slider_min,
slider_max,
slider_step,
new OnChange(slider_onChange_method, slider_onChange_gameObject)
);
}
if (isButton)
{
instrumentName = "button";
button = new Button(
button_buttonText,
new OnChange(button_onChange_method, button_onChange_gameObject)
);
}
if (isJoystick)
{
instrumentName = "joystick";
joystick = new Joystick(
joystick_throttle,
new OnChange(button_onChange_method, button_onChange_gameObject)
);
}
if (isThreeColumn)
{
instrumentName = "threeColumn";
threeColumn = new ThreeColumn(
threeColumn_left_buttonText,
threeColumn_center_buttonText,
threeColumn_right_buttonText,
new OnChange(threeColumn_left_onChange_method, threeColumn_left_onChange_gameObject),
new OnChange(threeColumn_center_onChange_method, threeColumn_center_onChange_gameObject),
new OnChange(threeColumn_right_onChange_method, threeColumn_right_onChange_gameObject)
);
}
}
}
[Serializable]
public class OnChange
{
public string gameObject;
public string method;
public OnChange(string _gameObject, string _method)
{
gameObject = _gameObject;
method = _method;
}
}
[Serializable]
public class Wasd : Instrument
{
public OnChange w_onChange;
public OnChange a_onChange;
public OnChange s_onChange;
public OnChange d_onChange;
public Wasd(OnChange _wONChange, OnChange _aONChange, OnChange _sONChange, OnChange _dONChange)
{
w_onChange = _wONChange;
a_onChange = _aONChange;
s_onChange = _sONChange;
d_onChange = _dONChange;
}
}
[Serializable]
public class Slider : Instrument
{
public int min;
public int max;
public float step;
public OnChange onChange;
public Slider(int _min, int _max, float _step, OnChange _onChange)
{
min = _min;
max = _max;
step = _step;
onChange = _onChange;
}
}
[Serializable]
public class Button : Instrument
{
public string buttonText;
public OnChange onChange;
public Button(string _buttonText, OnChange _onChange)
{
buttonText = _buttonText;
onChange = _onChange;
}
}
[Serializable]
public class Joystick : Instrument
{
public int throttle;
public OnChange onChange;
public Joystick(int _throttle, OnChange _onChange)
{
throttle = _throttle;
onChange = _onChange;
}
}
[Serializable]
public class ThreeColumn : Instrument
{
public string left_buttonText;
public string center_buttonText;
public string right_buttonText;
public OnChange left_onChange;
public OnChange center_onChange;
public OnChange right_onChange;
public ThreeColumn(string _leftButtonText, string _centerButtonText, string _rightButtonText, OnChange _leftONChange, OnChange _centerONChange, OnChange _rightONChange)
{
left_buttonText = _leftButtonText;
center_buttonText = _centerButtonText;
right_buttonText = _rightButtonText;
left_onChange = _leftONChange;
center_onChange = _centerONChange;
right_onChange = _rightONChange;
}
}
*/
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using BanSupport;
public class TestScrollGallery : MonoBehaviour
{
public ScrollGallery scrollGallery;
public Text label;
public class SimpleData
{
public int number;
}
// Start is called before the first frame update
void Start()
{
scrollGallery.SetOnItemOpen((aGo, aData) =>
{
aGo.GetComponentInChildren<Button>().onClick.AddListener(() =>
{
Debug.Log("OnOpen:" + (aData as SimpleData).number.ToString());
scrollGallery.Select(aData, true);
});
});
scrollGallery.SetOnItemClose((aGo, aData) =>
{
aGo.GetComponentInChildren<Button>().onClick.RemoveAllListeners();
});
scrollGallery.SetOnItemRefresh((aGo, aData, isSelected) =>
{
Debug.Log("OnRefresh:" + (aData as SimpleData).number + " isSelected:" + isSelected);
aGo.GetComponentInChildren<Text>().text = "number:" + (aData as SimpleData).number + (isSelected ? "√" : "");
});
this.datas = new SimpleData[10];
for (int i = 0; i < 10; i++)
{
datas[i] = new SimpleData { number = i };
scrollGallery.Add(datas[i]);
}
scrollGallery.Select(datas[1]);
}
private SimpleData[] datas;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
scrollGallery.Select(this.datas[0],true);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
scrollGallery.Select(this.datas[1], true);
}
if (Input.GetKeyDown(KeyCode.Alpha3))
{
scrollGallery.Select(this.datas[2], true);
}
if (Input.GetKeyDown(KeyCode.Alpha4))
{
scrollGallery.Select(this.datas[3], true);
}
if (Input.GetKeyDown(KeyCode.Alpha5))
{
scrollGallery.Select(this.datas[4], true);
}
if (Input.GetKeyDown(KeyCode.C))
{
scrollGallery.Clear();
}
if (Input.GetKeyDown(KeyCode.B))
{
datas[0].number += 10;
scrollGallery.Set(datas[0]);
}
if (Input.GetKeyDown(KeyCode.S))
{
for (int i = 0; i < datas.Length; i++)
{
Debug.Log(string.Format("data index:{0} isSelected:{1}",i, scrollGallery.IsSelected(datas[i])) );
}
}
//var str = (item != null) ? item.normalizedPos.ToString("0.00") : "";
//label.text = str;
}
}
|
using UnityEngine;
using UnityEngine.Timeline;
[TrackColor(255.0f / 255.0f, 102.0f / 255.0f, 51.0f / 255.0f)]
[TrackClipType(typeof(LabelClip))]
public class LabelTrack : TrackAsset
{
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignPattern_Factory
{
class Dagger : Weapon
{
public override int attackSpeed
{
get { return 30;}
}
public override int damage
{
get { return 10; }
}
}
}
|
namespace Ach.Fulfillment.Nacha.Enumeration
{
public enum PaddingType
{
Default,
ZeroPadRight,
ZeroPadLeft,
SpacePadRight,
SpacePadLeft,
CustomPadRight,
CustomPadLeft,
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class PatternEditorWindow : ExtendedEditorWindow
{
Vector2 pos;
static PatternDataBase p;
public static void Open(PatternDataBase patternDataBase)
{
PatternEditorWindow window = GetWindow<PatternEditorWindow>("Pattern Editor");
p = patternDataBase;
window.serializedObject = new SerializedObject(p);
}
private void OnGUI()
{
currentProperty = serializedObject.FindProperty("patterns");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical("box", GUILayout.MaxWidth(150), GUILayout.ExpandHeight(true));
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("+"))
{
p.Add();
Repaint();
}
if (GUILayout.Button("-"))
{
p.Remove();
Repaint();
}
EditorGUILayout.EndHorizontal();
DrawSidebar(currentProperty);
EditorGUILayout.EndVertical();
pos = EditorGUILayout.BeginScrollView(pos);
EditorGUILayout.BeginVertical("box", GUILayout.ExpandHeight(true));
if(selectedProperty != null)
{
DrawProperties(selectedProperty, true);
}
else
{
EditorGUILayout.LabelField("Select an item from the list");
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndScrollView();
EditorGUILayout.EndHorizontal();
Apply();
}
protected void Apply()
{
serializedObject.ApplyModifiedProperties();
serializedObject = new SerializedObject(p);
}
}
|
using System;
public class First_and_Reserve_Team
{
public static void Main()
{
var teams = new Team("proba");
var lines = int.Parse(Console.ReadLine());
for (int i = 0; i < lines; i++)
{
var cmdArgs = Console.ReadLine().Split();
var person = new Person(cmdArgs[0],
cmdArgs[1],
int.Parse(cmdArgs[2]),
double.Parse(cmdArgs[3]));
teams.AddPlayer(person);
}
Console.WriteLine($"First team have {teams.FirstTeam.Count} players");
Console.WriteLine($"Reserve team have {teams.ReserveTeam.Count} players");
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Projeto.Validators.DataAnnotations
{
public class ValidaMaiorDeIdade : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
return new ValidationResult("Preenchimento obrigatório");
DateTime date = (DateTime)value;
if ((DateTime.Now.Year - date.Year) < 18)
return new ValidationResult("Somente maiores de 18 anos");
return ValidationResult.Success;
}
}
} |
public enum MessageBusType
{
NONE,
LevelStart,
LevelEnd,
PlayerPosition,
PointAdded,
LoggedInFacebook,
LoggedOutFacebook,
UserDataConflicted,
UserDataConflictSolved,
UserDataChanged,
GameDataChanged,
AchievementDataChanged,
XPChanged,
LifeChanged,
DiamondChanged,
UserLevelChanged,
UserPlayRecordChanged,
TimeLifeCountDown,
FacebookUserDataReceived,
IAPManagerInitializeFailed,
PurchaseFailed,
ProductPurchased,
NativeAdItemLoaded,
LanguageChanged,
NativeAdItemFailedToLoad,
CompletedIAPLocalization,
OnSelectedOrUnselectedInviteFriend,
OnUserDataInitialized,
CompletedLevelRanking,
OnCompletedGetGeoLocation,
CompletedPostStatusShareFacebook,
CancelPostStatusShareFacebook,
OnCompletedRestoreApple,
PlaySongAction,
RewardVideoDiamond,
RewardVideoPostponeAds,
Evt_Room_Join_Status = 201,// when waiting another person in room
Evt_Room_MoveTo_Gameplay = 202,// start room
Evt_Room_Sync_Status = 203,// when waiting another download this song
Evt_Room_Error_To_Play = 204,// when room can not start due to error
Evt_Room_Ready_To_Play = 205,// when room ready to start(all person ready or time to go)
Evt_Room_Finish = 206,// when room end
Evt_SyncBehaviorToRoom = 207,// when user sync behavior
Evt_Room_Chat = 208,// when a person chat in waiting start room
Evt_Kick_out = 209,// kick user violate (hack, cheat, timeout...)
Evt_HasError = 1000,
Evt_Online_Disconnect = 2000,
OnMeDieOnline
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Reflection;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using IRAP.Global;
namespace IRAP.Client.GUI.MESPDC.Actions
{
public abstract class CustomPrint
{
public CustomPrint(XmlNode actionParams)
{
}
public abstract void DoPrint(string dataToPrint);
}
public class CustomPrintFactory
{
public static CustomPrint CreateInstance(XmlNode actionParams)
{
if (actionParams.Attributes["PrintType"] == null)
return null;
string printType = actionParams.Attributes["PrintType"].Value.ToString();
switch (printType.ToUpper())
{
case "LPT":
return new PrintToLPT(actionParams);
case "SOCKET":
return new PrintToSocket(actionParams);
default:
return null;
}
}
}
public class PrintToLPT : CustomPrint
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private string strLPTPort = "LPT1";
public PrintToLPT(XmlNode actionParams)
: base(actionParams)
{
try
{
strLPTPort = actionParams.Attributes["PrintTo"].Value.ToString();
}
catch { }
}
public override void DoPrint(string dataToPrint)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
WriteLog.Instance.Write(
string.Format(
"向端口[{0}]发送打印内容[{1}]",
strLPTPort,
dataToPrint),
strProcedureName);
using (LPTPrint print = new LPTPrint())
{
try
{
print.LPTWrite(strLPTPort, dataToPrint);
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
XtraMessageBox.Show(
error.Message,
"系统信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
public class PrintToSocket : CustomPrint
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private string printerIPAddress = "";
private int printerPort = 0;
public PrintToSocket(XmlNode actionParams)
: base(actionParams)
{
string temp = "";
try { temp = actionParams.Attributes["PrintToAddress"].Value; }
catch { temp = ""; }
if (temp != "")
printerIPAddress = temp;
try { temp = actionParams.Attributes["PrintToPort"].Value; }
catch { temp = ""; }
if (temp != "")
try { printerPort = Int32.Parse(temp); }
catch { }
}
public override void DoPrint(string dataToPrint)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
WriteLog.Instance.Write(
string.Format(
"向打印机[{0}:{1}]发送打印内容[{2}]",
printerIPAddress,
printerPort,
dataToPrint),
strProcedureName);
try
{
SocketPrint.Instance.PrinterAddress = printerIPAddress;
SocketPrint.Instance.PrinterPort = printerPort;
if (SocketPrint.Instance.PrinterReady())
SocketPrint.Instance.Print(dataToPrint);
else
{
WriteLog.Instance.Write(string.Format("打印机[{0}:{1}]离线,无法打印!",
SocketPrint.Instance.PrinterAddress,
SocketPrint.Instance.PrinterPort),
strProcedureName);
XtraMessageBox.Show(string.Format("打印机[{0}:{1}]离线,无法打印!",
SocketPrint.Instance.PrinterAddress,
SocketPrint.Instance.PrinterPort),
"系统信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
XtraMessageBox.Show(error.Message,
"系统信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PROnline.Models;
using PROnline.Models.Users;
namespace PROnline.Src
{
public class AuthAttribute : ActionFilterAttribute
{
public String MenuId { get; set; }
private bool isOk = false;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (MenuId != null)
{
if (filterContext.HttpContext.Session["role"] == null)
{
filterContext.HttpContext.Session["role"] = "public";
}
string role = (String)filterContext.HttpContext.Session["role"];
if (MenuId != null)
{
base.OnActionExecuting(filterContext);
HttpSessionStateBase session = filterContext.HttpContext.Session;
List<String> limit = PROnline.Src.Utils.getMenuLimit(session);
if (limit.Contains(MenuId) || role == "admin")
{
isOk = true;
}
}
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (MenuId != null && !isOk)
{
filterContext.Result = new RedirectResult("/Account/Login?from="+filterContext.HttpContext.Request.Url);
}
}
}
} |
using ServiceQuotes.Domain.Entities;
using ServiceQuotes.Domain.Repositories;
using ServiceQuotes.Infrastructure.Context;
namespace ServiceQuotes.Infrastructure.Repositories
{
public class JobValuationRepository : Repository<JobValuation>, IJobValuationRepository
{
public JobValuationRepository(AppDbContext dbContext) : base(dbContext) { }
}
}
|
// <copyright file="Update2.cs" company="TreverGannonsMadExperiment">
// Copyright (c) TreverGannonsMadExperiment. All rights reserved.
// </copyright>
namespace Database.DatabaseUpdates
{
/// <summary>
/// Represents the first iteration of the database.
/// </summary>
internal class Update2 : IUpdate
{
/// <inheritdoc/>
public string UpdateSQL =>
@"
create table if not exists exercisetracker
(
id uuid default gen_random_uuid() not null
constraint exercisecounts_pkey
primary key,
repetitions integer not null,
sets integer not null,
person_id uuid not null
constraint exercisecounts_person_id_fkey
references person,
exercise_id uuid not null
constraint exercisecounts_exercise_id_fkey
references exercise
);
alter table exercisetracker owner to postgres;
";
/// <inheritdoc/>
public int Priority => 2;
}
}
|
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UIKit;
using Foundation;
using Aquamonix.Mobile.IOS.Utilities;
using Aquamonix.Mobile.Lib.Environment;
using Aquamonix.Mobile.Lib.Utilities;
using Aquamonix.Mobile.Lib.Utilities.WebSockets;
using Aquamonix.Mobile.Lib.Services;
using Aquamonix.Mobile.Lib.Domain;
namespace Aquamonix.Mobile.IOS.Utilities.WebSockets
{
/// <summary>
/// Handles websocket events related to the connection state; manages the process of reconnecting both in background and foreground.
/// </summary>
public static class ConnectionManager
{
//how long to wait between retries, for server-down
private const int ServerDownRetryWaitSeconds = 30;
//how long to wait between retries, for auth retries (no longer relevant)
private const int AuthRetryWaitSeconds = 30;
//default wait in between retries
private const int DefaultRetryWaitSeconds = 10;
//how long it takes for a disconnected connection to be considered 'dead' (timed from beginning of reconnect process)
private const int ConnectionDeathSeconds = 100;
//how long the connection must be down before we can display the reconnecting banner (timed from beginning of reconnect process)
private const int BannerDelaySeconds = 5;
private static ConnectionState _state = ConnectionState.Disconnected;
private static ConnectionEventHandler _onConnected = null;
//true if we have not yet successfully connected to server in lifetime of app
public static bool InitialConnection = false;
/// <summary>
/// Gets the current state of connection
/// </summary>
public static ConnectionState State { get { return _state; } }
/// <summary>
/// Returns true if currently reconnecting, either in foreground or background
/// </summary>
public static bool IsReconnecting { get { return ReconnectProcess.Running; } }
/// <summary>
/// Returns true if currently showing reconnecting banner
/// </summary>
public static bool ShowingReconBar { get { return ReconnectProcess.IsShowingReconBar; } }
/// <summary>
/// Static constructor
/// </summary>
static ConnectionManager()
{
SetState(ConnectionState.Disconnected);
}
/// <summary>
/// Desubscribes all websocket events
/// </summary>
public static void Deinitialize()
{
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.ConnectionOpened -= OnConnectionOpened;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.ConnectionClosed -= OnConnectionClosed;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.RequestSucceeded -= OnRequestSucceeded;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.ConnectionFailed -= OnConnectionFailed;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.RequestFailed -= OnRequestFailed;
}
/// <summary>
/// Initializes instance; subscribes all websocket events
/// </summary>
public static void Initialize()
{
//unsubscribe first
Deinitialize();
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.ConnectionOpened += OnConnectionOpened;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.ConnectionClosed += OnConnectionClosed;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.RequestSucceeded += OnRequestSucceeded;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.ConnectionFailed += OnConnectionFailed;
Aquamonix.Mobile.Lib.Utilities.WebSockets.WebSocketsClient.RequestFailed += OnRequestFailed;
}
/// <summary>
/// Attempts to cancel any reconnection currently happening
/// </summary>
/// <returns>True on successful cancel (async)</returns>
public static async Task<bool> CancelReconnecting()
{
if (ReconnectProcess.Running)
{
await ReconnectProcess.Cancel();
if (WebSocketsClient.IsConnected)
SetState(ConnectionState.Connected);
else
SetState(ConnectionState.Disconnected, "cancelled");
}
return true;
}
//EVENT HANDLERS
private static void OnConnectionOpened(object sender, ConnectionEventArgs e)
{
LogUtility.LogMessage(String.Format("Connection opened"));
SetState(ConnectionState.Connected);
if (_onConnected != null)
_onConnected(sender, e);
}
private static void OnConnectionFailed(object sender, ConnectionEventArgs e)
{
LogUtility.LogMessage(String.Format("Connection failed"));
SetState(ConnectionState.Disconnected);
}
private static void OnConnectionClosed(object sender, ConnectionClosedEventArgs e)
{
LogUtility.LogMessage("Connection closed");
SetState(ConnectionState.Disconnected);
if (ReconnectIsAllowed())
{
ReconnectProcess.Begin();
}
}
private static void OnRequestSucceeded(object sender, RequestEventArgs e)
{
LogUtility.LogMessage(String.Format("Request succeeded"));
//InitialConnection = true;
SetState(ConnectionState.Connected);
}
private static void OnRequestFailed(object sender, RequestFailureEventArgs e)
{
HandleFailedRequest(sender as IWebSocketsClient, e);
}
/// <summary>
/// Handles a failed websocket request
/// </summary>
/// <param name="client">The websocket client which sent the request</param>
/// <param name="args">Arguments associated with failure</param>
private static void HandleFailedRequest(IWebSocketsClient client, RequestFailureEventArgs args)
{
LogUtility.LogMessage(String.Format("Request Failure (reason: {0})", Enum.GetName(typeof(RequestFailureReason), args.FailureReason)));
bool tryReconnect = false;
string message = null;
switch (args.FailureReason)
{
case RequestFailureReason.Auth:
tryReconnect = false;
message = "authentication problem";
NotificationUtility.PostNotification(NotificationType.AuthFailure);
break;
case RequestFailureReason.Timeout:
tryReconnect = ReconnectIsAllowed();
message = "timeout";
break;
case RequestFailureReason.ServerDown:
tryReconnect = ReconnectIsAllowed();
message = "server down";
break;
case RequestFailureReason.Network:
tryReconnect = ReconnectIsAllowed();
message = "network issue";
break;
case RequestFailureReason.ServerRequestedReconnect:
tryReconnect = ReconnectIsAllowed();
message = "server requested reconnect";
break;
case RequestFailureReason.Error:
break;
}
if (tryReconnect)
{
SetState(ConnectionState.Disconnected, message);
ReconnectProcess.Begin(args.ForegroundAction, args.OnResume, args.Request, args.FailureReason);
}
}
/// <summary>
/// Internally sets the instance connection state
/// </summary>
/// <param name="state">The state value to set</param>
/// <param name="message">Optional message to display on banner</param>
private static void SetState(ConnectionState state, string message = null)
{
state.Message = message;
if (_state != state)
{
LogUtility.LogMessage(String.Format("Connection state set to {0}", state.ToString()));
_state = state;
NotificationUtility.PostNotification(NotificationType.ConnectionStateChanged);
}
}
/// <summary>
/// Under certain circumstances, reconnect may not be allowed (e.g. on login screen)
/// </summary>
private static bool ReconnectIsAllowed()
{
return !(ViewControllers.TopLevelViewControllerBase.CurrentViewController is ViewControllers.UserConfigViewController);
}
/// <summary>
/// Handles the recurrent process of actually attempting to restore a dropped connection.
/// </summary>
public static class ReconnectProcess
{
//keeps count of the number of attempts (first attempt is 1)
private static int _attemptNumber = 0;
//optional limit on number of attempts allowed (default is 0 == infinite)
private static int _limitAttempts = 0;
//unix timestamp indicating the time of most recent reconnection process start
private static long _startTimestamp = DateTimeUtil.GetUnixTimestamp();
//used in cancellation
private static AutoResetEvent _cancelHandle = null;
//true if currently showing a progress spinner as part of reconnection process
private static bool _showingProgress = false;
//true if currently showing reconnection banner
private static bool _showingReconBar = false;
//1 when running, 0 when not
private static int _runFlag = 0;
//true if running in background (as opposed to foreground)
private static bool _runningInBackground = false;
//reason for reconnection (original)
private static RequestFailureReason? _originalReason = null;
//reason for reconnection (most recently assigned, may be different from original)
private static RequestFailureReason? _latestReason = null;
//connection dead
private static bool _connectionDead = false;
/// <summary>
/// Returns true if currently running in foreground or background
/// </summary>
public static bool Running
{
get { return _runFlag == 1; }
}
/// <summary>
/// Returns true if the connection's been down and unrecoverable for a long enough time.
/// </summary>
public static bool Dead { get { return _connectionDead; } }
/// <summary>
/// Returns true if currently running in background
/// </summary>
public static bool RunningInBackground { get { return _runningInBackground; } }
/// <summary>
/// Returns true if currently showing reconnecting banner
/// </summary>
public static bool IsShowingReconBar { get { return _showingReconBar; } }
/// <summary>
/// Returns true if reconnecting for an auth failure
/// </summary>
private static bool IsAuthFailure { get { return (_latestReason != null && _latestReason == RequestFailureReason.Auth); } }
/// <summary>
/// Starts the whole process running
/// </summary>
/// <param name="foregroundAction">True if we should try first in foreground before moving to background</param>
/// <param name="onResume">Optional action to retry if connection restored in foreground</param>
/// <param name="request">The request associated with retry attempt (e.g. the failed request)</param>
/// <param name="reason">The reason for the need to reconnect</param>
public static void Begin(bool foregroundAction = false, Action onResume = null, IApiRequest request = null, RequestFailureReason? reason = null, bool showBannerStraightAway = false)
{
ExceptionUtility.Try(() => {
if (reason != null)
{
if (_originalReason == null && reason != null)
_originalReason = reason;
_latestReason = reason;
}
if (showBannerStraightAway) {
ShowReconBanner();
}
Task.Factory.StartNew(() => { BeginInternal(foregroundAction, onResume, request); });
});
}
/// <summary>
/// Attempts to cancel the reconnection proces
/// </summary>
/// <returns>true on successful cancel</returns>
public static Task<bool> Cancel()
{
return Task.Run<bool>(() => {
return ExceptionUtility.Try<bool>(() =>
{
_attemptNumber = 0;
_limitAttempts = 0;
if (ReconnectProcess.Running)
{
_cancelHandle = new AutoResetEvent(false);
//wait for cancel to be recognized
bool timedOut = !_cancelHandle.WaitOne(120000);
if (_cancelHandle != null)
{
_cancelHandle.Dispose();
_cancelHandle = null;
}
//returns false if timed out
return !timedOut;
}
Stop();
return true;
});
});
}
/// <summary>
/// Gets the number of seconds since the process began
/// </summary>
/// <returns>The number of seconds since starting</returns>
public static long SecondsSinceStart()
{
return (DateTimeUtil.SecondsSinceTimestamp(_startTimestamp));
}
/// <summary>
/// Sets the connection to dead if conditions are met
/// </summary>
/// <returns>true if conditions are met to set connection to dead</returns>
private static bool ConditionalSetConnectionDead()
{
//after a while, the connection is considered 'dead'
if (SecondsSinceStart() > ConnectionDeathSeconds)
{
LogUtility.LogMessage("Connection is DEAD");
ConnectionManager.SetState(ConnectionState.Dead);
ShowReconBanner();
return true;
}
return false;
}
/// <summary>
/// Shows the reconnecting banner if conditions are met to do so.
/// </summary>
private static void ConditionalShowReconBanner()
{
if (SecondsSinceStart() > BannerDelaySeconds)
{
if (!ShowingReconBar)
ProgressUtility.Dismiss();
ShowReconBanner();
}
}
/// <summary>
/// Attempts to reconnect in the foreground while showing a progress spinner
/// </summary>
/// <returns>True on successful reconnect</returns>
private static async Task<bool> ReconnectForeground()
{
bool success = false;
try
{
ShowProgress();
LogUtility.LogMessage("Attempting to reconnect in foreground");
success = await TryReconnect();
if (success)
HideProgress();
}
catch (Exception e)
{
LogUtility.LogException(e);
HideProgress();
Stop();
}
return success;
}
/// <summary>
/// Stops the process (different from cancel, which is async - this is called only internally)
/// </summary>
private static void Stop()
{
HideReconBanner();
_runningInBackground = false;
_runFlag = 0;
_attemptNumber = 0;
_limitAttempts = 0;
_connectionDead = false;
}
/// <summary>
/// Checks for a cancellation attempt, makes the necessary changes if detected.
/// </summary>
/// <returns>true if cancelled (big if true)</returns>
private static bool CheckForCancellation()
{
if (_cancelHandle != null)
{
LogUtility.LogMessage("Reconnection process cancelled");
_cancelHandle.Set();
Stop();
return true;
}
return false;
}
/// <summary>
/// Attempt to reconnect to server one time
/// </summary>
/// <returns>True on successful reconnect</returns>
private static async Task<bool> TryReconnect()
{
try
{
_attemptNumber++;
LogUtility.LogMessage(String.Format("Reconnect attempt {0}", _attemptNumber));
ConnectionManager.SetState(ConnectionManager.State.IsDead ? ConnectionState.Dead : ConnectionState.Connecting, String.Format("attempt {0}", _attemptNumber));
var response = await ServiceContainer.UserService.RequestConnection(
User.Current.Username,
User.Current.Password,
silentMode: true);
bool output = false;
if (response != null)
{
output = response.IsSuccessful;
}
return output;
}
catch (Exception e)
{
LogUtility.LogException(e);
}
return false;
}
/// <summary>
/// Display the reconnecting banner
/// </summary>
private static void ShowReconBanner()
{
_showingReconBar = true;
NotificationUtility.PostNotification(NotificationType.ShowReconnecting);
}
/// <summary>
/// Hide the reconnecting banner
/// </summary>
private static void HideReconBanner()
{
_showingReconBar = false;
NotificationUtility.PostNotification(NotificationType.HideReconnecting);
}
/// <summary>
/// Display a progress spinner
/// </summary>
private static void ShowProgress()
{
if (!_showingProgress)
{
MainThreadUtility.InvokeOnMain(() => {
ProgressUtility.Show("Reconnecting...");
});
_showingProgress = true;
}
}
/// <summary>
/// Hide the progress spinner
/// </summary>
private static void HideProgress()
{
if (_showingProgress)
{
MainThreadUtility.InvokeOnMain(() => {
ProgressUtility.Dismiss();
});
_showingProgress = false;
}
}
/// <summary>
/// Takes appropriate actions up on successful reconnect
/// </summary>
/// <param name="onResume">Option action to retry upon successful reconnect</param>
private static void OnSuccess(Action onResume = null)
{
LogUtility.LogMessage("Reconnection success");
ConnectionManager.SetState(ConnectionState.Connected);
//NotificationUtility.PostNotification(NotificationType.Reconnected);
Stop();
if (onResume != null)
onResume();
}
/// <summary>
/// Takes appropriate actions up on failed reconnect
/// </summary>
private static void OnFailure()
{
Stop();
//if auth failure timeout, redirect to login screen
if (IsAuthFailure)
{
NotificationUtility.PostNotification(NotificationType.AuthFailure);
}
}
/// <summary>
/// Waits for n seconds.
/// </summary>
private static void WaitSeconds(int sec)
{
Thread.Sleep(sec * 1000);
}
/// <summary>
/// Starts the whole process running (to be called internally)
/// </summary>
/// <param name="foregroundAction">True if we should try first in foreground before moving to background</param>
/// <param name="onResume">Optional action to retry if connection restored in foreground</param>
/// <param name="request">The request associated with retry attempt (e.g. the failed request)</param>
private static async void BeginInternal(bool foregroundAction = false, Action onResume = null, IApiRequest request = null)
{
try
{
if (Interlocked.CompareExchange(ref _runFlag, 1, 0) == 0)
{
LogUtility.LogMessage(String.Format("Attempting to reconnect (reason: {0})", (_latestReason == null) ? "null" : Enum.GetName(typeof(RequestFailureReason), _latestReason)));
_attemptNumber = 0;
_connectionDead = false;
_startTimestamp = DateTimeUtil.GetUnixTimestamp();
ConnectionManager.SetState(ConnectionState.Connecting);
bool reconnectedFirstTime = false;
if (CheckForCancellation()) return;
//attempt first to reconnect in foreground
if (foregroundAction)
{
reconnectedFirstTime = await ReconnectForeground();
if (reconnectedFirstTime)
{
LogUtility.LogMessage("Connection restored in foreground");
OnSuccess(onResume);
}
else
{
//if a prog utility is showing, now we dismiss it cause we're going to background
ProgressUtility.Dismiss();
ShowReconBanner();
//if we're to try once only, then stop here
LogUtility.LogMessage("Connection not restored in foreground; will move to background");
}
}
//first attempt fails
if (!reconnectedFirstTime)
{
//continue trying in background
while (true)
{
_runningInBackground = true;
//limit the number of attempts for auth failure
_limitAttempts = (0);
if (CheckForCancellation()) break;
//make sure attempt limit isn't exceeded
if (_limitAttempts > 0 && _attemptNumber >= _limitAttempts)
{
OnFailure();
break;
}
//if it's been a while, show the reconnecting banner
ConditionalShowReconBanner();
ConditionalSetConnectionDead();
//the actual reconnect attempt
bool reconnected = await TryReconnect();
if (CheckForCancellation()) break;
//if reconnected, we're good
if (reconnected)
{
OnSuccess();
break;
}
//if it's been a while, show the reconnecting banner
ConditionalShowReconBanner();
ConditionalSetConnectionDead();
//wait in between retries
int waitSec = DefaultRetryWaitSeconds;
//for server-down or dead connection, extend the retry wait
if ((_latestReason != null && (_latestReason == RequestFailureReason.ServerDown)) || _connectionDead)
{
waitSec = ServerDownRetryWaitSeconds;
}
//wait
if (waitSec > 0)
{
LogUtility.LogMessage(String.Format("Reconnection process waiting {0} seconds", waitSec));
if (MainThreadUtility.IsOnMainThread)
{
LogUtility.LogMessage("Warning - ConnectionManager should not be waiting on Main Thread!", LogSeverity.Warn);
}
WaitSeconds(waitSec);
}
}
}
}
else
{
//could not enter
if (foregroundAction)
{
ProgressUtility.Dismiss();
ShowReconBanner();
}
}
}
catch (Exception e)
{
LogUtility.LogException(e);
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BreatheOut : MonoBehaviour {
GameObject avatar1;
GameObject avatar2;
public GameObject Player1WaveSpawn;
public GameObject Player2WaveSpawn;
Color auraColor;
public float instantiateSpeed = 4.0f;
void Start () {
avatar1 = GameObject.Find("NewWave1");
avatar2 = GameObject.Find("NewWave2");
Player1WaveSpawn = GameObject.Find("Player1_WaveSpawn");
Player2WaveSpawn = GameObject.Find("Player2_WaveSpawn");
// old waves
// avatar1 = GameObject.Find("planewaveP1");
//avatar2 = GameObject.Find("planewaveP2");
InvokeRepeating("InstantiateWaves", 2.0f, 6.0f);
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.RightArrow)) {InstantiateWaves();}
}
void InstantiateWaves()
{
Debug.Log("send waves!");
Player1WaveSpawn = GameObject.Find("Player1_WaveSpawn");
GameObject newWave = Instantiate(avatar1, Player1WaveSpawn.transform.position, avatar1.transform.rotation);
// MoveWave mWave = newWave.GetComponent<MoveWave>();
// DestroyWave dWave = newWave.GetComponent<DestroyWave>();
// mWave.enabled = true;
// dWave.enabled = true;
float auraH, auraS, auraV;
auraColor = GameObject.Find ("Player1_Manager").GetComponent<PlayerFAScript> ().PlayerColor;
Color.RGBToHSV(auraColor, out auraH, out auraS, out auraV);
auraS = 0.95f;
auraColor = Color.HSVToRGB(auraH,auraS,auraV);
auraColor.a = GameObject.Find ("Player1_Manager").GetComponent<PlayerFAScript> ().AuraColor.a*2f;
//auraColor.a = auraColor.a * 2f + 0.01f;
// GameObject.Find("Player1_Manager").GetComponent<PlayerFAScript>().AuraColor.a / 5;// + 0.2f;
// newWave.GetComponent<Renderer> ().material.color = auraColor;
// newWave.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
// newWave.GetComponent<ParticleSystem>().startColor = auraColor;
ParticleSystem ps = newWave.GetComponent<ParticleSystem>();
ps.Clear ();
ps.startColor = auraColor;
// ps.Simulate (5f,false, true);
ps.startLifetime = ps.startLifetime;
ps.emissionRate = 0;
ps.emissionRate = 200;
ps.Simulate (10f);
ps.Play ();
auraColor.a = auraColor.a/2f;
Light l = newWave.GetComponentInChildren(typeof(Light)) as Light;
l.color = auraColor;
Player2WaveSpawn = GameObject.Find("Player2_WaveSpawn");
newWave = Instantiate(avatar2, Player2WaveSpawn.transform.position, avatar2.transform.rotation);
// MoveWave2 mWave2 = newWave.GetComponent<MoveWave2>();
// dWave = newWave.GetComponent<DestroyWave>();
// mWave2.enabled = true;
// dWave.enabled = true;
auraColor = GameObject.Find ("Player2_Manager").GetComponent<PlayerFAScript> ().PlayerColor;
Color.RGBToHSV(auraColor, out auraH, out auraS, out auraV);
auraS = 0.95f;
auraColor = Color.HSVToRGB(auraH,auraS,auraV);
auraColor.a = GameObject.Find ("Player2_Manager").GetComponent<PlayerFAScript> ().AuraColor.a*2f;
//unity 5. has bug in particlesystem disabling looping. These are manual overrides that make it work.
ps = newWave.GetComponent<ParticleSystem>();
ps.Clear ();
ps.startColor = auraColor;
ps.startLifetime = ps.startLifetime;
ps.emissionRate = 0;
ps.emissionRate = 200;
ps.Simulate (10f);
ps.Play ();
auraColor.a = auraColor.a/2f;
l = newWave.GetComponentInChildren(typeof(Light)) as Light;
l.color = auraColor;
//GameObject waveGeometry = newWave.transform.Find("wave1_side1").gameObject;
//waveGeometry.GetComponent<Renderer> ().material.color = auraColor;
//waveGeometry.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
//waveGeometry = newWave.transform.Find("wave1_side2").gameObject;
//waveGeometry.GetComponent<Renderer> ().material.color = auraColor;
//waveGeometry.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
/* Old Waves
/* Player1WaveSpawn = GameObject.Find("Player1_WaveSpawn");
GameObject newWave = Instantiate(avatar1, Player1WaveSpawn.transform.position, avatar1.transform.rotation);
MoveWave mWave = newWave.GetComponent<MoveWave>();
DestroyWave dWave = newWave.GetComponent<DestroyWave>();
mWave.enabled = true;
dWave.enabled = true;
auraColor = GameObject.Find ("Player1_Manager").GetComponent<PlayerFAScript> ().PlayerColor;
auraColor.a = GameObject.Find ("Player1_Manager").GetComponent<PlayerFAScript> ().AuraColor.a*2 + 0.2f;
GameObject waveGeometry = newWave.transform.Find("wave1_side1").gameObject;
waveGeometry.GetComponent<Renderer> ().material.color = auraColor;
waveGeometry.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
waveGeometry = newWave.transform.Find("wave1_side2").gameObject;
waveGeometry.GetComponent<Renderer> ().material.color = auraColor;
waveGeometry.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
Player2WaveSpawn = GameObject.Find("Player2_WaveSpawn");
newWave = Instantiate(avatar2, Player2WaveSpawn.transform.position, avatar2.transform.rotation);
MoveWave2 mWave2 = newWave.GetComponent<MoveWave2>();
dWave = newWave.GetComponent<DestroyWave>();
mWave2.enabled = true;
dWave.enabled = true;
auraColor = GameObject.Find ("Player2_Manager").GetComponent<PlayerFAScript> ().PlayerColor;
auraColor.a = GameObject.Find ("Player2_Manager").GetComponent<PlayerFAScript> ().AuraColor.a*2 + 0.2f;
waveGeometry = newWave.transform.Find("wave2_side1").gameObject;
waveGeometry.GetComponent<Renderer> ().material.color = auraColor;
waveGeometry.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
waveGeometry = newWave.transform.Find("wave2_side2").gameObject;
waveGeometry.GetComponent<Renderer> ().material.color = auraColor;
waveGeometry.GetComponent<Renderer> ().material.SetColor ("_EmissionColor", auraColor);
*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clase3.Ejercicio1.Diccionario
{
/// <summary>
/// Implementar un diccionario que contendrá los siguientes valores:
/// values.Add("Juan", "55423412");
/// values.Add("Ernesto", "56985623");
/// values.Add("Mariana", "54787451");
/// Realice las siguientes operaciones:
/// a.Revisar en el diccionario si existe un índice llamado “Juan”. En caso de que exista,
/// mostrar su valor(utilice el método ContainsKey)
/// b.Revisar en el diccionario si existe un índice llamado “Pedro”. En caso de que exista,
/// mostrar su valor, si no existe imprimir por pantalla “No contiene la llave” (utilice el
/// método TryGetValue)
/// c.Recorrer el diccionario y mostrar todos sus datos(índice y valor).
/// d.Alterar el valor cuyo índice es “Mariana” por “58251425”. Imprimir el nuevo valor.
/// </summary>
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> documentos = new Dictionary<string, string>();
documentos.Add("Juan", "55423412");
documentos.Add("Ernesto", "56985623");
documentos.Add("Mariana", "54787451");
//punto a
if (documentos.ContainsKey("Juan"))
{
Console.WriteLine("Para:\"Juan\", el valor es: {0}.", documentos["Juan"]);
}
//punto b
string valor = "";
if (documentos.TryGetValue("Pedro", out valor))
{
Console.WriteLine("Para = \"Pedro\", el valor es : {0}.", valor);
}
else
{
Console.WriteLine("No contiene la llave.");
}
//punto c
foreach (var persona in documentos)
{
Console.WriteLine(persona.Key + "," + persona.Value);
}
//punto d
documentos["Mariana"] = "58251425";
Console.WriteLine("Nuevo teléfono de Mariana: {0}", documentos["Mariana"]);
Console.Read();
}
}
}
|
using System;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using SportHub.Models;
using SportHub.ViewModels;
namespace SportHub.Controllers
{
public class SportsController : Controller
{
private readonly ApplicationDbContext _context;
public SportsController()
{
_context = new ApplicationDbContext();
}
[Authorize]
public ActionResult Create()
{
var viewModel = new SportFormViewModel
{
SportKinds = _context.SportKinds.ToList(),
};
return View(viewModel);
}
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(SportFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.SportKinds = _context.SportKinds.ToList();
return View("Create", viewModel);
}
var sport = new Sport
{
SportManId = User.Identity.GetUserId(),
DateTime = viewModel.GetDateTime(),
SportKindId = viewModel.SportKind,
Venue = viewModel.Venue
};
_context.Sports.Add(sport);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace Formatter
{
/// <summary>
/// Форматирование чека
/// </summary>
public static class ReceiptFormatter
{
public static BaseReceiptFormatter InitInstance(Receipt receipt, int width, int posNumber, string FormatReceiptName, bool SlipInsideReceipt)
{
BaseReceiptFormatter ReceiptFormat = null;
switch (FormatReceiptName)
{
case "Format1":
{
ReceiptFormat = new ReceiptFormat1(receipt, width, posNumber, SlipInsideReceipt);
break;
}
case "Format2":
{
ReceiptFormat = new ReceiptFormat2(receipt, width, posNumber, SlipInsideReceipt);
break;
}
case "Format3":
{
ReceiptFormat = new ReceiptFormat3(receipt, width, posNumber, SlipInsideReceipt);
break;
}
case "Format4":
{
ReceiptFormat = new ReceiptFormat4(receipt, width, posNumber, SlipInsideReceipt);
break;
}
case "Format5":
{
ReceiptFormat = new ReceiptFormat5(receipt, width, posNumber, SlipInsideReceipt);
break;
}
case "Format6":
{
ReceiptFormat = new ReceiptFormat6(receipt, width, posNumber, SlipInsideReceipt);
break;
}
default:
ReceiptFormat = new ReceiptFormat2(receipt, width, posNumber, SlipInsideReceipt);
break;
}
return ReceiptFormat;
}
}
}
|
// This file is part of LAdotNET.
//
// LAdotNET is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// LAdotNET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY, without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with LAdotNET. If not, see <https://www.gnu.org/licenses/>.
using LAdotNET.Config;
namespace LAdotNET.LoginServer.Config
{
class LoginServerConfiguration : Configuration
{
public LoginConfig Login { get; set; }
/// <summary>
/// Initalize the configuration
/// </summary>
public LoginServerConfiguration() : base()
{
Login = new LoginConfig();
}
/// <summary>
/// Loads all config files
/// </summary>
public void Load()
{
LoadDefaults();
Login = LoadYaml<LoginConfig>("loginserver_config.yml");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BunqAggregation;
using Bunq.Sdk.Context;
using Bunq.Sdk.Model.Generated.Endpoint;
using Bunq.Sdk.Model.Generated.Object;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BunqAggregation.Controllers
{
[Route("api/[controller]")]
public class RequestController : Controller
{
[HttpPost]
public void Post([FromBody] JObject content)
{
JObject config = Settings.LoadConfig();
Console.WriteLine("Hi there, we are connecting to the bunq API...\n");
var apiContext = ApiContext.Restore();
BunqContext.LoadApiContext(apiContext);
Console.WriteLine(" -- Connected as: " + BunqContext.UserContext.UserPerson.DisplayName + " (" + BunqContext.UserContext.UserId + ")\n");
var amount = content["amount"].ToString();
string recipient = content["recipient"].ToString();
string description = content["description"].ToString();
Console.WriteLine("Todo:");
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("Description: " + description);
Console.WriteLine("Send to: " + recipient);
Console.WriteLine("Amount: € " + amount);
Console.WriteLine("----------------------------------------------------------");
if (Convert.ToDouble(amount) > 0)
{
Console.WriteLine("Executing...");
RequestInquiry.Create(new Amount(amount, "EUR"), new Pointer("EMAIL", recipient), description, true);
Console.WriteLine("Yeah, this one is completed!");
}
else
{
Console.WriteLine("Bummer, nothing to do!");
}
Console.WriteLine("----------------------------------------------------------\n");
}
}
}
|
using System.Collections.Generic;
using Properties.Core.Objects;
namespace Properties.Core.Interfaces
{
public interface IFeatureRepository
{
List<Feature> GetFeaturesForSubmittedProperty(string landlordReference, string submittedPropertyReference);
Feature GetFeatureForSubmittedProperty(string landlordReference, string submittedPropertyReference, string featureReference);
bool CreateFeature(string landlordReference, string submittedPropertyReference, Feature feature);
bool UpdateFeature(string landlordReference, string submittedPropertyReference, string featureReference, Feature feature);
bool DeleteFeature(string landlordReference, string submittedPropertyReference, string featureReference);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace HealthApp
{
/// <summary>
/// Interaction logic for SettingsPage.xaml
/// </summary>
public partial class SettingsPage : Page
{
public SettingsPage()
{
InitializeComponent();
this.DataContext = Storage.Settings;
}
private void SaveBtn_Click(object sender, RoutedEventArgs e)
{
Storage.Settings.Write();
Storage.MainFrame.Source = new Uri("LoginPage.xaml", UriKind.RelativeOrAbsolute);
}
private void TestDb_Click(object sender, RoutedEventArgs e)
{
if (Storage.Settings.TestDbConnection())
MessageBox.Show("Успех!");
else
MessageBox.Show("Ошибка тестирования!");
}
}
}
|
using C1.C1Excel;
using C1.Win.C1FlexGrid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;
namespace Common.Presentation.Controls
{
/// <summary>
/// C1FlexGrid with various types of features.
/// </summary>
/// <remarks>Modified from C1 example code.</remarks>
public class EnhancedFlexGrid : C1FlexGrid
{
#region Private Fields
private int mActiveSheet = -1;
private bool mAllowBlinking = false;
private SelectionModeEnum mBaseSelectionMode = SelectionModeEnum.ListBox;
private Color mBlinkOffColor = Color.Empty;
private Color mBlinkOnColor = Color.Empty;
private CellStyle mBlinkStyle = null;
private int mColumnIndex = -1;
private DataTable mDataSource = null;
private bool mDisableCellDoubleClick = false;
private bool mOverrideSelectionMode = false;
private int mResizeRow = -1;
private int mRowIndex = -1;
private List<int> mSelectedRows = new List<int>();
private int mSheet = -1;
private int mStartY = 0;
private Timer mTimer = null;
private C1XLBook mWorkbook = new C1XLBook();
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of EnhancedFlexGrid.
/// </summary>
public EnhancedFlexGrid()
{
base.SelectionMode = mBaseSelectionMode;
base.DrawMode = DrawModeEnum.OwnerDraw;
}
#endregion
#region Public Properties
[Browsable(false)]
public int ActiveSheet
{
get { return mActiveSheet; }
set { mActiveSheet = value; }
}
[Browsable(true), Category("Behavior"), Description("When set to True, allows cells to use the Blink style."),
DisplayName("AllowBlinking")]
public bool AllowBlinking
{
get { return mAllowBlinking; }
set { mAllowBlinking = value; }
}
[Browsable(true), Category("Appearance"), Description("The text color to blink from."), DisplayName("BlinkOffColor")]
public Color BlinkOffColor
{
get { return mBlinkOffColor; }
set
{
if (value != mBlinkOffColor)
{
mBlinkOffColor = value;
if (!mBlinkOnColor.Equals(Color.Empty) && !mBlinkOffColor.Equals(Color.Empty))
{
if (mBlinkStyle == null)
mBlinkStyle = this.Styles.Add("Blink");
}
}
}
}
[Browsable(true), Category("Appearance"), Description("The text color to blink to."), DisplayName("BlinkOnColor")]
public Color BlinkOnColor
{
get { return mBlinkOnColor; }
set
{
if (value != mBlinkOnColor)
{
mBlinkOnColor = value;
if (!mBlinkOnColor.Equals(Color.Empty) && !mBlinkOffColor.Equals(Color.Empty))
{
if (mBlinkStyle == null)
mBlinkStyle = this.Styles.Add("Blink");
}
}
}
}
/// <summary>
/// Gets or sets the index of the column at the current point.
/// </summary>
[Browsable(false)]
public int ColIndex
{
get { return mColumnIndex; }
set { mColumnIndex = value; }
}
[Browsable(false)]
public DataTable DataTable
{
get { return mDataSource; }
set { mDataSource = value; }
}
[Browsable(true), Category("Behavior"), Description("If set to True, prevents resizing when the user double-clicks a cell."),
DisplayName("DisableCellDoubleClick")]
public bool DisableCellDoubleClick
{
get { return mDisableCellDoubleClick; }
set { mDisableCellDoubleClick = value; }
}
[Browsable(true), Category("Behavior"), Description("If set to True, disables standard selection modes on the grid."),
DisplayName("OverrideSelectionMode")]
public bool OverrideSelectionMode
{
get { return mOverrideSelectionMode; }
set
{
mOverrideSelectionMode = value;
if (!mOverrideSelectionMode)
base.SelectionMode = mBaseSelectionMode;
}
}
/// <summary>
/// Gets or sets the index of the row at the current point.
/// </summary>
[Browsable(false)]
public int RowIndex
{
get { return mRowIndex; }
set { mRowIndex = value; }
}
[Browsable(true), Category("Behavior"), Description("Determines the selection mode for this control. This property " +
"is disabled when OverrideSelectionMode is set to True."), DisplayName("SelectionMode")]
public new SelectionModeEnum SelectionMode
{
get { return base.SelectionMode; }
set
{
if (mOverrideSelectionMode)
base.SelectionMode = mBaseSelectionMode;
else
base.SelectionMode = value;
}
}
[Browsable(false)]
public int Sheet
{
get { return mSheet; }
set { mSheet = value; }
}
[Browsable(false)]
public C1XLBook Workbook
{
get { return mWorkbook; }
}
#endregion
#region Public Methods
public void Blink(bool enable)
{
if (!mAllowBlinking)
return;
if (enable)
{
if (mTimer == null)
{
mTimer = new Timer();
mTimer.Tick += Timer_Tick;
}
mTimer.Interval = 400;
mTimer.Enabled = true;
}
else
{
mTimer.Enabled = false;
if (mTimer != null)
{
mTimer.Tick -= Timer_Tick;
mTimer.Dispose();
}
mTimer = null;
}
}
public void ClearSelections()
{
mSelectedRows.Clear();
BeginUpdate();
Refresh();
}
public int[] GetSelections()
{
mSelectedRows.Sort();
return mSelectedRows.ToArray();
}
public bool IsBlinking()
{
return mTimer.Enabled;
}
public override bool IsCellHighlighted(int row, int col)
{
if (DesignMode)
return false;
if (mSelectedRows.Contains(row))
return true;
if (base.IsCellHighlighted(row, col))
return true;
if (base.IsCellCursor(row, col))
{
if (base.FocusRect != FocusRectEnum.None && Focused)
return false;
if (base.Editor != null)
return false;
}
return false;
}
#endregion
#region Protected Methods
protected override void OnAfterSelChange(RangeEventArgs e)
{
base.OnAfterSelChange(e);
base.Redraw = false;
//A row has been selected programmatically.
if ((Control.MouseButtons & MouseButtons.Left) == 0)
{
if (!e.NewRange.IsValid)
return;
int rowIndex = e.NewRange.TopRow;
if (!mSelectedRows.Contains(rowIndex))
mSelectedRows.Add(rowIndex);
}
else
{
//Row selected by mouse click.
if ((Control.ModifierKeys & Keys.Control) == 0)
{
if (!e.NewRange.IsValid)
return;
int rowIndex = e.NewRange.TopRow;
mSelectedRows.Clear();
for (int i = base.Rows.Fixed; i < base.Rows.Count; i++)
{
if (i == rowIndex)
mSelectedRows.Add(rowIndex);
}
}
//Click-Shift clears the list.
if ((Control.ModifierKeys & Keys.Shift) != 0)
mSelectedRows.Clear();
else if ((Control.ModifierKeys & Keys.Control) != 0)
{
//Select non-contiguous rows.
if (!e.NewRange.IsValid)
return;
int rowIndex = e.NewRange.TopRow;
if (!mSelectedRows.Contains(rowIndex))
mSelectedRows.Add(rowIndex);
else
mSelectedRows.Remove(rowIndex);
}
}
base.Redraw = true;
}
protected override void OnComboDropDown(RowColEventArgs e)
{
CellStyle blank = this.Styles.Add(null);
blank.BackColor = Color.FromKnownColor(KnownColor.Window);
blank.ForeColor = Color.FromKnownColor(KnownColor.WindowText);
this.SetCellStyle(e.Row, e.Col, blank);
//base.OnComboDropDown(e);
}
/// <summary>
/// Overrides the double-click event.
/// </summary>
/// <param name="e"></param>
protected override void OnDoubleClick(EventArgs e)
{
HitTestInfo hti = HitTest();
//Load the coordinates from the hit test.
mRowIndex = hti.Row;
mColumnIndex = hti.Column;
switch (hti.Type)
{
case HitTestTypeEnum.RowHeader:
AutoSizeRow(hti.Row);
break;
case HitTestTypeEnum.ColumnHeader:
case HitTestTypeEnum.Cell:
if (hti.Type == HitTestTypeEnum.Cell)
{
if (mDisableCellDoubleClick)
{
base.OnDoubleClick(e);
return;
}
}
//Resize the column to accommodate the widest text in it.
//If the column allows sorting, disable it before resizing.
bool allowSort = Cols[hti.Column].AllowSorting;
if (allowSort)
Cols[hti.Column].AllowSorting = false;
AutoSizeCol(hti.Column);
//Reenable sorting if the column should support it.
if (allowSort)
Cols[hti.Column].AllowSorting = true;
break;
default:
break;
}
}
/// <summary>
/// Handles the CaptureChanged event.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseCaptureChanged(EventArgs e)
{
mResizeRow = -1;
base.OnMouseCaptureChanged(e);
}
/// <summary>
/// Handles the MouseDown event.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
HitTestInfo ht = HitTest(PointToClient(e.Location));
switch (ht.Type)
{
case HitTestTypeEnum.ColumnResize:
case HitTestTypeEnum.None:
base.OnMouseDown(e);
return;
case HitTestTypeEnum.RowHeader:
mDataSource = ((DataTable)DataSource).Copy();
base.OnMouseDown(e);
return;
}
bool pressed = (Control.MouseButtons & MouseButtons.Left) != 0;
if ((mResizeRow > -1 || ht.Type == HitTestTypeEnum.RowResize) && pressed)
{
mResizeRow = ht.Row;
Capture = true;
Row r = Rows[mResizeRow];
mStartY = e.Y - r.HeightDisplay;
if (mStartY < 2)
mStartY = 2;
}
else
base.OnMouseDown(e);
}
/// <summary>
/// Handles the MouseMove event.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseMove(MouseEventArgs e)
{
if (AllowResizing == AllowResizingEnum.Columns ||
AllowResizing == AllowResizingEnum.ColumnsUniform ||
AllowResizing == AllowResizingEnum.None)
return;
bool pressed = (Control.MouseButtons & MouseButtons.Left) != 0;
HitTestInfo ht = HitTest(PointToClient(e.Location));
if (!pressed && ht.Type == HitTestTypeEnum.Cell)
{
Rectangle rect = GetCellRect(ht.Row, ht.Column);
if (ht.Row > 0 && ht.Y - rect.Y < 4)
mResizeRow = ht.Row + 1;
else if (rect.Bottom - ht.Y < 4)
mResizeRow = ht.Row;
else
{
Cursor = null;
mResizeRow = -1;
}
}
if (ht.Type != HitTestTypeEnum.ColumnResize)
{
if (pressed && mResizeRow > 1)
{
Row r = Rows[mResizeRow];
r.HeightDisplay = e.Y + mStartY;
if (r.HeightDisplay < 2)
r.HeightDisplay = 2;
}
}
base.OnMouseMove(e);
}
/// <summary>
/// Handles the MouseUp event.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (mResizeRow > -1)
{
HitTestInfo hti = HitTest(PointToClient(e.Location));
if (hti.Type != HitTestTypeEnum.RowResize)
return;
//Resize all the rows to match the current row height.
Row r = Rows[mResizeRow];
AutoResize = false;
BeginUpdate();
if (r.HeightDisplay < 2)
r.HeightDisplay = 2;
for (int i = 1; i < Rows.Count; i++)
{
Rows[i].HeightDisplay = r.HeightDisplay;
}
EndUpdate();
AutoResize = true;
}
base.OnMouseUp(e);
}
protected override void OnOwnerDrawCell(OwnerDrawCellEventArgs e)
{
for (int i = base.Cols.Fixed; i < base.Cols.Count; i++)
{
CellStyle cs = base.GetCellStyle(e.Row, e.Col);
if (cs != null && !String.IsNullOrEmpty(cs.Name))
e.Style = base.Styles[cs.Name];
else if (base.IsCellHighlighted(e.Row, e.Col))
base.OnOwnerDrawCell(e);
else if (base.IsCellSelected(e.Row, e.Col))
base.OnOwnerDrawCell(e);
else
base.OnOwnerDrawCell(e);
}
}
#endregion
#region Private Methods
private void Timer_Tick(object sender, EventArgs e)
{
CellStyle cs = this.Styles["Blink"];
cs.ForeColor = (cs.ForeColor == mBlinkOffColor) ? mBlinkOnColor : mBlinkOffColor;
}
#endregion
}
} |
using System;
using System.Linq;
using System.Collections.Generic;
using UIKit;
using Aquamonix.Mobile.IOS.UI;
using Aquamonix.Mobile.Lib.Utilities;
namespace Aquamonix.Mobile.IOS.Views
{
/// <summary>
/// Header that shows brief summary texts.
/// </summary>
public class SummaryHeader : AquamonixView
{
private const int LeftMargin = 17;
private const int RightMargin = 10;
private const int TopMargin = 15;
private const int BottomMargin = 15;
private const int LabelHeight = 25;
private static readonly FontWithColor TextFont = new FontWithColor(Fonts.BoldFontName, Sizes.FontSize5, Colors.StandardTextColor);
private List<AquamonixLabel> _messageLabels = new List<AquamonixLabel>();
public int ContentHeight
{
get
{
return (this._messageLabels.Any() ? TopMargin + BottomMargin + (_messageLabels.Count * LabelHeight) : 0);
}
}
public SummaryHeader() : base()
{
ExceptionUtility.Try(() =>
{
this.BackgroundColor = Colors.LightGrayBackground;
});
}
public void SetMessages(IEnumerable<string> messages)
{
ExceptionUtility.Try(() =>
{
this.Clear();
if (messages != null)
{
foreach (string msg in messages)
{
var label = new AquamonixLabel();
label.Text = msg;
label.SetFontAndColor(TextFont);
this._messageLabels.Add(label);
this.AddSubview(label);
}
}
});
}
public void Clear()
{
ExceptionUtility.Try(() =>
{
foreach (var label in _messageLabels)
{
label.RemoveFromSuperview();
}
this._messageLabels.Clear();
});
}
public override void SizeToFit()
{
ExceptionUtility.Try(() =>
{
if (this.Superview?.Frame != null) {
this.SetFrameSize(this.Superview.Frame.Width, this.ContentHeight);
}
});
}
public override void LayoutSubviews()
{
ExceptionUtility.Try(() =>
{
base.LayoutSubviews();
int currentY = TopMargin;
foreach (var label in this._messageLabels)
{
label.SetFrameSize(this.Frame.Width - LeftMargin - RightMargin, LabelHeight);
label.SetFrameLocation(LeftMargin, currentY);
label.EnforceMaxXCoordinate(this.Frame.Width - RightMargin);
currentY = (int)label.Frame.Bottom;
}
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace SomeTechie.RoundRobinScheduleGenerator
{
[XmlType()]
public class RoundRobinTeamData
{
protected Team _team;
[XmlElement("Team", typeof(Team))]
public Team Team
{
get
{
return _team;
}
set
{
_team = value;
}
}
[XmlIgnore()]
public bool IsBye
{
get
{
return Team is ByeTeam;
}
}
protected int _scheduleVersion = -1;
[XmlIgnore()]
public int ScheduleVersion
{
get
{
return _scheduleVersion;
}
}
[XmlIgnore()]
protected int _numGamesWon = -1;
public int NumGamesWon
{
get
{
if (_numGamesWon == -1)
{
int numGamesWon = 0;
foreach (Game game in PlayedGames)
{
if (game.TeamGameResults[Team.Id].WonGame)
{
numGamesWon++;
}
}
_numGamesWon = numGamesWon;
}
return _numGamesWon;
}
}
[XmlIgnore()]
protected decimal _percentGamesWon = -1;
public decimal PercentGamesWon
{
get
{
if (_percentGamesWon == -1)
{
decimal percentGamesWon = 0;
if (PlayedGames.Length > 0)
{
percentGamesWon = (decimal)NumGamesWon / (decimal)PlayedGames.Length;
}
_percentGamesWon = percentGamesWon;
}
return _percentGamesWon;
}
}
[XmlIgnore()]
protected int _totalScore = -1;
public int TotalScore
{
get
{
if (_totalScore == -1)
{
int totalScore = 0;
foreach (Game game in PlayedGames)
{
totalScore += game.TeamGameResults[Team.Id].NumPoints;
}
_totalScore = totalScore;
}
return _totalScore;
}
}
[XmlIgnore()]
protected decimal _averageScore = -1;
public decimal AverageScore
{
get
{
if (_averageScore == -1)
{
decimal averageScore = 0;
if (PlayedGames.Length > 0)
{
averageScore = (decimal)TotalScore / (decimal)PlayedGames.Length;
}
_averageScore = averageScore;
}
return _averageScore;
}
}
private List<Game> _playedGames = new List<Game>();
private List<Game> _currentSchedulePlayedGames = new List<Game>();
private int _currentScheduleVersion = -1;
[XmlIgnore()]
public Game[] PlayedGames
{
get
{
int version = Controller.GetController().Tournament.ScheduleVersion;
List<Game> playedGamesForSchedule;
if (_currentScheduleVersion != version)
{
playedGamesForSchedule = new List<Game>();
foreach (Game game in _playedGames)
{
if (game.ScheduleVersion == version)
{
playedGamesForSchedule.Add(game);
}
}
_currentScheduleVersion = version;
_currentSchedulePlayedGames = playedGamesForSchedule;
resetStatistics();
}
else
{
playedGamesForSchedule = _currentSchedulePlayedGames;
}
return playedGamesForSchedule.ToArray();
}
protected set
{
_playedGames = new List<Game>(value);
}
}
protected List<int> _xmlPlayedGames;
[XmlArray("PlayedGames"), XmlArrayItem("PlayedGame")]
public int[] XmlSerializerPlayedGames
{
get
{
List<int> xmlPlayedGames = new List<int>();
foreach (Game playedGame in PlayedGames)
{
if (playedGame != null)
{
xmlPlayedGames.Add(playedGame.Id);
}
else
{
xmlPlayedGames.Add(-1);
}
}
return xmlPlayedGames.ToArray();
}
set
{
_xmlPlayedGames = new List<int>(value);
}
}
[XmlIgnore()]
public List<int> XmlPlayedGamesIn
{
get
{
return _xmlPlayedGames;
}
}
public RoundRobinTeamData(Team team)
{
_team = team;
}
protected RoundRobinTeamData()
{
}
public void resetStatistics()
{
_numGamesWon = -1;
_percentGamesWon = -1;
_totalScore = -1;
_averageScore = -1;
_scheduleVersion = Controller.GetController().Tournament.ScheduleVersion;
}
public void addPlayedGame(Game game)
{
_playedGames.Add(game);
if (game.ScheduleVersion == _currentScheduleVersion)
{
_currentSchedulePlayedGames.Add(game);
}
resetStatistics();
}
public void removePlayedGame(Game game)
{
_playedGames.Remove(game);
if (game.ScheduleVersion == _currentScheduleVersion)
{
_currentSchedulePlayedGames.Remove(game);
}
resetStatistics();
}
public override string ToString()
{
return Team.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.SqlServer.Metadata;
namespace OctoFX.Core.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Account",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Email = table.Column<string>(nullable: true),
IsActive = table.Column<bool>(nullable: false),
Name = table.Column<string>(nullable: true),
PasswordHashed = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Account", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ExchangeRate",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
Rate = table.Column<decimal>(nullable: false),
SellBuyCurrencyPair = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ExchangeRate", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Quote",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
BuyAmount = table.Column<decimal>(nullable: false),
ExpiryDate = table.Column<DateTimeOffset>(nullable: false),
QuotedDate = table.Column<DateTimeOffset>(nullable: false),
Rate = table.Column<decimal>(nullable: false),
SellAmount = table.Column<decimal>(nullable: false),
SellBuyCurrencyPair = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Quote", x => x.Id);
});
migrationBuilder.CreateTable(
name: "BeneficiaryAccount",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
AccountId = table.Column<int>(nullable: true),
AccountNumber = table.Column<string>(nullable: true),
Country = table.Column<string>(nullable: true),
IsActive = table.Column<bool>(nullable: false),
Nickname = table.Column<string>(nullable: true),
SwiftBicBsb = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_BeneficiaryAccount", x => x.Id);
table.ForeignKey(
name: "FK_BeneficiaryAccount_Account_AccountId",
column: x => x.AccountId,
principalTable: "Account",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "Deal",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn),
AccountId = table.Column<int>(nullable: true),
BuyAmount = table.Column<decimal>(nullable: false),
EnteredDate = table.Column<DateTimeOffset>(nullable: false),
NominatedBeneficiaryAccountId = table.Column<int>(nullable: true),
SellAmount = table.Column<decimal>(nullable: false),
Status = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Deal", x => x.Id);
table.ForeignKey(
name: "FK_Deal_Account_AccountId",
column: x => x.AccountId,
principalTable: "Account",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Deal_BeneficiaryAccount_NominatedBeneficiaryAccountId",
column: x => x.NominatedBeneficiaryAccountId,
principalTable: "BeneficiaryAccount",
principalColumn: "Id");
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("Deal");
migrationBuilder.DropTable("ExchangeRate");
migrationBuilder.DropTable("Quote");
migrationBuilder.DropTable("BeneficiaryAccount");
migrationBuilder.DropTable("Account");
}
}
}
|
using DataModel;
using DataStore.Interface;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace RequestMonitor.Controllers
{
[Route("[controller]")]
[Produces("application/json")]
public class ItemsController : Controller
{
IItemStore _itemStore;
public ItemsController(IItemStore itemStore)
{
_itemStore = itemStore;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var result = await _itemStore.GetLatestItemsByCountOrSeconds(100, 2);
System.Console.WriteLine(result.Count);
return Ok(result);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]ItemDataModel data)
{
if (data == null)
return StatusCode(400, new { Message = "Invalid Request Data. Json is not valid for expected contract" });
if (data.Item == null)
return StatusCode(400, new { Message = "Invalid Request Data. Json is not valid for expected contract" });
await _itemStore.AddItems(data);
return StatusCode(201);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Uplift.Models;
namespace Uplift.DataAccess.Data
{
public class ApplicationDbContext : IdentityDbContext
{
//Comment this while adding migrations
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
//Comment this while adding migrations
public DbSet<Category> Category { get; set; }
public DbSet<Frequency> Frequency { get; set; }
public DbSet<Service> Service { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("Server=localhost,1401;Database=Practice;User=sa;Password=benzy5@Rarc");
}
}
|
using System;
namespace Predictr.Models
{
public class PlayerScore
{
public String Guid { get; set; }
public String Username { get; set; }
public String FirstName { get; set; }
public String Surname { get; set; }
public int TotalPoints { get; set; }
}
}
|
using BO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TpWeb1.Models
{
public class CreateEditWarriorVM
{
public Warrior Warrior { get; set; }
public int? IdSelectedWeapon{ get; set; }
public IEnumerable<Weapon> Weapons{ get; set; }
}
} |
using UnityEngine;
using UnityEditor;
using Ardunity;
[CustomEditor(typeof(ImpulseInput))]
public class ImpulseInputEditor : ArdunityObjectEditor
{
SerializedProperty script;
SerializedProperty threshold;
SerializedProperty delayTime;
SerializedProperty clearTime;
SerializedProperty impulseMode;
SerializedProperty invert;
SerializedProperty OnTriggerShot;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
threshold = serializedObject.FindProperty("threshold");
delayTime = serializedObject.FindProperty("delayTime");
clearTime = serializedObject.FindProperty("clearTime");
impulseMode = serializedObject.FindProperty("impulseMode");
invert = serializedObject.FindProperty("invert");
OnTriggerShot = serializedObject.FindProperty("OnTriggerShot");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
ImpulseInput bridge = (ImpulseInput)target;
GUI.enabled = false;
EditorGUILayout.PropertyField(script, true, new GUILayoutOption[0]);
GUI.enabled = true;
EditorGUILayout.PropertyField(threshold, new GUIContent("Threshold"));
EditorGUILayout.PropertyField(delayTime, new GUIContent("Delay Time(sec)"));
EditorGUILayout.PropertyField(clearTime, new GUIContent("Clear Time(sec)"));
EditorGUILayout.PropertyField(impulseMode, new GUIContent("Impulse Mode"));
EditorGUILayout.PropertyField(invert, new GUIContent("Invert"));
if(Application.isPlaying)
{
EditorGUILayout.Slider("Impulse Value", bridge.Value, 0f, 1f);
EditorUtility.SetDirty(target);
}
EditorGUILayout.Separator();
EditorGUILayout.PropertyField(OnTriggerShot, new GUIContent("OnTriggerShot"));
this.serializedObject.ApplyModifiedProperties();
}
static public void AddMenuItem(GenericMenu menu, GenericMenu.MenuFunction2 func)
{
string menuName = "Unity/Add Bridge/Input/ImpulseInput";
if(Selection.activeGameObject != null)
menu.AddItem(new GUIContent(menuName), false, func, typeof(ImpulseInput));
else
menu.AddDisabledItem(new GUIContent(menuName));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace kindergarden.Models
{
public class ActiveUser
{
public int Id { get; set; }
public int UserId { get; set; }
public int SchoolId { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
} |
using System;
using System.Data.SQLite;
using Microsoft.AspNetCore.Mvc;
namespace TestWork.Controllers
{
[Route("[controller]")]
[ApiController]
public class CreateSqlController : Controller
{
static string connectionString = "Data Source=:memory:";
public SQLiteConnection connection = new SQLiteConnection(connectionString);
public object Performer { get; private set; }
public void CreateSql(SQLiteCommand command) // Создание таблицы Sql
{
command.CommandText = "DROP TABLE IF EXISTS TableSQL";
command.ExecuteNonQuery();
command.CommandText = @"CREATE TABLE TableSQL(DocumentNumber INTEGER
, Performer VARCHAR(2000), ApprovalState VARCHAR(2000))";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(1, 'Иванов И.И.','Согласовано')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(1, 'Петров П.П.','Ожидается решение')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(1, 'Сидоров С.С.','Ожидается решение')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(2, 'Ульянов В.Б.','Согласовано')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(2, 'Иванов И.И.','Ожидается решение')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(3, 'Петров П.П.','Согласовано')";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO TableSQL(DocumentNumber, Performer, ApprovalState) VALUES(4, 'Петров П.П.','Ожидается решение')";
command.ExecuteNonQuery();
}
[HttpGet("Return_TableSQL")]// Возвращает таблицу TableSQL
public IActionResult ReturnTableSQL()
{
using (connection)
{
connection.Open();
using (var command = new SQLiteCommand(connection))
{
CreateSql(command);
string readQuery = "SELECT * FROM TableSQL ";
var returnArray = new TableSQL[6];
command.CommandText = readQuery;
using (SQLiteDataReader reader = command.ExecuteReader())
{
var counter = 0;
while (reader.Read())
{
string value = reader.GetValue(1).ToString();
returnArray[counter] = new TableSQL
{
DocumentNumber = reader.GetInt32(0),
Performer = reader.GetValue(1).ToString(),
ApprovalState = reader.GetValue(2).ToString(),
};
counter++;
}
}
return Ok(returnArray);
}
}
}
[HttpGet("Return_Task1")]
public IActionResult ReturnSqlLiteTask1()
{
using (connection)
{
connection.Open();
using (var command = new SQLiteCommand(connection))
{
CreateSql(command);
string readQuery = "SELECT TableSQL.DocumentNumber, TableSQL.Performer FROM TableSQL WHERE TableSQL.ApprovalState = 'Ожидается решение' ORDER BY TableSQL.DocumentNumber";
var returnArray = new Task1[4];
command.CommandText = readQuery;
using (SQLiteDataReader reader = command.ExecuteReader())
{
var counter = 0;
while (reader.Read())
{
returnArray[counter] = new Task1
{
DocumentNumber = reader.GetInt32(0),
Performer = reader.GetValue(1).ToString(),
};
counter++;
}
}
return Ok(returnArray);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio24
{
class LerNumericos
{
static void Main(string[] args)
{
{
Console.Write("Digite a sua idade ");
int Idade = Convert.ToInt16(Console.ReadLine());
Console.Write("Digite o seu salário ");
double Salario = Convert.ToDouble(Console.ReadLine());
Console.Write("Digite um número muito grande ");
decimal Grande = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("Vc tem {0} anos e ganha {1} euros por mês! ", Idade, Salario);
Console.WriteLine("Digitou o número {0}", Grande);
}
}
}
}
|
using System.ComponentModel;
namespace XH.Domain.Enterprises
{
/// <summary>
/// 三场所三企业类型
/// </summary>
public enum TreePlaceOrEnterpriseType
{
[Description("金属冶炼企业")]
MetalSmelting = 1,
[Description("液氨制冷企业")]
LiquidAmmoniaCooling = 2,
[Description("船舶修造企业")]
ShipBuild = 3,
[Description("涉爆粉尘作业场所")]
ExplosiveDustOperations = 4,
[Description("有限空间作业场所")]
LimitedSpaceOperations = 5,
[Description("喷涂作业场所")]
SprayingOperations = 6
}
}
|
using Microsoft.EntityFrameworkCore;
using RegistroPedidosDetalle.DAL;
using RegistroPedidosDetalle.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace RegistroPedidosDetalle.BLL
{
public class OrdenesBLL
{
public static bool Guardar(Ordenes orden)
{
if (!Existe(orden.OrdenId))
return Insertar(orden);
else
return Modificar(orden);
}
public static bool Existe(int id)
{
Contexto contexto = new Contexto();
bool encontrado = false;
try
{
encontrado = contexto.Ordenes.Any(o => o.OrdenId== id);
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return encontrado;
}
public static bool Insertar(Ordenes orden)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
contexto.Ordenes.Add(orden);
paso = contexto.SaveChanges() > 0;
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static bool Modificar(Ordenes orden)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
contexto.Database.ExecuteSqlRaw($"Delete FROM MorasDetalle Where OrdenId = {orden.OrdenId}");
foreach (var item in orden.OrdenesDetalle)
{
contexto.Database.ExecuteSqlRaw($"INSERT INTO OrdenesDetalle (OrdenId, ProductoId, Cantidad, Costo) values({item.OrdenId},{orden.OrdenId},{item.Cantidad},{item.Costo})");
contexto.Entry(item).State = EntityState.Added;
}
contexto.Entry(orden).State = EntityState.Modified;
paso = contexto.SaveChanges() > 0;
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static bool Eliminar(int id)
{
bool paso = false;
Contexto contexto = new Contexto();
try
{
var orden = contexto.Ordenes.Find(id);
if (orden != null)
{
contexto.Ordenes.Remove(orden);
paso = contexto.SaveChanges() > 0;
}
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return paso;
}
public static Ordenes Buscar(int id)
{
Contexto contexto = new Contexto();
Ordenes orden;
try
{
orden = contexto.Ordenes
.Where(o => o.OrdenId== id)
.Include(o => o.OrdenesDetalle)
.FirstOrDefault();
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return orden;
}
public static List<Ordenes> GetList(Expression<Func<Ordenes, bool>> criterio)
{
List<Ordenes> lista = new List<Ordenes>();
Contexto contexto = new Contexto();
try
{
lista = contexto.Ordenes.Where(criterio).ToList();
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return lista;
}
public static List<Ordenes> GetOrdenes()
{
List<Ordenes> lista = new List<Ordenes>();
Contexto contexto = new Contexto();
try
{
lista = contexto.Ordenes.ToList();
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return lista;
}
public static Productos BuscarProductos(int id)
{
Contexto contexto = new Contexto();
Productos producto;
try
{
producto = contexto.Productos.Find(id);
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return producto;
}
public static List<Productos> GetListProductos(Expression<Func<Productos, bool>> criterio)
{
List<Productos> lista = new List<Productos>();
Contexto contexto = new Contexto();
try
{
lista = contexto.Productos.Where(criterio).ToList();
}
catch (Exception)
{
throw;
}
finally
{
contexto.Dispose();
}
return lista;
}
}
}
|
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Comment", "S1135", Justification = "XXX", Scope = "namespaceanddescendants", Target = "DFC.ServiceTaxonomy.UnitTests")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Comment", "S125", Justification = "XXX", Scope = "namespaceanddescendants", Target = "DFC.ServiceTaxonomy.UnitTests")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Comment", "S3881", Justification = "XXX", Scope = "namespaceanddescendants", Target = "DFC.ServiceTaxonomy.UnitTests")]
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
namespace Caapora
{
public class UIInterface : MonoBehaviour {
private static UIInterface _instance;
private Text TotalChamas;
private Text Timer;
public Text timeGUI;
public GameObject winnerModal;
public GameObject loserModal;
public GameObject pauseModal;
public static UIInterface instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<UIInterface>();
}
return _instance;
}
}
void Awake()
{
if (_instance == null)
{
_instance = this;
}
else
{
if (this != _instance)
Destroy(this.gameObject);
}
winnerModal = GameObject.Find("Winner");
loserModal = GameObject.Find("GameOver");
pauseModal = GameObject.Find("Pause");
instance.winnerModal.SetActive(false);
instance.loserModal.SetActive(false);
instance.pauseModal.SetActive(false);
TotalChamas = GameObject.Find("TotalChamas").GetComponent<Text>();
Timer = GameObject.Find("Tempo").GetComponent<Text>();
timeGUI = GameObject.Find("Hora").GetComponent<Text>();
}
private void Update()
{
TotalChamas.text = "Chamas: " + GameManager.totalOfFlames;
Timer.text = "Tempo : " + Mathf.Round(GameManager.instance.CurrentTimeLeft);
}
public void Hide()
{
_instance.gameObject.SetActive(false);
}
public void Show()
{
_instance.gameObject.SetActive(true);
}
public static IEnumerator showAndHideObject(GameObject go, int seconds)
{
go.SetActive(true);
yield return new WaitForSeconds(seconds);
go.SetActive(false);
yield return new WaitForSeconds(seconds);
}
public static IEnumerator hideAndShowObject(GameObject go, int seconds)
{
go.SetActive(false);
yield return new WaitForSeconds(seconds);
go.SetActive(true);
}
}
} |
namespace BlazorShared.Models.Patient
{
public class DeletePatientRequest : BaseRequest
{
public int ClientId { get; set; }
public int PatientId { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.