text stringlengths 13 6.01M |
|---|
using Report_ClassLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClosedXML.Excel;
using System.Text;
using DocumentFormat.OpenXml.Spreadsheet;
using CrystalDecisions.CrystalReports.Engine;
public partial class BranchExpenses : System.Web.UI.Page
{
ReportDocument rdoc1 = new ReportDocument();
Dictionary<string, bool> UserList = new Dictionary<string, bool>();
string conString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
Dictionary<string, string> permissionList = new Dictionary<string, string>();
List<string> sheetList = new List<string> {"VAN1", "VAN2", "VAN3", "VAN4", "VAN5", "VAN6", "VAN7", "VAN8", "VAN9", "VAN10", "VAN11", "VAN12", "VAN13",
"VAN21", "VAN22", "VAN23", "VAN24",
"VAN90", "VAN91", "VAN92", "VAN93", "VAN94", "VAN95", "VAN96", "VAN97", "VAN98", "VAN99" };
protected void Page_Load(object sender, EventArgs e)
{
if (Session["AllCashReportLogin"] != null)
{
UserList = (Dictionary<string, bool>)Session["AllCashReportLogin"];
if (UserList.First().Value.ToString() == "0")
{
Response.Redirect("~/index.aspx");
}
}
if (Session["AllCashReportLogin"] == null)
{
Response.Redirect("~/index.aspx");
}
if (!IsPostBack)
{
InitPage();
}
var requestTarget = this.Request["__EVENTTARGET"];
if (requestTarget != null && !string.IsNullOrEmpty(requestTarget))
{
if (requestTarget == "upload")
ImportExcel();
}
}
#region Private Methods
private void InitPage()
{
try
{
Dictionary<string, string> docStatusList = new Dictionary<string, string>();
docStatusList.Add("-1", "---ทั้งหมด---");
docStatusList.Add("1", "ศูนย์ส่งมาแล้ว");
docStatusList.Add("0", "ยังไม่ส่งข้อมูล");
ddlDocStatus.BindDropdownList(docStatusList);
ddlDocStatus.SelectedValue = "-1";
Dictionary<string, string> rankingList = new Dictionary<string, string>();
rankingList.Add("1", "Top 10 ค่าน้ำมันต่อวัน");
rankingList.Add("2", "Top 10 ค่าเฉลี่ยน้ำมันต่อวัน");
rankingList.Add("3", "Top 10 ระยะทางต่อวัน");
rankingList.Add("4", "Top 10 ค่าเฉลี่ยระยะทางต่อวัน");
rankingList.Add("5", "เรียงลำดับเอง");
//rankingList.Add("4", "Top 10 ค่าเฉลี่ยนการใช้น้ำมัน");
ddlRankingType.BindDropdownList(rankingList);
ddlRankingType.SelectedValue = "-1";
DataTable _per_dt = new DataTable();
_per_dt = Helper.ExecuteProcedureToTable(conString, "proc_branch_stock_report_get_branch_permission", null);
if (_per_dt != null && _per_dt.Rows.Count > 0)
{
foreach (DataRow item in _per_dt.Rows)
{
permissionList.Add(item["UserName"].ToString(), item["RoleName"].ToString());
}
}
if (permissionList.Count > 0)
{
DataTable _dt1 = new DataTable();
DataTable _dt2 = new DataTable();
Dictionary<string, object> b_prmt = new Dictionary<string, object>();
bool flagUser = false;
var user = permissionList.FirstOrDefault(x => x.Key == UserList.First().Key);
if (user.Value != null)
{
if (user.Value == "adminbranch")
flagUser = true;
}
if (!flagUser)
b_prmt = GetAllBranchFromDB(ref _dt1, ref _dt2);
else
{
string _branchID = user.Key.Substring(1, user.Key.Length - 1);
b_prmt.Add("BranchID", _branchID);
_dt1 = Helper.ExecuteProcedureToTable(conString, "proc_branch_stock_report_get_all_branch", b_prmt);
_dt2 = _dt1.Copy();
}
BindDDLSalesArea(ref _dt1, ref _dt2, ddlBranch, b_prmt);
BindDDLSalesArea(ref _dt1, ref _dt2, ddlBranch_R, b_prmt, true);
BindDDLSalesArea(ref _dt1, ref _dt2, ddlBranch_DT, b_prmt, true);
BindDDLSalesArea(ref _dt1, ref _dt2, ddlBranch_Rank, b_prmt, true);
}
//BindBranchData(ddlBranch);
//BindBranchData(ddlBranch_R, true);
//BindBranchData(ddlBranch_DT, true);
//BindBranchData(ddlBranch_Rank, true);
BindVanData(ddlBranch_DT, ddlVan_DT, true);
PrepareGridData();
}
catch (Exception ex)
{
throw ex;
}
}
private List<string> AddExcelToDB(FileUpload fileUP, string sheetName, string tableName)
{
bool validateEx = true;
string errMsg = "";
List<string> result = new List<string>();
try
{
if (fileUP.HasFile)
{
DateTime cDate = DateTime.Now;
string _transDate = "";
var _dDate = txtTransferDate.Text.Split('/').ToList();
_transDate = string.Join("/", _dDate[1], _dDate[0], _dDate[2]);
string _branchID = ddlBranch.SelectedValue;
string _vanID = "";
//string _vanID = ddlVanID.SelectedValue;
string path = string.Concat(Server.MapPath("~/App_Data/" + fileUP.FileName));
fileUP.SaveAs(path);
if (tableName == "tbl_branch_oil_bill_temp")
{
// Helper.GetExcelSheetNames(fileUP.FileName, path);
DataTable readDT = new DataTable(tableName);
//readDT.Columns.Add("PK", typeof(int));
readDT.Columns.Add("TransferDate", typeof(DateTime));
readDT.Columns.Add("DocDate", typeof(DateTime));
readDT.Columns.Add("BranchID", typeof(string));
readDT.Columns.Add("VanID", typeof(string));
readDT.Columns.Add("Licences", typeof(string));
readDT.Columns.Add("FleetGardNo", typeof(string));
readDT.Columns.Add("DocNo", typeof(string));
readDT.Columns.Add("VATNumber", typeof(string));
readDT.Columns.Add("CarrierName", typeof(string));
readDT.Columns.Add("Establishment", typeof(string));
readDT.Columns.Add("ExcVat", typeof(decimal));
readDT.Columns.Add("VatAmt", typeof(decimal));
readDT.Columns.Add("TotalDue", typeof(decimal));
readDT.Columns.Add("PricePerLiter", typeof(decimal));
readDT.Columns.Add("LiterAmt", typeof(decimal));
readDT.Columns.Add("StartMile", typeof(int));
readDT.Columns.Add("EndMile", typeof(int));
readDT.Columns.Add("MileUsed", typeof(int));
readDT.Columns.Add("AddFuelMileNo", typeof(int));
readDT.Columns.Add("Remarks", typeof(string));
readDT.Columns.Add("UpdateBy", typeof(string));
readDT.Columns.Add("UpdateDate", typeof(DateTime));
foreach (var _sheetName in sheetList)
{
var dataTable = new DataTable();
try
{
dataTable = Helper.ReadExcelToDataTable2(conString, fileUP.FileName, _sheetName);
//Helper.ReadSample(fileUP, path, _sheetName);
}
catch (Exception ex)
{
lblUploadResult.Text = "2) เกิดข้อผิดพลาดในการอัพโหลด excel!" + ex.Message;
lblUploadResult.ForeColor = System.Drawing.Color.Red;
dataTable = null;
}
if (dataTable != null && dataTable.Rows.Count > 0)
{
_vanID = GetVanID(_sheetName); //GetVanID(dataTable.Rows[1][2].ToString());
bool isValid = true;
List<bool> allCheckValid = new List<bool>();
string exMsg = "";
foreach (DataRow row in dataTable.Rows)
{
DateTime _date = new DateTime();
//validate Excel -------------------------------------------------------------------------------------------------------------------------------------------
if (DateTime.TryParse(row[0].ToString(), out _date))
{
DateTime validateDate = Convert.ToDateTime(cDate.ToShortDateString() + " 19:00:00");
var chkD1 = Convert.ToDateTime(cDate.ToShortDateString());
var chkD2 = Convert.ToDateTime(_date.ToShortDateString());
if (chkD1 > chkD2 ||
(chkD1 == chkD2 && cDate >= validateDate))
{
string _licences = row[3].ToString();
string _fleetGardNo = row[4].ToString();
string _docNo = row[5].ToString();
string _vatNumber = row[6].ToString();
string _carrierName = row[7].ToString();
string _establishment = row[8].ToString();
decimal _excVat = ConvertColToDec(row, 9);
decimal _vatAmt = ConvertColToDec(row, 10);
decimal _totalDue = ConvertColToDec(row, 11);
decimal _pricePerLiter = ConvertColToDec(row, 12);
decimal _literAmt = ConvertColToDec(row, 13);
int _startMile = ConvertColToInt(row, 14);
int _endMile = ConvertColToInt(row, 15);
int _mileUsed = ConvertColToInt(row, 16);
int _addFuelMileNo = ConvertColToInt(row, 17);
string _remarks = "";
if (!string.IsNullOrEmpty(row[18].ToString()))
_remarks = row[18].ToString();
string userName = UserList.First().Key;
if (_startMile > _endMile)
{
exMsg += "ข้อมูลแวน " + _vanID + " ของวันที่ " + _date.ToString("dd/MM/yyyy") + " : เลขไมค์เริ่มต้นมากกว่าเลขไมค์สิ้นสุด!" + "\n";
allCheckValid.Add(false);
}
if ((_excVat + _vatAmt) != _totalDue)
{
exMsg += "ข้อมูลแวน " + _vanID + " ของวันที่ " + _date.ToString("dd/MM/yyyy") + " : จำนวนเงินรวม ไม่ถูกต้อง!" + "\n";
allCheckValid.Add(false);
}
if (_mileUsed >= 1000)
{
exMsg += "ข้อมูลแวน " + _vanID + " ของวันที่ " + _date.ToString("dd/MM/yyyy") + " : จำนวนไมล์ใช้งาน ไม่ถูกต้อง!" + "\n";
allCheckValid.Add(false);
}
if (Convert.ToDateTime(_transDate).Month != _date.Month || Convert.ToDateTime(chkD2).Year >= 2100)
{
exMsg += "ข้อมูลแวน " + _vanID + " ของวันที่ " + _date.ToString("dd/MM/yyyy") + " : วันที่เติมน้ำมัน ไม่ถูกต้อง!" + "\n";
allCheckValid.Add(false);
}
readDT.Rows.Add(_transDate, _date, _branchID, _vanID, _licences, _fleetGardNo, _docNo, _vatNumber, _carrierName,
_establishment, _excVat, _vatAmt, _totalDue, _pricePerLiter, _literAmt, _startMile, _endMile, _mileUsed, _addFuelMileNo, _remarks, userName, cDate);
result.Add(_vanID);
}
if (Convert.ToDateTime(chkD2).Year >= 2100)
{
exMsg += "ข้อมูลแวน " + _vanID + " ของวันที่ " + _date.ToString("dd/MM/yyyy") + " : วันที่เติมน้ำมัน ไม่ถูกต้อง!" + "\n";
allCheckValid.Add(false);
}
}
//validate Excel -------------------------------------------------------------------------------------------------------------------------------------------
}
//validate Excel -------------------------------------------------------------------------------------------------------------------------------------------
bool _checkJCols = false;
bool _checkRCols = false;
if (readDT != null && readDT.Rows.Count > 0)
{
foreach (DataRow item in readDT.Rows)
{
decimal _check_excVat = 0;
if (decimal.TryParse(item[10].ToString(), out _check_excVat))
{
if (_check_excVat > 0)
{
_checkJCols = true;
break;
}
}
}
foreach (DataRow item in readDT.Rows)
{
int _check_addFuelMileNo = 0;
if (int.TryParse(item[18].ToString(), out _check_addFuelMileNo))
{
if (_check_addFuelMileNo > 0)
{
_checkRCols = true;
break;
}
}
}
}
if (allCheckValid.All(x => x) && _checkJCols && _checkRCols)
isValid = true;
else
{
if (readDT.AsEnumerable().All(x => x.Field<decimal>("TotalDue") == 0))
{
//Do nothing
}
else
{
exMsg += " กรุณาตรวจสอบ excel อีกครั้ง!!!" + "\n";
isValid = false;
}
}
if (!isValid)
{
errMsg = exMsg;
throw new Exception();
}
//validate Excel -------------------------------------------------------------------------------------------------------------------------------------------
}
}
if (readDT != null && readDT.Rows.Count > 0)
{
SqlBulkCopy bulkInsert = new SqlBulkCopy(conString);
bulkInsert.DestinationTableName = tableName;
bulkInsert.WriteToServer(readDT);
}
}
}
}
catch (Exception ex)
{
if (string.IsNullOrEmpty(errMsg))
lblUploadResult.Text = "2) เกิดข้อผิดพลาดในการอัพโหลด excel!" + ex.Message;
else
lblUploadResult.Text = errMsg;
lblUploadResult.ForeColor = System.Drawing.Color.Red;
result = new List<string>();
}
return result;
}
private decimal ConvertColToDec(DataRow row, int colIndex)
{
decimal ret = 0;
try
{
string colStr = "";
colStr = row[colIndex].ToString();
if (!string.IsNullOrEmpty(colStr) && colStr != "-")
{
decimal _tmp = 0;
if (decimal.TryParse(colStr, out _tmp))
ret = _tmp;
}
}
catch (Exception ex)
{
lblUploadResult.Text = "ข้อมูลใน excel ไม่ถูกต้อง!" + ex.Message;
lblUploadResult.ForeColor = System.Drawing.Color.Red;
}
return ret;
}
private int ConvertColToInt(DataRow row, int colIndex)
{
int ret = 0;
try
{
string colStr = "";
colStr = row[colIndex].ToString();
if (!string.IsNullOrEmpty(colStr) && colStr != "-")
{
int _tmp = 0;
if (int.TryParse(colStr, out _tmp))
ret = _tmp;
}
}
catch (Exception ex)
{
lblUploadResult.Text = "ข้อมูลใน excel ไม่ถูกต้อง!" + ex.Message;
lblUploadResult.ForeColor = System.Drawing.Color.Red;
}
return ret;
}
private void BindDDLSalesArea(ref DataTable _dt, ref DataTable _dt2, DropDownList ddlB, Dictionary<string, object> b_prmt, bool allFlag = false)
{
if (_dt != null && _dt.Rows.Count > 0)
{
if (allFlag)
ddlB.BindDropdownList(_dt2, "BranchName", "BranchID");
else
ddlB.BindDropdownList(_dt, "BranchName", "BranchID");
}
}
private void BindBranchData(DropDownList ddlB, bool allFlag = false)
{
DataTable _dt = new DataTable();
Dictionary<string, object> _prmt = new Dictionary<string, object>();
_prmt.Add("BranchID", "-1");
_dt = Helper.ExecuteProcedureToTable(conString, "proc_branch_stock_report_get_all_branch", _prmt);
if (allFlag)
{
DataTable _dt2 = _dt.Copy();
DataRow _sRow1 = _dt2.NewRow();
_sRow1["BranchID"] = "-1";
_sRow1["BranchName"] = "---สาขาทั้งหมด---";
_dt2.Rows.InsertAt(_sRow1, 0);
if (_dt2 != null && _dt2.Rows.Count > 0)
{
ddlB.BindDropdownList(_dt2, "BranchName", "BranchID");
}
}
else
{
if (_dt != null && _dt.Rows.Count > 0)
{
ddlB.BindDropdownList(_dt, "BranchName", "BranchID");
}
}
}
private void BindVanData(DropDownList ddlB, DropDownList ddlVan, bool allFlag = false)
{
try
{
DataTable _dt = new DataTable();
//Dictionary<string, object> _prmt = new Dictionary<string, object>();
//_prmt.Add("BranchID", ddlB.SelectedValue);
//_dt = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_get_van", _prmt);
_dt = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_get_van_2", null);
if (allFlag)
{
DataTable _dt2 = _dt.Copy();
DataRow _sRow1 = _dt2.NewRow();
_sRow1["van_id"] = "-1";
_sRow1["VanName"] = "---แวนทั้งหมด---";
_dt2.Rows.InsertAt(_sRow1, 0);
ddlVan.BindDropdownList(_dt2, "VanName", "van_id");
}
else
{
if (_dt != null && _dt.Rows.Count > 0)
{
ddlVan.BindDropdownList(_dt, "VanName", "van_id");
}
}
//else
//{
// DataTable _dt2 = new DataTable();
// _dt2.Columns.Add("van_id");
// _dt2.Columns.Add("VanName");
// DataRow _sRow1 = _dt2.NewRow();
// _sRow1["van_id"] = "-1";
// _sRow1["VanName"] = "---แวนทั้งหมด---";
// _dt2.Rows.InsertAt(_sRow1, 0);
// if (_dt2 != null && _dt2.Rows.Count > 0)
// {
// ddlVan.BindDropdownList(_dt2, "VanName", "van_id");
// }
//}
}
catch (Exception ex)
{
throw ex;
}
}
private void BindGridView(GridView grd, DataTable data)
{
try
{
grd.DataSource = data;
grd.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
private void ImportExcel()
{
List<bool> results = new List<bool>();
try
{
if (string.IsNullOrEmpty(FileUpload1.FileName))
{
lblUploadResult.Text = "กรุณาเลือก excel!";
lblUploadResult.ForeColor = System.Drawing.Color.Red;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowResultUpload()", true);
return;
}
if (FileUpload1.PostedFile != null)
{
if (!string.IsNullOrEmpty(FileUpload1.FileName))
{
results.Add(UploadExcel(FileUpload1, "", "tbl_branch_oil_bill_temp"));
}
}
if (results.Count > 0 && results.All(x => x))
{
PrepareGridData();
lblUploadResult.Text = "อัพโหลด excel เรียบร้อยแล้ว!";
lblUploadResult.ForeColor = System.Drawing.Color.Green;
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowResultUpload()", true); //SendResult
}
catch (Exception ex)
{
lblUploadResult.Text = "2) เกิดข้อผิดพลาดในการอัพโหลด excel!" + ex.Message;
lblUploadResult.ForeColor = System.Drawing.Color.Red;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowResultUpload()", true);
}
}
private string GetVanID(string sheetName)
{
string ret = "";
if (sheetName.Contains("VAN"))
{
var tmp = sheetName.Substring(3, sheetName.Length - 3);
var tmpInt = Convert.ToInt32(tmp);
if (tmpInt < 10)
{
ret = "V0" + tmpInt;
}
else
{
ret = "V" + tmpInt;
}
}
return ret;
}
private string GridViewSortDirection
{
get { return Session["SortDirection"] as string ?? "ASC"; }
set { Session["SortDirection"] = value; }
}
private string GridViewSortExpression
{
get { return Session["SortExpression"] as string ?? string.Empty; }
set { Session["SortExpression"] = value; }
}
private string GetSortDirection()
{
switch (GridViewSortDirection)
{
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
private Dictionary<string, object> GetAllBranchFromDB(ref DataTable _dt, ref DataTable _dt2)
{
Dictionary<string, object> b_prmt = new Dictionary<string, object>();
b_prmt.Add("BranchID", "-1");
_dt = Helper.ExecuteProcedureToTable(conString, "proc_branch_stock_report_get_all_branch", b_prmt);
_dt2 = _dt.Copy();
DataRow sRow = _dt2.NewRow();
sRow["BranchID"] = "-1";
sRow["BranchName"] = "---ทั้งหมด---";
_dt2.Rows.InsertAt(sRow, 0);
return b_prmt;
}
private void PrepareGridData()
{
//Dictionary<string, object> _prmt = new Dictionary<string, object>();
//_prmt.Add("QAType", ddlQAType_T.SelectedItem.Text);
//DataTable _dt = Helper.ExecuteProcedureToTable(conString_qa, "proc_qa_get_questionnaire", _prmt);
//if (_dt != null && _dt.Rows.Count > 0)
//{
// Session["grdQA"] = _dt;
// BindGridView(grdQA, _dt);
//}
}
private void Search()
{
try
{
string _branchID = ddlBranch_R.SelectedValue.ToString();
//string _vanID = ddlVanID_R.SelectedValue.ToString();
int _sendStatus = Convert.ToInt32(ddlDocStatus.SelectedValue.ToString());
string _transferDate = "";
if (!string.IsNullOrEmpty(txtTransferDate_R.Text))
{
var _td = txtTransferDate_R.Text.Split('/').ToList();
_transferDate = string.Join("/", _td[1], _td[0], _td[2]);
}
Dictionary<string, object> t_prmt = new Dictionary<string, object>();
t_prmt.Add("BranchID", _branchID);
t_prmt.Add("VanID", ""); // _vanID);
t_prmt.Add("TransferDate", _transferDate);
t_prmt.Add("SendStatus", _sendStatus);
DataTable t_DT = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_search_status", t_prmt);
if (t_DT != null && t_DT.Rows.Count > 0)
{
BindGridView(grdBExns, t_DT);
Session["grdBExns"] = t_DT;
btnExportExcel.Visible = true;
}
else
{
BindGridView(grdBExns, null);
Session["grdBExns"] = null;
btnExportExcel.Visible = false;
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(2)", true);
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
private void SearchDT(GridView grd, int? pk = null)
{
try
{
Dictionary<string, object> t_prmt = new Dictionary<string, object>();
bool isViewDT = false;
if (pk != null)
{
isViewDT = true;
t_prmt.Add("PK", pk);
t_prmt.Add("BranchID", "-1");
t_prmt.Add("VanID", "-1");
t_prmt.Add("TransferDateF", "");
t_prmt.Add("TransferDateT", "");
}
else
{
string _branchID = ddlBranch_DT.SelectedValue.ToString();
string _vanID = ddlVan_DT.SelectedValue.ToString();
string _transferDateF = "";
if (!string.IsNullOrEmpty(txtTransferDateF_DT.Text))
{
var _td = txtTransferDateF_DT.Text.Split('/').ToList();
_transferDateF = string.Join("/", _td[1], _td[0], _td[2]);
}
string _transferDateT = "";
if (!string.IsNullOrEmpty(txtTransferDateT_DT.Text))
{
var _td = txtTransferDateT_DT.Text.Split('/').ToList();
_transferDateT = string.Join("/", _td[1], _td[0], _td[2]);
}
t_prmt.Add("PK", -1);
t_prmt.Add("BranchID", _branchID);
t_prmt.Add("VanID", _vanID);
if (chkHistory.Checked)
{
t_prmt.Add("TransferDateF", _transferDateF);
t_prmt.Add("TransferDateT", _transferDateT);
}
else
{
t_prmt.Add("TransferDateF", "");
t_prmt.Add("TransferDateT", "");
}
}
DataTable t_DT = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_search", t_prmt);
if (t_DT != null && t_DT.Rows.Count > 1)
{
if (isViewDT)
ddlBranch_DT.SelectedValue = t_DT.Rows[1][4].ToString();
BindGridView(grd, t_DT);
Session[grd.ID] = t_DT;
btnExcel_DT.Visible = true;
}
else
{
BindGridView(grd, null);
Session[grd.ID] = null;
btnExcel_DT.Visible = false;
}
hidHistory.Value = chkHistory.Checked ? "1" : "0";
//ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
catch (Exception ex)
{
throw;
}
}
private void SearchDT_Popup(GridView grd, int pk)
{
try
{
Dictionary<string, object> t_prmt = new Dictionary<string, object>();
t_prmt.Add("PK", pk);
DataTable t_DT = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_search_dt", t_prmt);
if (t_DT != null && t_DT.Rows.Count > 0)
{
BindGridView(grd, t_DT);
Session[grd.ID] = t_DT;
btnExportOilDT.Visible = true;
}
else
{
BindGridView(grd, null);
Session[grd.ID] = null;
btnExportOilDT.Visible = false;
}
//ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
catch (Exception ex)
{
throw;
}
}
private void SearchRank()
{
try
{
Dictionary<string, object> t_prmt = new Dictionary<string, object>();
string _branchID = ddlBranch_Rank.SelectedValue.ToString();
int _rankingType = Convert.ToInt32(ddlRankingType.SelectedValue);
string _fromDate = "";
if (!string.IsNullOrEmpty(txtDateFrom.Text))
{
var _td = txtDateFrom.Text.Split('/').ToList();
_fromDate = string.Join("/", _td[1], _td[0], _td[2]);
}
string _toDate = "";
if (!string.IsNullOrEmpty(txtDateTo.Text))
{
var _td = txtDateTo.Text.Split('/').ToList();
_toDate = string.Join("/", _td[1], _td[0], _td[2]);
}
t_prmt.Add("BranchID", _branchID);
t_prmt.Add("RankingType", _rankingType);
t_prmt.Add("DateFrom", _fromDate);
t_prmt.Add("DateTo", _toDate);
//DataTable t_DT = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_search_rank", t_prmt);
DataTable t_DT = Helper.ExecuteProcedureToTable(conString, "proc_branch_expenses_search_rank_r2", t_prmt);
if (t_DT != null && t_DT.Rows.Count > 0)
{
BindGridView(grdRanking, t_DT);
Session["grdRanking"] = t_DT;
btnExport_Rank.Visible = true;
}
else
{
BindGridView(grdRanking, null);
Session["grdRanking"] = null;
btnExport_Rank.Visible = false;
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(4)", true);
}
catch (Exception ex)
{
throw;
}
}
protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging)
{
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
if (GridViewSortExpression != string.Empty)
{
if (isPageIndexChanging)
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection);
}
else
{
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection());
}
}
return dataView;
}
else
{
return new DataView();
}
}
private bool UploadExcel(FileUpload fileUP, string sheetName, string tableName)
{
bool result = false;
try
{
if (fileUP.PostedFile != null)
{
if (!string.IsNullOrEmpty(fileUP.FileName))
{
string sqlCmd = "TRUNCATE TABLE " + tableName;
Helper.ExecuteProcedureToTable(conString, sqlCmd, CommandType.Text);
List<string> _result = new List<string>();
_result = AddExcelToDB(fileUP, sheetName, tableName);
foreach (var _vanID in _result.Distinct().ToList())
{
string _transDate = "";
var _dDate = txtTransferDate.Text.Split('/').ToList();
_transDate = string.Join("/", _dDate[1], _dDate[0], _dDate[2]);
string user = UserList.First().Key;
Dictionary<string, object> _prmt = new Dictionary<string, object>();
_prmt.Add("BranchID", ddlBranch.SelectedValue);
_prmt.Add("VanID", _vanID);
_prmt.Add("TransferDate", _transDate);
_prmt.Add("UpdateBy", user);
Helper.ExecuteProcedureOBJ(conString, "proc_branch_expenses_update_data", _prmt);
}
if (_result.Count > 0)
result = true;
}
}
}
catch (Exception ex)
{
lblUploadResult.Text = "2) เกิดข้อผิดพลาดในการอัพโหลด excel!" + ex.Message;
lblUploadResult.ForeColor = System.Drawing.Color.Red;
//ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowResultUpload()", true);
result = false;
}
return result;
}
#endregion
#region Event Methods
protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
{
//BindVanData(ddlBranch, ddlVanID);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(1)", true);
}
protected void ddlBranch_R_SelectedIndexChanged(object sender, EventArgs e)
{
//BindVanData(ddlBranch_R, ddlVanID_R, true);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(2)", true);
}
protected void ddlBranch_DT_SelectedIndexChanged(object sender, EventArgs e)
{
BindVanData(ddlBranch_DT, ddlVan_DT, true);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
protected void btnSearchBE_Click(object sender, EventArgs e)
{
Search();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
try
{
if (Session["grdBExns"] != null)
{
DataTable _dt = (DataTable)Session["grdBExns"];
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(_dt, "Report");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=รายงานค่าน้ำมัน.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
//Response.End();
}
}
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void btnSearchDT_Click(object sender, EventArgs e)
{
SearchDT(grdBEDT);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
protected void btnExcel_DT_Click(object sender, EventArgs e)
{
try
{
if (Session["grdBEDT"] != null)
{
DataTable _dt = (DataTable)Session["grdBEDT"];
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(_dt, "Report");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Branch Expenses Report.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
//Response.End();
}
}
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void grdBExns_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "report")
{
int index = Convert.ToInt32(e.CommandArgument);
string _pk = "";
_pk = grdBExns.DataKeys[index].Value.ToString();
if (!string.IsNullOrEmpty(_pk))
{
SearchDT(grdBEDT, Convert.ToInt32(_pk));
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void grdBExns_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = grdBExns.PageIndex;
grdBExns.DataSource = SortDataTable((DataTable)Session["grdQA"], false);
grdBExns.DataBind();
for (int i = 1; i < grdBExns.Columns.Count - 1; i++)
{
string ht = ((LinkButton)grdBExns.HeaderRow.Cells[i].Controls[0]).Text;
if (ht == e.SortExpression)
{
TableCell tableCell = grdBExns.HeaderRow.Cells[i];
Image img = new Image();
img.ImageUrl = (GridViewSortDirection == "ASC") ? "~/img/panel_tool_collapse.gif" : "~/img/panel_tool_expand.gif";
tableCell.Controls.Add(img);
}
}
grdBExns.PageIndex = pageIndex;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(2)", true);
}
protected void grdBExns_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (Session["grdBExns"] != null)
{
grdBExns.PageIndex = e.NewPageIndex;
BindGridView(grdBExns, (DataTable)Session["grdBExns"]);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(2)", true);
}
}
protected void grdBExns_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable dt = ((DataTable)((BaseDataBoundControl)sender).DataSource);
if (e.Row.RowIndex > -1)
{
for (int j = 0; j < e.Row.Cells.Count; j++)
{
var cell = e.Row.Cells[j];
if (j == 5)
{
if (cell.Text == "ส่งเอกสารจากศูนย์แล้ว")
{
cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#92D050");
cell.Font.Bold = true;
}
else
{
cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFE699");
cell.Font.Bold = true;
}
}
//if (j == 9)
//{
// cell.Font.Bold = true;
//}
}
}
}
protected void grdBEDT_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (Session["grdBEDT"] != null)
{
grdBEDT.PageIndex = e.NewPageIndex;
BindGridView(grdBEDT, (DataTable)Session["grdBEDT"]);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
}
protected void grdBEDT_RowDataBound(object sender, GridViewRowEventArgs e)
{
//DataTable dt = ((DataTable)((BaseDataBoundControl)sender).DataSource);
if (e.Row.RowIndex == 0 && grdBEDT.PageIndex == 0)
{
for (int j = 0; j < e.Row.Cells.Count; j++)
{
var cell = e.Row.Cells[j];
cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#F4B084");
cell.Font.Bold = true;
cell.Enabled = false;
}
}
else if (e.Row.RowIndex > 0)
{
for (int j = 0; j < e.Row.Cells.Count; j++)
{
var cellMileAmt = e.Row.Cells[19];
if (!string.IsNullOrEmpty(cellMileAmt.Text))
{
int _cellMileAmt = 0;
if (int.TryParse(cellMileAmt.Text, out _cellMileAmt))
{
if (_cellMileAmt >= 100)
{
cellMileAmt.Font.Bold = true;
cellMileAmt.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1700");
}
}
}
var cellFuel = e.Row.Cells[20];
if (!string.IsNullOrEmpty(cellFuel.Text))
{
decimal _cellFuel = 0;
if (decimal.TryParse(cellFuel.Text, out _cellFuel))
{
if (_cellFuel > 0)
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#FDFFC2");
e.Row.Font.Bold = true;
}
}
}
}
}
}
protected void grdBEDT_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = grdBEDT.PageIndex;
grdBEDT.DataSource = SortDataTable((DataTable)Session["grdBEDT"], false);
grdBEDT.DataBind();
for (int i = 1; i < grdBEDT.Columns.Count - 1; i++)
{
string ht = ((LinkButton)grdBEDT.HeaderRow.Cells[i].Controls[0]).Text;
if (ht == e.SortExpression)
{
TableCell tableCell = grdBEDT.HeaderRow.Cells[i];
Image img = new Image();
img.ImageUrl = (GridViewSortDirection == "ASC") ? "~/img/panel_tool_collapse.gif" : "~/img/panel_tool_expand.gif";
tableCell.Controls.Add(img);
}
}
grdBEDT.PageIndex = pageIndex;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(3)", true);
}
protected void grdBEDT_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void btnSearch_Rank_Click(object sender, EventArgs e)
{
SearchRank();
}
protected void btnExport_Rank_Click(object sender, EventArgs e)
{
try
{
if (Session["grdRanking"] != null)
{
DataTable _dt = (DataTable)Session["grdRanking"];
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(_dt, "Report");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=รายงานการใช้ค่าน้ำมัน.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
//Response.End();
}
}
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void grdRanking_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = grdRanking.PageIndex;
var dv = SortDataTable((DataTable)Session["grdRanking"], false); ;
grdRanking.DataSource = dv.ToTable();
grdRanking.DataBind();
for (int i = 1; i < grdRanking.Columns.Count - 1; i++)
{
string ht = ((LinkButton)grdRanking.HeaderRow.Cells[i].Controls[0]).Text;
if (ht == e.SortExpression)
{
TableCell tableCell = grdRanking.HeaderRow.Cells[i];
Image img = new Image();
img.ImageUrl = (GridViewSortDirection == "ASC") ? "~/img/panel_tool_collapse.gif" : "~/img/panel_tool_expand.gif";
tableCell.Controls.Add(img);
}
}
grdRanking.PageIndex = pageIndex;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(4)", true);
}
protected void grdRanking_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (Session["grdRanking"] != null)
{
grdRanking.PageIndex = e.NewPageIndex;
var dv = SortDataTable((DataTable)Session["grdRanking"], false);
BindGridView(grdRanking, dv.ToTable());
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ActiveTab(4)", true);
}
}
protected void grdRanking_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
DataTable dt = ((DataTable)((BaseDataBoundControl)sender).DataSource);
for (int j = 0; j < e.Row.Cells.Count; j++)
{
if (j == 1)
{
e.Row.Cells[j].Visible = false;
}
if (j == 3)
{
e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Center;
}
if (j == 9)
{
e.Row.Cells[j].HorizontalAlign = HorizontalAlign.Right;
}
}
if (e.Row.RowIndex >= 0)
{
var cell14 = e.Row.Cells[9];
cell14.BackColor = System.Drawing.ColorTranslator.FromHtml("#FCECC4");
cell14.Font.Bold = true;
//var cell15 = e.Row.Cells[15];
//cell15.BackColor = System.Drawing.ColorTranslator.FromHtml("#F4B084");
//cell15.Font.Bold = true;
//var cell20 = e.Row.Cells[20];
//cell20.BackColor = System.Drawing.ColorTranslator.FromHtml("#FAFE9B");
//cell20.Font.Bold = true;
}
//if (e.Row.RowType == DataControlRowType.Header)
//{
// var _text = ddlRankingType.SelectedItem.Text;
// string htext = "";
// if (_text.Length > 13)
// htext = _text.Substring(7, _text.Length - 7);
// else
// htext = _text;
// e.Row.Cells[9].Text = htext;
//}
}
catch (Exception ex)
{
throw ex;
}
}
protected void grdRanking_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "details")
{
int index = Convert.ToInt32(e.CommandArgument);
string _pk = "";
_pk = grdRanking.DataKeys[index].Value.ToString();
SearchDT_Popup(grdSubDT, Convert.ToInt32(_pk));
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowDT(4)", true);
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void grdSubDT_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
for (int j = 0; j < e.Row.Cells.Count; j++)
{
var cellMileAmt = e.Row.Cells[19];
if (!string.IsNullOrEmpty(cellMileAmt.Text))
{
int _cellMileAmt = 0;
if (int.TryParse(cellMileAmt.Text, out _cellMileAmt))
{
if (_cellMileAmt >= 100)
{
cellMileAmt.Font.Bold = true;
cellMileAmt.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1700");
}
}
}
var cellFuel = e.Row.Cells[20];
if (!string.IsNullOrEmpty(cellFuel.Text))
{
decimal _cellFuel = 0;
if (decimal.TryParse(cellFuel.Text, out _cellFuel))
{
if (_cellFuel > 0)
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#FDFFC2");
e.Row.Font.Bold = true;
}
}
}
}
}
}
protected void grdSubDT_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = grdSubDT.PageIndex;
grdSubDT.DataSource = SortDataTable((DataTable)Session["grdSubDT"], false);
grdSubDT.DataBind();
for (int i = 1; i < grdSubDT.Columns.Count - 1; i++)
{
string ht = ((LinkButton)grdSubDT.HeaderRow.Cells[i].Controls[0]).Text;
if (ht == e.SortExpression)
{
TableCell tableCell = grdSubDT.HeaderRow.Cells[i];
Image img = new Image();
img.ImageUrl = (GridViewSortDirection == "ASC") ? "~/img/panel_tool_collapse.gif" : "~/img/panel_tool_expand.gif";
tableCell.Controls.Add(img);
}
}
grdSubDT.PageIndex = pageIndex;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowDT(4)", true);
}
protected void btnExportOilDT_Click(object sender, EventArgs e)
{
try
{
if (Session["grdSubDT"] != null)
{
DataTable _dt = (DataTable)Session["grdSubDT"];
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(_dt, "Report");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=รายงานอันดับค่าน้ำมัน.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
//Response.End();
}
}
}
}
catch (Exception ex)
{
Helper.WriteLog(ex.Message);
throw ex;
}
}
protected void ddlRankingType_SelectedIndexChanged(object sender, EventArgs e)
{
SearchRank();
}
#endregion
} |
using System;
namespace MazeGenerator
{
class Program
{
static void Main(string[] args)
{
Generator generator = new Generator(10, 10);
generator.Start();
Console.WriteLine("Debug:");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NewMonsterButtonScript : MonoBehaviour {
private Canvas canvasPrice, generateMonster, canvasNotEnoughGold;
private Interface canvasInterface;
void Start()
{
canvasInterface = GameObject.Find ("CanvasNight").GetComponent<Interface> ();
canvasPrice = GameObject.Find ("CanvasGenePrice").GetComponent<Canvas> ();
}
void Update()
{
}
// OnMouseEnter et OnMouseExit permettent de gérer la transparence des cases quand on passe dessus
public void OnMouseEnter()
{
canvasPrice.enabled = true;
}
public void OnMouseExit ()
{
canvasPrice.enabled = false;
}
public void OnMouseClick(int monsterNum)
{
//On vérifie qu'on a assez d'or pour acheter le monstre
if (canvasInterface.CanAffordMonster (monsterNum))
{
// monsternum == 0 correspond à la génération des 3 monstres que l'on peut acheter
if (monsterNum == 0) {
//On retire les 50g au coffre
canvasInterface.BuyMonster (50);
GameObject.Find ("GeneratedMonsters").GetComponent<Canvas> ().enabled = true;
GameObject.Find ("GenerateMonster").GetComponent<MonsterPool> ().GeneratePool ();
//On génère les monstres
} else {
//On active l'overlay pour choisir la salle dans laquelle instancier le monstre (c'est dans le contrôle de l'overlay que le monstre est ensuite instancié, voir MouseOverRoom.cs)
GameObject.Find ("Environment").GetComponent<Environment> ().addingMonster = true;
GameObject.Find ("Environment").GetComponent<Environment> ().monsterNum = monsterNum;
GameObject[] gameObjectOverlay = GameObject.FindGameObjectsWithTag ("Overlay");
foreach (GameObject Overlay in gameObjectOverlay) {
if (Overlay.GetComponentInParent<InfoRoom> ().containsMonster == false) {
Overlay.GetComponent<Renderer> ().enabled = true;
Overlay.GetComponent<PolygonCollider2D> ().enabled = true;
Overlay.GetComponent<SpriteRenderer> ().color = new Color (0f, 1f, 0f, .2f);
}
}
GameObject.Find ("GeneratedMonsters").GetComponent<Canvas> ().enabled = false;
}
} else {
CantAfford (monsterNum);
}
}
public void CancelGeneratedMonsetrs()
{
GameObject.Find ("GeneratedMonsters").GetComponent<Canvas> ().enabled = false;
}
//Achat impossible
public void CantAfford(int monsterNum)
{
StartCoroutine(CantAffordCanvas (monsterNum));
}
IEnumerator CantAffordCanvas(int monsterNum)
{
if (monsterNum == 0) {
canvasNotEnoughGold = GameObject.Find ("NotEnoughGold").GetComponent<Canvas> ();
canvasPrice.enabled = false;
canvasNotEnoughGold.enabled = true;
yield return new WaitForSeconds (1);
canvasNotEnoughGold.enabled = false;
canvasPrice.enabled = true;
} else {
canvasNotEnoughGold = GameObject.Find ("NotEnoughGold" + monsterNum.ToString ()).GetComponent<Canvas> ();
canvasNotEnoughGold.enabled = true;
yield return new WaitForSeconds (1);
canvasNotEnoughGold.enabled = false;
}
}
}
|
using DAL;
using Fina.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Repo
{
public interface IRepository
{
//employee
void AddEmployee(Employee entity);
void UpdateEmployee(Employee entity);
Employee GetEmployeeByID(int ID);
List<Employee> GetEmployies();
void RemoveEmployee(int ID);
//stores
void AddStore(Store entity);
void UpdateStore(Store entity);
Store GetstoreByID(int ID);
List<Store> GetStores();
void RemoveStore(int ID);
//salaries
void AddSalary(Salary entity);
void UpdateSalary(Salary entity);
Salary GetSalaryByID(int ID);
List<Salary> GetSalaries();
void RemoveSalary(int ID);
//products
void AddProduct(Product entity);
void UpdatePruduct(Product entity);
Product GetProductByID(int ID);
List<Product> GetProducts();
void RemoveProduct(int ID);
}
}
|
using AudioText.Models;
using AudioText.Models.DataModels;
using AudioText.Models.ViewModels;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace AudioText.Controllers
{
public class CatalogCategoryController : Controller
{
[HttpPost]
public ActionResult Index(CategoryDataModel model)
{
return View(new CategoryViewModel(model.pageTitle, model.categoryName));
}
[HttpPost]
public ActionResult ShowFilteredResults(CategoryDataModel model)
{
return View("Index",new CategoryViewModel(model.pageTitle, model.categoryName, model.selectedAuthorId, model.selectedFilterId));
}
}
} |
using System.ComponentModel;
namespace ModelViewViewModel_Voorbeeld.Stap3
{
class PersoonViewModel : INotifyPropertyChanged
{
private readonly Persoon model;
public PersoonViewModel(Persoon model)
{
this.model = model;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
// take a copy to prevent thread issues
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using UBaseline.Core.Extensions;
using Uintra.Core.Activity.Helpers;
using Umbraco.Core.Composing;
namespace Uintra.Core.Activity
{
public class ActivitiesServiceFactory : IActivitiesServiceFactory
{
private readonly IActivityTypeHelper _activityTypeHelper;
public ActivitiesServiceFactory(IActivityTypeHelper activityTypeHelper)
{
_activityTypeHelper = activityTypeHelper;
}
public TService GetService<TService>(Guid activityId) where TService : class, ITypedService
{
var activityType = _activityTypeHelper.GetActivityType(activityId);
return GetService<TService>(activityType);
}
public TService GetService<TService>(Enum type) where TService : class, ITypedService
{
var services= Current.Factory.EnsureScope(s=>(IEnumerable<TService>)s.GetAllInstances(typeof(TService)));
return services.FirstOrDefault(s => Equals(s.Type, type));
}
public IEnumerable<TService> GetServices<TService>() where TService : class, ITypedService
{
return DependencyResolver.Current.GetServices<TService>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Snake
{
public class Program
{
private static Random Random = new Random();
private const string TopLeftCorner = "╔";
private const int MaxHeight = 30;
private const int MaxWidth = 119;
private const int BorderSize = 4;
private const int StartingX = 60;
private const int StartingY = 15;
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.OutputEncoding = Encoding.UTF8;
DrawBorders();
SelfMovingSnake();
//#if (Debug)
//Console.ReadLine();
//#endif
}
static void InitGame()
{
}
static void DrawBorders()
{
var color = Console.ForegroundColor;
var x = Console.CursorTop;
var y = Console.CursorLeft;
Console.ForegroundColor = ConsoleColor.White;
for (int i = BorderSize; i <= MaxHeight - BorderSize; i++)
{
Console.SetCursorPosition(BorderSize, i);
Console.Write("║");
Console.SetCursorPosition(MaxWidth - BorderSize, i);
Console.Write("║");
}
for (int j = BorderSize; j <= MaxWidth - BorderSize; j++)
{
Console.SetCursorPosition(j, BorderSize);
Console.Write("═");
Console.SetCursorPosition(j, MaxHeight - BorderSize);
Console.Write("═");
}
Console.SetCursorPosition(BorderSize, BorderSize);
Console.Write(TopLeftCorner);
Console.SetCursorPosition(MaxWidth - BorderSize, BorderSize);
Console.Write("╗");
Console.SetCursorPosition(BorderSize, MaxHeight - BorderSize);
Console.Write("╚");
Console.SetCursorPosition(MaxWidth - BorderSize, MaxHeight - BorderSize);
Console.Write("╝");
Console.ForegroundColor = color;
Console.SetCursorPosition(x, y);
}
#region Game Logic
private static void SelfMovingSnake()
{
int BorderHeight = MaxHeight-BorderSize;
int BorderWidth = MaxWidth-BorderSize;
int lifePosX = BorderSize - 3;
int lifePosY = BorderSize - 3;
int startingLives = 5;
Console.SetCursorPosition(lifePosX, lifePosY);
Console.Write("Remaining Lives : " + startingLives);
int foodScoreX = MaxWidth - 12;
int foodScoreY = MaxHeight - 29;
int foodScore = 0;
int resetSpeed = 500;
Console.SetCursorPosition(foodScoreX, foodScoreY);
Console.Write("Score : " + foodScore);
int foodX = Random.Next(BorderSize + 2, BorderWidth-2);
int foodY = Random.Next(BorderSize + 2, BorderHeight-2);
int snakeSegments = 1;
int snakeSpeed = 500;
Point[] snakeBody = new Point[60];
snakeBody[0] = new Point(StartingX, StartingY);
for (int i = 1; i < snakeBody.Length; i++)
{
snakeBody[i] = new Point(0, 0);
}
Console.SetCursorPosition(foodX, foodY);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("*");
bool collision = false;
int xStep = 0;
int yStep = 0;
ConsoleKeyInfo key;
//Loop to play game...
while (true)
{
//Input Handling and Snake Controls...
if (Console.KeyAvailable)
{
//Has to be true to stop printing
key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.LeftArrow when (xStep == 0):
xStep = -1;
yStep = 0;
break;
case ConsoleKey.RightArrow when (xStep == 0):
xStep = 1;
yStep = 0;
break;
case ConsoleKey.UpArrow when (yStep == 0):
xStep = 0;
yStep = -1;
break;
case ConsoleKey.DownArrow when (yStep == 0):
xStep = 0;
yStep = 1;
break;
default:
break;
}
}
Console.SetCursorPosition(snakeBody[snakeSegments - 1].X, snakeBody[snakeSegments - 1].Y);
Console.Write(" ");
//Enables snake movement and the body follows the same movement...
for (int i = snakeSegments - 1; 0 < i; i--)
{
snakeBody[i].X = snakeBody[i - 1].X;
snakeBody[i].Y = snakeBody[i - 1].Y;
}
snakeBody[0].X += xStep;
snakeBody[0].Y += yStep;
Console.SetCursorPosition(snakeBody[0].X, snakeBody[0].Y);
Console.Write("#");
//Add food to snake body and spawn new food...
if (snakeBody[0].X == foodX && snakeBody[0].Y == foodY && snakeSegments < snakeBody.Length)
{
bool isFoodUncollided = false;
do
{
foodX = Random.Next(BorderSize + 2, BorderWidth - 2);
foodY = Random.Next(BorderSize + 2, BorderHeight - 2);
for (int i = 0; i < snakeSegments; i++)
{
isFoodUncollided = isFoodUncollided
|| (snakeBody[i].X == foodX && snakeBody[i].Y == foodY);
}
}
while (isFoodUncollided);
if (snakeSpeed > 40)
{
snakeSpeed /= 2;
}
foodScore += 1;
Console.SetCursorPosition(foodScoreX, foodScoreY);
Console.Write("Score : " + foodScore);
Console.SetCursorPosition(foodX, foodY);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("*");
Console.Beep(800, 10);
snakeSegments++;
}
//Win Condition...
if (snakeSegments == snakeBody.Length - 1)
{
Console.SetCursorPosition(StartingX - 15, StartingY);
Console.WriteLine("Congratulations!!");
Console.SetCursorPosition(StartingX - 25, StartingY + 1);
Console.WriteLine("You cleared the first level!");
Console.SetCursorPosition(StartingX - 30, StartingY + 2);
Console.WriteLine("The game will now quit..");
Console.ReadLine();
Console.Clear();
#region Border Draw
for (int i = BorderSize; i <= MaxHeight - BorderSize; i++)
{
Console.SetCursorPosition(BorderSize, i);
Console.Write("║");
Console.SetCursorPosition(MaxWidth - BorderSize, i);
Console.Write("║");
}
for (int j = BorderSize; j <= MaxWidth - BorderSize; j++)
{
Console.SetCursorPosition(j, BorderSize);
Console.Write("═");
Console.SetCursorPosition(j, MaxHeight - BorderSize);
Console.Write("═");
}
Console.SetCursorPosition(BorderSize, BorderSize);
Console.Write("╔");
Console.SetCursorPosition(MaxWidth - BorderSize, BorderSize);
Console.Write("╗");
Console.SetCursorPosition(BorderSize, MaxHeight - BorderSize);
Console.Write("╚");
Console.SetCursorPosition(MaxWidth - BorderSize, MaxHeight - BorderSize);
Console.Write("╝");
#endregion
foodX = Random.Next(BorderSize + 2, BorderWidth - 2);
foodY = Random.Next(BorderSize + 2, BorderHeight - 2);
key = Console.ReadKey();
if (key.Key == ConsoleKey.Enter)
{
Console.SetCursorPosition(StartingX, StartingY);
Console.WriteLine("Bye!");
break;
}
for (int i = 0; i < snakeBody.Length; i++)
{
snakeBody[i].X = 0;
snakeBody[i].Y = 0;
}
foodScore = 0;
snakeSegments = 1;
snakeBody[0].X = StartingX;
snakeBody[0].Y = StartingY;
collision = false;
xStep = 1;
yStep = 0;
}
//Check for collision with snakebody...
for (int i = 2; i < snakeBody.Length; i++)
{
collision = snakeBody[0].X == snakeBody[i].X
&& snakeBody[0].Y == snakeBody[i].Y;
if (collision)
{
break;
}
}
//Lose condition...
if (collision || snakeBody[0].X >= BorderWidth || snakeBody[0].X <= BorderSize
|| snakeBody[0].Y >= BorderHeight || snakeBody[0].Y <= BorderSize || startingLives==0)
{
foodX = Random.Next(BorderSize + 2, BorderWidth - 2);
foodY = Random.Next(BorderSize + 2, BorderHeight - 2);
Console.SetCursorPosition(StartingX - 15, StartingY);
Console.WriteLine("You lost.. Press enter to quit.");
key = Console.ReadKey();
if (key.Key == ConsoleKey.Enter)
{
Console.SetCursorPosition(StartingX, StartingY);
Console.WriteLine("Bye!");
break;
}
for (int i = 0; i < snakeBody.Length; i++)
{
snakeBody[i].X = 0;
snakeBody[i].Y = 0;
}
for (int j = startingLives; j <= 5; )
{
startingLives -= 1;
Console.SetCursorPosition(lifePosX, lifePosY);
Console.Write("Remaining Lives : " + startingLives);
break;
}
//Restart and Redraw...
if (key.Key != ConsoleKey.Enter)
{
Console.Clear();
snakeSpeed = resetSpeed;
Console.SetCursorPosition(foodScoreX, foodScoreY);
Console.Write("Score : " + foodScore);
Console.SetCursorPosition(lifePosX, lifePosY);
Console.Write("Remaining Lives : " + startingLives);
Console.ForegroundColor = ConsoleColor.Green;
foodX = Random.Next(BorderSize + 2, BorderWidth - 2);
foodY = Random.Next(BorderSize + 2, BorderHeight - 2);
Console.SetCursorPosition(foodX, foodY);
Console.Write("*");
Console.ForegroundColor = ConsoleColor.White;
#region Border Draw
for (int i = BorderSize; i <= MaxHeight - BorderSize; i++)
{
Console.SetCursorPosition(BorderSize, i);
Console.Write("║");
Console.SetCursorPosition(MaxWidth - BorderSize, i);
Console.Write("║");
}
for (int j = BorderSize; j <= MaxWidth - BorderSize; j++)
{
Console.SetCursorPosition(j, BorderSize);
Console.Write("═");
Console.SetCursorPosition(j, MaxHeight - BorderSize);
Console.Write("═");
}
Console.SetCursorPosition(BorderSize, BorderSize);
Console.Write("╔");
Console.SetCursorPosition(MaxWidth - BorderSize, BorderSize);
Console.Write("╗");
Console.SetCursorPosition(BorderSize, MaxHeight - BorderSize);
Console.Write("╚");
Console.SetCursorPosition(MaxWidth - BorderSize, MaxHeight - BorderSize);
Console.Write("╝");
#endregion
}
if (startingLives == 0)
{
Console.SetCursorPosition(StartingX - 20, StartingY);
Console.Write("Too bad.. You don't have any lives left..");
Console.SetCursorPosition(StartingX - 20, StartingY + 1);
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write("The game will quit unless you press the Enter key..");
Console.ForegroundColor = ConsoleColor.White;
}
snakeSegments = 1;
snakeBody[0].X = StartingX;
snakeBody[0].Y = StartingY;
collision = false;
xStep = 1;
yStep = 0;
}
Console.ForegroundColor = ConsoleColor.White;
Thread.Sleep(snakeSpeed/2);
}
}
#endregion
}
}
|
namespace ITMakesSense.CSharp.Enumerations
{
public class Int64Enumeration<TEnumeration> : Enumeration<TEnumeration, long>
where TEnumeration : Enumeration<TEnumeration, long>
{
public Int64Enumeration(string name, long value)
: base(name, value)
{
}
}
} |
using Quark.Spell;
using Quark.Targeting;
using Quark.Utilities;
using UnityEngine;
namespace Quark.Missile
{
/// <summary>
/// Missile class provides interface for MissileController objects to access to properties about the projectile
/// It also retrieves necessary movement vector or position vector and moves the carrier object appropriately
/// It is also responsible for handling the collisions and target checks
/// </summary>
public class Missile : MonoBehaviour
{
/// <summary>
/// The near enough distance constant which indicates that a missile will consider itself reached to a target point
/// </summary>
public static float NearEnough = 0.1F;
float _initialTime;
Vector3 _initialPosition;
Vector3 _targetPosition;
Targetable _target;
Cast _context;
MissileController _controller;
uint HitCount
{
get
{
return _context.HitCount;
}
set
{
_context.HitCount = value;
}
}
/// <summary>
/// Gets the initial position for this missile.
/// </summary>
/// <value>The initial position.</value>
public Vector3 InitPosition
{
get
{
return this._initialPosition;
}
}
public Vector3 Target
{
get
{
return ToPos ? this._targetPosition : this._target.transform.position;
}
}
public Vector3 CastRotation
{
get;
set;
}
public float InitTime
{
get
{
return this._initialTime;
}
}
bool HasReached
{
get
{
Vector3 a = transform.position, b = _targetPosition;
a.y = 0;
b.y = 0;
return Vector3.Distance(a, b) <= NearEnough;
}
}
#region Initialization
public static Missile Make(GameObject prefab, MissileController controller, Cast context)
{
GameObject obj = (GameObject)MonoBehaviour.Instantiate(prefab, context.CastBeginPoint, Quaternion.identity);
Missile m = obj.AddComponent<Missile>();
m._context = context;
m._controller = controller;
m._controller.Set(m);
return m;
}
bool ToPos = false;
public void Set(Vector3 target)
{
this.CastRotation = target - _context.CastBeginPoint;
this.ToPos = true;
this._targetPosition = target;
}
public void Set(Character target)
{
this.CastRotation = target.transform.position - _context.CastBeginPoint;
this._target = target;
}
public void Set(Targetable target)
{
this.CastRotation = target.transform.position - _context.CastBeginPoint;
this._target = target;
}
#endregion
void Start()
{
_initialPosition = this.transform.position;
_initialTime = Time.timeSinceLevelLoad;
}
void OnTriggerEnter(Collider c)
{
Character hit = c.gameObject.GetComponent<Character>();
if (IsHitValid(hit))
{
_context.Spell.OnHit(hit);
if ((!ToPos && hit.Equals(this._target)) || (this._context.Spell.TargetForm == TargetForm.Singular))
{
_context.Spell.CollectProjectile(this);
Destroy(this.gameObject);
}
}
Logger.Debug("Hit: " + c.gameObject.name + "\nTarget Was" + (hit == null ? " Not" : "") + " A Character");
}
protected virtual bool IsHitValid(Character hit)
{
bool result = hit != null && !hit.Equals(_context.Caster) && hit.IsTargetable;
if (result)
HitCount++;
return result;
}
void Update()
{
if (!ToPos)
_targetPosition = _target.transform.position;
_controller.Control();
_context.Spell.OnTravel(transform.position);
if (ToPos && HasReached)
{
_context.Spell.OnHit(_targetPosition);
_context.Spell.CollectProjectile(this);
Destroy(gameObject);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kuromori.DataStructure;
using Xamarin.Forms;
namespace Kuromori.Pages
{
/// <summary>
/// A Frame that consists of
/// 2 Labels : speakerName, speakerDesc
/// 1 Image - clickable : speakerImage
/// </summary>
public partial class SpeakerView : Frame
{
/// <summary>
/// Create a speakerview
/// </summary>
/// <param name="speaker">Speaker to be rendered inside the eventView</param>
public SpeakerView(Speaker speaker)
{
InitializeComponent();
Label speakerName = this.FindByName<Label>("Name");
Image speakerImage = this.FindByName<Image>("Image");
Label speakerDesc = this.FindByName<Label>("Description");
speakerName.Text = speaker.SpeakerName;
speakerDesc.Text = speaker.SpeakerDescription;
speakerImage.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() =>
{
try
{
Device.OpenUri(new Uri(speaker.SpeakerUrl));
}
catch (FormatException res)
{
}
})
});
Device.OnPlatform(null, null, () =>
{
speakerName.TextColor = Color.Black;
speakerDesc.TextColor = Color.Black;
}, null);
try
{
speakerImage.Source = new Uri(speaker.SpeakerImg);
}
catch (FormatException Excep)
{
speakerImage.Source = ImageSource.FromFile(("noimage.png"));
}
}
}
}
|
using IndusValley.Banking;
using SE.Miscellaneous;
using SE.Money;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IndusValley.Broker {
public class Brokerage : IBroker {
public Task<Maybe<IOrder>> CheckBuyOrder(Guid buyId) {
throw new NotImplementedException();
}
public Task<Maybe<IOrder>> CheckSellOrder(Guid sellId) {
throw new NotImplementedException();
}
public IObservable<Money> Stock(string symbol) {
throw new NotImplementedException();
}
public Task<Maybe<IOrder>> SubmitBuyOrder(string symbol, Account account, Money amount) {
throw new NotImplementedException();
}
public Task<Maybe<IOrder>> SubmitSellOrder(string symbol, Account account, double shares) {
throw new NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
namespace Structure
{
public class Path
{
private List<Point3D> points3D;
public Path()
{
this.points3D = new List<Point3D>();
}
public void AddPoint(Point3D point)
{
this.points3D.Add(point);
}
public Point3D this[int index]
{
get { return this.points3D[index]; }
set { this.points3D[index] = value; }
}
public int Count
{
get { return this.points3D.Count; }
}
public override string ToString()
{
return String.Format("{0}",this.points3D);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OpenPopUp : MonoBehaviour
{
public GameObject popUpToOpen = null;
public void OpenPopupMessage(){
popUpToOpen.SetActive(true);
}
}
|
/* Script for the moonstone PlayerItem?
*/
using UnityEngine;
using System.Collections;
public class moonGemstoneScript : MonoBehaviour
{
// public inventoryScript moon_Gemstone;
public GameObject moonStone;
// public GameObject[] PlayerItems;
// Use this for initialization
void Start ()
{
// moonStone.SetActive(false);
// PlayerItems[3] = moonStone;
moonStone.renderer.enabled = false;
}
// Update is called once per frame
void Update ()
{
// if(Input.GetKeyDown ("4") && moonStone.activeSelf == false)
if(Input.GetKeyDown ("4") && moonStone.renderer.enabled == false)
{
// moonStone.SetActive(true);
moonStone.renderer.enabled = true;
Debug.Log ("Power of the moon!!!");
}
// else if(Input.GetKeyDown("4") && moonStone.activeSelf == true)
else if(Input.GetKeyDown ("4") && moonStone.renderer.enabled == true)
{
// moonStone.SetActive(false);
moonStone.renderer.enabled = false;
Debug.Log("Moon power down");
}
}
}
|
namespace Sweet_Dessert
{
using System;
public class StartUp
{
public static void Main()
{
var ammountCash = decimal.Parse(Console.ReadLine());
var guestCount = long.Parse(Console.ReadLine());
var bananasPrice = decimal.Parse(Console.ReadLine());
var eggsPrice = decimal.Parse(Console.ReadLine());
var berriesPriceKg = decimal.Parse(Console.ReadLine());
var portions = Math.Ceiling((decimal)guestCount / 6);
var neededMoney = (decimal)(portions * (2 * bananasPrice) + portions * (4 * eggsPrice) + portions * (0.2M * berriesPriceKg));
if (ammountCash >= neededMoney)
{
Console.WriteLine($"Ivancho has enough money - it would cost {neededMoney:f2}lv.");
}
else
{
Console.WriteLine($"Ivancho will have to withdraw money - he will need {neededMoney - ammountCash:f2}lv more.");
}
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Vlc.DotNet.Core.Interops.Signatures
{
public enum Position
{
Disable=-1,
Center,
Left,
Right,
Top,
TopLeft,
TopRight,
Bottom,
BottomLeft,
BottomRight
}
}
|
namespace Sentry.Tests.Internals;
public class DuplicateEventDetectionEventProcessorTests
{
private class Fixture
{
public SentryOptions Options { get; set; } = new();
public DuplicateEventDetectionEventProcessor GetSut() => new(Options);
}
private readonly Fixture _fixture = new();
[Fact]
public void Process_DuplicateEvent_ReturnsNull()
{
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.Process(@event);
var actual = sut.Process(@event);
Assert.Null(actual);
}
[Fact]
public void Process_DuplicateEventDisabled_DoesNotReturnsNull()
{
_fixture.Options.DeduplicateMode ^= DeduplicateMode.SameEvent;
var @event = new SentryEvent();
var sut = _fixture.GetSut();
_ = sut.Process(@event);
var actual = sut.Process(@event);
Assert.NotNull(actual);
}
[Fact]
public void Process_FirstEventWithoutException_ReturnsEvent()
{
var expected = new SentryEvent();
var sut = _fixture.GetSut();
var actual = sut.Process(expected);
Assert.Same(expected, actual);
}
[Fact]
public void Process_FirstEventWithException_ReturnsEvent()
{
var expected = new SentryEvent(new Exception());
var sut = _fixture.GetSut();
var actual = sut.Process(expected);
Assert.Same(expected, actual);
}
[Fact]
public void Process_SecondEventWithSameExceptionInstance_ReturnsNull()
{
var duplicate = new Exception();
var first = new SentryEvent(duplicate);
var second = new SentryEvent(duplicate);
var sut = _fixture.GetSut();
_ = sut.Process(first);
var actual = sut.Process(second);
Assert.Null(actual);
}
[Fact]
public void Process_SecondEventWithSameExceptionInstanceDisabled_DoesNotReturnsNull()
{
_fixture.Options.DeduplicateMode ^= DeduplicateMode.SameExceptionInstance;
var duplicate = new Exception();
var first = new SentryEvent(duplicate);
var second = new SentryEvent(duplicate);
var sut = _fixture.GetSut();
_ = sut.Process(first);
var actual = sut.Process(second);
Assert.NotNull(actual);
}
[Fact]
public void Process_AggregateExceptionDupe_ReturnsNull()
{
var duplicate = new Exception();
var first = new SentryEvent(new AggregateException(duplicate));
var second = new SentryEvent(duplicate);
var sut = _fixture.GetSut();
_ = sut.Process(first);
var actual = sut.Process(second);
Assert.Null(actual);
}
[Fact]
public void Process_AggregateExceptionDupeDisabled_DoesNotReturnsNull()
{
_fixture.Options.DeduplicateMode ^= DeduplicateMode.AggregateException;
var duplicate = new Exception();
var first = new SentryEvent(new AggregateException(duplicate));
var second = new SentryEvent(duplicate);
var sut = _fixture.GetSut();
_ = sut.Process(first);
var actual = sut.Process(second);
Assert.NotNull(actual);
}
[Fact]
public void Process_InnerExceptionHasAggregateExceptionDupe_DoesNotReturnsNullByDefault()
{
var duplicate = new Exception();
var first = new SentryEvent(new InvalidOperationException("test", new AggregateException(duplicate)));
var second = new SentryEvent(new InvalidOperationException("another test",
new Exception("testing", new AggregateException(duplicate))));
var sut = _fixture.GetSut();
_ = sut.Process(first);
var actual = sut.Process(second);
Assert.NotNull(actual);
}
[Fact]
public void Process_InnerExceptionHasAggregateExceptionDupe_ReturnsNull()
{
_fixture.Options.DeduplicateMode |= DeduplicateMode.InnerException;
var duplicate = new Exception();
var first = new SentryEvent(new InvalidOperationException("test", new AggregateException(duplicate)));
var second = new SentryEvent(new InvalidOperationException("another test",
new Exception("testing", new AggregateException(duplicate))));
var sut = _fixture.GetSut();
_ = sut.Process(first);
var actual = sut.Process(second);
Assert.Null(actual);
}
}
|
using Microsoft.SqlServer.Management.Smo;
using SqlServerWebAdmin.Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SqlServerWebAdmin
{
public partial class CreateLogin : System.Web.UI.Page
{
protected void AuthType_Changed(object sender, EventArgs e)
{
if (AuthType.SelectedValue == "Standard")
{
Password.Enabled = true;
}
else
{
Password.Enabled = false;
}
}
public bool IsUserValid()
{
//todo:
bool success = true;
SqlConnection myConnection = new SqlConnection("");
try
{
myConnection.Open();
}
catch (SqlException ex)
{
string message = ex.Message;
success = false;
}
finally
{
myConnection.Close();
}
return success;
}
protected void AddLogin_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
LoginCollection logins;
Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer;
try
{
server.Connect();
}
catch (System.Exception ex)
{
Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace)));
}
if (IsUserValid())
{
logins = server.Logins;
try
{
var login = new Microsoft.SqlServer.Management.Smo.Login(server, LoginName.Text.Trim());
login.LoginType = (LoginType)Enum.Parse(typeof(LoginType), AuthType.SelectedValue);
login.Create();
logins.Add(login);
login.ChangePassword(Password.Text.Trim());
// Redirect user to the edit screen so they can edit more properties
Response.Redirect("~/Modules/Security/EditServerLogin.aspx?Login=" + Server.UrlEncode(login.Name));
}
catch (Exception ex)
{
ErrorMessage.Text = ex.Message;
}
}
server.Disconnect();
}
}
}
} |
using System;
using UnityEngine;
using UnityEngine.UI;
using GFW;
namespace CodeX
{
public class UIProgressPage : UIPage
{
public class ProgressInfo
{
public float progress;
public float durTime;
public float totTime;
public bool auto;
public ProgressInfo()
{
this.progress = 0;
this.durTime = 0;
this.totTime = 0;
this.auto = false;
}
public ProgressInfo(float progress, float totTime, bool auto)
{
this.progress = progress;
this.durTime = 0;
this.totTime = totTime;
this.auto = auto;
}
}
private Image m_BarImg;
private Action m_OnFinsh;
private bool m_IsFinish;
private float m_bTime;
private ProgressInfo m_ProgressInfo;
private void Awake()
{
m_BarImg = transform.Find("ProgressBar/bar").GetComponent<Image>();
}
protected override void OnOpen(object arg = null)
{
m_bTime = Time.time;
if (arg != null)
{
if (arg is ProgressInfo)
{
m_ProgressInfo = (ProgressInfo)arg;
}
}
if(m_ProgressInfo == null)
{
m_ProgressInfo = new ProgressInfo(0, 2, true);
}
Vector2 size = new Vector2(1200, 28);
m_BarImg.rectTransform.sizeDelta = size;
m_IsFinish = true;
}
private void Update()
{
if (m_IsFinish)
return;
if(m_ProgressInfo.auto)
{
m_ProgressInfo.durTime += Time.deltaTime;
m_ProgressInfo.progress = m_ProgressInfo.durTime / m_ProgressInfo.totTime;
m_ProgressInfo.progress = Mathf.Clamp(m_ProgressInfo.progress,0,1);
}
Vector2 size = new Vector2(1200 * m_ProgressInfo.progress, 28);
m_BarImg.rectTransform.sizeDelta = size;
if (m_ProgressInfo.progress >= 1)
{
m_IsFinish = true;
if (m_OnFinsh != null)
{
m_OnFinsh();
Close();
}
}
}
public void SetFinishCallback(Action callback)
{
m_OnFinsh = callback;
}
public void SetProgress(float value)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System;
using System.IO;
using System.Text;
public class Record : MonoBehaviour
{
public string record;
// Start is called before the first frame update
void Start()
{
string path = Application.persistentDataPath + "/record.txt";
record = File.ReadAllText(path);
//print(record);
GameObject.Find("Canvas/Panel/Record").GetComponent<Text>().text = record;
}
public void re()
{
string path = Application.persistentDataPath + "/record.txt";
File.WriteAllText(path, "錯誤紀錄:\n");
}
// Update is called once per frame
void Update()
{
string path = Application.persistentDataPath + "/record.txt";
record = File.ReadAllText(path);
//print(record);
GameObject.Find("Canvas/Panel/Record").GetComponent<Text>().text = record;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TraceWizard.Entities;
namespace TraceWizard.TwApp {
public partial class FixtureSummaryPanel : UserControl {
public FixtureClass FixtureClass { get;set;}
public FixtureSummary FixtureSummary { get;set;}
public FixtureSummaryPanel() {
InitializeComponent();
}
public void Initialize() {
ToolTipService.SetShowDuration(textBlockInstancesCount, 30000);
ToolTipService.SetInitialShowDelay(textBlockInstancesCount, 500);
textBlockInstancesCount.MouseEnter +=new MouseEventHandler(textBlockInstancesCount_MouseEnter);
}
void textBlockInstancesCount_MouseEnter(object sender, MouseEventArgs e) {
FixtureSummary.Events.UpdateMedians();
textBlockInstancesCount.ToolTip = new EventsProperties(
FixtureClass, FixtureSummary.Events,
FixtureSummary.Events.Count);
;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// This script is responsible for playing the background music, regardless on whether or not we are in the main menu
// or the game itself.
public class BackgroundAudio : MonoBehaviour
{
private static BackgroundAudio instance = null;
public static BackgroundAudio Instance
{
get { return instance; }
}
void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
return;
}
else
{
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Model.BaseModels.Configuration
{
public class LoginSettings
{
public static JwtLoginSettings Jwt { get; set; }
public static string HashPasswordSalt { get; set; }
}
public class JwtLoginSettings
{
public string Issuer { get; set; }
public string SignKey { get; set; }
public string Audience { get; set; }
public int Expiration { get; set; }
}
}
|
namespace developer0223.Tools.Demo
{
// Unity
using UnityEngine;
public class FpsDisplayerSample : MonoBehaviour
{
private void Start()
{
CreateFpsDisplayer();
ModifyFpsDisplayer();
}
public void CreateFpsDisplayer()
{
// You can create and destroy FpsDisplayer like below.
// Default value of fontSize, DisplayPosition is 30 and upper left.
//FpsDisplayer sample_01 = FpsDisplayer.GetOrCreate();
//FpsDisplayer sample_02 = FpsDisplayer.GetOrCreate(30);
FpsDisplayer sample_03 = FpsDisplayer.GetOrCreate(75, DisplayPosition.UpperRight);
}
public void ModifyFpsDisplayer()
{
FpsDisplayer fpsDisplayer = FpsDisplayer.GetOrCreate();
// Text Size
fpsDisplayer.SetFontSize(50);
// Text Color
//fpsDisplayer.SetTextColor(Color.red);
//fpsDisplayer.SetTextColor(new Color(1, 1, 1));
//fpsDisplayer.SetTextColor(new Color(1, 1, 1, 0.5f));
//fpsDisplayer.SetTextColor(new Vector4(1, 1, 1, 0.5f));
fpsDisplayer.SetTextColor(new Color32(0, 255, 0, 255));
// DisplayPosition
fpsDisplayer.SetDisplayPosition(DisplayPosition.MiddleCenter);
}
public void DestroyFpsDisplayer()
{
FpsDisplayer.Destroy();
}
}
} |
using System.Collections.Generic;
using UsersLib.Entity;
namespace UsersLib.DbControllers
{
public interface IDbUserController
{
List<User> GetUsers();
User GetUser( int userId );
Dictionary<User, List<Group>> GetUsersByGroups();
List<Group> GetUserGroups( int userId );
void SaveUser( User user );
void SaveUserGroups( int userId, List<int> userGroupIds );
void DeleteUser(int userId);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;
namespace _4._1_DirectoryInfo
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\");
Debug.WriteLine("Directories in C drive:");
foreach(DirectoryInfo di in directoryInfo.GetDirectories())
{
Debug.WriteLine(di.Name);
}
//Criar diretorios
var directory = Directory.CreateDirectory(@"C:\Temp2\Directory");
var directoryCreate = new DirectoryInfo(@"C:\Temp2\DirectoryInfo");
directoryCreate.Create();
//Deletar
/*if (Directory.Exists(@"C:\Temp2\Directory"))
{
Console.WriteLine("Deletando pasta 'C:\\Temp2\\Directory'");
Directory.Delete(@"C:\Temp2\Directory");
}
if (directoryCreate.Exists)
{
directoryCreate.Delete();
}*/
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
System.Security.Principal.NTAccount acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount;
string strEveryoneAccount = acct.ToString();
//Controle de acesso as pastas
//No caso abaixo não permitir a deleção de uma determinada pasta por um determinado usuario
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.AddAccessRule(new FileSystemAccessRule(@"DESKTOP\FulanoX", FileSystemRights.Delete, AccessControlType.Deny));
directoryCreate.SetAccessControl(directorySecurity);
Console.ReadLine();
}
}
}
|
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 BMI
{
public partial class Form1 : Form
{
double height = 0;
double weight = 0;
double BMI =0;
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
txtBMI.BackColor = Color.White;
height = Double.Parse(txtHeight.Text);
weight = Double.Parse(txtWeight.Text);
BMI = weight / (height * height) * 703;
txtBMI.Text = String.Format("{0:f}", BMI);
string BMI_description = string.Empty;
if ( BMI < 18.5)
{
txtBMI.BackColor = Color.Pink;
lblMsg.Text = "You are underweight.";
}
else if (BMI <= 24.9)
{
txtBMI.BackColor = Color.LightSeaGreen;
lblMsg.Text = "Congrats! You have healthy weight.";
}
else if (BMI <= 29.9)
{
txtBMI.BackColor = Color.Yellow;
lblMsg.Text = "You are overweight.";
}
else if (BMI <= 34.9)
{
txtBMI.BackColor = Color.OrangeRed;
lblMsg.Text = "You are obese!";
}
else if (BMI >= 40)
{
txtBMI.BackColor = Color.Red;
lblMsg.Text = "Alert! Morbid obesity.";
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtHeight.Clear();
txtWeight.Clear();
txtBMI.Clear();
lblMsg.Text = "";
txtBMI.Text = "";
txtBMI.BackColor = Color.White;
}
}
} |
using UnityEngine;
using System.Collections;
using System;
public class Heap<T> where T : IHeapItem<T>
{
private T[] items;
private int currentItemCount;
public Heap ( int _maxHeapSize )
{
items = new T[_maxHeapSize];
}
public void Add ( T _item )
{
_item.HeapIndex = currentItemCount;
items[currentItemCount] = _item;
SortUp(_item);
currentItemCount ++;
}
public T RemoveFirst ()
{
T firstItem = items[0];
currentItemCount --;
items[0] = items[currentItemCount];
items[0].HeapIndex = 0;
SortDown(items[0]);
return firstItem;
}
public bool Contains ( T _item )
{
return Equals(items[_item.HeapIndex],_item);
}
public void UpdateItem ( T _item )
{
SortUp(_item);
}
public int Count
{
get
{
return currentItemCount;
}
}
void SortDown ( T _item )
{
while ( true )
{
int childIndexLeft = _item.HeapIndex * 2 + 1;
int childIndexRight = _item.HeapIndex * 2 + 2;
int swapIndex = 0;
if ( childIndexLeft < currentItemCount )
{
swapIndex = childIndexLeft;
if ( childIndexRight < currentItemCount )
{
if ( items[childIndexLeft].CompareTo(items[childIndexRight]) < 0 )
{
swapIndex = childIndexRight;
}
}
if ( _item.CompareTo(items[swapIndex]) < 0 )
{
Swap(_item,items[swapIndex]);
}
else
{
return;
}
}
else
{
return;
}
}
}
void SortUp ( T _item )
{
int parentIndex = Mathf.RoundToInt((_item.HeapIndex - 1) * .5f);
while ( true )
{
T parentItem = items[parentIndex];
if ( _item.CompareTo(parentItem) > 0 )
{
Swap(_item,parentItem);
}
else
{
break;
}
parentIndex = Mathf.RoundToInt((_item.HeapIndex - 1) * .5f);
}
}
void Swap ( T _itemA, T _itemB )
{
items[_itemA.HeapIndex] = _itemB;
items[_itemB.HeapIndex] = _itemA;
int itemAIndex = _itemA.HeapIndex;
_itemA.HeapIndex = _itemB.HeapIndex;
_itemB.HeapIndex = itemAIndex;
}
}
public interface IHeapItem<T> : IComparable<T>
{
int HeapIndex
{
get;
set;
}
}
|
namespace DesignPatterns.State.SystemPermissionExample
{
public class PermissionGranted : PermissionState
{
public PermissionGranted()
{
name = "GRANTED";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace StringReplicator.Core.CodeGeneration
{
public class Resources
{
public const string History="History";
public const string String = "String";
public const string Session = "Session";
public const string Data = "Data";
public const string Database = "Database";
public const string Clean = "Clean";
public const string Test = "Test";
}
} |
using System.ComponentModel.DataAnnotations;
namespace ChatTest.App.Models
{
public class MessageCreateModel
{
[Required]
public string Text { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using UnityEngine;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
public class SystemTray : IDisposable
{
[DllImport("shell32.dll")]
static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, StringBuilder lpIconPath, out ushort lpiIcon);
public NotifyIcon trayIcon;
public ContextMenuStrip trayMenu;
public SystemTray(Icon icon)
{
trayMenu = new ContextMenuStrip();
trayIcon = new NotifyIcon();
trayIcon.Text = UnityEngine.Application.productName;
trayIcon.Icon = icon;
trayIcon.ContextMenuStrip = trayMenu;
trayIcon.Visible = true;
}
//Currently does not work
public void SetIcon(Texture2D icon)
{
using (MemoryStream ms = new MemoryStream(icon.EncodeToPNG()))
{
ms.Seek(0, SeekOrigin.Begin);
Bitmap bmp = new Bitmap(ms);
Icon tIcon = Icon.FromHandle(bmp.GetHicon());
trayIcon.Icon = tIcon;
}
}
public void SetTitle(string title)
{
trayIcon.Text = title;
}
public ToolStripItem AddItem(string label, Action function)
{
return trayMenu.Items.Add(label, null, (object sender, EventArgs e) =>
{
if (function != null)
{
function();
}
});
}
public void AddSeparator()
{
trayMenu.Items.Add("-");
}
public void AddDoubleClickEvent(Action action)
{
trayIcon.DoubleClick += (object sender, EventArgs e) =>
{
if (action != null)
{
action();
}
};
}
public void AddSingleClickEvent(Action action)
{
trayIcon.MouseDown += (object sender, MouseEventArgs e) =>
{
if (action != null)
{
action();
}
};
}
public void ShowNotification(int duration, string title, string text)
{
trayIcon.Visible = true;
trayIcon.BalloonTipTitle = title;
trayIcon.BalloonTipText = text;
trayIcon.BalloonTipIcon = ToolTipIcon.Info;
trayIcon.ShowBalloonTip(duration * 1000);
}
public void Dispose()
{
trayIcon.Visible = false;
trayMenu.Dispose();
trayIcon.Dispose();
}
}
|
using gView.DataSources.Fdb.MSSql;
using gView.Framework.Carto;
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.FDB;
using gView.Framework.Geometry;
using gView.Framework.system;
using gView.Framework.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.DataSources.Fdb.UI.MSSql
{
public class CreateTileGridClass : IProgressReporter
{
private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
private string _name, _cacheDirectory;
private IFeatureDataset _targetDataset;
private ISpatialIndexDef _spatialIndexDef;
private IRasterDataset _sourceDataset;
private double _tileSizeX, _tileSizeY, _resX, _resY;
private int _levels;
private bool _createTiles = true;
private gView.DataSources.Fdb.MSSql.SqlFDB _fdb = null;
private TileGridType _gridType = TileGridType.image_jpg;
private TileLevelType _levelType = TileLevelType.ConstantImagesize;
private CancelTracker _cancelTracker = new CancelTracker();
private List<int> _createLevels;
public CreateTileGridClass(
string name,
IFeatureDataset targetDataset,
ISpatialIndexDef spatialIndexDef,
IRasterDataset sourceDataset,
double tileSizeX, double tileSizeY,
double resX, double resY,
int levels,
string cacheDirectory,
TileGridType gridType)
{
_name = name;
_cacheDirectory = cacheDirectory;
_targetDataset = targetDataset;
_spatialIndexDef = spatialIndexDef;
_sourceDataset = sourceDataset;
_tileSizeX = tileSizeX;
_tileSizeY = tileSizeY;
_resX = resX;
_resY = resY;
_levels = levels;
_gridType = gridType;
_fdb = (SqlFDB)_targetDataset.Database;
_createLevels = new List<int>();
for (int i = 0; i < _levels; i++)
{
_createLevels.Add(i);
}
}
public bool CreateTiles
{
get { return _createTiles; }
set { _createTiles = value; }
}
public TileLevelType TileLevelType
{
get { return _levelType; }
set { _levelType = value; }
}
public List<int> CreateLevels
{
get { return _createLevels; }
set { _createLevels = value; }
}
// Thread
async private Task Run()
{
if (_targetDataset == null || _fdb == null || _sourceDataset == null)
{
return;
}
//if (_targetDataset[_name] != null)
//{
// MessageBox.Show("Featureclass '" + _name + "' already exists!");
// return;
//}
bool succeeded = false;
try
{
Envelope bounds = new Envelope(_spatialIndexDef.SpatialIndexBounds);
Envelope iBounds = new Envelope(bounds.minx - _tileSizeX, bounds.miny - _tileSizeY,
bounds.maxx + _tileSizeX, bounds.maxy + _tileSizeY);
_cacheDirectory += @"/" + _name;
if (!String.IsNullOrEmpty(_cacheDirectory))
{
DirectoryInfo di = new DirectoryInfo(_cacheDirectory);
if (!di.Exists)
{
di.Create();
}
StringBuilder sb = new StringBuilder();
sb.Append("<TileCacheDefinition>\r\n");
sb.Append(" <General levels='" + _levels + "' origin='lowerleft' />\r\n");
sb.Append(" <Envelope minx='" + bounds.minx.ToString(_nhi) + "' miny='" + bounds.miny.ToString(_nhi) + "' maxx='" + bounds.maxx.ToString(_nhi) + "' maxy='" + bounds.maxy.ToString(_nhi) + "' />\r\n");
sb.Append(" <TileSize x='" + _tileSizeX.ToString(_nhi) + "' y='" + _tileSizeY.ToString(_nhi) + "' />\r\n");
sb.Append(" <TileResolution x='" + _resX.ToString(_nhi) + "' y='" + _resY.ToString(_nhi) + "' />\r\n");
sb.Append("</TileCacheDefinition>");
StreamWriter sw = new StreamWriter(di.FullName + @"/tilecache.xml");
sw.WriteLine(sb.ToString());
sw.Close();
}
ProgressReport report = new ProgressReport();
int datasetId = await _fdb.DatasetID(_targetDataset.DatasetName);
if (datasetId == -1)
{
return;
}
IClass cls = null;
try
{
cls = (await _sourceDataset.Elements())[0].Class;
}
catch { cls = null; }
IMultiGridIdentify gridClass = cls as IMultiGridIdentify;
if (_gridType == TileGridType.binary_float && gridClass == null)
{
return;
}
IFeatureClass sourceFc = cls as IFeatureClass;
Map map = null;
if (_gridType == TileGridType.image_jpg || _gridType == TileGridType.image_png)
{
map = new Map();
ILayer layer = LayerFactory.Create(cls);
map.AddLayer(layer);
//map.iWidth = (int)(_tileSizeX / _resX);
//map.iHeight = (int)(_tileSizeY / _resY);
}
#region Create Featureclass
IFeatureClass fc = null;
IDatasetElement element = await _targetDataset.Element(_name);
if (element != null && element.Class is IFeatureClass)
{
fc = (IFeatureClass)element.Class;
if (fc.GeometryType == GeometryType.Polygon &&
fc.FindField("GRID_LEVEL") != null &&
fc.FindField("GRID_ROW") != null &&
fc.FindField("GRID_COLUMN") != null &&
fc.FindField("FILE") != null)
{
if (MessageBox.Show("TileGridClass already exists. Do you wan't to append to this Grid?",
"Warning",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes)
{
return;
}
}
else
{
await _fdb.DeleteFeatureClass(_name);
fc = null;
}
}
if (fc == null)
{
FieldCollection fields = new FieldCollection();
fields.Add(new Field("GRID_LEVEL", FieldType.integer));
fields.Add(new Field("GRID_ROW", FieldType.integer));
fields.Add(new Field("GRID_COLUMN", FieldType.integer));
fields.Add(new Field("FILE", FieldType.String, 512));
await _fdb.CreateFeatureClass(_targetDataset.DatasetName, _name,
new GeometryDef(GeometryType.Polygon),
fields);
element = await _targetDataset.Element(_name);
if (element == null || !(element.Class is IFeatureClass))
{
return;
}
await _fdb.SetSpatialIndexBounds(_name, "BinaryTree2", iBounds, _spatialIndexDef.SplitRatio, _spatialIndexDef.MaxPerNode, _spatialIndexDef.Levels);
fc = (IFeatureClass)element.Class;
}
#endregion
#region Create Tiles
#region Report
double tx = _tileSizeX, ty = _tileSizeY;
if (ReportProgress != null)
{
report.featureMax = 0;
for (int i = 0; i < _levels; i++)
{
if (_createLevels.Contains(i))
{
for (double y = bounds.miny; y < bounds.maxy; y += ty)
{
for (double x = bounds.minx; x < bounds.maxx; x += tx)
{
report.featureMax++;
}
}
}
if (_levelType == TileLevelType.ConstantImagesize)
{
tx *= 2;
ty *= 2;
}
}
report.Message = "Create Tiles";
report.featurePos = 0;
ReportProgress(report);
}
int reportInterval = (_createTiles ? 10 : 1000);
#endregion
List<IFeature> features = new List<IFeature>();
for (int level = 0; level < _levels; level++)
{
if (map != null)
{
map.iWidth = (int)(_tileSizeX / _resX);
map.iHeight = (int)(_tileSizeY / _resY);
}
if (_createLevels.Contains(level))
{
int row = 0;
for (double y = bounds.miny; y < bounds.maxy; y += _tileSizeY)
{
DirectoryInfo di = new DirectoryInfo(_cacheDirectory + @"/" + level + @"/" + row);
if (!di.Exists)
{
di.Create();
}
int column = 0;
for (double x = bounds.minx; x < bounds.maxx; x += _tileSizeX)
{
#region Polygon
Polygon polygon = new Polygon();
Ring ring = new Ring();
ring.AddPoint(new Point(x, y));
ring.AddPoint(new Point(Math.Min(x + _tileSizeX, bounds.maxx), y));
ring.AddPoint(new Point(Math.Min(x + _tileSizeX, bounds.maxx), Math.Min(y + _tileSizeY, bounds.maxy)));
ring.AddPoint(new Point(x, Math.Min(y + _tileSizeY, bounds.maxy)));
ring.Close();
polygon.AddRing(ring);
#endregion
if (sourceFc != null)
{
SpatialFilter filter = new SpatialFilter();
filter.AddField(sourceFc.IDFieldName);
filter.Geometry = polygon;
filter.FilterSpatialReference = fc.SpatialReference;
using (IFeatureCursor cursor = await sourceFc.GetFeatures(filter))
{
if (await cursor.NextFeature() == null)
{
column++;
report.featurePos++;
if (ReportProgress != null && report.featurePos % reportInterval == 0)
{
ReportProgress(report);
}
continue;
}
}
}
string relFilename = level + "/" + row + "/" + column + ".bin";
if (_createTiles)
{
string filename = di.FullName + @"/" + column;
if (_gridType == TileGridType.binary_float)
{
float[] vals = await gridClass.MultiGridQuery(
null,
new IPoint[] { ring[0], ring[1], ring[3] },
_resX, _resY,
fc.SpatialReference, null);
if (!HasFloatArrayData(vals))
{
column++;
report.featurePos++;
if (ReportProgress != null && report.featurePos % reportInterval == 0)
{
ReportProgress(report);
}
continue;
}
StoreFloatArray(filename + ".bin", x, y, _resX, _resY, vals);
}
else if (map != null)
{
map.ZoomTo(new Envelope(x, y, x + _tileSizeX, y + _tileSizeY));
await map.RefreshMap(DrawPhase.All, _cancelTracker);
if (_gridType == TileGridType.image_png)
{
map.Bitmap.Save(filename + ".png", GraphicsEngine.ImageFormat.Png);
}
else if (_gridType == TileGridType.image_jpg)
{
map.Bitmap.Save(filename + ".jpg", GraphicsEngine.ImageFormat.Jpeg);
}
}
}
Feature feature = new Feature();
feature.Shape = polygon;
feature.Fields.Add(new FieldValue("GRID_LEVEL", level));
feature.Fields.Add(new FieldValue("GRID_ROW", row));
feature.Fields.Add(new FieldValue("GRID_COLUMN", column));
feature.Fields.Add(new FieldValue("FILE", relFilename));
features.Add(feature);
column++;
report.featurePos++;
if (features.Count >= reportInterval)
{
if (ReportProgress != null)
{
ReportProgress(report);
}
if (!await _fdb.Insert(fc, features))
{
MessageBox.Show(_fdb.LastErrorMessage, "DB Insert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
features.Clear();
if (!_cancelTracker.Continue)
{
succeeded = true;
return;
}
}
}
row++;
}
}
if (_levelType == TileLevelType.ConstantImagesize)
{
_tileSizeX *= 2;
_tileSizeY *= 2;
}
_resX *= 2;
_resY *= 2;
}
if (features.Count > 0)
{
if (ReportProgress != null)
{
ReportProgress(report);
}
await _fdb.Insert(fc, features);
}
await _fdb.CalculateExtent(fc);
#endregion
succeeded = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (!succeeded)
{
await _fdb.DeleteFeatureClass(_name);
}
}
}
public Task RunTask()
{
return this.Run();
}
#region IProgressReporter Member
public event ProgressReporterEvent ReportProgress = null;
public gView.Framework.system.ICancelTracker CancelTracker
{
get { return _cancelTracker; }
}
#endregion
#region Helper
private bool StoreFloatArray(string filename, double x, double y, double resX, double resY, float[] f)
{
StreamWriter sw = new StreamWriter(filename);
BinaryWriter bw = new BinaryWriter(sw.BaseStream);
bw.Write(x);
bw.Write(y);
bw.Write(resX);
bw.Write(resY);
foreach (float v in f)
{
bw.Write(v);
}
sw.Close();
return true;
}
private bool HasFloatArrayData(float[] f)
{
float nodata = float.MinValue;
for (int i = 2; i < f.Length; i++) // 0 und 1 sind die GridSize
{
if (f[i] != nodata)
{
return true;
}
}
return false;
}
#endregion
}
}
|
using Compent.Shared.DependencyInjection.Contract;
using Localization.Core;
using Localization.Core.Configuration;
using Localization.Storage.UDictionary;
using System.Configuration;
using UBaseline.Core.RequestContext;
using Uintra.Core.Authentication;
using Uintra.Core.Controls.LightboxGallery;
using Uintra.Core.Localization;
using Uintra.Core.Updater;
using Uintra.Core.Updater._2._0;
using Uintra.Features.Information;
using Uintra.Features.Media.Enums;
using Uintra.Features.Media.Helpers;
using Uintra.Features.Media.Images.Helpers.Contracts;
using Uintra.Features.Media.Images.Helpers.Implementations;
using Uintra.Features.Media.Intranet.Services.Contracts;
using Uintra.Features.Media.Intranet.Services.Implementations;
using Uintra.Features.Media.Video.Converters.Contracts;
using Uintra.Features.Media.Video.Converters.Implementations;
using Uintra.Features.Media.Video.Helpers.Contracts;
using Uintra.Features.Media.Video.Helpers.Implementations;
using Uintra.Features.Media.Video.Services.Contracts;
using Uintra.Features.Media.Video.Services.Implementations;
using Uintra.Features.Permissions;
using Uintra.Features.Permissions.Implementation;
using Uintra.Features.Permissions.Interfaces;
using Uintra.Features.Permissions.TypeProviders;
using Uintra.Features.Subscribe;
using Uintra.Infrastructure.ApplicationSettings;
using Uintra.Infrastructure.Caching;
using Uintra.Infrastructure.Context;
using Uintra.Infrastructure.Providers;
using Uintra.Infrastructure.TypeProviders;
using Uintra.Infrastructure.Utils;
namespace Uintra.Infrastructure.Ioc
{
public class UintraInjectModule : IInjectModule
{
public IDependencyCollection Register(IDependencyCollection services)
{
//configurations
services.AddSingleton<IApplicationSettings, ApplicationSettings.ApplicationSettings>();
//services
services.AddSingleton<IInformationService, InformationService>();
services.AddSingleton<IDocumentTypeAliasProvider, DocumentTypeProvider>();
services.AddSingleton<IIntranetMemberGroupService, IntranetMemberGroupService>();
services.AddSingleton<IPermissionSettingsSchemaProvider, PermissionSettingsSchemaProvider>();
services.AddSingleton<IContentPageContentProvider, ContentPageContentProvider>();
services.AddSingleton(i =>
(ILocalizationConfigurationSection) ConfigurationManager.GetSection("localizationConfiguration"));
services.AddScoped<ICacheService, MemoryCacheService>();
services.AddScoped<IEmbeddedResourceService, EmbeddedResourceService>();
services.AddScoped<IMediaHelper, MediaHelper>();
services.AddScoped<IMediaFolderTypeProvider>(provider => new MediaFolderTypeProvider(typeof(MediaFolderTypeEnum)));
services.AddScoped<IImageHelper, ImageHelper>();
services.AddScoped<IVideoConverter, VideoConverter>();
services.AddScoped<IIntranetMediaService, IntranetMediaService>();
services.AddScoped<IIntranetMemberGroupProvider, IntranetMemberGroupProvider>();
services.AddScoped<IPermissionsService, PermissionsService>();
services.AddScoped<IPermissionActionTypeProvider>(provider =>
new PermissionActionTypeProvider(typeof(PermissionActionEnum)));
services.AddScoped<IPermissionResourceTypeProvider>(provider =>
new PermissionActivityTypeProvider(typeof(PermissionResourceTypeEnum)));
services.AddScoped<IDateTimeFormatProvider, DateTimeFormatProvider>();
services.AddScoped<IClientTimezoneProvider, ClientTimezoneProvider>();
services.AddScoped<ICookieProvider, CookieProvider>();
services.AddScoped<ISubscribeService, SubscribeService>();
services.AddScoped<IAuthenticationService, AuthenticationService>();
services.AddScoped<IIntranetLocalizationService, LocalizationService>();
services.AddScoped<ILocalizationCoreService, LocalizationCoreService>();
services.AddScoped<ILocalizationStorageService, LocalizationStorageService>();
services.AddScoped<ILocalizationCacheProvider, LocalizationMemoryCacheProvider>();
services.AddScoped<ILocalizationCacheService, LocalizationCacheService>();
services.AddScoped<ILocalizationSettingsService, LocalizationSettingsService>();
services.AddScoped<ILocalizationResourceCacheService, LocalizationResourceCacheService>();
services.AddScoped<ILightboxHelper, LightboxHelper>();
services.AddScoped<IUBaselineRequestContext, IntranetRequestContext>();
services.AddTransient<IVideoHelper, VideoHelper>();
services.AddTransient<IVideoConverterLogService, VideoConverterLogService>();
services.AddScoped<IMigrationHistoryService, MigrationHistoryService>();
services.AddScoped<IMigration, Migration>();
return services;
}
}
} |
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Cohorts
{
public class PostCreateCohortRequest : IPostApiRequest
{
public object Data { get; set; }
public string PostUrl => $"cohorts";
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
namespace WebPageTest.Models
{
public class Page
{
public string Url { get; set; }
public string Location { get; set; }
public string Browser { get; set; }
public string Connectivity { get; set; }
public string runs { get; set; }
public string DownloadBandwidth { get; set; }
public string UploadBandwidth { get; set; }
public string Latency { get; set; }
public int ReapeatView { get; set; }
public int isMobile { get; set; }
public string FormatConnectivity()
{
return $"{Location}:{Browser}.{Connectivity}";
}
}
} |
using System;
using com.Sconit.Entity.SCM;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.ORD
{
[Serializable]
public partial class OrderBinding : EntityBase, IAuditable
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Display(Name = "OrderBinding_OrderNo", ResourceType = typeof(Resources.ORD.OrderBinding))]
public string OrderNo { get; set; }
[Display(Name = "OrderBinding_BindFlow", ResourceType = typeof(Resources.ORD.OrderBinding))]
public string BindFlow { get; set; }
[Display(Name = "OrderBinding_BindFlowStrategy", ResourceType = typeof(Resources.ORD.OrderBinding))]
public com.Sconit.CodeMaster.FlowStrategy BindFlowStrategy { get; set; }
[Display(Name = "OrderBinding_BindOrderNo", ResourceType = typeof(Resources.ORD.OrderBinding))]
public string BindOrderNo { get; set; }
//public Int32 BindOrderDetailId { get; set; }
[Display(Name = "OrderBinding_BindType", ResourceType = typeof(Resources.ORD.OrderBinding))]
public com.Sconit.CodeMaster.BindType BindType { 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 Int32 Version { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
OrderBinding another = obj as OrderBinding;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
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 lab_023
{
public partial class Form1 : Form
{
string filename = @"C:\Text1.txt";
public Form1()
{
InitializeComponent();
textBox1.Multiline = true;
textBox1.Clear();
textBox1.TabIndex = 0;
textBox1.Size = new Size(268, 112);
button1.Text = "Открыть";
button1.TabIndex = 0;
button2.Text = "Сохранить";
base.Text = "Здесь кодировка Unicode";
}
private void button1_Click(object sender, EventArgs e)
{
try
{
var reader = new System.IO.StreamReader(filename);
textBox1.Text = reader.ReadToEnd();
reader.Close();
}
catch (System.IO.FileNotFoundException ex)
{
MessageBox.Show(ex.Message + "\nНет такого файла",
"Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
var writer = new System.IO.StreamWriter(filename, false);
writer.Write(textBox1.Text);
writer.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Zombies3
{
enum PickupType
{
None,
Health,
Shotgun,
AK47,
Uzi,
Gauss
}
class Pickup : GameObject
{
PickupType type;
Random random = new Random();
public Pickup(Game game)
: base(game)
{
this.game = game;
}
public Pickup(Game game, Vector2 position)
: base(game, position)
{
this.game = game;
this.position = position;
}
public override void Initialize()
{
spriteName = "Pickup";
solid = false;
alive = false;
boundsHeight = 25;
boundsWidth = 25;
base.Initialize();
}
public PickupType PickUp()
{
alive = false;
return PickupType.Uzi;
switch (random.Next(1, 5))
{
case 1:
return PickupType.Health;
case 2:
return PickupType.AK47;
case 3:
return PickupType.Shotgun;
case 4:
return PickupType.Uzi;
}
return PickupType.None;
}
}
}
|
using System;
using System.Text;
namespace EschoZadachka
{
class VetoEventArgs : EventArgs
{
public string Proposal { get; set; }
public VetoVoter VetoBy { get; set; }
}
class VetoComission
{
public event EventHandler<VetoEventArgs> OnVote;
public VetoEventArgs Vote(string proposal)
{
var args = new VetoEventArgs() { Proposal = proposal };
OnVote?.Invoke(this, args);
return args;
}
}
class VetoVoter
{
public string Name { get; set; }
public void VetoVoteHandler(object sender, VetoEventArgs args)
{
Random random = new Random();
if(random.Next(0, 5) == 0)
args.VetoBy ??= this;
}
}
class Program
{
static void Main(string[] args)
{
VetoComission comission = new VetoComission();
VetoVoter[] voters = new VetoVoter[5];
for (int i = 0; i < voters.Length; i++)
{
voters[i] = new VetoVoter() { Name = GetName() };
comission.OnVote += voters[i].VetoVoteHandler;
}
VetoEventArgs result = comission.Vote("Запретить перед сессией студентам доступ в интернет, чтобы они не смотрели видео с котиками?");
Console.WriteLine($"Вопрос голосования: \"{result.Proposal}\"\n");
Console.WriteLine($"Вето наложено: {result.VetoBy?.Name ?? "а никем не наложено (все согласны)"}");
}
static string GetName()
{
Random random = new Random();
StringBuilder name = new StringBuilder();
name.Append((char)random.Next('A', 'Z'));
for (int i = 0; i < random.Next(0, 10); i++)
name.Append((char)random.Next('a', 'z'));
return name.ToString();
}
}
}
|
using Sfa.Poc.ResultsAndCertification.CsvHelper.Application.Model;
using Sfa.Poc.ResultsAndCertification.CsvHelper.Common.CsvHelper.Model;
using Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Models;
using Sfa.Poc.ResultsAndCertification.CsvHelper.Models.BulkUpload;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Application.Interfaces
{
public interface IRegistrationService
{
Task<IEnumerable<CoreAndSpecialisms>> GetAllTLevelsByAoUkprnAsync(long ukPrn);
Task<IEnumerable<Registration>> ValidateRegistrationTlevelsAsync(long ukprn, IEnumerable<Registration> regdata);
Task<bool> SaveBulkRegistrationsAsync(IEnumerable<Registration> regdata, long ukprn);
Task ProcessRegistrations(IList<TqRegistration> registrations);
Task ReadRegistrations(IList<TqRegistration> registrations);
Task CompareRegistrations();
Task<BulkUploadResponse> CompareAndProcessRegistrations(IList<TqRegistrationProfile> importRegistrations);
IEnumerable<TqRegistrationProfile> TransformRegistrationModel(IList<Registration> stageTwoResponse, string performedBy);
Task<bool> CreateDocumentUploadHistory(DocumentUploadHistory documentUploadHistory);
}
}
|
namespace Crystal.Plot2D
{
/// <summary>
/// Represents a constraint which returns data rectangle, intersected with specified data domain.
/// </summary>
public class DomainConstraint : ViewportConstraint
{
/// <summary>
/// Initializes a new instance of the <see cref="DomainConstraint"/> class.
/// </summary>
public DomainConstraint() { }
/// <summary>
/// Initializes a new instance of the <see cref="DomainConstraint"/> class with given domain property.
/// </summary>
/// <param name="domain">
/// The domain.
/// </param>
public DomainConstraint(DataRect domain)
{
Domain = domain;
}
private DataRect domain = new(-1, -1, 2, 2);
/// <summary>
/// Gets or sets the domain.
/// </summary>
/// <value>
/// The domain.
/// </value>
public DataRect Domain
{
get { return domain; }
set
{
if (domain != value)
{
domain = value;
RaiseChanged();
}
}
}
/// <summary>
/// Applies the specified old data rect.
/// </summary>
/// <param name="oldDataRect">The old data rect.</param>
/// <param name="newDataRect">The new data rect.</param>
/// <param name="viewport">The viewport.</param>
/// <returns></returns>
public override DataRect Apply(DataRect oldDataRect, DataRect newDataRect, Viewport2D viewport)
{
DataRect res = domain;
if (domain.IsEmpty)
{
res = newDataRect;
}
else if (newDataRect.IntersectsWith(domain))
{
res = newDataRect;
if (newDataRect.Size == oldDataRect.Size)
{
if (res.XMin < domain.XMin)
{
res.XMin = domain.XMin;
}
if (res.YMin < domain.YMin)
{
res.YMin = domain.YMin;
}
if (res.XMax > domain.XMax)
{
res.XMin += domain.XMax - res.XMax;
}
if (res.YMax > domain.YMax)
{
res.YMin += domain.YMax - res.YMax;
}
}
else
{
res = DataRect.Intersect(newDataRect, domain);
}
}
return res;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using Unity.Mathematics;
using UnityEngine;
public class GunAnimatorManager : MonoBehaviour
{
Animator anim;
public GameObject rotationHandler;
public float rotationDamper;
public float rotationLimit;
bool pausing = false;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (pausing)
return;
float x = Input.GetAxis("Vertical");
float y = Input.GetAxis("Horizontal");
if (x == 0 && y == 0)
{
anim.SetBool("walking", false);
}
else
{
anim.SetBool("walking", true);
}
float locX = Mathf.Lerp(x / 10, 0, .1f);
float locZ = Mathf.Lerp(y / 10, 0, .1f);
rotationHandler.transform.localPosition = new Vector3(-locZ, 0, -locX);
float rotX = Input.GetAxis("Mouse Y") * 5;
float rotY = Input.GetAxis("Mouse X") * 5;
float finalX = Mathf.Clamp(rotX / rotationDamper, -rotationLimit, rotationLimit);
float finalY = Mathf.Clamp(rotY / rotationDamper, -rotationLimit, rotationLimit);
rotationHandler.transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.Euler(finalX, finalY, 0), .1f);
}
public void fireWeapon()
{
anim.SetTrigger("Fire");
Debug.Log("Firing");
}
public void playerInPauseMenu(bool pause)
{
pausing = pause;
}
public void OnEnable()
{
PauseMenu.OnPause += playerInPauseMenu;
}
public void OnDisable()
{
PauseMenu.OnPause -= playerInPauseMenu;
}
}
|
// <copyright file="Person.cs" company="Softuni">
// Copyright (c) 2014 All Rights Reserved
// <author>Me</author>
// </copyright>
namespace HWDefiningClassesTask01Persons
{
using System;
using System.Text;
public class Person
{
private string name;
private byte age;
private string mail;
public Person(string name, byte age, string mail)
{
this.Name = name;
this.Age = age;
this.Mail = mail;
}
public Person(string name, byte age)
: this(name, age, null)
{
}
public string Name
{
get
{
return this.name;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("Name", "Name must be non empty or null!");
}
this.name = value;
}
}
public byte Age
{
get
{
return this.age;
}
set
{
if (value < 1 || value > 100)
{
throw new ArgumentOutOfRangeException("Age", "Age must be between 1 and 100!");
}
this.age = value;
}
}
public string Mail
{
get
{
if (string.IsNullOrEmpty(this.mail))
{
return "N/A";
}
return this.mail;
}
set
{
if (value != null && !value.Contains("@"))
{
throw new ArgumentException("Mail cannot be empty string and must be valid email or null!", "Mail");
}
this.mail = value;
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
string name = string.Format("Name: {0}", this.Name);
string age = string.Format(" Age: {0}", this.Age);
string mail = string.Format("Mail: {0}", this.Mail);
int maxLength = Utils.GetMaxLength(new string[] { name, age, mail });
sb.AppendLine(string.Format("{0}{1}{2}", '\u2554', new string('\u2550', maxLength), '\u2557'));
sb.AppendLine(string.Format("{0}{1}{0}", '\u2551', name.PadRight(maxLength, ' ')));
sb.AppendLine(string.Format("{0}{1}{0}", '\u2551', age.PadRight(maxLength, ' ')));
sb.AppendLine(string.Format("{0}{1}{0}", '\u2551', mail.PadRight(maxLength, ' ')));
sb.AppendLine(string.Format("{0}{1}{2}", '\u255A', new string('\u2550', maxLength), '\u255D'));
return sb.ToString();
}
}
}
|
using UnityEngine;
using System.Collections;
using UnitySpineImporter;
public class PlayerAnimation : CharacterAnimation {
public SkinController skin {
get;
private set;
}
public Animator animator {
get;
private set;
}
void Awake() {
skin = GetComponent<SkinController>();
animator = GetComponent<Animator>();
}
void Update() {
AnimationInfo[] animations = animator.GetCurrentAnimationClipState(0);
animator.speed = 1f;
foreach (AnimationInfo info in animations) {
if (info.clip.name == "Run" && info.weight >= 0.9f) {
animator.speed = Mathf.Min(3f, Mathf.Abs(transform.parent.rigidbody2D.velocity.x / 3f));
break;
}
}
}
}
|
using System.Collections.Generic;
using com.Sconit.Entity.INP;
using com.Sconit.Entity.INV;
using com.Sconit.Entity.ISS;
using com.Sconit.Entity.ORD;
using com.Sconit.Entity.SCM;
using com.Sconit.Entity.CUST;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.BIL;
using com.Sconit.Entity.TMS;
using com.Sconit.Entity.WMS;
using com.Sconit.Entity.FMS;
namespace com.Sconit.Service
{
public interface INumberControlMgr
{
string GetNextSequenceo(string codePrefix);
string GetOrderNo(OrderMaster orderMaster);
string GetIpNo(IpMaster ipMaster);
string GetReceiptNo(ReceiptMaster receiptMaster);
string GetStockTakeNo(StockTakeMaster stockTake);
string GetIssueNo(IssueMaster issueMaster);
string GetInspectNo(InspectMaster inspectMaster);
string GetPickListNo(PickListMaster pickListMaster);
string GetRejectNo(RejectMaster rejectMaster);
string GetSequenceNo(SequenceMaster sequenceMaster);
string GetConcessionNo(ConcessionMaster concessionOrder);
string GetMiscOrderNo(MiscOrderMaster miscOrderMaster);
string GetVehicleInFactoryNo(VehicleInFactoryMaster vehicleInFactoryMaster);
string GetKanBanCardNo();
string GetBillNo(BillMaster billMaster);
string GetTransportOrderNo(TransportOrderMaster transportOrderMaster);
IDictionary<string, decimal> GetHuId(FlowDetail flowDetail);
IDictionary<string, decimal> GetHuId(OrderDetail orderDetail);
IDictionary<string, decimal> GetHuId(IpDetail ipDetail);
IDictionary<string, decimal> GetHuId(ReceiptDetail receiptDetail);
IDictionary<string, decimal> GetHuId(Item item);
string GetContainerId(string prefix);
IDictionary<string, decimal> GetHuId(string lotNo, string item, string manufactureParty, decimal qty, decimal unitCount);
string GetNextSequence(string code);
string GetShipmentNo();
string GetTaskNo(string prefix);
IDictionary<string, decimal> GetDeliveryBarCode(ShipPlan shipPlan);
string GetPackingListCode();
string GetTransportBillNo(TransportBillMaster billMaster);
string GetFCID(FacilityMaster facilityMaster);
string GetTraceCode();
string GetPalletCode();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core.DAL;
using Core.BIZ;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WinForm.Views
{
public partial class frmThongKeTonKho : Form
{
public frmThongKeTonKho(Form parent)
{
InitializeComponent();
_frmParent = parent;
}
#region Private Properties
private Form _frmParent;
private List<TheKho> _DMTheKho;
private decimal _tongLuongSach;
#endregion
#region Form Control Listen
private void frmThongKeTonKho_Load(object sender, EventArgs e)
{
//Load thẻ kho
loadTheKho();
}
private void dtpNgayGhi_ValueChanged(object sender, EventArgs e)
{
loadTheKho();
}
private void btnLoNhap_Click(object sender, EventArgs e)
{
frmThongKeLoNhap form = new frmThongKeLoNhap(this);
form.ShowDialog(this);
}
private void btnLoXuat_Click(object sender, EventArgs e)
{
frmThongKeLoXuat form = new frmThongKeLoXuat(this);
form.ShowDialog(this);
}
private void btnLoc_Click(object sender, EventArgs e)
{
}
private void txbLoc_KeyDown(object sender, KeyEventArgs e)
{
}
private void txbLoc_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void btnThoat_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region Form Services
public void loadTheKho()
{
_DMTheKho = TheKhoManager.getAllByDate(dtpNgayGhi.Value);
gdvTheKho.DataSource = _DMTheKho;
_tongLuongSach = _DMTheKho.Sum(tk => tk.SoLuong);
lbTongLuongSach.Text = _tongLuongSach.ToString();
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Bạn có muốn xuất tạo file báo cáo", "Thông báo", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var printer = new PrintHelper();
string x = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "";
string tenfile = x + "ReportTonKho.pdf";
printer.FileName = tenfile;
printer.FolderPath = "D://Report";
printer.Title = "Báo cáo tồn kho";
printer.printTonKho(_DMTheKho, dtpNgayGhi.Value);
MessageBox.Show("Đã tạo file thành công , Tên file là : " + tenfile);
//var redListTextFont = FontFactory.RegisterDirectory(Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts");
//var _bold = FontFactory.GetFont("Times New Roman", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10f,iTextSharp.text.Font.BOLD, BaseColor.BLACK);
//var _bold1 = FontFactory.GetFont("Times New Roman", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10f, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
//PdfPTable pdfTable = new PdfPTable(gdvTheKho.ColumnCount);
//pdfTable.DefaultCell.Padding = 3;
//pdfTable.WidthPercentage = 30;
//pdfTable.HorizontalAlignment = Element.ALIGN_CENTER;
//pdfTable.DefaultCell.BorderWidth = 1;
//pdfTable.TotalWidth = 350f;
//pdfTable.LockedWidth = true;
//float[] widths = new float[] { 50f, 100f, 100f, 100f };
//pdfTable.SetWidths(widths);
////Adding Header row
//foreach (DataGridViewColumn column in gdvTheKho.Columns)
//{
// PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText,_bold));
// cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
// pdfTable.AddCell(cell);
//}
////Adding DataRow
//foreach (DataGridViewRow row in gdvTheKho.Rows)
//{
// foreach (DataGridViewCell cell in row.Cells)
// {
// if (!String.IsNullOrEmpty(Convert.ToString(cell.Value)))
// pdfTable.AddCell(new Phrase(cell.Value.ToString(),_bold1));
// }
//}
////Exporting to PDF
//string folderPath = @"D:\Report\";
//string x = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-"+ DateTime.Now.Hour + "-"+ DateTime.Now.Minute +"-"+ DateTime.Now.Second + "";
//string tenfile = x + "ReportTonKho.pdf";
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
//using (FileStream stream = new FileStream(folderPath + tenfile, FileMode.Create))
//{
// Document pdfDoc = new Document(PageSize.A3, 100f, 100f, 100f, 0);
// PdfWriter.GetInstance(pdfDoc, stream);
// pdfDoc.Open();
// var FontColour = new BaseColor(255, 0, 0);
// var _bold2 = FontFactory.GetFont("Times New Roman", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 20f, iTextSharp.text.Font.NORMAL, BaseColor.BLUE);
// Paragraph docTitle = new Paragraph("Thống kê tồn kho ngày : " + dtpNgayGhi.Value.Day + "-" + dtpNgayGhi.Value.Month + "-" + dtpNgayGhi.Value.Year + "\n", _bold2);
// Paragraph docTitle1 = new Paragraph("Tổng số lượng sách : " + lbTongLuongSach.Text + "\n", _bold2);
// docTitle.Alignment = Element.ALIGN_LEFT;
// docTitle1.Alignment = Element.ALIGN_LEFT;
// pdfDoc.Add(docTitle);
// pdfDoc.Add(docTitle1);
// pdfDoc.Add(new Paragraph("\n"));
// pdfDoc.Add(new Paragraph("\n"));
// pdfDoc.Add(pdfTable);
// pdfDoc.Close();
// stream.Close();
// MessageBox.Show("Đã tạo file thành công , Tên file là : " + tenfile);
//}
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SoundServant.Controls
{
/// <summary>
/// Interaction logic for NavTab.xaml
/// </summary>
public partial class NavTab : UserControl
{
public event MouseButtonEventHandler Clicked;
private bool isSelected = false;
bool enabled = false;
public bool Enabled
{
get
{
return enabled;
}
set
{
if (value == true)
{ this.IsEnabled = true; enabled = true; }
else if (value == false) { this.IsEnabled = false; enabled = false; }
}
}
public NavTab()
{
InitializeComponent();
IsEnabledChanged += new DependencyPropertyChangedEventHandler(NavTab_IsEnabledChanged);
}
void NavTab_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue == true)
{
if (isSelected)
{
TabLabel.Foreground = Brushes.Black;
}
else
{
TabLabel.Foreground = Brushes.White;
}
}
if ((bool)e.NewValue == false)
{
TabLabel.Foreground = Brushes.DarkGray;
}
}
public UIElement TabPage;
Brush selectedBgBrush = Brushes.White;
Brush unSelectedBgBrush = Brushes.Black;
Brush selectedFgBrush = Brushes.Black;
Brush unSelectedFgBrush = Brushes.White;
public Brush BgBrush { get { return unSelectedBgBrush; } set { unSelectedBgBrush = value; if (!isSelected) Tab.Background = value; } }
public String NavTitle { get { return TabLabel.Content.ToString(); } set { TabLabel.Content = value; } }
public void Select()
{
isSelected = true;
SelectedOverlay.Visibility = Visibility.Visible;
TabLabel.FontWeight = FontWeights.Bold;
TabLabel.Foreground = Brushes.Black;
}
public void Unselect()
{
isSelected = false;
SelectedOverlay.Visibility = Visibility.Collapsed;
TabLabel.FontWeight = FontWeights.Normal;
if (this.IsEnabled == true)
TabLabel.Foreground = Brushes.White;
else
TabLabel.Foreground = Brushes.DarkGray;
}
public void Click(MouseButtonEventArgs _e)
{
if (!isSelected)
{
Select();
if (Clicked != null) Clicked(this, _e);
}
}
private void Tab_MouseDown(object sender, MouseButtonEventArgs e)
{
if (!isSelected)
{
Select();
if (Clicked != null) Clicked(this, e);
}
}
}
}
|
using Nac.Common;
using Nac.Common.Control;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Nac.Engine.Control {
[DataContract]
public class NacEngineTask : NacEngineObjectWithChildren {
[DataMember]
public new NacTask Base { get { return base.Base as NacTask; } set { base.Base = value; } }
public NacEngineTask(NacTask task) : base(task) { }
public IEnumerable<NacEngineSection> Sections { get { return Children.Cast<NacEngineSection>();} }
public TimeSpan CycleTime { get { return Base.CycleTime; } }
public TimeSpan CycleCountdown { get { return Base.CycleCountdown; } set { Base.CycleCountdown = value; } }
private DateTime _lastExec = default(DateTime);
public void Execute() {
DateTime now = DateTime.Now;
var _countdown = CycleTime - (now - _lastExec);
if (_countdown > TimeSpan.Zero) { CycleCountdown = _countdown; return; }
CycleCountdown = TimeSpan.Zero;
_lastExec = now;
foreach (var section in Sections) section.Execute();
}
}
}
|
using AspectCore.Extensions.DependencyInjection;
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using WebApplication1.Extend;
namespace WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 在asp.net core项目中,可以借助于asp.net core的依赖注入,简化代理类对象的注入,
// 不用再自己调用 ProxyGeneratorBuilder 进行代理类对象的注入了。
//services.AddScoped<Person>();
RegisterServices(this.GetType().Assembly, services);
// Install-Package AspectCore.Extensions.DependencyInjection
// 让aspectcore接管注入
return services.BuildDynamicProxyProvider();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// 部署到不同服务器的时候不能写成127.0.0.1或者0.0.0.0,因为这是让服务消费者调用的地址
string ip = Configuration["ip"];
int port = int.Parse(Configuration["port"]);
// 向consul注册服务
ConsulClient client = new ConsulClient(ConfigurationOverview);
Task<WriteResult> result = client.Agent.ServiceRegister(new AgentServiceRegistration()
{
// 服务编号,不能重复,用Guid最简单
ID = "apiservice1" + Guid.NewGuid(),
// 服务的名字
Name = "apiservice1",
// 我的ip地址(可以被其他应用访问的地址,本地测试可以用127.0.0.1,机房环境中一定要写自己的内网ip地址)
Address = ip,
// 我的端口
Port = port,
Check = new AgentServiceCheck()
{
// 服务停止多久后反注册
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
// 健康检查时间间隔,或者称为心跳间隔
Interval = TimeSpan.FromSeconds(10),
// 健康检查地址
HTTP = $"http://{ip}:{port}/api/health",
Timeout = TimeSpan.FromSeconds(5)
}
});
}
private static void ConfigurationOverview(ConsulClientConfiguration obj)
{
obj.Address = new Uri("http://127.0.0.1:8500");
obj.Datacenter = "dc1";
}
/// <summary>
/// 根据特性批量注入
///
/// 通过反射扫描所有Service类,只要类中有标记了CustomInterceptorAttribute的方法都算作服务实现类。
/// 为了避免一下子扫描所有类,所以RegisterServices还是手动指定从哪个程序集中加载。
/// </summary>
private static void RegisterServices(Assembly assembly, IServiceCollection services)
{
// 遍历程序集中的所有public类型
foreach (Type type in assembly.GetExportedTypes())
{
// 判断类中是否有标注了CustomInterceptorAttribute的方法
bool hasHystrixCommandAttr = type.GetMethods().Any(m => m.GetCustomAttribute(typeof(HystrixCommandAttribute)) != null);
if (hasHystrixCommandAttr)
{
services.AddSingleton(type);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chapter04_01
{
class CVector
{
public int theX;
public int theY;
public CVector(int aX, int aY)
{
theX = aX;
theY = aY;
}
public int this[int aIndex]
{
get
{
if (aIndex == 0) return (theX);
if (aIndex == 1) return (theY);
throw new IndexOutOfRangeException();
}
set
{
if (aIndex == 0)
{
theX = value;
}
else if (aIndex == 1)
{
theY = value;
}
else
{
throw new IndexOutOfRangeException();
}
}
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net;
namespace DataSiftTests
{
[TestClass]
public class Pylon : TestBase
{
private const string VALID_CSDL = "fb.content contains_any \"BMW, Mercedes, Cadillac\"";
private const string VALID_HASH = "58eb8c4b74257406547ab1ed3be346a8";
private const string VALID_NAME = "Example recording";
private DateTimeOffset VALID_START = DateTimeOffset.Now.AddDays(-30);
private DateTimeOffset VALID_END = DateTimeOffset.Now;
public dynamic DummyParameters
{
get
{
return new
{
analysis_type = "freqDist",
parameters = new
{
threshold = 5,
target = "fb.author.age"
}
};
}
}
#region Get
[TestMethod]
public void Get_Succeeds()
{
var response = Client.Pylon.Get();
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Get_By_Hash_Empty_Fails()
{
Client.Pylon.Get(hash: "");
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Get_By_Hash_Bad_Format_Fails()
{
Client.Pylon.Get(hash: "invalid");
}
[TestMethod]
public void Get_By_Hash_Complete_Succeeds()
{
var response = Client.Pylon.Get(hash: VALID_HASH);
Assert.AreEqual(VALID_HASH, response.Data.hash);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Get_Page_Is_Less_Than_One_Fails()
{
Client.Pylon.Get(page: 0);
}
[TestMethod]
public void Get_Page_Succeeds()
{
var response = Client.Pylon.Get(page: 1);
Assert.AreEqual(1, response.Data.Count);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Get_Per_Page_Is_Less_Than_One_Fails()
{
Client.Pylon.Get(perPage: 0);
}
[TestMethod]
public void Get_PerPage_Succeeds()
{
var response = Client.Pylon.Get(page: 1, perPage: 1);
Assert.AreEqual(1, response.Data.Count);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
#endregion
#region Validate
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Validate_Null_CSDL_Fails()
{
Client.Pylon.Validate(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Validate_Empty_CSDL_Fails()
{
Client.Pylon.Validate("");
}
[TestMethod]
public void Validate_Complete_CSDL_Succeeds()
{
var response = Client.Pylon.Validate(VALID_CSDL);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
#endregion
#region Compile
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Compile_Null_CSDL_Fails()
{
Client.Pylon.Compile(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Compile_Empty_CSDL_Fails()
{
Client.Pylon.Compile("");
}
[TestMethod]
public void Compile_Complete_CSDL_Succeeds()
{
var response = Client.Pylon.Compile(VALID_CSDL);
Assert.AreEqual("58eb8c4b74257406547ab1ed3be346a8", response.Data.hash);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
#endregion
#region Start
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Start_Null_Hash_Fails()
{
Client.Pylon.Start(null, VALID_NAME);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Start_Empty_Hash_Fails()
{
Client.Pylon.Start("", VALID_NAME);
}
[TestMethod]
public void Start_Null_Name_Succeeds()
{
var response = Client.Pylon.Start(VALID_HASH, null);
Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Start_Empty_Name_Fails()
{
var response = Client.Pylon.Start(VALID_HASH, "");
}
[TestMethod]
public void Start_Succeeds()
{
var response = Client.Pylon.Start(VALID_HASH, VALID_NAME);
Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
}
#endregion
#region Stop
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Stop_Null_Hash_Fails()
{
Client.Pylon.Stop(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Stop_Empty_Hash_Fails()
{
Client.Pylon.Stop("");
}
[TestMethod]
public void Stop_Succeeds()
{
var response = Client.Pylon.Stop(VALID_HASH);
Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
}
#endregion
#region Analyze
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Analyze_Null_Hash_Fails()
{
Client.Pylon.Analyze(null, DummyParameters);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Analyze_Empty_Hash_Fails()
{
Client.Pylon.Analyze("", DummyParameters);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Analyze_Empty_Filter_Fails()
{
Client.Pylon.Analyze(VALID_HASH, DummyParameters, filter: "");
}
[TestMethod]
public void Analyze_With_Null_Filter_Succeeds()
{
var response = Client.Pylon.Analyze(VALID_HASH, DummyParameters, filter: null);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
public void Analyze_With_Filter_Succeeds()
{
var response = Client.Pylon.Analyze(VALID_HASH, DummyParameters, filter: "interaction.content contains 'apple'");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Analyze_Too_Late_Start_Fails()
{
Client.Pylon.Analyze(VALID_HASH, DummyParameters, start: DateTimeOffset.Now.AddDays(1), end: DateTimeOffset.Now.AddDays(3));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Analyze_Too_Late_End_Fails()
{
Client.Pylon.Analyze(VALID_HASH, DummyParameters, start: VALID_START, end: DateTimeOffset.Now.AddDays(1));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Analyze_End_Before_Start_Fails()
{
Client.Pylon.Analyze(VALID_HASH, DummyParameters, start: VALID_START, end: DateTimeOffset.Now.AddDays(-31));
}
[TestMethod]
public void Analyze_With_Null_Start_Succeeds()
{
var response = Client.Pylon.Analyze(VALID_HASH, DummyParameters, start: null, end: DateTimeOffset.Now);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
public void Analyze_With_Null_End_Succeeds()
{
var response = Client.Pylon.Analyze(VALID_HASH, DummyParameters, start: DateTimeOffset.Now.AddDays(-1), end: null);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
public void Analyze_With_Start_And_End_Succeeds()
{
var response = Client.Pylon.Analyze(VALID_HASH, DummyParameters, start: DateTimeOffset.Now.AddDays(-1), end: DateTimeOffset.Now);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Analyze_With_Null_Parameters_Fails()
{
Client.Pylon.Analyze(VALID_HASH, parameters: null, start: DateTimeOffset.Now.AddDays(-1), end: DateTimeOffset.Now);
}
[TestMethod]
public void Analyze_Succeeds()
{
var response = Client.Pylon.Analyze(VALID_HASH, DummyParameters);
Assert.AreEqual(false, response.Data.analysis.redacted);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
[TestMethod]
public void Analyze_Nested()
{
dynamic nested = new {
analysis_type = "freqDist",
parameters = new
{
threshold = 3,
target = "fb.author.gender"
},
child = new {
parameters = new
{
threshold = 3,
target = "fb.author.age"
}
}
};
var response = Client.Pylon.Analyze("58eb8c4b74257406547ab1ed3bnested", nested);
Assert.AreEqual(false, response.Data.analysis.redacted);
Assert.AreEqual("freqDist", response.Data.analysis.results[0].child.analysis_type);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
#endregion
#region Tags
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void Tags_Null_Hash_Fails()
{
Client.Pylon.Tags(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Tags_Empty_Hash_Fails()
{
Client.Pylon.Tags("");
}
[TestMethod]
public void Tags_Succeeds()
{
var response = Client.Pylon.Tags(VALID_HASH);
Assert.AreEqual("tag.one", response.Data[0]);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AssembleAction : MonoBehaviour
{
public AssembleProcess[] assembleArr;
public string equipName;//设备名称
public Part[] partDictionary;//零部件注册表
public int curStep = 0;//当前操作步数
public Level level;
private Hashtable ht;//
private Camera orbitCam;//观察用摄像机
public enum Level
{
Easy,
Medium,
Hard
}
// Use this for initialization
void Start()
{
ini();
}
void Awake()
{
orbitCam = GameObject.Find("KGFOrbitCam").GetComponent<Camera>();
}
/// <summary>
/// 初始化
/// </summary>
private void ini()
{
setHashTable();
}
/// <summary>
/// 将参与操作的所有零部件登记,
/// 便于显示有意义的名称
/// </summary>
private void setHashTable()
{
ht = new Hashtable();
if (partDictionary.Length > 0)
{
foreach (Part part in partDictionary)
{
ht.Add(part.gameObj.name, part.name);
}
}
}
// Update is called once per frame
void Update()
{
if (!GameManager.Instance.isStart)
return;
Ray ray = orbitCam.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (ht.Contains(hit.collider.gameObject.name))
{
string nameStr = ht[hit.collider.gameObject.name].ToString();
UITooltip.ShowText(nameStr);
}
else
{
UITooltip.ShowText("");
}
}
else
{
UITooltip.ShowText("");
}
}
/// <summary>
/// 下一步拆解
/// </summary>
public void nextStep()
{
}
/// <summary>
/// 上一步拆解
/// </summary>
public void preStep()
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractionTriggerDog : MonoBehaviour
{
[Tooltip("交互类型,0表示推门,1表示扒石头,2表示跳箱子,3表示拿零件,4仅给出光标提示")]
public int interaction_type;
public GameObject getOrLose_prefab;
private bool dog_inBounds=false;
private GameObject m_dog;
private bool action_finished = false;
private GameObject getOrLose;
private GetOrLostItem getOrLostItem;
private ZimuUI zimu;
private AudioSourceController m_AudioSourceController;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Dog")
{
if (interaction_type == 0)
{
if (collision.contacts[0].normal.x == 1)
{
transform.parent.GetComponent<Animator>().SetTrigger("Open");
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().EnterPointPlane();
m_AudioSourceController = AudioSourcesManager.ApplyAudioSourceController();
m_AudioSourceController.Play("开关门", transform);
GetComponent<Collider2D>().enabled=false;
transform.parent.Find("Gate").gameObject.SetActive(false);
InputController.BanMouse(true);
InputController.BanButton(true);
Invoke("CanMove", 2f);
}
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Dog"))
{
dog_inBounds = true;
m_dog = collision.gameObject;
if (getOrLose_prefab != null)
{
getOrLose = Instantiate(getOrLose_prefab);
getOrLostItem = getOrLose.GetComponent<GetOrLostItem>();
}
zimu = GameObject.Find("UI").transform.Find("字幕UI").GetComponent<ZimuUI>();
m_AudioSourceController = AudioSourcesManager.ApplyAudioSourceController();
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Dog"))
{
dog_inBounds = false;
m_dog = null;
}
}
private void CanMove()
{
InputController.BanButton(false);
InputController.BanMouse(false);
}
private void Awake()
{
if (interaction_type == 2)
{
Physics2D.IgnoreCollision(GetComponent<Collider2D>(), GameObject.FindGameObjectWithTag("Player").GetComponent<Collider2D>(), true);
}
if (interaction_type == 3)
{
Physics2D.IgnoreCollision(transform.parent.GetChild(2).GetComponent<Collider2D>(), GameObject.FindGameObjectWithTag("Player").GetComponent<Collider2D>(), true);
}
}
private void Update()
{
Vector3 playerWordDir = Camera.main.WorldToScreenPoint(new Vector3(0, 0, 0f));
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, playerWordDir.z));
switch (interaction_type)
{
case 1:
if (transform.parent.GetComponent<Collider2D>().bounds.Contains(mousePosition))
{
if (!action_finished)
{
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().InterationPrompt();
}
InputController.GetKey();
if (!dog_inBounds)
{
return;
}
if (m_dog.GetComponent<PlayerActions>().GetInteraction()&&!action_finished)
{
action_finished = true;
m_AudioSourceController.Play("碎石", transform);
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().EnterPointPlane();
Transform stone = transform.parent;
stone.GetChild(1).GetComponent<ShowAndHide>().Hide(3f);
stone.GetChild(2).gameObject.SetActive(true);
stone.GetChild(2).GetComponent<ShowAndHide>().Show(3f);
StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
{
m_dog.GetComponent<DogMoving>().StopMoving();
gameObject.SetActive(false);
stone.GetComponent<Collider2D>().isTrigger = true;
}, 3f));
}
}else
{
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().EnterPointPlane();
}
break;
case 3:
if (transform.parent.GetComponent<Collider2D>().bounds.Contains(mousePosition))
{
if (!action_finished)
{
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().InterationPrompt();
}
InputController.GetKey();
if (!dog_inBounds)
{
return;
}
if (m_dog.GetComponent<PlayerActions>().GetInteraction() && !action_finished)
{
GetSomething("零件");
GameObject.Find("箱子").GetComponent<Collider2D>().enabled=false;
transform.parent.GetChild(2).GetComponent<Collider2D>().enabled=false;
GameObject.Find("BackpackUI").GetComponent<BackpackUI>().AddItem("零件");
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().EnterPointPlane();
zimu.Show("拿到了零件!可以修理一下轮椅了。");
GameObject.Find("CameraAndCharacterController").GetComponent<CameraAndCharacterController>().SendMessage("LookAtMan");
}
}else
{
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().EnterPointPlane();
}
break;
case 4:
if (transform.parent.GetComponent<Collider2D>().bounds.Contains(mousePosition))
{
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().InterationPrompt();
}
else
{
GameObject.Find("MouseCursor").GetComponent<MouseCursorController>().EnterPointPlane();
}
break;
default:
break;
}
}
private void GetSomething(string name)
{
getOrLostItem.character = m_dog.transform;
getOrLostItem.xOffset = 0f;
getOrLostItem.yOffset = 2.6f;
transform.parent.GetChild(1).GetComponent<ShowAndHide>().Hide(2f);
GetComponent<InteractionTriggerDog>().enabled=false;
InputController.BanButton(true);
InputController.BanMouse(true);
getOrLostItem.GetShow(name, 1f, 1f, 1f, delegate () {
Destroy(getOrLostItem);
InputController.BanButton(false);
InputController.BanMouse(false);
}, 1f);
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Teste.Models
{
public class ProdutoContexto : DbContext
{
public ProdutoContexto(DbContextOptions<ProdutoContexto> options) : base(options)
{
}
public DbSet<Produto> Produto { get;set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Produto>().HasKey(m => m.Id);
base.OnModelCreating(builder);
}
}
}
|
using Common.Business;
using Common.Log;
using Contracts.Clipboard;
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading.Tasks;
namespace Clients.Clipboard
{
/// <summary>
/// Proxy class for asynchronous Clipboard operations.
/// </summary>
[CallbackBehavior(AutomaticSessionShutdown = true, ConcurrencyMode = ConcurrencyMode.Reentrant,
UseSynchronizationContext = false, MaxItemsInObjectGraph = Int32.MaxValue,
IncludeExceptionDetailInFaults = Constants.IncludeExceptionDetailInFaults,
TransactionTimeout = "00:30:00")]
public class AsyncClipboardProxy : DuplexClientBase<IAsyncClipboardService>, IAsyncClipboardService
{
#region Constructors
/// <summary>
/// Creates a new instance of AsyncClipboardProxy.
/// </summary>
/// <param name="callbackInstance">The instance context for callbacks.</param>
/// <param name="endpoint">The endpoint to use.</param>
public AsyncClipboardProxy(InstanceContext callbackInstance, ServiceEndpoint endpoint)
: base(callbackInstance, endpoint)
{
////Set inner timeouts to prevent the system from hanging during a load.
////InnerChannel.OperationTimeout = TimeSpan.FromMinutes(30);
////InnerDuplexChannel.OperationTimeout = TimeSpan.FromMinutes(30);
////InnerChannel.AllowOutputBatching = true;
////InnerDuplexChannel.AllowOutputBatching = true;
//OperationContext.Current.Channel.Closing += Channel_Closing;
//OperationContext.Current.Channel.Faulted += Channel_Faulted;
}
//void Channel_Faulted(object sender, EventArgs e)
//{
// IContextChannel channel = sender as IContextChannel;
// IInputSession session = channel.InputSession;
//}
//void Channel_Closing(object sender, EventArgs e)
//{
// IContextChannel channel = sender as IContextChannel;
//}
#endregion
#region Public Methods
/// <summary>
/// Cancels the asynchronous operation.
/// </summary>
public void CancelClipboardAsync()
{
try
{
Channel.CancelClipboardAsync();
}
catch (CommunicationObjectAbortedException)
{
Abort();
Logging.Log("Cancel request was aborted.", "Clipboard.Async.Service", "CancelClipboardAsync");
}
}
/// <summary>
/// Loads the Clipboard asynchronously.
/// </summary>
/// <param name="userState">A TableLoader with connection string, user name, and other information needed
/// to process the request.</param>
/// <returns>The result of the load, as a MemoryStream.</returns>
public Task<MemoryStream> LoadClipboardAsync(object userState)
{
try
{
return Channel.LoadClipboardAsync(userState);
}
catch (Exception e)
{
Abort();
Logging.Log(e, "AsyncClipboardProxy", "LoadClipboardAsync");
return null;
}
}
/// <summary>
/// Sends a portion of the requested IDs to the server.
/// </summary>
/// <param name="ids">The IDs to send.</param>
/// <remarks>This method is necessary because WCF cannot handle large chunks of data (e.g., 10000 IDs) all at once.
/// The time it takes the client to send all of the list to the server is not perceptible to the user.</remarks>
public void SendNextChunk(List<int> ids)
{
Channel.SendNextChunk(ids);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginDevelopment.Model
{
public class Message
{
public string Id { get; set; }
public string Category { get; set; }
public string TextId { get; set; }
public byte[] EntryContent { get; set; }
public TextEdit TextEdit { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TickSystem : MonoBehaviour
{
public static TickSystem instance;
private void Awake ()
{
if (instance == null)
instance = this;
else if (instance != this)
{
Destroy ( this.gameObject );
return;
}
}
public System.Action tick;
public static System.Action Tick
{
get
{
return TickSystem.instance.tick;
}
set
{
TickSystem.instance.tick = value;
}
}
private float timePerTick = 0.025f;
private float currentTimeCounter;
private int currentTick = 0;
private void Update ()
{
currentTimeCounter += Time.deltaTime;
if (currentTimeCounter >= timePerTick)
{
currentTimeCounter = 0.0f;
currentTick++;
tick?.Invoke ( );
}
}
public static bool Equals (int t)
{
return (instance.currentTick % t == 0);
}
} |
using Newtonsoft.Json;
namespace CutieBox.API.RandomApi
{
public class CatFactResponse
{
[JsonProperty]
public string Fact { get; private set; } = string.Empty;
[JsonConstructor]
private CatFactResponse() { }
}
}
|
using gView.Framework.system;
using gView.Server.Services.MapServer;
using Microsoft.AspNetCore.Mvc;
namespace gView.Server.Controllers;
public class Info : Controller
{
private readonly MapServiceManager _mapServiceManager;
public Info(MapServiceManager mapServerService)
{
_mapServiceManager = mapServerService;
}
public IActionResult Index()
{
return Json(new
{
version = SystemInfo.Version,
queue = new
{
IdleDuration = _mapServiceManager.TaskQueue.IdleDuration,
currentQueued = _mapServiceManager.TaskQueue.CurrentQueuedTasks,
currentRunningTasks = _mapServiceManager.TaskQueue.CurrentRunningTasks
}
});
}
}
|
using System;
using System.Collections.Generic;
using Pe.Stracon.SGC.Aplicacion.Core.Base;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
namespace Pe.Stracon.SGC.Aplicacion.Core.ServiceContract
{
/// <summary>
/// Servicio que representa los Contratos
/// </summary>
/// <remarks>
/// Creación: GMD 20150710 <br />
/// Modificación: <br />
/// </remarks>
public interface IBienService : IGenericService
{
/// <summary>
/// Método que retorna la Lista de Bienes
/// </summary>
/// <param name="filtro">objeto request del tipo Bien</param>
/// <returns>Lista de Bienes</returns>
ProcessResult<List<BienResponse>> ListarBienes(BienRequest filtro, List<CodigoValorResponse> plstTipoBien = null,
List<CodigoValorResponse> plstTipoTarifa = null,
List<CodigoValorResponse> plstMoneda = null,
List<CodigoValorResponse> plstPeriodoAlq = null);
/// <summary>
/// Método que registra y/o Edita un Bien
/// </summary>
/// <param name="objRqst">objeto request del tipo Bien</param>
/// <returns>Retorna entero, 1 transacción Ok.</returns>
ProcessResult<Object> RegistraEditaBien(BienRequest objRqst);
/// <summary>
/// Retorna información del bien.
/// </summary>
/// <param name="codigoBien">código del bien</param>
/// <returns>Información del bien</returns>
ProcessResult<BienResponse> RetornaBienPorId(Guid codigoBien);
/// <summary>
/// Retorna información del bien alquiler por código.
/// </summary>
/// <param name="codigoBienAlquiler">código del bien alquiler</param>
/// <returns>Información del bien alquiler por código</returns>
ProcessResult<BienAlquilerResponse> RetornaBienAlquilerPorId(Guid codigoBienAlquiler);
/// <summary>
/// Método que retorna la Lista de Bienes Alquiler
/// </summary>
/// <param name="filtro">objeto request del tipo Bien</param>
/// <returns>Lista de Bienes</returns>
ProcessResult<List<BienAlquilerResponse>> ListarBienAlquiler(Guid codigoBien);
/// <summary>
/// Método que registra y/o Edita un Bien Alquiler
/// </summary>
/// <param name="objRqst">objeto request del tipo BienAlquiler</param>
/// <returns>Retorna entero, 1 transacción Ok.</returns>
ProcessResult<Object> RegistraEditaBienAlquiler(BienAlquilerRequest objRqst);
/// <summary>
/// Retorna los periodos de alquiler.
/// </summary>
/// <param name="tipoTarifa">Código del Tipo de Tarifa</param>
/// <returns>Periodos de alquiler</returns>
ProcessResult<List<CodigoValorResponse>> PeriodoAlquilerPorTarifa(string tipoTarifa);
/// <summary>
/// Retorna la lista del descripciones de campos del bien.
/// </summary>
/// <param name="tipoContenido">código del tipo de contenido</param>
/// <returns></returns>
ProcessResult<List<BienRegistroResponse>> ListaBienRegistro(string tipoContenido);
/// <summary>
/// Retorna la lista de bienes con su descripción completa.
/// </summary>
/// <param name="filtro">Filtro de Búsqueda</param>
/// <returns>Lista de bienes con su descripción completa</returns>
ProcessResult<List<BienResponse>> ObtenerDescripcionCompletaBien(BienRequest filtro);
/// <summary>
/// Elimina uno o muchos Bien
/// </summary>
/// <param name="listaCodigosBien">Lista de Códigos de Bien a eliminar</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<object> EliminarBien(List<object> listaCodigosBien);
/// <summary>
/// Elimina uno o muchos Bien Alquiler
/// </summary>
/// <param name="listaCodigosBienAlquiler">Lista de Códigos de Bien Alquiler a eliminar</param>
/// <returns>Indicador con el resultado de la operación</returns>
ProcessResult<object> EliminarBienAlquiler(List<object> listaCodigosBienAlquiler);
/// <summary>
/// Sincronizar bienes de servicio Amt
/// </summary>
/// <returns>Registro de nuevos equipos de Amt</returns>
ProcessResult<string> SincronizarBienesServicioAmt();
/// <summary>
/// Sincronizar bienes de servicio SAP
/// </summary>
/// <returns>Registro de nuevos equipos de SAP</returns>
ProcessResult<string> SincronizarBienesServicioSAP();
}
}
|
namespace ChatServer.Messaging.Decorators
{
using System.Threading.Tasks;
using ChatServer.Messaging.Commands;
using HServer.Networking;
/// <summary>
/// The server command decorator.
/// </summary>
public abstract class ServerCommandDecorator : IChatServerCommand
{
/// <summary>
/// The chat server command implementation.
/// </summary>
private readonly IChatServerCommand command;
/// <summary>
/// Initializes a new instance of the <see cref="ServerCommandDecorator"/> class.
/// </summary>
/// <param name="command">
/// The chat server command implementation.
/// </param>
protected ServerCommandDecorator(IChatServerCommand command)
{
this.command = command;
}
/// <summary>
/// The execute task.
/// </summary>
/// <param name="client">
/// The client.
/// </param>
/// <param name="message">
/// The message.
/// </param>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
public Task ExecuteTaskAsync(HChatClient client, RequestMessage message)
{
return command.ExecuteTaskAsync(client, message);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public static float maxPlayerHealth = 20;
public static float PlayerHealth = 20;
private Animator BodyAnimator;
private Animator ArmsAnimator;
[SerializeField] private float speed = 4;
private Vector2 movement;
private Rigidbody2D rb;
public bool ableToMove = true;
private bool cantMoveCusM = false;
public static Inventory inventory;
[SerializeField] UI_Inventory uiInventory;
private Transform arms;
private Transform holdPoint;
private SpriteRenderer holdPointSpriteRenderer;
private Transform MemoryBoxesPanel;
private Transform MemoryBoxesBoxesBox;
private bool MemoryBoxesDown = false;
private Animator MemoryBoxesAnimator;
private Transform shootPoint;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
ArmsAnimator = transform.Find("MC_Arms").GetComponent<Animator>();
BodyAnimator = transform.Find("MC_Body").GetComponent<Animator>();
arms = transform.Find("MC_Arms");
holdPoint = arms.Find("HoldPoint");
holdPointSpriteRenderer = holdPoint.GetComponent<SpriteRenderer>();
MemoryBoxesPanel = GameObject.Find("MemoryBoxesPanel").transform;
MemoryBoxesBoxesBox = GameObject.Find("MemoryBoxesBoxesBox").transform;
MemoryBoxesAnimator = MemoryBoxesBoxesBox.GetComponent<Animator>();
shootPoint = GameObject.Find("ShootPoint").transform;
}
private void Awake()
{
IEnumerator coroutine = waitOneFrame();
StartCoroutine(coroutine);
}
private IEnumerator waitOneFrame()
{
yield return null;
inventory = new Inventory(useItem);
uiInventory.SetInventory(inventory);
uiInventory.SetPlayer(this);
}
private void useItem(Item item)
{
switch (item.itemType)
{
case Item.ItemType.HealthPosion:
inventory.RemoveItem(new Item { itemType = Item.ItemType.HealthPosion, amount = 1 });
PlayerHealth += 5;
HealthBar.SetHealth(0);
break;
case Item.ItemType.ManaPosion:
//do action
inventory.RemoveItem(new Item { itemType = Item.ItemType.ManaPosion, amount = 1 });
break;
}
}
public void holdItem(Item item)
{
switch (item.itemType)
{
case Item.ItemType.Sword:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdSwordSpite;
weponStats(0.55f, 1.5f);
break;
case Item.ItemType.Knife:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdKnifeSprite;
weponStats(0.4f, 1);
break;
case Item.ItemType.Bow:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdBowSprite;
weponStats(69, 1.25f);
break;
case Item.ItemType.Mase:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdMaseSprite;
weponStats(0.6f, 2.5f); //:)
break;
case Item.ItemType.Wand:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdWandSprite;
weponStats(69, 1.75f);
break;
case Item.ItemType.Bomb:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdBombSprite;
weponStats(72, 5);
break;
case Item.ItemType.Gun:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdGunSprite;
weponStats(69, 6);
break;
case Item.ItemType.Katana:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdKatanaSprite;
weponStats(1, 1.25f);
break;
case Item.ItemType.QuickKnife:
holdPointSpriteRenderer.sprite = ItemAssets.Instance.holdQuickKnifeSprite;
weponStats(0.35f, 0.25f);
break;
}
}
private void weponStats(float range, float damage)
{
Attack.MCAttackRange = range;
Attack.MCdamage = damage;
}
private void OnTriggerEnter2D(Collider2D collider)
{
ItemWorld itemWorld = collider.GetComponent<ItemWorld>();
if (collider.gameObject.GetComponent<ItemWorld>() == true)
{
inventory.checkItemAlreadyInItemList(itemWorld.GetItem());
}
if (itemWorld != null)
{
if (UI_Inventory.inventoryFull == false)
{
//touching item
inventory.AddItem(itemWorld.GetItem());
itemWorld.DestroySelf();
}
else if (inventory.itemAlreadyInInventory && itemWorld.GetItem().IsStackable() == true)
{
//touching item
inventory.AddItem(itemWorld.GetItem());
itemWorld.DestroySelf();
}
Debug.Log(itemWorld.GetItem().IsStackable());
}
}
void Update()
{
if (ableToMove)
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
if (Input.GetKeyDown("space"))
{
ArmsAnimator.SetBool("Holding", false);
BodyAnimator.SetBool("Holding", false);
holdPointSpriteRenderer.sprite = null;
shootPoint.GetComponent<SpriteRenderer>().sprite = null;
Attack.MCAttackRange = 0;
}
}
else
{
movement.x = 0;
movement.y = 0;
}
if (Input.GetKeyDown(KeyCode.M))
{
if (!MemoryBoxesDown)
{
MemoryBoxesPanel.localPosition = Vector3.zero;
MemoryBoxesAnimator.SetBool("IsDown", true);
MemoryBoxesDown = true;
cantMoveCusM = true;
if (ableToMove == false)
{
cantMoveCusM = false;
}
ableToMove = false;
}
else
{
IEnumerator coroutine = WaitHalfASecond();
StartCoroutine(coroutine);
MemoryBoxesAnimator.SetBool("IsDown", false);
MemoryBoxesDown = false;
if (cantMoveCusM)
{
ableToMove = true;
cantMoveCusM = false;
}
}
}
BodyAnimator.SetFloat("HorizontalSpeed", movement.x);
BodyAnimator.SetFloat("VerticalSpeed", movement.y);
ArmsAnimator.SetFloat("HorizontalSpeed", movement.x);
ArmsAnimator.SetFloat("VerticalSpeed", movement.y);
}
private IEnumerator WaitHalfASecond()
{
yield return new WaitForSeconds(0.5f);
MemoryBoxesPanel.localPosition = new Vector3(0, 450, 0);
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement * speed * Time.deltaTime);
}
public Vector3 GetPosition()
{
return transform.position;
}
}
|
using System.Collections;
using System.Collections.Generic;
using DChild.Gameplay.Player;
using UnityEngine;
public interface IOnEquipEffect
{
void OnEquip(Player player);
void OnUnequip(Player player);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace MyIVDatabase
{
public class DeletePoke
{
public static async void DeleteRow(string name)
{
SQLiteConnection cnc = new SQLiteConnection(Connection.ConnectString());
cnc.Open();
SQLiteCommand cmd = new SQLiteCommand(Queries.DeletePoke(name), cnc);
await cmd.ExecuteNonQueryAsync();
cnc.Close();
}
}
}
|
using senai.inlock.webApi_.Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace senai.inlock.webApi_.Interfaces
{
interface IJogoRepository
{
/// <summary>
/// Retorna todos os jogos
/// </summary>
/// <returns>Uma lista de jogos</returns>
List<JogoDomain> ListarTodos();
/// <summary>
/// Busca um jogo atraves do id
/// </summary>
/// <param name="id">id do jogo que sera buscado</param>
/// <returns>Um objeto do tipo JogoDomain que foi buscado</returns>
JogoDomain BuscarPorId(int id);
/// <summary>
/// Cadastra um novo jogo
/// </summary>
/// <param name="novoJogo">Objeto novoJogo que sera cadastrado</param>
void Cadastrar(JogoDomain novoJogo);
/// <summary>
/// Atualiza um jogo passando o id pele corpo
/// </summary>
/// <param name="jogo"></param>
void AtualizaIdCorpo(JogoDomain jogo);
/// <summary>
/// Deleta um jogo
/// </summary>
/// <param name="id">id do jogo que sera deletado</param>
void Deletar(int id);
}
}
|
//using WeifenLuo.WinFormsUI.Docking;
//namespace gView.Framework.system.UI
//{
// public class DocumentFiller
// {
// private DocumentTabList _tabPages;
// private DocumentTab _selectedTab = null;
// private DockPanel _dockPanel;
// public DocumentFiller(DockPanel dockPanel)
// {
// _dockPanel = dockPanel;
// _tabPages = new DocumentTabList(dockPanel);
// }
// public DocumentTabList TabPages
// {
// get { return _tabPages; }
// }
// public DocumentTab SelectedTab
// {
// get
// {
// if (_selectedTab == null && _tabPages.Count > 0)
// return _tabPages[0];
// return _selectedTab;
// }
// }
// public class DocumentTabList
// {
// private DockPanel _dockPanel;
// private List<DocumentTab> _list = new List<DocumentTab>();
// public DocumentTabList(DockPanel dockPanel)
// {
// _dockPanel = dockPanel;
// }
// public void Add(DocumentTab tab)
// {
// if (tab == null || _list.Contains(tab)) return;
// //tab.ShowDialog();
// if (_list.Count == 0)
// {
// tab.Show(_dockPanel, DockState.Document);
// }
// else
// {
// tab.Show(_list[0].Pane, null);
// }
// _list.Add(tab);
// }
// public void Clear()
// {
// foreach (DocumentTab tab in _list)
// {
// tab.Hide();
// }
// _list.Clear();
// }
// public DocumentTab this[int index]
// {
// get
// {
// if (index < 0 || index >= _list.Count)
// throw new ArgumentException("Index out of bounds");
// return _list[index];
// }
// }
// public int Count
// {
// get { return _list.Count; }
// }
// }
// }
//}
|
using NUnit.Framework;
using System;
using System.IO;
using System.Linq;
namespace WebDriverManager
{
[TestFixture]
public class TestClass
{
[OneTimeSetUp]
public void Setup()
{
string user = System.Environment.GetEnvironmentVariable("USERPROFILE");
string destination = user + "\\WebDrivers\\";
if (Directory.Exists(destination))
{
Directory.Delete(destination, true);
}
}
[Test]
public void GoogleChromeWindows()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("chromedriver.exe"));
}
[Test]
public void FireFoxWindows()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.FIREFOX, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("geckodriver.exe"));
}
[Test]
public void InternetExplorerWindows()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.INTERNET_EXPLORER, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("IEDriverServer.exe"));
}
[Test]
public void EdgeWindows()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("msedgedriver.exe"));
}
[Test]
public void GoogleChromeLinux()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.LINUX);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("chromedriver"));
}
[Test]
public void FireFoxLinux()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.FIREFOX, Manager.OperatingSystem.LINUX);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("geckodriver"));
}
[Test]
public void InternetExplorerLinux()
{
Assert.Throws<NotImplementedException>(() => Manager.GetWebDriver(Manager.BrowserType.INTERNET_EXPLORER, Manager.OperatingSystem.LINUX));
}
[Test]
public void EdgeLinux()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.LINUX);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.LINUX);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("msedgedriver.exe"));
}
[Test]
public void GoogleChromeWindows_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.WINDOWS);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("chromedriver.exe"));
}
[Test]
public void FireFoxWindows_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.FIREFOX, Manager.OperatingSystem.WINDOWS);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.FIREFOX, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("geckodriver.exe"));
}
[Test]
public void InternetExplorerWindows_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.INTERNET_EXPLORER, Manager.OperatingSystem.WINDOWS);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.INTERNET_EXPLORER, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("IEDriverServer.exe"));
}
[Test]
public void EdgeWindows_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.WINDOWS);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.WINDOWS);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("msedgedriver.exe"));
}
[Test]
public void GoogleChromeLinux_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.LINUX);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.LINUX);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("chromedriver"));
}
[Test]
public void FireFoxLinux_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.FIREFOX, Manager.OperatingSystem.LINUX);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.FIREFOX, Manager.OperatingSystem.LINUX);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("geckodriver"));
}
[Test]
public void EdgeLinux_PreDownload()
{
string chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.LINUX);
chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.EDGE, Manager.OperatingSystem.LINUX);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("msedgedriver.exe"));
}
[Test]
public void Chrome_NonExistentVersion()
{
Browser browser = Manager.GetBrowser(Manager.GetBrowsers(), Manager.BrowserType.CHROME);
browser.Version = "1000.00.00";
Assert.Throws<Exception>(()=>Manager.GetVersionFromGoogleAPIS(Manager.chrome_url, browser, Manager.OperatingSystem.WINDOWS));
}
[Test]
public void IE_NonExistentVersion()
{
Browser browser = Manager.GetBrowser(Manager.GetBrowsers(), Manager.BrowserType.INTERNET_EXPLORER);
browser.Version = "1000.00.00";
Assert.Throws<Exception>(() => Manager.GetVersionFromGoogleAPIS(Manager.ie_url, browser, Manager.OperatingSystem.WINDOWS));
}
[Test]
public void Edge_NonExistentVersion()
{
Browser browser = Manager.GetBrowser(Manager.GetBrowsers(), Manager.BrowserType.EDGE);
browser.Version = "1000.00.00";
Assert.Throws<Exception>(() => Manager.GetEdgeURL(browser, Manager.OperatingSystem.WINDOWS));
}
[Test]
public void Chrome_Linux_ManualBrowser()
{
Browser browser = new Browser()
{
Name = "Google Chrome",
Version = "84.0.4147.135"
};
var chromedriverDir = Manager.GetWebDriver(Manager.BrowserType.CHROME, Manager.OperatingSystem.LINUX, browser);
var files = Directory.GetFiles(chromedriverDir);
var filenames = files.Select(x => Path.GetFileName(x));
Assert.IsTrue(filenames.Contains("chromedriver"));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAudioHandler : MonoBehaviour
{
// THIS SCRIPT IS REQUIRED FOR ANIMATION BEHAVIOR SCRIPTS IN THIS PACKAGE
// This script is used by the animation behaviors. This way, multiple sounds can be played during animations
// Each variable should have it's own audio source, so you should have a minimum of 3 separate audio sources.
public AudioSource attackAudioSource;
public AudioSource walkAudioSource;
public AudioSource jumpAudioSource;
}
|
using System.Web.Mvc;
using web_ioc.components;
using web_ioc.Models;
namespace web_ioc.Controllers
{
public class HomeController : Controller
{
private readonly ILegendService _service;
public HomeController(ILegendService service)
{
_service = service;
}
public ActionResult Index()
{
ViewBag.Title = "Home Page";
_service.Touched = true;
return View();
}
public ActionResult Logoff()
{
Session.Abandon();
return View("Index");
}
}
}
|
using System;
namespace Chapter_5___Estimator
{
class DinnerParty
{
public const int CostOfFoodPerPerson = 25;
public int NumberOfPeople { get; set; }
public bool FancyDecorations { get; set; }
public bool HealthyOptions { get; set; }
public decimal Cost
{
get
{
decimal totalCost = CalculateCostOfDecorations();
totalCost += NumberOfPeople *
(CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson);
if (HealthyOptions)
totalCost *= 0.95M;
return totalCost;
}
}
public DinnerParty(int numberOfPeople, bool fancyDecorations, bool healthyOptions)
{
Console.Write(this.Cost);
Console.Write(CalculateCostOfDecorations());
NumberOfPeople = numberOfPeople;
FancyDecorations = fancyDecorations;
HealthyOptions = healthyOptions;
}
private decimal CalculateCostOfDecorations()
{
return FancyDecorations ?
NumberOfPeople * 15.00M + 50.00M :
NumberOfPeople * 7.50M + 30.00M;
}
private decimal CalculateCostOfBeveragesPerPerson()
{
return HealthyOptions ? 5.00M : 20.00M;
}
/*
public decimal CostOfBeveragesPerPerson, CostOfDecorations;
public int NumberOfPeople;
public const int CostOfFoodPerPerson = 25;
public void SetHealthyOption(bool healthy)
{
CostOfBeveragesPerPerson = healthy ? 5.00M : 20.00M;
}
public void CalculateCostOfDecorations(bool fancy)
{
if (fancy)
{
CostOfDecorations = NumberOfPeople * 15.00M + 50.00M;
}
else
{
CostOfDecorations = NumberOfPeople * 7.50M + 30.00M;
}
}
public decimal CalculateCost(bool healthy)
{
decimal totalCost = NumberOfPeople
* (CostOfBeveragesPerPerson + CostOfFoodPerPerson)
+ CostOfDecorations;
if (healthy)
{
totalCost *= 0.95M;
}
return totalCost;
}
*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab8_task2
{
class iPhone : ColorScreenPhone
{
public override void Call()
{
Console.WriteLine("Well, put on your airpods and call someone :D");
}
public override void RingTone()
{
Console.WriteLine("*plays a song downloaded from the Apple Music(cool I know)*");
}
public override void SurfTheNet()
{
Console.WriteLine("We're using wi-fi and 4g. Do you want to watch something on YouTube?");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//. Crear una aplicación de consola que cargue 20 números enteros (positivos y negativos) distintos de cero de forma aleatoria utilizando la clase Random.
// a. Mostrar el vector tal como fue ingresado
// b. Luego mostrar los positivos ordenados en forma decreciente.
// c. Por último, mostrar los negativos ordenados en forma creciente.
namespace Ejercicio_26
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Ejercicio 26";
Random r = new Random();
double[] arrayRandom = new double[20];
for (int i = 0; i < arrayRandom.Length; i++)
{
double random = r.Next(-1000, 1001);
while(random == 0)
{
random = r.Next(-1000, 1001);
}
arrayRandom[i] = random;
}
Console.WriteLine("Array completo:\n");
foreach (double num in arrayRandom)
{
Console.WriteLine($"{num}\n");
}
//primero ordenar decreciente, despues mostrar solo posit
Array.Sort(arrayRandom); // orden creciente
Array.Reverse(arrayRandom); // orden decreciente
Console.WriteLine("\n\nEnteros positivos decreciente:\n");
foreach (double num in arrayRandom)
{
if (num > 0) // solo posit
{
Console.WriteLine($"{num}\n");
}
}
//primero ordenar creciente, despues mostrar solo negativos
Array.Reverse(arrayRandom); // orden creciente
Console.WriteLine("\n\nNegativos creciente:\n");
foreach (double num in arrayRandom)
{
if (num < 0)
{
Console.WriteLine($"{num}\n"); // solo negativos
}
}
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MultiUserBlock.Common;
using MultiUserBlock.Common.Enums;
using MultiUserBlock.Common.Repository;
using MultiUserBlock.ViewModels;
namespace MultiUserBlock.DB
{
public class UserRepository : IUserRepository
{
private readonly DataContext _context;
private readonly DbSet<User> _db;
public UserRepository(DataContext context)
{
_context = context;
_db = context.Set<User>();
}
public async Task AddOrUpdate(UserViewModel user)
{
var ex = await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).SingleOrDefaultAsync(u => u.UserId == user.UserId);
if (ex == null)
{
var usr = new User()
{
Username = user.Username,
Name = user.Name,
Vorname = user.Vorname,
Password = user.Password,
};
List<RoleToUser> rtus = new List<RoleToUser>();
foreach (var role in user.Roles)
{
var _rtu = new RoleToUser()
{
Role = role != -1 ? _context.Roles.First(r => r.UserRoleType == (UserRoleType)role) : _context.Roles.First(r => r.UserRoleType == UserRoleType.Default),
User = usr
};
rtus.Add(_rtu);
_context.RoleToUsers.Add(_rtu);
}
usr.RoleToUsers = rtus;
}
else
{
_delRoles(ex);
ex.Name = user.Name;
ex.Vorname = user.Vorname;
ex.Username = user.Username;
List<RoleToUser> rtus = new List<RoleToUser>();
foreach (var role in user.Roles)
{
var _rtu = new RoleToUser()
{
Role = role != -1 ? _context.Roles.First(r => r.UserRoleType == (UserRoleType)role) : _context.Roles.First(r => r.UserRoleType == UserRoleType.Default),
User = ex
};
rtus.Add(_rtu);
_context.RoleToUsers.Add(_rtu);
}
ex.RoleToUsers = rtus;
}
try
{
_context.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private User _delRoles(User user)
{
var rtus = _context.RoleToUsers.Where(rtu => rtu.UserId == user.UserId);
_context.RemoveRange(rtus);
_context.SaveChanges();
return user;
}
public async Task<List<UserViewModel>> GetAll()
{
return await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).Select(r => _map(r)).ToListAsync();
}
public async Task<UserViewModel> GetById(int userId)
{
return _map(await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).SingleOrDefaultAsync(u => u.UserId == userId));
}
public async Task<UserViewModel> GetByUserName(string userName)
{
return _map(await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).SingleOrDefaultAsync(u => u.Username == userName));
}
public async Task<bool> HasRole(int userId, UserRoleType urt)
{
var result = await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).SingleOrDefaultAsync(u => u.UserId == userId);
return result.RoleToUsers.Any(rtu => rtu.Role.UserRoleType == urt);
}
public async Task Remove(int userId)
{
_db.Remove(await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).SingleOrDefaultAsync(u => u.UserId == userId));
_context.SaveChanges();
}
private UserViewModel _map(User user)
{
if (user != null)
{
return new UserViewModel()
{
UserId = user.UserId,
Username = user.Username,
ShowName = user.Username,
Name = user.Name,
Vorname = user.Vorname,
Password = user.Password,
Roles = user.RoleToUsers.Select(r => r.Role).Select(r => (int)r.UserRoleType)
};
}
else
{
return default(UserViewModel);
}
}
private User _map(UserViewModel user)
{
if (user != null)
{
var usr = new User()
{
UserId = user.UserId,
Username = user.Username,
Name = user.Name,
Vorname = user.Vorname,
Password = user.Password,
};
List<RoleToUser> rtus = new List<RoleToUser>();
foreach (var role in user.Roles)
{
rtus.Add(new RoleToUser()
{
Role = role != -1 ? _context.Roles.First(r => r.UserRoleType == (UserRoleType)role) : _context.Roles.First(r => r.UserRoleType == UserRoleType.Default),
User = usr
});
}
usr.RoleToUsers = rtus;
return usr;
}
else
{
return default(User);
}
}
}
}
|
namespace BeerMapApi.Core.Models
{
public class Brewery
{
public string Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using Welic.Dominio.Models.EBook.Map;
using Welic.Dominio.Models.Lives.Maps;
using Welic.Dominio.Models.Users.Mapeamentos;
namespace Welic.Dominio.Models.Schedule.Maps
{
public class ScheduleMap : Patterns.Pattern.Ef6.Entity
{
public ScheduleMap()
{
//UserClass = new List<AspNetUser>();
}
public int ScheduleId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public DateTime DateEvent { get; set; }
public bool Private { get; set; }
public bool Ativo { get; set; }
public string TeacherId { get; set; }
public AspNetUser UserTeacher { get; set; }
public virtual ICollection<AspNetUser> UserClass { get; set; }
//public virtual LiveMap Live { get; set; }
//public EBookMap Ebook { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using PterodactylEngine;
using Xunit;
using Xunit.Sdk;
namespace UnitTestEngine
{
public class TestTableHelper : TheoryData<List<string>, List<int>, string[,], List<int>, string, string, List<string>>
{
public TestTableHelper()
{
Add(new List<string> { "Head 1", "Head 2", "Alol" },
new List<int> { 0, 1, 2 },
new string[,] { { "2", "5" }, { "lol", "hrhrhrh" }, { "r", "h" } },
new List<int> { 6, 7, 4 },
"| Head 1 | Head 2 | Alol |",
"| ------ | :-----: | ---: |",
new List<string>
{
"| 2 | lol | r |",
"| 5 | hrhrhrh | h |"
});
Add(new List<string> { "", "a"},
new List<int> { 0, 0 },
new string[,] { { "", "", "" }, { "a", "a", "a" }, },
new List<int> { 4, 4 },
"| | a |",
"| ---- | ---- |",
new List<string>
{
"| | a |",
"| | a |",
"| | a |"
});
}
}
public class TestTableExceptionHelper : TheoryData<List<string>, List<int>, string[,], string>
{
public TestTableExceptionHelper()
{
Add(new List<string> { "Example column", "Example 2", "C3", "C4" },
new List<int> { 0, 2, 1 },
new string[,] { { "2", "5" }, { "lol", "hrhrhrh rhrhh" }, { "r", "h" }, { "aaaaaaaaaa", "bbbbbbbbb" } },
"Headings list should match alignment list. " +
"Check if both input lists have the same number of elements.");
Add(new List<string> { "Example column", "Example 2", "C3", "C4" },
new List<int> { 0, 2, 1, 0 },
new string[,] { { "2", "5" }, { "lol", "hrhrhrh rhrhh" }, { "r", "h" }},
"Headings list should match number of columns given in data tree. " +
"Check if both inputs have the same number of elements.");
Add(new List<string> { "Example column", "Example 2", "C3", "C4" },
new List<int> { 0, 2, 1, 5 },
new string[,] { { "2", "5" }, { "lol", "hrhrhrh rhrhh" }, { "r", "h" }, { "aaaaaaaaaa", "bbbbbbbbb" } },
"Alignment should be an integer between 0 and 2");
}
}
public class TestCreateTableHelper : TheoryData<List<string>, List<int>, string[,], List<string>>
{
public TestCreateTableHelper()
{
Add(new List<string> {"Example column", "Example 2", "C3", "C4"},
new List<int> {0, 2, 1, 0},
new string[,] {{"2", "5"}, {"lol", "hrhrhrh rhrhh"}, {"r", "h"}, {"aaaaaaaaaa", "bbbbbbbbb"}},
new List<string>
{
"| Example column | Example 2 | C3 | C4 |",
"| -------------- | ------------: | :--: | ---------- |",
"| 2 | lol | r | aaaaaaaaaa |",
"| 5 | hrhrhrh rhrhh | h | bbbbbbbbb |"
});
Add(new List<string> { "One column" },
new List<int> { 1 },
new string[,] { { "One", "Two" } },
new List<string>
{
"| One column |",
"| :--------: |",
"| One |",
"| Two |"
});
Add(new List<string> { "First column", "Second column" },
new List<int> { 1, 1 },
new string[,] { { "One" }, { "Two" } },
new List<string>
{
"| First column | Second column |",
"| :----------: | :-----------: |",
"| One | Two |",
});
}
}
public class TestTable
{
[Theory]
[ClassData(typeof(TestTableHelper))]
public void CorrectData(List<string> headings, List<int> alignment,
string[,] dataTree, List<int> columnSizes, string headingReport, string alignmentReport,
List<string> rowsReport)
{
Table testObject = new Table(headings, alignment, dataTree);
Assert.Equal(headings, testObject.Headings);
Assert.Equal(alignment, testObject.Alignment);
Assert.Equal(dataTree, testObject.DataTree);
}
}
public class TestTableCreate
{
[Theory]
[ClassData(typeof(TestCreateTableHelper))]
public void CorrectData(List<string> headings, List<int> alignment, string[,] dataTree, List<string> expected)
{
Table testObject = new Table(headings, alignment, dataTree);
List<string> actual = testObject.Create();
Assert.Equal(expected, actual);
}
}
public class TestTableException
{
[Theory]
[ClassData(typeof(TestTableExceptionHelper))]
public void CheckExceptions(List<string> headings, List<int> alignment, string[,] dataTree, string message)
{
var exception = Assert.Throws<ArgumentException>(() => new Table(headings, alignment, dataTree));
Assert.Equal(message, exception.Message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XH.Domain.Catalogs;
using XH.Domain.Shared;
namespace XH.Queries.Catalogs.Dtos
{
public class RegionOverviewDto
{
public string Id { get; set; }
public virtual string AdministrativeId { get; set; }
public virtual string Name { get; set; }
public virtual string ShortName { get; set; }
public virtual string ZipCode { get; set; }
public virtual string PinYin { get; set; }
public virtual string ShortPinYin { get; set; }
public RegionType RegionType { get; set; }
public int Level { get; set; }
public virtual int DisplayOrder { get; set; }
public Coordinate Coordinate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace LoLInfo.Models
{
public class Champion : ICustomImageCellModel
{
public int Id { get; set; }
public string Name { get; set; }
public string SearchName { get; set; }
public string Title { get; set; }
public List<Skin> Skins { get; set; }
#region CustomImageCell Properties
public string SquareImageUrl { get; set; }
public string PrimaryText { get { return Name; } }
public string SecondaryText { get { return Title; } }
#endregion
}
}
|
// Add authorization roles from OA database to AD claims.
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using TRACSNarrative.Data;
using System.Diagnostics;
namespace TRACSNarrative
{
public class ClaimsTransformer : IClaimsTransformation
{
private readonly UserContext _context;
public ClaimsTransformer(UserContext context)
{
_context = context;
}
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var identity = (ClaimsIdentity)principal.Identity;
var userName = identity.Name;
var roles = _context.Role.Where(r => r.UserRoles.Any(u => u.User.UserName == userName)).Select(r => r.RoleId);
foreach (var role in roles)
{
var claim = new Claim("Role", role.ToString().Trim());
identity.AddClaim(claim);
}
return Task.FromResult(principal);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SubC.Attachments;
public class ClingyExamplesMouseDrag : MonoBehaviour {
ClingyMouse mouse;
Attachment attachment;
public AttachStrategy dragStrategy;
void Start() {
mouse = GetComponent<ClingyMouse>();
mouse.events.OnMouse0Down.AddListener(info => {
Collider2D coll = Physics2D.OverlapPoint(transform.position);
if (!coll)
return;
attachment = Clingy.AttachOneToOne(dragStrategy, gameObject, coll.gameObject);
});
mouse.events.OnMouse0Up.AddListener(info => {
if (attachment != null) {
attachment.Detach();
attachment = null;
}
});
}
}
|
using Mojang.Minecraft.Protocol.Providers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Mojang.Minecraft.Protocol
{
public partial class EssentialClient
{
private void OnPackageReceived(FieldMatcher fieldMatcher)
{
try
{
_PackageHandlerManager.InvokeHandler(new PackageHandlerKey(fieldMatcher.PackageTypeCode, _ConnectState), fieldMatcher);
}
catch (ArgumentException)
{
}
catch (HandlerNotFoundException)
{
}
}
/// <summary>
/// 在控制台中输出指定handler的签名及实参
/// </summary>
[Conditional("DEBUG")]
private void ShowPackageHandlerInvokeMessage(HandlerInfo<EssentialClient, PackageHandlerAttribute, PackageHandlerKey> handler, object[] actualParameters, string[] handlerRange)
{
if (handlerRange.Contains(handler.Name))
{
var output = new StringBuilder($"handler's invoking info: {handler.Name}");
output.AppendLine();
for (var i = 0; i < actualParameters.Length; i++)
output.AppendLine($"{handler.Fields[i].Name}: {actualParameters[i]?.ToString() ?? "null"}");
Console.WriteLine(output);
}
}
}
}
|
//using System.Linq;
//using ApartmentApps.Api.BindingModels;
//using ApartmentApps.Api.ViewModels;
//using ApartmentApps.Data;
//using ApartmentApps.Data.Repository;
//using ApartmentApps.Portal.Controllers;
//using ApartmentApps.Modules.CourtesyOfficer;
//namespace ApartmentApps.Api
//{
// public class IncidentService : StandardCrudService<IncidentReport, IncidentReportViewModel>
// {
// public IMapper<ApplicationUser, UserBindingModel> UserMapper { get; set; }
// public PropertyContext Context { get; set; }
// private IBlobStorageService _blobStorageService;
// private readonly IUserContext _userContext;
// public IncidentService(IMapper<ApplicationUser, UserBindingModel> userMapper, IBlobStorageService blobStorageService, PropertyContext context, IUserContext userContext) : base(context.IncidentReports)
// {
// UserMapper = userMapper;
// Context = context;
// _blobStorageService = blobStorageService;
// _userContext = userContext;
// }
// public IncidentService(IRepository<IncidentReport> repository, IMapper<IncidentReport, IncidentReportViewModel> mapper) : base(repository, mapper)
// {
// }
// public override void ToModel(IncidentReportViewModel viewModel, IncidentReport model)
// {
// }
// public override void ToViewModel(IncidentReport model, IncidentReportViewModel viewModel)
// {
// viewModel.Title = model.IncidentType.ToString();
// viewModel.RequestDate = model.CreatedOn;
// viewModel.Comments = model.Comments;
// viewModel.SubmissionBy = UserMapper.ToViewModel(model.User);
// viewModel.StatusId = model.StatusId;
// viewModel.Id = model.Id.ToString();
// viewModel.UnitName = model.Unit?.Name;
// viewModel.BuildingName = model.Unit?.Building?.Name;
// viewModel.LatestCheckin = model.LatestCheckin?.ToIncidentCheckinBindingModel(_blobStorageService);
// viewModel.Checkins = model.Checkins.Select(p => ApartmentApps.Modules.CourtesyOfficer.ModelExtensions.ToIncidentCheckinBindingModel(p, _blobStorageService));
// }
// }
//} |
namespace Entoarox.AdvancedLocationLoader.Configs
{
internal class Override : MapFileLink
{
/*********
** Public methods
*********/
public override string ToString()
{
return $"Override({this.MapName},{this.FileName})";
}
}
}
|
using Newtonsoft.Json;
using Settlement.Classes.Other;
using System.Collections.Generic;
namespace Settlement.Classes.DataModel
{
public class Transaction
{
[JsonProperty("created_settlement_dt")]
public string CreatedDatetimeSettlement { get; set; }
[JsonProperty("bank")]
public string Bank { get; set; }
[JsonProperty("details")]
public List<DetailTransaction> DetailTransaction;
public Transaction(string createdDatetimeSettlement, string bank, List<DetailTransaction> details)
{
CreatedDatetimeSettlement = createdDatetimeSettlement;
Bank = bank;
DetailTransaction = details;
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Foundry.Website.Models.Account
{
public class RegisterViewModel : ViewModel
{
[Required(ErrorMessage = "Email is required to login.")]
public string Email { get; set; }
[Required(ErrorMessage = "Username is required to login.")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required to register.")]
public string Password { get; set; }
[Required(ErrorMessage = "Password is required to register.")]
public string PasswordAgain { get; set; }
[Required(ErrorMessage = "Display Name is required to login.")]
public string DisplayName { get; set; }
}
} |
using UnityEngine;
//using UnityEditor;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using MusicIO;
using UI;
public abstract class BaseAttachment : MonoBehaviour{
public bool isCloneable;
public bool isDraggable;
public bool isDockable;
public virtual void Awake(){
m_isCloneable = isCloneable;
m_isDockable = isDockable;
m_isDockable = isDockable;
m_acceptedTypes = new List<System.Type>();
m_childDockables = new List<BaseAttachment>();
SetCollideable(m_doesCollide);
}
public virtual void Start(){}
public virtual void Update()
{
if (m_toggleControls)
{
m_toggleControls = false;
ToggleControls();
}
}
/*
* Unity status setters
*/
public void SetActive(){gameObject.SetActive(true);}
public void SetInactive(){gameObject.SetActive(false);}
/*
* Filter to only respond to defined tool modes
*/
public void SetToolmodeResponse(BaseTool.ToolMode[] modes){ m_respondsToToolMode = modes; }
public BaseTool.ToolMode[] m_respondsToToolMode;
public bool respondsToToolMode(BaseTool.ToolMode mode){
if(m_respondsToToolMode.Length > 0){
foreach(BaseTool.ToolMode responder in m_respondsToToolMode){
if(responder == mode)
return true;
}
//Always return true when hovering over an attachment
if (mode == BaseTool.ToolMode.IDLE)
return true;
}
return false;
}
/*
* Collider references
*/
public bool m_doesCollide = true;
public bool IsCollideable{ get { return m_doesCollide; }}
public void SetCollideable(bool state){
m_doesCollide = state;
if (m_interiorTrigger == null || m_proximityTrigger == null)
{
Transform area = transform.Find("areaTrigger");
if(area != null){
Transform interior = area.Find("interiorTrigger");
Transform proximity = area.Find("proximityTrigger");
m_interiorTrigger = interior.GetComponent<HandProximityTrigger>();
m_proximityTrigger = proximity.GetComponent<HandProximityTrigger>();
m_interiorTrigger.isActive = m_doesCollide;
m_proximityTrigger.isActive = m_doesCollide;
}
}
}
protected HandProximityTrigger m_interiorTrigger;
protected HandProximityTrigger m_proximityTrigger;
public HandProximityTrigger interiorTrigger { get { return m_interiorTrigger; } }
public HandProximityTrigger proximityTrigger { get { return m_proximityTrigger; } }
public virtual Collider interiorCollider{ get {return m_interiorTrigger.collider; }}
public virtual Collider proximityCollider{ get {return m_proximityTrigger.collider; }}
/*
* Collider size updaters
*/
public void UpdateColliders(Vector3 position, Vector3 size)
{
UpdateColliders(position, size, 1.2f);
}
public void UpdateColliders(Vector3 position, float size)
{
UpdateColliders(position, new Vector3(size, size, size), 1.2f);
}
public void UpdateColliders(Vector3 position, Vector3 size, float extMultiplier)
{
m_interiorTrigger.UpdateCollider(position, size);
m_proximityTrigger.UpdateCollider(position, size * extMultiplier);
}
/*
* Transient states
*/
public void SetTransient(bool state) { m_isTransient = state; }
public bool IsTransient { get { return m_isTransient; } }
protected bool m_isTransient;
public void SetCloneable(bool state) { m_isCloneable = state; isCloneable = state;}
public bool IsCloneable { get { return m_isCloneable; } }
protected bool m_isCloneable;
/*
* Music reference state
*/
protected bool bHasMusicRef;
public bool HasMusicRef{ get { return bHasMusicRef; }}
/*
* First gesture states
*/
protected bool bIsFirstGesture = true;
public bool IsFirstGesture{ get { return bIsFirstGesture; }}
public void ResetFirstGesture(){ bIsFirstGesture = false; }
/*
* Active tool hand
*/
protected BaseTool.ToolHand m_hand;
public BaseTool.ToolHand ActiveHand{ get { return m_hand; }}
public void SetActiveHand(BaseTool.ToolHand hand){ m_hand = hand; }
/*
* Active tool modes
*/
protected BaseTool.ToolMode m_mode;
public BaseTool.ToolMode mode{ get { return m_mode; }}
public virtual void SetToolMode(BaseTool.ToolMode mode){ m_mode = mode; }
/*
* Selection
*/
protected bool m_selected;
public bool selected{ get { return m_selected; }}
public bool m_toggleControls;
public virtual void ToggleSelected(){ SetSelected(!m_selected); }
public virtual void SetSelected(bool state){
m_selected = state;
if (m_outlineMat != null)
{
if (selected)
{
SetOutlineColor(UIFactory.outlineSelectedColor);
SetOutlineSize(UIFactory.outlineSelectedSize);
}
else
{
SetOutlineColor(UIFactory.outlineDeselectedColor);
SetOutlineSize(0.0f);
}
}
}
/*
* Outline and hovering
*/
protected Material m_outlineMat;
public void SetOutlineMat(Material mat){ m_outlineMat = mat; }
public void SetOutlineSize(float size)
{
if (m_outlineMat != null)
iTween.ValueTo(gameObject, iTween.Hash("from", m_outlineMat.GetFloat("_Outline"), "to", size, "time", 0.15f, "onupdate", "SetOutlineUpdate", "easetype", iTween.EaseType.easeOutExpo));
}
public void SetOutlineColor(Color color)
{
if (m_outlineMat != null)
iTween.ValueTo(gameObject, iTween.Hash("from", m_outlineMat.GetColor("_OutlineColor"), "to", color, "time", 0.15f, "onupdate", "SetOutlineColorUpdate", "easetype", iTween.EaseType.easeOutExpo));
}
private void SetOutlineUpdate(float size){ m_outlineMat.SetFloat("_Outline", size); }
private void SetOutlineColorUpdate(Color color){ m_outlineMat.SetColor("_OutlineColor", color); }
public virtual void StartHover()
{
if(!selected){
SetOutlineSize(UIFactory.outlineHoverSize);
SetOutlineColor(UIFactory.outlineHoverColor);
}
}
public virtual void StopHover()
{
if(!selected){
SetOutlineSize(0.0f);
SetOutlineColor(UIFactory.outlineDeselectedColor);
}
}
/*
* Dragging states
*/
protected bool m_isDragging;
protected void SetIsDragging(bool state){ m_isDragging = (IsDraggable) ? state : false; isDraggable = state;}
public bool IsDragging{ get { return (IsDraggable) ? m_isDragging : false; }}
protected bool m_isDraggable;
public bool IsDraggable{
get { return m_isDraggable; }
}
public void SetIsDraggable(bool state){
m_isDraggable = state;
if(!m_isDraggable) m_isDragging = false;
}
public virtual void StartDragging(GameObject target){
if (IsDraggable)
{
//StartDragging(HydraController.Instance.GetHand(m_hand));
if (!HydraController.Instance.IsHandDragging(m_hand))
{
//Clone instrument here
if (IsCloneable)
{
BaseAttachment attach = UIFactory.CreateGhostDragger(this);
attach.StartDragging(HydraController.Instance.GetHand(m_hand));
}
else
{
if (IsDragging) StopDragging();
SetIsDragging(true);
Undock();
FixedJoint joint = gameObject.AddComponent<FixedJoint>();
joint.connectedBody = target.GetComponent<Rigidbody>();
rigidbody.isKinematic = false;
HydraController.Instance.SetHandDragging(m_hand, this);
}
}
}
}
public virtual void StopDragging(){
if (IsDragging)
{
FixedJoint[] jointList = gameObject.GetComponents<FixedJoint>();
for(int i = 0 ; i < jointList.Length; i++){
Destroy( jointList[i] );
}
rigidbody.isKinematic = true;
SetIsDragging(false);
//If we're a dockable object, we need to find something to slot into.
if(IsDockable) DockIntoClosest();
HydraController.Instance.SetHandDragging(m_hand, null);
}
}
/*
* Docking states
*/
protected bool m_acceptsDockables;
protected bool m_isDockable;
public void SetAsDock(bool state){ m_acceptsDockables = state;}
public void SetIsDockable(bool state){ m_isDockable = state;}
public bool IsDock{ get { return m_acceptsDockables;}}
public bool IsDockable{ get { isDockable = true; return m_isDockable; }}
/*
* Docked children / owner accessors
*/
protected BaseAttachment m_dockedInto;
protected BaseAttachment m_dockedIntoLast;
public BaseAttachment DockedInto{ get { return m_dockedInto; }}
protected List<BaseAttachment> m_childDockables;
public List<BaseAttachment> DockedChildren{ get { return m_childDockables; }}
/*
* Dockable object modifiers
*/
public virtual void DockInto(BaseAttachment attach){
attach.AddDockableAttachment(this);
m_dockedInto = attach;
m_dockedIntoLast = attach;
if(IsDraggable) SetIsDragging(false);
}
public virtual void Undock(){
if(m_dockedInto != null){
m_dockedInto.RemoveDockableAttachment(this);
m_dockedInto = null;
}
}
public virtual void DockIntoClosest(){
GameObject[] docks = GameObject.FindGameObjectsWithTag("ParentIsADock");
BaseAttachment closestValidDock = null;
float closestDist = 0.0f;
foreach(GameObject dockTag in docks){
BaseAttachment dockAttach = dockTag.transform.parent.GetComponent<BaseAttachment>();
if(dockAttach.DockAcceptsType(this.GetType())){
if(closestValidDock == null){
closestDist = Vector3.Distance( dockAttach.transform.position, transform.position);
closestValidDock = dockAttach;
}
float dist = Vector3.Distance( dockAttach.transform.position, transform.position);
if( dist < closestDist ){
closestValidDock = dockAttach;
closestDist = dist;
}
}
}
if(closestValidDock != null){
if (IsInDockingRange(closestValidDock, closestValidDock.dockingRange))
DockInto(closestValidDock);
else
Floating();
} else {
Floating();
}
}
public virtual void Floating()
{
if (IsTransient)
{
if (DockedInto == null)
{
GameObject.Destroy(gameObject);
return;
}
}
if (m_dockedIntoLast != null)
DockInto(m_dockedIntoLast);
}
/*
* Dock modifiers
*/
public virtual bool AddDockableAttachment(BaseAttachment attach){
if(m_childDockables == null)
m_childDockables = new List<BaseAttachment>();
if(DockAcceptsType(attach.GetType())){
m_childDockables.Add(attach);
attach.transform.parent = transform;
return true;
} else {
Debug.LogError(this + " can't dock with a " + attach.GetType());
}
return false;
}
public virtual void RemoveDockableAttachment(BaseAttachment attach){
while(m_childDockables.Contains(attach))
m_childDockables.Remove(attach);
attach.transform.parent = null;
}
/*
* Dock type / distance checking
*/
protected List<System.Type> m_acceptedTypes;
public void AddAcceptedDocktype(System.Type type){m_acceptedTypes.Add(type);}
public bool DockAcceptsType(System.Type type){
foreach(System.Type acceptedType in m_acceptedTypes){
if(type == acceptedType)
return true;
}
return false;
}
public float dockingRange = 1.5f;
public virtual bool IsInDockingRange(BaseAttachment attach, float range){
if(attach == null)
return false;
return (Vector3.Distance(transform.position, attach.transform.position) < range) ? true : false;
}
/*
* Child UI controls
*/
public bool controlsEnabled { get { return m_controlsEnabled; } }
protected bool m_controlsEnabled = true;
public bool controlsVisible { get { return m_controlsVisible; } }
protected bool m_controlsVisible;
public void EnableControls() { m_controlsEnabled = true; }
public void DisableControls()
{
m_controlsEnabled = false;
HideControls();
}
public virtual void ShowControls() { m_controlsVisible = true; }
public virtual void HideControls() { m_controlsVisible = false; }
public void ToggleControls() {
if(controlsVisible)
HideControls();
else
ShowControls();
}
/*
* Gesture implementations
*/
public virtual void Gesture_First(){ bIsFirstGesture = false; }
public virtual void Gesture_Exit(){ bIsFirstGesture = true; }
public virtual void Gesture_IdleInterior(){}
public virtual void Gesture_IdleProximity(){}
public virtual void Gesture_IdleExterior(){}
public virtual void Gesture_ExitIdleInterior(){}
public virtual void Gesture_ExitIdleProximity() {}
public virtual void Gesture_ExitIdleExterior() {}
public virtual void Gesture_PushIn(){}
public virtual void Gesture_PullOut(){}
public virtual void Gesture_Twist(float amount){}
}
/*
* Derived classes from BaseAttachment can specify what type of music specific object they are meant to represent
*/
public class BaseAttachmentIO<T> : BaseAttachment {
private T m_musicRef;
public virtual void Init(T managedReference){
m_musicRef = managedReference;
bHasMusicRef = true;
//Set default tool filter if not set
if(m_respondsToToolMode == null)
m_respondsToToolMode = new BaseTool.ToolMode[]{BaseTool.ToolMode.PRIMARY, BaseTool.ToolMode.SECONDARY};
}
public T musicRef{ get { return m_musicRef; }}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Zitadel.Authentication.Options;
namespace Zitadel.Authentication.Handler
{
internal class LocalFakeZitadelHandler : AuthenticationHandler<LocalFakeZitadelSchemeOptions>
{
private const string FakeAuthHeader = "x-zitadel-fake-auth";
public LocalFakeZitadelHandler(
IOptionsMonitor<LocalFakeZitadelSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (Context.Request.Headers.TryGetValue(FakeAuthHeader, out var value) && value == "false")
{
return Task.FromResult(AuthenticateResult.Fail($@"The {FakeAuthHeader} was set with value ""false""."));
}
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, Options.FakeZitadelOptions.FakeZitadelId),
new("sub", Options.FakeZitadelOptions.FakeZitadelId),
}.Concat(Options.FakeZitadelOptions.AdditionalClaims)
.Concat(Options.FakeZitadelOptions.Roles.Select(r => new Claim(ClaimTypes.Role, r)));
var identity = new ClaimsIdentity(claims, ZitadelDefaults.FakeAuthenticationScheme);
return Task.FromResult(
AuthenticateResult.Success(
new AuthenticationTicket(new ClaimsPrincipal(identity), ZitadelDefaults.FakeAuthenticationScheme)));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Optymalizacja_wykorzystania_pamieci.Tasks.Graph
{
class Subgraph
{
public Vertex representative { get; set; }
public List<Vertex> list_of_vertices { get; set; }
public Subgraph(Vertex vertex)
{
this.representative = vertex;
this.list_of_vertices = new List<Vertex>();
list_of_vertices.Add(vertex);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HandlingWordRules
{
public class cntOfSqcWrdsStartCA : ICountingRulesStrategy
{
//Requirement 4/Rule 4 : For all the words starts with “c” or “C”, if the next word starts with “a” or “A”, count the number of this
//sequence.Save the result to “count_of_sequence_of_words_starting_withs_c_and_a.txt”
//The method: ruleImplementation gets implemented with the business requirement
public float ruleImplementation(List<string> inputWordsList)
{
int posOfWordStartWithA;
float SqcWrdsStartCA = 0;
foreach (string innerString in inputWordsList)
{
if (innerString.StartsWith("C"))
{
posOfWordStartWithA = inputWordsList.IndexOf(innerString);
if (inputWordsList[posOfWordStartWithA + 1].StartsWith("A")) { SqcWrdsStartCA++; };
}
}
return SqcWrdsStartCA;
string[] lines = { SqcWrdsStartCA.ToString() };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\count_of_sequence_of_words_starting_withs_c_and_a.txt", lines);
//throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.matrix_problems
{
/// <summary>
/// Rotate the square matrix inplace by 90 degree
/// </summary>
class Rotate_Matrix_90_degree
{
public int[,] RotateMatrix(int[,] mat)
{
// get the row length of the matrix
int rowLength = mat.GetLength(0)-1;
// get the column length of the matrix
int colLength = mat.GetLength(1)-1;
// We need to traverse the row of the matrix from 0 to rowLength/2, because
// for each row traversal we will traverse the outermost square with the row as
// one of the sides of the square
for (int r =0; r <= (int)rowLength/2; r++)
{
// We will traverse the outermost square
// top-left corner of the square will be (r,r)
// top-right corner of the square will be (r,colLength-r)
for (int c = r; c < colLength -r; c++)
{
int temp = mat[r, c];
mat[r, c] = mat[rowLength - c, r];
mat[rowLength - c, r] = mat[rowLength - r, colLength - c];
mat[rowLength - r, colLength - c] = mat[c, colLength - r];
mat[c, colLength - r] = temp;
}
}
return mat;
}
public static void TestRotateMatrix()
{
Rotate_Matrix_90_degree rtMat = new Rotate_Matrix_90_degree();
int[,] mat = MatrixProblemHelper.CreateMatrix(4, 4);
MatrixProblemHelper.PrintMatrix(mat);
Console.WriteLine();
mat = rtMat.RotateMatrix(mat);
MatrixProblemHelper.PrintMatrix(mat);
}
}
}
|
using System.Linq.Expressions;
using SpatialEye.Framework.Client;
using SpatialEye.Framework.Parameters;
using glf = SpatialEye.Framework.Features.Expressions.GeoLinqExpressionFactory;
namespace Lite
{
/// <summary>
/// A sample representation of a Feature Geometry element, displaying the number of elements
/// </summary>
public class LiteMapThemeLayerFeatureGeometryElement : MapThemeLayerElementViewModel
{
#region Static Property Names
/// <summary>
/// The property name for the description property
/// </summary>
public static string DescriptionPropertyName = "Description";
#endregion
#region Fields
/// <summary>
/// The description to be displayed as part of the Themes
/// </summary>
private string _description;
private FeatureGeometryMapLayerViewModel _featureGeometryMapLayerViewModel;
#endregion
#region Constructor
/// <summary>
/// Constructor for the feature geometry description element
/// </summary>
internal LiteMapThemeLayerFeatureGeometryElement(MapViewModel map, FeatureGeometryMapLayerViewModel featureGeometryLayer)
{
this.Map = map;
this.Map.PropertyChanged += Map_PropertyChanged;
this.FeatureGeometryLayer = featureGeometryLayer;
}
#endregion
#region Internal helpers
/// <summary>
/// Returns a predicate that determines whether things are on screen
/// </summary>
private Expression OnScreenPredicate()
{
var field = FeatureGeometryLayer.GeometryField;
var constant = SystemParameterManager.Instance.CurrentMapExtent;
return constant != null ? glf.Spatial.Interacts(glf.Data.Field(field), glf.Constant(constant)) : null;
}
/// <summary>
/// A property of the map has changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Map_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == MapViewModel.EnvelopePropertyName)
{
// Only set up the description in case the map is not busy
if (!Map.IsAnimating && !Map.IsPanning)
{
SetupDescription();
}
}
}
/// <summary>
/// A property has changed of the feature geometry layer
/// </summary>
void FeatureGeometryLayer_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == FeatureGeometryMapLayerViewModel.FeaturesPropertyName)
{
SetupDescription();
}
}
/// <summary>
/// Sets up the description
/// </summary>
private async void SetupDescription()
{
var features = this.FeatureGeometryLayer.Features;
var count = 0;
var countOnScreen = 0;
if (features != null)
{
var onScreen = OnScreenPredicate();
count = features.Count;
countOnScreen = onScreen != null ? await features.Where(onScreen).CountAsync() : 0;
}
Description = string.Format("{0} - {1} {2}", countOnScreen, count, this.FeatureGeometryLayer.GeometryField.TableDescriptor.ExternalName);
}
#endregion
#region Public Properties
/// <summary>
/// The map that we are belonging to
/// </summary>
private MapViewModel Map
{
get;
set;
}
/// <summary>
/// The feature geometry layer
/// </summary>
private FeatureGeometryMapLayerViewModel FeatureGeometryLayer
{
get
{
return _featureGeometryMapLayerViewModel;
}
set
{
if (_featureGeometryMapLayerViewModel != null)
{
_featureGeometryMapLayerViewModel.PropertyChanged -= FeatureGeometryLayer_PropertyChanged;
}
_featureGeometryMapLayerViewModel = value;
_featureGeometryMapLayerViewModel.PropertyChanged += FeatureGeometryLayer_PropertyChanged;
}
}
/// <summary>
/// The description of the Feature Geometry Layer, to be picked up for display
/// in the themes part
/// </summary>
public string Description
{
get { return _description; }
set
{
if (_description != value)
{
_description = value;
RaisePropertyChanged(DescriptionPropertyName);
}
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace learningWindowsForms.Models
{
public class Parameter
{
public int ParameterID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public bool PreQuery { get; set; }
public bool Required { get; set; }
}
}
|
using Anywhere2Go.Business.Master;
using Anywhere2Go.DataAccess.Entity;
using Claimdi.Web.TH.Filters;
using Claimdi.Web.TH.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Claimdi.Web.TH.Controllers
{
public class TaskPriorityController : Controller
{
// GET: TaskPriority
[AuthorizeUser(AccessLevel = "View", PageAction = "TaskPriority")]
public ActionResult Index()
{
TaskLogic task = new TaskLogic();
var result = task.getTaskPriority();
return View( "~/Views/Admin/taskpriority/Index.cshtml",result);
}
[AuthorizeUser(AccessLevel = "Add", PageAction = "TaskPriority")]
public ActionResult Create()
{
return View("~/Views/Admin/taskpriority/CreateEdit.cshtml", new TaskPriority() { taskPriorityId = "", sort = 99, isActive = true });
}
[AuthorizeUser(AccessLevel = "Edit", PageAction = "TaskPriority")]
public ActionResult Edit(string id)
{
TaskLogic task = new TaskLogic();
return View("~/Views/Admin/taskpriority/CreateEdit.cshtml", task.getTaskPriority(id).SingleOrDefault());
}
[HttpPost]
[AuthorizeUser(AccessLevel = "Edit", PageAction = "TaskPriority")]
public ActionResult CreateEdit(TaskPriority model)
{
if (ModelState.IsValid)
{
TaskLogic task = new TaskLogic();
var res = task.saveTaskPriority(model, ClaimdiSessionFacade.ClaimdiSession);
if (res.Result) {
//return RedirectToAction("Index");
ViewBag.Message = "success";
}
else
{
ViewBag.Message = res.Message;
}
}
return View("~/Views/Admin/taskpriority/CreateEdit.cshtml", model);
}
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.CUST
{
[Serializable]
public partial class RoutingPositionMap : EntityBase
{
#region O/R Mapping Properties
//[Display(Name = "SAPPosition", ResourceType = typeof(Resources.CUST.RoutingPositionMap))]
public string SAPPosition { get; set; }
//[Display(Name = "Position", ResourceType = typeof(Resources.CUST.RoutingPositionMap))]
public string Position { get; set; }
//[Display(Name = "Location", ResourceType = typeof(Resources.CUST.RoutingPositionMap))]
public string Location { get; set; }
#endregion
public override int GetHashCode()
{
if (SAPPosition != null)
{
return SAPPosition.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
RoutingPositionMap another = obj as RoutingPositionMap;
if (another == null)
{
return false;
}
else
{
return (this.SAPPosition == another.SAPPosition);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignPatternsApp.Models
{
public class FoodMenuModel
{
private string restaurantID;
public string RestaurantID
{
get { return restaurantID; }
set { restaurantID = value; }
}
private string foodID;
public string FoodID
{
get { return foodID; }
set { foodID = value; }
}
private string foodName;
public string FoodName
{
get { return foodName; }
set { foodName = value; }
}
private string cuisine;
public string Cuisine
{
get { return cuisine; }
set { cuisine = value; }
}
private double price;
public double Price
{
get { return price; }
set { price = value; }
}
private double rating;
public double Rating
{
get { return rating; }
set { rating = value; }
}
}
}
|
namespace FacebookClone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class PopulateGender : DbMigration
{
public override void Up()
{
Sql(@"INSERT INTO Genders ( Name ) values ( 'Male' )");
Sql(@"INSERT INTO Genders ( Name ) values ( 'Female' )");
}
public override void Down()
{
Sql(@"DELETE FROM Genders WHERE Name = 'Male'");
Sql(@"DELETE FROM Genders WHERE Name = 'Female'");
}
}
}
|
using System;
using System.Linq;
using System.Linq.Expressions;
namespace GenRepo
{
internal class Query<T> : IQuery<T, T>
{
private readonly IFilter<T> _filter;
public Query(IFilter<T> filter)
{
_filter = filter;
}
public IQueryable<T> Execute(IQueryable<T> items)
{
return _filter.Apply(items);
}
}
public static class QueryExtension
{
public static IQuery<TIn, TOut> OrderBy<TIn, TOut>(this IQuery<TIn, TOut> query, Func<Order<TOut>, IOrder<TOut>> orderFunc)
{
return new OrderedQuery<TIn, TOut>(query, orderFunc(new Order<TOut>()));
}
public static IQuery<TIn, TOut> ToProjection<TIn, TOut>(this IQuery<TIn, TIn> query, Expression<Func<TIn, TOut>> projection)
{
return new ProjectedQuery<TIn, TOut>(query, projection);
}
}
public static class Query
{
public static IQuery<TIn,TIn> WithFilter<TIn>(Filter<TIn> filter)
=> new Query<TIn>(filter);
public static IQuery<TIn, TIn> Everything<TIn>() => WithFilter(Filter<TIn>.Nothing);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace task1_Odd_Lines
{
public class task1_Odd_Lines
{
public static void Main()
{
var lines = File.ReadAllLines("TextFile1.txt");
if (!File.Exists("result.txt"))
{
File.Create("result.txt");
}
var oddLines = new List<string>();
for (int i = 0; i < lines.Length; i++)
{
if (i%2 != 0)
{
oddLines.Add(lines[i]);
}
}
File.WriteAllLines("result.txt", oddLines);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.