text stringlengths 13 6.01M |
|---|
namespace Ach.Fulfillment.Scheduler.Common
{
using System;
using System.Diagnostics.Contracts;
using Microsoft.Practices.ServiceLocation;
using Quartz;
using Quartz.Spi;
internal class JobFactory : IJobFactory
{
#region Constants and Fields
private readonly IServiceLocator serviceLocator;
#endregion
#region Constructors and Destructors
public JobFactory(IServiceLocator serviceLocator)
{
this.serviceLocator = serviceLocator;
}
#endregion
#region Public Methods and Operators
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
try
{
var job = this.serviceLocator.GetInstance(bundle.JobDetail.JobType) as IJob;
Contract.Assert(job != null);
return job;
}
catch (Exception exception)
{
throw new SchedulerException("Error on creation of new job", exception);
}
}
#endregion
}
} |
using Discord;
using OrbCore.ContentStructures;
using OrbCore.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrbCore.ContentTools {
internal static class DirectMessageTools {
public static DirectMessageContent CreateDirectMessageContentFromSocketMessage(IMessage message) {
ThrowIfContainsNull(message);
ThrowIfNotRightType(message);
return ExtractMessageToCreateDirectMessageContent(message);
}
public static bool IsSocketMessageDirectMessage(IMessage message) {
return IsTypeSocketUserMessage(message) && IsChannelTypeSocketDMChannel(message);
}
private static void ThrowIfNotRightType(IMessage message) {
if (!IsSocketMessageDirectMessage(message)) {
var ex = new InvalidCastException($"The type of SocketMessage that was given is not one that is from a direct message channel. It is of type {message.GetType().Name}. Suggest to correct and validate the type before sending in");
CoreLogger.LogException(ex);
throw ex;
}
}
private static void ThrowIfContainsNull(IMessage message) {
if (IsMessageNull(message)) {
ThrowNullField("message");
} else if (IsMessageContentNull(message)) {
ThrowNullField("message content");
} else if (IsChannelNull(message)) {
ThrowNullField("channel");
} else if (IsAuthorNull(message)) {
ThrowNullField("user");
}
}
private static void ThrowNullField(string field) {
var ex = new ArgumentNullException($"The {field} field in the message appears to be null");
CoreLogger.LogException(ex);
throw ex;
}
private static DirectMessageContent ExtractMessageToCreateDirectMessageContent(IMessage message) {
var content = message.Content;
var user = message.Author;
var channel = message.Channel;
return new DirectMessageContent(message, content, user, channel);
}
private static bool IsTypeSocketUserMessage(IMessage message) {
return message is IUserMessage;
}
private static bool IsMessageNull(IMessage message) {
return message == null;
}
private static bool IsMessageContentNull(IMessage message) {
return message.Content == null;
}
private static bool IsChannelTypeSocketDMChannel(IMessage message) {
return message.Channel is IDMChannel;
}
private static bool IsChannelNull(IMessage message) {
return message.Channel == null;
}
private static bool IsAuthorNull(IMessage message) {
return message.Author == null;
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Aquamonix.Mobile.Lib.Domain;
using Aquamonix.Mobile.Lib.Domain.Requests;
using Aquamonix.Mobile.Lib.Domain.Responses;
using Aquamonix.Mobile.Lib.Database;
using Aquamonix.Mobile.Lib.Utilities;
namespace Aquamonix.Mobile.Lib.Services
{
/// <summary>
/// Interface to alerts service.
/// </summary>
public interface IAlertService : IService
{
/// <summary>
/// Requests alerts for the given device.
/// The response from this call may be cached temporarily on the service layer.
/// </summary>
/// <param name="device">The device for which to start circuits</param>
/// <param name="onReconnect">What to do if the connection is interrupted & restored</param>
/// <param name="silentMode">If true, show no alerts or popups for any reason</param>
/// <returns>Response from the server</returns>
Task<AlertsResponse> RequestAlerts(Device device, Action onReconnect = null, bool silentMode = false);
/// <summary>
/// Requests alerts for all specified devices.
/// The response from this call may be cached temporarily on the service layer.
/// </summary>
/// <param name="deviceIds">The devices for which to get alerts</param>
/// <param name="onReconnect">What to do if the connection is interrupted & restored</param>
/// <param name="silentMode">If true, show no alerts or popups for any reason</param>
/// <returns>Response from the server</returns>
Task<AlertsResponse> RequestGlobalAlerts(IEnumerable<string> deviceIds, Action onReconnect = null, bool silentMode = false);
Task<DevicesResponse> DismissDeviceAlerts(string deviceId, IEnumerable<string> alertIds, Action onReconnect = null, bool silentMode = false);
Task<DevicesResponse> DismissGlobalAlerts(IEnumerable<string> alertIds, Action onReconnect = null, bool silentMode = false);
}
/// <summary>
/// Implementation of alerts service.
/// </summary>
public class AlertService : ServiceBase, IAlertService
{
public async Task<DevicesResponse> DismissDeviceAlerts(string deviceId, IEnumerable<string> alertIds, Action onReconnect = null, bool silentMode = false)
{
return await (this.DismissAlerts(alertIds, onReconnect, silentMode, global:false, deviceId:deviceId));
}
public async Task<DevicesResponse> DismissGlobalAlerts(IEnumerable<string> alertIds, Action onReconnect = null, bool silentMode = false)
{
return await (this.DismissAlerts(alertIds, onReconnect, silentMode, global:true));
}
public async Task<AlertsResponse> RequestAlerts(Device device, Action onReconnect = null, bool silentMode = false)
{
try
{
//prepare request
var deviceRequest = new DeviceRequest(device);
var request = new AlertsRequest(new DeviceRequest[] { deviceRequest });
//get response
var response = await this.DoRequest<AlertsRequest, AlertsResponse>(request, withCaching:false, onReconnect:onReconnect, silentMode:silentMode);
//after-response tasks
this.UpdateDevices(response, new string[] { device.Id});
return response;
}
catch (Exception e)
{
LogUtility.LogException(e);
}
return null;
}
public async Task<AlertsResponse> RequestGlobalAlerts(IEnumerable<string> deviceIds, Action onReconnect = null, bool silentMode = false)
{
try
{
//prepare request
var request = new AlertsRequest(deviceIds);
//get response
var response = await this.DoRequest<AlertsRequest, AlertsResponse>(request, withCaching: false, onReconnect:onReconnect, silentMode: silentMode);
//after-response tasks
this.UpdateDevices(response, deviceIds);
if (response != null && response.IsSuccessful)
{
DataCache.SetActiveAlertsCount(response.Body?.ActiveAlertsCount);
}
return response;
}
catch (Exception e)
{
LogUtility.LogException(e);
}
return null;
}
private void UpdateDevices(AlertsResponse alertsResponse, IEnumerable<string> deviceIds)
{
Dictionary<string, Device> devices = new Dictionary<string, Device>();
foreach (var id in deviceIds)
devices.Add(id, new Device() { Id = id, Alerts = new ItemsDictionary<Alert>() });
if (alertsResponse != null && alertsResponse.IsSuccessful && alertsResponse.Body.Alerts != null)
{
foreach (var alert in alertsResponse.Body.Alerts.Values)
{
string deviceId = alert.DeviceId;
if (deviceId != null && devices.ContainsKey(deviceId))
devices[deviceId].Alerts.Add(alert.Id, alert);
}
foreach (var device in devices.Values)
DataCache.AddOrUpdate(device);
}
}
private async Task<DevicesResponse> DismissAlerts(IEnumerable<string> alertIds, Action onReconnect = null, bool silentMode = false, bool global = false, string deviceId = null)
{
try
{
//prepare request
var request = new DismissAlertRequest(alertIds);
//get response
var response = await this.DoRequest<DismissAlertRequest, DevicesResponse>(request, withCaching: false, onReconnect: onReconnect, silentMode: silentMode);
//after-response tasks
if (response != null && response.Body != null)
{
if (global)
{
if (response.Body.ActiveAlertsCount != null)
{
DataCache.SetActiveAlertsCount(response.Body.ActiveAlertsCount);
}
if (response.Body.Alerts != null)
{
DataCache.CacheAlerts(response.Body.Alerts.Values, deleteNonexisting: true);
}
}
else
{
if (response.Body.Alerts != null)
{
DataCache.CacheAlertsForDevice(deviceId, response.Body.Alerts.Values, deleteNonexisting: true);
}
}
}
return response;
}
catch (Exception e)
{
LogUtility.LogException(e);
}
return null;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoogieLight : MonoBehaviour
{
public bool active = true;
private Material material;
private Color color;
void Start()
{
material = GetComponent<MeshRenderer>().material;
color = material.GetColor("_EmissiveColor");
}
void Update()
{
}
public void SetActive(bool a)
{
active = a;
if(!active)
{
material.SetColor("_EmissiveColor", Color.black);
}
else
{
material.SetColor("_EmissiveColor", color);
}
}
public void SetColor(Color c)
{
color = c;
if(active)
material.SetColor("_EmissiveColor", color);
}
}
|
namespace ConsoleApplication1.Models
{
public class MakelaarPartialViewModel
{
public string Naam { get; set; }
public int Positie { get; set; }
public int TotaalAantalObjecten { get; set; }
}
} |
/*-------------------------------------------------------------------------------------------------------------
* Programa: Ejercicio 13
* Autor: Douglas W. Jurado Peña
* Versión: DAM 2018/2019
* Descripción: Haz un programa que tenga un fichero en el que vaya guardando los datos: Nombre usuario, fecha, hora y tiempo de
* conexión, para cada una de las veces que se ha ejecutado.
-------------------------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics; // Sirve para por ejemplo, poder medir el tiempo transcurrido. Además de poder abrir automaticamente un archivo seleccionado cuando termine de realizar las operaciones.
using System.Security.Principal; //Para saber información del usuario y sobre windows.
namespace R8_Ejercicio13
{
class Program
{
static void Main(string[] args)
{
string ruta = @"C:\Prueba\ej13.txt";
Stopwatch sw = Stopwatch.StartNew();
DateTime fechaInicio = DateTime.Now;
using (FileStream flujo = new FileStream(ruta, FileMode.Append, FileAccess.Write))
{
using (StreamWriter escritor = new StreamWriter(flujo))
{
escritor.WriteLine(" Nombre de Usuario: {0}", WindowsIdentity.GetCurrent().Name);
escritor.WriteLine(" Fecha de conexión: {0}", fechaInicio.ToShortDateString());
escritor.WriteLine(" Hora de conexión: {0}", fechaInicio.ToShortTimeString());
sw.Stop();
escritor.WriteLine(" Tiempo de conexión: {0}", sw.Elapsed);
escritor.WriteLine("".PadLeft(40,'─'));
}
}
Process.Start(ruta); // Abre el fichero automaticamente.
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dropbox.Api;
using Dropbox.Api.Files;
using Dropbox.Api.Sharing;
using System.IO;
namespace PrinterTimerControl
{
public class DropboxConnection //1.0 build 25022016
{
public DropboxClient Connection { get; set; }
public string NomeAccount { get; set; }
public string EmailAccount { get; set; }
public string[] FolderList { get; set; }
public string[] FileList { get; set; }
public DropboxConnection() { }
public async Task Connetti(string token)
{
Connection = new DropboxClient(token);
await Credenziali();
await RefreshFolderList();
await RefreshFileList();
}
private async Task Credenziali()
{
var data = await Connection.Users.GetCurrentAccountAsync();
NomeAccount = data.Name.DisplayName;
EmailAccount = data.Email;
}
public async Task RefreshFolderList()
{
List<string> lista = new List<string>();
var list = await Connection.Files.ListFolderAsync(string.Empty);
foreach (var item in list.Entries.Where(i => i.IsFolder))
{
Console.WriteLine("Folder: " + item.Name);
lista.Add(item.Name);
}
FolderList = lista.ToArray();
}
public async Task RefreshFileList()
{
List<string> lista = new List<string>();
var list = await Connection.Files.ListFolderAsync(string.Empty);
foreach (var item in list.Entries.Where(i => i.IsFile))
{
Console.WriteLine("File: " + item.Name);
lista.Add(item.Name);
}
FileList = lista.ToArray();
}
public async Task Download(string folder, string file, string destinationPath)
{
byte[] data;
using (var response = await Connection.Files.DownloadAsync(folder + "/" + file))
{
data = await response.GetContentAsByteArrayAsync();
}
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
File.WriteAllBytes(destinationPath + @"\" + file, data);
}
public async void Upload(string folder, string file, string content)
{
var mem = new MemoryStream(Encoding.UTF8.GetBytes(content));
var updated = await Connection.Files.UploadAsync(folder + "/" + file, WriteMode.Overwrite.Instance, body: mem);
}
public async void Delete(string folder, string file)
{
await Connection.Files.DeleteAsync(folder + "/" + file);
}
}
}
|
using System.Linq;
using System.Security.Claims;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Web.Authentication;
using SFA.DAS.ProviderCommitments.Web.Extensions;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Extensions
{
[TestFixture]
class ServiceClaimExtensionsTests
{
[TestCase("DAA", true)]
[TestCase("DAB", true)]
[TestCase("DAC", true)]
[TestCase("DAV", true)]
[TestCase("DA", false)]
[TestCase("FAKE", false)]
public void ValidateServiceClaimsTest(string claim, bool expected)
{
bool result = claim.IsServiceClaim();
Assert.AreEqual(expected, result);
}
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAA, ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAA, ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAA, ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAA, ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, false)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAB, ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAC, ServiceClaim.DAV }, false)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAC, ServiceClaim.DAV }, false)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAC, ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAA }, true)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAA }, true)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAA }, true)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAA }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAB }, false)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAB }, true)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAB }, true)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAB }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAC }, false)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAC }, false)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAC }, true)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAC }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { ServiceClaim.DAV }, false)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { ServiceClaim.DAV }, false)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { ServiceClaim.DAV }, false)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { ServiceClaim.DAV }, true)]
[TestCase(ServiceClaim.DAA, new ServiceClaim[] { }, false)]
[TestCase(ServiceClaim.DAB, new ServiceClaim[] { }, false)]
[TestCase(ServiceClaim.DAC, new ServiceClaim[] { }, false)]
[TestCase(ServiceClaim.DAV, new ServiceClaim[] { }, false)]
public void ShouldReturnHasPermission(ServiceClaim minimumServiceClaim, ServiceClaim[] actualServiceClaims, bool expected)
{
var claims = actualServiceClaims.Select(a => new Claim(ProviderClaims.Service, a.ToString()));
var identity = new ClaimsIdentity(claims, "TestAuthType");
var claimsPrincipal = new ClaimsPrincipal(identity);
bool result = claimsPrincipal.HasPermission(minimumServiceClaim);
Assert.AreEqual(expected, result);
}
[TestCase(ServiceClaim.DAA, new string[] {"DCS", "DCFT"}, false)]
[TestCase(ServiceClaim.DAB, new string[] {"DCS", "DCFT"}, false)]
[TestCase(ServiceClaim.DAC, new string[] {"DCS", "DCFT"}, false)]
[TestCase(ServiceClaim.DAV, new string[] {"DCS", "DCFT"}, false)]
public void ShouldHandleNonDasClaimPermissions(ServiceClaim minimumServiceClaim, string[] actualServiceClaims, bool expected)
{
var claims = actualServiceClaims.Select(a => new Claim(ProviderClaims.Service, a));
var identity = new ClaimsIdentity(claims, "TestAuthType");
var claimsPrincipal = new ClaimsPrincipal(identity);
bool result = claimsPrincipal.HasPermission(minimumServiceClaim);
Assert.AreEqual(expected, result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ReqresTestTask.Models
{
class UserList
{
public int Page { get; set; }
public int PerPage { get; set; }
public int Total { get; set; }
public int TotalPages { get; set; }
public List<UserData> Data { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EasyDev.Presentation;
using SQMS.Services;
using EasyDev.BL;
using EasyDev.SQMS;
using System.Data;
using EasyDev.Util;
using SQMS.Application.Views.Common;
namespace SQMS.Application.Views.Basedata
{
public partial class RoleView : SQMSPage<RoleService>
{
private RoleService srv = null;
private Common.sGridItemList sGridItemlist;
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnPreInitializeViewEventHandler(object sender, EventArgs e)
{
srv = Service as RoleService;
sGridItemlist = new Common.sGridItemList(srv, this.ID);
}
protected override void OnInitializeViewEventHandler(object sender, EventArgs e)
{
DataRow drRole = DataSetUtil.GetFirstRowFromDataSet(this.ViewData, "ROLE");
if (drRole != null)
{
this.lblRoleCode.Text = ConvertUtil.ToStringOrDefault(drRole["ROLECODE"]);
this.lblRoleName.Text = ConvertUtil.ToStringOrDefault(drRole["ROLENAME"]);
this.lblStatus.Text = ConvertUtil.ToStringOrDefault(drRole["ISVOID"]) == "Y" ? "禁用" : "启用";
this.lblMeno.Text = ConvertUtil.ToStringOrDefault(drRole["MEMO"]);
}
////显示权限设置
//DataTable dtResPer = DataSetUtil.GetDataTableFromDataSet(ViewData, "RESPERMISSION");
//foreach (DataRow dr in dtResPer.Rows)
//{
//}
this.ShowGrid();
}
protected override void OnLoadDataEventHandler(object sender, EventArgs e)
{
this.ViewData = srv.LoadByKey(this.ID, true);
this.ViewData.Merge(srv.ResourceService.LoadByCondition("ISVOID='N'"));
this.ViewData.Merge(srv.OperationService.LoadByCondition("ISVOID='N'"));
this.ViewData.Merge(srv.ResPermissionService.LoadByCondition("roleid='" + this.ID + "'"));
}
/// <summary>
/// 显示权限设置界面
/// </summary>
private void ShowGrid()
{
//清空
this.sGrid.Columns.Clear();
//添加资源列
BoundField bf1 = new BoundField() { DataField = "RESTYPE", HeaderText = "分类", SortExpression = "RESTYPE", Visible = true };
bf1.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
bf1.ItemStyle.VerticalAlign = VerticalAlign.Middle;
//bf1.ItemStyle.BorderStyle = BorderStyle.None;
BoundField bf2 = new BoundField() { DataField = "resid", HeaderText = "功能标识", SortExpression = "resid", Visible = true };
bf2.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
BoundField bf3 = new BoundField() { DataField = "RESNAME", HeaderText = "功能点", SortExpression = "RESNAME" };
bf3.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
this.sGrid.Columns.Add(bf1);
this.sGrid.Columns.Add(bf2);
this.sGrid.Columns.Add(bf3);
//添加权限列
DataTable dtOperation = DataSetUtil.GetDataTableFromDataSet(ViewData, "OPERATION");
//int count_op = dtOperation.Rows.Count;
foreach (DataRow dr in dtOperation.Rows)
{
TemplateField bf = new TemplateField() { HeaderText = ConvertUtil.ToStringOrDefault(dr["OPNAME"]), SortExpression = "" };
bf.ItemTemplate = sGridItemlist.GetsGridItem(DataControlRowType.EmptyDataRow, ConvertUtil.ToStringOrDefault(dr["OPID"]), ConvertUtil.ToStringOrDefault(dr["OPNAME"]));
bf.HeaderTemplate = sGridItemlist.GetsGridItem(DataControlRowType.Header, ConvertUtil.ToStringOrDefault(dr["OPID"]), ConvertUtil.ToStringOrDefault(dr["OPNAME"]));
bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
bf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
this.sGrid.Columns.Add(bf);
}
//显示GRID
DataTable dtRESOURCE = DataSetUtil.GetDataTableFromDataSet(ViewData, "RESOURCEITEM");
DataView dvRes = dtRESOURCE.DefaultView;
dvRes.Sort = "RESTYPE";
//int count_res = dtRESOURCE.Rows.Count;
this.sGrid.DataSource = dvRes.Table;
this.sGrid.DataBind();
//显示权限设置
DataTable dtResPer = DataSetUtil.GetDataTableFromDataSet(ViewData, "RESPERMISSION");
foreach (DataRow dr in dtResPer.Rows)
{
foreach (GridViewRow gvr in this.sGrid.Rows)
{
if (gvr.Cells[1].Text == ConvertUtil.ToStringOrDefault(dr["RESID"]))
{
CheckBox cb = gvr.FindControl(ConvertUtil.ToStringOrDefault(dr["OPID"])) as CheckBox;
if (cb != null)
{
cb.Checked = true;
}
}
}
}
}
public void btnDelete_OnClick(object sender, EventArgs e)//删除
{
try
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("ROLEID", this.ID);
//ResPermission
srv.ResPermissionService.DeleteByKeys(dic);
//UserRole
srv.UserRoleService.DeleteByKeys(dic);
//Role
srv.DeleteByKey(this.ID);
}
catch (System.Exception ex)
{
throw ex;
}
Response.Redirect("RoleList.aspx");
}
public void btnEdit_Click(object sender, EventArgs e)
{
Response.Redirect("RoleEdit.aspx?p=employeeedit&id=" + this.ID);
}
public void btnNew_Click(object sender, EventArgs e)
{
Response.Redirect("RoleEdit.aspx?p=employeenew");
}
}
}
|
// Copyright (c) 2019 Jennifer Messerly
// This code is licensed under MIT license (see LICENSE for details)
using Kingmaker.Blueprints;
using Kingmaker.Blueprints.Classes.Spells;
using Kingmaker.ElementsSystem;
using Kingmaker.EntitySystem.Stats;
using Kingmaker.Enums.Damage;
using Kingmaker.RuleSystem;
using Kingmaker.RuleSystem.Rules.Abilities;
using Kingmaker.UnitLogic.Abilities;
using Kingmaker.UnitLogic.Abilities.Blueprints;
using Kingmaker.UnitLogic.Abilities.Components;
using Kingmaker.UnitLogic.Buffs;
using Kingmaker.UnitLogic.Buffs.Actions;
using Kingmaker.UnitLogic.Buffs.Blueprints;
using Kingmaker.UnitLogic.Mechanics.Actions;
using Kingmaker.UnitLogic.Mechanics.Components;
using Kingmaker.UnitLogic.Mechanics.Conditions;
using Kingmaker.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using static Kingmaker.UnitLogic.Commands.Base.UnitCommand;
using RES = EldritchArcana.Properties.Resources;
namespace EldritchArcana
{
static class FireSpells
{
internal static BlueprintAbility wallOfFire, delayedBlastFireball, incendiaryCloud, meteorSwarm;
internal static BlueprintBuff delayedBlastFireballBuff;
internal const string incendiaryCloudAreaId = "55e718bec0ea45caafb63ebad37d1829";
static LibraryScriptableObject library => Main.library;
internal static void Load()
{
Main.SafeLoad(LoadWallOfFire, "Wall of Fire");
Main.SafeLoad(LoadDelayedBlastFireball, RES.DelayedBlastFireballAbilityName_info);
Main.SafeLoad(LoadIncendiaryCloud, "Incendiary Cloud");
Main.SafeLoad(LoadMeteorSwarm, "Meteor Swarm");
}
static void LoadIncendiaryCloud()
{
var cloudArea = library.CopyAndAdd<BlueprintAbilityAreaEffect>(
"a892a67daaa08514cb62ad8dcab7bd90", // IncendiaryCloudArea, used by brass golem breath
"IncendiaryCloudSpellArea",
incendiaryCloudAreaId);
// TODO: should be 20ft.
// Visual effects can probably be scaled by hooking IAreaEffectHandler,
// and getting AreaEffectView.m_SpawnedFx, then .GetComponentsInChildren<ParticleSystem>(),
// then .transform.localScale or something like that.
cloudArea.Size = 15.Feet();
cloudArea.SetComponents(Helpers.CreateAreaEffectRunAction(round:
Helpers.CreateActionSavingThrow(SavingThrowType.Reflex,
Helpers.CreateActionDealDamage(DamageEnergyType.Fire,
DiceType.D6.CreateContextDiceValue(6), halfIfSaved: true))));
var spell = Helpers.CreateAbility("IncendiaryCloud", RES.IncendiaryCloudAbilityName_info,
RES.IncendiaryCloudAbilityDescription_info,
"85923af68485439dac5c3e9ddd2dd66c",
Helpers.GetIcon("e3d0dfe1c8527934294f241e0ae96a8d"), // fire storm
AbilityType.Spell, CommandType.Standard, AbilityRange.Medium,
Helpers.roundsPerLevelDuration, Helpers.reflexHalfDamage,
Helpers.CreateSpellComponent(SpellSchool.Conjuration),
Helpers.CreateSpellDescriptor(SpellDescriptor.Fire),
FakeTargetsAround.Create(cloudArea.Size),
Helpers.CreateContextRankConfig(),
Helpers.CreateRunActions(Helpers.Create<ContextActionSpawnAreaEffect>(c =>
{
c.DurationValue = Helpers.CreateContextDuration();
c.AreaEffect = cloudArea;
})));
spell.SpellResistance = false;
spell.CanTargetEnemies = true;
spell.CanTargetPoint = true;
spell.CanTargetFriends = true;
spell.CanTargetPoint = true;
spell.EffectOnAlly = AbilityEffectOnUnit.Harmful;
spell.EffectOnEnemy = AbilityEffectOnUnit.Harmful;
spell.AvailableMetamagic = Metamagic.Empower | Metamagic.Extend | Metamagic.Maximize | Metamagic.Quicken | Metamagic.Heighten | Metamagic.Reach;
incendiaryCloud = spell;
spell.AddToSpellList(Helpers.wizardSpellList, 8);
Helpers.AddSpellAndScroll(spell, "1cbb88fbf2a6bb74aa437fadf6946d22"); // scroll fire storm
spell.FixDomainSpell(8, "d8f30625d1b1f9d41a24446cbf7ac52e"); // fire domain
}
static void LoadDelayedBlastFireball()
{
// Note: this was reworked a bit. It does not spawn an item.
// The original version did use an item, and it worked (the code is still in ExperimentalSpells).
//
// But this version has nicer UX, IMO: you get the AOE targeting circle, and you can see the
// buff tick down, and the projectile is fired later from the caster's position, which looks neat.
// And it doesn't spawn the loot bag. I'm more confident it'll work correctly with saves and such.
var fireball = library.Get<BlueprintAbility>("2d81362af43aeac4387a3d4fced489c3");
var spell = Helpers.CreateAbility("DelayedBlastFireball", RES.DelayedBlastFireballAbilityName_info,
RES.DelayedBlastFireballAbilityDescription_info,//", and that time cannot change once it has been set unless someone touches the bead. If you choose a delay, the glowing bead sits at its destination until it detonates. " +
//"A creature can pick up and hurl the bead as a thrown weapon (range increment 10 feet). If a creature handles and moves the bead within 1 round of its detonation, there is a 25% chance that the bead detonates while being handled.",
"dfe891561c4d48ed8235268b0e7692e7",
fireball.Icon, AbilityType.Spell,
CommandType.Standard,
fireball.Range,
RES.DelayedBlastFireballDelayRoundsDescription_info,
fireball.LocalizedSavingThrow);
spell.SpellResistance = true;
spell.EffectOnAlly = AbilityEffectOnUnit.Harmful;
spell.EffectOnEnemy = AbilityEffectOnUnit.Harmful;
spell.AvailableMetamagic = Metamagic.Empower | Metamagic.Heighten | Metamagic.Maximize | Metamagic.Quicken | Metamagic.Reach;
var delayIds = new String[] {
"1e403a3188214a5c94ad63ede5928f81",
"2b6efa3759d842f7a549b85712784ee2",
"d762acc02c71446b834723ac20eb722a",
"2ca70c4525574cba8661beaef0a6b35f",
"45f6b2f4c3ce424d98d269548691d6bc",
"c1b683e809c348428011f0ed2e9da67b",
};
var spell0 = library.CopyAndAdd(fireball, $"{spell.name}Delay0", delayIds[0]);
spell0.SetNameDescriptionIcon(spell);
spell0.ReplaceContextRankConfig(c =>
{
Helpers.SetField(c, "m_UseMax", false);
Helpers.SetField(c, "m_Max", 20);
});
spell0.SpellResistance = true;
var buff = Helpers.CreateBuff($"{spell.name}Buff", spell.Name, spell.Description, "fc9490e3a7d24723a017609397521ea1",
spell.Icon, null,
Helpers.CreateAddFactContextActions(
deactivated: ActionCastSpellWithOriginalParams.Create(spell0)));
buff.Stacking = StackingType.Stack;
delayedBlastFireballBuff = buff;
var variants = new List<BlueprintAbility> { spell0 };
for (int delay = 1; delay <= 5; delay++)
{
var delaySpell = library.CopyAndAdd(spell0, $"{spell.name}Delay{delay}", delayIds[delay]);
delaySpell.SetName(String.Format(RES.DelaySpellName_info, spell.Name, delay));
delaySpell.SetComponents(
spell0.GetComponent<SpellComponent>(),
FakeTargetsAround.Create(20.Feet(), toCaster: true),
Helpers.CreateRunActions(
Helpers.CreateApplyBuff(buff, Helpers.CreateContextDuration(delay),
fromSpell: true, dispellable: false, toCaster: true)));
variants.Add(delaySpell);
}
spell.SetComponents(
Helpers.CreateSpellComponent(fireball.School),
Helpers.CreateSpellDescriptor(fireball.SpellDescriptor),
spell.CreateAbilityVariants(variants));
spell.AddToSpellList(Helpers.wizardSpellList, 7);
Helpers.AddSpellAndScroll(spell, "5b172c2c3e356eb43ba5a8f8008a8a5a", 1); // scroll of fireball
delayedBlastFireball = spell;
}
static void LoadMeteorSwarm()
{
var fireball = library.Get<BlueprintAbility>("2d81362af43aeac4387a3d4fced489c3");
var spell = library.CopyAndAdd(fireball, "MeteorSwarm", "2d18f8a4de6742e2ba954da0f19a4957");
spell.SetNameDescriptionIcon(RES.MeteorSwarmAbilityName_info,
RES.MeteorSwarmAbilityDescription_info,
Image2Sprite.Create("Mods/EldritchArcana/sprites/meteor_swarm.png"));
spell.LocalizedSavingThrow = Helpers.CreateString($"{spell.name}.SavingThrow", RES.MeteorSwarmSavingThrowDescription_info);
var deliverProjectile = UnityEngine.Object.Instantiate(fireball.GetComponent<AbilityDeliverProjectile>());
var fireballProjectile = deliverProjectile.Projectiles[0];
deliverProjectile.Projectiles.AddToArray(fireballProjectile, fireballProjectile);
var fire24d6 = Helpers.CreateActionDealDamage(DamageEnergyType.Fire,
DiceType.D6.CreateContextDiceValue(24), isAoE: true, halfIfSaved: true);
var fireDmgSave = Helpers.CreateActionSavingThrow(SavingThrowType.Reflex, fire24d6);
var conditionalDCIncrease = Harmony12.AccessTools.Inner(typeof(ContextActionSavingThrow), "ConditionalDCIncrease");
var dcAdjustArray = Array.CreateInstance(conditionalDCIncrease, 1);
var dcAdjust = Activator.CreateInstance(conditionalDCIncrease);
// If the main target was hit by the ranged touch attack, increase the DC by 4.
Helpers.SetField(dcAdjust, "Condition", Helpers.CreateConditionsCheckerAnd(ContextConditionNearMainTarget.Create()));
Helpers.SetField(dcAdjust, "Value", AbilitySharedValue.StatBonus.CreateContextValue());
dcAdjustArray.SetValue(dcAdjust, 0);
Helpers.SetField(fireDmgSave, "m_ConditionalDCIncrease", dcAdjustArray);
var increaseDCBy4 = Helpers.Create<ContextActionChangeSharedValue>(c =>
{
c.SharedValue = AbilitySharedValue.StatBonus;
c.SetValue = 4;
c.Type = SharedValueChangeType.Set;
});
var physical2d6 = Helpers.CreateActionDealDamage(PhysicalDamageForm.Bludgeoning,
DiceType.D6.CreateContextDiceValue(2));
spell.SetComponents(
SpellSchool.Evocation.CreateSpellComponent(),
SpellDescriptor.Fire.CreateSpellDescriptor(),
deliverProjectile,
Helpers.CreateAbilityTargetsAround(40.Feet(), TargetType.Any),
Helpers.CreateRunActions(
Helpers.CreateConditional(
// Check if this unit is the primary target
ContextConditionNearMainTarget.Create(),
// Perform a ranged touch attack on the primary target
ContextActionRangedTouchAttack.Create(
// If ranged touch succeeded:
// - 4 meteors hit for 2d6 bludgeoning damage each.
// - target takes 24d6 fire damage, -4 penalty to reflex save for half
new GameAction[] {
physical2d6, physical2d6, physical2d6, physical2d6,
increaseDCBy4
})),
// Apply fire damage to all targets in range.
fireDmgSave));
spell.AddToSpellList(Helpers.wizardSpellList, 9);
//spell.AddToSpellList(Helpers.magusSpellList, 9);
//spell.AddToSpellList(Helpers.fireDomainSpellList, 9);
//spell.AddToSpellList(Helpers.druidSpellList, 9);
//spell.AddToSpellList(Helpers., 9);
Helpers.AddSpellAndScroll(spell, "5b172c2c3e356eb43ba5a8f8008a8a5a"); // scroll of fireball
meteorSwarm = spell;
}
static void LoadWallOfFire()
{
// Convert the Evocation school's Elemental Wall (Sp) ability to a spell.
var areaEffect = library.CopyAndAdd<BlueprintAbilityAreaEffect>("ac8737ccddaf2f948adf796b5e74eee7",
"WallOfFireAreaEffect", "ff829c48791146aa9203fa243603d807");
var spell = wallOfFire = library.CopyAndAdd<BlueprintAbility>("77d255c06e4c6a745b807400793cf7b1",
"WallOfFire", "3d3be0a2b36f456384c6f5d50bc6daf2");
var areaComponents = areaEffect.ComponentsArray.Where(c => !(c is ContextRankConfig)).ToList();
areaComponents.Add(Helpers.CreateContextRankConfig());
areaEffect.SetComponents(areaComponents);
spell.name = "WallOfFire";
spell.SetNameDescriptionIcon(RES.WallOfFireAbilityName_info,
RES.WallOfFireAbilityDescription_info,
Helpers.GetIcon("9256a86aec14ad14e9497f6b60e26f3f")); // BlessingOfTheSalamander
spell.Type = AbilityType.Spell;
spell.SpellResistance = true;
spell.Parent = null;
spell.EffectOnAlly = AbilityEffectOnUnit.Harmful;
spell.EffectOnEnemy = AbilityEffectOnUnit.Harmful;
spell.AvailableMetamagic = Metamagic.Empower | Metamagic.Extend | Metamagic.Maximize | Metamagic.Quicken | Metamagic.Heighten | Metamagic.Reach;
var components = spell.ComponentsArray.Where(
c => !(c is AbilityResourceLogic) && !(c is ContextRankConfig) && !(c is AbilityEffectRunAction)).ToList();
components.Add(Helpers.CreateRunActions(Helpers.Create<ContextActionSpawnAreaEffect>(c =>
{
c.AreaEffect = areaEffect;
c.DurationValue = Helpers.CreateContextDuration();
})));
components.Add(Helpers.CreateContextRankConfig());
spell.SetComponents(components);
spell.AddToSpellList(Helpers.wizardSpellList, 4);
spell.AddToSpellList(Helpers.magusSpellList, 4);
spell.AddToSpellList(Helpers.druidSpellList, 5);
spell.AddSpellAndScroll("4b0ff254dca06894cba7eace7eef6bfe"); // scroll controlled fireball
spell.FixDomainSpell(4, "d8f30625d1b1f9d41a24446cbf7ac52e"); // fire domain
}
}
// Like ContextActionCastSpell, but preserves the spell's original ability params (caster level, DC, etc).
public class ActionCastSpellWithOriginalParams : BuffAction
{
public BlueprintAbility Spell;
public bool IsInstant;
public static ActionCastSpellWithOriginalParams Create(BlueprintAbility spell, bool instant = false)
{
var a = Helpers.Create<ActionCastSpellWithOriginalParams>();
a.Spell = spell;
a.IsInstant = instant;
return a;
}
public override string GetCaption() => $"Cast spell {Spell.name} with original ability params" + (IsInstant ? " instantly" : "");
public override void RunAction()
{
try
{
//Log.Append($"{GetType().Name}.RunAction()");
var context = Buff.Context.SourceAbilityContext;
var ability = context.Ability;
//Log.Append($" ability {ability} caster {context.Caster.CharacterName} fact {ability.Fact}");
//Log.Append($" spellbook {ability.Spellbook?.Blueprint} main target {context.MainTarget}");
//Log.Flush();
var spellData = new AbilityData(Spell, context.Caster.Descriptor, ability.Fact, ability.Spellbook?.Blueprint);
spellData.OverrideSpellLevel = Context.Params.SpellLevel;
var castSpell = new RuleCastSpell(spellData, context.MainTarget);
// Disable spell failure: we already cast the spell.
castSpell.IsCutscene = true;
castSpell = Rulebook.Trigger(castSpell);
if (IsInstant) castSpell.ExecutionProcess.InstantDeliver();
}
catch (Exception e)
{
Log.Error(e);
}
}
}
// Like ContextConditionIsMainTarget, but fixes targeting for spells that can also
// be cast at points (these spells always record a point as their target)
//
// TODO: AbilityEffectRunActionOnClickedTarget might be the way to solve this with
// the game's existing components.
public class ContextConditionNearMainTarget : ContextCondition
{
public static ContextConditionNearMainTarget Create() => Helpers.Create<ContextConditionNearMainTarget>();
protected override string GetConditionCaption() => "Is near main target?";
protected override bool CheckCondition()
{
var mainTarget = Context.MainTarget;
var target = Target;
Log.Append($"{GetType().Name}: main target {mainTarget}, target {target}");
if (mainTarget.IsUnit || !target.IsUnit) return mainTarget == target;
var distance = target.Unit.DistanceTo(mainTarget.Point);
Log.Append($" distance: {distance}, corpulence: {target.Unit.Corpulence}");
return distance < target.Unit.Corpulence;
}
}
}
|
using System;
using HTB.Database;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;
using HTBUtilities;
using Google.Api.Maps.Service.Geocoding;
using Google.Api.Maps.Service;
using System.Data;
using System.Threading;
namespace HTB.v2.intranetx
{
public partial class GetGegnerLatAndLng : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UpdateLatLong(HTBUtils.GetSqlRecords("SELECT Top 10 * FROM tblGegner WHERE GegnerLastZipPrefix = 'A' AND GegnerLatitude = 0", typeof(tblGegner)));
}
private void PopulateAddressgrid()
{
DataTable dt = GetInvoicesDataTableStructure();
ArrayList gList = HTBUtilities.HTBUtils.GetSqlRecords("SELECT * FROM tblGegner WHERE GegnerLastZipPrefix = 'A' ", typeof(tblGegner));
var request = new GeocodingRequest();
foreach (tblGegner g in gList)
{
var address = g.GegnerLastStrasse + ", " + g.GegnerLastZip + ", " + g.GegnerLastOrt + ", " + HTBUtils.GetCountryName(g.GegnerLastZipPrefix);
request.Address = address;
request.Sensor = "false";
var response = GeocodingService.GetResponse(request);
DataRow dr = dt.NewRow();
dr["Address"] = address;
dr["Lat"] = "";
dr["Lon"] = "";
if (response.Status == ServiceResponseStatus.Ok)
{
if (response.Results == null || response.Results.Length <= 0)
dr["Lat"] = "NIX";
else
{
foreach (var result in response.Results)
{
dr["Lat"] += result.Geometry.Location.Latitude + " ";
dr["Lon"] += result.Geometry.Location.Longitude + " ";
g.GegnerLatitude = Convert.ToDouble(result.Geometry.Location.Latitude);
g.GegnerLongitude = Convert.ToDouble(result.Geometry.Location.Longitude);
RecordSet.Update(g);
}
}
}
dt.Rows.Add(dr);
Thread.Sleep(200);
}
gvAddress.DataSource = dt;
gvAddress.DataBind();
}
private void UpdateLatLong(ArrayList list)
{
if (list.Count <= 0) return;
var request = new GeocodingRequest();
foreach (tblGegner g in list)
{
var address = g.GegnerLastStrasse + ", " + g.GegnerLastZip + ", " + g.GegnerLastOrt + ", " + HTBUtils.GetCountryName(g.GegnerLastZipPrefix);
request.Address = address;
request.Sensor = "false";
var response = GeocodingService.GetResponse(request);
if (response.Status == ServiceResponseStatus.Ok)
{
foreach (var result in response.Results)
{
g.GegnerLatitude = Convert.ToDouble(result.Geometry.Location.Latitude);
g.GegnerLongitude = Convert.ToDouble(result.Geometry.Location.Longitude);
RecordSet.Update(g);
}
}
}
Thread.Sleep(200);
UpdateLatLong(HTBUtils.GetSqlRecords("SELECT Top 10 * FROM tblGegner WHERE GegnerLastZipPrefix = 'A' AND GegnerLatitude = 0", typeof(tblGegner)));
}
private DataTable GetInvoicesDataTableStructure()
{
var dt = new DataTable();
dt.Columns.Add(new DataColumn("Address", typeof(string)));
dt.Columns.Add(new DataColumn("Lat", typeof(string)));
dt.Columns.Add(new DataColumn("Lon", typeof(string)));
return dt;
}
}
} |
using System;
using BlueSky.CommandBase;
using BSky.Lifetime.Interfaces;
using BSky.Lifetime;
using BlueSky.Windows;
using Microsoft.Practices.Unity;
using BSky.Statistics.Common;
using System.Windows;
using BSky.RecentFileHandler;
using BSky.Interfaces.Interfaces;
using BSky.ConfService.Intf.Interfaces;
namespace BlueSky.Commands.File
{
class FileNewCommand : BSkyCommandBase
{
protected override void OnPreExecute(object param)
{
}
public const String FileNameFilter = "IBM SPSS (*.sav)|*.sav| Excel 2003 (*.xls)|*.xls|Excel 2007-2010 (*.xlsx)|*.xlsx|Comma Seperated (*.csv)|*.csv|DBF (*.dbf)|*.dbf|R Obj (*.RData)|*.RData";
IConfigService confService = LifetimeService.Instance.Container.Resolve<IConfigService>();//12Dec2013
RecentDocs recentfiles = LifetimeService.Instance.Container.Resolve<RecentDocs>();//21Dec2013
protected override void OnExecute(object param)
{
//// Get initial Dir 12Feb2013 ////
string initDir = confService.GetConfigValueForKey("InitialDirectory");
// Start Some animation for loading dataset ///
//DatasetLoadingBusyWindow bw = new DatasetLoadingBusyWindow("Please wait while Dataset is Loading...");
//bw.Show();
//bw.Activate();
//bw.Close();//Comment this line after testing and uncomment one below FileOpen
//some code from here moved to FileOpen //
NewFileOpen("");//openFileDialog.FileName);
/// Stop the animation after loading ///
//bw.Close();
///Set initial Dir. 12Feb2013///
// initDir = Path.GetDirectoryName("");//openFileDialog.FileName);
// confService.ModifyConfig("InitialDirectory", initDir);
// confService.RefreshConfig();
}
protected override void OnPostExecute(object param)
{
}
IUnityContainer container = null;
IDataService service = null;
IUIController controller = null;
Window1 appwindow = null;
private void initGlobalObjects()
{
container = LifetimeService.Instance.Container;
service = container.Resolve<IDataService>();
controller = container.Resolve<IUIController>();
appwindow = LifetimeService.Instance.Container.Resolve<Window1>();//for refeshing recent files list
}
public void NewFileOpen(string filename)//21Feb 2013 For opening Dataset from File > Open & File > Recent
{
//if (filename != null && filename.Length > 0)
{
//IUnityContainer container = LifetimeService.Instance.Container;
//IDataService service = container.Resolve<IDataService>();
//IUIController controller = container.Resolve<IUIController>();
//Window1 appwindow = LifetimeService.Instance.Container.Resolve<Window1>();//for refeshing recent files list
initGlobalObjects();
if (!AreDefaultRPackagesLoaded())
return;
//if (System.IO.File.Exists(filename))
{
DataSource ds = service.NewDataset();//filename);
if (ds != null)
{
controller.LoadNewDataSet(ds);
//recentfiles.AddXMLItem(filename);//adding to XML file for recent docs
}
else
{
MessageBox.Show(appwindow, BSky.GlobalResources.Properties.Resources.cantopen+" " + filename +
".\n"+BSky.GlobalResources.Properties.Resources.reasonsAre +
"\n"+BSky.GlobalResources.Properties.Resources.ReqRPkgNotInstalled +
"\n"+BSky.GlobalResources.Properties.Resources.FormatNotSupported+
//"\nOR."+
"\n"+BSky.GlobalResources.Properties.Resources.OldSessionRunning +
//"\nOR."+
"\n"+BSky.GlobalResources.Properties.Resources.RSideIssue);
SendToOutputWindow( BSky.GlobalResources.Properties.Resources.ErrOpeningDataset, filename);
}
}
//else
//{
// MessageBox.Show(filename + " does not exist!", "File not found!", MessageBoxButton.OK, MessageBoxImage.Warning);
// //If file does not exist. It should be removed from the recent files list.
// recentfiles.RemoveXMLItem(filename);
//}
//18OCt2013 move up for using in msg box Window1 appwindow = LifetimeService.Instance.Container.Resolve<Window1>();//for refeshing recent files list
appwindow.RefreshRecent();
}
//08Apr2015 bring main window in front after file open, instead of output window
Window1 window = LifetimeService.Instance.Container.Resolve<Window1>();
window.Activate();
}
//Check for default pacakges those are required for opening datasets
private bool AreDefaultRPackagesLoaded()
{
if (Window1.DatasetReqRPackagesLoaded)//Check global if TRUE no need to get results from R
{
return true;
}
bool alldefaultloaded = true;
UAReturn retn = service.getMissingDefaultRPackages();
string missinglist = (string)retn.SimpleTypeData;
if (missinglist != null && missinglist.Length > 0)
{
alldefaultloaded = false;
}
if (!alldefaultloaded)
{
string firstmsg = BSky.GlobalResources.Properties.Resources.BSkyNeedsRPkgs+"\n\n";
string msg = "\n\n"+BSky.GlobalResources.Properties.Resources.InstallReqRPkgFrmCRAN + "\n"+BSky.GlobalResources.Properties.Resources.RegPkgsMenuPath;
MessageBox.Show(firstmsg + missinglist + msg, BSky.GlobalResources.Properties.Resources.ErrReqRPkgMissing, MessageBoxButton.OK, MessageBoxImage.Error);
}
//set global flag. if TRUE is set next line will not execute next time.
// as the 'if' in the beginning will return the control
Window1.DatasetReqRPackagesLoaded = alldefaultloaded;
Window1.DatasetReqPackages = missinglist;
return alldefaultloaded;
}
}
}
|
using Funding.Common.Constants;
using System.ComponentModel.DataAnnotations;
namespace Funding.Web.Models.ProjectViewModels
{
public class DonateViewModel
{
[Required(ErrorMessage = ProjectConst.DonateMessageRequired)]
public string Message { get; set; }
[Range(ProjectConst.MinimumAmountToDonate, double.MaxValue, ErrorMessage = ProjectConst.DonateAmountRequired)]
public decimal Amount { get; set; }
public int ProjectId { get; set; }
}
}
|
using System.Windows.Controls;
namespace WPF.NewClientl.UI.Dialogs
{
/// <summary>
/// SiginStatisticsDialog.xaml 的交互逻辑
/// </summary>
public partial class MeetingTopicFilesDialog : UserControl
{
public MeetingTopicFilesDialog()
{
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace MoodleStats.Droid
{
public class dialog_createAccount : DialogFragment
{
Button btnCreate;
EditText txtfName;
EditText txtlName;
EditText txtEmail;
EditText txtPassword;
EditText txtNewPassword;
EditText txtLocation;
public Context con{ get; set;}
public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
var view = inflater.Inflate (Resource.Layout.dialog_createAccount,container,false);
this.btnCreate = view.FindViewById<Button> (Resource.Id.btnCreateAccountDialog);
this.txtfName = view.FindViewById <EditText> (Resource.Id.txtfName);
this.txtlName = view.FindViewById<EditText> (Resource.Id.txtlName);
this.txtEmail = view.FindViewById<EditText> (Resource.Id.txtEmail);
this.txtPassword = view.FindViewById<EditText> (Resource.Id.txtMoodlePassword);
this.txtNewPassword = view.FindViewById<EditText> (Resource.Id.txtNewPassword);
this.txtLocation = view.FindViewById<EditText> (Resource.Id.txtLocation);
this.btnCreate.Click += delegate {
string msg = "";
if(this.txtfName.Text =="") msg="Enter First Name"; else if(this.txtlName.Text=="") msg="Enter Last name";else if(this.txtEmail.Text=="") msg="enter email";else if(this.txtPassword.Text=="")msg="enter moodle password";
else if(this.txtNewPassword.Text=="")msg="enter apps password";else if(this.txtLocation.Text=="")msg="Enter town or city";
else //Create
{
Controller.getController().service.Register(txtEmail.Text,txtPassword.Text,txtNewPassword.Text,txtfName.Text,txtlName.Text,txtLocation.Text);
}
if(msg!="")
{
Toast.MakeText(Activity,msg,ToastLength.Long).Show();
}
};
return view;
}
public override void OnActivityCreated (Bundle savedInstanceState)
{
Dialog.Window.RequestFeature (WindowFeatures.NoTitle);
base.OnActivityCreated (savedInstanceState);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerScorePanel : MonoBehaviour
{
public TextMeshProUGUI username;
public TextMeshProUGUI score;
public void SetScore(int _score)
{
this.score.text = _score.ToString();
}
public void SetUsername(string _name)
{
username.text = _name;
}
}
|
namespace DChild.Databases
{
public enum AccessoryType
{
Necklace = 1,
Ring,
_COUNT
}
} |
using System.ComponentModel;
namespace RimDev.AspNetCore.FeatureFlags.Tests
{
[Description("Test feature description.")]
public class TestFeature : Feature
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Profiling2.Domain.Prf.Documentation;
namespace Profiling2.Web.Mvc.Areas.Documents.Controllers.ViewModels
{
public class DocumentationFileViewModel
{
public int Id { get; set; }
public HttpPostedFileBase FileData { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime? LastModifiedDate { get; set; }
public int TagId { get; set; }
public IEnumerable<SelectListItem> TagSelectItems { get; set; }
public DocumentationFileViewModel() { }
public void PopulateDropDowns(IEnumerable<DocumentationFileTag> tags)
{
this.TagSelectItems = tags.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).OrderBy(x => x.Text);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControllerPosition : MonoBehaviour {
// access two Vive controllers
private SteamVR_TrackedObject trackedObject;
private SteamVR_Controller.Device device;
// create variable to hold controllers' vertical position
public float yPosition;
// Use this for initialization
void Start () {
trackedObject = GetComponent<SteamVR_TrackedObject>();
device = SteamVR_Controller.Input((int)trackedObject.index);
}
public void Update()
{
// we populate the variable with controllers' current vertical position (y axis) every frame.
// however,
// SteamVR calculates the controllers' vertical position using the distance from the floor which is created when you calibrate your play-area with SteamVR
// we want to meaningfully control effects using the controllers' vertical position.
// so we subtract 1.5 from the current vertical position, essentially setting the floor higher than it actually is.
// this way we get more usable 0-1 values that correspond better to real life movement.
yPosition = transform.position.y-1.25f;
}
}
|
using System;
class PlayWithIntDoubleAndString
{
private static void Main()
{
while (true)
{
ConsoleKeyInfo lsKey;
Console.WriteLine("Please choose a type :");
Console.WriteLine("1 --> int");
Console.WriteLine("2 --> double");
Console.WriteLine("3 --> string");
lsKey = Console.ReadKey(true);
switch (lsKey.Key)
{
case ConsoleKey.D1:
Console.Write("Please enter a int : ");
int liUsrEnt;
if (int.TryParse(Console.ReadLine(), out liUsrEnt))
{
Console.WriteLine(liUsrEnt + 1);
}
else
{
Console.WriteLine("Only int");
}
break;
case ConsoleKey.D2:
Console.Write("Please enter a double : ");
double ldUsrEnt;
if (double.TryParse(Console.ReadLine(), out ldUsrEnt))
{
Console.WriteLine(ldUsrEnt + 1);
}
else
{
Console.WriteLine("Only double");
}
break;
case ConsoleKey.D3:
Console.Write("Please enter a string : ");
string lsUsrStr = Console.ReadLine();
Console.WriteLine(lsUsrStr + "*");
break;
default:
Console.WriteLine("Only digit 1-2-3");
break;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
/// <summary>
/// Samling af små hjælpe funktioner
/// </summary>
public class Helpers
{
private const string Url = "http://localhost:38728/";
/// <summary>
/// Her sættes den "globale" connection string
/// </summary>
public static string ConnectionString = ConfigurationManager.ConnectionStrings["cmk_asp_nyhedssite"].ToString();
/// <summary>
/// Trim en string ned til en bestemt maksimum længde
/// </summary>
/// <param name="FullText">Den fulde tekst der skal klippes af</param>
/// <param name="MaxLength">Antallet af tegn der skal trimmes ned til</param>
/// <returns></returns>
public static string EvalTrimmed(string FullText, int MaxLength)
{
// Teksten kan indeholde HTML tags, som ikke bør blive klippet over,
// derfor fjernes alt der ligger imellem to <>
FullText = Regex.Replace(FullText, "<.*?>", string.Empty);
// hvis teksten stadig er længere end MaxLength
if (FullText.Length > MaxLength)
{
// så returneres det ønskede antal tegn, plus tre ...
return FullText.Substring(0, MaxLength - 3) + "..."; ;
}
// hvis teksten ikke er længere end MaxLength, returneres den den HTML frie tekst
return FullText;
}
public static string getHashSha256(string text, string mail)
{
byte[] key = Encoding.UTF8.GetBytes(mail);
byte[] bytes = Encoding.UTF8.GetBytes(text);
HMACSHA256 hashstring = new HMACSHA256(key);
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
public static void RSSSletNews(int value)
{
DataClassesDataContext db = new DataClassesDataContext();
var sletnew = db.dbNews.FirstOrDefault(i => i.Id == value);
if (sletnew != null)
{
string filePath = HttpContext.Current.Server.MapPath("~/Feeds/") + sletnew.Title + ".xml";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
public static void RSSSletKategori(int value)
{
DataClassesDataContext db = new DataClassesDataContext();
var sletKategori = db.dbCategories.FirstOrDefault(i => i.Id == value);
if (sletKategori != null)
{
string filePath = HttpContext.Current.Server.MapPath("~/Feeds/") + sletKategori.Title + ".xml";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
public static void RSSOpret(int idvalue)
{
DataClassesDataContext db = new DataClassesDataContext();
List<dbCategory> ListCategory = db.dbCategories.Where(i => i.Id == idvalue).ToList();
foreach (var itemChannel in ListCategory)
{
XmlDocument dom = new XmlDocument();
XmlProcessingInstruction xpi = dom.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
dom.AppendChild(xpi);
XmlElement rss = dom.CreateElement("rss");
rss.SetAttribute("version", "2.0");
XmlElement addRes = dom.CreateElement("channel");
XmlElement navn = dom.CreateElement("title");
navn.AppendChild(dom.CreateTextNode(itemChannel.Title));
addRes.AppendChild(navn);
XmlElement status = dom.CreateElement("description");
status.AppendChild(dom.CreateTextNode(itemChannel.Description));
addRes.AppendChild(status);
XmlElement links = dom.CreateElement("link");
links.AppendChild(dom.CreateTextNode(Url + "Categories.aspx?category_id='" + itemChannel.Id));
addRes.AppendChild(links);
List<dbNew> ListNews = db.dbNews.Where(i => i.CategoryId == idvalue).OrderByDescending(d => d.PostDate).ToList();
foreach (var item in ListNews)
{
XmlElement addNew = dom.CreateElement("item");
XmlElement titlenews = dom.CreateElement("title");
titlenews.AppendChild(dom.CreateTextNode(item.Title));
addNew.AppendChild(titlenews);
XmlElement statusNew = dom.CreateElement("description");
statusNew.AppendChild(dom.CreateTextNode(item.Content));
addNew.AppendChild(statusNew);
XmlElement linkNew = dom.CreateElement("link");
linkNew.AppendChild(dom.CreateTextNode(Url + "News.aspx?category_id=" + itemChannel.Id + "&news_id=" + itemChannel.Id));
addNew.AppendChild(linkNew);
addRes.AppendChild(addNew);
}
rss.AppendChild(addRes);
dom.AppendChild(rss);
dom.Save(HttpContext.Current.Server.MapPath("~/feeds/") + itemChannel.Id + "_" + itemChannel.Title + ".xml");
}
}
public static void RSSOpret()
{
throw new NotImplementedException();
}
} |
using System.Security.Cryptography;
using System.Text;
namespace Infrastructure.Encryption
{
/// <summary>
/// Collection of encryption methods
/// </summary>
public class DefaultEncryptor : IEncryptor
{
public string Md5Encrypt(string phrase)
{
var bytes = Encoding.UTF8.GetBytes(phrase);
bytes = new MD5CryptoServiceProvider().ComputeHash(bytes);
var hashBuilder = new StringBuilder();
foreach (byte b in bytes)
{
hashBuilder.Append(b.ToString("x2").ToLower());
}
return hashBuilder.ToString();
}
public string Sha512Encrypt(string phrase)
{
var bytes = Encoding.UTF8.GetBytes(phrase);
bytes = new SHA512CryptoServiceProvider().ComputeHash(bytes);
var hashBuilder = new StringBuilder();
foreach (byte b in bytes)
{
hashBuilder.Append(b.ToString("x2").ToLower());
}
return hashBuilder.ToString();
}
}
} |
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using System;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
namespace NLogServer
{
public class NLogHandler : ChannelHandlerAdapter
{
private static StreamWriter sw;
private static DateTime fileDate;
private static string logRoot;
private static string logFileFormat;
public NLogHandler(IConfiguration config)
{
logRoot = config["logRoot"];
logFileFormat = config["logFileFormat"];
Directory.CreateDirectory(logRoot);
OpenLogFileStream();
}
public override void ChannelRead(IChannelHandlerContext context, object message)
{
if (DateTime.Now.DayOfYear != fileDate.DayOfYear || DateTime.Now.Year != fileDate.Year)
{
sw.Flush();
sw.Close();
sw.Dispose();
OpenLogFileStream();
}
var buffer = message as IByteBuffer;
if (buffer != null)
{
var msg = buffer.ToString(Encoding.UTF8);
Console.Write(msg);
sw.Write(msg);
}
}
public override void ChannelReadComplete(IChannelHandlerContext context)
{
context.Flush();
}
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Console.WriteLine("Exception: " + exception);
sw.WriteLine("Exception: " + exception);
context.CloseAsync();
}
public static void OpenLogFileStream()
{
var logFile = Path.Combine(logRoot, string.Format(logFileFormat, DateTime.Now));
if (!File.Exists(logFile))
{
File.Create(logFile).Dispose();
}
var fs = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
sw = new StreamWriter(fs);
sw.AutoFlush = true;
fileDate = DateTime.Now;
}
}
} |
public class Solution {
public string ConvertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while (n > 0) {
int curr = n % 26;
if (curr == 0) {
sb.Insert(0, 'Z');
n -= 26;
}
else sb.Insert(0, (Char)(Convert.ToUInt16('A') + curr-1));
n = n / 26;
}
return sb.ToString();
}
} |
namespace FullTraversal
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Startup
{
public static void Main()
{
string sourcePath = @"D:\Vsichki Startupi\Softuni\C# Advanced 2\Streams";
string destinationPath = @"D:\Vsichki Startupi\Softuni\C# Advanced 2\Streams\files";
var filesDict = new Dictionary<string, Dictionary<string, long>>();
SearchDirectory(sourcePath, destinationPath, filesDict);
}
private static void SearchDirectory(string sourcePath, string destinationPath, Dictionary<string, Dictionary<string, long>> filesDict)
{
var filesInDirectory = System.IO.Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
foreach (var file in filesInDirectory)
{
var fileInfo = new FileInfo(file);
var extension = fileInfo.Extension;
var name = fileInfo.Name;
var length = fileInfo.Length;
if (!filesDict.ContainsKey(extension))
{
filesDict[extension] = new Dictionary<string, long>();
}
if (!filesDict[extension].ContainsKey(name))
{
filesDict[extension][name] = length;
}
}
filesDict = filesDict
.OrderByDescending(x => x.Value.Count) // number of files
.ThenBy(x => x.Key)
.ToDictionary(x => x.Key, x => x.Value);
using (var report = new StreamWriter($"{destinationPath}/reportFullSearch.txt"))
{
foreach (var kvp in filesDict)
{
var extension = kvp.Key;
var files = filesDict[extension]
.OrderByDescending(x => x.Value);
report.WriteLine(extension);
foreach (var file in files)
{
report.WriteLine($"--{file.Key} - {(double)file.Value / 1024:f3} kb");
}
}
}
}
}
} |
using System.Threading;
namespace VendingMachine.App
{
public class Machine
{
private const int TotalCapacity = 25;
private Can[] _inventory = new Can[TotalCapacity];
private int _pointer = 0;
public int Capacity
{
get { return _inventory.Length; }
}
private Can LookupCan()
{
return _inventory[_pointer-1];
}
private Can RetrieveCan()
{
Can can = _inventory[Interlocked.Decrement(ref _pointer)];
_inventory[_pointer] = null;
return can;
}
public bool AddCan(Can can_)
{
if (_pointer < TotalCapacity)
{
_inventory[_pointer] = can_;
Interlocked.Increment(ref _pointer);
return true;
}
return false;
}
public bool AddCans(int number_)
{
for (int i = 0; i < number_; i++)
{
if (!AddCan(new Can()))
{
return false;
}
}
return true;
}
public Can Vend(Card card_, string pin_)
{
if (card_ != null && card_.Account != null)
{
if(card_.EnterPIN(pin_))
{
Can can = LookupCan();
if(card_.Account.DebitAccount(can.Price))
{
can = RetrieveCan();
return can;
}
}
}
return null;
}
}
}
|
using TY.SPIMS.Entities;
using TY.SPIMS.POCOs;
using TY.SPIMS.Utilities;
namespace TY.SPIMS.Controllers.Interfaces
{
public interface IPurchaseCounterController
{
void Delete(int id);
CounterPurchas FetchCounterById(int id);
SortableBindingList<PurchaseCounterDisplayModel> FetchPurchaseCounterWithSearch(CounterFilterModel filter);
SortableBindingList<PurchaseCounterItemModel> FetchPurchaseItems(int id);
void Insert(CounterPurchas counter);
void Update(CounterPurchas newCounter);
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Research.TradingOrder.PurchaseCostCalculation
{
#region 【订单】调用采购 查底价
public class OrderBriefInfoWithProductsInput
{
[JsonProperty("orderNo")]
public string OrderNo { get; set; }
[JsonProperty("purchaseOrderItemIdList")]
public List<int>Products { get; set; }
}
public class PurchaseBriefProductItem
{
public string PID { set; get; }
public int Num { get; set; }
#region 批次
public int BatchId { get; set; }
public int ProductBatchId { get; set; }
#endregion
//采购子单号
public int POId { get; set; }
}
public class OrderInfoCostOutput
{
[JsonProperty("priceInfoList")]
public List<PurchaseProductCostItem> Products { get; set; }
}
public class PurchaseProductCostItem
{
#region Useless
//public string PID { set; get; }
//public int Num { get; set; }
#region 批次
//public int BatchId { get; set; }
//public int ProductBatchId { get; set; }
#endregion
#endregion
/// <summary>
//采购子单号
/// </summary>
[JsonProperty("purchaseOrderItemId")]
public int POId { get; set; }
/// <summary>
/// 采购是否优惠折扣
/// </summary>
///
[JsonProperty("isPromotion")]
public bool IsPromotion { get; set; }
/// <summary>
/// 底价
/// 若无优惠折扣--返回带成本的采购价
/// </summary>
[JsonProperty("basePrice")]
public decimal BaseCostPrice { set; get; }
}
#endregion
#region 仓库请求【订单】
public class OrderBasePriceWithProductsResponse
{
}
public class OrderBasePriceWithProductsRequest
{
public string OrderNo { get; set; }
public List<PurchaseProductItem> Products { get; set; }
}
public class PurchaseProductItem
{
public string PID { set; get; }
/// <summary>
/// ?是否需要
/// </summary>
public string Name { set; get; }
public int Num { get; set; }
#region 批次
public int BatchId { get; set; }
public int ProductBatchId { get; set; }
#endregion
#region 货主
//货主
public int OwnerId { get; set; }
// 货主名称
public string OwnerName { get; set; }
// 货主类型
public string OwnerType { get; set; }
#endregion
#region 供应商
//供应商
public int VendorId { get; set; }
public string VendorName { get; set; }
#endregion
//采购子单号
public int POId { get; set; }
//public decimal CostPrice { set; get; }
}
#endregion
}
|
// 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.Tests.Events;
public class LogEventPropertyValueTests
{
readonly PropertyValueConverter _converter =
new(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false);
[Fact]
public void AnEnumIsConvertedToANonStringScalarValue()
{
var value = _converter.CreatePropertyValue(Debug, Destructuring.Default);
Assert.IsType<ScalarValue>(value);
var sv = (ScalarValue)value;
Assert.NotNull(sv.Value);
Assert.IsType<LogEventLevel>(sv.Value);
}
[Fact]
public void AScalarValueToStringRendersTheValue()
{
var num = Some.Int();
var value = _converter.CreatePropertyValue(num, Destructuring.Default);
var str = value.ToString();
Assert.Equal(num.ToString(CultureInfo.InvariantCulture), str);
}
[Fact]
public void AScalarValueToStringRendersTheValueUsingFormat()
{
var num = Some.Decimal();
var value = _converter.CreatePropertyValue(num, Destructuring.Default);
var str = value.ToString("N2", null);
Assert.Equal(num.ToString("N2", CultureInfo.InvariantCulture), str);
}
[Fact]
public void AScalarValueToStringRendersTheValueUsingFormatProvider()
{
var num = Some.Decimal();
var value = _converter.CreatePropertyValue(num, Destructuring.Default);
var str = value.ToString(null, new CultureInfo("fr-FR"));
Assert.Equal(num.ToString(new CultureInfo("fr-FR")), str);
}
[Fact]
public void WhenDestructuringAKnownLiteralTypeIsScalar()
{
var guid = Guid.NewGuid();
var value = _converter.CreatePropertyValue(guid, Destructuring.Destructure);
var str = value.ToString();
Assert.Equal(guid.ToString(), str);
}
}
|
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour
{
//For this, your GameObject this script is attached to would have a
//Transform Component, a Mesh Filter Component, and a Mesh Renderer
//component. You will also need to assign your texture atlas / material
//to it.
[SerializeField] private MeshFilter filter;
public int mapSizeX;
public int mapSizeY;
private Mesh mesh;
private Vector2[] uvArray;
void Start()
{
BuildMesh();
}
public void BuildMesh()
{
int numTiles = mapSizeX * mapSizeY;
int numTriangles = numTiles * 6;
int numVerts = numTiles * 4;
Vector3[] vertices = new Vector3[numVerts];
uvArray = new Vector2[numVerts];
int x, y, iVertCount = 0;
for (x = 0; x < mapSizeX; x++)
{
for (y = 0; y < mapSizeY; y++)
{
vertices[iVertCount + 0] = new Vector3(x, y, 0);
vertices[iVertCount + 1] = new Vector3(x + 1, y, 0);
vertices[iVertCount + 2] = new Vector3(x + 1, y + 1, 0);
vertices[iVertCount + 3] = new Vector3(x, y + 1, 0);
iVertCount += 4;
}
}
int[] triangles = new int[numTriangles];
int iIndexCount = 0; iVertCount = 0;
for (int i = 0; i < numTiles; i++)
{
triangles[iIndexCount + 0] += (iVertCount + 0);
triangles[iIndexCount + 1] += (iVertCount + 1);
triangles[iIndexCount + 2] += (iVertCount + 2);
triangles[iIndexCount + 3] += (iVertCount + 0);
triangles[iIndexCount + 4] += (iVertCount + 2);
triangles[iIndexCount + 5] += (iVertCount + 3);
iVertCount += 4; iIndexCount += 6;
}
mesh = new Mesh();
//mesh.MarkDynamic(); //if you intend to change the vertices a lot, this will help.
mesh.vertices = vertices;
mesh.triangles = triangles;
filter.mesh = mesh;
//UpdateMesh(); //I put this in a separate method for my own purposes.
}
//Note, the example UV entries I have are assuming a tile atlas
//with 16 total tiles in a 4x4 grid.
public void UpdateMesh()
{
int iVertCount = 0;
for (int x = 0; x < mapSizeX; x++)
{
for (int y = 0; y < mapSizeY; y++)
{
uvArray[iVertCount + 0] = new Vector2(0, 0); //Top left of tile in atlas
uvArray[iVertCount + 1] = new Vector2(.25f, 0); //Top right of tile in atlas
uvArray[iVertCount + 2] = new Vector2(.25f, .25f); //Bottom right of tile in atlas
uvArray[iVertCount + 3] = new Vector2(0, .25f); //Bottom left of tile in atlas
iVertCount += 4;
}
}
filter.mesh.uv = uvArray;
}
}
|
namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Models.ServiceBus
{
public class RegistrationItem : InfoDataItem
{
}
}
|
namespace ElevatorKata
{
public class LiftArrivedEvent
{
public LiftArrivedEvent(Floor floor, Direction direction)
{
Direction = direction;
Floor = floor;
}
public Floor Floor { get; private set; }
public Direction Direction { get; private set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Runtime.InteropServices;
namespace identity
{
enum Screen
{
StartScreen,
Prologue,
Gameplay,
Pause,
Text,
Music,
RandomRoom,
JumpScare,
Chapter1,
Chapter2,
Chapter2b
}
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont Font;
//Classes
Screen currentScreen;
Screen introScreen;
Screen RandomRoom;
Screen Jump;
Screen chapter1;
Screen chapter2;
Screen chapter2b;
Screen gameplayscreen;
Screen gamepause;
Screen text;
Screen sounds;
StartScreen startscreen;
Prologue intro;
RandomRoom room;
JumpScare scare;
Chapter1 startgame;
Chapter2 startgame2;
Chapter2b startgame2b;
Gameplay gameplay;
Pause pause;
Text textbox;
Music music;
//Integers
int mousex;
int mousey;
private KeyboardState newState;
public int start = 2;
public int pausegame = 0;
public int level1 = 0;
public float scale;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
newState = Keyboard.GetState();
//graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = (int)(1150);
graphics.PreferredBackBufferHeight = (int)(720);
scale = 1.4444f;
}
//1440w // 900h
//center = 720w //450h
protected override void Initialize()
{
base.Initialize();
IsMouseVisible = true;
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
startscreen = new StartScreen(this);
currentScreen = Screen.StartScreen;
intro = new Prologue(this);
introScreen = Screen.Prologue;
room = new RandomRoom(this);
RandomRoom = Screen.RandomRoom;
scare = new JumpScare(this);
Jump = Screen.JumpScare;
startgame = new Chapter1(this);
chapter1 = Screen.Chapter1;
startgame2 = new Chapter2(this);
chapter2 = Screen.Chapter2;
startgame2b = new Chapter2b(this);
chapter2b = Screen.Chapter2b;
gameplay = new Gameplay(this);
gameplayscreen = Screen.Gameplay;
pause = new Pause(this);
gamepause = Screen.Pause;
textbox = new Text(this);
text = Screen.Text;
music = new Music(this);
sounds = Screen.Music;
Font = Content.Load<SpriteFont>(@"font");
base.LoadContent();
this.Window.Title = "Identity...";
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
//Mouse X and Y
MouseState mouseState = Mouse.GetState();
mousex = mouseState.X;
mousey = mouseState.Y;
//Main Menu
if (start == 0 || start == 2)
{
switch (currentScreen)
{
case Screen.StartScreen:
if (startscreen != null)
startscreen.Update(gameTime);
break;
}
}
if (JumpScare.shock >= 1)
{
switch (Jump)
{
case Screen.JumpScare:
if (scare != null)
scare.Update(gameTime);
break;
}
}
if (pausegame == 0)
{
//Character Movement
if (level1 >= 1)
{
switch (gameplayscreen)
{
case Screen.Gameplay:
if (gameplay != null)
gameplay.Update(gameTime);
break;
}
}
//Prologue
if (intro.time <= 20)
{
switch (introScreen)
{
case Screen.Prologue:
if (intro != null)
intro.Update(gameTime);
break;
}
}
//Chapter 1
if (level1 == 1)
{
switch (chapter1)
{
case Screen.Chapter1:
if (startgame != null)
startgame.Update(gameTime);
break;
}
}
//Chapter 2
if (level1 == 2)
{
switch (chapter2)
{
case Screen.Chapter2:
if (startgame2 != null)
startgame2.Update(gameTime);
break;
}
}
if (level1 == 3)
{
switch (chapter2b)
{
case Screen.Chapter2b:
if (startgame2b != null)
startgame2b.Update(gameTime);
break;
}
}
if (level1 == 4 || level1 == 5 || level1 == 6 || level1 == 7)
{
switch (RandomRoom)
{
case Screen.RandomRoom:
if (room != null)
room.Update(gameTime);
break;
}
}
}
//Pause
if (pausegame == 1)
{
switch (gamepause)
{
case Screen.Pause:
if (pause != null)
pause.Update(gameTime);
break;
}
}
switch (text)
{
case Screen.Text:
if (textbox != null)
textbox.Update(gameTime);
break;
}
switch (sounds)
{
case Screen.Music:
if (music != null)
music.Update(gameTime);
break;
}
//Exit
KeyboardState keyboardState = Keyboard.GetState();
newState = keyboardState;
if (newState.IsKeyDown(Keys.Escape)) { this.Exit(); }
//Keyboard Shortcuts to levels for debugging
if (newState.IsKeyDown(Keys.D1))
{
level1 = 1;
}
if (newState.IsKeyDown(Keys.D2))
{
level1 = 2;
}
if (newState.IsKeyDown(Keys.D3))
{
level1 = 3;
}
if (newState.IsKeyDown(Keys.D4))
{
level1 = 4;
}
if (newState.IsKeyDown(Keys.D5))
{
level1 = 5;
}
if (newState.IsKeyDown(Keys.D6))
{
level1 = 6;
}
if (newState.IsKeyDown(Keys.D7))
{
level1 = 7;
}
if (newState.IsKeyDown(Keys.D8))
{
level1 = 8;
}
if (newState.IsKeyDown(Keys.D9))
{
level1 = 9;
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
if (pausegame == 0)
{
GraphicsDevice.Clear(Color.Black);
//Draw SplashScreen
if (start == 0 || start == 2)
{
switch (currentScreen)
{
case Screen.StartScreen:
if (startscreen != null)
startscreen.Draw(spriteBatch);
break;
}
}
if (intro.time <= 16)
{
//Draw Intro
switch (introScreen)
{
case Screen.Prologue:
if (intro != null)
intro.Draw(spriteBatch);
break;
}
}
if (level1 == 1)
{
//Chapter 1
switch (chapter1)
{
case Screen.Chapter1:
if (startgame != null)
startgame.Draw(spriteBatch);
break;
}
}
if (level1 == 2)
{
//Chapter 2
switch (chapter2)
{
case Screen.Chapter2:
if (startgame2 != null)
startgame2.Draw(spriteBatch);
break;
}
}
if (level1 == 3)
{
//Chapter 2
switch (chapter2b)
{
case Screen.Chapter2b:
if (startgame2b != null)
startgame2b.Draw(spriteBatch);
break;
}
}
if (level1 == 4 || level1 == 5 || level1 == 6 || level1 == 7)
{
switch (RandomRoom)
{
case Screen.RandomRoom:
if (room != null)
room.Draw(spriteBatch);
break;
}
}
//Character Movement
if (level1 >= 1)
{
switch (gameplayscreen)
{
case Screen.Gameplay:
if (gameplay != null)
gameplay.Draw(spriteBatch);
break;
}
}
}
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
spriteBatch.DrawString(Font, mousex.ToString(), new Vector2(0, 0), Color.White);
spriteBatch.DrawString(Font, mousey.ToString(), new Vector2(50, 0), Color.White);
spriteBatch.DrawString(Font, level1.ToString(), new Vector2(100, 0), Color.White);
spriteBatch.End();
if (JumpScare.shock >= 1)
{
switch (Jump)
{
case Screen.JumpScare:
if (scare != null)
scare.Draw(spriteBatch);
break;
}
}
switch (text)
{
case Screen.Text:
if (textbox != null)
textbox.Draw(spriteBatch);
break;
}
//Pause
if (pausegame == 1)
{
switch (gamepause)
{
case Screen.Pause:
if (pause != null)
pause.Draw(spriteBatch);
break;
}
}
base.Draw(gameTime);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebCalcMVC.Models;
namespace WebCalcMVC.Controllers
{
public class HomeController : Controller
{
// GET: Home
[HttpGet]
public ActionResult Index()
{
UserInput userIn = new UserInput();
Session.Add("userInput", userIn);
return View("Index", userIn);
}
[HttpPost]
public ActionResult Index(string submitButton, string currentInput) {
UserInput userIn = (UserInput)this.Session["userInput"];
userIn.CurrentInput = currentInput;
userIn.Result = Calculate(userIn);
userIn.History += userIn.CurrentInput + submitButton;
switch (submitButton)
{
case "+":
userIn.LastOperation = Operation.Add;
break;
case "-":
userIn.LastOperation = Operation.Minus;
break;
case "*":
userIn.LastOperation = Operation.Multi;
break;
case "/":
userIn.LastOperation = Operation.Div;
break;
case "C":
userIn.History = String.Empty;
userIn.LastOperation = Operation.None;
userIn.Result = 0.0;
userIn.CurrentInput = String.Empty;
break;
case "=":
userIn.History += userIn.Result;
userIn.LastOperation = Operation.Result;
userIn.CurrentInput = String.Empty;
break;
}
return View("Index", userIn);
}
private double Calculate(UserInput userIn)
{
double result = 0.0;
if (userIn.LastOperation == Operation.None)
{
result = ParseInput(userIn.CurrentInput);
}
else
{
result = userIn.Result;
double value = ParseInput(userIn.CurrentInput);
switch (userIn.LastOperation)
{
case Operation.Add:
result += value;
break;
case Operation.Minus:
result -= value;
break;
case Operation.Multi:
result *= value;
break;
case Operation.Div:
result /= value;
break;
case Operation.Result:
userIn.History = userIn.Result.ToString();
break;
}
}
return result;
}
private double ParseInput(String input)
{
double inputValue = 0.0;
if (input != null && !input.Equals(""))
{
try
{
inputValue = Double.Parse(input);
}
catch
{
inputValue = 0.0;
}
}
return inputValue;
}
}
} |
using System;
using System.Windows.Threading;
namespace Waterskibaan
{
public class Game
{
public readonly Waterskibaan _waterskibaan = new Waterskibaan();
private readonly WachtrijInstructie _wachtrijInstrucie = new WachtrijInstructie();
private readonly InstructieGroep _instructieGroep = new InstructieGroep();
private readonly WachtrijStarten _wachtrijStarten = new WachtrijStarten();
private int _timeElapsed;
public event Action<NieuweBezoekerArgs> NieuweBezoeker;
public event Action<InstructieAfgelopenArgs> InstructieAfgelopen;
public event Action<LijnenVerplaatsArgs> LijnenVerplaats;
public readonly Logger logger;
public Game()
{
logger = new Logger(_waterskibaan.Kabel);
}
public void Initialize(DispatcherTimer timer)
{
NieuweBezoeker += _wachtrijInstrucie.OnNieuweBezoeker;
InstructieAfgelopen += _instructieGroep.OnInstructieAfgelopen;
InstructieAfgelopen += _wachtrijStarten.OnInstructieAfgelopen;
timer.Tick += GameLoop;
}
private void GameLoop(object source, EventArgs args)
{
_timeElapsed++;
if (_timeElapsed % 3 == 0)
{
HandleNewVisitor();
}
if (_timeElapsed % 4 == 0)
{
HandleChangeLines();
}
if (_timeElapsed % 20 == 0)
{
HandleInstructionEnded();
}
}
private void HandleNewVisitor()
{
var visitor = new Sporter(MoveCollection.GetWillekeurigeMoves());
var args = new NieuweBezoekerArgs()
{
Sporter = visitor
};
logger.AddVisitor(visitor);
NieuweBezoeker?.Invoke(args);
}
private void HandleInstructionEnded()
{
var args = new InstructieAfgelopenArgs
{
SportersKlaar = _instructieGroep.SportersVerlatenRij(5),
SportersNieuw = _wachtrijInstrucie.SportersVerlatenRij(5)
};
InstructieAfgelopen?.Invoke(args);
}
private void HandleChangeLines()
{
_waterskibaan.VerplaatsKabel();
if (_wachtrijStarten.GetAlleSporters().Count > 0 && _waterskibaan.Kabel.IsStartPositieLeeg() != false)
{
var athlete = _wachtrijStarten.SportersVerlatenRij(1)[0];
var random = new Random();
athlete.Skies = new Skies();
athlete.Zwemvest = new Zwemvest();
_waterskibaan.SporterStart(athlete);
foreach (var line in _waterskibaan.Kabel.Lijnen)
{
line.Sporter.HuidigeMove = random.Next(0, 100) <= 25 ? line.Sporter.Moves[random.Next(0, line.Sporter.Moves.Count)] : null;
line.Sporter.Score += line.Sporter.HuidigeMove?.Move() ?? 0;
}
var args = new LijnenVerplaatsArgs
{
Sporter = athlete,
Lijnen = _waterskibaan.Kabel.Lijnen
};
LijnenVerplaats?.Invoke(args);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace transport.Models.ApplicationModels
{
public class Kontrahent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdKontrahent { get; set; }
[Display(Name = "Nazwa firmy")]
public string Nazwa { get; set; }
public string NIP { get; set; }
public string Regon { get; set; }
[Display(Name = "Właściciel")]
public string Wlasciciel { get; set; }
public string Ulica { get; set; }
[DataType(DataType.PostalCode)]
[Display(Name = "Kod pocztowy")]
public string Kod { get; set; }
public string Miasto { get; set; }
[DataType(DataType.PhoneNumber)]
[Display(Name = "Numer telefonu")]
public string Telefon { get; set; }
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string EMail { get; set; }
public string Typ { get; set; }
public bool Aktywny { get; set; }
public List<Zlecenie> Zlecenie { get; set; }
public int IdFirma { get; set; }
[ForeignKey("IdFirma")]
public virtual Firma Firma { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActivateScope : MonoBehaviour {
public Animator animator;
// Update is called once per frame
void Update () {
GetComponent<Canvas> ().enabled = animator.GetBool ("Scope");
}
}
|
using System;
using System.Threading.Tasks;
using CRUD_Razor_2_1.Models;
using CRUD_Razor_2_1.Pages.BookList;
using Microsoft.EntityFrameworkCore;
//using Microsoft.EntityFrameworkCore.
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
using System.Collections.Generic;
namespace CRUD_Tests.Pages.BookList
{
public class IndexTest
{
[Fact]
public void Index_Init_BooksNull()
{
// Arrange
var builder = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "InMemoryDb_Index");
var mockAppDbContext = new ApplicationDbContext(builder.Options);
// Act
var pageModel = new IndexModel(mockAppDbContext);
// Assert
Assert.Null(pageModel.Books);
}
[Fact]
public async void Index_OnGet_BooksShouldSet()
{
// Arrange
var builder = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "InMemoryDb_Index");
var mockAppDbContext = new ApplicationDbContext(builder.Options);
Seed(mockAppDbContext);
var pageModel = new IndexModel(mockAppDbContext);
// Act
await pageModel.OnGet();
// Assert
var actualMessages = Assert.IsAssignableFrom<List<Book>>(pageModel.Books);
Assert.Equal(3, actualMessages.Count);
await Teardown(mockAppDbContext);
}
[Fact]
public async void Index_OnPostDelete_BookGetsDeleted()
{
// Arrange
var builder = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: "InMemoryDb_Index");
var mockAppDbContext = new ApplicationDbContext(builder.Options);
Seed(mockAppDbContext);
var pageModel = new IndexModel(mockAppDbContext);
// Act
var deleteBooks = await mockAppDbContext.Books.ToListAsync();
await pageModel.OnPostDelete(deleteBooks[1].Id);
var books = await mockAppDbContext.Books.ToListAsync();
// Assert
Assert.Equal(2, books.Count);
Assert.Matches(pageModel.Message, "Book deleted");
await Teardown(mockAppDbContext);
}
// Seed
private void Seed(ApplicationDbContext context)
{
var books = new[]
{
new Book() { Name = "Name", Author = "Author", ISBN = "moo" },
new Book() { Name = "Name", Author = "Author", ISBN = "moo" },
new Book() { Name = "Name", Author = "Author", ISBN = "moo" }
};
context.Books.AddRange(books);
context.SaveChanges();
}
private async Task Teardown(ApplicationDbContext context)
{
var books = await context.Books.ToListAsync();
context.Books.RemoveRange(books);
context.SaveChanges();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Health : MonoBehaviour
{
public float _hp;
public bool _Dead;
private float _maxHP;
private bool _Invincible;
private Rigidbody2D _Rb;
private void Awake()
{
_Rb = GetComponent<Rigidbody2D>();
_maxHP = _hp;
}
private void Update()
{
_hp = Mathf.Clamp(_hp, 0, _maxHP);
if(_hp == 0 && _Dead == false)
{
_Dead = true;
}
}
public void TakeDamage(float damage, AttackTypes type, Vector2 origin)
{
if (_Invincible)
return;
_hp -= damage;
switch (type)
{
case AttackTypes.Projectile:
KnockBack(origin, 30);
StartCoroutine(HealthCooldown(1));
break;
case AttackTypes.Melee:
KnockBack(origin, 100);
StartCoroutine(HealthCooldown(1));
break;
case AttackTypes.Crush:
break;
}
}
private void KnockBack(Vector2 origin, float multiplier)
{
Vector2 force = new Vector2(transform.position.x, transform.position.y) - origin;
_Rb.AddForce(force * multiplier);
}
private IEnumerator HealthCooldown(float time)
{
_Invincible = true;
yield return new WaitForSecondsRealtime(time);
_Invincible = false;
}
}
|
namespace Olive.Web.MVC.ViewModels.Administration
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Olive.Data;
using Olive.Data.Uow;
using System.Windows;
using System.ComponentModel;
using System.Reflection;
public enum IngredientsAdminMode
{
View,
Edit,
Insert,
Update
}
public enum UnitsAdminMode
{
View,
Edit,
Insert,
Update
}
public enum SourcesAdminMode
{
View,
Edit,
Insert,
Update
}
public class AdministrationViewModel : ViewModelBase, IPageViewModel
{
private string testValidation;
public string TestValidation
{
get { return testValidation; }
set { testValidation = value; this.OnPropertyChanged("TestValidation"); }
}
public string Name
{
get { return "Администрация"; }
}
public AdministrationViewModel()
{
this.NewCategory = new Category();
this.EditUpdateDeleteCategory = new Category();
this.hasParentCategory = false;
this.IsEditMode = false;
SwitchIngredientsToMode(IngredientsAdminMode.View);
SwitchUnitsToMode(UnitsAdminMode.View);
SwitchSourcesToMode(SourcesAdminMode.View);
}
#region Categories adminstration
#region Categories fields
private ObservableCollection<Category> categories;
private ObservableCollection<Category> parentCategories;
private bool hasParentCategory;
private Category newCategory;
private Category editUpdateDeleteCategory;
private bool isEditMode;
private bool isNormalMode;
#endregion
public Category NewCategory
{
get
{
return this.newCategory;
}
set
{
this.newCategory = value;
this.OnPropertyChanged("NewCategory");
}
}
public Category EditUpdateDeleteCategory
{
get
{
if (this.editUpdateDeleteCategory == null)
{
this.editUpdateDeleteCategory = new Category();
}
return this.editUpdateDeleteCategory;
}
set
{
this.editUpdateDeleteCategory = value;
this.OnPropertyChanged("EditUpdateDeleteCategory");
}
}
public bool HasParentCategory
{
get
{
return this.hasParentCategory;
}
set
{
this.hasParentCategory = value;
this.OnPropertyChanged("HasParentCategory");
}
}
public bool IsEditMode
{
get
{
return this.isEditMode;
}
set
{
this.isEditMode = value;
this.IsNormalMode = !value;
this.OnPropertyChanged("IsEditMode");
}
}
public bool IsNormalMode
{
get
{
return this.isNormalMode;
}
set
{
this.isNormalMode = value;
this.OnPropertyChanged("IsNormalMode");
}
}
public ObservableCollection<Category> Categories
{
get
{
if (this.categories == null)
{
this.categories = new ObservableCollection<Category>(this.Db.Categories.All().ToList());
}
return this.categories;
}
set
{
this.categories = value;
this.OnPropertyChanged("Categories");
}
}
public ObservableCollection<Category> ParentCategories
{
get
{
if (this.parentCategories == null)
{
this.parentCategories = new ObservableCollection<Category>(this.Db.Categories.AllParentCategories().ToList());
}
return this.parentCategories;
}
set
{
this.parentCategories = value;
this.OnPropertyChanged("ParentCategories");
}
}
private void HandleAddUpdateCategory(object parameter)
{
if (this.IsNormalMode)
{
int result = 0;
try
{
this.Db.Categories.Add(this.NewCategory);
result = this.Db.SaveChanges();
}
catch (Exception)
{
}
if (result != 0)
{
RaiseCategoriesChanged();
HandleCancelCategoryCommand(null);
this.ParentCategories = new ObservableCollection<Category>(this.Db.Categories.AllParentCategories().ToList());
}
}
if (this.IsEditMode)
{
if (this.EditUpdateDeleteCategory.ParentCategoryID == null)
{
this.EditUpdateDeleteCategory.ParentCategoryID = null;
}
int result = 0;
if (!String.IsNullOrEmpty(this.EditUpdateDeleteCategory.Name))
{
this.Db.Categories.Update(this.EditUpdateDeleteCategory);
result = this.Db.SaveChanges();
}
else
{
this.ParentCategories = new ObservableCollection<Category>(this.GetUowDataInstance().Categories.AllParentCategories().ToList());
HandleCancelCategoryCommand(null);
}
if (result != 0)
{
RaiseCategoriesChanged();
HandleCancelCategoryCommand(null);
this.ParentCategories = new ObservableCollection<Category>(this.Db.Categories.AllParentCategories().ToList());
}
}
this.IsEditMode = false;
}
private void HandleEditCategoryCommand(object parameter)
{
this.IsEditMode = true;
if (this.EditUpdateDeleteCategory.ParentCategoryID != null)
{
this.HasParentCategory = true;
}
}
private void HandleDeleteCategoryCommand(object parameter)
{
this.Db.Categories.Delete(this.EditUpdateDeleteCategory);
int result = this.Db.SaveChanges();
if (result != 0)
{
RaiseCategoriesChanged();
HandleCancelCategoryCommand(null);
this.ParentCategories = new ObservableCollection<Category>(this.Db.Categories.AllParentCategories().ToList());
}
}
private void HandleCancelCategoryCommand(object parameter)
{
this.NewCategory = new Category();
this.HasParentCategory = false;
this.IsEditMode = false;
}
public event EventHandler<EventArgs> CategoriesChanged;
private void RaiseCategoriesChanged()
{
if (this.CategoriesChanged != null)
{
this.CategoriesChanged(this, new EventArgs());
}
}
#endregion
#region Ingredients administaration
#region Ingredients fields
private ObservableCollection<Ingredient> ingredients;
private Ingredient ingredientItem;
private bool isViewModeIngredeients;
private bool isInsertModeIngredeients;
private bool isEditModeIngredeients;
private bool isUpdateModeIngredeients;
#endregion
public bool IsViewModeIngredeients
{
get
{
return this.IsViewModeIngredeients;
}
set
{
this.isViewModeIngredeients = value;
this.OnPropertyChanged("IsViewModeIngredeients");
}
}
public bool IsInsertModeIngredeients
{
get
{
return this.isInsertModeIngredeients;
}
set
{
this.isInsertModeIngredeients = value;
this.OnPropertyChanged("IsInsertModeIngredeients");
}
}
public bool IsEditModeIngredeients
{
get
{
return this.isEditModeIngredeients;
}
set
{
this.isEditModeIngredeients = value;
this.OnPropertyChanged("IsEditModeIngredeients");
}
}
public bool IsUpdateModeIngredeients
{
get
{
return this.isUpdateModeIngredeients;
}
set
{
this.isUpdateModeIngredeients = value;
this.OnPropertyChanged("IsUpdateModeIngredeients");
}
}
public Ingredient IngredientItem
{
get
{
if (this.ingredientItem == null)
{
this.ingredientItem = new Ingredient();
}
return this.ingredientItem;
}
set
{
this.ingredientItem = value;
this.OnPropertyChanged("IngredientItem");
}
}
public ObservableCollection<Ingredient> Ingredients
{
get
{
if (this.ingredients == null)
{
this.ingredients = new ObservableCollection<Ingredient>(this.Db.Ingredients.All().OrderBy(x => x.Name).ToList());
}
return this.ingredients;
}
set
{
this.ingredients = value;
this.OnPropertyChanged("Ingredients");
}
}
private void HandleAddIngredientCommand(object parameter)
{
int result = 0;
try
{
this.Db.Ingredients.Add(this.IngredientItem);
result = this.Db.SaveChanges();
}
catch (Exception)
{
}
if (result != 0)
{
HandleCancelIngredientCommand(null);
this.Ingredients = new ObservableCollection<Ingredient>(this.Db.Ingredients.All().OrderBy(x => x.Name).ToList());
}
}
private void HandleEditIngredientCommand(object parameter)
{
this.SwitchIngredientsToMode(IngredientsAdminMode.Update);
}
private void HandleUpdateIngredientCommand(object parameter)
{
int result = 0;
if (!String.IsNullOrEmpty(this.IngredientItem.Name))
{
this.Db.Ingredients.Update(this.IngredientItem);
result = this.Db.SaveChanges();
}
else
{
this.Ingredients = new ObservableCollection<Ingredient>(this.GetUowDataInstance().Ingredients.All().OrderBy(x => x.Name).ToList());
HandleCancelIngredientCommand(null);
}
if (result != 0)
{
HandleCancelIngredientCommand(null);
this.Ingredients = new ObservableCollection<Ingredient>(this.Db.Ingredients.All().OrderBy(x => x.Name).ToList());
}
}
private void HandleDeleteIngredientCommand(object parameter)
{
this.Db.Ingredients.Delete(this.IngredientItem);
int result = this.Db.SaveChanges();
if (result != 0)
{
HandleCancelIngredientCommand(null);
this.Ingredients = new ObservableCollection<Ingredient>(this.Db.Ingredients.All().OrderBy(x => x.Name).ToList());
}
}
private void HandleCancelIngredientCommand(object parameter)
{
SwitchIngredientsToMode(IngredientsAdminMode.View);
this.IngredientItem = new Ingredient();
}
private void SwitchIngredientsToMode(IngredientsAdminMode selectIngredientMode)
{
switch (selectIngredientMode)
{
case IngredientsAdminMode.View:
{
this.IsViewModeIngredeients = true;
this.IsEditModeIngredeients = false;
this.IsInsertModeIngredeients = true;
this.IsUpdateModeIngredeients = false;
break;
}
case IngredientsAdminMode.Edit:
{
this.IsEditModeIngredeients = true;
this.IsViewModeIngredeients = false;
break;
}
case IngredientsAdminMode.Insert:
{
this.IsViewModeIngredeients = false;
this.IsEditModeIngredeients = true;
this.IsInsertModeIngredeients = true;
this.IsUpdateModeIngredeients = false;
break;
}
case IngredientsAdminMode.Update:
{
this.IsViewModeIngredeients = false;
this.IsEditModeIngredeients = true;
this.IsInsertModeIngredeients = false;
this.IsUpdateModeIngredeients = true;
break;
}
}
}
#endregion
#region Units administaration
#region Units fields
private ObservableCollection<Unit> units;
private Unit unitItem;
private bool isViewModeUnits;
private bool isInsertModeUnits;
private bool isEditModeUnits;
private bool isUpdateModeUnits;
#endregion
public bool IsViewModeUnits
{
get
{
return this.IsViewModeUnits;
}
set
{
this.isViewModeUnits = value;
this.OnPropertyChanged("IsViewModeUnits");
}
}
public bool IsInsertModeUnits
{
get
{
return this.isInsertModeUnits;
}
set
{
this.isInsertModeUnits = value;
this.OnPropertyChanged("IsInsertModeUnits");
}
}
public bool IsEditModeUnits
{
get
{
return this.isEditModeUnits;
}
set
{
this.isEditModeUnits = value;
this.OnPropertyChanged("IsEditModeUnits");
}
}
public bool IsUpdateModeUnits
{
get
{
return this.isUpdateModeUnits;
}
set
{
this.isUpdateModeUnits = value;
this.OnPropertyChanged("IsUpdateModeUnits");
}
}
public Unit UnitItem
{
get
{
if (this.unitItem == null)
{
this.unitItem = new Unit();
}
return this.unitItem;
}
set
{
this.unitItem = value;
this.OnPropertyChanged("UnitItem");
}
}
public ObservableCollection<Unit> Units
{
get
{
if (this.units == null)
{
this.units = new ObservableCollection<Unit>(this.Db.Units.All().OrderBy(x => x.UnitName).ToList());
}
return this.units;
}
set
{
this.units = value;
this.OnPropertyChanged("Units");
}
}
private void HandleAddUnitCommand(object parameter)
{
int result = 0;
try
{
this.Db.Units.Add(this.UnitItem);
result = this.Db.SaveChanges();
}
catch (Exception)
{
}
if (result != 0)
{
HandleCancelUnitCommand(null);
this.Units = new ObservableCollection<Unit>(this.Db.Units.All().OrderBy(x => x.UnitName).ToList());
}
}
private void HandleEditUnitCommand(object parameter)
{
this.SwitchUnitsToMode(UnitsAdminMode.Update);
}
private void HandleUpdateUnitCommand(object parameter)
{
int result = 0;
if (!String.IsNullOrEmpty(this.UnitItem.UnitName) || !String.IsNullOrEmpty(this.UnitItem.UnitName))
{
this.Db.Units.Update(this.UnitItem);
result = this.Db.SaveChanges();
}
else
{
this.Units = new ObservableCollection<Unit>(this.GetUowDataInstance().Units.All().OrderBy(x => x.UnitName).ToList());
HandleCancelUnitCommand(null);
}
if (result != 0)
{
HandleCancelUnitCommand(null);
this.Units = new ObservableCollection<Unit>(this.Db.Units.All().OrderBy(x => x.UnitName).ToList());
}
}
private void HandleDeleteUnitCommand(object parameter)
{
this.Db.Units.Delete(this.UnitItem);
int result = this.Db.SaveChanges();
if (result != 0)
{
HandleCancelUnitCommand(null);
this.Units = new ObservableCollection<Unit>(this.Db.Units.All().OrderBy(x => x.UnitName).ToList());
}
}
private void HandleCancelUnitCommand(object parameter)
{
SwitchUnitsToMode(UnitsAdminMode.View);
this.UnitItem = new Unit();
}
private void SwitchUnitsToMode(UnitsAdminMode selectUnitsMode)
{
switch (selectUnitsMode)
{
case UnitsAdminMode.View:
{
this.IsViewModeUnits = true;
this.IsEditModeUnits = false;
this.IsInsertModeUnits = true;
this.IsUpdateModeUnits = false;
break;
}
case UnitsAdminMode.Edit:
{
this.IsEditModeUnits = true;
this.IsViewModeUnits = false;
break;
}
case UnitsAdminMode.Insert:
{
this.IsViewModeUnits = false;
this.IsEditModeUnits = true;
this.IsInsertModeUnits = true;
this.IsUpdateModeUnits = false;
break;
}
case UnitsAdminMode.Update:
{
this.IsViewModeUnits = false;
this.IsEditModeUnits = true;
this.IsInsertModeUnits = false;
this.IsUpdateModeUnits = true;
break;
}
}
}
#endregion
#region Sources administration
#region Sources fields
private ObservableCollection<Source> sources;
private Source sourceItem;
private bool isViewModeSources;
private bool isInsertModeSources;
private bool isEditModeSources;
private bool isUpdateModeSources;
#endregion
public bool IsViewModeSources
{
get
{
return this.IsViewModeSources;
}
set
{
this.isViewModeSources = value;
this.OnPropertyChanged("IsViewModeSources");
}
}
public bool IsInsertModeSources
{
get
{
return this.isInsertModeSources;
}
set
{
this.isInsertModeSources = value;
this.OnPropertyChanged("IsInsertModeSources");
}
}
public bool IsEditModeSources
{
get
{
return this.isEditModeSources;
}
set
{
this.isEditModeSources = value;
this.OnPropertyChanged("IsEditModeSources");
}
}
public bool IsUpdateModeSources
{
get
{
return this.isUpdateModeSources;
}
set
{
this.isUpdateModeSources = value;
this.OnPropertyChanged("IsUpdateModeSources");
}
}
public Source SourceItem
{
get
{
if (this.sourceItem == null)
{
this.sourceItem = new Source();
}
return this.sourceItem;
}
set
{
this.sourceItem = value;
this.OnPropertyChanged("SourceItem");
}
}
public ObservableCollection<Source> Sources
{
get
{
if (this.sources == null)
{
this.sources = new ObservableCollection<Source>(this.Db.Sources.All().OrderBy(x => x.Name).ToList());
}
return this.sources;
}
set
{
this.sources = value;
this.OnPropertyChanged("Sources");
}
}
private string sourceError;
public string SourceError
{
get { return sourceError; }
set { sourceError = value; this.OnPropertyChanged("SourceError"); }
}
private void HandleAddSourceCommand(object parameter)
{
int result = 0;
try
{
this.Db.Sources.Add(this.SourceItem);
result = this.Db.SaveChanges();
}
catch (Exception)
{
}
if (result != 0)
{
HandleCancelSourceCommand(null);
this.Sources = new ObservableCollection<Source>(this.Db.Sources.All().OrderBy(x => x.Name).ToList());
}
}
private bool HandleStopAddSourceCommand(object parameter)
{
bool validateSuccess = true;
if (String.IsNullOrEmpty(this.SourceItem.Name))
{
validateSuccess = false;
}
return validateSuccess;
}
private void HandleEditSourceCommand(object parameter)
{
this.SwitchSourcesToMode(SourcesAdminMode.Update);
}
private void HandleUpdateSourceCommand(object parameter)
{
int result = 0;
if (!String.IsNullOrEmpty(this.SourceItem.Name))
{
this.Db.Sources.Update(this.SourceItem);
result = this.Db.SaveChanges();
}
else
{
this.Sources = new ObservableCollection<Source>(this.GetUowDataInstance().Sources.All().OrderBy(x => x.Name).ToList());
HandleCancelSourceCommand(null);
}
if (result != 0)
{
HandleCancelSourceCommand(null);
this.Sources = new ObservableCollection<Source>(this.Db.Sources.All().OrderBy(x => x.Name).ToList());
}
}
private void HandleDeleteSourceCommand(object parameter)
{
this.Db.Sources.Delete(this.SourceItem);
int result = this.Db.SaveChanges();
if (result != 0)
{
HandleCancelSourceCommand(null);
this.Sources = new ObservableCollection<Source>(this.Db.Sources.All().OrderBy(x => x.Name).ToList());
}
}
private void HandleCancelSourceCommand(object parameter)
{
SwitchSourcesToMode(SourcesAdminMode.View);
this.SourceItem = new Source();
}
private void SwitchSourcesToMode(SourcesAdminMode selectSourcesMode)
{
switch (selectSourcesMode)
{
case SourcesAdminMode.View:
{
this.IsViewModeSources = true;
this.IsEditModeSources = false;
this.IsInsertModeSources = true;
this.IsUpdateModeSources = false;
break;
}
case SourcesAdminMode.Edit:
{
this.IsEditModeSources = true;
this.IsViewModeSources = false;
break;
}
case SourcesAdminMode.Insert:
{
this.IsViewModeSources = false;
this.IsEditModeSources = true;
this.IsInsertModeSources = true;
this.IsUpdateModeSources = false;
break;
}
case SourcesAdminMode.Update:
{
this.IsViewModeSources = false;
this.IsEditModeSources = true;
this.IsInsertModeSources = false;
this.IsUpdateModeSources = true;
break;
}
}
}
#endregion
}
}
|
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace MoviesUpdater
{
static class Program
{
///// <summary>
///// Tests for access to the cache path used by the updater to copy files for updating.
///// </summary>
///// <param name="path">The cache path.</param>
///// <param name="count">The number of times to check for access to the directory.</param>
//private static void CheckCachePath(string path, int count)
//{
// try
// {
// if (count > 10)
// throw new ApplicationException("Unable to update Movies. The update period timed out.");
// if (!Directory.Exists(path))
// Directory.CreateDirectory(path);
// }
// catch (IOException)
// {
// System.Threading.Thread.Sleep(100);
// CheckCachePath(path, count++);
// }
//}
/// <summary>
/// Handles exceptions not caught by the rest of the application.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string logPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (!logPath.EndsWith("\\"))
logPath += "\\";
logPath += "log\\";
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
string logFile = logPath + "movieslog.log";
if (!File.Exists(logPath + logFile))
{
using (TextWriter tw = new StreamWriter(logPath + logFile))
{
tw.WriteLine("Exception in MoviesUpdater:");
tw.WriteLine(GetExceptions((Exception)e.ExceptionObject));
tw.Flush();
tw.Close();
}
}
else
{
using (TextWriter tw = new StreamWriter(logPath + logFile, true))
{
tw.WriteLine("Exception in MoviesUpdater:");
tw.WriteLine(GetExceptions((Exception)e.ExceptionObject));
tw.Flush();
tw.Close();
}
}
MessageBox.Show(@"A fatal exception occurred in Movies.\nPlease check c:\log\movieslog.log for more information.");
}
/// <summary>
/// Gets the DSN (data source name) to use for updating Movies.
/// </summary>
/// <returns>The name of the data source to use.</returns>
private static string GetDSN()
{
string result = "Movie_Rebuild_A";
string machineName = Environment.MachineName;
bool showModalForm = false;
if (machineName.Length > 7)
{
if (machineName.Substring(0, 8).Equals("NBI20429") ||
machineName.Substring(0, 8).Equals("NBI2172T"))
showModalForm = true;
}
else
{
switch (machineName.Substring(0, 7))
{
case "NBI2192":
case "NBI2119":
case "NBI2139":
case "NBIDEV2":
case "NBI2167":
case "NBI2172":
showModalForm = true;
break;
}
}
if (showModalForm)
{
using (DSNForm form = new DSNForm())
{
if (form.ShowDialog() == DialogResult.OK)
result = form.SelectedDSN;
}
}
return result;
}
/// <summary>
/// Gets all exceptions contained in the current exception.
/// </summary>
/// <param name="e">The exception containing the data.</param>
/// <returns>A string representation of the exception.</returns>
private static string GetExceptions(Exception e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(e.Message);
sb.AppendLine(e.StackTrace);
if (e.InnerException != null)
sb.AppendLine(GetExceptions(e.InnerException));
return sb.ToString();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[LoaderOptimization(LoaderOptimization.MultiDomain)]
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
string startupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
AppDomainSetup mainSetup = new AppDomainSetup();
//mainSetup.ApplicationName = "MoviesNew";
mainSetup.ApplicationBase = startupPath;
mainSetup.ShadowCopyFiles = "true";
mainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
//mainSetup.CachePath = @"C:\Windows\Temp\Movies\";
mainSetup.PrivateBinPath = "bin";
//CheckCachePath(mainSetup.CachePath, 1);
//AppDomain.CreateDomain("MoviesNew", AppDomain.CurrentDomain.Evidence, mainSetup);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string dsn = "";// GetDSN();
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
Application.Run(new UpdateForm(dsn));
}
}
} |
namespace MySurveys.Web.Areas.Administration.ViewModels
{
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using AutoMapper;
using Base;
using Models;
using MvcTemplate.Web.Infrastructure.Mapping;
public class SurveyViewModel : AdministrationViewModel, IMapFrom<Survey>, IHaveCustomMappings
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required]
[StringLength(100), MinLength(3)]
[UIHint("CustomString")]
public string Title { get; set; }
[Required]
[Display(Name = "Author")]
[HiddenInput(DisplayValue = false)]
public string AuthorUsername { get; set; }
[HiddenInput(DisplayValue = false)]
public int TotalQuestions { get; set; }
[HiddenInput(DisplayValue = false)]
public int TotalResponses { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
{
configuration.CreateMap<Survey, SurveyViewModel>()
.ForMember(s => s.TotalQuestions, opt => opt.MapFrom(q => q.Questions.Count))
.ForMember(s => s.TotalResponses, opt => opt.MapFrom(q => q.Responses.Count))
.ForMember(s => s.AuthorUsername, opt => opt.MapFrom(u => u.Author.UserName))
.ReverseMap();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class Assignments_Assignment2_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
SqlDataReader reader = null;
SqlConnection connection = connectToDB();
connection.Open();
SqlCommand cmd = new SqlCommand(@"select Distinct Semester_Name, Start_Date from [schedule_db].[semester] order by [schedule_db].[semester].[Start_Date];", connection);
reader = cmd.ExecuteReader();
while (reader.Read())
{
semesterList.Items.Add(new ListItem(String.Format("{0}", reader["Semester_Name"]), String.Format("{0}", reader["Semester_Name"])));
}
reader.Close();
cmd = new SqlCommand("select Department_Abrev, Department_ID from [schedule_db].[department] order by Department_Abrev;", connection);
reader = cmd.ExecuteReader();
while (reader.Read())
{
departmentList.Items.Add(new ListItem(String.Format("{0}", reader["Department_Abrev"]), String.Format("{0}", reader["Department_ID"])));
}
reader.Close();
closeConnectionToDB(connection);
DropDown_SelectedIndexChanged(new object(), new EventArgs());
} catch (Exception error) {
Console.WriteLine(error.Message);
}
}
}
protected SqlConnection connectToDB()
{
String connectionString = "Server=tcp:cpsc4125cad.database.windows.net,1433;Initial Catalog=CPSC4125;Persist Security Info=False;User ID=testUser;Password=password1234!@#$;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
return new SqlConnection(connectionString);
}
protected void closeConnectionToDB(SqlConnection connection)
{
connection.Close();
}
protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataReader reader = null;
SqlConnection connection = connectToDB();
connection.Open();
SqlCommand cmd = new SqlCommand(
@"Select [schedule_db].[department].[Department_Abrev], [schedule_db].[class].[Class_Number], [schedule_db].[class].[Class_Name],
[schedule_db].[class].[Class_Credits], [schedule_db].[class].[Class_Description], [schedule_db].[course].[CRN], [schedule_db].[course].[Section],
[schedule_db].[day].[Days], [schedule_db].[course].[Start_Time], [schedule_db].[course].[End_Time], [schedule_db].[building].[Building_Name],
[schedule_db].[location].[Room_ID], [schedule_db].[person].[First_Name], [schedule_db].[person].[Last_Name], [schedule_db].[semester].[Start_Date], [schedule_db].[semester].[End_Date]
From [schedule_db].[department]
Inner Join [schedule_db].[class] On [schedule_db].[department].[Department_ID] = [schedule_db].[class].[Department_ID]
Inner Join [schedule_db].[course] On [schedule_db].[course].[Class_ID] = [schedule_db].[class].[Class_ID]
Inner Join [schedule_db].[day] On [schedule_db].[day].[Day_ID] = [schedule_db].[course].[Day_ID]
Inner Join [schedule_db].[location] On [schedule_db].[location].[Location_ID] = [schedule_db].[course].[Location_ID]
Inner Join [schedule_db].[building] On [schedule_db].[location].[Building_ID] = [schedule_db].[building].[Buidling_ID]
Inner Join [schedule_db].[person] On [schedule_db].[person].[Person_ID] = [schedule_db].[course].[Instructor_ID]
Inner Join [schedule_db].[semester] On [schedule_db].[semester].[Semester_ID] = [schedule_db].[course].[Semester_ID]
And [schedule_db].[department].[Department_ID] = @Department
And [schedule_db].[semester].[Semester_Name] = @Semester
Order By [schedule_db].[class].[Class_Number]", connection);
SqlParameter departmentParameter = new SqlParameter();
departmentParameter.ParameterName = "@Department";
departmentParameter.Value = departmentList.SelectedValue;
SqlParameter semesterParameter = new SqlParameter();
semesterParameter.ParameterName = "@Semester";
semesterParameter.Value = semesterList.SelectedValue;
cmd.Parameters.Add(departmentParameter);
cmd.Parameters.Add(semesterParameter);
reader = cmd.ExecuteReader();
while (reader.Read())
{
TableRow row1 = new TableRow();
TableHeaderCell row1_cell1 = new TableHeaderCell();
row1_cell1.Text = String.Format("{0}{1}", reader["Department_Abrev"], reader["Class_Number"]);
row1_cell1.ColumnSpan = 7;
row1.Cells.Add(row1_cell1);
resultsTable.Rows.Add(row1);
TableRow row2 = new TableRow();
TableHeaderCell row2_cell1 = new TableHeaderCell();
row2_cell1.Text = String.Format("{0}", reader["Class_Name"]);
row2_cell1.ColumnSpan = 7;
row2.Cells.Add(row2_cell1);
resultsTable.Rows.Add(row2);
TableRow row3 = new TableRow();
TableHeaderCell row3_cell1 = new TableHeaderCell();
row3_cell1.Text = String.Format("Credits: {0}", reader["Class_Credits"]);
row3_cell1.ColumnSpan = 7;
row3.Cells.Add(row3_cell1);
resultsTable.Rows.Add(row3);
TableRow row4 = new TableRow();
TableCell row4_cell1 = new TableCell();
row4_cell1.Text = String.Format("{0}", reader["Class_Description"]);
row4_cell1.ColumnSpan = 7;
row4.Cells.Add(row4_cell1);
resultsTable.Rows.Add(row4);
TableRow row5 = new TableRow();
TableHeaderCell row5_cell1 = new TableHeaderCell();
TableHeaderCell row5_cell2 = new TableHeaderCell();
TableHeaderCell row5_cell3 = new TableHeaderCell();
TableHeaderCell row5_cell4 = new TableHeaderCell();
TableHeaderCell row5_cell5 = new TableHeaderCell();
TableHeaderCell row5_cell6 = new TableHeaderCell();
TableHeaderCell row5_cell7 = new TableHeaderCell();
row5_cell1.Text = "CRN";
row5_cell2.Text = "Section";
row5_cell3.Text = "Day";
row5_cell4.Text = "Time";
row5_cell5.Text = "Location";
row5_cell6.Text = "Instructor";
row5_cell7.Text = "Begin / End Dates";
row5.Cells.Add(row5_cell1);
row5.Cells.Add(row5_cell2);
row5.Cells.Add(row5_cell3);
row5.Cells.Add(row5_cell4);
row5.Cells.Add(row5_cell5);
row5.Cells.Add(row5_cell6);
row5.Cells.Add(row5_cell7);
resultsTable.Rows.Add(row5);
TableRow row6 = new TableRow();
TableCell row6_cell1 = new TableCell();
TableCell row6_cell2 = new TableCell();
TableCell row6_cell3 = new TableCell();
TableCell row6_cell4 = new TableCell();
TableCell row6_cell5 = new TableCell();
TableCell row6_cell6 = new TableCell();
TableCell row6_cell7 = new TableCell();
row6_cell1.Text = String.Format("{0}", reader["CRN"]);
row6_cell2.Text = String.Format("{0}", reader["Section"]);
row6_cell3.Text = String.Format("{0}", reader["Days"]);
row6_cell4.Text = String.Format("{0} - {1}", reader["Start_Time"], reader["End_Time"]);
row6_cell5.Text = String.Format("{0}{1}", reader["Building_Name"], reader["Room_ID"]);
row6_cell6.Text = String.Format("{0}, {1}", reader["Last_Name"], reader["First_Name"]);
row6_cell7.Text = String.Format("{0:d} - {1:d}", reader["Start_Date"], reader["End_Date"]);
row6.Cells.Add(row6_cell1);
row6.Cells.Add(row6_cell2);
row6.Cells.Add(row6_cell3);
row6.Cells.Add(row6_cell4);
row6.Cells.Add(row6_cell5);
row6.Cells.Add(row6_cell6);
row6.Cells.Add(row6_cell7);
row6.CssClass = "margin-bottom-20";
resultsTable.Rows.Add(row6);
TableRow emptyRow = new TableRow();
TableCell emptyCell = new TableCell();
emptyCell.ColumnSpan = 7;
emptyRow.Cells.Add(emptyCell);
resultsTable.Rows.Add(emptyRow);
}
reader.Close();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
public class Actor : MonoBehaviour
{
public Bone[] Bones = new Bone[0];
public bool DrawSkeleton = true;
public bool DrawVelocities = true;
public bool DrawTransforms = true;
public bool TargetRoot = true;
public float BoneSize = 0.035f;
private Color BoneColor = Color.cyan;
private Color JointColor = Color.red;
private void Reset()
{
ExtractSkeleton();
}
private void OnRenderObject()
{
Draw();
}
private void OnDrawGizmos()
{
if (!Application.isPlaying)
OnRenderObject();
}
public void Draw()
{
Draw(BoneColor, JointColor, 1.0f);
}
public void Draw(Color boneColor, Color jointColor, float alpha)
{
UltiDraw.Begin();
if(DrawSkeleton)
{
Action<Bone> recursion = null;
recursion = new Action<Bone>((bone) =>
{
if(bone.Visiable)
{
if (bone.GetParent() != null)
{
UltiDraw.DrawBone
(
bone.GetParent().Transform.position,
Quaternion.FromToRotation(bone.GetParent().Transform.forward, bone.Transform.position - bone.GetParent().Transform.position) * bone.GetParent().Transform.rotation,
12.5f * BoneSize * bone.GetLength(), bone.GetLength(),
boneColor.Transparent(alpha)
);
}
UltiDraw.DrawSphere(
bone.Transform.position,
Quaternion.identity,
3f / 8f * BoneSize,
jointColor.Transparent(alpha)
);
}
for (int i = 0; i < bone.Childs.Length; i++)
recursion(bone.GetChild(i));
});
if (Bones.Length > 0)
recursion(Bones[0]);
}
if (DrawVelocities)
{
for (int i = 0; i < Bones.Length; i++)
{
if (Bones[i].Visiable)
{
UltiDraw.DrawArrow(
Bones[i].Transform.position,
Bones[i].Transform.position + Bones[i].Velocity,
0.25f,
0.025f,
0.2f,
UltiDraw.DarkGreen.Transparent(0.5f)
);
}
}
}
if (DrawTransforms)
{
Action<Bone> recursion = null;
recursion = new Action<Bone>((bone) =>
{
if(bone.Visiable)
{
UltiDraw.DrawTranslateGizmo(bone.Transform.position, bone.Transform.rotation, 0.05f);
for (int i = 0; i < bone.Childs.Length; i++)
recursion(bone.GetChild(i));
}
});
if (Bones.Length > 0)
{
recursion(Bones[0]);
}
}
UltiDraw.End();
}
public Transform GetRoot()
{
return transform;
}
public Transform FindTransform(string name)
{
Transform element = null;
Action<Transform> recursion = null;
recursion = new Action<Transform>((transform) => {
if (transform.name == name)
{
element = transform;
return;
}
for (int i = 0; i < transform.childCount; i++)
{
recursion(transform.GetChild(i));
}
});
recursion(GetRoot());
return element;
}
public void ExtractSkeleton()
{
ArrayExtensions.Clear(ref Bones);
Action<Transform, Bone> recursion = null;
recursion = new Action<Transform, Bone>((transform, parent) => {
Bone bone = new Bone(this, transform, Bones.Length);
ArrayExtensions.Add(ref Bones, bone);
if (parent != null)
{
bone.Parent = parent.Index;
bone.Level = parent.Level + 1;
bone.ComputeLength();
ArrayExtensions.Add(ref parent.Childs, bone.Index);
}
parent = bone;
for (int i = 0; i < transform.childCount; i++)
{
recursion(transform.GetChild(i), parent);
}
});
recursion(GetRoot(), null);
}
public void ExtractSkeleton(Transform[] bones)
{
ArrayExtensions.Clear(ref Bones);
Action<Transform, Bone> recursion = null;
recursion = new Action<Transform, Bone>((transform, parent) => {
if (System.Array.Find(bones, x => x == transform))
{
Bone bone = new Bone(this, transform, Bones.Length);
ArrayExtensions.Add(ref Bones, bone);
if (parent != null)
{
bone.Parent = parent.Index;
bone.ComputeLength();
ArrayExtensions.Add(ref parent.Childs, bone.Index);
}
parent = bone;
}
for (int i = 0; i < transform.childCount; i++)
{
recursion(transform.GetChild(i), parent);
}
});
recursion(GetRoot(), null);
}
public Bone FindBone(string name)
{
return Array.Find(Bones, x => x.Name == name);
}
public Bone FindBoneContains(string name)
{
return System.Array.Find(Bones, x => x.Name.Contains(name));
}
public string[] GetBoneNames()
{
string[] names = new string[Bones.Length];
for(int i = 0; i < Bones.Length; i++)
names[i] = Bones[i].Name;
return names;
}
[Serializable]
public class Bone
{
public Actor Actor;
public Transform Transform;
public Vector3 Velocity;
public string Name;
public int Index;
public int Parent;
public int[] Childs;
public int Level;
public float Length;
public bool Visiable;
public Bone(Actor actor, Transform transform, int index)
{
Actor = actor;
Transform = transform;
Velocity = Vector3.zero;
Name = transform.name;
Index = index;
Parent = -1;
Childs = new int[0];
Level = 0;
Length = 0.0f;
Visiable = true;
}
public string GetName()
{
return Name;
}
public string GetFixedName()
{
char[] space = new char[] { ' ', ':', '_' };
string[] fixedName = Name.Split(space);
return fixedName[fixedName.Length - 1];
}
public Bone GetParent()
{
return Parent == -1 ? null : Actor.Bones[Parent];
}
public Bone GetChild(int index)
{
return index >= Childs.Length ? null : Actor.Bones[Childs[index]];
}
public void SetLength(float value)
{
Length = Mathf.Max(float.MinValue, value);
}
public float GetLength()
{
return Length;
}
public void ComputeLength()
{
Length = GetParent() == null ? 0f : Vector3.Distance(GetParent().Transform.position, Transform.position);
}
public void ApplyLength()
{
if (GetParent() != null)
{
Transform.position = GetParent().Transform.position + Length * (Transform.position - GetParent().Transform.position).normalized;
}
}
public Actor GetActor()
{
return Actor;
}
}
[CustomEditor(typeof(Actor))]
public class ActorEditor : Editor
{
public Actor Target;
private bool Visiable = false;
private bool BoneVisiable = false;
private void Awake()
{
Target = (Actor)target;
}
public override void OnInspectorGUI()
{
Target.DrawSkeleton = EditorGUILayout.Toggle("Draw Skeleton", Target.DrawSkeleton);
Target.DrawVelocities = EditorGUILayout.Toggle("Draw Velocities", Target.DrawVelocities);
Target.DrawTransforms = EditorGUILayout.Toggle("Draw Transforms", Target.DrawTransforms);
Target.TargetRoot = EditorGUILayout.Toggle("Set Root by BVH Data", Target.TargetRoot);
Target.BoneSize = EditorGUILayout.FloatField("Bone Size:", Target.BoneSize);
using (new EditorGUILayout.VerticalScope("Box"))
{
EditorGUILayout.BeginHorizontal();
Visiable = EditorGUILayout.Toggle(Visiable, GUILayout.Width(20.0f));
EditorGUILayout.LabelField("Show All Bone", GUILayout.Width(300.0f));
EditorGUILayout.EndHorizontal();
if(Visiable)
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Enable All"))
{
for (int i = 0; i < Target.Bones.Length; i++)
Target.Bones[i].Visiable = true;
}
if (GUILayout.Button("Disable All"))
{
for (int i = 0; i < Target.Bones.Length; i++)
Target.Bones[i].Visiable = false;
}
EditorGUILayout.EndHorizontal();
for(int i = 0; i < Target.Bones.Length; i++)
{
EditorGUILayout.BeginHorizontal();
BoneVisiable = EditorGUILayout.Toggle(Target.Bones[i].Visiable, GUILayout.Width(20.0f));
if(Target.Bones[i].Visiable != BoneVisiable)
ToggleBoneVisiable(Target.Bones[i]);
for (int j = 0; j < Target.Bones[i].Level; j++)
EditorGUILayout.LabelField("--", GUILayout.Width(15.0f));
EditorGUILayout.LabelField(Target.Bones[i].Name);
EditorGUILayout.EndHorizontal();
}
}
}
}
public void ToggleBoneVisiable(Bone bone)
{
bone.Visiable = BoneVisiable;
for (int i = 0; i < bone.Childs.Length; i++)
{
ToggleBoneVisiable(bone.GetChild(i));
}
}
}
}
|
using System;
using com.Sconit.Entity.BIL;
using com.Sconit.Entity.ORD;
using System.Collections.Generic;
using com.Sconit.Entity.VIEW;
using com.Sconit.Entity.FMS;
namespace com.Sconit.Service
{
public interface IFacilityMgr
{
void CreateFacilityMaster(FacilityMaster facilityMaster);
void GetFacilityControlPoint(string facilityName, string orderNo);
void CreateFacilityOrder(string facilityName);
void GenerateFacilityMaintainPlan();
bool CheckProductLine(string productline);
void GetFacilityParamater(string facilityName, string paramaterName, string name, string traceCode);
void CreateCheckListOrder(CheckListOrderMaster checkListOrderMaster);
void ReleaseCheckListOrder(CheckListOrderMaster checkListOrderMaster);
void StartFacilityOrder(string facilityOrderNo);
void FinishFacilityOrder(FacilityOrderMaster facilityOrderMaster);
}
}
|
namespace TelegramBot
{
/// <summary>
/// Класс хранит токен телеграмм-бота
/// </summary>
public static class BotCredentials
{
public static readonly string BotToken = "Здесь мог бы быть Ваш токен;)";
}
}
|
// -----------------------------------------------------------------------
// <copyright file="ApiStatusCode.cs" company="Andrey Kurdiumov">
// Copyright (c) Andrey Kurdiumov. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Dub.Web.Core
{
/// <summary>
/// Error codes for the operations.
/// </summary>
public enum ApiStatusCode
{
/// <summary>
/// Range for the generic codes.
/// </summary>
RangeGeneric = 0x0,
/// <summary>
/// Range for the account related errors.
/// </summary>
RangeAccount = 0x10000000,
/// <summary>
/// Successful operation.
/// </summary>
Ok = 0,
/// <summary>
/// Generic operation failure.
/// </summary>
OperationFailed = RangeGeneric + 1,
/// <summary>
/// Invalid parameters passed to the operation.
/// </summary>
InvalidArguments = RangeGeneric + 2,
/// <summary>
/// User is locked out.
/// </summary>
AccountLockedOut = RangeAccount + 1,
/// <summary>
/// Additional verification is required.
/// </summary>
AccountRequiresVerification = RangeAccount + 2,
/// <summary>
/// Invalid authorization parameters passed.
/// </summary>
AuthorizationFailure = RangeAccount + 3,
/// <summary>
/// Invalid verification code given.
/// </summary>
InvalidVerificationCode = RangeAccount + 4,
/// <summary>
/// Registration is failed.
/// </summary>
RegistrationFailed = RangeAccount + 5,
/// <summary>
/// Removing associated login from account failed.
/// </summary>
RemoveLoginError = RangeAccount + 6,
/// <summary>
/// Login for this account is disallowed.
/// </summary>
LoginNotAllowedError = RangeAccount + 7,
}
}
|
namespace iRunes.Controllers
{
public class CreateTrackAlbumVewModel
{
public string AlbumId { get; set; }
}
} |
using AurelienRibon.Ui.SyntaxHighlightBox;
using ProgFrog.Interface.Data;
using ProgFrog.Interface.Model;
using ProgFrog.Interface.TaskRunning;
using ProgFrog.Interface.TaskRunning.ResultsChecking;
using ProgFrog.Interface.TaskRunning.Runners;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
namespace ProgFrog.WpfApp.ViewModel
{
public class DoTasksViewModel : ViewModelBase
{
private IProgrammingTaskRepository _taskRepo;
private IResultsChecker _resultsChecker;
private ITaskRunnerProvider _taskRunnerProvider;
private string _taskStatus;
private ProgrammingTask _selectedTask;
private ProgrammingLanguage _programmingLaguage;
// Binding props
public ObservableCollection<ProgrammingTask> ProgrammingTasks { get; set; } = new ObservableCollection<ProgrammingTask>();
public string UserCode { get; set; }
public string TaskStatus
{
get { return _taskStatus; }
set
{
_taskStatus = value;
OnPropertyChanged("TaskStatus");
}
}
public ObservableCollection<ProgrammingLanguage> ProgrammingLanguages { get; set; } = new ObservableCollection<ProgrammingLanguage>();
public IHighlighter CodeHighlighter
{
get
{
return HighlighterManager.Instance.Highlighters["CSharp"];
}
}
public ProgrammingLanguage ProgrammingLanguage
{
get
{
return _programmingLaguage;
}
set
{
_programmingLaguage = value;
OnPropertyChanged("ProgrammingLanguage");
}
}
public ProgrammingTask SelectedTask
{
get { return _selectedTask; }
set
{
_selectedTask = value;
OnPropertyChanged("SelectedTask");
}
}
// ctors
public DoTasksViewModel(ITaskRunnerProvider taskRunnerProvider, IProgrammingTaskRepository taskRepo, IResultsChecker resultsChecker)
{
_taskRepo = taskRepo;
_taskRunnerProvider = taskRunnerProvider;
_resultsChecker = resultsChecker;
}
// actions
public async Task RunSelectedTask()
{
var runner = _taskRunnerProvider.GetRunner(ProgrammingLanguage);
var runTask = runner.Run(SelectedTask, UserCode);
TaskStatus = "Task running";
var runResults = await runTask;
if (!runResults.IsRunError)
{
var checkResults = _resultsChecker.Check(runResults.Results);
if (checkResults.IsSuccessfull)
{
TaskStatus = "OK";
}
else
{
TaskStatus = GetErrorMessage(checkResults.ErrorType);
}
}
else
{
TaskStatus = GetRunErrorMessage(runResults.ErrorType);
}
}
public async void Initialize(object sender, EventArgs e)
{
foreach (var item in _taskRunnerProvider.GetAvailableLanguages())
{
ProgrammingLanguages.Add(item);
}
var tasks = await _taskRepo.GetAll();
foreach (var task in tasks)
{
ProgrammingTasks.Add(task);
}
}
private string GetRunErrorMessage(TaskRunErrorType? errorType)
{
switch (errorType)
{
case TaskRunErrorType.CompilationFailed:
return "Compilation failed";
default:
throw new ApplicationException("Unknown run error type");
}
}
private string GetErrorMessage(ResultFailureType? errorType)
{
switch (errorType)
{
case ResultFailureType.WrongResults:
return "Несовпадение результов с правильными";
case ResultFailureType.RuntimeException:
return "Ошибка времени выполнения";
default:
throw new ApplicationException("Unknown failure type");
}
}
}
}
|
using System.Collections.Generic;
using Tomelt.ContentManagement;
using Tomelt.ContentManagement.MetaData;
using Tomelt.ContentManagement.MetaData.Builders;
using Tomelt.ContentManagement.MetaData.Models;
using Tomelt.ContentManagement.ViewModels;
using Tomelt.Layouts.Helpers;
namespace Tomelt.Layouts.Settings {
public class ContentTypeLayoutSettingsHooks : ContentDefinitionEditorEventsBase {
public override IEnumerable<TemplateViewModel> TypeEditor(ContentTypeDefinition definition) {
var model = definition.Settings.GetModel<ContentTypeLayoutSettings>();
yield return DefinitionTemplate(model);
}
public override IEnumerable<TemplateViewModel> TypeEditorUpdate(ContentTypeDefinitionBuilder builder, IUpdateModel updateModel) {
var model = new ContentTypeLayoutSettings();
updateModel.TryUpdateModel(model, "ContentTypeLayoutSettings", null, null);
builder.Placeable(model.Placeable);
yield return DefinitionTemplate(model);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure.Encryption;
using WebGrease.Css.Extensions;
namespace Web.ViewModels.User
{
public class DisplayUserViewModel
{
public DisplayUserViewModel(Domain.Users.User user, IEncryptor encryptor)
{
UserId = user.Id;
Email = user.Email;
DisplayName = user.DisplayName;
Roles = string.Join(", ", user.Roles);
IsActive = user.IsActive;
GravatarHash = encryptor.Md5Encrypt(Email).Trim().ToLower();
AllRoles =
(
from object role in Enum.GetValues(typeof (Domain.Users.Role))
select new RoleViewModel { RoleId = (int)role , RoleName = role.ToString(), IsSelected = user.IsInRole(role.ToString())}
)
.ToList();
}
public int UserId { get; private set; }
public string Email { get; private set; }
public string DisplayName { get; private set; }
public string Roles { get; private set; }
public bool IsActive { get; private set; }
public string GravatarHash { get; private set; }
public List<RoleViewModel> AllRoles { get; private set; }
}
} |
using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security.Infrastructure;
using Ricky.Infrastructure.Core;
using Ricky.Infrastructure.Core.ObjectContainer;
using VnStyle.Services.Business;
using VnStyle.Services.Data.Domain.Memberships;
namespace VnStyle.Web.Infrastructure.Security.Providers
{
/// <summary>
///
/// </summary>
public class ApplicationRefreshTokenProvider : IAuthenticationTokenProvider
{
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public void Create(AuthenticationTokenCreateContext context)
{
var clientid = context.Ticket.Properties.Dictionary["as:client_id"];
if (string.IsNullOrEmpty(clientid))
{
return;
}
var refreshTokenId = Guid.NewGuid().ToString("n");
var userService = EngineContext.Current.Resolve<IUserService>();
var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");
var token = new AspNetRefreshToken()
{
TokenId = CommonHelper.GetHashId(refreshTokenId),
ClientId = clientid,
Subject = context.Ticket.Identity.Name,
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
};
context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
token.ProtectedTicket = context.SerializeTicket();
var result = userService.AddRefreshToken(token);
if (result)
{
context.SetToken(refreshTokenId);
}
}
public Task CreateAsync(AuthenticationTokenCreateContext context)
{
Create(context);
return Task.FromResult<object>(null);
}
public void Receive(AuthenticationTokenReceiveContext context)
{
}
public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
string hashedTokenId = CommonHelper.GetHashId(context.Token);
// using (AuthRepository _repo = new AuthRepository())
{
var userService = EngineContext.Current.Resolve<IUserService>();
var refreshToken = userService.FindRefreshToken(hashedTokenId);
if (refreshToken != null)
{
//Get protectedTicket from refreshToken class
context.DeserializeTicket(refreshToken.ProtectedTicket);
var result = userService.RemoveRefreshToken(hashedTokenId);
}
}
return Task.FromResult<object>(null);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JustRipeFarm.ClassEntity
{
public class BoxStorage
{
private int id;
private int storingJob_id;
private int product_id;
private int box_id;
private double nettWeight;
private int storeroom_id;
private DateTime add_date;
private DateTime best_before;
private DateTime out_date;
private int order_id;
public int Id { get => id; set => id = value; }
public int StoringJob_id { get => storingJob_id; set => storingJob_id = value; }
public int Product_id { get => product_id; set => product_id = value; }
public int Box_id { get => box_id; set => box_id = value; }
public double NettWeight { get => nettWeight; set => nettWeight = value; }
public int Storeroom_id { get => storeroom_id; set => storeroom_id = value; }
public DateTime Add_date { get => add_date; set => add_date = value; }
public DateTime Best_before { get => best_before; set => best_before = value; }
public DateTime Out_date { get => out_date; set => out_date = value; }
public int Order_id { get => order_id; set => order_id = value; }
public BoxStorage()
{
}
public BoxStorage(int storingJob_id, int product_id, int box_id, double nettWeight, int storeroom_id, DateTime add_date, DateTime best_before, DateTime out_date, int order_id)
{
this.StoringJob_id = storingJob_id;
this.Product_id = product_id;
this.Box_id = box_id;
this.NettWeight = nettWeight;
this.Storeroom_id = storeroom_id;
this.Add_date = add_date;
this.Best_before = best_before;
this.Out_date = out_date;
this.Order_id = order_id;
}
}
}
|
using System.Collections.Generic;
using TheMapToScrum.Back.BLL.Interfaces;
using TheMapToScrum.Back.BLL.Mapping;
using TheMapToScrum.Back.DAL.Entities;
using TheMapToScrum.Back.DTO;
using TheMapToScrum.Back.Repositories.Contract;
namespace TheMapToScrum.Back.BLL
{
public class ProductOwnerLogic : IProductOwnerLogic
{
private readonly IProductOwnerRepository _repo;
public ProductOwnerLogic(IProductOwnerRepository repo)
{
_repo = repo;
}
public ProductOwnerDTO Create(ProductOwnerDTO objet)
{
ProductOwner entite = MapProductOwner.ToEntity(objet, true);
ProductOwner resultat = _repo.Create(entite);
ProductOwnerDTO retour = MapProductOwnerDTO.ToDto(resultat);
return retour;
}
public ProductOwnerDTO Update(ProductOwnerDTO objet)
{
ProductOwner entite = MapProductOwner.ToEntity(objet, false);
ProductOwner resultat = _repo.Update(entite);
ProductOwnerDTO retour = MapProductOwnerDTO.ToDto(resultat);
return retour;
}
public List<ProductOwnerDTO> List()
{
List<ProductOwnerDTO> retour = new List<ProductOwnerDTO>();
List<ProductOwner> liste = _repo.GetAll();
retour = MapProductOwnerDTO.ToDto(liste);
return retour;
}
public List<ProductOwnerDTO> ListActive()
{
List<ProductOwnerDTO> retour = new List<ProductOwnerDTO>();
List<ProductOwner> liste = _repo.GetAllActive();
retour = MapProductOwnerDTO.ToDto(liste);
return retour;
}
public ProductOwnerDTO GetById(int Id)
{
ProductOwnerDTO retour = new ProductOwnerDTO();
ProductOwner objet = _repo.Get(Id);
retour = MapProductOwnerDTO.ToDto(objet);
return retour;
}
public bool Delete(int Id)
{
return _repo.Delete(Id);
}
}
}
|
public interface IThirdPartyTransfer {
void PerformThirdPartyTransfer(BankAccount bankAccount,VMThirdPartyTransfer vmThirdPartyTransfer);
} |
using CC.Web.Model.System;
using System;
using System.Collections.Generic;
using System.Text;
namespace CC.Web.Model
{
public class Article : BaseModel
{
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 所属用户主键
/// </summary>
public Guid UserId { get; set; }
/// <summary>
/// 所属用户
/// </summary>
public User User { get; set; }
/// <summary>
/// 点赞数
/// </summary>
public int Support { get; set; }
/// <summary>
/// 踩踏数
/// </summary>
public int Trample { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Vista_Diseno_brearCrumbs_previo : System.Web.UI.UserControl
{
#region Variable
private string sResultado = "";
#endregion
#region Inicio migajas
/// <summary>
/// Método para dibujar brearCrumbs de previo
/// </summary>
/// <param name="datosB"></param>
/// <param name="url"></param>
public void vMigajas(string[] sDatos, string[] sUrl, bool iAplicaHome)
{
//se declaran variables
int iTotal = 0;
string sRes = "<div class='container'>"+
"<div class='row'>" +
"<div class='btn-group btn-breadcrumb' style='padding-bottom: 2%;'>";
/*============================*/
//se valida si aplica home
if (iAplicaHome == true)
{
sRes += "<a href='../../Vista/Inicio/home_previo.aspx' class='btn btn-default'><i class='glyphicon glyphicon-home txt-Azul'></i></a>";
}
//Inicio <strong>│</strong> Contenidos <strong>│</strong> SEGURIDAD EN LA CADENA DE SUMINISTRO
//se valida su el
if (sDatos.Length > 0)
{
iTotal = sDatos.Length;
for (int i = 0; i < sDatos.Length; i++)
{
///VERIFICA SI ES EL ULTIMO REGISTRO PARA ASIGNAR CLASE ACTIVA
if (i == (iTotal - 1))
{
sRes += "<a href='#' class='btn btn-default text-Bread'><b class='txt-Azul'>" + sDatos[i] + " </b><i class='fa fa-check-circle icon_green'></i></a>";
}///ELSE DE QUE ES UNA SECUENCIA ANTERIOR
else
{
sRes += "<a href='#' class='btn btn-default'>" + sDatos[i] + "</a>";
}
}
}
//se cierra div
sRes += "</div>" +
"</div>"+
"</div>";
sResultado = sRes;
}
#endregion
#region PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
//se pintan breadcrumbs
lblBreadCrumbs.Text = sResultado;
}
#endregion
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Models
{
public class RefreshToken
{
public string Token { get; set; } = Guid.NewGuid().ToString();
public DateTime Expires { get; set; }
public string UserAgent { get; set; }
public User User { get; set; }
public string UserId { get; set; }
public bool Expired => Expires.CompareTo(DateTime.Now) < 0;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FluidSimulation : MonoBehaviour
{
public int N = 16;
public int iter = 4;
public Fluid fluid;
public FilterMode filtermode = FilterMode.Point;
public Texture2D tex;
public float viscosity = 0.0002f;
public bool render = false;
public float power = 8;
void Start() {
tex = new Texture2D(N, N, TextureFormat.RGB24, false);
tex.wrapMode = TextureWrapMode.Clamp;
tex.filterMode = filtermode;
fluid = new Fluid(viscosity, N);
RenderFluid ();
}
void RenderFluid() {
var stepsize = 1f / N;//
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
//texture.SetPixel(x, y, Color.red);
//tex.SetPixel(x, y, new Color(fluid.density[IX(x,y)],0f , 0f));
//tex.SetPixel(x, y, new Color(fluid.Vx[IX(x, y)], fluid.Vy[IX(x, y)], fluid.density[IX(x, y)]));
if (render) {
//tex.SetPixel(x, y, new Color( fluid.velocity[x, y].magnitude , fluid.velocity[x, y].magnitude, fluid.velocity[x, y].magnitude));
tex.SetPixel(x, y, new Color( fluid.velocity[x, y].x, -fluid.velocity[x, y].x, Mathf.Abs(fluid.velocity[x, y].y)));
}
else {
tex.SetPixel(x, y, new Color(/*(Vector2. right * fluid.Vx[IX(x, y)] + Vector2.up * fluid.Vy[IX(x, y)]).magnitude*/0, Mathf.Abs(fluid.velocity[x,y].x), Mathf.Abs(fluid.velocity[x, y].y)));
}
}
//tex.SetPixel(13, y, Color.blue);
}
// Apply all SetPixel calls
tex.Apply();
GetComponent<Renderer>().material.mainTexture = tex;
}
Vector3 mouse0 = Vector2.zero;
// Update is called once per frame
void Update() {
var s = Input.mousePosition - mouse0;
s.Normalize();
s *= 10;
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) {
Vector2Int v = Vector2Int.RoundToInt(hit.textureCoord * N);
if (Input.GetKey(KeyCode.Mouse0)) {
fluid.AddVelocity(v.x, v.y, s * power / 8);
}
}
var x = Mathf.Sin(Time.time) * 40;
var y = Mathf.Cos(Time.time) * 40;
//fluid.AddDensity(N / 2, N / 2, 10);
//fluid.AddVelocity(N / 2, N / 2, x, y );
fluid.AddVelocity((int)(N / 1.5), N / 2, -power * Vector2.right);
fluid.AddVelocity((int)(N / 3), N / 2, power * Vector2.right);
//fluid.AddVelocity(N / 4, N / 4, x *-1, y * -1);
if (Input.GetKeyDown(KeyCode.Space)) {
//fluid.AddVelocity(2, 3, 2, 4);
}
tex.filterMode = filtermode;
fluid.FluidStep(Time.deltaTime, iter);
RenderFluid();
mouse0 = Input.mousePosition;
}
private void OnDestroy() {
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
public GameObject goodBall;
public GameObject currentBall;
public GameAction changeBall;
public void SpawnBall()
{
var newBall = Instantiate(goodBall, goodBall.transform.position, goodBall.transform.rotation);
currentBall = newBall;
changeBall.action.Invoke();
}
}
|
namespace rm.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Lapm
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int idLamp { get; set; }
[StringLength(45)]
public string Name { get; set; }
[StringLength(45)]
public string Spectre { get; set; }
public int idRidge { get; set; }
public int? Efficacy { get; set; }
public byte? Toggle { get; set; }
public virtual Ridge Ridge { get; set; }
}
}
|
using FeriaVirtual.Application.Services.Signin.Queries;
namespace Application.Test.Users
{
public class SigninMother
{
public static SigninQuery GetValidSigninQuery() =>
new("user.test", "a55d3ef664c94df0c32f44bc299d3e4180df61e8");
public static SigninQuery GetNullSigninQuery() =>
null;
}
}
|
// File Prologue
// Name: Darren Moody
// CS 1400 Section 005
// Project: CS1400 Project 5
// Date: 10/19/2013
//
// I declare that the following code was written by me or provided
// by the instructor for this project. I understand that copying source
// code from any other source constitutes cheating, and that I will receive
// a zero on this project if I am found in violation of this policy.
// ---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace project05
{
class Shipment
{
private string shipMethod, alaskaHawaii;
private double numItems, lbsWeight, shipCost;
private const double STANDARD_PRICE_ITEM = 3.00, STANDARD_PRICE_LBS = 1.45, STANDARD_AK_HA = 2.50,
EXPRESS_PRICE_ITEM = 4.00, EXPRESS_PRICE_LBS = 2.50, EXPRESS_AK_HA = 5.00,
SAMEDAY_PRICE_ITEM = 5.50, SAMEDAY_PRICE_LBS = 3.00, SAMEDAY_AK_HA = 8.00;
// SalesInvoice()
// Constructor: initializes values to 0
// when a class object is created
public Shipment()
{
numItems = 0;
lbsWeight = 0;
shipCost = 0;
shipMethod = "";
alaskaHawaii = "";
}
// The SetNumItems() method
// Purpose: Sets the "number of items" entered by user
// Parameters: The object generating the event
// and the event arguments
// Returns: None
public void SetNumItems(double items)
{
numItems = items;
}
// The SetLbsWeight() method
// Purpose: Sets the "number of lbs" entered by user
// Parameters: The object generating the event
// and the event arguments
// Returns: None
public void SetLbsWeight(double weight)
{
lbsWeight = weight;
}
// The SetShipMethod() method
// Purpose: Sets the shipping method selected by user
// Parameters: The object generating the event
// and the event arguments
// Returns: None
public void SetShipMethod(string method)
{
shipMethod = method;
}
// The SetAlaHaw() method
// Purpose: Sets the option selected by user for Alaska or Hawaii
// Parameters: The object generating the event
// and the event arguments
// Returns: None
public void SetAlaHaw(string akHa)
{
alaskaHawaii = akHa;
}
// The CalcShipCost() method
// Purpose: Calculates the total shipping cost
// Parameters: The object generating the event
// and the event arguments
// Returns: None
public void CalcShipCost()
{ //PSEUDO-CODE FOR CALCSHIPCOST METHOD
double shipMethPriceItemsLbs = 0, akHaPrice = 0; //declare 2 local doubles shipMethPriceItemsLbs & akHaPrice
if (alaskaHawaii == "Yes" && shipMethod == "Standard") //if Yes and Standard buttons are clicked
{
akHaPrice = STANDARD_AK_HA; //set akHaPrice to STANDARD_AK_HA
}
else if (alaskaHawaii == "Yes" && shipMethod == "Express") //if Yes and Express buttons are clicked
{
akHaPrice = EXPRESS_AK_HA; //set akHaPrice to EXPRESS_AK_HA
}
else if (alaskaHawaii == "Yes" && shipMethod == "Same Day")//if Yes and Same Day buttons are clicked
{
akHaPrice = SAMEDAY_AK_HA; //set akHaPrice to SAMEDAY_AK_HA
}
if (shipMethod == "Standard" && numItems != 0) //if Standard and Category A (numItems != 0) is clicked
{
shipMethPriceItemsLbs = STANDARD_PRICE_ITEM; //set shipMethPriceItemsLbs to STANDARD_PRICE_ITEM
}
else if (shipMethod == "Express" && numItems != 0) //if Standard and Category A (numItems != 0) is clicked
{
shipMethPriceItemsLbs = EXPRESS_PRICE_ITEM; //set shipMethPriceItemsLbs to EXPRESS_PRICE_ITEM
}
else if (shipMethod == "Same Day" && numItems != 0) //if Standard and Category A (numItems != 0) is clicked
{
shipMethPriceItemsLbs = SAMEDAY_PRICE_ITEM; //set shipMethPriceItemsLbs to SAMEDAY_PRICE_ITEM
}
else if (shipMethod == "Standard" && lbsWeight != 0) //if Standard and Category B (lbsWeight != 0) is clicked
{
shipMethPriceItemsLbs = STANDARD_PRICE_LBS; //set shipMethPriceItemsLbs to STANDARD_PRICE_LBS
}
else if (shipMethod == "Express" && lbsWeight != 0) //if Standard and Category B (lbsWeight != 0) is clicked
{
shipMethPriceItemsLbs = EXPRESS_PRICE_LBS; //set shipMethPriceItemsLbs to EXPRESS_PRICE_LBS
}
else if (shipMethod == "Same Day" && lbsWeight != 0) //if Standard and Category B (lbsWeight != 0) is clicked
{
shipMethPriceItemsLbs = SAMEDAY_PRICE_LBS; //set shipMethPriceItemsLbs to SAMEDAY_PRICE_LBS
}
if (numItems != 0) //if Category A (numItems != 0)
{
shipCost = shipMethPriceItemsLbs * numItems + akHaPrice; //Calculate using number of items
}
else if (lbsWeight != 0) //if Category B (lbsWeight != 0)
{
shipCost = shipMethPriceItemsLbs * lbsWeight + akHaPrice;//Calculate using weight in pounds
}
//WORKS!!! :-)
}
// The GetShipCost() method
// Purpose: Returns the total price without tax, netPrice
// Parameters: The object generating the event
// and the event arguments
// Returns: double shipCost
public double GetShipCost()
{
return shipCost;
}
}
}
|
using System.Collections.Generic;
namespace MusicAPI.Models
{
public interface IMusicBrainzModel
{
IEnumerable<MusicBrainzModel.MusicBrainzAlbum> Albums { get; set; }
string Name { get; set; }
IEnumerable<MusicBrainzModel.MusicBrainzWikiDataInfo> Relations { get; set; }
string GetWikiDataQNumber();
string GetWikiPediaTitle();
}
} |
namespace Shimakaze.Toolkit.Csf.Data
{
public static class OverAll
{
public static string GetResource(this string key) => Properties.Resource.ResourceManager.GetString(key);
}
} |
using UnityEngine;
using System.Collections;
public class FruitgameController : MonoBehaviour {
private GameController gc;
public int time;
private bool gameOver;
public GameObject enemies1;
public GameObject enemies2;
public GameObject enemies3;
public GameObject enemies4;
private int enemyTotal1;
private int enemyTotal2;
public int enemiesKilled1;
public int enemiesKilled2;
// Use this for initialization
void Start () {
int enemySelector = Random.Range (0, 4);
if (enemySelector == 0)
enemies1.SetActive (true);
else if (enemySelector == 1)
enemies2.SetActive (true);
else if (enemySelector == 2)
enemies3.SetActive (true);
else
enemies4.SetActive (true);
enemyTotal1 = GameObject.FindGameObjectsWithTag ("Enemies1").Length;
enemyTotal2 = GameObject.FindGameObjectsWithTag ("Enemies2").Length;
gc = GameController.gc;
gc.startGame (time);
gc.timeBeforeTransition = 2;
}
// Update is called once per frame
void Update () {
if (GameObject.FindGameObjectWithTag ("Enemies1") != null) // for hiddenNux: keep track of how many enemies killed
enemiesKilled1 = enemyTotal1 - GameObject.FindGameObjectsWithTag ("Enemies1").Length;
if (GameObject.FindGameObjectWithTag ("Enemies2") != null)
enemiesKilled1 = enemyTotal1 - GameObject.FindGameObjectsWithTag ("Enemies2").Length;
if (GameObject.FindGameObjectWithTag ("Enemies1") == null && !gameOver) { // if there arent any enemies left on your side
gameOver = true; // you win
gc.overrideTimer = true;
gc.gameTime = 0;
enemiesKilled1 = enemyTotal1;
gc.gameOver (1);
}
if (GameObject.FindGameObjectWithTag ("Enemies2") == null && !gameOver) {
gameOver = true;
gc.overrideTimer = true;
gc.gameTime = 0;
enemiesKilled2 = enemyTotal2;
gc.gameOver (2);
}
if (gc.gameTime <= 0 && !gameOver) { // check how many enemies there are left and whoever has less wins
gameOver = true;
if (GameObject.FindGameObjectsWithTag ("Enemies1").Length < GameObject.FindGameObjectsWithTag ("Enemies2").Length)
gc.gameOver (1);
else if (GameObject.FindGameObjectsWithTag ("Enemies1").Length > GameObject.FindGameObjectsWithTag("Enemies2").Length)
gc.gameOver (2);
else
gc.gameOver (0);
}
}
} |
using System;
namespace Sind.Web.Cadastros
{
public partial class Cadastros : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} |
using OpenTK.Graphics.OpenGL;
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace Glib
{
/// <summary>
/// Obsahuje 2D textůru.
/// </summary>
public class Texture2D
{
private int id;
/// <summary>
/// Konstruktor.
/// </summary>
/// <param name="textureID">ID textůry.</param>
public Texture2D(int textureID)
{
id = textureID;
}
/// <summary>
/// ID textůry.
/// </summary>
public int ID
{
get { return id; }
}
/// <summary>
/// Načte textůru.
/// </summary>
/// <param name="filename">Cesta k textůře.</param>
/// <returns>Nová 2D textůra.</returns>
public static Texture2D Load(string filename)
{
if (string.IsNullOrEmpty(filename))
throw new ArgumentException(filename);
int id = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, id);
Bitmap bmp = new Bitmap(filename);
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpData.Width, bmpData.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
bmp.UnlockBits(bmpData);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Nearest);
return new Texture2D(id);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Reflection;
using UnityEditor;
[CustomEditor(typeof(GenerationScript))]
public class GenerationEditor : Editor {
string tag;
public override void OnInspectorGUI() {
DrawDefaultInspector();
GenerationScript generation_script = (GenerationScript)target;
if(GUILayout.Button("New Level"))
{
ClearLog();
generation_script.newLevel();
}
tag = EditorGUILayout.TagField("Tag:", tag);
if(GUILayout.Button("Print all with Tag"))
{
ClearLog();
generation_script.printObjects(tag);
}
if(GUILayout.Button("Generate"))
{
generation_script.Decide();
}
}
public static void ClearLog()
{
var assembly = Assembly.GetAssembly(typeof(UnityEditor.ActiveEditorTracker));
var type = assembly.GetType("UnityEditorInternal.LogEntries");
var method = type.GetMethod("Clear");
method.Invoke(new object(), null);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyCube : MonoBehaviour
{
public float speed = 3f;
public float jumpPower = 5f;
Rigidbody rigidbody;
Vector3 movement;
float horizentalMove;
float verticalMove;
bool isJumping;
private void Awake()
{
rigidbody = GetComponent<Rigidbody>();
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
horizentalMove = Input.GetAxisRaw("Horizontal");
verticalMove = Input.GetAxisRaw("Vertical");
if (Input.GetButtonDown("Jump"))
{
isJumping = true;
}
}
private void FixedUpdate()
{
Run();
Jump();
}
void Run()
{
movement.Set(horizentalMove, 0, verticalMove);
movement = movement.normalized * speed * Time.deltaTime;
rigidbody.MovePosition(transform.position + movement);
}
void Jump()
{
if (!isJumping)
{
return;
}
rigidbody.AddForce(Vector3.up * jumpPower, ForceMode.Impulse);
isJumping = false;
}
}
|
using System;
using UnityEngine;
public class Tank : MonoBehaviour
{
private Transform bodyTransform; //bodyオブジェクトのTransformコンポーネント情報
private Transform tarrotTransform; //tarrotオブジェクトのTransformコンポーネント情報
void Start()
{
bodyTransform = GameObject.Find("Body").GetComponent<Transform>(); //BodyオブジェクトのTransformコンポーネント情報を取得
tarrotTransform = GameObject.Find("Tarrot").GetComponent<Transform>(); //BatteryオブジェクトのTransformコンポーネント情報を取得
}
void Update()
{
this.transform.position += new Vector3(-0.01f, 0, 0); //このスクリプトがアタッチされているオブジェクトのTransform.positionをx軸方向に-0.01ずつ移動する
}
} |
using UnityEngine;
public class Spawner : MonoBehaviour
{
[Header("Configurables")]
[SerializeField]
private string poolObjectToSpawn = string.Empty;
[SerializeField]
private float adjustmentAngle = 0f;
[SerializeField]
private float spawnAreaRange = 3f;
[SerializeField]
private Vector3 spawnAreaOffset = Vector3.zero;
public void Spawn()
{
Vector3 randomPosition = transform.position + (Vector3)(Random.insideUnitCircle * spawnAreaRange);
Spawn(randomPosition + spawnAreaOffset);
}
private void Spawn(Vector3 position)
{
Vector3 rotationDegrees = transform.eulerAngles;
rotationDegrees.z += adjustmentAngle;
Quaternion rotation = Quaternion.Euler(rotationDegrees);
GameObject newObj = PoolManager.Instance.Get(poolObjectToSpawn);
newObj.transform.position = position;
newObj.transform.rotation = rotation;
newObj.SetActive(true);
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position + spawnAreaOffset, spawnAreaRange);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileManager
{
public interface IOperation
{
string Invoker(string action, string filePath);
int GetCommands { get; }
}
}
|
using System;
using System.Collections.Generic;
namespace Zesty.Core.Entities
{
public class Domain
{
public Guid Id { get; set; }
public Guid ParentDomainId { get; set; }
public string Name { get; set; }
public List<Domain> Childs { get; set; }
}
}
|
using ArquiteturaLimpaMVC.Aplicacao.DTOs;
using ArquiteturaLimpaMVC.Aplicacao.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
namespace ArquiteturaLimpaMVC.WebUI.Controllers
{
[Authorize]
public class CategoriasController : Controller
{
private readonly ICategoriaService _categoriaService;
public CategoriasController(ICategoriaService categoriaService)
{
_categoriaService = categoriaService;
}
[HttpGet]
public async Task<IActionResult> Index()
{
var categorias = await _categoriaService.TodasCategoriasAsync();
return View(categorias);
}
[HttpGet]
public IActionResult Criar()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Criar(CategoriaDTO categoriaDTO)
{
if (ModelState.IsValid)
{
await _categoriaService.CriarAsync(categoriaDTO);
return RedirectToAction(nameof(Index));
}
return View(categoriaDTO);
}
[HttpGet]
public async Task<IActionResult> Editar(int? id)
{
if (id is null) return NotFound();
var categoriaDTO = await _categoriaService.CategoriaPorIdAsync(id);
if (categoriaDTO is null) return NotFound();
return View(categoriaDTO);
}
[HttpPost]
public async Task<IActionResult> Editar(CategoriaDTO categoriaDTO)
{
if (ModelState.IsValid)
{
await _categoriaService.AtualizarAsync(categoriaDTO);
return RedirectToAction(nameof(Index));
}
return View(categoriaDTO);
}
[HttpGet]
public async Task<IActionResult> Remover(int? id)
{
if (id is null) return NotFound();
var categoriaDTO = await _categoriaService.CategoriaPorIdAsync(id);
if (categoriaDTO is null) return NotFound();
return View(categoriaDTO);
}
[HttpPost(), ActionName(nameof(Remover))]
public async Task<IActionResult> ConfirmarRemocao(int? id)
{
await _categoriaService.RemoverAsync(id);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> Detalhes(int? id)
{
if (id is null) return NotFound();
var categoriaDTO = await _categoriaService.CategoriaPorIdAsync(id);
if (categoriaDTO is null) return NotFound();
return View(categoriaDTO);
}
}
} |
namespace Calculator
{
partial class ArithmeticParser
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HomeWorkOOP3_2
{
class Program
{
static void Main(string[] args)
{
Ship ship = new Ship(100, 10, "1999") {Port="NSK",People=20};
Console.Write("price:{0} speed:{1} year:{2} port:{3} people:{4}",ship.Price,ship.Speed,ship.ReleaseYear,ship.Port,ship.People);
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using Uintra.Core.Feed.Models;
namespace Uintra.Features.CentralFeed
{
public class CentralFeedItemComparer : IComparer<IFeedItem>
{
private readonly DateTime _currentDate;
public CentralFeedItemComparer()
{
_currentDate = DateTime.UtcNow;
}
public int Compare(IFeedItem x, IFeedItem y)
{
if (IsCurrent(x) && IsCurrent(y))
{
return DateTime.Compare(y.PublishDate, x.PublishDate);
}
if (IsFuture(x) && IsFuture(y))
{
return DateTime.Compare(x.PublishDate, y.PublishDate);
}
if (IsPast(x) && IsPast(y))
{
return DateTime.Compare(y.PublishDate, x.PublishDate);
}
if (IsCurrent(x) && IsFuture(y) || IsCurrent(x) && IsPast(y))
{
return -1;
}
if (IsFuture(x) && IsPast(y))
{
return -1;
}
if (IsFuture(x) && IsCurrent(y))
{
return 1;
}
if (IsPast(x) && IsCurrent(y) || IsPast(x) && IsFuture(y))
{
return 1;
}
return DateTime.Compare(x.PublishDate, y.PublishDate);
}
private bool IsFuture(IFeedItem item)
{
return item.PublishDate.Date > _currentDate.Date;
}
private bool IsCurrent(IFeedItem item)
{
return item.PublishDate.Date == _currentDate.Date;
}
private bool IsPast(IFeedItem item)
{
return item.PublishDate.Date < _currentDate.Date;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SampleGameManager : MonoBehaviour
{
public static SampleGameManager instance;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else
{
Debug.LogWarning("SampleGameManager 2개");
Destroy(gameObject);
}
currentCoinList = new List<GameObject>();
}
// 코인 리스폰
void Start()
{
}
public List<GameObject> currentCoinList;
public GameObject[] coins;
public float maxDelayTime;
public GameObject spawnRangeObject;
IEnumerator CoinSpawn_Coroutine() // 코인 반복 소환 코루틴
{
while (true)
{
// 리스폰 대기 시간
// 코인 랜덤 소환 및 스폰
int randomIndex = Random.Range(0, coins.Length);
Instantiate(coins[randomIndex], Return_CoinPosition(), Quaternion.identity);
}
}
Vector3 Return_CoinPosition()
{
float range_X = spawnRangeObject.GetComponent<BoxCollider2D>().bounds.size.x;
float range_Y = spawnRangeObject.GetComponent<BoxCollider2D>().bounds.size.y;
range_X = Random.Range(range_X / 2 * -1, range_X / 2);
range_Y = Random.Range(range_Y / 2 * -1, range_Y / 2);
Vector3 respawnPosition = new Vector3(range_X, range_Y, 0);
return respawnPosition;
}
// 게임 오버 및 재시작
private void Update()
{
if(currentCoinList.Count >= 10) GameOver();
// 재시작
}
public GameObject gameOverText;
public Text gameOverScoreText;
public bool isDead = false;
void GameOver()
{
Show_GameOverUI(); // 게임오버 UI 키기
}
void ReStart()
{
SceneManager.LoadScene(2);
}
// UI 업데이트
public int gameScore;
public Text scoreText;
public void UpdateScoreText()
{
scoreText.text = "점수 : " + gameScore;
}
public Text coinCountText;
public void UpdateCoinCountText()
{
coinCountText.text = "현재 코인 수 : " + currentCoinList.Count;
}
void Show_GameOverUI()
{
gameOverText.SetActive(true);
gameOverScoreText.text = "최종 점수 : " + gameScore;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dontebot
{
class Program
{
static void Main(string[] args)
{
MinunBotti bot = new MinunBotti();
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class VisualToken : MonoBehaviour
{
[SerializeField] Sprite[] typeSprites;
Token sourceToken;
System.Action<VisualToken> onClickCallback;
public Token Source { get => sourceToken; }
public void Setup(Token source, System.Action<VisualToken> onClickDelegate)
{
sourceToken = source;
onClickCallback = onClickDelegate;
GetComponent<SpriteRenderer>().sprite = typeSprites[(int)source.Type];
}
private void OnMouseDown()
{
onClickCallback.Invoke(this);
}
private void OnMouseEnter()
{
//Debug.Log("Hovering: " + Source.Type);
//Enable description;
}
private void OnMouseExit()
{
//Disable description;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ISE.UILibrary;
using ISE.SM.Client.Common.Presenter;
using ISE.Framework.Utility.Utils;
using ISE.SM.Common.DTO;
using ISE.ClassLibrary;
namespace ISE.SM.Client.UCEntry
{
public partial class UCGroupEntry : IUserControl
{
TransMode tmode;
public SecurityGroupDto NewGroup { get; set; }
public DialogResult DialogResult { get; set; }
public UCGroupEntry(TransMode tmode,SecurityGroupDto group)
{
this.tmode = tmode;
DialogResult = System.Windows.Forms.DialogResult.None;
InitializeComponent();
LoadAppDomains();
if (tmode == TransMode.EditRecord || tmode == TransMode.ViewRecord)
{
NewGroup = group;
this.txtDisplayName.Text = group.DisplayName;
this.txtGroupName.Text = group.GroupName;
this.chkEnabled.Checked = group.IsEnabled;
if(group.AppDomainId!=null)
this.cmbDomain.SelectedValue = group.AppDomainId;
else
{
this.cmbDomain.SelectedIndex = -1;
}
if (tmode == TransMode.ViewRecord)
{
this.txtDisplayName.ReadOnly = true;
this.txtGroupName.ReadOnly = true;
this.chkEnabled.Enabled = false;
this.cmbDomain.Enabled = false;
}
}
}
public UCGroupEntry()
{
this.tmode = TransMode.NewRecord;
DialogResult = System.Windows.Forms.DialogResult.None;
InitializeComponent();
LoadAppDomains();
}
public void LoadAppDomains()
{
AppDomainPresenter appDomainPresenter = new AppDomainPresenter();
var lst = appDomainPresenter.GetAppDomainList();
cmbDomain.DataSource = lst;
cmbDomain.DisplayMember = AssemblyReflector.GetMemberName((ApplicationDomainDto m) => m.Title);
cmbDomain.ValueMember = AssemblyReflector.GetMemberName((ApplicationDomainDto m) => m.ApplicationDomainId);
}
private void iTransToolBar1_SaveRecord(object sender, EventArgs e)
{
short enabled = 0;
if (chkEnabled.Checked)
{
enabled = 1;
}
if (tmode == TransMode.NewRecord)
{
SecurityGroupDto group = new SecurityGroupDto()
{
DisplayName = txtDisplayName.Text,
Enabled = enabled,
GroupName = txtGroupName.Text,
};
if (this.cmbDomain.SelectedValue != null)
{
group.AppDomainId = (int)this.cmbDomain.SelectedValue;
}
NewGroup = group;
}
else if (tmode == TransMode.EditRecord)
{
if (NewGroup != null)
{
if (this.cmbDomain.SelectedValue != null)
{
NewGroup.AppDomainId = (int)this.cmbDomain.SelectedValue;
}
NewGroup.ApplicationDomainDto = (ApplicationDomainDto) cmbDomain.SelectedItem;
NewGroup.Enabled = enabled;
NewGroup.GroupName = txtGroupName.Text;
NewGroup.DisplayName = txtDisplayName.Text;
}
}
DialogResult = System.Windows.Forms.DialogResult.OK;
this.ParentForm.Close();
}
private void iTransToolBar1_Close(object sender, EventArgs e)
{
this.ParentForm.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BitClassroom.DAL.Models
{
public class Survey
{
public int Id { get; set; }
[Display(Name="Report Title")]
[Required]
public string Title { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm tt}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[ReportDateValidator]
[Required]
[Display(Name="Date Created")]
public DateTime DateCreated { get; set; }
public List<QuestionResponse> Responses { get; set; }
[Display(Name="Current")]
public bool IsActive { get; set; }
}
}
|
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 Core.BIZ;
using Core.DAL;
using System.Globalization;
namespace WinForm.Views
{
public partial class frmCongNoNXB : Form
{
public frmCongNoNXB(Form parent)
{
InitializeComponent();
_frmParent = parent;
}
#region Private Properties
private Form _frmParent;
private NhaXuatBan _currentNXB;
private List<NhaXuatBan> _DMNXB;
private int _startMonth;
private int _startYear;
private int _endMonth;
private int _endYear;
private decimal? _tongTienNo;
private decimal? _tongTienNhap;
private CultureInfo _cultureInfo;
#endregion
#region Form Control Listener
//Khi load form
private void frmCongNoNXB_Load(object sender, EventArgs e)
{
createGridViewColumns();
_startMonth = 1;
_startYear = DateTime.Now.Year;
_endMonth = 12;
_endYear = DateTime.Now.Year;
_cultureInfo = CultureInfo.GetCultureInfo("vi-VN");
//Load combobox tháng và năm
cmbStartMonth.DataSource = new BindingSource(FilterHelper.Monthes, null);
cmbEndMonth.DataSource = new BindingSource(FilterHelper.Monthes, null);
cmbStartMonth.DisplayMember = "Key";
cmbEndMonth.DisplayMember = "Key";
cmbStartMonth.ValueMember = "Value";
cmbEndMonth.ValueMember = "Value";
cmbStartYear.DataSource = new BindingSource(FilterHelper.Years, null);
cmbEndYear.DataSource = new BindingSource(FilterHelper.Years, null);
cmbStartYear.DisplayMember ="Key";
cmbEndYear.DisplayMember = "Key";
cmbStartYear.ValueMember = "Value";
cmbEndYear.ValueMember = "Value";
//Set Tháng năm mặc định
cmbStartMonth.SelectedValue = _startMonth;
cmbStartYear.SelectedValue = _startYear;
cmbEndMonth.SelectedValue = _endMonth;
cmbEndYear.SelectedValue = _endYear;
//Set Event Listener
cmbStartMonth.SelectedIndexChanged += cmbStartMonth_SelectedIndexChanged;
cmbStartYear.SelectedIndexChanged += cmbStartYear_SelectedIndexChanged;
cmbEndMonth.SelectedIndexChanged += cmbEndMonth_SelectedIndexChanged;
cmbEndYear.SelectedIndexChanged += cmbEndYear_SelectedIndexChanged;
loadNXB();
//Set textbox goi y search
txbLoc.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txbLoc.AutoCompleteSource = AutoCompleteSource.CustomSource;
txbLoc.AutoCompleteCustomSource = null;
}
//Khi chọn xem chi tiết
private void btnXemChiTiet_Click(object sender, EventArgs e)
{
frmChiTietCongNoNXB form = new frmChiTietCongNoNXB(this, _currentNXB);
form.ShowDialog(this);
}
//Khi chọn thanh toán
private void btnThanhToan_Click(object sender, EventArgs e)
{
frmThanhToanNXB form = new frmThanhToanNXB(this, _currentNXB);
form.ShowDialog(this);
}
//Khi chọn nút lọc
private void btnLoc_Click(object sender, EventArgs e)
{
}
//Khi chọn nút thoát
private void btnThoat_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Bạn có muốn thoát", "Thông báo", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
this.Close();
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
//Khi chọn thắng bắt đầu
private void cmbStartMonth_SelectedIndexChanged(object sender, EventArgs e)
{
_startMonth = ((KeyValuePair<string, int>)((ComboBox)sender).SelectedItem).Value;
loadNXB();
}
//Khi chọn năm bắt đầu
private void cmbStartYear_SelectedIndexChanged(object sender, EventArgs e)
{
_startYear = ((KeyValuePair<string, int>)((ComboBox)sender).SelectedItem).Value;
loadNXB();
}
//Khi chọn tháng kết thúc
private void cmbEndMonth_SelectedIndexChanged(object sender, EventArgs e)
{
_endMonth = ((KeyValuePair<string, int>)((ComboBox)sender).SelectedItem).Value;
loadNXB();
}
//Khi chọn năm kết thúc
private void cmbEndYear_SelectedIndexChanged(object sender, EventArgs e)
{
_endYear = ((KeyValuePair<string, int>)((ComboBox)sender).SelectedItem).Value;
loadNXB();
}
//Khi nhập từ khóa lọc
private void txbLoc_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 123)
{
txbLoc.Text = txbLoc.Text + "{";
string request = txbLoc.Text;
var pros = NhaXuatBan.searchKeysTheoDoiNo();
AutoCompleteStringCollection source = new AutoCompleteStringCollection();
foreach (var info in pros)
{
source.Add(request + info);
}
txbLoc.AutoCompleteCustomSource = source;
}
}
private void txbLoc_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
gdvDMNXB.DataSource = NhaXuatBanManager.filter(txbLoc.Text, _DMNXB);
}
}
private void gdvDMNXB_SelectionChanged(object sender, EventArgs e)
{
int index = ((DataGridView)sender).CurrentRow.Index;
_currentNXB = (((DataGridView)sender).DataSource as List<NhaXuatBan>)[index];
selectNXB(_currentNXB);
}
#endregion
#region Form Services
public void loadNXB()
{
_DMNXB = NhaXuatBanManager.getAllAlive()
.Where(nxb => nxb.tongTienNoThang(_startMonth, _startYear, _endMonth, _endYear) > 0
&& nxb.tinhTongSoLuongNoTheoThang(_startMonth, _startYear, _endMonth, _endYear) > 0
&& nxb.tongTienNhapThang(_startMonth, _startYear, _endMonth, _endYear) > 0).ToList();
gdvDMNXB.DataSource = _DMNXB;
_tongTienNo = _DMNXB.Sum(nxb => nxb.TongTienNoThang);
_tongTienNhap = _DMNXB.Sum(nxb => nxb.TongTienNhapTheoThang);
lbTongConNo.Text = String.Format(_cultureInfo, "{0:c}", _tongTienNo);
lbTongTienSach.Text = String.Format(_cultureInfo, "{0:c}", _tongTienNhap);
lbTongDaChi.Text = String.Format(_cultureInfo, "{0:c}", _tongTienNhap - _tongTienNo);
}
public void loadNXB(List<NhaXuatBan> DMNXB)
{
_DMNXB = DMNXB.Where(nxb => nxb.tongTienNoThang(_startMonth, _startYear, _endMonth, _endYear) > 0
&& nxb.tinhTongSoLuongNoTheoThang(_startMonth, _startYear, _endMonth, _endYear) > 0
&& nxb.tongTienNhapThang(_startMonth, _startYear, _endMonth, _endYear) > 0).ToList();
gdvDMNXB.DataSource = _DMNXB;
_tongTienNo = _DMNXB.Sum(nxb => nxb.TongTienNoThang);
_tongTienNhap = _DMNXB.Sum(nxb => nxb.TongTienNhapTheoThang);
lbTongConNo.Text = String.Format(_cultureInfo, "{0:c}", _tongTienNo);
lbTongTienSach.Text = String.Format(_cultureInfo, "{0:c}", _tongTienNhap);
lbTongDaChi.Text = String.Format(_cultureInfo, "{0:c}", _tongTienNhap - _tongTienNo);
}
public void selectNXB(NhaXuatBan nxb)
{
if(nxb != null)
{
lbMaSoNXB.Text = nxb.MaSoNXB.ToString();
lbTenNXB.Text = nxb.TenNXB;
lbTienSachNXB.Text = String.Format(_cultureInfo, "{0:c}", nxb.TongTienNhapTheoThang);
lbConNoNXB.Text = String.Format(_cultureInfo, "{0:c}", nxb.TongTienNoThang);
lbDaChiNXB.Text = String.Format(_cultureInfo, "{0:c}", nxb.TongTienNhapTheoThang - nxb.TongTienNoThang);
}
}
private void createGridViewColumns()
{
gdvDMNXB.AutoGenerateColumns = false; // Bỏ auto generate Columns
gdvDMNXB.ColumnCount = 6; // Xác định số columns có
setColumn(gdvDMNXB.Columns[0]
, nameof(NhaXuatBanManager.Properties.MaSoNXB)
, NhaXuatBanManager.Properties.MaSoNXB);
setColumn(gdvDMNXB.Columns[1]
, nameof(NhaXuatBanManager.Properties.TenNXB)
, NhaXuatBanManager.Properties.TenNXB);
setColumn(gdvDMNXB.Columns[2]
, nameof(NhaXuatBanManager.Properties.DiaChi)
, NhaXuatBanManager.Properties.DiaChi);
setColumn(gdvDMNXB.Columns[3]
, nameof(NhaXuatBanManager.Properties.SoDienThoai)
, NhaXuatBanManager.Properties.SoDienThoai);
setColumn(gdvDMNXB.Columns[4]
, nameof(NhaXuatBanManager.Properties.TongTienNo)
, NhaXuatBanManager.Properties.TongTienNo);
setColumn(gdvDMNXB.Columns[5]
, nameof(NhaXuatBanManager.Properties.TongTienNoThang)
, NhaXuatBanManager.Properties.TongTienNoThang);
}
private void setColumn(DataGridViewColumn column, string propertyName, string name)
{
column.Name = propertyName;
column.DataPropertyName = propertyName;
column.HeaderText = name;
}
#endregion
}
}
|
using MongoDB.Bson.Serialization.Attributes;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities
{
public class Label
{
[BsonId]
public int LabelId { get; set; }
[BsonElement("description")]
public string Description { get; set; }
}
} |
using Business.Abstract;
using Entities.Concreate;
using Microsoft.AspNetCore.Mvc;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
readonly ICustomerService _customerService;
public CustomersController(ICustomerService customerService)
{
_customerService = customerService;
}
[HttpGet("getall")]
public IActionResult GetAll()
{
var result = _customerService.GetlAll();
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
[HttpPost("getbyid")]
public IActionResult GetById(int id)
{
var result = _customerService.GetById(id);
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
[HttpPost("add")]
public IActionResult Add(Customer customer)
{
var result = _customerService.Add(customer);
if (result.Success)
{
return Ok(result.Message);
}
return BadRequest(result.Message);
}
}
}
|
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 WpfApp1
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
LineSegment lineSegment = new LineSegment(new Point(80, 80), true);
private void btnSet_Click(object sender, RoutedEventArgs e)
{
double angle = 0.0;
double.TryParse(txtAngle.Text, out angle);
angle = angle % 360;
if (angle < 0)
{
angle += 360;
}
double radian = angle * Math.PI / 180;//弧度
double r = 40;
points.Segments.Clear();
points.Segments.Add(new LineSegment(new Point(40, 0), true));
if (angle > 0 && angle <= 45)
{
double x = Math.Tan(radian)*r+r;
points.Segments.Add(new LineSegment(new Point(x, 0), true));
}
if (angle > 45 && angle <= 135)
{
points.Segments.Add(new LineSegment(new Point(80, 0), true));
radian = Math.PI / 2 - radian; //弧度
double y = r - r * Math.Tan(radian);
points.Segments.Add(new LineSegment(new Point(80, y), true));
}
if (angle > 135 && angle <= 225)
{
points.Segments.Add(new LineSegment(new Point(80, 0), true));
points.Segments.Add(new LineSegment(new Point(80, 80), true));
radian = Math.PI - radian;
double x = (1 + Math.Tan(radian)) * r;
points.Segments.Add(new LineSegment(new Point(x,80), true));
}
if (angle > 225 && angle <= 315)
{
points.Segments.Add(new LineSegment(new Point(80, 0), true));
points.Segments.Add(new LineSegment(new Point(80, 80), true));
points.Segments.Add(new LineSegment(new Point(0, 80), true));
radian = Math.PI*3/2 - radian;
double y = (1 + Math.Tan(radian)) * r;
points.Segments.Add(new LineSegment(new Point(0, y), true));
}
if (angle > 315)
{
points.Segments.Add(new LineSegment(new Point(80, 0), true));
points.Segments.Add(new LineSegment(new Point(80, 80), true));
points.Segments.Add(new LineSegment(new Point(0, 80), true));
points.Segments.Add(new LineSegment(new Point(0,0), true));
radian = radian-Math.PI*2;
double x = (1 + Math.Tan(radian)) * r;
points.Segments.Add(new LineSegment(new Point(x, 0), true));
}
}
private void txtAngle_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
btnSet_Click(sender, e);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using feedback.Models;
using System.Net.Mail;
namespace feedback
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void OnSaveButtonClicked(object sender, EventArgs e)
{
var comment = new Comment();
comment.FullName = name.Text;
comment.Email = email.Text;
comment.Opinion = opinion.Text;
try
{
await App.Database.SaveCommentAsync(comment);
}
catch(Exception ex)
{
await DisplayAlert("Ошибка",ex.Message.ToString(),"ОК");
}
MailMessage msg = new MailMessage();
msg.To.Add("it@mile.by");
msg.Subject = "Отзыв о работе магазина от " + name.Text;
msg.From = new MailAddress(email.Text);
msg.Body = opinion.Text;
SmtpClient smtp = new SmtpClient("aspmx.l.google.com", 25);
try
{
smtp.Send(msg);
}
catch(Exception ex)
{
await DisplayAlert("Ошибка", ex.Message,"OK");
}
}
private void OnCancelButtonClicked(object sender, EventArgs e)
{
name.Text = "";
email.Text = "";
opinion.Text = "";
}
}
}
|
using System.Collections.Generic;
using Autofac;
using Tests.Pages.ActionID;
using Framework.Core.Common;
using NUnit.Framework;
using Tests.Pages.Oberon.CommunicationCenter;
using OpenQA.Selenium;
namespace Tests.Projects.Oberon.CommunicationCenter
{
public class AddToEmailList : BaseTest
{
private Driver Driver { get { return Scope.Resolve<Driver>(); }}
[Test]
[Category("oberon"), Category("oberon_smoketest"), Category("oberon_comm_center")]
public void AddToEmailListTest()
{
var actionIdLogin = Scope.Resolve<ActionIdLogIn>();
actionIdLogin.LogInTenant();
var emailList = Scope.Resolve<CommunicationCenterEmailLists>();
emailList.GoToThisPageDirectly();
emailList.DeleteAllEmailLists();
emailList.ClickAddLink();
string name = FakeData.RandomLetterString(10);
string publicLabel = FakeData.RandomLetterString(15);
string description = FakeData.RandomLetterString(50);
emailList.CreateEmailList(name, publicLabel, description);
var rows = new List<IWebElement>(emailList.EmailListTable.FindElements(By.TagName("tr")));
while (rows.Count<2)
{
rows = new List<IWebElement>(emailList.EmailListTable.FindElements(By.TagName("tr")));
}
var table = emailList.EmailListTable;
Assert.IsTrue(Driver.FindTextInTable(table, name), name + " found in table");
Assert.IsTrue(Driver.FindTextInTable(table, publicLabel), publicLabel + " found in table");
// deleteing email list
emailList.DeleteEmailList(name);
table = emailList.EmailListTable;
Assert.IsFalse(Driver.FindTextInTable(table, name), name + " not found in table");
Assert.IsFalse(Driver.FindTextInTable(table, publicLabel), publicLabel + " not found in table");
//cleaning out old email lists
emailList.DeleteAllEmailLists();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Integer.Domain.Paroquia;
using System.Web.Mvc;
using Foolproof;
using System.ComponentModel.DataAnnotations;
using Integer.Domain.Agenda;
namespace Integer.Api.Models
{
public class ReservaDeLocalModel
{
[Required(ErrorMessage = "obrigatório")]
public string LocalId { get; set; }
[Required(ErrorMessage = "obrigatório")]
public DateTime? Data { get; set; }
[Required(ErrorMessage = "obrigatório")]
public IList<HoraReservaEnum> Hora { get; set; }
public string DataUtc
{
get
{
if (Data.HasValue)
return Data.Value.ToUniversalTime().ToString();
else
return "";
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControlAvatar : MonoBehaviour {
private bool der = false;
private bool izq = false;
public GameObject objPanel;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void controlDer()
{ }
public void controlIzq()
{ }
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMov : MonoBehaviour
{
public Rigidbody rb;
public KeyCode moveR;
public KeyCode moveL;
public float forward_velociy;
private float side_velocity = 0f ;
private float timeLeft = 0.25f;
// lane is 0 for middle, -1 for left and 1 for right
public int lane = 0;
private bool control_locked = false;
// Update is called once per frame
void Update()
{
rb.velocity = new Vector3(side_velocity, rb.velocity.y, forward_velociy);
// Increasing speed with time
forward_velociy += 0.1f * Time.deltaTime;
forward_velociy = Math.Min(8, forward_velociy);
// making it move with constant speed in forward direction
if (Input.GetKey(moveR) && lane<1 && !control_locked)
{
side_velocity = 5f;
lane += 1;
//rb.transform.Translate(2f, 0, 0);
StartCoroutine(stopSlide());
control_locked = true;
}
if (Input.GetKey(moveL) && lane>-1 && !control_locked)
{
side_velocity = -5f;
lane += -1;
//rb.transform.Translate(-2f, 0, 0);
StartCoroutine(stopSlide());
control_locked = true;
}
}
IEnumerator stopSlide()
{
//rb.transform.Translate(Time.deltaTime * side_velocity, 0, 0);
yield return new WaitForSeconds(0.4f);
side_velocity = 0;
control_locked = false;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class GenericActionOnTriggerScript : MonoBehaviour
{
// public GameObject trailerCamera;
public UnityEvent Actions;
private void OnCollisionEnter(Collision other) {
Actions.Invoke();
}
private void OnTriggerEnter(Collider other) {
Actions.Invoke();
}
}
|
using Ghostpunch.OnlyDown.Common.ViewModels;
using Ghostpunch.OnlyDown.Game.Views;
using Lean;
using UnityEngine;
namespace Ghostpunch.OnlyDown.Game.ViewModels
{
public class PlayerViewModel : ViewModelBase<PlayerView>
{
[Inject]
public PlayerDigSignal PlayerDig { get; set; }
private Transform _transform = null;
public override void OnRegister()
{
base.OnRegister();
_transform = transform;
}
void OnEnable()
{
LeanTouch.OnFingerTap += OnTap;
}
void OnDisable()
{
LeanTouch.OnFingerTap -= OnTap;
}
private void OnTap(LeanFinger obj)
{
PlayerDig.Dispatch(_transform.localPosition);
View._dig.Dispatch();
}
}
}
|
namespace Sentry.Testing;
public sealed class Waiter<T> : IDisposable
{
private readonly TaskCompletionSource<object> _taskCompletionSource = new();
private readonly CancellationTokenSource _cancellationTokenSource = new();
public Waiter(Action<EventHandler<T>> callback)
{
_cancellationTokenSource.Token.Register(() => _taskCompletionSource.SetCanceled());
callback.Invoke((_, _) => _taskCompletionSource.SetResult(null));
}
public async Task WaitAsync(TimeSpan timeout)
{
_cancellationTokenSource.CancelAfter(timeout);
await _taskCompletionSource.Task;
}
public void Dispose()
{
_cancellationTokenSource.Dispose();
}
}
|
using Volo.Abp.Modularity;
namespace powerDg.KMS
{
[DependsOn(
typeof(KMSApplicationModule),
typeof(KMSDomainTestModule)
)]
public class KMSApplicationTestModule : AbpModule
{
}
} |
using UnityEditor;
using UnityAtoms.Editor;
namespace UnityAtoms.BaseAtoms.Editor
{
/// <summary>
/// Variable Inspector of type `bool`. Inherits from `AtomVariableEditor`
/// </summary>
[CustomEditor(typeof(BoolVariable))]
public sealed class BoolVariableEditor : AtomVariableEditor<bool, BoolPair> { }
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HeroCombatManager : MonoBehaviour
{
public float attackSpeed = 2.5f;
public float timeSinceAttacked;
public bool isAttacking;
public bool isShooting;
public bool isCasting;
public bool isDead;
public Vector3 originalPosition;
public float originalX;
public GameObject[] bullets;
public List<GameObject> shootedBullets = new List<GameObject>();
public GameObject blood;
public List<GameObject> effects = new List<GameObject>();
public Material effectMaterial;
public string attackSkill;
void Start()
{
for (int i = 0; i < GetComponent<HeroAttributes>().heroSkills.Count; i++)
{
if (GetComponent<HeroAttributes>().heroSkills[i] == "Melee attack" ||
GetComponent<HeroAttributes>().heroSkills[i] == "Ranged attack" ||
GetComponent<HeroAttributes>().heroSkills[i] == "Magic attack" ||
GetComponent<HeroAttributes>().heroSkills[i].Split('-')[0] == "Heal" ||
GetComponent<HeroAttributes>().heroSkills[i].Split('-')[0] == "Steal" ||
GetComponent<HeroAttributes>().heroSkills[i].Split('-')[0] == "Inspire")
{
attackSkill = GetComponent<HeroAttributes>().heroSkills[i];
}
}
}
void Update ()
{
if (Camera.main.GetComponent<StateKeeper>().inPlay && transform.position.y < -12f && !isDead)
{
if (!Camera.main.GetComponent<CombatManager>().inCombat)
{
if (Camera.main.GetComponent<CombatManager>().partyHeroes.Contains(gameObject))
{
if (GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("walk"))
{
for (int j = -40; j > Camera.main.GetComponent<CombatManager>().lenght - 1; j -= 20)
{
if (transform.position.z > j && transform.position.z <= j + 20)
{
transform.Translate(0f, Time.deltaTime * -5f, 0f);
if (transform.position.z <= j)
{
transform.position = new Vector3(transform.position.x, transform.position.y, j);
GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f));
if (j != Camera.main.GetComponent<CombatManager>().lenght)
{
originalPosition = transform.position;
originalPosition.x = originalX;
}
else
{
Camera.main.GetComponent<CombatManager>().inReward = true;
Camera.main.GetComponent<CombatManager>().effect.GetComponent<SpriteRenderer>().color = new Color(0f, 1f, 0f, 0f);
}
}
}
}
}
}
}
else
{
if (Camera.main.GetComponent<CombatManager>().partyHeroes.Contains(gameObject) || Camera.main.GetComponent<CombatManager>().enemies[0].Contains(gameObject))
{
if (GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("idle") &&
Camera.main.GetComponent<CombatManager>().partyHeroes.Count > 0 && Camera.main.GetComponent<CombatManager>().enemies[0].Count > 0)
{
timeSinceAttacked += Time.deltaTime * attackSpeed;
if (timeSinceAttacked > 25f / GetComponent<HeroAttributes>().heroSpeed)
{
if (attackSkill == "Melee attack" || attackSkill.Split('-')[0] == "Steal")
{
isAttacking = true;
GetComponent<Animator>().Play("walk", -1, Random.Range(0f, 1f));
}
if (attackSkill == "Ranged attack")
{
isShooting = true;
GetComponent<Animator>().Play("shoot", -1, 0f);
shootedBullets.Add(Instantiate(bullets[1]));
shootedBullets[shootedBullets.Count - 1].transform.position = transform.GetChild(0).GetChild(2).position;
shootedBullets[shootedBullets.Count - 1].transform.rotation = Quaternion.Euler(90f * GetAlignment(gameObject), 0f, 0f);
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().shooter = gameObject;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().target = Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.GetChild(0).GetChild(0).gameObject;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().damage = Mathf.Max(0, GetComponent<HeroAttributes>().heroDexterity - Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroReaction);
}
if (attackSkill == "Magic attack")
{
isShooting = true;
GetComponent<Animator>().Play("shoot", -1, 0f);
shootedBullets.Add(Instantiate(bullets[0]));
shootedBullets[shootedBullets.Count - 1].transform.position = transform.GetChild(0).GetChild(2).position;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().shooter = gameObject;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().target = Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.GetChild(0).GetChild(0).gameObject;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().damage = Mathf.Max(0, GetComponent<HeroAttributes>().heroMagic - Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroMagicResist);
shootedBullets[shootedBullets.Count - 1].GetComponent<Renderer>().material.color = GetComponent<HeroAttributes>().heroClothesColor;
shootedBullets[shootedBullets.Count - 1].transform.GetChild(0).GetComponent<Light>().color = GetComponent<HeroAttributes>().heroClothesColor;
}
if (attackSkill.Split('-')[0] == "Heal" || attackSkill.Split('-')[0] == "Inspire")
{
isCasting = true;
GetComponent<Animator>().Play("cast", -1, 0f);
}
}
}
if (GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("shoot"))
{
bool heroIsShooting = false;
for (int i = 0; i < shootedBullets.Count; i++)
{
if (shootedBullets[i] != null)
heroIsShooting = true;
}
if (!heroIsShooting)
{
isShooting = false;
timeSinceAttacked = 0f;
}
if (!isShooting)
GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f));
}
if (GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("cast"))
{
if (attackSkill.Split('-')[0] == "Heal")
{
timeSinceAttacked += Time.deltaTime;
if (effects.Count == 0)
{
if (GetAlignment(gameObject) == 1)
{
effects.Add(new GameObject("heal"));
effects[effects.Count - 1].AddComponent(typeof(ParticleSystem));
effects[effects.Count - 1].transform.SetParent(Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform);
effects[effects.Count - 1].transform.localPosition = new Vector3(0f, 0f, 0f);
effects[effects.Count - 1].transform.rotation = Quaternion.Euler(270f, 0f, 0f);
effects[effects.Count - 1].transform.localScale = new Vector3(1f, 1f, 1f);
effects[effects.Count - 1].GetComponent<ParticleSystem>().startLifetime = 0.5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startSpeed = 5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startColor = GetComponent<HeroAttributes>().heroClothesColor;
SetRendererMaterial(effects[effects.Count - 1].GetComponent<ParticleSystem>());
SetEmissionRate(effects[effects.Count - 1].GetComponent<ParticleSystem>(), 25f);
SetShapeShape(effects[effects.Count - 1].GetComponent<ParticleSystem>(), ParticleSystemShapeType.Box);
}
else
{
effects.Add(new GameObject("heal"));
effects[effects.Count - 1].AddComponent(typeof(ParticleSystem));
effects[effects.Count - 1].transform.SetParent(Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform);
effects[effects.Count - 1].transform.localPosition = new Vector3(0f, 0f, 0f);
effects[effects.Count - 1].transform.rotation = Quaternion.Euler(270f, 0f, 0f);
effects[effects.Count - 1].transform.localScale = new Vector3(1f, 1f, 1f);
effects[effects.Count - 1].GetComponent<ParticleSystem>().startLifetime = 0.5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startSpeed = 5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startColor = GetComponent<HeroAttributes>().heroClothesColor;
SetRendererMaterial(effects[effects.Count - 1].GetComponent<ParticleSystem>());
SetEmissionRate(effects[effects.Count - 1].GetComponent<ParticleSystem>(), 25f);
SetShapeShape(effects[effects.Count - 1].GetComponent<ParticleSystem>(), ParticleSystemShapeType.Box);
}
}
if (timeSinceAttacked > 25f / GetComponent<HeroAttributes>().heroSpeed + 1)
{
Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroHealth += int.Parse(attackSkill.Split('-')[1]);
timeSinceAttacked = 0;
isCasting = false;
GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f));
for (int i = 0; i < effects.Count; i++)
{
Destroy(effects[i]);
effects.RemoveAt(i);
i--;
}
}
}
if (attackSkill.Split('-')[0] == "Group Heal")
{
timeSinceAttacked += Time.deltaTime;
if (effects.Count == 0)
{
if (GetAlignment(gameObject) == 1)
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().partyHeroes.Count; i++)
{
effects.Add(new GameObject("heal"));
effects[effects.Count - 1].AddComponent(typeof(ParticleSystem));
effects[effects.Count - 1].transform.SetParent(Camera.main.GetComponent<CombatManager>().partyHeroes[i].transform);
effects[effects.Count - 1].transform.localPosition = new Vector3(0f, 0f, 0f);
effects[effects.Count - 1].transform.rotation = Quaternion.Euler(270f, 0f, 0f);
effects[effects.Count - 1].transform.localScale = new Vector3(1f, 1f, 1f);
effects[effects.Count - 1].GetComponent<ParticleSystem>().startLifetime = 0.5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startSpeed = 5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startColor = GetComponent<HeroAttributes>().heroClothesColor;
SetRendererMaterial(effects[effects.Count - 1].GetComponent<ParticleSystem>());
SetEmissionRate(effects[effects.Count - 1].GetComponent<ParticleSystem>(), 25f);
SetShapeShape(effects[effects.Count - 1].GetComponent<ParticleSystem>(), ParticleSystemShapeType.Box);
}
}
else
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().enemies[0].Count; i++)
{
effects.Add(new GameObject("heal"));
effects[effects.Count - 1].AddComponent(typeof(ParticleSystem));
effects[effects.Count - 1].transform.SetParent(Camera.main.GetComponent<CombatManager>().enemies[0][i].transform);
effects[effects.Count - 1].transform.localPosition = new Vector3(0f, 0f, 0f);
effects[effects.Count - 1].transform.rotation = Quaternion.Euler(270f, 0f, 0f);
effects[effects.Count - 1].transform.localScale = new Vector3(1f, 1f, 1f);
effects[effects.Count - 1].GetComponent<ParticleSystem>().startLifetime = 0.5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startSpeed = 5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startColor = GetComponent<HeroAttributes>().heroClothesColor;
SetRendererMaterial(effects[effects.Count - 1].GetComponent<ParticleSystem>());
SetEmissionRate(effects[effects.Count - 1].GetComponent<ParticleSystem>(), 25f);
SetShapeShape(effects[effects.Count - 1].GetComponent<ParticleSystem>(), ParticleSystemShapeType.Box);
}
}
}
if (timeSinceAttacked > 25f / GetComponent<HeroAttributes>().heroSpeed + 1)
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().partyHeroes.Count; i++)
{
Camera.main.GetComponent<CombatManager>().partyHeroes[i].GetComponent<HeroAttributes>().heroHealth += int.Parse(attackSkill.Split('-')[1]);
timeSinceAttacked = 0;
isCasting = false;
GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f));
}
for (int i = 0; i < effects.Count; i++)
{
Destroy(effects[i]);
effects.RemoveAt(i);
i--;
}
}
}
if (attackSkill.Split('-')[0] == "Inspire")
{
timeSinceAttacked += Time.deltaTime;
if (effects.Count == 0)
{
if (GetAlignment(gameObject) == 1)
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().partyHeroes.Count; i++)
{
effects.Add(new GameObject("inpiration"));
effects[effects.Count - 1].AddComponent(typeof(ParticleSystem));
effects[effects.Count - 1].transform.SetParent(Camera.main.GetComponent<CombatManager>().partyHeroes[i].transform);
effects[effects.Count - 1].transform.localPosition = new Vector3(0f, 0f, 0f);
effects[effects.Count - 1].transform.rotation = Quaternion.Euler(270f, 0f, 0f);
effects[effects.Count - 1].transform.localScale = new Vector3(1f, 1f, 1f);
effects[effects.Count - 1].GetComponent<ParticleSystem>().startLifetime = 0.5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startSpeed = 5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startColor = GetComponent<HeroAttributes>().heroClothesColor;
SetRendererMaterial(effects[effects.Count - 1].GetComponent<ParticleSystem>());
SetEmissionRate(effects[effects.Count - 1].GetComponent<ParticleSystem>(), 25f);
SetShapeShape(effects[effects.Count - 1].GetComponent<ParticleSystem>(), ParticleSystemShapeType.Box);
}
}
else
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().enemies[0].Count; i++)
{
effects.Add(new GameObject("inpiration"));
effects[effects.Count - 1].AddComponent(typeof(ParticleSystem));
effects[effects.Count - 1].transform.SetParent(Camera.main.GetComponent<CombatManager>().enemies[0][i].transform);
effects[effects.Count - 1].transform.localPosition = new Vector3(0f, 0f, 0f);
effects[effects.Count - 1].transform.rotation = Quaternion.Euler(270f, 0f, 0f);
effects[effects.Count - 1].transform.localScale = new Vector3(1f, 1f, 1f);
effects[effects.Count - 1].GetComponent<ParticleSystem>().startLifetime = 0.5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startSpeed = 5f;
effects[effects.Count - 1].GetComponent<ParticleSystem>().startColor = GetComponent<HeroAttributes>().heroClothesColor;
SetRendererMaterial(effects[effects.Count - 1].GetComponent<ParticleSystem>());
SetEmissionRate(effects[effects.Count - 1].GetComponent<ParticleSystem>(), 25f);
SetShapeShape(effects[effects.Count - 1].GetComponent<ParticleSystem>(), ParticleSystemShapeType.Box);
}
}
}
if (timeSinceAttacked > 25f / GetComponent<HeroAttributes>().heroSpeed + 1)
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().partyHeroes.Count; i++)
{
Camera.main.GetComponent<CombatManager>().partyHeroes[i].GetComponent<HeroAttributes>().heroStrenght += int.Parse(attackSkill.Split('-')[1]);
Camera.main.GetComponent<CombatManager>().partyHeroes[i].GetComponent<HeroAttributes>().heroDexterity += int.Parse(attackSkill.Split('-')[1]);
Camera.main.GetComponent<CombatManager>().partyHeroes[i].GetComponent<HeroAttributes>().heroMagic += int.Parse(attackSkill.Split('-')[1]);
timeSinceAttacked = 0;
isCasting = false;
GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f));
}
for (int i = 0; i < effects.Count; i++)
{
Destroy(effects[i]);
effects.RemoveAt(i);
i--;
}
}
}
}
if (GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("walk"))
{
if (isAttacking &&
Camera.main.GetComponent<CombatManager>().partyHeroes.Count > 0 && Camera.main.GetComponent<CombatManager>().enemies[0].Count > 0)
{
transform.position = Vector3.Lerp(transform.position, Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.position, Time.deltaTime * attackSpeed);
if (Vector3.Distance(transform.position, Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.position) < 1)
{
if (attackSkill.Split('-')[0] == "Steal")
{
isAttacking = false;
isShooting = true;
GetComponent<Animator>().Play("shoot", -1, 0f);
shootedBullets.Add(Instantiate(bullets[0]));
shootedBullets[shootedBullets.Count - 1].transform.position = Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.GetChild(0).GetChild(0).position;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().shooter = gameObject;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().target = Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.GetChild(0).GetChild(0).gameObject;
shootedBullets[shootedBullets.Count - 1].GetComponent<BulletController>().damage = int.Parse(attackSkill.Split('-')[1]);
shootedBullets[shootedBullets.Count - 1].GetComponent<Renderer>().material.color = GetComponent<HeroAttributes>().heroClothesColor;
shootedBullets[shootedBullets.Count - 1].transform.GetChild(0).GetComponent<Light>().color = GetComponent<HeroAttributes>().heroClothesColor;
}
else
{
int damage = 0;
if (attackSkill == "Melee attack")
{
damage = GetComponent<HeroAttributes>().heroStrenght - Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroConstitution;
}
for (int j = 0; j < Mathf.Min(Mathf.Max(0, damage), Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroHealth); j++)
{
GameObject newBlood = Instantiate(blood);
newBlood.transform.position = Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).transform.GetChild(0).GetChild(0).transform.position;
if (Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroRace == "Slime")
newBlood.GetComponent<Renderer>().material.color = Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroSkinColor;
if (Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroRace == "Goblin")
newBlood.GetComponent<Renderer>().material.color = Color.green;
newBlood.GetComponent<Rigidbody>().AddForce(0f, 0f, 100f * GetAlignment(Camera.main.GetComponent<CombatManager>().GetTarget(gameObject)));
}
Camera.main.GetComponent<CombatManager>().GetTarget(gameObject).GetComponent<HeroAttributes>().heroHealth -= Mathf.Max(1, damage);
isAttacking = false;
timeSinceAttacked = 0f;
}
}
}
}
}
if (!isAttacking && !isShooting && !isCasting)
{
for (int i = 0; i < effects.Count; i++)
{
Destroy(effects[i]);
effects.RemoveAt(i);
i--;
}
if (!GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("walk") && Vector3.Distance(transform.position, originalPosition) > 0.1)
{
GetComponent<Animator>().Play("walk", -1, Random.Range(0f, 1f));
}
transform.position = Vector3.Lerp(transform.position, originalPosition, Time.deltaTime * attackSpeed);
if (!GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("idle") && Vector3.Distance(transform.position, originalPosition) <= 0.1)
{
GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f));
}
}
}
}
if (GetComponent<HeroAttributes>().heroHealth <= 0 && !isDead)
{
GetComponent<Animator>().Play("die", -1, 0f);
isAttacking = false;
isShooting = false;
isCasting = false;
isDead = true;
Camera.main.GetComponent<CombatManager>().deadHeroes.Add(gameObject);
if (GetAlignment(gameObject) == 1) Camera.main.GetComponent<CombatManager>().partyHeroes.Remove(gameObject);
else
{
for (int i = 0; i < Camera.main.GetComponent<CombatManager>().enemies.Count; i++)
{
if (Camera.main.GetComponent<CombatManager>().enemies[i].Contains(gameObject)) Camera.main.GetComponent<CombatManager>().enemies[i].Remove(gameObject);
}
}
for (int i = 0; i < effects.Count; i++)
{
Destroy(effects[i]);
effects.RemoveAt(i);
i--;
}
}
}
int GetAlignment(GameObject hero)
{
if (Camera.main.GetComponent<CombatManager>().partyHeroes.Contains(hero)) return 1;
else return -1;
}
void SetEmissionRate(ParticleSystem particleSystem, float rate)
{
ParticleSystem.EmissionModule emission = particleSystem.emission;
ParticleSystem.MinMaxCurve emissionRate = emission.rate;
emissionRate.constantMax = rate;
emission.rate = emissionRate;
}
void SetShapeShape(ParticleSystem particleSystem, ParticleSystemShapeType type)
{
ParticleSystem.ShapeModule shape = particleSystem.shape;
ParticleSystemShapeType shapeType = shape.shapeType;
shapeType = type;
shape.shapeType = shapeType;
}
void SetRendererMaterial(ParticleSystem particleSystem)
{
ParticleSystemRenderer renderer = particleSystem.GetComponent<ParticleSystemRenderer>();
Material material = renderer.material;
material = effectMaterial;
renderer.material = material;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.