text
stringlengths 13
6.01M
|
|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Dentistry
{
class database_
{
public static string STR_CON = @"Data Source=SAMAN\SERVER;Initial Catalog=dbsell92;Integrated Security=True";
static public DataSet DS = new DataSet();
/////////////////////////////////////////////////////////SQLITE///////////////////////////////////////////////////////////
public static void SetConString()
{
if (Vars.dbPassword == "" && Vars.dbuser == "")
{
database_.STR_CON = String.Format(@"Data Source={0};Initial Catalog={1};Integrated Security=True", Vars.server, Vars.dbname);
}
else
{
database_.STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.server, Vars.dbname, Vars.dbuser, Vars.dbPassword);
}
}
static public DataSet showData(string strsql)
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = STR_CON;
con1.Open();
SqlDataAdapter da = new SqlDataAdapter(strsql, con1);
DataSet ds = new DataSet();
da.Fill(ds);
con1.Close();
return (ds);
}
static public string ExeScalar(string sqlstr)
{
SqlConnection con1 = new SqlConnection(STR_CON);
con1.Open();
SqlCommand objcmd = new SqlCommand(sqlstr, con1);
object tmp = new object();
string temp = "";
tmp = objcmd.ExecuteScalar();
con1.Close();
if (tmp != null)
{
temp = Convert.ToString(tmp);
return (temp);
}
else
return ("");
}
public static Boolean SetData(SqlCommand cmd)
{
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
//SqlCommand cmd = new SqlCommand(STR_COM, con);
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static Boolean getScalar(string STR_COM1, ref string obj)
{
//string STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.Server, Vars.dbName, Vars.dbUser, Vars.dbPassword);
string STR_CON1 = STR_CON;
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
string ScalarObj = "0";
obj = "";
SqlCommand SqlCom = new SqlCommand(STR_COM1, con);
try
{
ScalarObj = SqlCom.ExecuteScalar().ToString();
if (ScalarObj != "")
{
obj = ScalarObj;
}
else
{
obj = "0";
}
}
catch (NullReferenceException ex)
{
obj = "0";
NoError = false;
//MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (NullReferenceException ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static Boolean getScalar(string STR_COM, ref string obj, Boolean ShowErr)
{
// string STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.Server, Vars.dbName, Vars.dbUser, Vars.dbPassword);
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
string ScalarObj = "";
SqlCommand SqlCom = new SqlCommand(STR_COM, con);
try
{
ScalarObj = SqlCom.ExecuteScalar().ToString();
if (ScalarObj != "") obj = ScalarObj;
}
catch (NullReferenceException ex)
{
NoError = false;
if (ShowErr) MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (NullReferenceException ex)
{
NoError = false;
if (ShowErr) MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static Boolean getScalar(string STR_COM, ref object obj)
{
//string STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.Server, Vars.dbName, Vars.dbUser, Vars.dbPassword);
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
object ScalarObj = "";
SqlCommand SqlCom = new SqlCommand(STR_COM, con);
try
{
ScalarObj = SqlCom.ExecuteScalar();
if (ScalarObj != null) obj = ScalarObj;
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static object getScalar(string STR_COM)
{
// string STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.Server, Vars.dbName, Vars.dbUser, Vars.dbPassword);
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
object ScalarObj = "";
SqlCommand SqlCom = new SqlCommand(STR_COM, con);
try
{
ScalarObj = SqlCom.ExecuteScalar();
if (ScalarObj != null)
{
return ScalarObj;
}
else
{
return null;
}
}
catch (NullReferenceException ex)
{
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
return false;
}
}
catch (NullReferenceException ex)
{
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
return false;
}
finally
{
if (con != null)
con.Dispose();
}
}
public static SqlConnection OpenConnection()
{
// string STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.Server, Vars.dbName, Vars.dbUser, Vars.dbPassword);
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
return con;
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
return null;
}
public static Boolean getdata(string STR_COM, DataSet ds)
{
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
SqlDataAdapter dr = new SqlDataAdapter(STR_COM, con);
try
{
dr.Fill(ds);
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static Boolean getdata(SqlCommand cmd, DataGridView dgv, int ColCount)
{
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
cmd.Connection = con;
try
{
SqlDataReader dr = cmd.ExecuteReader();
object[] obj = new object[ColCount];
while (dr.Read())
{
dr.GetValues(obj);
dgv.Rows.Add(obj);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static void SetData2(SqlConnection con, SqlCommand cmd, SqlTransaction tr)
{
cmd.Connection = con;
cmd.Transaction = tr;
cmd.ExecuteNonQuery();
}
public static Boolean SetData(string STR_COM)
{
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
SqlCommand cmd = new SqlCommand(STR_COM, con);
try
{
cmd.ExecuteNonQuery();
//var t = Task<int>.Factory.FromAsync(cmd., cmd.EndExecuteNonQuery, null);
//t.Wait();
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static string computMande(string code)
{
try
{
string cmd = "Select sum(abs(bedehkar))-sum(abs(bestankar)) from tblgrsanad where tafzilyCode='" + code + "'";
database_.getScalar(cmd, ref code);
return code;
}
catch
{
return "0";
}
}
public static void computMande2(string code,ref string bed,ref string bes,ref string mand)
{
DataSet ds = new DataSet();
try
{
string cmd = "Select sum(abs(bedehkar)),sum(abs(bestankar)),sum(abs(bedehkar))-sum(abs(bestankar)) from tblgrsanad where tafzilyCode='" + code + "'";
database_.getdata(cmd, ds);
bed = ds.Tables[0].Rows[0][0].ToString();
bes = ds.Tables[0].Rows[0][1].ToString();
mand = ds.Tables[0].Rows[0][2].ToString();
//return code;
}
catch
{
bed = "0";
bes = "0";
mand = "0";
//return "0";
}
}
public static Boolean getdata(string STR_COM, DataSet ds, string DataTable)
{
// string STR_CON = String.Format("Server ={0}; initial catalog={1};user id={2};password={3};Asynchronous Processing=true", Vars.Server, Vars.dbName, Vars.dbUser, Vars.dbPassword);
Boolean NoError = true;
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = STR_CON;
con.Open();
SqlDataAdapter dr = new SqlDataAdapter(STR_COM, con);
try
{
dr.Fill(ds, DataTable);
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
public static void moenMande(string code, ref string bed, ref string bes, ref string mand)
{
DataSet ds = new DataSet();
try
{
string cmd = "Select sum(abs(bedehkar)),sum(abs(bestankar)),sum(abs(bedehkar))-sum(abs(bestankar)) from tblgrsanad where MoenCode='" + code + "'";
database_.getdata(cmd, ds);
bed = ds.Tables[0].Rows[0][0].ToString();
bes = ds.Tables[0].Rows[0][1].ToString();
mand = ds.Tables[0].Rows[0][2].ToString();
//return code;
}
catch
{
bed = "0";
bes = "0";
mand = "0";
//return "0";
}
}
public static Boolean getTarazMoen(SqlCommand cmd, DataGridView dgv, int ColCount)
{
Boolean NoError = true;
SqlConnection con = new SqlConnection();
double moenbed = 0;
double moenbes = 0;
double mandmoenbed = 0;
double mandmoenbes = 0;
int i = 0;
string coll = "101";
try
{
con.ConnectionString = STR_CON;
con.Open();
cmd.Connection = con;
try
{
SqlDataReader dr = cmd.ExecuteReader();
object[] obj = new object[ColCount];
object[] obj2 = new object[ColCount];
while (dr.Read())
{
dr.GetValues(obj);
if (coll != obj[1].ToString().Substring(0, 3))
{
obj2[0] = "";
obj2[1] = "";
obj2[2] = "جمع کل";
obj2[3] = moenbed;
obj2[4] = moenbes;
if (mandmoenbed - mandmoenbes > 0)
{
obj2[5] = mandmoenbed - mandmoenbes;
obj2[6] = "0";
}
else
{
obj2[5] = "0";
obj2[6] = mandmoenbes - mandmoenbed;
}
i = i + 1;
dgv.Rows.Add(obj2);
dgv.Rows[i - 1].Cells[0].Style.BackColor = Color.Salmon;
dgv.Rows[i - 1].Cells[1].Style.BackColor = Color.Salmon;
dgv.Rows[i - 1].Cells[2].Style.BackColor = Color.Salmon;
//dgv.Rows[i - 1].Cells[3].Style.BackColor = Color.Salmon;
//dgv.Rows[i - 1].Cells[4].Style.BackColor = Color.Salmon;
//dgv.Rows[i - 1].Cells[5].Style.BackColor = Color.Salmon;
//dgv.Rows[i - 1].Cells[6].Style.BackColor = Color.Salmon;
moenbed = 0;
moenbes = 0;
mandmoenbed = 0;
mandmoenbes = 0;
coll = obj[1].ToString().Substring(0, 3);
}
else
{
}
moenbed = moenbed + Functions.ConvertToDouble(obj[3]);
moenbes = moenbes + Functions.ConvertToDouble(obj[4]);
mandmoenbed = mandmoenbed + Functions.ConvertToDouble(obj[5]);
mandmoenbes = mandmoenbes + Functions.ConvertToDouble(obj[6]);
i = i + 1;
dgv.Rows.Add(obj);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای پرس و جو\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
}
catch (Exception ex)
{
NoError = false;
MessageBox.Show("خطای برقراری ارتباط\r\n" + ex.Message, Vars.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
}
finally
{
if (con != null)
con.Dispose();
}
return NoError;
}
}
}
|
using System;
using System.Diagnostics;
namespace Crystal.Plot2D.Common
{
public sealed class DisposableTimer : IDisposable
{
private readonly bool isActive = true;
private readonly string name;
readonly Stopwatch timer;
public DisposableTimer(string name) : this(name, true) { }
public DisposableTimer(string name, bool isActive)
{
this.name = name;
this.isActive = isActive;
if (isActive)
{
timer = Stopwatch.StartNew();
Trace.WriteLine(name + ": started " + DateTime.Now.TimeOfDay);
}
}
#region IDisposable Members
public void Dispose()
{
//#if DEBUG
if (isActive)
{
var duration = timer.ElapsedMilliseconds;
Trace.WriteLine(name + ": elapsed " + duration + " ms.");
timer.Stop();
}
//#endif
}
#endregion
}
}
|
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.Geometry.Tiling;
using gView.GraphicsEngine.Abstraction;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace gView.DataSources.TileCache
{
class ParentRasterClass : IRasterClass, IParentRasterLayer
{
private Dataset _dataset;
public ParentRasterClass(Dataset dataset)
{
_dataset = dataset;
}
#region IRasterClass Member
public Framework.Geometry.IPolygon Polygon
{
get
{
if (_dataset != null)
{
return _dataset.Extent.ToPolygon(0);
}
return null;
}
}
public IBitmap Bitmap
{
get { return null; }
}
public double oX
{
get { return 0D; }
}
public double oY
{
get { return 0D; }
}
public double dx1
{
get { return 0D; }
}
public double dx2
{
get { return 0D; }
}
public double dy1
{
get { return 0D; }
}
public double dy2
{
get { return 0D; }
}
public Framework.Geometry.ISpatialReference SpatialReference
{
get
{
return ((gView.DataSources.TileCache.Dataset)this.Dataset).SpatialReference;
}
set
{
}
}
public Task<IRasterPaintContext> BeginPaint(Framework.Carto.IDisplay display, Framework.system.ICancelTracker cancelTracker)
{
return Task.FromResult<IRasterPaintContext>(new RasterPaintContext(null));
}
#endregion
#region IClass Member
public string Name
{
get { return this.Dataset.DatasetName; }
}
public string Aliasname
{
get { return this.Name; }
}
public IDataset Dataset
{
get { return _dataset; }
set { _dataset = value as Dataset; }
}
#endregion
#region IParentRasterLayer Member
public Task<IRasterLayerCursor> ChildLayers(gView.Framework.Carto.IDisplay display, string filterClause)
{
if (_dataset == null || _dataset.Extent == null || _dataset.Scales == null)
{
return null;
}
double dpi = 96.0; // gView Default... //25.4D / 0.28D; // wmts 0.28mm -> 1 Pixel in WebMercator;
// !!!! Only correct, if diplay unit is meter !!!!
double displayResolution = display.mapScale / (display.dpi / 0.0254);
Grid grid = new Grid(new Point(_dataset.Extent.minx, _dataset.Extent.maxx), _dataset.TileWidth, _dataset.TileHeight, dpi, _dataset.Origin);
for (int i = 0, to = _dataset.Scales.Length; i < to; i++)
{
grid.AddLevel(i, _dataset.Scales[i] / (dpi / 0.0254));
}
IEnvelope dispEnvelope = display.DisplayTransformation.TransformedBounds(display); //display.Envelope;
if (display.GeometricTransformer != null)
{
dispEnvelope = ((IGeometry)display.GeometricTransformer.InvTransform2D(dispEnvelope)).Envelope;
}
int level = grid.GetBestLevel(displayResolution, 90D);
double res = grid.GetLevelResolution(level);
int col0 = grid.TileColumn(dispEnvelope.minx, res);
int row0 = grid.TileRow(dispEnvelope.maxy, res);
int col1 = grid.TileColumn(dispEnvelope.maxx, res);
int row1 = grid.TileRow(dispEnvelope.miny, res);
int col_from = Math.Max(0, Math.Min(col0, col1)), col_to = Math.Min((int)Math.Round(_dataset.Extent.Width / (_dataset.TileWidth * res), 0) - 1, Math.Max(col0, col1));
int row_from = Math.Max(0, Math.Min(row0, row1)), row_to = Math.Min((int)Math.Round(_dataset.Extent.Height / (_dataset.TileHeight * res), 0) - 1, Math.Max(row0, row1));
LayerCursor cursor = new LayerCursor();
for (int r = row_from; r <= row_to; r++)
{
for (int c = col_from; c <= col_to; c++)
{
cursor.Layers.Add(
new RasterTile(_dataset, grid, level, r, c, res));
}
}
cursor.Layers.Sort(new TileSorter(dispEnvelope.Center));
return Task.FromResult<IRasterLayerCursor>(cursor);
}
#endregion
#region Classes
private class LayerCursor : IRasterLayerCursor
{
private int _pos = 0;
internal List<IRasterLayer> Layers = new List<IRasterLayer>();
#region IRasterLayerCursor Member
public Task<IRasterLayer> NextRasterLayer()
{
if (_pos >= Layers.Count)
{
return Task.FromResult<IRasterLayer>(null);
}
return Task.FromResult<IRasterLayer>(Layers[_pos++]);
}
#endregion
#region IDisposable Member
public void Dispose()
{
}
#endregion
}
public class TileSorter : IComparer<IRasterLayer>
{
private IPoint _center;
public TileSorter(IPoint centerPoint)
{
_center = centerPoint;
}
#region IComparer<IRasterClass> Member
public int Compare(IRasterLayer x, IRasterLayer y)
{
IPolygon p1 = ((IRasterClass)x).Polygon;
IPolygon p2 = ((IRasterClass)y).Polygon;
if (p1 == null)
{
return 1;
}
if (p2 == null)
{
return -1;
}
double d1 = _center.Distance2(p1[0][0]);
double d2 = _center.Distance2(p2[0][0]);
if (d1 < d2)
{
return -1;
}
if (d1 > d2)
{
return 1;
}
return 0;
}
#endregion
}
#endregion
}
}
|
using System.Collections.Generic;
using Microsoft.VisualBasic.FileIO;
namespace FootballTAL.DataAccess
{
public class CSVFileReading : IFileReading
{
private string FullPath { get; set; }
public CSVFileReading(string path)
{
this.FullPath = path;
}
public IList<string[]> ReadFile()
{
List<string[]> fileContent = new List<string[]>();
//use in-build csv parser from Microsoft
using (TextFieldParser parser = new TextFieldParser(FullPath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
if (fields[0].ToString().ToLower() == "team" || fields[0].Contains("--"))
continue; //reach "----" or title row
fileContent.Add(fields);
}
}
return fileContent;
}
}
}
|
namespace P09TrafficLights.Enums
{
public enum TrafficLightEnumeration
{
Red,
Green,
Yellow
}
}
|
using NUnit.Framework;
using SingLife.FacebookShareBonus.Model;
using System.Collections.Generic;
namespace SingLife.FacebookShareBonus.Test
{
[TestFixture]
internal class FakeSortOrder : IPolicySortService
{
public IEnumerable<Policy> Sort(IEnumerable<Policy> policies)
{
return policies;
}
}
}
|
using UnityEngine;
using System.Collections;
public class End : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
Cursor.visible = true;
Application.LoadLevel(0);
}
}
|
namespace Models
{
public class ExchangeRate
{
public string Currency { get; set; }
public double Rate { get; set; }
}
}
|
// O(nlogn)
public class Solution {
private int MinWidth(int[] sums, int left, int right, int target) {
int start = left - 1;
while (left + 1 < right) {
int mid = (right - left) / 2 + left;
if (sums[mid] == target) return mid - start;
else if (sums[mid] < target) left = mid;
else right = mid;
}
//Console.WriteLine($"{start} {left} {right}");
if (sums[left] >= target) return left - start;
if (sums[right] >= target) return right - start;
return int.MaxValue;
}
public int MinSubArrayLen(int s, int[] nums) {
if (nums.Length == 0) return 0;
int[] sums = new int[nums.Length+1];
sums[0] = 0;
for (int i=1; i<=nums.Length; i++) {
sums[i] = sums[i-1] + nums[i-1];
}
int res = int.MaxValue;
for (int i=0; i<sums.Length-1; i++) {
int left = i + 1, right = sums.Length-1;
int currRes = MinWidth(sums, left, right, sums[i]+s);
res = Math.Min(res, currRes);
}
if (res != int.MaxValue) return res;
return 0;
}
}
// O(n)
/*
public class Solution {
public int MinSubArrayLen(int s, int[] nums) {
if (nums.Length == 0) return 0;
int left = 0, right = 1, res = int.MaxValue, sum = nums[0];
while (left < nums.Length) {
int currRes = int.MaxValue;
while (sum<s && right<nums.Length) {
sum += nums[right];
right++;
}
if (sum>=s) currRes = right-left;
res = Math.Min(res, currRes);
while (sum-nums[left]>=s && left<=right) {
sum -= nums[left];
left++;
}
if (sum>=s) currRes = right-left;
res = Math.Min(res, currRes);
sum -= nums[left];
left++;
if (right <= left) right = left + 1;
}
if (res != int.MaxValue) return res;
return 0;
}
}
*/
|
using BusinessObjects;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess
{
public class BookmarkDAO
{
private static BookmarkDAO instance = null;
private static readonly object instanceLock = new object();
private BookmarkDAO() { }
public static BookmarkDAO Instance
{
get
{
lock (instanceLock)
{
if (instance == null)
instance = new BookmarkDAO();
}
return instance;
}
}
public void AddBookmark(int postID, string username)
{
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
Bookmark bookmark = new Bookmark
{
PostId = postID,
Username = username
};
context.Bookmarks.Add(bookmark);
context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
public void DeleteBookmark(Bookmark bookmark)
{
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
context.Bookmarks.Remove(bookmark);
context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
public Bookmark GetBookmark(int postId, string username)
{
Bookmark bookmark = null;
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
//bookmark = context.Bookmarks.Where(b => b.PostId == postId && b.Username.Equals(username)).Single();
bookmark = context.Bookmarks.SingleOrDefault(b => b.PostId == postId && b.Username.Equals(username));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
return bookmark;
}
public IEnumerable<Post> GetPostsByBookmark(string username, int pageIndex)
{
List<Post> posts = new List<Post>();
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
SqlConnection con = (SqlConnection)context.Database.GetDbConnection();
string SQL = "SELECT PostId, PostTitle, PostDescription, FileURL, UploaderUsername, UploadDate FROM \n"
+ "(SELECT ROW_NUMBER() OVER(ORDER BY PostId) as [row], * \n"
+ "FROM Post WHERE PostId IN( \n"
+ "SELECT PostId FROM Bookmark \n"
+ "WHERE Username = @username"
+ " )) as x \n"
+ "WHERE x.[row] BETWEEN @index * 3 - (3 - 1) AND 3 * @index";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@index", pageIndex);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
int postID = reader.GetInt32(0);
string title = reader.GetString(1);
string desc = reader.GetString(2);
string fileURL = reader.GetString(3);
string uploaderUsername = reader.GetString(4);
DateTime date = reader.GetDateTime(5);
Post post = new Post
{
PostId = postID,
PostTitle = title,
PostDescription = desc,
FileUrl = fileURL,
UploadDate = date,
UploaderUsername = uploaderUsername
};
posts.Add(post);
}
reader.NextResult();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return posts;
}
public int CountBookMarkPost(string username)
{
var bookMarkList = new List<Bookmark>();
try
{
using var context = new PRN211_OnlyFunds_CopyContext();
bookMarkList = context.Bookmarks.Where(b => b.Username.Equals(username)).ToList();
int counts = bookMarkList.Count();
return counts;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
|
using Tomelt.UI.Resources;
namespace UEditor {
public class ResourceManifest : IResourceManifestProvider {
public void BuildManifests(ResourceManifestBuilder builder)
{
var manifest = builder.Add();
manifest.DefineScript("UEditorConfig").SetUrl("ueditor.config.js");
manifest.DefineScript("UEditor").SetUrl("ueditor.all.min.js").SetVersion("1.4.3").SetDependencies("UEditorConfig");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace _14.Hex_to_Decimal
{
class HexToDecimal
{
static void Main(string[] args)
{
string hexValue = Console.ReadLine();
long result = long.Parse(hexValue, NumberStyles.HexNumber);
Console.WriteLine(result);
}
}
}
|
using System.Web;
using FluentAssertions;
using NSubstitute;
using Xunit;
namespace SitecoreAdaptors.Tests
{
public class MediaRequestShould
{
[Fact]
public void do_stuff()
{
//// Arrange
var processor = new TestHttpProcessor();
var context = Substitute.For<HttpContextBase>();
context.Request.RawUrl.Returns("/~/media/hello.png");
var sitecore = Substitute.For<SitecoreContextBase>();
sitecore.IsNull.Returns(false);
sitecore.DatabaseName.Returns("web");
sitecore.LanguageName.Returns("da-DK");
sitecore.SiteName.Returns("website");
var mediaRequest = Substitute.For<MediaRequestBase>();
mediaRequest.DatabaseName.Returns("web");
mediaRequest.LanguageName.Returns("da-DK");
var mediaManager = Substitute.For<MediaManagerBase>();
mediaManager.IsMediaRequest().Returns(true);
mediaManager.ParseMediaRequest().Returns(mediaRequest);
//// Act
processor.Process(context, sitecore, mediaManager);
//// Assert
mediaRequest.MediaPath.Should().Be("/sitecore/media library/hello");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class ServerListInfo
{
public List<ServerInfo> server_infos = new List<ServerInfo>();
}
public class LoginServerList : UiSingleton<LoginServerList>
{
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
public void SetServerListInfo(ServerListInfo pServerListInfo)
{
for (int i = 0; i < pServerListInfo.server_infos.Count; i++)
{
GameObject obj = (GameObject)Instantiate(m_pObj, m_pContentTransform);
LoginServerInfo oInfo = obj.GetComponent<LoginServerInfo>();
//Vector3 v3 = new Vector3(0, m_pScrollRect.content.rect.height / 2 - (i + 0.5f) * oInfo.m_pButton.GetComponent<RectTransform>().rect.height, 0);
////obj.GetComponent<RectTransform>().localPosition = v3;
////obj.GetComponent<RectTransform>().position = v3;
//obj.transform.position = v3;
oInfo.SetServerInfo(pServerListInfo.server_infos[i]);
}
}
[SerializeField]
Object m_pObj = null;
[SerializeField]
Transform m_pContentTransform = null;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HPYL.Model
{
/// <summary>
/// 多点执业模型
/// </summary>
public class MultipointShops
{
/// <summary>
/// 标识id
/// </summary>
public long Id { get; set; }
/// <summary>
/// 店铺logo
/// </summary>
public string Logo { get; set; }
/// <summary>
/// 店铺名称
/// </summary>
public string ShopName { get; set; }
/// <summary>
/// 区域完整路径
/// </summary>
public string RegionFullName { get; set; }
/// <summary>
/// 详细地址
/// </summary>
public string CompanyAddress { get; set; }
/// <summary>
/// 简介
/// </summary>
public string Remark { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppExercise
{
class Program
{
static void Main(string[] args)
{
//1. Takes an input from the user, multiplies it by 50, and prints the result to the console. (Note: make sure your code can take inputs larger than 10,000,000).
Console.WriteLine("Please enter a number.");
string multi = Console.ReadLine();
uint num1 = Convert.ToUInt32(multi);
UInt32 total = num1 * 50;
Console.WriteLine("The number you chose multiplied by 50 is: " + total);
//2. Takes an input from the user, adds 25 to it, and prints the result to the console.
Console.WriteLine("Please enter another number.");
string add = Console.ReadLine();
int num2 = Convert.ToInt32(add);
int total2 = num2 + 25;
Console.WriteLine("The number you chose plus 25 is: " + total2);
//3. Takes an input from the user, divides it by 12.5, and prints the result to the console.
Console.WriteLine("Please write another number.");
string div = Console.ReadLine();
int num3 = Convert.ToInt32(div);
double total3 = num3 / 12.5;
Console.WriteLine("The number you chose divided by 12.5 is: " + total3);
//4. Takes an input from the user, checks if it is greater than 50, and prints the true/false result to the console.
Console.WriteLine("Please Enter another number.");
string great = Console.ReadLine();
int num4 = Convert.ToInt32(great);
bool fer = num4 > 50;
Console.WriteLine("Your number is greater than 50: " + fer);
//5. Takes an input from the user, divides it by 7, and prints the remainder to the console (tip: think % operator).
Console.WriteLine("Please enter one last number.");
string rem = Console.ReadLine();
int num5 = Convert.ToInt32(rem);
int mod = num5 % 7;
Console.WriteLine("Your number divided by 7 has the remainder of: " + mod);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace TruckPad.Services.Models
{
public partial class Viagem
{
public Viagem()
{
ViagemParada = new HashSet<ViagemParada>();
}
[Key]
public int IdViagem { get; set; }
public int IdOrigem { get; set; }
public int IdDestino { get; set; }
public int IdMotorista { get; set; }
public int IdVeiculo { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DataPrevistaSaida { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DataSaida { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DataPrevistaChegada { get; set; }
[Column(TypeName = "datetime")]
public DateTime? DataChegada { get; set; }
public bool Carregado { get; set; }
[Column(TypeName = "datetime")]
public DateTime DataRegistro { get; set; }
public int? ViagemOrigem { get; set; }
[ForeignKey("IdDestino")]
[InverseProperty("ViagemIdDestinoNavigation")]
public Empresa IdDestinoNavigation { get; set; }
[ForeignKey("IdMotorista")]
[InverseProperty("Viagem")]
public Motorista IdMotoristaNavigation { get; set; }
[ForeignKey("IdOrigem")]
[InverseProperty("ViagemIdOrigemNavigation")]
public Empresa IdOrigemNavigation { get; set; }
[ForeignKey("IdVeiculo")]
[InverseProperty("Viagem")]
public Veiculo IdVeiculoNavigation { get; set; }
[InverseProperty("IdViagemNavigation")]
public ICollection<ViagemParada> ViagemParada { get; set; }
}
}
|
using System;
// Ai for playing connect four
public class OGAI : Player
{
public OGAI( bool p, Random r ) : base( p, r ){}
// Lets the AI make its move
// takes the game its playing and a token its using
public override int MakeMove( GameBoard g )
{
// game to test moves on
GameBoard gprime;
// if any moves will result in a win use it
// and block any wins that the player might have
int i;
if( CanWin( g, player, out i ) )
{
return i;
}
if( CanWin( g, !player, out i ) )
{
return i;
}
// else choose a random move that wont give the player a win
int r;
const int MAXTRIES = 500;
// number of tries before giving up and trying something completely random
int tries = 0;
// make sure the move is a valid move
bool valid;
do
{
r = rand.Next( 1, 8 );
gprime = new GameBoard( g.Board );
valid = gprime.MakeMove( r, player );
tries++;
// while the player can win in the next move or the next move is not valid
} while( ( CanWin( gprime, !player, out i ) && tries < MAXTRIES ) || !valid );
return r;
}
// private helper function which determines if a player can win in one move
private bool CanWin( GameBoard g, bool player, out int move )
{
move = 1;
GameBoard gprime = new GameBoard( g.Board );
for( int i = 1; i < 8; i++ )
{
gprime.MakeMove( i, player );
if( gprime.IsWinner( player ) )
{
move = i;
return true;
}
gprime = new GameBoard( g.Board );
}
return false;
}
}
|
using System;
using System.Collections.Generic;
namespace CourseHunter_27_DataTime
{
class Program
{
static void Main(string[] args)
{
DateTime now = DateTime.Now; // свойство показывающее сегоднящнюю дату и время
Console.WriteLine("Now is {0}", now);
Console.WriteLine($"Now is {now.Hour}:{now.Minute} time, {now.Day}.{now.Month}.{now.Year}");
Console.WriteLine(new string('-', 30));
DateTime dt = new DateTime(2016, 2, 28);
DateTime newDt = dt.AddYears(4); // добавление даты
Console.WriteLine(newDt);
Console.WriteLine(new string('-', 30));
TimeSpan ts = now - dt;
Console.WriteLine(ts); // as like ts=now.Subtract(dt)
Console.WriteLine(new string('-', 30));
DateTime startDate = DateTime.Now;
DateTime finishDate = startDate.AddMonths(6);
Console.WriteLine($"{startDate} + 6 month {finishDate}");
Console.WriteLine(new string('-', 30));
int count = 1;
//Console.WriteLine($"Start date is --- {startDate.AddMonths(-1)}");
//for (var i = startDate.AddMonths(1).Month; i <= finishDate.Month; i++)
//{
// Console.WriteLine($"{count} month left --- {i}");
// count++;
//}
//for (var i = startDate.AddMonths(1); i <= finishDate; i = i.AddMonths(1))
//{
// Console.WriteLine($"{count} month left --- {i}");
// count++;
//}
DateTime start = DateTime.Now;
DateTime finish = startDate.AddMonths(6);
int period = PayPeriodByMonth(start, finish);
for (int i = 1; i <=period; i++)
{
Console.WriteLine($"{start.AddMonths(i)}");
}
Console.ReadLine();
}
public static int PayPeriodByMonth(DateTime start, DateTime end)
{
return (end.Year * 12 + end.Month) - (start.Year * 12 + start.Month);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using BLL.DLib;
using System.Data;
using DLib.DAL;
public partial class Controls_Records_RecordsListTreeDual : System.Web.UI.Page
{
private static DlibEntities Db
{
get
{
if (HttpContext.Current.Session["DB"] == null)
{
var entities = new DlibEntities();
HttpContext.Current.Session["DB"] = entities;
return entities;
}
else
return HttpContext.Current.Session["DB"] as DlibEntities;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Access.IsAdmin() && !Access.UserShowLib(Library.GetActiveLibrary()))
Page.Response.Redirect("~/login.aspx");
if (!IsPostBack)
initTrees();
}
protected void initTrees()
{
RadTreeView1.DataTextField = "Title";
RadTreeView1.DataFieldID = "ID";
RadTreeView1.DataValueField = "ID";
RadTreeView1.DataFieldParentID = "ParentID";
RadTreeView1.DataSource = LibRecTree.GetList(Library.GetActiveLibrary(),false);
RadTreeView1.DataBind();
RadTreeView1.Font.Name = Profile.FontName;
RadTreeView1.Font.Size = Convert.ToInt32(Profile.FontSize);
PrepaireTree(RadTreeView1.Nodes);
RadTreeView2.DataTextField = "Title";
RadTreeView2.DataFieldID = "ID";
RadTreeView2.DataValueField = "ID";
RadTreeView2.DataFieldParentID = "ParentID";
RadTreeView2.DataSource = LibRecTree.GetList(Library.GetActiveLibrary(),false);
RadTreeView2.DataBind();
RadTreeView2.Font.Name = Profile.FontName;
RadTreeView2.Font.Size = Convert.ToInt32(Profile.FontSize);
PrepaireTree(RadTreeView2.Nodes);
}
protected void PrepaireTree(RadTreeNodeCollection nodes)
{
Guid CurrentUser = Access.GetCurrentUserID();
foreach (RadTreeNode t in nodes)
{
t.ContextMenuID = "MainContextMenu";
t.ImageUrl = "~/Controls/Images/folder.png";
if (t.Nodes.Count > 0)
PrepaireTree(t.Nodes);
if (Profile.ShowTreeDetails == 1)
{
int ID = Convert.ToInt32(t.Value);
var q = Db.tblLibRecords.Where(c => c.TreeID == ID).OrderBy(c => c.Order);
bool AddRec = true;
foreach (var c in q)
{
if (Profile.Status == 1)
{
AddRec = c.Status == null ? false : c.Status.Value == true ? true : false;
}
if (AddRec)
{
RadTreeNode NewNode = new RadTreeNode();
NewNode.Text = c.Title;
NewNode.Value = "R" + c.ID.ToString();
if (c.Creator == CurrentUser)
NewNode.ImageUrl = "~/Controls/Images/fileedit.png";
else
NewNode.ImageUrl = "~/Controls/Images/file.png";
NewNode.ContextMenuID = "RecordContextMenu";
t.Nodes.Add(NewNode);
}
}
}
}
}
protected void RadTreeView1_NodeEdit(object sender, RadTreeNodeEditEventArgs e)
{
if (Access.IsAdmin() || Access.UserCreateRecordTree(Library.GetActiveLibrary()) || Access.UserUpdateOtherRecordTree(Library.GetActiveLibrary()))
LibRecTree.GetLibRecTree(e.Node.Value.ToInt32(),Lang.GetDefaultLang().ID).Update(e.Text, Access.GetCurrentUserID(), e);
}
protected void RadTreeView1_HandleDrop(object sender, RadTreeNodeDragDropEventArgs e)
{
RadTreeNode sourceNode = e.SourceDragNode;
RadTreeNode destNode = e.DestDragNode;
RadTreeViewDropPosition dropPosition = e.DropPosition;
if (destNode != null) //drag&drop is performed between trees
{
string val = sourceNode.Value;
bool AllowDD = false;
if (val.Substring(0, 1) == "R")
{
Records rec = Records.GetRecord(val.Substring(1, val.Length - 1).ToInt32(),Lang.GetDefaultLang().ID);
if (rec.Creator == Access.GetCurrentUserID() || Access.IsAdmin())
{
rec.TreeID = Convert.ToInt32(destNode.Value);
rec.Update();
AllowDD = true;
}
}
else
{
LibRecTree CTree = LibRecTree.GetLibRecTree(val.ToInt32(),Lang.GetDefaultLang().ID);
if (CTree.Creator == Access.GetCurrentUserID() || Access.IsAdmin())
{
CTree.ParentID = Convert.ToInt32(destNode.Value);
CTree.Save();
AllowDD = true;
}
}
if (AllowDD)
{
sourceNode.Owner.Nodes.Remove(sourceNode);
switch (dropPosition)
{
case RadTreeViewDropPosition.Over:
// child
if (!sourceNode.IsAncestorOf(destNode))
{
destNode.Nodes.Add(sourceNode);
}
break;
case RadTreeViewDropPosition.Above:
// sibling - above
destNode.InsertBefore(sourceNode);
break;
case RadTreeViewDropPosition.Below:
// sibling - below
destNode.InsertAfter(sourceNode);
break;
}
//sourceNode.Owner.Nodes.Remove(sourceNode);
//destNode.Nodes.Add(sourceNode);
destNode.Expanded = true;
sourceNode.TreeView.UnselectAllNodes();
}
}
}
protected void RadTreeView1_ContextMenuItemClick(object sender, RadTreeViewContextMenuEventArgs e)
{
switch (e.MenuItem.Value)
{
case "New":
int NewID = LibRecTree.Save(e);
startNodeInEditMode(NewID.ToString());
break;
case "Delete":
string msg = "";
msg = LibRecTree.GetLibRecTree(e.Node.Value.ToInt32(),Lang.GetDefaultLang().ID).Delete(e);
general.ShowAlertMessage(msg);
break;
}
}
private void startNodeInEditMode(string nodeValue)
{
//find the node by its Value and edit it when page loads
string js = "Sys.Application.add_load(editNode); function editNode(){ ";
js += "var tree = $find(\"" + RadTreeView1.ClientID + "\");";
js += "var node = tree.findNodeByValue('" + nodeValue + "');";
js += "if (node) node.startEdit();";
js += "Sys.Application.remove_load(editNode);};";
RadScriptManager.RegisterStartupScript(Page, Page.GetType(), "nodeEdit", js, true);
}
protected void BTN_SaveTree_1_Click(object sender, EventArgs e)
{
SaveNodes(RadTreeView1.Nodes);
initTrees();
}
private static void PerformDragAndDrop(RadTreeViewDropPosition dropPosition, RadTreeNode sourceNode, RadTreeNode destNode)
{
if (sourceNode.Equals(destNode) || sourceNode.IsAncestorOf(destNode))
{
return;
}
sourceNode.Owner.Nodes.Remove(sourceNode);
switch (dropPosition)
{
case RadTreeViewDropPosition.Over:
// child
if (!sourceNode.IsAncestorOf(destNode))
{
destNode.Nodes.Add(sourceNode);
}
break;
case RadTreeViewDropPosition.Above:
// sibling - above
destNode.InsertBefore(sourceNode);
break;
case RadTreeViewDropPosition.Below:
// sibling - below
destNode.InsertAfter(sourceNode);
break;
}
}
protected void SaveNodes(RadTreeNodeCollection nodes)
{
foreach (RadTreeNode n in nodes)
{
if (n.Value.Substring(0, 1) != "R")
{
int ID = Convert.ToInt32(n.Value);
var q = Db.tblLibRecTree.FirstOrDefault(c => c.ID == ID);
q.Order = n.Index;
q.ParentID = n.ParentNode == null ? q.ParentID : Convert.ToInt32(n.ParentNode.Value);
Db.SaveChanges();
if (n.Nodes.Count > 0)
{
SaveNodes(n.Nodes);
}
}
else
{
int ID = Convert.ToInt32(Convert.ToInt32(n.Value.Substring(1, n.Value.Length - 1)));
var q = Db.tblLibRecords.FirstOrDefault(c => c.ID == ID);
q.Order = n.Index;
q.TreeID = Convert.ToInt32(n.ParentNode.Value);
Db.SaveChanges();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsolePiano.InstrumentalNote
{
class DecayPhase : Phase
{
public override double Duration => (double)1 / 9; //980.0 (double)1 / 9
//Set State with prev. limit - need mechanism to ensure order of the phases
public override double Lowerlimit { get; set; } //441.0;
public override double UpperLimit { get; set; } //1421.0;
protected override double Strength => -14767; //14767 //18000.0
public DecayPhase() { }
public DecayPhase(DefaultInstrumentNote defaultInstrumentNote)
{
this.defaultInstrumentNote = defaultInstrumentNote;
}
protected override bool IsNextPhase(int limit)
{
//TODO FIX subobt. relies on the loop be
return limit + 2 >= UpperLimit;
}
protected override void SetPhase()
{
defaultInstrumentNote.Phase = defaultInstrumentNote.SustainPhase;//new SustainPhase(this);
}
}
}
|
using System.Windows.Forms;
namespace Com.Colin.Win.Customized
{
public partial class NumberTextBox : TextBox
{
public NumberTextBox()
{
InitializeComponent();
}
private void E_TextBox_KeyDown(object sender, KeyEventArgs e)
{
}
private void E_TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!((e.KeyChar <= 'z' && e.KeyChar >= 'a') || (e.KeyChar <= 'Z' && e.KeyChar >= 'A') || e.KeyChar == '\b' || e.KeyChar == '\r'))//如果输入的数字
{
e.Handled = true;//处理KeyPress事件
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Lab.MIS.MonitorMIS.Controllers
{
/// <summary>
/// PicUpload 的摘要说明
/// </summary>
public class PicUpload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpPostedFile file = context.Request.Files["file_data"];
//files[j].name.substring(files[j].name.lastIndexOf(".")).toLowerCase();
string path = "/Resource/UpImages/" + Guid.NewGuid().ToString() + file.FileName.Substring(file.FileName.LastIndexOf("."));
file.SaveAs(context.Request.MapPath(path));
//string json = "{\"msg\":\"成功!\"}";
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("\"msg\":\"" + path + "\"");
sb.Append("}");
context.Response.Write(sb.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformManager : MonoBehaviour
{
[SerializeField]
private GameObject[] _floorPrefabs;
[SerializeField]
private float _zOffset;
// Start is called before the first frame update
void Start()
{
for (int i =0; i < _floorPrefabs.Length; i++)
{
Instantiate(_floorPrefabs[Random.Range(0,_floorPrefabs.Length)], new Vector3(0, 0, i * 50), Quaternion.Euler(0, 0, 0));
_zOffset += 50;
}
}
public void RecyclePlatform(GameObject platform)
{
// repositioning to next z offset
platform.transform.position = new Vector3(0, 0, _zOffset);
_zOffset += 50;
}
}
|
using Backend.Model;
using FeedbackAndSurveyService.CustomException;
using FeedbackAndSurveyService.SurveyService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FeedbackAndSurveyService.SurveyService.Repository
{
public class HospitalSurveyReportGeneratorRepository : IHospitalSurveyReportGeneratorRepository
{
private readonly MyDbContext _context;
public HospitalSurveyReportGeneratorRepository(MyDbContext context)
{
_context = context;
}
public SurveyReportGenerator Get()
{
try
{
List<SurveyReportGeneratorItem> items = new List<SurveyReportGeneratorItem>();
if (_context.SurveysAboutHospital.Count() == 0)
throw new NotFoundException("No information available.");
var nursing = _context.SurveysAboutHospital.Select(s => new Grade(s.Nursing));
items.Add(new SurveyReportGeneratorItem("Nursing", nursing));
var cleanliness = _context.SurveysAboutHospital.Select(s => new Grade(s.Cleanliness));
items.Add(new SurveyReportGeneratorItem("Cleanliness", cleanliness));
var general = _context.SurveysAboutHospital.Select(s => new Grade(s.OverallRating));
items.Add(new SurveyReportGeneratorItem("General rating", general));
var medicationAndInstruments = _context.SurveysAboutHospital.Select(s => new Grade(s.SatisfiedWithDrugAndInstrument));
items.Add(new SurveyReportGeneratorItem("Medication and instruments", medicationAndInstruments));
return new SurveyReportGenerator(items);
}
catch (FeedbackAndSurveyServiceException)
{
throw;
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PCToAccessMinigame : MonoBehaviour {
public GameObject text;
public GameObject Player;
bool playerEntered;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// Allows interaction when in range
if (playerEntered == true && Input.GetButtonDown("Interact"))
{
SceneManager.LoadScene("Minigame_2", LoadSceneMode.Additive);
PlayerMovement.playerCanMove = false;
}
}
// Functions for allowing text to appear and dissapear
private void OnTriggerEnter2D(Collider2D collision)
{
playerEntered = true;
text.SetActive(true);
}
private void OnTriggerExit2D(Collider2D collision)
{
playerEntered = false;
text.SetActive(false);
}
}
|
using gView.Framework.IO;
using System;
namespace gView.Framework.Geometry
{
public class PersistableGeometry : IPersistable
{
IGeometry _geometry = null;
public PersistableGeometry()
{
}
public PersistableGeometry(IGeometry geometry)
{
_geometry = geometry;
}
public IGeometry Geometry
{
get { return _geometry; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
PersistablePoint ppoint = stream.Load("Point", null, new PersistablePoint(new Point())) as PersistablePoint;
if (ppoint != null && ppoint.Point != null)
{
_geometry = ppoint.Point;
return;
}
PersistablePointCollection pmultipoint = stream.Load("Multipoint", null, new PersistablePointCollection(new MultiPoint())) as PersistablePointCollection;
if (pmultipoint != null && pmultipoint.PointCollection is IMultiPoint)
{
_geometry = pmultipoint.PointCollection as IMultiPoint;
return;
}
PersistablePolyline ppolyline = stream.Load("Polyline", null, new PersistablePolyline(new Polyline())) as PersistablePolyline;
if (ppolyline != null && ppolyline.Polyline != null)
{
_geometry = ppolyline.Polyline;
return;
}
PersistablePolygon ppolygon = stream.Load("Polygon", null, new PersistablePolygon(new Polygon())) as PersistablePolygon;
if (ppolygon != null && ppolygon.Polygon != null)
{
_geometry = ppolygon.Polygon;
return;
}
PersistableEnvelope penvelope = stream.Load("Envelope", null, new PersistableEnvelope(new Envelope())) as PersistableEnvelope;
if (penvelope != null && penvelope.Envelope != null)
{
_geometry = penvelope.Envelope;
return;
}
PersistableAggregateGeometry pageometry = stream.Load("AggregateGeometry", null, new PersistableAggregateGeometry(new AggregateGeometry())) as PersistableAggregateGeometry;
if (pageometry != null && pageometry.AggregateGeometry != null)
{
_geometry = pageometry.AggregateGeometry;
return;
}
}
public void Save(IPersistStream stream)
{
if (_geometry == null || stream == null)
{
return;
}
if (_geometry is IPoint)
{
stream.Save("Point", new PersistablePoint(_geometry as IPoint));
}
else if (_geometry is IMultiPoint)
{
stream.Save("Multipoint", new PersistablePointCollection(_geometry as IMultiPoint));
}
else if (_geometry is IPolyline)
{
stream.Save("Polyline", new PersistablePolyline(_geometry as IPolyline));
}
else if (_geometry is Polygon)
{
stream.Save("Polygon", new PersistablePolygon(_geometry as IPolygon));
}
else if (_geometry is IEnvelope)
{
stream.Save("Envelope", new PersistableEnvelope(_geometry as IEnvelope));
}
else if (_geometry is IAggregateGeometry)
{
stream.Save("AggregateGeometry", new PersistableAggregateGeometry(_geometry as IAggregateGeometry));
}
}
#endregion
}
internal class PersistablePoint : IPersistable
{
IPoint _point = null;
public PersistablePoint(IPoint point)
{
_point = point;
}
public IPoint Point
{
get { return _point; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_point == null || stream == null)
{
return;
}
_point.X = (double)stream.Load("x", 0.0);
_point.Y = (double)stream.Load("y", 0.0);
}
public void Save(IPersistStream stream)
{
if (_point == null)
{
return;
}
stream.Save("x", _point.X);
stream.Save("y", _point.Y);
}
#endregion
}
internal class PersistablePointCollection : IPersistable
{
IPointCollection _pColl;
public PersistablePointCollection(IPointCollection pcoll)
{
_pColl = pcoll;
}
public IPointCollection PointCollection
{
get { return _pColl; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_pColl == null || stream == null)
{
return;
}
PersistablePoint p;
while ((p = stream.Load("v", null, new PersistablePoint(new Point())) as PersistablePoint) != null)
{
_pColl.AddPoint(p.Point);
}
}
public void Save(IPersistStream stream)
{
if (_pColl == null)
{
return;
}
for (int i = 0; i < _pColl.PointCount; i++)
{
stream.Save("v", new PersistablePoint(_pColl[i]));
}
}
#endregion
}
internal class PersistablePolyline : IPersistable
{
private IPolyline _polyline;
public PersistablePolyline(IPolyline polyline)
{
_polyline = polyline;
}
public IPolyline Polyline
{
get { return _polyline; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_polyline == null || stream == null)
{
return;
}
PersistablePointCollection p;
while ((p = stream.Load("Path", null, new PersistablePointCollection(new Path())) as PersistablePointCollection) != null)
{
_polyline.AddPath(p.PointCollection as IPath);
}
}
public void Save(IPersistStream stream)
{
if (_polyline == null || stream == null)
{
return;
}
for (int i = 0; i < _polyline.PathCount; i++)
{
stream.Save("Path", new PersistablePointCollection(_polyline[i]));
}
}
#endregion
}
internal class PersistablePolygon : IPersistable
{
private IPolygon _polygon;
public PersistablePolygon(IPolygon polygon)
{
_polygon = polygon;
}
public IPolygon Polygon
{
get { return _polygon; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_polygon == null || stream == null)
{
return;
}
PersistablePointCollection p;
while ((p = stream.Load("Ring", null, new PersistablePointCollection(new Ring())) as PersistablePointCollection) != null)
{
_polygon.AddRing(p.PointCollection as IRing);
}
}
public void Save(IPersistStream stream)
{
if (_polygon == null || stream == null)
{
return;
}
for (int i = 0; i < _polygon.RingCount; i++)
{
stream.Save("Ring", new PersistablePointCollection(_polygon[i]));
}
}
#endregion
}
internal class PersistableAggregateGeometry : IPersistable
{
private IAggregateGeometry _ageometry;
public PersistableAggregateGeometry(IAggregateGeometry ageometry)
{
_ageometry = ageometry;
}
public IAggregateGeometry AggregateGeometry
{
get { return _ageometry; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (_ageometry == null || stream == null)
{
return;
}
PersistableGeometry p;
while ((p = stream.Load("Geometry", null, new PersistableGeometry()) as PersistableGeometry) != null)
{
_ageometry.AddGeometry(p.Geometry);
}
}
public void Save(IPersistStream stream)
{
if (_ageometry == null || stream == null)
{
return;
}
for (int i = 0; i < _ageometry.GeometryCount; i++)
{
stream.Save("Geometry", new PersistableGeometry(_ageometry[i]));
};
}
#endregion
}
internal class PersistableEnvelope : IPersistable
{
private IEnvelope _envelope;
public PersistableEnvelope(IEnvelope envelope)
{
_envelope = envelope;
}
public IEnvelope Envelope
{
get { return _envelope; }
}
#region IPersistable Member
public void Load(IPersistStream stream)
{
if (stream == null || _envelope == null)
{
return;
}
PersistablePoint lowerleft = (PersistablePoint)stream.Load("lowerleft", new PersistablePoint(new Point()), new PersistablePoint(new Point()));
PersistablePoint upperright = (PersistablePoint)stream.Load("upperright", new PersistablePoint(new Point()), new PersistablePoint(new Point()));
_envelope.minx = Math.Min(lowerleft.Point.X, upperright.Point.X);
_envelope.miny = Math.Min(lowerleft.Point.Y, upperright.Point.Y);
_envelope.maxx = Math.Max(lowerleft.Point.X, upperright.Point.X);
_envelope.maxy = Math.Max(lowerleft.Point.Y, upperright.Point.Y);
}
public void Save(IPersistStream stream)
{
if (stream == null || _envelope == null)
{
return;
}
stream.Save("lowerleft", new PersistablePoint(_envelope.LowerLeft));
stream.Save("upperright", new PersistablePoint(_envelope.UpperRight));
}
#endregion
}
}
|
using CommonMark;
using MarkdownUtils.Core;
using MarkdownUtils.MdDoc;
using Miktemk;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZConsoleTests
{
class Program
{
static void Main(string[] args)
{
new Program();
}
const string userName = "miktemk";
//const string userName = "Mikhail";
public Program()
{
var mdText = File.ReadAllText($@"C:\Users\{userName}\Google Drive\md-notes\mdanim-sample.md");
var doc = CommonMarkConverter.Parse(mdText);
//var result = CommonMarkConverter.Convert(mdText);
//File.WriteAllText(@"C:\Users\Mikhail\Desktop\___test.html", result);
var converter = new MdDocumentConverter();
var mdDoc = converter.CommonMark2MdDocument(doc);
var converterAnim = new MdAnimatedConverter();
var mdDocAnim = converterAnim.MdDocument2Animated(mdDoc);
File.WriteAllText(OnDesktop("mdDoc.json"), JsonConvert.SerializeObject(mdDoc, Formatting.Indented));
//File.WriteAllText($@"C:\Users\{userName}\Desktop\mdDocAnim.json", JsonConvert.SerializeObject(mdDocAnim, Formatting.Indented));
XmlFactory.WriteToFile(mdDoc, OnDesktop("mdDoc.xml"));
XmlFactory.WriteToFile(mdDocAnim, OnDesktop("mdDocAnim.xml"));
}
private string OnDesktop(string filename)
{
return Path.Combine($@"C:\Users\{userName}\Desktop", filename);
}
}
}
|
using System;
using UnityEngine;
using System.IO;
using System.Linq;
using Kernel;
using Sini.Unity;
using UnityEditor;
namespace Kernel
{
public class KernelConfigWindow : EditorWindow
{
private SceneSelectionItem[] _kernelSceneOptions;
private int _selectedIndex;
[MenuItem("uFrame/Kernel Configuration")]
public static void Init()
{
var window = GetWindow<KernelConfigWindow>();
window.Repaint();
window.Show();
}
public Rect Bounds
{
get
{
return new Rect(0, 0, this.position.width, this.position.height);
}
}
public Rect PaddedBounds
{
get
{
return new Rect(0, 0, position.width, position.height).PadSides(15);
}
}
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; }
}
public SceneSelectionItem[] KernelSceneOptions
{
get
{
return new[]
{
new SceneSelectionItem()
{
SceneName = null,
Title = "None",
Index = -1,
Scene = null
}
}.Concat(EditorBuildSettings.scenes.Select((s, i) => new SceneSelectionItem()
{
Scene = s,
Title = Path.GetFileNameWithoutExtension(s.path),
SceneName = Path.GetFileNameWithoutExtension(s.path),
Index = i
})).ToArray();
}
set { _kernelSceneOptions = value; }
}
public void Awake()
{
var selectedScene = KernelRegister.RootKernelScene;
if (string.IsNullOrEmpty(selectedScene))
{
SelectedIndex = 0;
}
else
{
SelectedIndex = Array.IndexOf(EditorBuildSettings.scenes.Select(s => Path.GetFileNameWithoutExtension(s.path)).ToArray(), selectedScene);
}
}
public void OnGUI()
{
var kernelSceneSelectionRowBounds = PaddedBounds.WithHeight(40);
EditorGUI.BeginChangeCheck();
var selectedIndex = EditorGUI.Popup(kernelSceneSelectionRowBounds, "Select Kernel Scene", SelectedIndex,
KernelSceneOptions.Select(s => s.Title).ToArray());
if (EditorGUI.EndChangeCheck())
{
if (selectedIndex >= 0 && selectedIndex < KernelSceneOptions.Length)
{
SelectedIndex = selectedIndex;
KernelRegister.RootKernelScene = KernelSceneOptions[selectedIndex].SceneName;
}
}
}
public class SceneSelectionItem
{
public string SceneName { get; set; }
public EditorBuildSettingsScene Scene { get; set; }
public int Index { get; set; }
public string Title { get; set; }
}
}
}
|
using Piovra.Ds;
using Xunit;
namespace Piovra.Tests;
public class FenwickTreeTests {
[Fact]
public void Test() {
var tree = new FenwickTree(10);
tree.
Update(1, 1).
Update(2, 3).
Update(3, 4).
Update(4, 8).
Update(5, 6).
Update(6, 1).
Update(7, 4).
Update(8, 2);
var sum = tree.Sum(2, 4);
Assert.Equal(15, sum);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class GeneradorTerrenoProcedural : MonoBehaviour
{
#region variables
#region deInspector
// tamaño piezas
public float longitudMuroX;
public float longitudMuroZ;
public float porcentajeMinimoCubos;
public float probabilidadMuro;
public float distanciaMinMalos;
public NavMeshSurface surface;
public Celda[][] celdas;
public GameObject[] malos;
public GameObject cube;
public GameObject cuboFalso;
public GameObject soldado;
public GameObject malo;
public GameObject camara;
public GameObject moneda;
public TextAsset datos;
public GameObject llave;
public GameObject puerta;
public int nivel;
#endregion
private int width;
private int heigth;
private int cantidadMalos;
private int numMonedas;
private float distanciaLlavePuerta = 10f; // dependera de la amplitud del nivel
#region datosDeFichero
#endregion
#region privadas
private int numMalos;
private GameObject prota;
private Controlador controller;
private NavMeshAgent agent;
private bool loop = false; // indica si hay que repetir la correción del escenario
private bool escenarioValido = true;
private NavMeshAgent[] enemsAgents;
private float numeroMinCubos;
private float numeroCasillas;
private int maxIntentosCrearEscenario = 4;
private float velocidadMalos;
#endregion
#endregion
private void Awake()
{
controller = FindObjectOfType<Controlador>();
controller.pedirNivel();
}
// Start is called before the first frame update
void Start() // el mapa debe ser siempre multiplo de 2
{
leerDatos(nivel);
malos = new GameObject[cantidadMalos];
int intentosCrearEscenario = 0;
this.transform.localScale = new Vector3 (width, this.transform.localScale.y,heigth);
numeroCasillas = (width / longitudMuroX) * (heigth / longitudMuroZ);
numeroMinCubos = ((probabilidadMuro/100) * numeroCasillas*(porcentajeMinimoCubos/100));
enemsAgents = new NavMeshAgent[cantidadMalos];
celdas = new Celda[(width / 2)][]; // por esto
for (int i = 0; i < width / 2; i++)
{
celdas[i] = new Celda[heigth / 2];
}
numMalos = 0;
do
{
if(prota != null)
{
Destroy(prota);
prota = null;
}
CrearEscenario();
intentosCrearEscenario++;
surface.BuildNavMesh();
do
{
loop = false;
retocarEscenario();
surface.BuildNavMesh();
} while (loop == true);
comprobacionCubos();
if(intentosCrearEscenario >= maxIntentosCrearEscenario)
{
escenarioValido = true;
Debug.LogWarning("Limite de intentos alcazado, se da por valio el escenario");
}
if(escenarioValido == false)
{
foreach (Celda [] columna in celdas)
{
foreach (Celda celdilla in columna)
{
if (celdilla.ocupada)
{
Destroy(celdilla.Cubo);
celdilla.ocupada = false;
celdilla.miObj = Celda.TipoObjeto.Nada;
}
}
}
}
Debug.Log(intentosCrearEscenario + " Intentos realizados");
} while (escenarioValido == false);
ponerMasCubos(); // crea cubos en aquellos sitios con pocos espacios
generarObjetos();
controller.reiniciarControlador();
surface.BuildNavMesh();
}
// Update is called once per frame
void Update()
{
}
void CrearEscenario()
{
int indiceGeneral = -1;
int indexX = -1;
for (int x = 0; x < width; x += (int)longitudMuroX)
{
indexX++;
int indexZ = -1;
for (int z = 0; z < heigth; z += (int)longitudMuroZ)
{
indiceGeneral++;
indexZ++;
celdas[indexX][indexZ] = new Celda ();
Celda CeldaActual = celdas[indexX][indexZ];
float numero = Random.Range(0, 100); // sobre 100
Vector3 pos = new Vector3(x - ((width - longitudMuroX) / 2f), 1f, z - ((heigth - longitudMuroZ) / 2f));
pos = pos + this.transform.position;
CeldaActual.pos = pos;
CeldaActual.indice = indiceGeneral;
CeldaActual.ocupada = false;
CeldaActual.miObj = Celda.TipoObjeto.Nada;
if (x == (int)(width /2) && z == (int)(heigth/2))
{
prota = Instantiate(soldado, pos, Quaternion.identity); // para guardar las cosas lo haremos de 1 en 1 siendo el 0,0 la esquina nose cual
agent = prota.GetComponent<NavMeshAgent>();
camara.GetComponent<MovimientoCamara>().asignarPadre(prota);
}
else if ((numero >= 0f) && (numero < probabilidadMuro))
{
CeldaActual.Cubo = Instantiate(cube, pos, Quaternion.identity);
CeldaActual.ocupada = true;
CeldaActual.miObj = Celda.TipoObjeto.Cubo;
}
else
{
/*
if (numMalos < cantidadMalos)
{
if (numero > 95f)
{
GameObject aux = Instantiate(malo, pos, Quaternion.identity);// mejor no incluirlo
enemsAgents[numMalos] = aux.GetComponent<NavMeshAgent>();
numMalos++;
}
}
*/
}
}
}
}
public void generarObjetos() // hace que lo smalos no se choquen entre si, máximo 100 malos
{
Celda celdaLibre;
do
{
celdaLibre = encontrarCeldaLibre();
GameObject aux = Instantiate(malo, celdaLibre.pos, Quaternion.identity);// mejor no incluirlo
aux.GetComponent<Enemigo>().fijarLimites(heigth, width);
enemsAgents[numMalos] = aux.GetComponent<NavMeshAgent>();
malos[numMalos] = aux;
numMalos++;
} while (numMalos < cantidadMalos);
celdaLibre = encontrarCeldaLibre();
GameObject llaveAux = Instantiate(llave, new Vector3(celdaLibre.pos.x, 0, celdaLibre.pos.z), Quaternion.identity);
celdaLibre.ocupada = true;
celdaLibre.miObj = Celda.TipoObjeto.Llave;
do
{
celdaLibre = encontrarCeldaLibre();
} while (Vector3.Distance(llaveAux.transform.position, celdaLibre.pos) < distanciaLlavePuerta);
Instantiate(puerta, new Vector3(celdaLibre.pos.x, 0, celdaLibre.pos.z), Quaternion.identity);
celdaLibre.ocupada = true;
celdaLibre.miObj = Celda.TipoObjeto.Puerta;
for (int i = 0; i < numMalos; i++)
{
enemsAgents[i].gameObject.GetComponent<Enemigo>().prota = prota;
enemsAgents[i].avoidancePriority = i;
}
for (int i = 0; i < numMonedas; i++)
{
celdaLibre = encontrarCeldaLibre();
Instantiate(moneda, new Vector3(celdaLibre.pos.x, 1.3f, celdaLibre.pos.z), Quaternion.identity);
celdaLibre.ocupada = true;
celdaLibre.miObj = Celda.TipoObjeto.Moneda;
}
}
public void ponerMasCubos()
{
bool ponerCubo = false;
for (int i = 0; i < width / 2; i++)
{
for (int z = 0; z < heigth / 2; z++)
{
if((i == 0) || (i == ((width / 2)-1))|| (z == 0) || (z == (heigth / 2)-1))
{
} else
{
if (!celdas[i][z].ocupada)
{
if (celdas[i - 1][z].ocupada) // izquierda
{
ponerCubo = false;
}
else if (celdas[i + 1][z].ocupada) // derecha
{
ponerCubo = false;
}
else if (celdas[i + 1][z + 1].ocupada) // arriba derecha
{
ponerCubo = false;
}
else if (celdas[i + 1][z - 1].ocupada) // abajo derecha
{
ponerCubo = false;
}
else if (celdas[i - 1][z + 1].ocupada) // arriba izquierda
{
ponerCubo = false;
}
else if (celdas[i - 1][z - 1].ocupada) // abajo izquierda
{
ponerCubo = false;
}
else if (celdas[i][z - 1].ocupada) // abajo
{
ponerCubo = false;
}
else if (celdas[i][z + 1].ocupada) // arriba
{
ponerCubo =false;
} else
{
ponerCubo = true;
}
if (ponerCubo)
{
celdas[i][z].ocupada = true;
celdas[i][z].Cubo = Instantiate(cube, celdas[i][z].pos, Quaternion.identity);
celdas[i][z].miObj = Celda.TipoObjeto.Cubo;
Debug.Log("Celda Generada");
}
}
}
}
}
}
public void retocarEscenario() // creo que quitar muros no es realmente aleatorio, habria que cambiarlo.
{
List<Celda> listaAux = new List<Celda>(); //celdas Ocupadas que hay que destruir
for (int i = 0; i < width / 2; i++)
{
for (int z = 0; z < heigth / 2; z++)
{
Celda CeldaArriba = null;
Celda CeldaAbajo = null;
Celda CeldaIzq = null;
Celda CeldaDer = null;
Celda CeldaActual = celdas[i][z];
NavMeshPath aux = new NavMeshPath();
if (!CeldaActual.ocupada && (CeldaActual.miObj != Celda.TipoObjeto.Cubo)) // si la celda esta libre
{
//cogemos las casillas adyacentes
if (i == 0) //estamos a la izq
{
if (z <= ((heigth / 2)-2))
{
CeldaArriba = celdas[i][z + 1];
}
if (z >= 1)
{
CeldaAbajo = celdas[i][z - 1];
}
CeldaDer = celdas[i + 1][z];
}
else if (i == (width / 2)-1)
{
if (z <= ((heigth / 2) - 2))
{
CeldaArriba = celdas[i][z + 1];
}
if (z >= 1)
{
CeldaAbajo = celdas[i][z - 1];
}
CeldaIzq = celdas[i - 1][z];
}
else if (z == 0)
{
CeldaIzq = celdas[i - 1][z];
CeldaDer = celdas[i + 1][z];
CeldaArriba = celdas[i][z + 1];
}
else if (z == ((heigth / 2) - 1))
{
CeldaIzq = celdas[i - 1][z];
CeldaDer = celdas[i + 1][z];
CeldaAbajo = celdas[i][z - 1];
}
else
{
CeldaIzq = celdas[i - 1][z];
CeldaDer = celdas[i + 1][z];
CeldaAbajo = celdas[i][z - 1];
CeldaArriba = celdas[i][z + 1];
}
agent.CalculatePath(CeldaActual.pos, aux);
CeldaActual.visitada = true;
if (aux.status == NavMeshPathStatus.PathPartial) // no se puede llegar a esa celda
{
if(CeldaAbajo != null)
{
if(CeldaAbajo.ocupada == true)
{
listaAux.Add(CeldaAbajo);
}
}
if (CeldaArriba != null)
{
if (CeldaArriba.ocupada == true)
{
listaAux.Add(CeldaArriba);
}
}
if (CeldaDer != null)
{
if (CeldaDer.ocupada == true)
{
listaAux.Add(CeldaDer);
}
}
if (CeldaIzq != null)
{
if (CeldaIzq.ocupada == true)
{
listaAux.Add(CeldaIzq);
}
}
Celda borrar = null;
foreach(Celda aux2 in listaAux)
{
borrar = aux2;
}
if(borrar != null)
{
Destroy(borrar.Cubo);
borrar.ocupada = false;
CeldaActual.miObj = Celda.TipoObjeto.Nada;
loop = true;
}
}
}
}
}
}
public void comprobacionCubos()
{
int numCubos = 0;
for (int i = 0; i < width / 2; i++)
{
for (int z = 0; z < heigth / 2; z++)
{
if( celdas[i][z].ocupada)
{
numCubos++;
}
}
}
Debug.Log(" el numero de cubos es : " + numCubos);
if(numCubos < numeroMinCubos)
{
escenarioValido = false;
}
}
public void leerDatos(int nivel)
{
string [] aux = datos.text.Split('\n');
string[] aux1 = aux[nivel].Split(';');
width = int.Parse( aux1[1]);
heigth = int.Parse(aux1[2]);
cantidadMalos = int.Parse(aux1[3]);
numMonedas = int.Parse(aux1[4]);
}
public Celda encontrarCeldaLibre()
{
int casillaX = -1;
int casillaZ = -1;
Celda aux2;
do
{
casillaX = Random.Range(0, (int)(width / longitudMuroX));
casillaZ = Random.Range(0, (int)(heigth / longitudMuroZ));
aux2 = celdas[casillaX][casillaZ];
} while (aux2.ocupada);
return aux2;
}
public void congelarMov()
{
Rigidbody protaBody = prota.GetComponent<Rigidbody>();
protaBody.velocity = Vector3.zero;
protaBody.constraints = RigidbodyConstraints.FreezeAll;
foreach(GameObject malo in malos)
{
NavMeshAgent aux = malo.GetComponent<NavMeshAgent>();
velocidadMalos = aux.speed;
aux.speed = 0;
}
}
public void descongelarMov()
{
Rigidbody protaBody = prota.GetComponent<Rigidbody>();
protaBody.constraints = RigidbodyConstraints.None;
foreach (GameObject malo in malos)
{
NavMeshAgent aux = malo.GetComponent<NavMeshAgent>();
aux.speed = velocidadMalos;
}
}
}
|
using System;
using System.Linq;
namespace Pobs.Tests.Integration.Helpers
{
internal static class Utils
{
private static readonly Random s_random = new Random();
internal static string GenerateRandomString(int length)
{
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
return new string(Enumerable.Repeat(chars, length).Select(s => s[s_random.Next(s.Length)]).ToArray());
}
}
}
|
using BethanysPieShopHRM.Shared;
using IdentityModel.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace BethanysPieShopHRM.App.Services
{
public class EmployeeDataService: IEmployeeDataService
{
private readonly HttpClient _httpClient;
private readonly TokenManager _tokenManager;
public EmployeeDataService(HttpClient httpClient,
TokenManager tokenManager)
{
_httpClient = httpClient;
_tokenManager = tokenManager;
}
public async Task<IEnumerable<Employee>> GetAllEmployees()
{
//_httpClient.DefaultRequestHeaders.Add("Cookie",
// ".AspNetCore.Cookies=" + _tokenProvider.Cookie);
_httpClient.SetBearerToken(await _tokenManager.RetrieveAccessTokenAsync());
return await JsonSerializer.DeserializeAsync<IEnumerable<Employee>>
(await _httpClient.GetStreamAsync($"api/employee"),
new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
public async Task<Employee> GetEmployeeDetails(int employeeId)
{
return await JsonSerializer.DeserializeAsync<Employee>
(await _httpClient.GetStreamAsync($"api/employee/{employeeId}"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}
public async Task<Employee> AddEmployee(Employee employee)
{
var employeeJson =
new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("api/employee", employeeJson);
if (response.IsSuccessStatusCode)
{
return await JsonSerializer.DeserializeAsync<Employee>(await response.Content.ReadAsStreamAsync());
}
return null;
}
public async Task UpdateEmployee(Employee employee)
{
var employeeJson =
new StringContent(JsonSerializer.Serialize(employee), Encoding.UTF8, "application/json");
await _httpClient.PutAsync("api/employee", employeeJson);
}
public async Task DeleteEmployee(int employeeId)
{
await _httpClient.DeleteAsync($"api/employee/{employeeId}");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RNET
{
class Produto
{
public string Codigo;
public string Nome;
public double Preco;
public int Quantidade;
public Produto()
{
Codigo = "000";
Nome = "Sem Nome";
Quantidade = 0;
Preco = 0;
}
public Produto(string _codigo, string _nome, int _quantidade, double _preco )
{
this.Codigo = _codigo;
this.Nome = _nome;
this.Quantidade = _quantidade;
this.Preco = _preco;
}
public string GetDetalhes()
{
return $"[ Código: {Codigo} | Nome: {Nome} | Quanitdade: {Quantidade} | Preço: {Preco} ]";
}
/// <summary>
/// Aplica um desconto percentual no preço do produto
/// </summary>
/// <param name="desconto">Desconto em %</param>
public void AplicarDesconto(double desconto)
{
if (desconto < 0)
desconto = 0;
if (desconto > 100)
desconto = 100;
Preco = Preco * (1 - desconto / 100);
}
}
}
|
using System.Collections.Generic;
namespace EQS.AccessControl.Domain.ObjectValue
{
public class Validator
{
public Validator()
{
ErrorMessages = new List<string>();
}
public bool IsValid { get; set; }
public List<string> ErrorMessages { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using Elrond.Dotnet.Sdk.Domain.Values;
namespace Elrond.Dotnet.Sdk.Domain.Codec
{
public class MultiBinaryCodec : IBinaryCodec
{
private readonly BinaryCodec _binaryCodec;
public MultiBinaryCodec(BinaryCodec binaryCodec)
{
_binaryCodec = binaryCodec;
}
public string Type => TypeValue.BinaryTypes.Multi;
public (IBinaryType Value, int BytesLength) DecodeNested(byte[] data, TypeValue type)
{
var result = new Dictionary<TypeValue, IBinaryType>();
var buffer = data.ToList();
var offset = 0;
foreach (var multiType in type.MultiTypes)
{
var (value, bytesLength) = _binaryCodec.DecodeNested(buffer.ToArray(), multiType);
result.Add(multiType, value);
offset += bytesLength;
buffer = buffer.Skip(bytesLength).ToList();
}
var multiValue = new MultiValue(type, result);
return (multiValue, offset);
}
public IBinaryType DecodeTopLevel(byte[] data, TypeValue type)
{
var decoded = DecodeNested(data, type);
return decoded.Value;
}
public byte[] EncodeNested(IBinaryType value)
{
var multiValueObject = value.ValueOf<MultiValue>();
var buffers = new List<byte[]>();
foreach (var multiValue in multiValueObject.Values)
{
var fieldBuffer = _binaryCodec.EncodeNested(multiValue.Value);
buffers.Add(fieldBuffer);
}
var data = buffers.SelectMany(s => s);
return data.ToArray();
}
public byte[] EncodeTopLevel(IBinaryType value)
{
return EncodeNested(value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using alg;
/*
* tags: greedy
* Time(logn), Space(1)
* we need to add a new number of sum+1, where sum is sum of all previous numbers.
*/
namespace leetcode
{
public class Lc330_Patching_Array
{
public int MinPatches(int[] nums, int n)
{
int res = 0;
long sum = 0;
for (int i = 0; sum < n;)
{
if (i < nums.Length && nums[i] <= sum + 1)
sum += nums[i++];
else
{
sum += sum + 1;
res++;
}
}
return res;
}
public void Test()
{
var nums = new int[] { 1, 3 };
Console.WriteLine(MinPatches(nums, 6) == 1); // add {2}
nums = new int[] { 1, 5, 10 };
Console.WriteLine(MinPatches(nums, 20) == 2); // add {2, 4}
nums = new int[] { 1, 2, 2 };
Console.WriteLine(MinPatches(nums, 5) == 0); // add {}
nums = new int[] { 1, 2, 31, 33 };
Console.WriteLine(MinPatches(nums, 2147483647) == 28); // add {}
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
namespace Backend.DataAccess.Models
{
public class Product : Model
{
public string Description { get; set; }
public virtual Merchant Merchant { get; set; }
[ForeignKey("Merchant")]
public int MerchantId { get; set; }
public float Price { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UBaseline.Shared.Node;
using UBaseline.Shared.PageSettings;
using UBaseline.Shared.Property;
using Uintra.Core.Member.Entities;
using Uintra.Core.UbaselineModels.RestrictedNode;
using Uintra.Features.Groups;
using Uintra.Features.Groups.Models;
using Uintra.Features.Links.Models;
namespace Uintra.Features.Events.Models
{
public class EventEditPageViewModel : UintraRestrictedNodeViewModel, IGroupHeader
{
public PropertyViewModel<INodeViewModel[]> Panels { get; set; }
public PageSettingsCompositionViewModel PageSettings { get; set; }
public EventViewModel Details { get; set; }
public bool CanEditOwner { get; set; }
public bool PinAllowed { get; set; }
public IEnumerable<IntranetMember> Members { get; set; } = Enumerable.Empty<IntranetMember>();
public string AllowedMediaExtensions { get; set; }
public IActivityLinks Links { get; set; }
public GroupHeaderViewModel GroupHeader { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class InventoryController : MonoBehaviour {
private PlayerController pc;
public Flower flowerEmptyAppearance;
public List<GameObject> inventoryDisplays;
private List<Flower> inventory = new List<Flower> ();
public GameObject visualInventoryPrefab;
public List<GameObject> visualInventory;
public int inventoryLimit = 3;
public Vector2 visualInventoryTargetOffset;
public float visualInventorySpeed = 1f;
public float visualInventorySpeedMod = 0.01f;
public Vector2 thrownForce;
public GameObject flowerProjectile;
public float throwDelay = 0.2f;
// Use this for initialization
void Start () {
this.emptyInventoryDisplay ();
pc = this.gameObject.GetComponent <PlayerController> ();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1") || Input.GetButtonDown ("Fire2")) {
this.throwFlower ();
}
if (this.visualInventory.Count > 0) {
this.updateVisualInventory ();
}
}
public bool canBonusJump () {
if (this.inventory.Count > 0) {
return true;
}
return false;
}
public void emptyInventoryDisplay () {
foreach (GameObject dis in this.inventoryDisplays) {
Image sr = dis.GetComponent <Image> ();
sr.color = flowerEmptyAppearance.color;
sr.sprite = flowerEmptyAppearance.sprite;
}
}
public void updateInventory (List<Flower> flowers) {
this.emptyInventoryDisplay ();
for (int i = 0; i < flowers.Count; i++) {
Image sr = this.inventoryDisplays [i].GetComponent <Image> ();
sr.color = flowers [i].color;
sr.sprite = flowers [i].sprite;
}
Canvas.ForceUpdateCanvases ();
}
public void throwFlower () {
if (this.inventory.Count > 0 && this.flowerProjectile && this.pc.canThrow) {
Flower thrownFlower = this.inventory [0];
GameObject newFlower = GameObject.Instantiate (this.flowerProjectile);
Vector2 force = this.thrownForce;
if (!this.pc.facesRight ()) {
force.x = -this.thrownForce.x;
}
newFlower.transform.position = (Vector2) (this.transform.position) + this.pc.facingDirection ();
Rigidbody2D rb = newFlower.GetComponent<Rigidbody2D> ();
if (rb) {
rb.AddForce (force, ForceMode2D.Impulse);
}
SpriteRenderer sp = newFlower.GetComponent<SpriteRenderer> ();
if (sp) {
sp.sprite = thrownFlower.sprite;
sp.color = thrownFlower.color;
}
newFlower.GetComponent<ThrownFlowerController> ().properties = thrownFlower;
this.removeFlower (thrownFlower);
this.pc.suspendThrow (this.throwDelay);
}
}
public void removeFlower () { // override that assumes last item
//Debug.Log (this.inventory [this.inventory.Count - 1]);
this.removeFlower ( this.inventory [this.inventory.Count - 1]);
}
public void removeFlower (Flower f) {
int fIndex = this.inventory.IndexOf (f);
GameObject flowerObj = this.visualInventory [fIndex];
//GameObject removedItem = this.visualInventory.RemoveAt (fIndex);
this.inventory.Remove (f);
this.visualInventory.Remove (flowerObj);
Destroy (flowerObj);
this.updateInventory (this.inventory);
}
public bool offerFlower (Flower flowerType) {
if (inventory.Count < inventoryLimit) {
this.inventory.Add (flowerType);
this.updateInventory (this.inventory);
// create a new visual inventory item
GameObject newVisualItem = GameObject.Instantiate (this.visualInventoryPrefab);
newVisualItem.transform.position = this.transform.position;
this.visualInventory.Add (newVisualItem);
return true;
}
return false;
}
void updateVisualInventory () {
Vector2 previousPos = (Vector2)this.transform.position +
this.visualInventoryTargetOffset + -this.pc.facingDirection ();
for (int i = 0; i < this.visualInventory.Count; i++) {
Vector2 currentPos = this.visualInventory [i].transform.position;
float speed = (this.visualInventorySpeed * Time.deltaTime);
float speedMod = (i * this.visualInventorySpeedMod) * speed;
speed -= speedMod;
// Create a little accordian movement effect
// A more desirable method may be to make a line of desired positions
// based on player position, then have each move to their spot
this.visualInventory [i].transform.position = Vector2.MoveTowards (
currentPos, previousPos, speed);
previousPos = currentPos; // point next at this's last pos
}
}
}
|
using System;
using Apache.Shiro.Subject;
namespace Apache.Shiro.Authc
{
public class LogoutEventArgs : AuthenticationEventArgs
{
private readonly IPrincipalCollection _principals;
public LogoutEventArgs(IPrincipalCollection principals)
{
if (principals == null)
{
throw new ArgumentNullException("principals");
}
_principals = principals;
}
public IPrincipalCollection Principals
{
get
{
return _principals;
}
}
}
public delegate void LogoutEventHandler(object sender, LogoutEventArgs e);
}
|
namespace Fingo.Auth.AuthServer.Services.Interfaces
{
public interface IHashingService
{
string HashWithDatabaseSalt(string password , string userLogin);
string HashWithGivenSalt(string password , string hexSalt);
string GenerateNewSalt();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playermovement : MonoBehaviour
{
public float movementspeed;
public Rigidbody2D rb;
Vector2 movement;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxis("Horizontal"); //getting input for move left right
movement.y = Input.GetAxis("Vertical"); //getting input move up and down
// rb.MovePosition(rb.position + movement * movementspeed * Time.fixedDeltaTime);
}
void FixedUpdate()
{
rb.MovePosition(rb.position + movement *movementspeed*Time.fixedDeltaTime); // move player using rigidbody and by some amount of speed
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace P2PChat
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your nickname and your port: ");
string nick = Console.ReadLine(), host="";
int myport = int.Parse(Console.ReadLine()), rport = 0;
while (true)
{
Console.Write("Are you first user? (y/n): ");
char c = (char) Console.Read();
Console.ReadLine();
if (c == 'n')
{
Console.WriteLine("Enter remote host, port: ");
host = Console.ReadLine();
string n = Console.ReadLine();
rport = int.Parse(n);
}
Member m;
try
{
m = new Member(nick, host, rport, "127.0.0.1", myport);
m.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CSConsoleRL.Enums;
using CSConsoleRL.Entities;
using CSConsoleRL.Data;
namespace CSConsoleRL.Events
{
public class ChangeActiveItemEvent : IGameEvent
{
public string EventName { get { return "ChangeActiveItem"; } }
public List<object> EventParams { get; set; }
/// <summary>
/// Changes the active item to the next item in inventory
/// </summary>
/// <param name="entity"></param>
public ChangeActiveItemEvent(Guid id)
{
EventParams = new List<object>() { id };
}
/// <summary>
/// Changes the active item to the specified one
/// </summary>
/// <param name="entity"></param>
/// <param name="newActiveItem"></param>
public ChangeActiveItemEvent(Guid id, Item newActiveItem)
{
EventParams = new List<object>() { id, newActiveItem };
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace register
{
public partial class frmmain : Form
{
String[][] majors = BAL.getMajors();
public frmmain()
{
InitializeComponent();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.Hide();
regfrm r = new regfrm();
r.Show();
}
private void loginbtn_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("لطفا ابتدا یک رشته را انتخاب نید");
return;
}
BAL b = new BAL();
getcoursefrm g=new getcoursefrm();
b.majorid = majors[comboBox1.SelectedIndex][0];//0 = id ; 1 = name
b.stdno = stdtxt.Text;
if (b.stdno.Length != 0 && b.majorid.Length != 0 && b.check_login(b.stdno, b.majorid))
{
MessageBox.Show("به سامانه خوش آمدید");
this.Hide();
g.majorID = majors[comboBox1.SelectedIndex][0];
g.Show();
}
else
MessageBox.Show("اطلاعات وارد شده اشتباه می باشد");
}
private void frmmain_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void frmmain_Load(object sender, EventArgs e)
{
if (majors.Length == 0) return;
for (int i = 0; i < majors.Length ; i++)
{
comboBox1.Items.Add(majors[i][1]);
}
comboBox1.SelectedIndex = 0;
}
}
}
|
using System;
namespace WebSim.Common.Dates
{
public class DateService : IDateService
{
public DateTime GetDate()
{
return DateTime.Now;
}
}
}
|
// Author: Jonathan Spalding
// Assignment: Project 6
// Instructor "Roger deBry
// Clas: CS 1400
// Date Written: 3/5/2016
//
// "I declare that the following source code was written solely by me. I understand that copying any source code, in whole or in part, constitutes cheating, and that I will receive a zero on this project if I am found in violation of this policy."
//----------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Shipping_Rates
{
public partial class Form1 : Form
{
// create a Invoice_Class object
ShippingRatesClass objectRef;
// create Constants
private const double STANDARD = 1;
private const double EXPRESS = 2;
private const double SAME = 3;
private const double WEIGHT = 4;
private const double PIECE = 5;
public Form1()
{
InitializeComponent();
objectRef = new ShippingRatesClass();
}
// The exitToolStripMenuItem1_Click Method
// Purpose: Display a pop up box when you click About
// Parameters: The sending object, and the event arguments
// Returns: none
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Close();
}
// The aboutToolStripMenuItem_Click Method
// Purpose: Display a pop up box when you click About
// Parameters: The sending object, and the event arguments
// Returns: none
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Jonathan Spalding\nCS1400\nProjecct 06");
}
// The shippingMethod_SelectIndexChanged method
// Purpose: checks the combo box to see if what method was chosen, then assigns that method in the SetMethod method.
// Parameters: The sending object, and the event arguments
// returns: none
private void shippingMethod_SelectedIndexChanged(object sender, EventArgs e)
{
// create string for which item is selected.
string selectedItem = shippingMethod.Text;
// if statement for standard that assigns SetMethod to Standard
if (selectedItem == "Standard")
objectRef.SetMethod(STANDARD);
// else if statement for Express that assigs SetMethod to Express
else if (selectedItem == "Express")
objectRef.SetMethod(EXPRESS);
// else if statement for Same Day that assigns SetMethod to Same Day
else if (selectedItem == "Same Day")
objectRef.SetMethod(SAME);
}
// The category_SelectedIndexChanged method
// Purpose: checks the category combo box and sees if weight or items was chosen. Then assigns those categories to the SetCategory method in the class.
// Parameters: The sending object, and the event arguments
// returns: none
private void category_SelectedIndexChanged(object sender, EventArgs e)
{
// if statement for finding if weight is chosen. Then assigns to SetCategory Method
if (category.Text == "By Weight")
{
numOfItemsLabel.Text = "Weight of Shipment";
objectRef.SetCategory(WEIGHT);
}
// if statement for finding if Items is chosen. Then assigns to SetCategory Method
if (category.Text == "Number of Items")
{
numOfItemsLabel.Text = "Number of Items";
objectRef.SetCategory(PIECE);
}
}
// The yes_CheckedChanged method
// Purpose: radio button for checking yes to have Surecharge
// Parameters: The sending object, and the event arguments
// returns: none
private void yes_CheckedChanged(object sender, EventArgs e)
{
// if statement for if Yes is checked. Assigns to SetSurcharge method
if (yes.Checked)
objectRef.SetSurcharge(true);
}
// The no_CheckedChanged method
// Purpose: radio button for checking no to not have a Surecharge
// Parameters: The sending object, and the event arguments
// returns: none
private void no_CheckedChanged(object sender, EventArgs e)
{
// if statement for if No is checked. Assigns to SetSurcharge method
if (no.Checked)
objectRef.SetSurcharge(false);
}
// The numOfItems_TextChanged method
// Purpose: Allows the user to enter the total for number of items or weight, parses it to a string, then outputs it into the SetWeight, or SetNumItems methods.
// Parameters: The sending object, and the event arguments
// returns: none
private void numOfItems_TextChanged(object sender, EventArgs e)
{
// if statement that checks for the weight of the item, else check for the number of items. Then parse into a string and assign to SetWeight or SetNumItems.
if (category.Text == "By Weight")
objectRef.SetWeight(double.Parse(numOfItems.Text));
else
objectRef.SetNumItems(double.Parse(numOfItems.Text));
}
// The calcShippingBtn_Click method
// Purpose: displays the total returned in the calShippingCost Method.
// Parameters: The sending object, and the event arguments
// returns: none
private void calcShippingBtn_Click(object sender, EventArgs e)
{
// Change the label to show the calculated Shipping Cost.
shippingCost.Text = string.Format("{0:C}", objectRef.calcShippingCost());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QLBSX_DAL_WS.SubInfo
{
public class Calculator : ICalculator
{
public double Eval(double a, double b, double c)
{
return a * b * c;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CQRS.Abstraction;
namespace Client.Command
{
public class DocumentCreateCommand:ICommand
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
}
|
using Specification_OCPrinciple.Specification;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Specification_OCPrinciple.Interfaces
{
/// <summary>
/// В рамках спецификации создаем интерфейс который будет фильтровать не важно что
/// </summary>
/// <typeparam name="T"></typeparam>
internal interface IFilter<T>
{
IEnumerable<T> Filter(IEnumerable<T>items,
// И вторым параметром будет интерфейс/абстрактный класс спецификации по которой будет проходить фильтрация
BaseSpecification<T> specification
);
}
}
|
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base;
using System;
namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual
{
/// <summary>
/// Clase que representa la entidad Contrato
/// </summary>
/// <remarks>
/// Creación: GMD 20150525 <br />
/// Modificación: <br />
/// </remarks>
public class ContratoEntity : Entity
{
/// <summary>
/// Código de Contrato
/// </summary>
public Guid CodigoContrato { get; set; }
/// <summary>
/// Código de Unidad Operativa
/// </summary>
public Guid CodigoUnidadOperativa { get; set; }
/// <summary>
/// Código de Proveedor
/// </summary>
public Guid CodigoProveedor { get; set; }
/// <summary>
/// Número de Contrato
/// </summary>
public string NumeroContrato { get; set; }
/// <summary>
/// Descripción
/// </summary>
public string Descripcion { get; set; }
/// <summary>
/// Código de Tipo de Servicio
/// </summary>
public string CodigoTipoServicio { get; set; }
/// <summary>
/// Código de Tipo de Requerimiento
/// </summary>
public string CodigoTipoRequerimiento { get; set; }
/// <summary>
/// Código de Tipo de Documento
/// </summary>
public string CodigoTipoDocumento { get; set; }
/// <summary>
/// Indicador de Versión Oficial
/// </summary>
public bool IndicadorVersionOficial { get; set; }
/// <summary>
/// Fecha de Inicio de Vigencia
/// </summary>
public DateTime FechaInicioVigencia { get; set; }
/// <summary>
/// Fecha de Fin de Vigencia
/// </summary>
public DateTime FechaFinVigencia { get; set; }
/// <summary>
/// Código de Moneda
/// </summary>
public string CodigoMoneda { get; set; }
/// <summary>
/// Monto de Contrato
/// </summary>
public decimal MontoContrato { get; set; }
/// <summary>
/// Monto Acumulado
/// </summary>
public decimal MontoAcumulado { get; set; }
/// <summary>
/// Código de Estado
/// </summary>
public string CodigoEstado { get; set; }
/// <summary>
/// Código de Plantilla
/// </summary>
public Guid? CodigoPlantilla { get; set; }
/// <summary>
/// Código de Contrato Principal
/// </summary>
public Guid? CodigoContratoPrincipal { get; set; }
/// <summary>
/// Código de Estado de Edición
/// </summary>
public string CodigoEstadoEdicion { get; set; }
/// <summary>
/// Comentario de Modificación
/// </summary>
public string ComentarioModificacion { get; set; }
/// <summary>
/// Respuesta de Modificación
/// </summary>
public string RespuestaModificacion { get; set; }
/// <summary>
/// Código de Flujo de Aprobación
/// </summary>
public Guid? CodigoFlujoAprobacion { get; set; }
/// <summary>
/// Código de Estadio Actual
/// </summary>
public Guid? CodigoEstadioActual { get; set; }
/// <summary>
/// Número de correlativo de adenda
/// </summary>
public int? NumeroAdenda { get; set; }
/// <summary>
/// Número de adenda concantenado
/// </summary>
public string NumeroAdendaConcatenado { get; set; }
/// <summary>
/// Si el contrato es flexible
/// </summary>
public bool? EsFlexible { get; set; }
/// <summary>
/// Si el contrato es corporativo
/// </summary>
public bool? EsCorporativo { get; set; }
/// <summary>
/// Código de Contrato Original (se registra cuando se realiza la copia del contrato)
/// </summary>
public Guid? CodigoContratoOriginal { get; set; }
}
}
|
using AlgorithmProblems.Linked_List.Linked_List_Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Linked_List
{
class NthLastElementOfLinkedList
{
public SingleLinkedListNode<int> NthLastNodeOfLinkedListAlgo1(SingleLinkedListNode<int> head, int n)
{
// Step1: Get the length of the linked list
SingleLinkedListNode<int> currentNode = head;
int length = 0;
while(currentNode != null)
{
length++;
currentNode = currentNode.NextNode;
}
// Step2: Get the index of the element from the start
int indexOfNodeFromStart = length - n;
// Error condition where the length of the linked list is less than n
if(indexOfNodeFromStart <0 || indexOfNodeFromStart >= length)
{
return null;
}
// Step3: traverse the linked list to get the element
currentNode = head;
while (indexOfNodeFromStart > 0)
{
currentNode = currentNode.NextNode;
indexOfNodeFromStart--;
}
return currentNode;
}
public SingleLinkedListNode<int> NthLastNodeOfLinkedListAlgo2(SingleLinkedListNode<int> head, int n)
{
// Step1: Have 2 pointers to the head of the linked list
SingleLinkedListNode<int> slowPointer = head;
SingleLinkedListNode<int> fastPointer = head;
// Step2: Move the fast pointer till we are n distance from the slow pointer
while(n!=0)
{
n--;
// Error condition where the length of the linked list is less than n
if(fastPointer == null)
{
return null;
}
fastPointer = fastPointer.NextNode;
}
// Step3: Move both pointers till next node of fast pointer is not null
while(fastPointer.NextNode != null)
{
fastPointer = fastPointer.NextNode;
slowPointer = slowPointer.NextNode;
}
// Step4: The position of the slow pointer is our nth element from the last element
return slowPointer;
}
public static void TestNthLastNodeOfLinkedList()
{
Console.WriteLine("Test the nth node from the last for the linked list");
NthLastElementOfLinkedList nthLstElem = new NthLastElementOfLinkedList();
SingleLinkedListNode<int> ll = LinkedListHelper.CreateSinglyLinkedList(10);
LinkedListHelper.PrintSinglyLinkedList(ll);
SingleLinkedListNode<int> nthNode = nthLstElem.NthLastNodeOfLinkedListAlgo1(ll, 4);
Console.WriteLine("The 4th node is "+ nthNode!= null? nthNode.Data.ToString() : "null");
ll = LinkedListHelper.CreateSinglyLinkedList(10);
LinkedListHelper.PrintSinglyLinkedList(ll);
nthNode = nthLstElem.NthLastNodeOfLinkedListAlgo1(ll, 4);
Console.WriteLine("The 4th node is " + nthNode != null ? nthNode.Data.ToString() : "null");
}
}
}
|
using Microsoft.AspNet.Identity;
namespace XH.Infrastructure.Identity.MongoDb
{
public class IdentityRole : IdentityRole<string>
{
public virtual string TenantId { get; set; }
}
public class IdentityRole<TKey> : IRole<TKey>
{
public virtual TKey Id { get; set; }
public virtual string Name { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CustomControlz.Labels
{
public partial class CcLabel : Label
{
public CcLabel()
{
InitializeComponent();
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace WebApp.Data.Models
{
public class UserRequestModel
{
[Required(ErrorMessage = "Email could not be empty!")]
public string Email { get; set; }
[Required(ErrorMessage = "Password could not be empty!")]
public string Password { get; set; }
[Required(ErrorMessage = "Permissions fields are required!")]
public PermissionRequestModel Permission { get; set; }
}
}
|
/*
* Board class that is in charge of keeping game and player informations.
* Copyright (c) Yulo Leake 2016
*/
using Deadwood.Model.Exceptions;
using Deadwood.Model.Factories;
using Deadwood.Model.Rooms;
using System;
using System.Collections.Generic;
namespace Deadwood.Model
{
class Board
{
// Singleton Construction
private Board()
{
}
private static Board instance;
public static Board mInstance
{
get
{
if(instance == null)
{
instance = new Board();
}
return instance;
}
}
// Player fields
private List<Player> playerList;
public int playerCount { get; private set; }
public Player currentPlayer { get; private set; }
private int currentPlayerIdx;
public Random rng { get; private set; }
// Room fields
private Dictionary<string, int> roomToIndexDict;
private Dictionary<string, Room> roomNameToRoomDict;
string[] roomnames;
bool[,] roomAdjMat;
private List<Room> setList;
// Scene stuff
private Stack<Scene> sceneDeck;
private int wrapUpsLeft = 0; // when it hits 1, it's the end of the day
public void SetUpBoard(int playerCount, Random rng)
{
this.playerCount = playerCount;
if(rng == null)
{
rng = new Random();
}
this.rng = rng;
SetUpRooms();
SetUpAdjMat();
SetUpScenes();
SetUpPlayers(playerCount);
StartOfDay();
}
private void SetUpRooms()
{
IRoomFactory factory = RawRoomFactory.mInstance;
roomnames = RawRoomFactory.GetRoomNames();
roomToIndexDict = new Dictionary<string, int>(roomnames.Length);
for (int i = 0; i < roomnames.Length; i++)
{
roomToIndexDict.Add(roomnames[i], i);
}
roomNameToRoomDict = new Dictionary<string, Room>(roomnames.Length);
roomNameToRoomDict["Trailers"] = factory.CreateRoom("Trailers");
roomNameToRoomDict["Casting Office"] = factory.CreateRoom("Casting Office");
setList = new List<Room>();
for (int i = 2; i < roomnames.Length; i++)
{
// Skips Trailers and Casting Office, make all other Sets
Room s = factory.CreateRoom(roomnames[i]);
roomNameToRoomDict[roomnames[i]] = s;
setList.Add(s);
}
}
private void SetUpAdjMat()
{
// TODO: define room adjacency in XML or something
// TODO: probably move this responsibility to the actual Room class
roomAdjMat = new bool[roomnames.Length, roomnames.Length];
int i = roomToIndexDict["Train Station"];
List<int> list = new List<int>(3);
list.Add(roomToIndexDict["Jail"]);
list.Add(roomToIndexDict["General Store"]);
list.Add(roomToIndexDict["Casting Office"]);
foreach(int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Jail"];
list.Clear();
list.Add(roomToIndexDict["Main Street"]);
list.Add(roomToIndexDict["General Store"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Main Street"];
list.Clear();
list.Add(roomToIndexDict["Saloon"]);
list.Add(roomToIndexDict["Trailers"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["General Store"];
list.Clear();
list.Add(roomToIndexDict["Ranch"]);
list.Add(roomToIndexDict["Saloon"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Saloon"];
list.Clear();
list.Add(roomToIndexDict["Bank"]);
list.Add(roomToIndexDict["Trailers"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Trailers"];
list.Clear();
list.Add(roomToIndexDict["Hotel"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Casting Office"];
list.Clear();
list.Add(roomToIndexDict["Ranch"]);
list.Add(roomToIndexDict["Secret Hideout"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Ranch"];
list.Clear();
list.Add(roomToIndexDict["Bank"]);
list.Add(roomToIndexDict["Secret Hideout"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Bank"];
list.Clear();
list.Add(roomToIndexDict["Hotel"]);
list.Add(roomToIndexDict["Church"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Secret Hideout"];
list.Clear();
list.Add(roomToIndexDict["Church"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
i = roomToIndexDict["Church"];
list.Clear();
list.Add(roomToIndexDict["Hotel"]);
foreach (int j in list)
{
roomAdjMat[i, j] = true;
roomAdjMat[j, i] = true;
}
}
private void SetUpPlayers(int count)
{
this.playerList = new List<Player>(count);
string[] colors = {"blue", "cyan", "green", "orange", "pink", "red", "violet", "yellow"}; // used as name for players
int startingCred = 0;
int startingRank = 1;
switch (count)
{
case 2:
case 3:
Console.WriteLine("Special Rule: Only 3 days instead of 4");
// POP 10 cards, since each day uses 10 scenes
for (int i = 0; i < 10; i++)
{
sceneDeck.Pop();
}
break;
case 5:
Console.WriteLine("Special Rule: Every player starts with 2 credits..");
startingCred = 2;
break;
case 6:
Console.WriteLine("Special Rule: Every player starts with 4 credits.");
startingCred = 4;
break;
case 7:
case 8:
Console.WriteLine("Special Rule: Every player starts with rank 2.");
startingRank = 2;
break;
}
// Create prototype of Player with same starting credit and rank, clone prototype with different names
Player proto = Player.MakePrototype(startingCred, startingRank);
for (int i = 0; i < count; i++)
{
playerList.Add(proto.Clone(colors[i]));
}
currentPlayerIdx = 0; ;
currentPlayer = playerList[currentPlayerIdx];
currentPlayer.StartOfTurn();
}
// Create the 40 scenes in the game
private void SetUpScenes()
{
// Get scene names and create each scenes
List<Scene> scenes = new List<Scene>();
ISceneFactory factory = RawSceneFactory.mInstance;
string[] sceneNames = RawSceneFactory.GetSceneNames();
foreach(string s in sceneNames)
{
scenes.Add(factory.MakeScene(s));
}
// Shuffle the Scene list and put it in a stack
int n = scenes.Count;
Console.WriteLine(n);
while(n > 1)
{
n--;
int k = rng.Next(n+1);
Scene tmp = scenes[k];
scenes[k] = scenes[n];
scenes[n] = tmp;
}
sceneDeck = new Stack<Scene>(scenes);
}
private void StartOfDay()
{
if(setList.Count == 0)
{
// End of the game
Console.WriteLine("Game over!");
DisplayScore();
return;
}
Console.WriteLine("A new Day has begun.");
Console.WriteLine("Everybody starts at the Trailers.");
Console.WriteLine("New Scenes has been set on each Set.");
Console.WriteLine("");
// Put out a scene card to each set
Scene scene = null;
foreach(Set set in setList)
{
scene = sceneDeck.Pop();
set.AssignScene(scene);
wrapUpsLeft++;
}
Console.WriteLine("Scenes left = {0:d}", sceneDeck.Count);
Player.BrandNewDay(playerList);
}
private void EndOfDay()
{
Console.WriteLine("The Day has ended.");
wrapUpsLeft = 0;
foreach (Room r in setList)
{
r.EndOfDay();
}
DisplayScore();
Console.WriteLine("");
}
// Rolling the die [1,6] and return the value
public int RollD6()
{
return this.rng.Next(1, 7);
}
// Return list of roomnames that is adjacent to current player's room
public List<Room> GetAdjacentRooms()
{
string roomname = currentPlayer.room.name;
return GetAdjacentRooms(roomname);
}
// Return list of room that is adjacent to given roomname
public List<Room> GetAdjacentRooms(string roomname)
{
// Check if roomname given is a valid roomname
if (roomToIndexDict.ContainsKey(roomname) == false)
{
Console.Error.WriteLine("Error: room \"{0}\" does not exist", roomname);
return null;
}
// Create list and add all adjacent rooms
List <Room> list = new List<Room>();
int i = roomToIndexDict[roomname];
for(int j = 0; j < roomnames.Length; j++)
{
if(roomAdjMat[i, j])
{
list.Add(roomNameToRoomDict[roomnames[j]]);
}
}
return list;
}
// Return true if src and dec are adjacent, false otherwise
public bool AreRoomsAdjacent(string src, string des)
{
// Handle for non-existing room cases
if(roomToIndexDict.ContainsKey(src) == false)
{
throw new IllegalBoardRequestException("Error: Requested source room \"" + src + "\" does not exist.");
}
if(roomToIndexDict.ContainsKey(des) == false)
{
throw new IllegalBoardRequestException("Error: Requested destination room \"" + des + "\" does not exist.");
}
int srcIdx = roomToIndexDict[src];
int desIdx = roomToIndexDict[des];
return roomAdjMat[srcIdx, desIdx];
}
// Return a list of all available starring roles in given room
public List<Role> GetAvailableStarringRoles(string roomname)
{
try
{
// Check if given roomname is a valid one
ValidateRoom(roomname);
// Get available starring roles
return roomNameToRoomDict[roomname].GetAvailableStarringRoles();
}
catch (KeyNotFoundException)
{
// Given roomname was not valid, throw an error
throw;
}
catch (IllegalRoomActionException)
{
// There were no available roles
throw;
}
}
// Return a list of all starring roles in given room, regardless of their availability
public List<Role> GetAllStarringRoles(string roomname)
{
try
{
// Check if given roomname is a valid one
ValidateRoom(roomname);
// Get all starring roles
return roomNameToRoomDict[roomname].GetAllStarringRoles();
}
catch (KeyNotFoundException)
{
// Given roomname was not valid, throw an error
throw;
}
catch (IllegalRoomActionException)
{
// There were no available roles
throw;
}
}
// Return a list of all available extra roles in given room
public List<Role> GetAvailableExtraRoles(string roomname)
{
try
{
// Check if given roomname is a valid one
ValidateRoom(roomname);
// Get available extra roles
return roomNameToRoomDict[roomname].GetAvailableExtraRoles();
}
catch (KeyNotFoundException)
{
// Given roomname was not valid, throw an error
throw;
}
catch (IllegalRoomActionException)
{
// There were no available roles
throw;
}
}
// Return a list of all extra roles in given room, regardless of their availability
public List<Role> GetAllExtraRoles(string roomname)
{
try
{
// Check if given roomname is a valid one
ValidateRoom(roomname);
// Get all extra roles
return roomNameToRoomDict[roomname].GetAllExtraRoles();
}
catch (KeyNotFoundException)
{
// Given roomname was not valid, throw an error
throw;
}
catch (IllegalRoomActionException)
{
// There were no available roles
throw;
}
}
public Room GetRoom(string roomname)
{
if(roomNameToRoomDict.ContainsKey(roomname) == false)
{
throw new IllegalBoardRequestException("Error: Requested room \"" + roomname + "\" does not exist.");
}
return roomNameToRoomDict[roomname];
}
// Player moves
public void Move(string dst)
{
try
{
currentPlayer.Move(dst);
}
catch(IllegalBoardRequestException e)
{
Console.WriteLine(e.msg);
}
catch(IllegalUserActionException e)
{
Console.WriteLine(e.msg);
}
}
// Give current player the role
public void TakeRole(string rolename)
{
try
{
currentPlayer.TakeRole(rolename);
}
catch(IllegalUserActionException e)
{
Console.WriteLine(e.msg);
}
}
// Player ends turn, switch to next player
public void EndTurn()
{
currentPlayerIdx++;
currentPlayerIdx %= playerCount; // wrap it back
currentPlayer = playerList[currentPlayerIdx];
currentPlayer.StartOfTurn();
}
// Make current player rehearse
public void Rehearse()
{
try
{
currentPlayer.Rehearse();
}
catch(IllegalUserActionException e)
{
Console.WriteLine(e.msg);
}
}
// Make current player act
public void Act()
{
try
{
currentPlayer.Act();
}
catch (IllegalUserActionException e)
{
Console.WriteLine(e.msg);
}
}
private void ValidateRoom(string roomname)
{
if (roomToIndexDict.ContainsKey(roomname) == false)
{
throw new KeyNotFoundException(string.Format("Error: room \"{0}\" does not exist", roomname));
}
}
// Called by Sets when a scene has wrapped
// Decrease the wrapups that is left and start a new day if there is 1 wrapup left
public void WrapScene()
{
wrapUpsLeft--;
if(wrapUpsLeft == 1)
{
// One scene left, start a new day
EndTurn();
EndOfDay();
StartOfDay();
}
}
// Upgrade current player's rank using money
public void UpgradeMoney(int rank)
{
try
{
currentPlayer.Upgrade(CurrencyType.Money, rank);
}
catch(IllegalUserActionException e)
{
Console.WriteLine(e.msg);
}
}
// Upgrade current player's rank using credit
public void UpgradeCredit(int rank)
{
try
{
currentPlayer.Upgrade(CurrencyType.Credit, rank);
}
catch (IllegalUserActionException e)
{
Console.WriteLine(e.msg);
}
}
public void DisplayScore()
{
Console.WriteLine("Current Score:");
for(int i = 0; i < playerList.Count; i++)
{
Console.WriteLine("\t{0:d}). " + playerList[i], i+1);
}
}
}
}
|
using System;
using System.Collections.Generic;
using Backend.Models;
using Backend.Services;
using Nancy;
using Nancy.ModelBinding;
namespace Backend.Modules
{
public class CartModule : Module
{
private readonly CartService _cartService;
public CartModule(CartService cartService)
: base("/Cart")
{
Before += OnBeforeRequest;
_cartService = cartService;
Get["/"] = _ => GetCarts();
Post["/"] = _ => PostCart();
Get["/{cartId:int}"] = p => GetCart(p.cartId);
Get["/{cartId:int}/User/{phonenumber:long}"] = p => GetCart(p.cartId, p.phonenumber);
Post["/{cartId:int}/Item"] = p => PostCartItem(p.cartId);
Post["/{cartId:int}/Item/{productId:int}"] = p => PostCartItem(p.cartId, p.productId);
Delete["/Item/{itemId:int}"] = p => DeleteCartItem(p.itemId);
Post["/Item/{itemId:int}/User/{phonenumber:long}"] = p => PostUser(p.itemId, p.phonenumber);
Delete["/Item/{itemId:int}/User/{phonenumber:long}"] = p => DeleteUser(p.itemId, p.phonenumber);
Put["/Item/{itemId:int}/User/{phonenumber:long}/Amount/{amount:int}"] = p => PutUser(p.itemId, p.phonenumber, p.amount);
Get["/{cartId:int}/Balance/{phonenumber:long}"] = p => GetBalance(p.cartId, p.phonenumber);
Get["/{cartId:int}/Users"] = p => GetUsers(p.cartId);
Post["/Item/{itemId:int}/Pay"] = p => PostPayCash(p.itemId);
Post["/{cartId:int}/Pay"] = p => PostPayPaymit(p.cartId);
}
private object DeleteCartItem(int itemId)
{
_cartService.DeleteItem(itemId);
NotifyClients();
return HttpStatusCode.OK;
}
private object DeleteUser(int itemId, long phonenumber)
{
_cartService.RemoveUserFromItem(itemId, phonenumber);
NotifyClients();
return HttpStatusCode.OK;
}
private object GetBalance(int cartId, long phonenumber)
{
return new { Balance = _cartService.GetBalance(cartId, phonenumber) };
}
private object GetCart(int cartId)
{
return Response.AsJson(_cartService.GetCart(cartId));
}
private object GetCart(int cartId, long phonenumber)
{
Console.WriteLine(phonenumber);
return Response.AsJson(_cartService.GetCart(cartId, phonenumber));
}
private object GetCarts()
{
int merchantId = Request.Query.merchantId;
return _cartService.GetCarts(merchantId);
}
private object GetUsers(int cartId)
{
return _cartService.GetUsers(cartId);
}
private Response OnBeforeRequest(NancyContext arg)
{
//UserId = arg.Request.Query.userId;
//MerchantId = arg.Request.Query.merchantId;
//if (UserId <= 0 && MerchantId <= 0)
//{
// return HttpStatusCode.Unauthorized;
//}
//return null;
return null;
}
private object PostCart()
{
int merchantId = Request.Query.merchantId;
var response = Response.AsJson(new { CartId = _cartService.CreateCart(merchantId) });
NotifyClients();
return response;
}
private object PostCartItem(int cartId)
{
var model = this.Bind<CartItemModel>();
var response = Response.AsJson(new { ItemId = _cartService.CreateItem(cartId, model.Description, model.Price, model.Amount) });
NotifyClients();
return response;
}
private object PostCartItem(int cartId, int productId)
{
var response = Response.AsJson(new { ItemId = _cartService.CreateItem(cartId, productId, 1) });
NotifyClients();
return response;
}
private object PostPayCash(int itemId)
{
_cartService.PayCash(itemId);
NotifyClients();
return HttpStatusCode.OK;
}
private object PostPayPaymit(int cartId)
{
// TODO create a payment from the currently logged in user to the merchant
const int userId = 0;
var phonenumbers = this.Bind<IEnumerable<long>>();
Console.Write("phonenumbers: " + phonenumbers);
if (phonenumbers != null)
{
Console.WriteLine(string.Join(", ", phonenumbers));
}
_cartService.PayCart(cartId, phonenumbers);
NotifyClients();
return HttpStatusCode.OK;
}
private object PostUser(int itemId, long phonenumber)
{
_cartService.AddUserToItem(itemId, phonenumber);
NotifyClients();
return HttpStatusCode.OK;
}
private object PutUser(int itemId, long phonenumber, int amount)
{
_cartService.SetItemAmount(itemId, phonenumber, amount);
NotifyClients();
return HttpStatusCode.OK;
}
}
}
|
using UnityEngine.Events;
public class LastBlockDestroyed : UnityEvent
{
}
|
using System.ComponentModel;
namespace Properties.Core.Objects
{
public enum CheckType
{
Unknown = 0,
[Description("Smoke Detector")]
SmokeDetector = 1,
[Description("Carbon Monoxide Detector")]
CarbonMonoxideDetector = 2,
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Ecommerce_Framework.Api.Models
{
[Table("Produto", Schema = "EcommerceFramework")]
public class ProdutoModel {
public ProdutoModel() { }
public ProdutoModel(int id, string produto, string descricao, double valor, int saldoestoque,string img)
{
this.ProdutoId = id;
this.Produto = produto;
this.Descricao = descricao;
this.Valor = valor;
this.SaldoEstoque = saldoestoque;
this.Img = img;
}
[Key]
public int ProdutoId { get; set; }
[Required, MaxLength(100)]
public string Produto { get; set; }
[MaxLength(300)]
public string Descricao { get; set; }
[Required]
public Double Valor { get; set; }
public int SaldoEstoque { get; set; }
[MaxLength(100)]
public string Img { get; set; }
}
}
|
using System;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;
using DgKMS.Cube.CubeCore.Dtos;
using DgKMS.Cube.CubeCore;
namespace DgKMS.Cube.CubeCore
{
/// <summary>
/// 应用层服务的接口方法
///</summary>
public interface IEvernoteTagAppService : IApplicationService
{
/// <summary>
/// 获取的分页列表集合
///</summary>
/// <param name="input"></param>
/// <returns></returns>
Task<PagedResultDto<EvernoteTagListDto>> GetPaged(GetEvernoteTagsInput input);
/// <summary>
/// 通过指定id获取ListDto信息
/// </summary>
Task<EvernoteTagListDto> GetById(EntityDto<ulong> input);
/// <summary>
/// 返回实体的EditDto
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<GetEvernoteTagForEditOutput> GetForEdit(NullableIdDto<ulong> input);
/// <summary>
/// 添加或者修改的公共方法
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task CreateOrUpdate(CreateOrUpdateEvernoteTagInput input);
/// <summary>
/// 删除
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task Delete(EntityDto<ulong> input);
/// <summary>
/// 批量删除
/// </summary>
Task BatchDelete(List<ulong> input);
/// <summary>
/// 导出为excel文件
/// </summary>
/// <returns></returns>
//Task<FileDto> GetToExcelFile();
//// custom codes
//// custom codes end
}
}
|
namespace com.Sconit.Web.Controllers
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.PRD;
using com.Sconit.Entity.SCM;
using com.Sconit.Entity.SYS;
//using com.Sconit.Entity.SCM;
using com.Sconit.Web.Models;
using Telerik.Web.Mvc.UI;
using System;
using com.Sconit.Entity.BIL;
using com.Sconit.Service;
using NHibernate.Criterion;
using com.Sconit.Entity.ORD;
using NHibernate.Type;
using NHibernate;
using com.Sconit.Entity.ISS;
using com.Sconit.Entity.ACC;
using com.Sconit.Entity.INP;
using com.Sconit.Entity;
public class CommonController : WebAppBaseController
{
private static int firstRow = 0;
private static int maxRow = 20;
private static string selectEqItemStatement = "from Item as i where i.Code = ? and IsActive = ?";
private static string selectLikeItemStatement = "from Item as i where i.Code like ? and IsActive = ?";
//private static string selectEqUserStatement = "from User as u where u.Code = ? and u.IsActive = ?";
//private static string selectLikeUserStatement = "from User as u where u.Code like ? and u.IsActive = ?";
//private static string selectEqItemPackageStatement = "from ItemPackage as i where convert(VARCHAR,i.UnitCount) = ?";
//private static string selectLikeItemPackageStatement = "from ItemPackage as i where i.Item=? and convert(VARCHAR,i.UnitCount) like ? ";
private static string selectEqSupplierStatement = "from Supplier as s where s.Code = ? and IsActive = ?";
private static string selectLikeSupplierStatement = "from Supplier as s where s.Code like ? and IsActive = ?";
//private static string selectEqCustomerStatement = "from Customer as c where c.Code = ? and IsActive = ?";
//private static string selectLikeCustomerStatement = "from Customer as c where c.Code like ? and IsActive = ?";
//private static string selectEqRegionStatement = "from Region as r where r.Code = ? and IsActive = ?";
//private static string selectLikeRegionStatement = "from Region as r where r.Code like ? and IsActive = ?";
//private static string selectLikeRoutingStatement = "from RoutingMaster as r where r.Code like ? and IsActive = ?";
//private static string selectEqBomStatement = "from BomMaster as b where b.Code = ? and IsActive = ?";
//private static string selectLikeBomStatement = "from BomMaster as b where b.Code like ? and IsActive = ?";
//private static string selectEqIssueAddressStatement = "from IssueAddress as ia where ia.Code = ? or ia.Description = ? order by Sequence";
//private static string selectLikeIssueAddressStatement = "from IssueAddress as ia where ia.Code like ? or ia.Description like ? order by Sequence";
//private static string selectRegionStatement = "from Region as r where r.IsActive = ?";
//private static string selectEqFlowStatement = "from FlowMaster as f where f.Code = ?";
//private static string selectEqOrderStatement = "from OrderMaster as o where o.Code = ?";
//private static string selectEqTraceCodeStatement = "from OrderDetailTrace as t where t.Code = ?";
//private static string supplierAddress = @"select a from PartyAddress p join p.Address as a where p.Party=? and a.Type=?";
//private static string shipToAddress = @"select a from PartyAddress p join p.Address as a where p.Party=? and a.Type=?";
//private static string selectProductLineFacilityStatement = "from ProductLineFacility as p where p.ProductLine = ?";
//private static string selectLikeLocationStatement = "from Location as l where l.Code like ? and l.IsActive = ?";
//public IGenericMgr genericMgr { get; set; }
//#region public methods
//public ActionResult _SiteMapPath(string menuContent)
//{
// IList<com.Sconit.Entity.SYS.Menu> allMenu = systemMgr.GetAllMenu();
// IList<MenuModel> allMenuModel = Mapper.Map<IList<com.Sconit.Entity.SYS.Menu>, IList<MenuModel>>(allMenu);
// List<MenuModel> menuList = allMenuModel.Where(m => m.Code == menuContent).ToList();
// this.NestGetParentMenu(menuList, menuList, allMenuModel);
// return PartialView(menuList);
//}
//#region CodeMaster
//public ActionResult _CodeMasterDropDownList(com.Sconit.CodeMaster.CodeMaster code, string controlName, string controlId, string selectedValue, string ajaxActionName,
// //string[] parentCascadeControlNames, string[] cascadingControlNames,
// bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable, bool? isConsignment, bool? isShowNA)
//{
// IList<CodeDetail> codeDetailList = systemMgr.GetCodeDetails(code, includeBlankOption, blankOptionDescription, blankOptionValue);
// //采购路线中的结算方式 不显示寄售结算
// if (isConsignment != null)
// {
// if (code == com.Sconit.CodeMaster.CodeMaster.BillTerm)
// {
// if ((bool)isConsignment)
// {
// codeDetailList = this.queryMgr.FindAll<CodeDetail>("from CodeDetail c where c.Description in ('" + "CodeDetail_BillTerm_BAC" + "','" + "CodeDetail_BillTerm_NA" + "','" + "CodeDetail_BillTerm_BAR" + "') order by c.Sequence");
// }
// else
// {
// IList<CodeDetail> codeDetail = this.queryMgr.FindAll<CodeDetail>("from CodeDetail c where c.Description = ?", "CodeDetail_BillTerm_BAC");
// if (codeDetail.Count > 0)
// {
// codeDetailList.Remove(codeDetail[0]);
// }
// }
// if (isShowNA != null)
// {
// if (!(bool)isShowNA)
// {
// IList<CodeDetail> codeDetail = this.queryMgr.FindAll<CodeDetail>("from CodeDetail c where c.Description = ?", "CodeDetail_BillTerm_NA");
// if (codeDetail.Count > 0)
// {
// codeDetailList.Remove(codeDetail[0]);
// }
// }
// }
// }
// }
// //收货和发货的OrderType 不显示销售和生产
// if (code == com.Sconit.CodeMaster.CodeMaster.OrderType)
// {
// if (controlName == "GoodsReceiptOrderType" || controlName == "IpOrderType")
// {
// IList<CodeDetail> codeDetail = this.queryMgr.FindAll<CodeDetail>("from CodeDetail c where c.Description = ? or c.Description=?",
// new object[] { "CodeDetail_OrderType_Distribution", "CodeDetail_OrderType_Production" });
// if (codeDetail.Count > 0)
// {
// for (int i = 0; i < codeDetail.Count; i++)
// {
// codeDetailList.Remove(codeDetail[i]);
// }
// }
// }
// }
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.AjaxActionName = ajaxActionName;
// ViewBag.Enable = enable;
// // codeDetailList.Add(new CodeDetail());
// //ViewBag.CascadingControlNames = cascadingControlNames;
// //ViewBag.ParentCascadeControlNames = parentCascadeControlNames;
// return PartialView(base.Transfer2DropDownList(code, codeDetailList, selectedValue));
//}
////public ActionResult _CodeMasterAjaxDropDownList(com.Sconit.CodeMaster.CodeMaster code, string controlName, string controlId, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue)
////{
//// ViewBag.Code = code;
//// ViewBag.ControlName = controlName;
//// ViewBag.IncludeBlankOption = includeBlankOption;
//// ViewBag.BlankOptionDescription = blankOptionDescription;
//// ViewBag.BlankOptionValue = blankOptionValue;
//// return PartialView();
////}
//public ActionResult _AjaxLoadingCodeMaster(com.Sconit.CodeMaster.CodeMaster code, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable)
//{
// ViewBag.Enable = enable;
// IList<CodeDetail> codeDetailList = systemMgr.GetCodeDetails(code, includeBlankOption, blankOptionDescription, blankOptionValue);
// return new JsonResult { Data = base.Transfer2DropDownList(code, codeDetailList) };
//}
//#endregion
//#region Region
//public ActionResult _RegionDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? coupled)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Coupled = coupled;
// //ViewBag.SelectedValue = selectedValue;
// IList<Region> regionList = queryMgr.FindAll<Region>(selectRegionStatement, true);
// if (regionList == null)
// {
// regionList = new List<Region>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Region blankRegion = new Region();
// blankRegion.Code = blankOptionValue;
// blankRegion.Name = blankOptionDescription;
// regionList.Insert(0, blankRegion);
// }
// return PartialView(new SelectList(regionList, "Code", "Name", selectedValue));
//}
//#endregion
//#region User
//public ActionResult _UserComboBox(string controlName, string controlId, string selectedValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Enable = enable;
// IList<User> userList = new List<User>();
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// userList = queryMgr.FindAll<User>(selectEqUserStatement, new object[] { selectedValue, true });
// }
// //ViewBag.UserFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.UserFilterMode);
// //ViewBag.UserFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.UserFilterMinimumChars));
// return PartialView(new SelectList(userList, "Code", "CodeDescription", selectedValue));
//}
//public ActionResult _UserAjaxLoading(string text)
//{
// //AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.UserFilterMode), true);
// IList<User> userList = new List<User>();
// //if (fileterMode == AutoCompleteFilterMode.Contains)
// //{
// // userList = queryMgr.FindAll<User>(selectLikeUserStatement, new object[] { "%" + text + "%", true });
// //}
// //else
// //{
// userList = queryMgr.FindAll<User>(selectLikeUserStatement, new object[] { text + "%", true });
// //}
// return new JsonResult { Data = new SelectList(userList, "Code", "CodeDescription") };
//}
//#endregion
//#region Item
public ActionResult _ItemComboBox(string controlName, string controlId, string selectedValue, bool? enable, bool? coupled)
{
ViewBag.ControlName = controlName;
ViewBag.ControlId = controlId;
ViewBag.Enable = enable;
ViewBag.Coupled = coupled;
IList<Item> itemList = new List<Item>();
if (selectedValue != null && selectedValue.Trim() != string.Empty)
{
itemList = queryMgr.FindAll<Item>(selectEqItemStatement, new object[] { selectedValue, true });
}
ViewBag.ItemFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode);
ViewBag.ItemFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMinimumChars));
return PartialView(new SelectList(itemList, "Code", "CodeDescription", selectedValue));
}
public ActionResult _ItemAjaxLoading(string text)
{
AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode), true);
IList<Item> itemList = new List<Item>();
if (fileterMode == AutoCompleteFilterMode.Contains)
{
itemList = queryMgr.FindAll<Item>(selectLikeItemStatement, new object[] { "%" + text + "%", true }, firstRow, maxRow);
}
else
{
itemList = queryMgr.FindAll<Item>(selectLikeItemStatement, new object[] { text + "%", true }, firstRow, maxRow);
}
return new JsonResult { Data = new SelectList(itemList, "Code", "CodeDescription") };
}
//#endregion
//#region Bom
//public ActionResult _BomComboBox(string controlName, string controlId, string selectedValue)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<BomMaster> bomList = new List<BomMaster>();
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// bomList = queryMgr.FindAll<BomMaster>(selectEqBomStatement, new object[] { selectedValue, true });
// }
// ViewBag.ItemFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode);
// ViewBag.ItemFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMinimumChars));
// return PartialView(new SelectList(bomList, "Code", "CodeDescription", selectedValue));
//}
//public ActionResult _BomAjaxLoading(string text)
//{
// AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode), true);
// IList<BomMaster> bomList = new List<BomMaster>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// bomList = queryMgr.FindAll<BomMaster>(selectLikeBomStatement, new object[] { "%" + text + "%", true });
// }
// else
// {
// bomList = queryMgr.FindAll<BomMaster>(selectLikeBomStatement, new object[] { text + "%", true });
// }
// return new JsonResult { Data = new SelectList(bomList, "Code", "CodeDescription") };
//}
//#endregion
//#region ItemCategory
//public ActionResult _ItemCategoryDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.Enable = enable;
// IList<ItemCategory> itemCategoryList = queryMgr.FindAll<ItemCategory>("from ItemCategory as i");
// if (itemCategoryList == null)
// {
// itemCategoryList = new List<ItemCategory>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// ItemCategory blankitemCategory = new ItemCategory();
// blankitemCategory.Code = blankOptionValue;
// blankitemCategory.Description = blankOptionDescription;
// itemCategoryList.Insert(0, blankitemCategory);
// }
// return PartialView(new SelectList(itemCategoryList, "Code", "Description", selectedValue));
//}
//#endregion
//#region Location
//public ActionResult _LocationDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.Enable = enable;
// ViewBag.IsChange = isChange;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<Location> locationList = queryMgr.FindAll<Location>("from Location as l where l.IsActive=?", true);
// if (locationList == null)
// {
// locationList = new List<Location>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Location blankLocation = new Location();
// blankLocation.Code = blankOptionValue;
// blankLocation.Name = blankOptionDescription;
// locationList.Insert(0, blankLocation);
// }
// return PartialView(new SelectList(locationList, "Code", "Name", selectedValue));
//}
//public ActionResult _LocationComboBox(string controlName, string controlId, string selectedValue, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.Enable = enable;
// ViewBag.IsChange = isChange;
// ViewBag.ControlId = controlId;
// ViewBag.SelectedValue = selectedValue;
// IList<Location> locationList = queryMgr.FindAll<Location>("from Location as l where l.IsActive=?", true);
// if (locationList == null)
// {
// locationList = new List<Location>();
// }
// return PartialView(new SelectList(locationList, "Code", "CodeName", selectedValue));
//}
//public ActionResult _LocationAjaxLoading(string text)
//{
// AutoCompleteFilterMode fileterMode = AutoCompleteFilterMode.StartsWith;
// IList<Location> locationList = new List<Location>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// locationList = queryMgr.FindAll<Location>(selectLikeLocationStatement, new object[] { "%" + text + "%", true });
// }
// else
// {
// locationList = queryMgr.FindAll<Location>(selectLikeLocationStatement, new object[] { text + "%", true });
// }
// return new JsonResult { Data = new SelectList(locationList, "Code", "Name") };
//}
//#endregion
//#region Party
//public ActionResult _PartyDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<Party> PartyList = queryMgr.FindAll<Party>("from Party as p");
// if (PartyList == null)
// {
// PartyList = new List<Party>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Party blankParty = new Party();
// blankParty.Code = blankOptionValue;
// blankParty.Name = blankOptionDescription;
// PartyList.Insert(0, blankParty);
// }
// return PartialView(new SelectList(PartyList, "Code", "Name", selectedValue));
//}
//#endregion
//#region Tax
//public ActionResult _TaxDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<Tax> taxList = queryMgr.FindAll<Tax>("from Tax as t");
// if (taxList == null)
// {
// taxList = new List<Tax>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Tax blankTax = new Tax();
// blankTax.Code = blankOptionValue;
// blankTax.Name = blankOptionDescription;
// taxList.Insert(0, blankTax);
// }
// return PartialView(new SelectList(taxList, "Code", "Name", selectedValue));
//}
//#endregion
//#region Supplier lqy
//public ActionResult _SupplierDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? coupled)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Coupled = coupled;
// //ViewBag.SelectedValue = selectedValue;
// IList<Supplier> supplierList = queryMgr.FindAll<Supplier>("from Supplier as s where s.IsActive = ?", true);
// if (supplierList == null)
// {
// supplierList = new List<Supplier>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Supplier blankSupplier = new Supplier();
// supplierList.Insert(0, blankSupplier);
// }
// return PartialView(new SelectList(supplierList, "Code", "Name", selectedValue));
//}
//#endregion
//#region Customer lqy
//public ActionResult _CustomerDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? coupled)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Coupled = coupled;
// //ViewBag.SelectedValue = selectedValue;
// IList<Customer> customerList = queryMgr.FindAll<Customer>("from Customer as c where c.IsActive = ?", true);
// if (customerList == null)
// {
// customerList = new List<Customer>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Customer blankCustomer = new Customer();
// customerList.Insert(0, blankCustomer);
// }
// return PartialView(new SelectList(customerList, "Code", "Name", selectedValue));
//}
//#endregion
//#region ShipAddress lqy
//public ActionResult _ShipAddressDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.IsChange = isChange;
// ViewBag.Enable = enable;
// IList<Address> addressList = queryMgr.FindAll<Address>(" from Address as a where a.Type = ? ", 0);
// if (addressList == null)
// {
// addressList = new List<Address>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Address blankAddress = new Address();
// addressList.Insert(0, blankAddress);
// }
// return PartialView(new SelectList(addressList, "Code", "AddressContent", selectedValue));
//}
//public ActionResult _ShipAddressComboBox(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.IsChange = isChange;
// ViewBag.Enable = enable;
// IList<Address> addressList = queryMgr.FindAll<Address>(" from Address as a where a.Type = ? ", 0);
// if (addressList == null)
// {
// addressList = new List<Address>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Address blankAddress = new Address();
// addressList.Insert(0, blankAddress);
// }
// return PartialView(new SelectList(addressList, "Code", "AddressContent", selectedValue));
//}
//#endregion
//#region BillAddress lqy
//public ActionResult _BillAddressDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.IsChange = isChange;
// ViewBag.Enable = enable;
// IList<Address> addressList = queryMgr.FindAll<Address>(" from Address as a where a.Type = ? ", 1);
// if (addressList == null)
// {
// addressList = new List<Address>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Address blankAddress = new Address();
// addressList.Insert(0, blankAddress);
// }
// return PartialView(new SelectList(addressList, "Code", "AddressContent", selectedValue));
//}
//public ActionResult _BillAddressComboBox(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.IsChange = isChange;
// ViewBag.Enable = enable;
// IList<Address> addressList = queryMgr.FindAll<Address>(" from Address as a where a.Type = ? ", 1);
// if (addressList == null)
// {
// addressList = new List<Address>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Address blankAddress = new Address();
// addressList.Insert(0, blankAddress);
// }
// return PartialView(new SelectList(addressList, "Code", "AddressContent", selectedValue));
//}
//#endregion
//#region Routing lqy
//public ActionResult _RoutingDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// IList<RoutingMaster> routingList = queryMgr.FindAll<RoutingMaster>(" from RoutingMaster as r where r.IsActive = ? ", true);
// if (routingList == null)
// {
// routingList = new List<RoutingMaster>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// RoutingMaster blankRoutingMaster = new RoutingMaster();
// routingList.Insert(0, blankRoutingMaster);
// }
// return PartialView(new SelectList(routingList, "Code", "Name", selectedValue));
//}
//public ActionResult _RoutingComboBox(string controlName, string selectedValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.Enable = enable;
// IList<RoutingMaster> routingList = queryMgr.FindAll<RoutingMaster>(" from RoutingMaster as r where r.IsActive = ? ", true);
// if (routingList == null)
// {
// routingList = new List<RoutingMaster>();
// }
// return PartialView(new SelectList(routingList, "Code", "Name", selectedValue));
//}
//public ActionResult _RoutingAjaxLoading(string text)
//{
// AutoCompleteFilterMode fileterMode = AutoCompleteFilterMode.StartsWith;
// IList<RoutingMaster> routingList = new List<RoutingMaster>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// routingList = queryMgr.FindAll<RoutingMaster>(selectLikeRoutingStatement, new object[] { "%" + text + "%", true });
// }
// else
// {
// routingList = queryMgr.FindAll<RoutingMaster>(selectLikeRoutingStatement, new object[] { text + "%", true });
// }
// return new JsonResult { Data = new SelectList(routingList, "Code", "Name") };
//}
//#endregion
//#region PriceList lqy
//public ActionResult _PriceListDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.IsChange = isChange;
// ViewBag.Enable = enable;
// IList<PriceListMaster> priceList = queryMgr.FindAll<PriceListMaster>(" from PriceListMaster as p where p.IsActive = ? ", true);
// if (priceList == null)
// {
// priceList = new List<PriceListMaster>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// PriceListMaster blankPriceListMaster = new PriceListMaster();
// priceList.Insert(0, blankPriceListMaster);
// }
// return PartialView(new SelectList(priceList, "Code", "Code", selectedValue));
//}
//#endregion
//#region Uom
//public ActionResult _UomDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.Enable = enable;
// IList<Uom> uomList = queryMgr.FindAll<Uom>("from Uom as u");
// if (uomList == null)
// {
// uomList = new List<Uom>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Uom blankUom = new Uom();
// blankUom.Code = blankOptionValue;
// blankUom.Description = blankOptionDescription;
// uomList.Insert(0, blankUom);
// }
// return PartialView(new SelectList(uomList, "Code", "Code", selectedValue));
//}
//#endregion
//#region IssueType
//public ActionResult _IssueTypeDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable, bool? coupled)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.Enable = enable;
// ViewBag.Coupled = coupled;
// IList<IssueType> issueTypeList = queryMgr.FindAll<IssueType>("from IssueType where IsActive = ?", true);
// if (issueTypeList == null)
// {
// issueTypeList = new List<IssueType>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// IssueType blankIssueType = new IssueType();
// blankIssueType.Code = blankOptionValue;
// blankIssueType.Description = blankOptionDescription;
// issueTypeList.Insert(0, blankIssueType);
// }
// return PartialView(new SelectList(issueTypeList, "Code", "Description", selectedValue));
//}
//#endregion
//#region IssueNo
//public ActionResult _IssueNoDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.Enable = enable;
// ViewBag.IsChange = isChange;
// IList<IssueNo> issueNoList = queryMgr.FindAll<IssueNo>("from IssueNo as ino");
// if (issueNoList == null)
// {
// issueNoList = new List<IssueNo>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// IssueNo blankIssueNo = new IssueNo();
// blankIssueNo.Code = blankOptionValue;
// blankIssueNo.Description = blankOptionDescription;
// issueNoList.Insert(0, blankIssueNo);
// }
// return PartialView(new SelectList(issueNoList, "Code", "Description", selectedValue));
//}
//#endregion
//#region IssueLevel
//public ActionResult _IssueLevelDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.Enable = enable;
// IList<IssueLevel> issueLevelList = queryMgr.FindAll<IssueLevel>("from IssueLevel as il");
// if (issueLevelList == null)
// {
// issueLevelList = new List<IssueLevel>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// IssueLevel blankIssueLevel = new IssueLevel();
// blankIssueLevel.Code = blankOptionValue;
// blankIssueLevel.Description = blankOptionDescription;
// issueLevelList.Insert(0, blankIssueLevel);
// }
// return PartialView(new SelectList(issueLevelList, "Code", "Description", selectedValue));
//}
//#endregion
//#region IssueAddress
//public ActionResult _IssueAddressDropDownList(string code, string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// ViewBag.Enable = enable;
// string hql = "from IssueAddress as ia ";
// if (!string.IsNullOrEmpty(code))
// {
// hql += "where ia.Code !='" + code + "'";
// }
// IList<IssueAddress> issueAddressList = queryMgr.FindAll<IssueAddress>(hql);
// if (issueAddressList == null)
// {
// issueAddressList = new List<IssueAddress>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// IssueAddress blankIssueAddress = new IssueAddress();
// issueAddressList.Insert(0, blankIssueAddress);
// }
// return PartialView(new SelectList(issueAddressList, "Code", "CodeDescription", selectedValue));
//}
//public ActionResult _IssueAddressComboBox(string controlName, string controlId, string selectedValue)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.SelectedValue = selectedValue;
// IList<IssueAddress> issueAddressList = new List<IssueAddress>();
// //ViewBag.IssueAddressFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.IssueAddressFilterMode);
// //ViewBag.IssueAddressFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.IssueAddressFilterMinimumChars));
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// issueAddressList = queryMgr.FindAll<IssueAddress>(selectEqIssueAddressStatement, new object[] { selectedValue, selectedValue });
// if (issueAddressList.Count == 0)
// {
// IssueAddress ia = new IssueAddress();
// ia.Code = selectedValue;
// issueAddressList.Add(ia);
// return PartialView(new SelectList(issueAddressList, "Code", "CodeDescription", selectedValue));
// }
// }
// return PartialView(new SelectList(issueAddressList, "Code", "CodeDescription", selectedValue));
//}
//public ActionResult _IssueAddressAjaxLoading(string text)
//{
// //AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.IssueAddressFilterMode), true);
// IList<IssueAddress> issueAddressList = new List<IssueAddress>();
// //if (fileterMode == AutoCompleteFilterMode.Contains)
// //{
// // issueAddressList = queryMgr.FindAll<IssueAddress>(selectLikeIssueAddressStatement, new object[] { "%" + text + "%", "%" + text + "%" });
// //}
// //else
// //{
// issueAddressList = queryMgr.FindAll<IssueAddress>(selectLikeIssueAddressStatement, new object[] { text + "%", text + "%" });
// //}
// return new JsonResult { Data = new SelectList(issueAddressList, "Code", "CodeDescription") };
//}
//#endregion
//#region LocationArea
//public ActionResult _LocationAreaDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, string LocationCode)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<LocationArea> locationAreaList = queryMgr.FindAll<LocationArea>("from LocationArea as i where i.IsActive = ? and i.Location=?",
// new object[] { true, LocationCode });
// if (locationAreaList == null)
// {
// locationAreaList = new List<LocationArea>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// LocationArea blankItem = new LocationArea();
// blankItem.Code = blankOptionValue;
// blankItem.Name = blankOptionDescription;
// locationAreaList.Insert(0, blankItem);
// }
// return PartialView(new SelectList(locationAreaList, "Code", "Name", selectedValue));
//}
//#endregion
//#region LocationBin
//public ActionResult _LocationBinDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<LocationBin> locationBinList = queryMgr.FindAll<LocationBin>("from LocationBin as l where l.IsActive = ?", true);
// if (locationBinList == null)
// {
// locationBinList = new List<LocationBin>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// LocationBin blankItem = new LocationBin();
// blankItem.Code = blankOptionValue;
// blankItem.Name = blankOptionDescription;
// locationBinList.Insert(0, blankItem);
// }
// return PartialView(new SelectList(locationBinList, "Code", "Name", selectedValue));
//}
//public ActionResult _LocationBinComboBox(string controlName, string controlId, string selectedValue, bool? enable, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.Enable = enable;
// ViewBag.IsChange = isChange;
// ViewBag.ControlId = controlId;
// ViewBag.SelectedValue = selectedValue;
// IList<LocationBin> locationBinList = queryMgr.FindAll<LocationBin>("from LocationBin as l where l.IsActive=?", true);
// if (locationBinList == null)
// {
// locationBinList = new List<LocationBin>();
// }
// return PartialView(new SelectList(locationBinList, "Code", "CodeName", selectedValue));
//}
//public ActionResult _LocationBinAjaxLoading(string text)
//{
// AutoCompleteFilterMode fileterMode = AutoCompleteFilterMode.StartsWith;
// IList<LocationBin> locationBinList = new List<LocationBin>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// locationBinList = queryMgr.FindAll<LocationBin>("from LocationBin as l where l.Code like ? and l.IsActive = ?", new object[] { "%" + text + "%", true });
// }
// else
// {
// locationBinList = queryMgr.FindAll<LocationBin>("from LocationBin as l where l.Code like ? and l.IsActive = ?", new object[] { text + "%", true });
// }
// return new JsonResult { Data = new SelectList(locationBinList, "Code", "Name") };
//}
//#endregion
//#region ItemPackage
//public ActionResult _ItemPackageDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, string itemCode)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<ItemPackage> itemPackageList = queryMgr.FindAll<ItemPackage>("from ItemPackage as i where i.Item=?", itemCode);
// if (itemPackageList == null)
// {
// itemPackageList = new List<ItemPackage>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// ItemPackage blankItemPackage = new ItemPackage();
// blankItemPackage.UnitCount = Convert.ToDecimal(blankOptionValue);
// blankItemPackage.UnitCount = Convert.ToDecimal(blankOptionDescription);
// itemPackageList.Insert(0, blankItemPackage);
// }
// return PartialView(new SelectList(itemPackageList, "UnitCount", "UnitCount", selectedValue));
//}
//#endregion
//#region Container
//public ActionResult _ContainerDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// //ViewBag.SelectedValue = selectedValue;
// IList<Container> containerList = queryMgr.FindAll<Container>("from Container as c where c.IsActive=?", true);
// if (containerList == null)
// {
// containerList = new List<Container>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Container blankContainer = new Container();
// blankContainer.Code = blankOptionValue;
// blankContainer.Description = blankOptionDescription;
// containerList.Insert(0, blankContainer);
// }
// return PartialView(new SelectList(containerList, "Code", "Description", selectedValue));
//}
//#endregion
//#region ItemPackage ComboBox
//public ActionResult _ItemPackageComboBox(string controlName, string controlId, string selectedValue, string item)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// IList<ItemPackage> itemPackageList = new List<ItemPackage>();
// if (!string.IsNullOrEmpty(item))
// {
// itemPackageList = queryMgr.FindAll<ItemPackage>("select i from ItemPackage as i where i.Item=?", item);
// }
// else if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// itemPackageList = queryMgr.FindAll<ItemPackage>(selectEqItemPackageStatement, selectedValue);
// }
// //ViewBag.UnitCountFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.UnitCountFilterMode);
// //ViewBag.UnitCountFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.UnitCountMinimumChars));
// if (!string.IsNullOrEmpty(selectedValue))
// {
// if (itemPackageList.Count < 1)
// {
// ItemPackage itemPackage = new ItemPackage();
// itemPackage.Item = item;
// itemPackage.IsDefault = false;
// itemPackage.UnitCount = decimal.Parse(selectedValue);
// itemPackage.Description = selectedValue;
// itemPackageList.Add(itemPackage);
// }
// }
// return PartialView(new SelectList(itemPackageList, "UnitCount", "UnitCount", selectedValue));
//}
//public ActionResult _ItemPackageAjaxLoading(string text, string item)
//{
// //AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.UnitCountFilterMode), true);
// IList<ItemPackage> itemPackageList = new List<ItemPackage>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// if (item == null)
// {
// itemPackageList = queryMgr.FindAll<ItemPackage>(selectLikeItemPackageStatement, new object[] { "", "%" + text + "%" });
// }
// else
// {
// itemPackageList = queryMgr.FindAll<ItemPackage>(selectLikeItemPackageStatement, new object[] { item, "%" + text + "%" });
// }
// }
// else
// {
// if (item == null)
// {
// itemPackageList = queryMgr.FindAll<ItemPackage>(selectLikeItemPackageStatement, new object[] { "", text + "%" });
// }
// else
// {
// itemPackageList = queryMgr.FindAll<ItemPackage>(selectLikeItemPackageStatement, new object[] { item, text + "%" });
// }
// }
// return new JsonResult { Data = new SelectList(itemPackageList, "UnitCount", "UnitCount") };
//}
//#endregion
//#region Flow lqy
///// <summary>
///// 获取Flow
///// </summary>
///// <param name="controlName"></param>
///// <param name="selectedValue"></param>
///// <param name="includeBlankOption"></param>
///// <param name="flowTypes">多个flowtype用'|'分割</param>
///// <returns></returns>
//public ActionResult _FlowDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string flowTypes)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// IList<FlowMaster> flowList = new List<FlowMaster>();
// if (string.IsNullOrWhiteSpace(flowTypes))
// {
// flowList = queryMgr.FindAll<FlowMaster>
// (" from FlowMaster as f where f.IsActive = ? ", true);
// }
// else
// {
// DetachedCriteria criteria = DetachedCriteria.For<FlowMaster>();
// criteria.Add(Expression.Eq("IsActive", true));
// criteria.Add(Expression.In("Type", flowTypes.Split('|')));
// flowList = queryMgr.FindAll<FlowMaster>(criteria);
// }
// if (flowList == null)
// {
// flowList = new List<FlowMaster>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// FlowMaster flowMaster = new FlowMaster();
// flowList.Insert(0, flowMaster);
// }
// return PartialView(new SelectList(flowList, "Code", "Description", selectedValue));
//}
//#region Flow
//public ActionResult _FlowComboBox(string controlName, string controlId, string selectedValue, int? type, string onChangeFunc, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Type = type;
// ViewBag.OnChangeFunc = onChangeFunc;
// ViewBag.IsChange = isChange;
// IList<FlowMaster> flowList = new List<FlowMaster>();
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// flowList = queryMgr.FindAll<FlowMaster>(selectEqFlowStatement, new object[] { selectedValue.Trim() });
// }
// ViewBag.FlowFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.FlowFilterMode);
// ViewBag.FlowFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.FlowFilterMinimumChars));
// return PartialView(new SelectList(flowList, "Code", "Description"));
//}
//public ActionResult _FlowAjaxLoading(string text, int? type)
//{
// AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.FlowFilterMode), true);
// IList<FlowMaster> flowList = new List<FlowMaster>();
// string selectLikeFlowStatement = null;
// object[] paramContainList = new object[] { };
// object[] paramList = new object[] { };
// if (type == null)
// {
// selectLikeFlowStatement = "from FlowMaster as f where f.Code like ? ";
// paramContainList = new object[] { "%" + text + "%" };
// paramList = new object[] { text + "%" };
// }
// else if ((int)type == (int)com.Sconit.CodeMaster.OrderType.Procurement)
// {
// selectLikeFlowStatement = "from FlowMaster as f where f.Code like ? and f.Type in (?,?,?,?,?) ";
// paramContainList = new object[] { "%" + text + "%", (int)com.Sconit.CodeMaster.OrderType.CustomerGoods, (int)com.Sconit.CodeMaster.OrderType.Procurement, (int)com.Sconit.CodeMaster.OrderType.SubContract, (int)com.Sconit.CodeMaster.OrderType.Transfer, (int)com.Sconit.CodeMaster.OrderType.SubContractTransfer };
// paramList = new object[] { text + "%", (int)com.Sconit.CodeMaster.OrderType.CustomerGoods, (int)com.Sconit.CodeMaster.OrderType.Procurement, (int)com.Sconit.CodeMaster.OrderType.SubContract, (int)com.Sconit.CodeMaster.OrderType.Transfer, (int)com.Sconit.CodeMaster.OrderType.SubContractTransfer };
// }
// else if ((int)type == (int)com.Sconit.CodeMaster.OrderType.Distribution)
// {
// selectLikeFlowStatement = "from FlowMaster as f where f.Code like ? and f.Type in (?,?,?) ";
// paramContainList = new object[] { "%" + text + "%", (int)com.Sconit.CodeMaster.OrderType.Distribution, (int)com.Sconit.CodeMaster.OrderType.Transfer, (int)com.Sconit.CodeMaster.OrderType.SubContractTransfer };
// paramList = new object[] { text + "%", (int)com.Sconit.CodeMaster.OrderType.Distribution, (int)com.Sconit.CodeMaster.OrderType.Transfer, (int)com.Sconit.CodeMaster.OrderType.SubContractTransfer };
// }
// else if ((int)type == (int)com.Sconit.CodeMaster.OrderType.Production)
// {
// selectLikeFlowStatement = "from FlowMaster as f where f.Code like ? and f.Type in (?) ";
// paramContainList = new object[] { "%" + text + "%", (int)com.Sconit.CodeMaster.OrderType.Production };
// paramList = new object[] { text + "%", (int)com.Sconit.CodeMaster.OrderType.Production };
// }
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// flowList = queryMgr.FindAll<FlowMaster>(selectLikeFlowStatement, paramContainList);
// }
// else
// {
// flowList = queryMgr.FindAll<FlowMaster>(selectLikeFlowStatement, paramList);
// }
// return new JsonResult { Data = new SelectList(flowList, "Code", "CodeDescription") };
//}
//#endregion
//#endregion
//#region Supplier Combox
public ActionResult _SupplierComboBox(string controlName, string controlId, string selectedValue, bool? coupled, bool? enable)
{
ViewBag.ControlName = controlName;
ViewBag.ControlId = controlId;
ViewBag.Coupled = coupled;
ViewBag.Enable = enable;
IList<Supplier> supplierList = new List<Supplier>();
if (selectedValue != null && selectedValue.Trim() != string.Empty)
{
supplierList = queryMgr.FindAll<Supplier>(selectEqSupplierStatement, new object[] { selectedValue, true });
}
ViewBag.ItemFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode);
ViewBag.ItemFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMinimumChars));
return PartialView(new SelectList(supplierList, "Code", "CodeDescription", selectedValue));
}
public ActionResult _SupplierAjaxLoading(string text)
{
AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode), true);
IList<Supplier> supplierList = new List<Supplier>();
if (fileterMode == AutoCompleteFilterMode.Contains)
{
supplierList = queryMgr.FindAll<Supplier>(selectLikeSupplierStatement, new object[] { "%" + text + "%", true });
}
else
{
supplierList = queryMgr.FindAll<Supplier>(selectLikeSupplierStatement, new object[] { text + "%", true });
}
return new JsonResult { Data = new SelectList(supplierList, "Code", "CodeDescription") };
}
//#endregion
//#region Customer Combox
//public ActionResult _CustomerComboBox(string controlName, string controlId, string selectedValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Enable = enable;
// IList<Customer> customerList = new List<Customer>();
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// customerList = queryMgr.FindAll<Customer>(selectEqCustomerStatement, new object[] { selectedValue, true });
// }
// ViewBag.ItemFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode);
// ViewBag.ItemFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMinimumChars));
// return PartialView(new SelectList(customerList, "Code", "CodeDescription", selectedValue));
//}
//public ActionResult _CustomerAjaxLoading(string text)
//{
// AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode), true);
// IList<Customer> customerList = new List<Customer>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// customerList = queryMgr.FindAll<Customer>(selectLikeCustomerStatement, new object[] { "%" + text + "%", true });
// }
// else
// {
// customerList = queryMgr.FindAll<Customer>(selectLikeCustomerStatement, new object[] { text + "%", true });
// }
// return new JsonResult { Data = new SelectList(customerList, "Code", "CodeDescription") };
//}
//#endregion
//#region Region Combox
//public ActionResult _RegionComboBox(string controlName, string controlId, string selectedValue, bool? coupled)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Coupled = coupled;
// IList<Region> regionList = new List<Region>();
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// regionList = queryMgr.FindAll<Region>(selectEqRegionStatement, new object[] { selectedValue, true });
// }
// //ViewBag.ItemFilterMode = base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode);
// //ViewBag.ItemFilterMinimumChars = int.Parse(base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMinimumChars));
// //if (itemList.Count > 0)
// //{
// return PartialView(new SelectList(regionList, "Code", "CodeDescription", selectedValue));
// //}
// //else
// //{
// // Item item = new Item();
// // item.Code = selectedValue;
// // item.Description = selectedValue;
// // itemList.Add(item);
// // return PartialView(new SelectList(itemList, "Code", "Description"));
// //}
//}
//public ActionResult _RegionAjaxLoading(string text)
//{
// AutoCompleteFilterMode fileterMode = (AutoCompleteFilterMode)Enum.Parse(typeof(AutoCompleteFilterMode), base.systemMgr.GetEntityPreferenceValue(EntityPreference.CodeEnum.ItemFilterMode), true);
// IList<Region> regionList = new List<Region>();
// if (fileterMode == AutoCompleteFilterMode.Contains)
// {
// regionList = queryMgr.FindAll<Region>(selectLikeRegionStatement, new object[] { "%" + text + "%", true });
// }
// else
// {
// regionList = queryMgr.FindAll<Region>(selectLikeRegionStatement, new object[] { text + "%", true });
// }
// return new JsonResult { Data = new SelectList(regionList, "Code", "CodeDescription") };
//}
//#endregion
//#region OrderMaster PartyFrom
//public ActionResult _OrderMasterPartyFromDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, int? orderType)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Enable = enable;
// IList<Supplier> supplierList = queryMgr.FindAll<Supplier>("from Supplier as s where s.IsActive = ?", true);
// IList<Customer> customerList = queryMgr.FindAll<Customer>("from Customer as c where c.IsActive = ?", true);
// IList<Region> regionList = queryMgr.FindAll<Region>("from Region as r where r.IsActive = ?", true);
// List<Party> partyList = new List<Party>();
// if (orderType == (int)com.Sconit.CodeMaster.OrderType.Procurement)
// {
// partyList.AddRange(supplierList);
// partyList.AddRange(customerList);
// partyList.AddRange(regionList);
// }
// if (orderType == (int)com.Sconit.CodeMaster.OrderType.Distribution)
// {
// partyList.AddRange(regionList);
// }
// if (orderType == (int)com.Sconit.CodeMaster.OrderType.Production)
// {
// partyList.AddRange(regionList);
// }
// else
// {
// partyList.AddRange(supplierList);
// partyList.AddRange(customerList);
// partyList.AddRange(regionList);
// }
// if (partyList == null)
// {
// partyList = new List<Party>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Party blankParty = new Party();
// partyList.Insert(0, blankParty);
// }
// return PartialView(new SelectList(partyList, "Code", "Name", selectedValue));
//}
//#endregion
//#region OrderMaster PartyFrom
//public ActionResult _OrderMasterPartyToDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, bool? enable, int? orderType)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Enable = enable;
// IList<Supplier> supplierList = queryMgr.FindAll<Supplier>("from Supplier as s where s.IsActive = ?", true);
// IList<Customer> customerList = queryMgr.FindAll<Customer>("from Customer as c where c.IsActive = ?", true);
// IList<Region> regionList = queryMgr.FindAll<Region>("from Region as r where r.IsActive = ?", true);
// List<Party> partyList = new List<Party>();
// if (orderType == (int)com.Sconit.CodeMaster.OrderType.Procurement)
// {
// partyList.AddRange(regionList);
// }
// if (orderType == (int)com.Sconit.CodeMaster.OrderType.Distribution)
// {
// partyList.AddRange(regionList);
// partyList.AddRange(customerList);
// }
// if (orderType == (int)com.Sconit.CodeMaster.OrderType.Production)
// {
// partyList.AddRange(regionList);
// }
// else
// {
// partyList.AddRange(supplierList);
// partyList.AddRange(customerList);
// partyList.AddRange(regionList);
// }
// if (partyList == null)
// {
// partyList = new List<Party>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Party blankParty = new Party();
// partyList.Insert(0, blankParty);
// }
// return PartialView(new SelectList(partyList, "Code", "Name", selectedValue));
//}
//#endregion
//#region Currency
//public ActionResult _CurrencyDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? enable)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.Enable = enable;
// IList<Currency> currencyList = queryMgr.FindAll<Currency>("from Currency as c");
// if (currencyList == null)
// {
// currencyList = new List<Currency>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Currency blankCurrency = new Currency();
// blankCurrency.Code = blankOptionValue;
// blankCurrency.Name = blankOptionDescription;
// currencyList.Insert(0, blankCurrency);
// }
// return PartialView(new SelectList(currencyList, "Code", "Name", selectedValue));
//}
//#endregion
//#region Address
//public ActionResult _AddressDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, string addressType)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// IList<Address> addressList = queryMgr.FindAll<Address>("from Address as a where a.Type=?", addressType);
// if (addressList == null)
// {
// addressList = new List<Address>();
// }
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// Address blankAddress = new Address();
// blankAddress.Code = blankOptionValue;
// blankAddress.AddressContent = blankOptionDescription;
// addressList.Insert(0, blankAddress);
// }
// return PartialView(new SelectList(addressList, "Code", "AddressContent", selectedValue));
//}
//#endregion
//#region Address
//public ActionResult _ProductLineFacilityDropDownList(string controlName, string controlId, string selectedValue, bool? includeBlankOption, string blankOptionDescription, string blankOptionValue, bool? isChange, string dataBindFunc)
//{
// ViewBag.ControlName = controlName;
// ViewBag.ControlId = controlId;
// ViewBag.IsChange = isChange;
// ViewBag.DataBindFunc = dataBindFunc;
// IList<ProductLineFacility> productLineFacilityList = new List<ProductLineFacility>();
// if (includeBlankOption.HasValue && includeBlankOption.Value)
// {
// ProductLineFacility productLineFacility = new ProductLineFacility();
// productLineFacility.Code = blankOptionValue;
// productLineFacilityList.Insert(0, productLineFacility);
// }
// return PartialView(new SelectList(productLineFacilityList, "Code", "Code", selectedValue));
//}
//#endregion
//#region Order
//public ActionResult _OrderComboBox(string controlName, string selectedValue, int? orderType, bool? canFeed)
//{
// ViewBag.ControlName = controlName;
// ViewBag.OrderType = orderType;
// ViewBag.CanFeed = canFeed;
// IList<OrderMaster> orderList = new List<OrderMaster>();
// IList<object> para = new List<object>();
// string hql = "from OrderMaster as o where o.OrderNo = ?";;
// if (!string.IsNullOrEmpty(selectedValue))
// {
// para.Add(selectedValue);
// orderList = queryMgr.FindAll<OrderMaster>(hql, para.ToArray());
// }
// return PartialView(new SelectList(orderList, "OrderNo", "OrderNo"));
//}
//public ActionResult _OrderAjaxLoading(string text, int? orderType, bool? canFeed)
//{
// IList<OrderMaster> orderList = new List<OrderMaster>();
// string hql = "from OrderMaster as o where 1 = 1 ";
// IList<object> para = new List<object>();
// if (string.IsNullOrEmpty(text))
// {
// hql += " and o.OrderNo like ?";
// para.Add(text + "%");
// }
// if (orderType != null)
// {
// hql += " and o.Type = ?";
// para.Add(orderType.Value);
// }
// if (canFeed != null)
// {
// if (canFeed.Value)
// {
// hql += " and o.Status in (?,?)";
// para.Add((int)com.Sconit.CodeMaster.OrderStatus.InProcess);
// para.Add((int)com.Sconit.CodeMaster.OrderStatus.Complete);
// }
// else
// {
// hql += " and o.Status not in (?,?)";
// para.Add((int)com.Sconit.CodeMaster.OrderStatus.InProcess);
// para.Add((int)com.Sconit.CodeMaster.OrderStatus.Complete);
// }
// }
// orderList = queryMgr.FindAll<OrderMaster>(hql, para.ToArray());
// return new JsonResult { Data = new SelectList(orderList, "OrderNo", "OrderNo") };
//}
//#endregion
//#region OrderDetailTrace
//public ActionResult _TraceCodeComboBox(string controlName, string selectedValue, bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.IsChange = isChange;
// IList<OrderDetailTrace> orderDetailTraceList = new List<OrderDetailTrace>();
// if (selectedValue != null && selectedValue.Trim() != string.Empty)
// {
// orderDetailTraceList = queryMgr.FindAll<OrderDetailTrace>(selectEqTraceCodeStatement, new object[] { selectedValue.Trim() });
// }
// return PartialView(new SelectList(orderDetailTraceList, "Id", "TraceCode"));
//}
//public ActionResult _TraceCodeAjaxLoading(string text)
//{
// IList<OrderDetailTrace> orderDetailTraceList = new List<OrderDetailTrace>();
// string selectLikeTraceCodeStatement = null;
// object[] paramList = new object[] { };
// selectLikeTraceCodeStatement = "from OrderDetailTrace as o where o.TraceCode like ? ";
// paramList = new object[] { text + "%" };
// //追溯码只能like +%
// orderDetailTraceList = queryMgr.FindAll<OrderDetailTrace>(selectLikeTraceCodeStatement, paramList);
// return new JsonResult { Data = new SelectList(orderDetailTraceList, "Id", "TraceCode") };
//}
//#endregion
//#region RejectOrder
//public ActionResult _RejectComboBox(string controlName, string selectedValue, int? status,bool? isChange)
//{
// ViewBag.ControlName = controlName;
// ViewBag.Status = status;
// ViewBag.IsChange = isChange;
// IList<RejectMaster> rejectList = new List<RejectMaster>();
// IList<object> para = new List<object>();
// string hql = "from RejectMaster as r where r.RejectNo = ?"; ;
// if (!string.IsNullOrEmpty(selectedValue))
// {
// para.Add(selectedValue);
// rejectList = queryMgr.FindAll<RejectMaster>(hql, para.ToArray());
// }
// return PartialView(new SelectList(rejectList, "RejectNo", "RejectNo"));
//}
//public ActionResult _RejectAjaxLoading(string text, int? status)
//{
// IList<RejectMaster> rejectList = new List<RejectMaster>();
// string hql = "from RejectMaster as r where 1 = 1 ";
// IList<object> para = new List<object>();
// if (!string.IsNullOrEmpty(text))
// {
// hql += " and r.RejectNo like ?";
// para.Add(text + "%");
// }
// if (status != null)
// {
// hql += " and r.Status = ?";
// para.Add(status.Value);
// }
// rejectList = queryMgr.FindAll<RejectMaster>(hql, para.ToArray());
// return new JsonResult { Data = new SelectList(rejectList, "RejectNo", "RejectNo") };
//}
//#endregion
//#region 联动
//public ActionResult _AjaxLoadingIssueNo(string issueType)
//{
// IList<IssueNo> issueNoList = new List<IssueNo>();
// if (issueType == null)
// {
// issueNoList = this.genericMgr.FindAll<IssueNo>("from IssueNo i ");
// }
// else
// {
// issueNoList = this.genericMgr.FindAll<IssueNo>("select i from IssueNo i join i.IssueType it where it.Code =? and it.IsActive=?", new object[] { issueType, true });
// }
// IssueNo blankIssueNo = new IssueNo();
// blankIssueNo.Code = string.Empty;
// blankIssueNo.Description = string.Empty;
// issueNoList.Insert(0, blankIssueNo);
// return new JsonResult
// {
// Data = new SelectList(issueNoList, "Code", "Description", "")
// };
//}
//public ActionResult _AjaxLoadingLocation(string party, string RegionValue)
//{
// IList<Location> locationList = new List<Location>();
// if (party == null)
// {
// locationList = this.genericMgr.FindAll<Location>("from Location l where l.Region is null and l.IsActive=?", true);
// }
// else
// {
// locationList = this.genericMgr.FindAll<Location>("from Location l where l.Region=? and l.IsActive=?", new object[] { party, true });
// }
// Location blankLocation = new Location();
// blankLocation.Code = string.Empty;
// blankLocation.Name = string.Empty;
// locationList.Insert(0, blankLocation);
// if (string.IsNullOrEmpty(RegionValue))
// {
// return new JsonResult
// {
// Data = new SelectList(locationList, "Code", "CodeName", "")
// };
// }
// else
// {
// return new JsonResult
// {
// Data = new SelectList(locationList, "Code", "Name", RegionValue)
// };
// }
//}
//public ActionResult _AjaxLoadingLocationFrom(string partyFrom, string regionValue)
//{
// return _AjaxLoadingLocation(partyFrom, regionValue);
//}
//public ActionResult _AjaxLoadingLocationTo(string partyTo)
//{
// return _AjaxLoadingLocation(partyTo, "");
//}
//public ActionResult _AjaxLoadingLocationBin(string party, string RegionValue)
//{
// IList<LocationBin> locationBinList = new List<LocationBin>();
// if (party == null)
// {
// locationBinList = this.genericMgr.FindAll<LocationBin>("from locationBin l where l.Region is null and l.IsActive=?", true);
// }
// else
// {
// locationBinList = this.genericMgr.FindAll<LocationBin>("from locationBin l where l.Region=? and l.IsActive=?", new object[] { party, true });
// }
// LocationBin blankLocation = new LocationBin();
// blankLocation.Code = string.Empty;
// blankLocation.Name = string.Empty;
// locationBinList.Insert(0, blankLocation);
// if (string.IsNullOrEmpty(RegionValue))
// {
// return new JsonResult
// {
// Data = new SelectList(locationBinList, "Code", "CodeName", "")
// };
// }
// else
// {
// return new JsonResult
// {
// Data = new SelectList(locationBinList, "Code", "Name", RegionValue)
// };
// }
//}
//public ActionResult _AjaxLoadingLocationBinFrom(string partyFrom, string regionValue)
//{
// return _AjaxLoadingLocationBin(partyFrom, regionValue);
//}
//public ActionResult _AjaxLoadingLocationBinTo(string partyTo)
//{
// return _AjaxLoadingLocationBin(partyTo, "");
//}
//public ActionResult _AjaxLoadingBillAddress(string party)
//{
// IList<Address> addressList = new List<Address>();
// addressList = this.genericMgr.FindAll<Address>(supplierAddress, new object[] { party, 1 });
// Address blankAddress = new Address();
// blankAddress.Code = string.Empty;
// blankAddress.AddressContent = string.Empty;
// addressList.Insert(0, blankAddress);
// return new JsonResult
// {
// Data = new SelectList(addressList, "Code", "AddressContent", "")
// };
//}
//public ActionResult _AjaxLoadingShipFrom(string partyFrom)
//{
// return _AjaxLoadingShipAdress(partyFrom);
//}
//public ActionResult _AjaxLoadingShipTo(string partyTo)
//{
// return _AjaxLoadingShipAdress(partyTo);
//}
//public ActionResult _AjaxLoadingShipAdress(string party)
//{
// IList<Address> addressList = new List<Address>();
// addressList = this.genericMgr.FindAll<Address>(shipToAddress, new object[] { party, 0 });
// Address blankAddress = new Address();
// blankAddress.Code = string.Empty;
// blankAddress.AddressContent = string.Empty;
// addressList.Insert(0, blankAddress);
// return new JsonResult
// {
// Data = new SelectList(addressList, "Code", "AddressContent", "")
// };
//}
//public ActionResult _AjaxLoadingProductLineFacility(string productLine)
//{
// IList<ProductLineFacility> facilityList = this.genericMgr.FindAll<ProductLineFacility>(selectProductLineFacilityStatement, productLine);
// ProductLineFacility facility = new ProductLineFacility();
// facility.Code = string.Empty;
// facilityList.Insert(0, facility);
// return new JsonResult
// {
// Data = new SelectList(facilityList, "Code", "Code", "")
// };
//}
//public ActionResult _AjaxLoadingPriceList(string party)
//{
// IList<PriceListMaster> priceListMasterList = new List<PriceListMaster>();
// priceListMasterList = this.genericMgr.FindAll<PriceListMaster>("from PriceListMaster p where p.Party=? and p.IsActive=?", new object[] { party, true });
// PriceListMaster blankPriceListMaster = new PriceListMaster();
// blankPriceListMaster.Code = string.Empty;
// blankPriceListMaster.Code = string.Empty;
// priceListMasterList.Insert(0, blankPriceListMaster);
// return new JsonResult
// {
// Data = new SelectList(priceListMasterList, "Code", "Code", "")
// };
//}
public ActionResult _AjaxLoadingSupplier(string text, bool checkPermission)
{
string hql = "from Supplier as s where s.Code like ? and s.IsActive = ?";
IList<object> paraList = new List<object>();
paraList.Add(text + "%");
paraList.Add(true);
User user = SecurityContextHolder.Get();
if (user.Code.Trim().ToLower() != "su" && checkPermission)
{
hql += " and exists (select 1 from UserPermissionView as u where u.UserId =" + user.Id + "and u.PermissionCategoryType =" + (int)com.Sconit.CodeMaster.PermissionCategoryType.Supplier + " and u.PermissionCode = s.Code)";
}
IList<Supplier> supplierList = queryMgr.FindAll<Supplier>(hql, paraList.ToArray(), firstRow, maxRow);
return new JsonResult { Data = new SelectList(supplierList, "Code", "CodeDescription", text) };
}
//public ActionResult _AjaxLoadingCustomer()
//{
// IList<Customer> customerList = queryMgr.FindAll<Customer>("from Customer as c where c.IsActive = ?", true);
// return new JsonResult
// {
// Data = new SelectList(customerList, "Code", "Name")
// };
//}
//public ActionResult _AjaxLoadingRegion()
//{
// IList<Region> regionList = queryMgr.FindAll<Region>("from Region as r where r.IsActive = ?", true);
// return new JsonResult
// {
// Data = new SelectList(regionList, "Code", "Name")
// };
//}
//public ActionResult _AjaxLoadingIssueType()
//{
// IList<IssueType> issueTypeList = queryMgr.FindAll<IssueType>("from IssueType as it where it.IsActive = ?", true);
// return new JsonResult
// {
// Data = new SelectList(issueTypeList, "Code", "Description")
// };
//}
//#endregion
//#endregion
//#region private methods
//#endregion
public ActionResult _StatusDropDownList(int? selectedValue)
{
List<Status> statusList = new List<Status>();
Status status0 = new Status();
status0.Code = 0;
status0.Name = "创建";
statusList.Add(status0);
Status status1 = new Status();
status1.Code = 1;
status1.Name = "成功";
statusList.Add(status1);
Status status2 = new Status();
status2.Code = 2;
status2.Name = "失败";
statusList.Add(status2);
selectedValue = selectedValue.HasValue ? selectedValue.Value : 2;
return PartialView(new SelectList(statusList, "Code", "Name", selectedValue));
}
}
class Status
{
public int Code { get; set; }
public string Name { get; set; }
}
}
|
using System.Collections.Generic;
namespace PFM.Products.Interfaces
{
public interface IProductManager
{
IEnumerable<IProduct> Get();
IProduct Get(string id);
void Insert(IProduct product);
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ServerApp.Data;
using ServerApp.Models;
using Microsoft.AspNetCore.Authorization;
namespace ServerApp.Controllers{
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class QuestionsController:ControllerBase
{
private readonly SocialContext _context;
public QuestionsController(SocialContext context){
_context=context;
}
[HttpGet]
public async Task<IActionResult> GetQuestions(){
var questions=await _context.question.ToListAsync();
return Ok(questions);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetQuestion(int id){
var q=await _context.question.FirstOrDefaultAsync(i=>i.QuestionId==id);
if(q==null)
{
return NotFound();
}
return Ok(q);
}
[HttpPost]
public async Task<IActionResult> CreateQuestions(Questions entity){
_context.question.Add(entity);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetQuestion),new{id=entity.QuestionId},entity);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateQuestions(int id,Questions entity)
{
if(id!=entity.QuestionId)
{
return BadRequest();
}
var questions=await _context.question.FindAsync(id);
if(questions==null){
return NotFound();
}
questions.Question=entity.Question;
questions.Answer=entity.Answer;
questions.AnswerLength=entity.AnswerLength;
questions.Level=entity.Level;
questions.ipucu=entity.ipucu;
questions.Chapter=entity.Chapter;
questions.chapter_image=entity.chapter_image;
questions.level_image=entity.level_image;
questions.levelId=entity.levelId;
try{
await _context.SaveChangesAsync();
}catch{
return NotFound();
}
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteQuestion(int id){
var questions=await _context.question.FindAsync(id);
if(questions==null){
return NotFound();
}
_context.question.Remove(questions);
await _context.SaveChangesAsync();
return NoContent();
}
}
}
|
namespace Masuit.LuceneEFCore.SearchEngine.Interfaces
{
/// <summary>
/// 结果项
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IScoredSearchResult<T>
{
/// <summary>
/// 匹配度
/// </summary>
float Score { get; set; }
/// <summary>
/// 实体
/// </summary>
T Entity { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SolidPrinciples.OpenClose
{
class Triangle : IArea
{
public double Trianglebase { get; set; }
public double Triangleheight { get; set; }
public double Area()
{
var area = (Trianglebase * Triangleheight) / 2;
return area;
}
}
}
|
using AppTimedoc.Views;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace AppTimedoc.Helpers
{
public class MainTabbedPage : TabbedPage
{
public MainTabbedPage()
{
var playPage = new Time() { Title = "", Icon = null };
var workPage = new NavigationPage(new Work() { Title = "Leistungserfassung", Icon = null });
var settingsPage = new AboutPage() { Title = "", Icon = null };
var aboutPage = new Login() { Title = "", Icon = null };
switch (Device.RuntimePlatform)
{
case Device.iOS:
playPage.Icon = "ic_access_time.png";
workPage.Icon = "ic_list.png";
settingsPage.Icon = "ic_error_outline.png";
aboutPage.Icon = "ic_accessibility.png";
break;
case Device.Android:
playPage.Title = string.Empty;
playPage.Icon = "ic_access_time_black_24dp.png";
workPage.Title = string.Empty;
workPage.Icon = "ic_list_black_24dp.png";
settingsPage.Title = string.Empty;
settingsPage.Icon = "ic_error_outline_black_24dp.png";
aboutPage.Title = string.Empty;
aboutPage.Icon = "ic_accessibility_black_24dp.png";
break;
default:
break;
}
Children.Add(playPage);
Children.Add(workPage);
Children.Add(settingsPage);
Children.Add(aboutPage);
}
public void SwitchTab(int index)
{
CurrentPage = this.Children[index];
}
}
}
|
using UnityEngine;
using System.Collections;
public class CameraControl : MonoBehaviour {
public Transform target; //variabe which copies the player position
public float speed; //this is the speed of the camera multiplier (how fast it moves)
// Update is called once per frame
void Update () {
// get the cameras position, then as the player moves transform camera position to follow player
transform.position = Vector3.Lerp (transform.position, new Vector3 (target.transform.position.x, target.transform.position.y +1f, transform.position.z), Time.deltaTime * speed);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeneralResources.CursoAlgoritmoEstruturaDeDados.Sorting
{
public class BubbleSort
{
public static void Sort(int[] m)
{
bool hasChanges = false;
for (int i = m.Length - 1; i >= 0; i--)
{
for (int j = 0; j < i; j++)
{
if (m[j] > m[j + 1])
{
SortUtils.Swap(m, j, j + 1);
hasChanges = true;
}
}
if (hasChanges == false) break;
hasChanges = false;
}
}
[Theory]
[InlineData(new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 2, 3, 4, 5 })]
[InlineData(new int[] { 3, 1, 6, 4, 2 }, new int[] { 1, 2, 3, 4, 6 })]
public void Validate(int[] input, int[] expected)
{
//Arrange
//Act
BubbleSort.Sort(input);
//Assert
Assert.Equal(expected, input);
}
}
}
|
using PaperPlane.API.Global;
using PaperPlane.API.MemoryManager;
using PaperPlane.API.ProtocolSchema.Base;
using PaperPlane.API.ProtocolSchema.DataTypes.Auth;
using PaperPlane.API.ProtocolSchema.Methods.Auth;
using PaperPlane.API.ProtocolSchema.Parser;
using PaperPlane.API.ProtocolStack.Security.Messaging;
using PaperPlane.API.ProtocolStack.Transport;
using PaperPlane.API.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using static PaperPlane.API.Log.GlobalLogger;
using BI = System.Numerics.BigInteger;
namespace PaperPlane.API.ProtocolStack.Security.Auth
{
internal class AuthStateMachine : IDisposable
{
private enum AuthState
{
ReqPQ,
ResPQ_ReqDH,
ResDH_SetDH,
DHGenCheck
}
private readonly object _lock = new object();
private Dictionary<AuthState, AuthState> _stateMap = new Dictionary<AuthState, AuthState>
{
[AuthState.ReqPQ] = AuthState.ResPQ_ReqDH,
[AuthState.ResPQ_ReqDH] = AuthState.ResDH_SetDH,
[AuthState.ResDH_SetDH] = AuthState.DHGenCheck
};
private AuthState _endState = AuthState.DHGenCheck;
private readonly ConnectionPool _transport;
private AuthState currentState;
private TaskCompletionSource<TLAuth> authKeyTask;
private byte[] _nonceClient;
private byte[] _nonceServer;
private byte[] _newNonce;
private byte[] _authKey;
private long _serverSalt;
public AuthStateMachine(ConnectionPool transport)
{
_transport = transport;
_transport.NewPacket += NewPacket;
}
private void NewPacket(Memory<byte> memory) => Step(memory);
public Task<TLAuth> Run()
{
currentState = AuthState.ReqPQ;
authKeyTask = new TaskCompletionSource<TLAuth>();
Step(Memory<byte>.Empty);
return authKeyTask.Task;
}
private void WritePacket(TLObject method)
{
var payload = method.SerializeToMemory();
var packet = new UnsecuredMessage(payload);
_transport.QueuePacket(packet);
}
private void Step(Memory<byte> data)
{
lock (_lock)
{
if (authKeyTask.Task.IsFaulted)
return;
switch (currentState)
{
case AuthState.ReqPQ:
ReqPQ();
break;
case AuthState.ResPQ_ReqDH:
ResPQ(data);
break;
case AuthState.ResDH_SetDH:
ResDH(data);
break;
case AuthState.DHGenCheck:
DHGenCheck(data);
break;
default:
break;
}
try
{
if (_endState == currentState)
{
authKeyTask.SetResult(new TLAuth(_authKey, _serverSalt));
return;
}
Info($"Auth state chaging from {currentState} to {_stateMap[currentState]}");
currentState = _stateMap[currentState];
}
catch (KeyNotFoundException)
{
authKeyTask.SetException(new InvalidOperationException($"Can not switch from {currentState}"));
}
}
}
private void DHGenCheck(Memory<byte> data)
{
DGenOk genResult = new DGenOk();
using (var responseStream = new MemoryStream(data.ToArray()))
using (var sr = new BinaryReader(responseStream))
{
if (data.Length == 4)
{
Error($"Error from server {sr.ReadInt32()}");
return;
}
var authId = sr.ReadInt64();
var messageId = sr.ReadInt64();
var length = sr.ReadInt32();
genResult.Deserialize(sr.BaseStream);
}
Memory<byte> authKeySHA = _authKey.ComputeSHAHash();
var clientNonce1 =
MemoryLine.Create(_newNonce, (byte)1, authKeySHA.Slice(0, 8)).ToArray()
.ComputeSHAHash().GetLowestBytes(16);
_serverSalt = BitConverter.ToInt64(_newNonce.Cut(0, 8).ToArray().XOR(_nonceServer.Cut(0, 8).ToArray()), 0);
var anotherSalt = BitConverter.ToInt64(((Span<byte>)_newNonce).Slice(0, 8)) ^ BitConverter.ToInt64(((Span<byte>)_nonceServer).Slice(0, 8));
Info($"DH Gen OK is {genResult.Parsed}");
}
private void ResDH(Memory<byte> data)
{
if (!UnsecuredMessage.TryParse(data, out UnsecuredMessage message))
return;
ServerDHParams resDH = new ServerDHParams();
using (var responseStream = new MemoryStream(message.Payload.ToArray()))
using (var sr = new BinaryReader(responseStream))
{
resDH.Deserialize(sr.BaseStream);
}
byte[] CalculateTmpAesKey(byte[] newNonce, byte[] serverNonce)
{
var hash1 = newNonce.Concat(serverNonce).ToArray().ComputeSHAHash();
var hash2 = serverNonce.Concat(newNonce).ToArray().ComputeSHAHash();
return hash1.Concat(hash2.Cut(0, 12).ToArray()).ToArray();
}
byte[] CalculateTmpAesIV(byte[] newNonce, byte[] serverNonce)
{
var hash1 = serverNonce.Concat(newNonce).ToArray().ComputeSHAHash();
var hash2 = newNonce.Concat(newNonce).ToArray().ComputeSHAHash();
return hash1.GetLowestBytes(8).ToArray().Concat(hash2).Concat(newNonce.Cut(0, 4).ToArray()).ToArray();
}
var aesVector = CalculateTmpAesIV(_newNonce, _nonceServer);
var aesKey = CalculateTmpAesKey(_newNonce, _nonceServer);
var answerWithHash = Encryption.AES256IGEDecrypt(resDH.EncData, aesVector, aesKey);
var answer = answerWithHash.Skip(20).ToArray();
if (!TLObjectParser.TryParse((ReadOnlyMemory<byte>)answer, out ServerDHInner serverDhInner))
{
throw new ArgumentException("Can not parse server dh inner");
}
var DHPrime = new BI(serverDhInner.DHPrime, isBigEndian: true, isUnsigned: true);
var GA = new BI(serverDhInner.GA, isBigEndian: true, isUnsigned: true);
var G = new BI(serverDhInner.G);
var B = new BI(new byte[256].NoiseArray(), isBigEndian: true, isUnsigned: true);
_authKey = BI.ModPow(GA, B, DHPrime).ToByteArray(isUnsigned: true, isBigEndian: true);
var clientDH = new ClientDHInner
{
Nonce = _nonceClient,
ServerNonce = _nonceServer,
RetryId = 0
};
clientDH.GB = BI.ModPow(G, B, DHPrime).ToByteArray(isUnsigned: true, isBigEndian: true);
var clientDHInnerData = clientDH.Serialize().ToArray();
var setClientDH = new SetClientDHParams
{
Nonce = _nonceClient,
ServerNonce = _nonceServer,
EncData = Encryption.AES256IGEEncrypt(clientDHInnerData.PackWithHash(16), aesVector, aesKey)
};
WritePacket(setClientDH);
}
private void ResPQ(Memory<byte> data)
{
if (!UnsecuredMessage.TryParse(data, out UnsecuredMessage message))
return;
if (!TLObjectParser.TryParse(message.Payload, out ResPQ resPQ))
throw new InvalidOperationException("Can not parse ResPQ from response");
for (int i = 0; i < 16; i++)
{
if (_nonceClient[i] != resPQ.Nonce.Span[i])
authKeyTask.SetException(
new InvalidOperationException("Client nonce from server does not match local nonce"));
}
_nonceServer = resPQ.ServerNonce.ToArray();
var pq = new BI(resPQ.PQ, isBigEndian: true);
BI rhoPollard(BI n)
{
BI x = 2;
BI y = 2;
BI d = 1;
Func<BI, BI> gX = _x => BI.Remainder(BI.Pow(_x, 2) + 1, n);
while (d == 1)
{
x = gX(x);
y = gX(gX(y));
d = BI.GreatestCommonDivisor(BI.Abs(x - y), n);
}
if (d == n)
throw new ArgumentException("RHO failure");
else
return d;
}
var primeFactor1 = rhoPollard(pq);
var primeFactor2 = pq / primeFactor1;
BI p, q;
if (primeFactor1 < primeFactor2)
{
p = primeFactor1;
q = primeFactor2;
}
else
{
p = primeFactor2;
q = primeFactor1;
}
var localPublicKey = PublicKeys.Keys.FirstOrDefault(k => resPQ.KeyFingerPrints.Contains(k.FingerPrint));
if (localPublicKey == null)
throw new SecurityException("Local public key not found");
_newNonce = new byte[32].NoiseArray();
var pqInner = new PQInner(
pq.ToByteArray(isBigEndian: true),
p.ToByteArray(isBigEndian: true),
q.ToByteArray(isBigEndian: true),
_nonceClient,
_nonceServer,
_newNonce);
byte[] dataWithHash;
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
var pqInnerData = pqInner.SerializeToMemory().ToArray();
bw.Write(pqInnerData.ComputeSHAHash());
bw.Write(pqInnerData);
ms.Align(255);
}
dataWithHash = ms.ToArray();
}
byte[] encryptedData = Encryption.RSAEncrypt(dataWithHash, localPublicKey.Modulus, localPublicKey.Exponent);
var reqDHParams = new ReqDHParams
{
Nonce = _nonceClient,
ServerNonce = _nonceServer,
P = p.ToByteArray(isBigEndian: true),
Q = q.ToByteArray(isBigEndian: true),
PublicKeyFingerPrint = localPublicKey.FingerPrint,
Data = encryptedData
};
WritePacket(reqDHParams);
}
private void ReqPQ()
{
_nonceClient = new byte[16].NoiseArray();
WritePacket(new ReqPQ(_nonceClient));
}
public void Dispose()
{
_transport.NewPacket -= NewPacket;
}
}
}
|
namespace RRExpress.Seller {
internal static class Const {
public static readonly string SettingCatlog = "我是卖家";
}
}
|
using Backend.Model.Users;
using GraphicalEditorServer.DTO;
namespace GraphicalEditorServer.Mappers
{
public class SpecialtyMapper
{
public static Specialty SpecialtyDTOToSpecialty(SpecialtyDTO specialtyDTO)
{
Specialty specialty = new Specialty();
specialty.Id = specialtyDTO.Id;
specialty.Name = specialtyDTO.Name;
return specialty;
}
public static SpecialtyDTO SpecialtyToSpecialtyDTO(Specialty specialty)
{
SpecialtyDTO specialtyDTO = new SpecialtyDTO();
specialtyDTO.Id = specialty.Id;
specialtyDTO.Name = specialty.Name;
return specialtyDTO;
}
}
}
|
using UnityEngine;
using UnityEngine.Networking;
public class Player : NetworkBehaviour
{
[SerializeField]
private Card _cardPrefab;
void Start ()
{
}
void Update ()
{
if (!isLocalPlayer) return;
/*if (Input.GetKeyDown(KeyCode.Space))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
CmdSpawnCard("Ponder", hit.point);
}
}*/
if (Input.GetKeyDown(KeyCode.D))
{
NetworkCommander.Get.SendCommand(new DebugCommand());
}
if (Input.GetKeyDown(KeyCode.Q))
{
NetworkCommander.Get.SendCommand(new DebugMessageCommand("QQQ"));
}
if (Input.GetKeyDown(KeyCode.W))
{
NetworkCommander.Get.SendCommand(new DebugMessageCommand("\\_/\\_/"));
}
if (Input.GetKeyDown(KeyCode.E))
{
NetworkCommander.Get.SendCommand(new DebugMessageCommand("USE!"));
}
}
/*[Command]
void CmdSpawnCard(string name, Vector3 position)
{
Card card = Instantiate(_cardPrefab);
card.transform.position = position;
card.Name = name;
NetworkServer.SpawnWithClientAuthority(card.gameObject, gameObject);
}*/
void OnGUI()
{
//Temp fix for crash when building WebGL with codestripping enabled.
//Should be fixed in Unity 5.3.
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Firebase.Database;
using Firebase.Database.Query;
using Firebase.Database.Streaming;
using Xamarin.Forms;
using App1.ViewModels;
using App1.Models;
namespace App1
{
public class MainPageViewModel : BaseViewModel
{
private readonly string ENDERECO_FIREBASE = "https://demoapp-1df56.firebaseio.com/";
private readonly FirebaseClient _firebaseClient;
private ObservableCollection<Pedido> _pedidos;
public ObservableCollection<Pedido> Pedidos
{
get { return _pedidos; }
set { _pedidos = value; OnPropertyChanged();}
}
public Pedido PedidoSelecionado;
public ICommand AceitarPedidoCmd { get; set; }
public MainPageViewModel()
{
_firebaseClient = new FirebaseClient(ENDERECO_FIREBASE);
Pedidos = new ObservableCollection<Pedido>();
AceitarPedidoCmd = new Command(() => AceitarPedido());
ListenerPedidos();
}
private void AceitarPedido()
{
PedidoSelecionado.IdVendedor = 1;
_firebaseClient
.Child("pedidos")
.Child(PedidoSelecionado.KeyPedido)
.PutAsync(PedidoSelecionado);
}
private void ListenerPedidos()
{
_firebaseClient
.Child("pedidos")
.AsObservable<Pedido>()
.Subscribe(d =>
{
if (d.EventType == FirebaseEventType.InsertOrUpdate)
{
if (d.Object.IdVendedor == 0)
AdicionarPedido(d.Key, d.Object);
else
RemoverPedido(d.Key);
}
else if (d.EventType == FirebaseEventType.Delete)
{
RemoverPedido(d.Key);
}
});
}
private void AdicionarPedido(string key, Pedido pedido)
{
Pedidos.Add(new Pedido()
{
KeyPedido = key,
Cliente = pedido.Cliente,
Produto = pedido.Produto,
Preco = pedido.Preco
});
}
private void RemoverPedido(string pedidoKey)
{
var pedido = Pedidos.FirstOrDefault(x => x.KeyPedido == pedidoKey);
Pedidos.Remove(pedido);
}
}
}
|
using Exiled.API.Features;
using Exiled.API.Enums;
using System;
using HarmonyLib;
using System.Runtime.Remoting.Messaging;
using System.Runtime.CompilerServices;
namespace CustomTeslaDamage
{
public class CustomTeslaDamagePlugin : Plugin<Config>
{
public override string Name { get; } = "Custom Tesla Damage";
public override string Prefix { get; } = "CTD";
public override string Author { get; } = "CubeRuben";
public override PluginPriority Priority { get; } = PluginPriority.Low;
public override Version Version { get; } = new Version(1, 0, 0);
public override Version RequiredExiledVersion { get; } = new Version(2, 1, 0);
Harmony Harmony;
public static CustomTeslaDamagePlugin Plugin;
public CustomTeslaDamagePlugin()
{
Plugin = this;
}
public override void OnEnabled()
{
Harmony = new Harmony("com.cuberuben.customtesladamage");
Harmony.PatchAll();
}
public override void OnDisabled()
{
Harmony.UnpatchAll();
}
}
}
|
using System.Collections.Generic;
namespace RESTfulAPI.Repository.Interfaces
{
public interface IUserInterface
{
public List<T> View<T>();
public T View<T>(int id);
public int Add<T>(T data);
public void Update<T>(T data);
public void Delete<T>(T id);
}
}
|
using UnityEngine;
using System.Collections;
public class GameHUD : MonoBehaviour {
public GUISkin Skin;
public Transform _xaxis;
public Transform Foregrounds;
public void OnGUI()
{
/*
GUI.skin = Skin;
//Debug.Log("milliseconds: "+LevelManager.instance.LevelMusic.timeSamples / LevelManager.instance.LevelMusic.clip.frequency);
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
{
GUILayout.BeginVertical(Skin.GetStyle("GameHud"));
{
var time = LevelManager.Instance.RunningTime;
GUILayout.Label(string.Format(
"{0:00}:{1:00}:{2:000} : {3:000000} : {4:000000} : {5:00000000} : {6:0000000}",
time.Minutes + (time.Hours * 60),
time.Seconds,
time.Milliseconds,
time.TotalMilliseconds / 1000,
LevelManager.Instance.LevelMusic.time,
LevelManager.Instance.LevelMusic.time * 12.8f - 12.8f,
Foregrounds.position.x,
Skin.GetStyle("TimeText")));
//if ( time.ToString().Substring(0,10) == "00:00:46.0")
//if ( time.ToString().Substring(0,10) == "00:01:00.6")
//Debug.Log("_xaxis.position.x: " + _xaxis.position.x);
}
GUILayout.EndVertical();
}
GUILayout.EndArea();
*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ApartmentApps.Api.BindingModels;
using ApartmentApps.Api.NewFolder1;
using StaticMap.Core.Model;
using StaticMap.Google;
namespace ApartmentApps.Api
{
public class DailyOfficerReport : EmailData
{
public IEnumerable<CourtesyCheckinBindingModel> Checkins { get; set; }
public GeoCoordinate Center
{
get
{
return GetCentralGeoCoordinate(
Checkins.Select(x => new GeoCoordinate(x.Latitude, x.Longitude)).ToList());
}
}
public string StaticMapUrl
{
get
{
var center = Center;
var staticMap = new GoogleStaticMapUrlBuilder("https://maps.googleapis.com/maps/api/staticmap")
.SetCenter(new Point(center.Latitude,center.Longitude));
foreach (var item in Checkins.Where(p => p.Complete))//
{
staticMap.AddMarker(new StaticMap.Core.Model.Marker(new Point(item.Latitude, item.Longitude))
{
DrawColor = HttpUtility.UrlEncode(item.Complete ? "green" : "grey"),
// Label = Uri.EscapeUriString(item.Label)
});
}
staticMap.SetZoom(17);
return staticMap.Build(500, 500) +"&key=AIzaSyDjBsoydtvTc55SZZsqlJZQMstPtyIs3z8";
}
}
public static GeoCoordinate GetCentralGeoCoordinate(
IList<GeoCoordinate> geoCoordinates)
{
if (geoCoordinates.Count == 1)
{
return geoCoordinates.Single();
}
double x = 0;
double y = 0;
double z = 0;
foreach (var geoCoordinate in geoCoordinates)
{
var latitude = geoCoordinate.Latitude * Math.PI / 180;
var longitude = geoCoordinate.Longitude * Math.PI / 180;
x += Math.Cos(latitude) * Math.Cos(longitude);
y += Math.Cos(latitude) * Math.Sin(longitude);
z += Math.Sin(latitude);
}
var total = geoCoordinates.Count;
x = x / total;
y = y / total;
z = z / total;
var centralLongitude = Math.Atan2(y, x);
var centralSquareRoot = Math.Sqrt(x * x + y * y);
var centralLatitude = Math.Atan2(z, centralSquareRoot);
return new GeoCoordinate(centralLatitude * 180 / Math.PI, centralLongitude * 180 / Math.PI);
}
//public StaticMap GoogleMap
//{
// get
// {
// var map = new StaticMap();
// map.Markers.Add(new StaticMap.Marker()
// {
// });
// map.
// }
//}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading;
using ConsoleTables;
namespace MeybankATMSystem
{
class MeybankATM : ILogin, IBalance, IDeposit, IWithdrawal, IThirdPartyTransfer, ITransaction
{
private static int tries;
private const int maxTries = 3;
private const decimal minimum_kept_amt = 20;
//todo: A transaction class with transaction amount can replace these two variable.
private static decimal transaction_amt;
private static List<BankAccount> _accountList;
private static List<Transaction> _listOfTransactions;
private static BankAccount selectedAccount;
private static BankAccount inputAccount;
public void Execute()
{
//Initialization();
ATMScreen.ShowMenu1();
while (true)
{
switch (Utility.GetValidIntInputAmt("your option"))
{
case 1:
CheckCardNoPassword();
_listOfTransactions = new List<Transaction>();
while (true)
{
ATMScreen.ShowMenu2();
switch (Utility.GetValidIntInputAmt("your option"))
{
case (int)SecureMenu.CheckBalance:
CheckBalance(selectedAccount);
break;
case (int)SecureMenu.PlaceDeposit:
PlaceDeposit(selectedAccount);
break;
case (int)SecureMenu.MakeWithdrawal:
MakeWithdrawal(selectedAccount);
break;
case (int)SecureMenu.ThirdPartyTransfer:
var vMThirdPartyTransfer = new VMThirdPartyTransfer();
vMThirdPartyTransfer = ATMScreen.ThirdPartyTransferForm();
PerformThirdPartyTransfer(selectedAccount, vMThirdPartyTransfer);
break;
case (int)SecureMenu.ViewTransaction:
ViewTransaction(selectedAccount);
break;
case (int)SecureMenu.Logout:
Utility.PrintMessage("You have succesfully logout. Please collect your ATM card..", true);
Execute();
break;
default:
Utility.PrintMessage("Invalid Option Entered.", false);
break;
}
}
case 2:
Console.Write("\nThank you for using Meybank. Exiting program now .");
Utility.printDotAnimation(15);
System.Environment.Exit(1);
break;
default:
Utility.PrintMessage("Invalid Option Entered.", false);
break;
}
}
}
private static void LockAccount()
{
Console.Clear();
Utility.PrintMessage("Your account is locked.", true);
Console.WriteLine("Please go to the nearest branch to unlocked your account.");
Console.WriteLine("Thank you for using Meybank. ");
Console.ReadKey();
System.Environment.Exit(1);
}
public void Initialization()
{
transaction_amt = 0;
_accountList = new List<BankAccount>
{
new BankAccount() { FullName = "John", AccountNumber=333111, CardNumber = 123, PinCode = 111111, Balance = 2000.00m, isLocked = false },
new BankAccount() { FullName = "Mike", AccountNumber=111222, CardNumber = 456, PinCode = 222222, Balance = 1500.30m, isLocked = true },
new BankAccount() { FullName = "Mary", AccountNumber=888555, CardNumber = 789, PinCode = 333333, Balance = 2900.12m, isLocked = false }
};
}
public void CheckCardNoPassword()
{
bool pass = false;
while (!pass)
{
inputAccount = new BankAccount();
Console.WriteLine("\nNote: Actual ATM system will accept user's ATM card to validate");
Console.Write("and read card number, bank account number and bank account status. \n\n");
//Console.Write("Enter ATM Card Number: ");
//inputAccount.CardNumber = Convert.ToInt32(Console.ReadLine());
inputAccount.CardNumber = Utility.GetValidIntInputAmt("ATM Card Number");
Console.Write("Enter 6 Digit PIN: ");
inputAccount.PinCode = Convert.ToInt32(Utility.GetHiddenConsoleInput());
// for brevity, length 6 is not validated and data type.
System.Console.Write("\nChecking card number and password.");
Utility.printDotAnimation();
foreach (BankAccount account in _accountList)
{
if (inputAccount.CardNumber.Equals(account.CardNumber))
{
selectedAccount = account;
if (inputAccount.PinCode.Equals(account.PinCode))
{
if (selectedAccount.isLocked)
LockAccount();
else
pass = true;
}
else
{
pass = false;
tries++;
if (tries >= maxTries)
{
selectedAccount.isLocked = true;
LockAccount();
}
}
}
}
if (!pass)
Utility.PrintMessage("Invalid Card number or PIN.", false);
Console.Clear();
}
}
public void CheckBalance(BankAccount bankAccount)
{
Utility.PrintMessage($"Your bank account balance amount is: {Utility.FormatAmount(bankAccount.Balance)}", true);
}
public void PlaceDeposit(BankAccount account)
{
Console.WriteLine("\nNote: Actual ATM system will just let you ");
Console.Write("place bank notes into ATM machine. \n\n");
//Console.Write("Enter amount: " + ATMScreen.cur);
transaction_amt = Utility.GetValidDecimalInputAmt("amount");
System.Console.Write("\nCheck and counting bank notes.");
Utility.printDotAnimation();
if (transaction_amt <= 0)
Utility.PrintMessage("Amount needs to be more than zero. Try again.", false);
else if (transaction_amt % 10 != 0)
Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false);
else if (!PreviewBankNotesCount(transaction_amt))
Utility.PrintMessage($"You have cancelled your action.", false);
else
{
// Bind transaction_amt to Transaction object
// Add transaction record - Start
var transaction = new Transaction()
{
BankAccountNoFrom = account.AccountNumber,
BankAccountNoTo = account.AccountNumber,
TransactionType = TransactionType.Deposit,
TransactionAmount = transaction_amt,
TransactionDate = DateTime.Now
};
InsertTransaction(account, transaction);
// Add transaction record - End
// Another method to update account balance.
account.Balance = account.Balance + transaction_amt;
Utility.PrintMessage($"You have successfully deposited {Utility.FormatAmount(transaction_amt)}", true);
}
}
public void MakeWithdrawal(BankAccount account)
{
Console.WriteLine("\nNote: For GUI or actual ATM system, user can ");
Console.Write("choose some default withdrawal amount or custom amount. \n\n");
// Console.Write("Enter amount: " + ATMScreen.cur);
// transaction_amt = ATMScreen.ValidateInputAmount(Console.ReadLine());
transaction_amt = Utility.GetValidDecimalInputAmt("amount");
if (transaction_amt <= 0)
Utility.PrintMessage("Amount needs to be more than zero. Try again.", false);
else if (transaction_amt > account.Balance)
Utility.PrintMessage($"Withdrawal failed. You do not have enough fund to withdraw {Utility.FormatAmount(transaction_amt)}", false);
else if ((account.Balance - transaction_amt) < minimum_kept_amt)
Utility.PrintMessage($"Withdrawal failed. Your account needs to have minimum {Utility.FormatAmount(minimum_kept_amt)}", false);
else if (transaction_amt % 10 != 0)
Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false);
else
{
// Bind transaction_amt to Transaction object
// Add transaction record - Start
var transaction = new Transaction()
{
BankAccountNoFrom = account.AccountNumber,
BankAccountNoTo = account.AccountNumber,
TransactionType = TransactionType.Withdrawal,
TransactionAmount = transaction_amt,
TransactionDate = DateTime.Now
};
InsertTransaction(account, transaction);
// Add transaction record - End
// Another method to update account balance.
account.Balance = account.Balance - transaction_amt;
Utility.PrintMessage($"Please collect your money. You have successfully withdraw {Utility.FormatAmount(transaction_amt)}", true);
}
}
public void PerformThirdPartyTransfer(BankAccount bankAccount, VMThirdPartyTransfer vMThirdPartyTransfer)
{
if (vMThirdPartyTransfer.TransferAmount <= 0)
Utility.PrintMessage("Amount needs to be more than zero. Try again.", false);
else if (vMThirdPartyTransfer.TransferAmount > bankAccount.Balance)
// Check giver's account balance - Start
Utility.PrintMessage($"Withdrawal failed. You do not have enough fund to withdraw {Utility.FormatAmount(transaction_amt)}", false);
else if (bankAccount.Balance - vMThirdPartyTransfer.TransferAmount < 20)
Utility.PrintMessage($"Withdrawal failed. Your account needs to have minimum {Utility.FormatAmount(minimum_kept_amt)}", false);
// Check giver's account balance - End
else
{
// Check if receiver's bank account number is valid.
var selectedBankAccountReceiver = (from b in _accountList
where b.AccountNumber == vMThirdPartyTransfer.RecipientBankAccountNumber
select b).FirstOrDefault();
if (selectedBankAccountReceiver == null)
Utility.PrintMessage($"Third party transfer failed. Receiver bank account number is invalid.", false);
else if (selectedBankAccountReceiver.FullName != vMThirdPartyTransfer.RecipientBankAccountName)
Utility.PrintMessage($"Third party transfer failed. Recipient's account name does not match.", false);
else
{
// Bind transaction_amt to Transaction object
// Add transaction record - Start
Transaction transaction = new Transaction()
{
BankAccountNoFrom = bankAccount.AccountNumber,
BankAccountNoTo = vMThirdPartyTransfer.RecipientBankAccountNumber,
TransactionType = TransactionType.ThirdPartyTransfer,
TransactionAmount = vMThirdPartyTransfer.TransferAmount,
TransactionDate = DateTime.Now
};
_listOfTransactions.Add(transaction);
Utility.PrintMessage($"You have successfully transferred out {Utility.FormatAmount(vMThirdPartyTransfer.TransferAmount)} to {vMThirdPartyTransfer.RecipientBankAccountName}", true);
// Add transaction record - End
// Update balance amount (Giver)
bankAccount.Balance = bankAccount.Balance - vMThirdPartyTransfer.TransferAmount;
// Update balance amount (Receiver)
selectedBankAccountReceiver.Balance = selectedBankAccountReceiver.Balance + vMThirdPartyTransfer.TransferAmount;
}
}
}
private static bool PreviewBankNotesCount(decimal amount)
{
int hundredNotesCount = (int)amount / 100;
int fiftyNotesCount = ((int)amount % 100) / 50;
int tenNotesCount = ((int)amount % 50) / 10;
Console.WriteLine("\nSummary");
Console.WriteLine("-------");
Console.WriteLine($"{ATMScreen.cur} 100 x {hundredNotesCount} = {100 * hundredNotesCount}");
Console.WriteLine($"{ATMScreen.cur} 50 x {fiftyNotesCount} = {50 * fiftyNotesCount}");
Console.WriteLine($"{ATMScreen.cur} 10 x {tenNotesCount} = {10 * tenNotesCount}");
Console.Write($"Total amount: {Utility.FormatAmount(amount)}\n\n");
//Console.Write("\n\nPress 1 to confirm or 0 to cancel: ");
string opt = Utility.GetValidIntInputAmt("1 to confirm or 0 to cancel").ToString();
return (opt.Equals("1")) ? true : false;
}
public void ViewTransaction(BankAccount bankAccount)
{
if (_listOfTransactions.Count <= 0)
Utility.PrintMessage($"There is no transaction yet.", true);
else
{
var table = new ConsoleTable("Type", "From", "To", "Amount " + ATMScreen.cur, "Transaction Date");
foreach (var tran in _listOfTransactions)
{
table.AddRow(tran.TransactionType, tran.BankAccountNoFrom, tran.BankAccountNoTo, tran.TransactionAmount,
tran.TransactionDate);
}
table.Options.EnableCount = false;
table.Write();
Utility.PrintMessage($"You have performed {_listOfTransactions.Count} transactions.", true);
}
}
public void InsertTransaction(BankAccount bankAccount, Transaction transaction)
{
_listOfTransactions.Add(transaction);
}
}
}
|
using System;
using System.Text;
using System.Text.RegularExpressions;
class Chains
{
static void Main()
{
//string input = System.IO.File.ReadAllText(@"..\..\themanual.txt");
string input = Console.ReadLine();
string getp = @"<p>(.*?)<\/p>";
MatchCollection ptags = new Regex(getp).Matches(input);
StringBuilder sb = new StringBuilder();
foreach (Match match in ptags)
{
sb.Append(match.Groups[1]);
}
//get rid of non-(a-z, A-Z, 0-9 stuff
string invalidcharsRegex = @"[^a-z0-9]";
for (int i = 0; i < sb.Length; i++)
{
if (Regex.IsMatch(sb[i].ToString(), invalidcharsRegex))
{
sb[i] = ' ';
}
}
sb = new StringBuilder(Regex.Replace(sb.ToString(), @"( )\1*", " "));
//ROT13
for (int i = 0; i < sb.Length; i++)
{
if (Regex.IsMatch(sb[i].ToString(), @"[a-m]"))
{
sb[i] = (char)(sb[i] + 13);
}
else if (Regex.IsMatch(sb[i].ToString(), @"[n-z]"))
{
sb[i] = (char)(sb[i] - 13);
}
}
Console.WriteLine(sb);
}
}
|
using MonitorBoletos.DAO;
using MonitorBoletos.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MonitorBoletos.Business
{
public class ContaCorrenteBusiness
{
/// <summary>
/// Validar a Conta Corrente
/// </summary>
/// <param name="conta">para verificar se ela existe</param>
/// <returns>retorna uma conta</returns>
public ContaCorrente validarContaCorrente(ContaCorrente conta)
{
var account = new ContaCorrenteDAO();
var contacorrente = account.getByNumero(conta);
return contacorrente;
}
}
}
|
using UnityEngine;
using UnityAtoms.BaseAtoms;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Variable Instancer of type `bool`. Inherits from `AtomVariableInstancer<BoolVariable, BoolPair, bool, BoolEvent, BoolPairEvent, BoolBoolFunction>`.
/// </summary>
[EditorIcon("atom-icon-hotpink")]
[AddComponentMenu("Unity Atoms/Variable Instancers/Bool Variable Instancer")]
public class BoolVariableInstancer : AtomVariableInstancer<
BoolVariable,
BoolPair,
bool,
BoolEvent,
BoolPairEvent,
BoolBoolFunction>
{ }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ChargeIO
{
public class SignatureOptions
{
[JsonProperty("gratuity")]
public int? GratuityInCents { get; set; }
[JsonProperty("mime_type")]
public string MimeType { get; set; }
[JsonProperty("data")]
public string Data { get; set; }
}
}
|
using System;
namespace Test_numbers
{
class Program
{
static void Main(string[] args)
{
// • First line – N – integer in the interval[1…100]
//• Second line – M – integer in the interval[1…100]
//• Third line – maximum sum boundary – integer in the interval[1…1000000]
int firstInt = int.Parse(Console.ReadLine());
int secondInt = int.Parse(Console.ReadLine());
int boundry = int.Parse(Console.ReadLine());
int sum = 0;
int combinations = 0;
for (int i = firstInt; i >= 1; i--)
{
for (int j = 1; j <= secondInt; j++)
{
combinations++;
int product = (i * j) * 3;
sum += product;
if (sum >= boundry)
{
Console.WriteLine($"{combinations} combinations");
Console.WriteLine($"Sum: {sum} >= {boundry}");
return;
}
}
}
Console.WriteLine($"{combinations} combinations");
Console.WriteLine($"Sum: {sum}");
}
}
}
|
using Microsoft.Maps.MapControl.WPF;
using UFO.Commander.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using UFO.Server;
using UFO.Server.Data;
namespace UFO.Commander.ViewModel {
public class VenueManagementViewModel :INotifyPropertyChanged {
private IVenueService venueService;
private VenueViewModel currentVenue;
public event PropertyChangedEventHandler PropertyChanged;
public string NameInput { get; set; }
public string ShortCutInput { get; set; }
public double LatitudeInput { get; set; }
public double LongitudeInput { get; set; }
private ICommand createCommand;
public ObservableCollection<VenueViewModel> Venues { get; set; }
public VenueManagementViewModel(IVenueService venueService) {
this.venueService = venueService;
NameInput = "";
ShortCutInput = "";
this.Venues = new ObservableCollection<VenueViewModel>();
UpdateVenues();
}
public void UpdateVenues() {
CurrentVenue = null;
Venues.Clear();
Task.Run(() => {
List<Venue> venues = venueService.GetAllVenues();
foreach (var venue in venues) {
VenueViewModel vm = new VenueViewModel(venueService, venue);
PlatformService.Instance.RunByUiThread(() => {
Venues.Add(vm);
});
}
});
}
public VenueViewModel CurrentVenue {
get {
return this.currentVenue;
}
set {
if (this.currentVenue != value) {
this.currentVenue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentVenue)));
}
}
}
public ICommand CreateCommand {
get {
if (createCommand == null) {
createCommand = new RelayCommand((param) => {
Venue venue;
try {
venue = venueService.CreateVenue(NameInput, ShortCutInput,LatitudeInput,LongitudeInput);
} catch (DataValidationException ex) {
PlatformService.Instance.ShowErrorMessage(ex.Message, "Error creating venue");
return;
}
VenueViewModel newVenue = new VenueViewModel(venueService, venue);
Venues.Add(newVenue);
PlatformService.Instance.ShowInformationMessage("Created venue '" + venue.Name + "'!","Information");
NameInput = "";
ShortCutInput = "";
LongitudeInput = 0;
LatitudeInput = 0;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NameInput)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShortCutInput)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LatitudeInput)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(LongitudeInput)));
currentVenue = newVenue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentVenue)));
});
}
return createCommand;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cis237inclass1
{
class UserInterface
{
//no variables, constructors, or properties
//ONLY METHODS BWAHAHAHAHA
//Methods
public int GetUserInput()
{
//print out a menu
PrintMenu();
//get the input from the user
String input = Console.ReadLine();
//while the input is not valid, re-get input
while (input != "1" && input != "2")
{
//print error message
PrintErrorMessage();
PrintMenu();
input = Console.ReadLine();
}
//at this point I know the input is good, so return it
return int.Parse(input);
}
public void Output(String s)
{
Console.WriteLine(s);
}
private void PrintMenu()
{
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Print List");
Console.WriteLine("2. Exit");
}
private void PrintErrorMessage()
{
Console.WriteLine("That is not a valid value.");
Console.WriteLine("Please make a valid choice.");
Console.WriteLine();
}
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// This is my attempt at making a character.
/// </summary>
public class CharacterGenerator
{
public enum Stats
{
Rhythm,
Vocals,
Instrument,
LevelBonus
}
public enum Modifier
{
Added,
Percent,
}
public Stats id;
public Modifier modifier;
public int amount;
static public string GetName(Stats i)
{
return i.ToString();
}
static public string GetDescription(Stats i)
{
switch (i)
{
case Stats.Rhythm:
return "Put down some fat beats, Yo";
case Stats.Vocals:
return "You sing purtay";
case Stats.Instrument:
return "You can play well";
}
return null;
}
//switch (rand)
//{
// case 1:
// string[] maleNames = new string[] {
// "Kurt Lo Mein", "John Lemon", "Beathoven", "Bob Marmalade", "Elvis Parsley",
// "Bruce Springrollstein", "Wolfgang Mozzarella", "Mayonaise Kebab", "LL Koolade", "Wu Tang Flan", "Burrito Mars",
// "Ice T", "Snoop Hotdog",
//};
// character.Name = maleNames[Random.Range(0, maleNames.Length)];
// break;
// case 2:
// string[] femaleNames = new string[] {
// "Rebecca Blackberry", "Sheryl Cranberry", "Britney Spearmint", "Susan B Artichoke", "Lady GoGurt" , "Joan Beanz",
//};
// character.Name = femaleNames[Random.Range(0, femaleNames.Length)];
// break;
//}
}
|
using Newtonsoft.Json;
namespace BDTest.Test;
internal class BDTestRuntimeInformation
{
[JsonIgnore]
internal string CallerMember { get; set; }
[JsonIgnore]
internal string CallerFile { get; set; }
[JsonIgnore]
internal BDTestBase BdTestBase { get; set; }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookShelf.BusinessLogic;
using BookShelfWeb.BookShelfModel;
namespace BookShelfWeb
{
/// <summary>
/// Behind code for LoanReturn.aspx
/// </summary>
public partial class LoanReturn : System.Web.UI.Page
{
#region methods
/// <summary>
/// Page Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreRender(object sender, EventArgs e)
{
LoanButton.Attributes.Add("onmouseup", "ShowModalDialog();");
ReturnButton.Attributes.Add("onmouseup", "ShowModalDialog();");
}
/// <summary>
/// Clear inputs server side approach
/// </summary>
/// <param name="ctrls">control collection</param>
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearInputs(ctrl.Controls);
}
}
/// <summary>
/// Loan button click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void LoanButton_Click(object sender, EventArgs e)
{
try
{
//member variables
string uitb = this.UserIDTextBox.Text;
string bitb = this.BookNameTextBox.Text;
//BookShelfUserManagerBLL to get book entity by book name
BookShelfUserManagerBLL bookShelfUserManagerBLL = new BookShelfUserManagerBLL();
BookShelfUser user = bookShelfUserManagerBLL.GetUserbyID(Int32.Parse(uitb));
BookShelfBookManagerBLL bookShelfBookBLL = new BookShelfBookManagerBLL();
BookShelfBook book = bookShelfBookBLL.GetBookbyName(bitb);
book.UserID = Int32.Parse(uitb);
bookShelfUserManagerBLL.UpdateBookMembership(Int32.Parse(uitb), book, "Loan");
if (IsPostBack)
{
HiddenLabel.Text = "";
ClearInputs(Page.Controls);
HiddenLabel.Visible = true;
HiddenLabel.Text += "Loan is done successfully!";
}
}
catch (Exception ex)
{
HiddenLabel.Text = "";
ClearInputs(Page.Controls);
HiddenLabel.Visible = true;
HiddenLabel.Text += "Loan is failed!";
}
}
protected void ReturnButton_Click(object sender, EventArgs e)
{
try
{
//member variables
string uitb = this.UserIDTextBox.Text;
string bitb = this.BookNameTextBox.Text;
//BookShelfUserManagerBLL to get book entity by book name
BookShelfUserManagerBLL bookShelfUserManagerBLL = new BookShelfUserManagerBLL();
BookShelfUser user = bookShelfUserManagerBLL.GetUserbyID(Int32.Parse(uitb));
BookShelfBookManagerBLL bookShelfBookManagerBLL = new BookShelfBookManagerBLL();
BookShelfBook book = bookShelfBookManagerBLL.GetBookbyName(bitb);
book.UserID = Int32.Parse(uitb);
bookShelfUserManagerBLL.UpdateBookMembership(Int32.Parse(uitb), book, "Return");
if (IsPostBack)
{
HiddenLabel.Text = "";
ClearInputs(Page.Controls);
HiddenLabel.Visible = true;
HiddenLabel.Text += "Return is done successfully!";
}
}
catch (Exception ex)
{
HiddenLabel.Text = "";
ClearInputs(Page.Controls);
HiddenLabel.Visible = true;
HiddenLabel.Text += "Return is failed!";
}
}
#endregion methods
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.MLAgents;
public class GameScene : MonoBehaviour
{
GameArena[] arenas;
public int defaultNumArenas = 0;
public void Awake()
{
Academy.Instance.OnEnvironmentReset += EnvironmentReset;
arenas = GetComponentsInChildren<GameArena>(true);
EnvironmentReset();
}
void EnvironmentReset()
{
int numArenas = (int)Academy.Instance.EnvironmentParameters.GetWithDefault("max_arenas", defaultNumArenas);
int ind = 0;
if (numArenas == 0)
{
// Leave them as they were.
return;
}
foreach (GameArena obj in arenas)
{
obj.gameObject.SetActive(ind < numArenas);
ind++;
}
}
}
|
using Fleck;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using UNO.Model.Karten;
namespace UNO.Model
{
class Spielfeld
{
public List<ISpieler> AllSpieler = new List<ISpieler>();
List<ISpieler> FertigeSpieler = new List<ISpieler>();
Queue<IKarte> Stapel = new Queue<IKarte>();
List<IKarte> GelegteKarten = new List<IKarte>();
ISpieler AktiverSpieler;
bool NichtGelegt = true;
bool vierziehenAktiv = false;
int KartenZiehen;
public Spielfeld(IEnumerable<ISpieler> spieler)
{
KartenZiehen = 0;
AllSpieler = spieler.ToList();
InitStapel();
}
private void Austeilen()
{
for (int i = 0; i < 7; i++)
{
foreach (ISpieler spieler in AllSpieler)
{
if (Stapel.Count() < 7)
{
InitStapel();
}
spieler.Karten.Add(Stapel.Dequeue());
}
}
}
private void LegtKarte(IKarte karte)
{
if (AktiverSpieler.Ziehen != true || karte.Typ == KartenTyp.Ziehen || karte.Typ == KartenTyp.VierZiehen)
{
AktiverSpieler.Karten.Remove(karte);
GelegteKarten.Add(karte);
NichtGelegt = false;
}
}
private void Spielzug()
{
if (AllSpieler.Count == 1)
{
SpielNeustart();
}
AktiverSpieler = AllSpieler.First();
if (AktiverSpieler.Aussetzen == true)
{
if (AktiverSpieler.Ki == true)
{
((KI)AktiverSpieler).Aussetzen = false;
}
else
{
((Spieler)AktiverSpieler).Aussetzen = false;
}
NächsterSpieler();
}
foreach (ISpieler temp in AllSpieler)
{
if (temp.Ki == false)
{
if (temp == AktiverSpieler)
{
temp.TeileSpielStand(GelegteKarten.Last(), true, AllSpieler);
}
else
{
temp.TeileSpielStand(GelegteKarten.Last(), false, AllSpieler);
}
}
}
if (AktiverSpieler.Ki)
{
Stopwatch st = new Stopwatch();
st.Start();
while (st.ElapsedMilliseconds < 1500)
{
}
st.Stop();
}
NichtGelegt = true;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (stopWatch.ElapsedMilliseconds < 20000 && NichtGelegt)
{
if (AktiverSpieler.Ki == true)
{
KIMachtZug();
break;
}
else if (AktiverSpieler.CardIndex != null)
{
IKarte gelegteKarteSpieler = AktiverSpieler.Karten[(int)AktiverSpieler.CardIndex];
if (VersuchtKarteLegen(gelegteKarteSpieler))
{
if (gelegteKarteSpieler.Farbe == KartenFarbe.Schwarz || gelegteKarteSpieler.Typ == KartenTyp.VierZiehen)
{
int blauCounter = 0;
int rotCounter = 0;
int gelbCounter = 0;
int grünCounter = 0;
foreach (IKarte zk in AktiverSpieler.Karten)
{
switch (zk.Farbe)
{
case KartenFarbe.Gelb:
gelbCounter++;
break;
case KartenFarbe.Rot:
rotCounter++;
break;
case KartenFarbe.Blau:
blauCounter++;
break;
case KartenFarbe.Gruen:
grünCounter++;
break;
default:
break;
}
}
if (blauCounter > rotCounter && blauCounter > grünCounter && blauCounter > gelbCounter)
{
gelegteKarteSpieler.Farbe = KartenFarbe.Blau;
}
else if (rotCounter > blauCounter && rotCounter > grünCounter && rotCounter > gelbCounter)
{
gelegteKarteSpieler.Farbe = KartenFarbe.Rot;
}
else if (grünCounter > rotCounter && grünCounter > blauCounter && grünCounter > gelbCounter)
{
gelegteKarteSpieler.Farbe = KartenFarbe.Gruen;
}
else
{
gelegteKarteSpieler.Farbe = KartenFarbe.Gelb;
}
if (gelegteKarteSpieler.Typ == KartenTyp.VierZiehen)
{
vierziehenAktiv = true;
KartenZiehen += 4;
}
LegtKarte(gelegteKarteSpieler);
}
else
{
LegtKarte(gelegteKarteSpieler);
}
break;
}
else
{
if (vierziehenAktiv)
{
for (int i = 0; i < KartenZiehen; i++)
{
GenugKartenImStapel();
AktiverSpieler.ZiehtKarte(Stapel);
}
KartenZiehen = 0;
vierziehenAktiv = false;
((Spieler)AktiverSpieler).Ziehen = false;
((Spieler)AktiverSpieler).CardIndex = null;
}
else
{
if (AktiverSpieler.Ziehen == true)
{
break;
}
GenugKartenImStapel();
AktiverSpieler.ZiehtKarte(Stapel);
((Spieler)AktiverSpieler).CardIndex = null;
}
NächsterSpieler();
}
}
}
if (GelegteKarten.Last().Typ == KartenTyp.Ziehen && !NichtGelegt)
{
if (AllSpieler[1].Ki)
{
((KI)AllSpieler[1]).Ziehen = true;
}
else
{
((Spieler)AllSpieler[1]).Ziehen = true;
}
if (AktiverSpieler.Ki)
{
((KI)AktiverSpieler).Ziehen = false;
}
else
{
((Spieler)AktiverSpieler).Ziehen = false;
}
KartenZiehen += 2;
}
else if (KartenZiehen != 0)
{
if (NichtGelegt)
{
for (int i = 0; i < KartenZiehen; i++)
{
GenugKartenImStapel();
AktiverSpieler.ZiehtKarte(Stapel);
}
vierziehenAktiv = false;
KartenZiehen = 0;
if (AktiverSpieler.Ki)
{
((KI)AktiverSpieler).Ziehen = false;
}
else
{
((Spieler)AktiverSpieler).Ziehen = false;
}
}
}
else if (KartenZiehen == 0 && NichtGelegt)
{
GenugKartenImStapel();
AktiverSpieler.ZiehtKarte(Stapel);
}
stopWatch.Stop();
if (AktiverSpieler.Karten.Count == 0)
{
SpielerGewinnt();
AktiverSpieler.HastGewonnen();
Spielzug();
}
if (AllSpieler.Count > 1)
{
if (!AktiverSpieler.Ki)
{
((Spieler)AktiverSpieler).CardIndex = null;
}
NächsterSpieler();
}
}
private void KIMachtZug()
{
if (vierziehenAktiv)
{
((KI)AktiverSpieler).ZiehtKarte(Stapel);
((KI)AktiverSpieler).ZiehtKarte(Stapel);
((KI)AktiverSpieler).ZiehtKarte(Stapel);
((KI)AktiverSpieler).ZiehtKarte(Stapel);
KartenZiehen = 0;
NichtGelegt = false;
vierziehenAktiv = false;
}
else
{
((KI)AktiverSpieler).ÜberprüftKarten(GelegteKarten.Last());
IKarte gelegteKarteSpieler = ((KI)AktiverSpieler).LegtKarte();
if (VersuchtKarteLegen(gelegteKarteSpieler))
{
if (gelegteKarteSpieler.Typ == KartenTyp.VierZiehen)
{
vierziehenAktiv = true;
KartenZiehen += 4;
gelegteKarteSpieler.Farbe = KartenFarbe.Blau;
}
else if (gelegteKarteSpieler.Typ == KartenTyp.Farbwechsel)
{
gelegteKarteSpieler.Farbe = KartenFarbe.Blau;
}
LegtKarte(gelegteKarteSpieler);
}
else
{
if (((KI)AktiverSpieler).Ziehen != true)
{
GenugKartenImStapel();
((KI)AktiverSpieler).ZiehtKarte(Stapel);
((KI)AktiverSpieler).CardIndex = null;
NächsterSpieler();
}
}
}
}
private void SpielerGewinnt()
{
AllSpieler.Remove(AktiverSpieler);
FertigeSpieler.Add(AktiverSpieler);
SpielEnde();
}
private void GenugKartenImStapel()
{
if (Stapel.Count == 0)
{
if (GelegteKarten.Count > 4)
{
Stapel = new Queue<IKarte>(GelegteKarten.GetRange(0, GelegteKarten.Count - 1));
GelegteKarten.RemoveRange(0, GelegteKarten.Count - 1);
}
else
{
InitStapel();
}
}
}
public bool VersuchtKarteLegen(IKarte karte)
{
IKarte obersteKarte = GelegteKarten.Last();
//Schwarze Karten noch nicht da
if (vierziehenAktiv)
{
return false;
}
if (karte.Farbe == obersteKarte.Farbe)
{
if (karte.Typ == KartenTyp.Richtungswechsel)
{
Richtungswechsel();
}
else if (karte.Typ == KartenTyp.Aussetzen)
{
if (AllSpieler[1].Ki)
{
((KI)AllSpieler[1]).Aussetzen = true;
}
else
{
((Spieler)AllSpieler[1]).Aussetzen = true;
}
}
return true;
}
else if (karte.Typ == KartenTyp.Zahl && obersteKarte.Typ == KartenTyp.Zahl)
{
ZahlKarte zk = (ZahlKarte)karte;
ZahlKarte zk2 = (ZahlKarte)obersteKarte;
if (zk.Zahl == zk2.Zahl)
{
return true;
}
}
else if (karte.Typ == KartenTyp.Ziehen && obersteKarte.Typ == KartenTyp.Ziehen)
{
return true;
}
else if (karte.Typ == KartenTyp.Richtungswechsel && obersteKarte.Typ == KartenTyp.Richtungswechsel)
{
Richtungswechsel();
return true;
}
else if (karte.Typ == KartenTyp.Aussetzen && obersteKarte.Typ == KartenTyp.Aussetzen)
{
if (AllSpieler[1].Ki)
{
((KI)AllSpieler[1]).Aussetzen = true;
}
else
{
((Spieler)AllSpieler[1]).Aussetzen = true;
}
return true;
}
else if (karte.Farbe == KartenFarbe.Schwarz)
{
return true;
}
return false;
}
private void Richtungswechsel()
{
AllSpieler.Reverse();
}
private void NächsterSpieler()
{
AllSpieler.Remove(AktiverSpieler);
AllSpieler.Add(AktiverSpieler);
Spielzug();
}
private void InitStapel()
{
foreach (KartenFarbe farbe in Enum.GetValues(typeof(KartenFarbe)))
{
if (farbe == KartenFarbe.Schwarz)
{
Stapel.Enqueue(new FarbwechselKarte());
Stapel.Enqueue(new FarbwechselKarte());
Stapel.Enqueue(new FarbwechselKarte());
Stapel.Enqueue(new FarbwechselKarte());
Stapel.Enqueue(new VierZiehenKarte());
Stapel.Enqueue(new VierZiehenKarte());
Stapel.Enqueue(new VierZiehenKarte());
Stapel.Enqueue(new VierZiehenKarte());
continue;
}
Stapel.Enqueue(new ZahlKarte(0, farbe));
for (int j = 0; j < 2; j++)
{
for (int i = 1; i <= 9; i++)
{
Stapel.Enqueue(new ZahlKarte(i, farbe));
}
Stapel.Enqueue(new ZweiZiehenKarte(farbe));
Stapel.Enqueue(new RichtungswechselKarte(farbe));
Stapel.Enqueue(new AussetzenKarte(farbe));
}
}
Stapel = Stapel.Mischen();
}
public void SpielStart()
{
int count = 0;
while (AllSpieler.Count < 4)
{
AllSpieler.Add(new KI("Knud" + count, null));
count++;
}
Austeilen();
GelegteKarten.Add(Stapel.Dequeue());
if (GelegteKarten[0].Typ == KartenTyp.Ziehen)
{
((Spieler)AllSpieler[0]).Ziehen = true;
KartenZiehen = 2;
}
else if (GelegteKarten[0].Typ == KartenTyp.VierZiehen || GelegteKarten[0].Typ == KartenTyp.Farbwechsel)
{
GelegteKarten.Add(Stapel.Dequeue());
for (int i = 1; i < 99; i++)
{
if (GelegteKarten[i].Typ == KartenTyp.VierZiehen || GelegteKarten[i].Typ == KartenTyp.Farbwechsel)
{
GelegteKarten.Add(Stapel.Dequeue());
}
else
{
i = 100;
}
}
}
Spielzug();
}
public void SpielEnde()
{
List<ISpieler> AlleSpielerImSpiel = AllSpieler.Concat(FertigeSpieler).ToList();
foreach (ISpieler sp in AlleSpielerImSpiel)
{
if (sp.Karten.Count > 0)
{
sp.Karten.RemoveAll(x => (true));
}
}
AllSpieler.RemoveRange(0, AllSpieler.Count - 1);
FertigeSpieler.RemoveRange(0, FertigeSpieler.Count - 1);
Stapel.Clear();
GelegteKarten.RemoveRange(0, GelegteKarten.Count - 1);
AllSpieler = AlleSpielerImSpiel;
for (int i = 0; i < AllSpieler.Count; i++)
{
object ki = AllSpieler.Where(x => x.Ki == true).FirstOrDefault();
if (ki != null)
{
AllSpieler.Remove(AllSpieler.Where(x => x.Ki == true).FirstOrDefault());
i--;
}
}
foreach (ISpieler qwe in AllSpieler)
{
qwe.Spielstarten = false;
var obj = new { spielEnde = true };
var json = new JavaScriptSerializer().Serialize(obj);
qwe.Socket.Send(json);
}
if(AllSpieler.Count > 1)
{
ISpieler ersterSpieler = AllSpieler.First();
while(ersterSpieler.Spielstarten != true)
{
Thread.Sleep(200);
}
SpielStart();
}
}
private void SpielNeustart()
{
List<ISpieler> AlleSpielerImSpiel = AllSpieler.Concat(FertigeSpieler).ToList();
foreach (ISpieler sp in AlleSpielerImSpiel)
{
if (sp.Karten.Count > 0)
{
sp.Karten.RemoveRange(0, sp.Karten.Count - 1);
}
}
AllSpieler.RemoveRange(0, AllSpieler.Count - 1);
FertigeSpieler.RemoveRange(0, FertigeSpieler.Count - 1);
Stapel.Clear();
GelegteKarten.RemoveRange(0, GelegteKarten.Count - 1);
AllSpieler = AlleSpielerImSpiel;
InitStapel();
SpielStart();
}
}
}
|
namespace CarDealer.Services
{
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Data;
using Data.Interfaces;
using Models;
using Models.ViewModels;
public class CarsService : Service
{
public CarsService(IDataProvidable data) : base(data)
{
}
public CarsService() : this(new CarDealerData(new CarDealerContext()))
{
}
public IEnumerable<CarViewModel> GetAllCars()
{
return Mapper
.Map<IEnumerable<Car>, IEnumerable<CarViewModel>>(
this.Data
.Cars
.GetAll()
.OrderBy(c => c.Make)
.ThenBy(c => c.Model)
.ThenByDescending(c => c.TravelledDistance));
}
public IEnumerable<CarViewModel> GetCarFromMake(string make)
{
IEnumerable<Car> cars = this.Data.Cars.GetAll(c => c.Make == make);
return Mapper.Map<IEnumerable<Car>, IEnumerable<CarViewModel>>(cars);
}
public CarWithPartsViewModel GetCarWithPars(int id)
{
var car = this.Data.Cars.Find(id);
return Mapper.Map<Car, CarWithPartsViewModel>(car);
}
}
}
|
namespace RelationsLive
{
using System;
using System.Data.Entity;
using System.Linq;
using Models;
public class RelationsLiveContext : DbContext
{
public RelationsLiveContext()
: base("name=RelationsLiveContext")
{
Database.SetInitializer(new MyInitializer());
}
public virtual DbSet<Student> Students { get; set; }
public virtual DbSet<Address> Addresses { get; set; }
public virtual DbSet<Post> Posts { get; set; }
public virtual DbSet<Comment> Comments { get; set; }
public virtual DbSet<Town> Towns { get; set; }
public virtual DbSet<Person> People { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Project> Projects { get; set; }
public virtual DbSet<ProjectEmployees> ProjectEmployees { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HospitalSystem.Models
{
public class ExamineRecordList
{
public List<ExamineRecord> examineRecordList { set; get; }
public ExamineRecordList()
{
examineRecordList = new List<ExamineRecord>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BO;
using TpRace.Models;
namespace TpRace.Controllers
{
public class OrganizerController : Controller
{
// GET: Organizer
public ActionResult Index()
{
return View();
}
// GET: Organizer/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Organizer/Create
public ActionResult Create()
{
return View();
}
// POST: Organizer/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
private ActionResult CreateEdit(Organizer organizer=null)
{
var vm = new CreateEditOrganizerVM();
vm.Organizer =organizer ;
vm.races=organizer.Races ;
if (organizer.Races.Count == 0)
{
vm.Organizer.Races.id = Race.;
}
return View("CreateEdit", vm);
}
// GET: Organizer/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Organizer/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Organizer/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Organizer/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace evrostroy.Web.Models
{
public class NavModel
{
public List<string> BrandOutDoor { get; set; }
public List<string> BrandInDoor { get; set; }
public List<string> Attention { get; set; }
public Dictionary<string, string> CategoryD { get; set; }
public Dictionary<string, string> PodCategoryD { get; set; }
public List<string> Category { get; set; }
public List<string> Podcat1 { get; set; }
public List<string> Podcat2 { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleAppSpace_Objects
{
/// <summary>
/// clsse astratta per gli oggeti spaziali
/// </summary>
abstract class OggettoSpaziale
{
//costruttore contenente le coordinate dell'oggetto
public OggettoSpaziale(int x, int y)
{
X = x;
Y = y;
}
//coordinata x
public int X { get; set; }
public int Y { get; set; }
//metodo astratto Step
public abstract void Step();
/// <summary>
/// Stampa la matrice nella console
/// </summary>
/// <param name="matrice"></param>
protected static void StampaMatrice(ref string[,] matrice)
{
//ciclo in cui viene stampato l'elemento della matrice
for (int r = 0; r < matrice.GetLength(0); r++)
{
for (int c = 0; c < matrice.GetLength(1); c++)
Console.Write(matrice[r, c]);
//dopo aver scritto una riga va a capo
Console.Write("\n");
}
//Necessario per evitare che gli oggetti lampeggino
Thread.Sleep(100);
//Refresha la console per un'altra stampa
Console.Clear();
}
}
}
|
using ISE.Framework.Common.CommonBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISE.SM.Common.DTO
{
public partial class UserToRoleDto:BaseDto
{
public UserToRoleDto()
{
this.PrimaryKeyName = "UrId";
}
}
}
|
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Welic.Dominio.Models.Acesso.Dtos;
using Welic.Dominio.Models.Acesso.Servicos;
namespace WebApi.API.Controllers
{
[Authorize]
[RoutePrefix("api/Dispositivo")]
public class DispositivosController : BaseController
{
public readonly IServicoDispositivo _servico;
public DispositivosController(IServicoDispositivo servico)
{
_servico = servico;
}
[HttpGet]
[Route("GetById/{id}")]
public Task<HttpResponseMessage> GetById(string id)
{
return CriaResposta(HttpStatusCode.OK, _servico.ConsultarPorId(id));
}
[HttpPost]
[Route("salvar")]
public Task<HttpResponseMessage> salvar([FromBody] DispositivoDto dispositivoDto)
{
return CriaResposta(HttpStatusCode.OK, _servico.Salvar(dispositivoDto));
}
[HttpPost]
[Route("alterar")]
public Task<HttpResponseMessage> Alterar([FromBody]DispositivoDto dispositivoDto)
{
return CriaResposta(HttpStatusCode.OK, _servico.Alterar(dispositivoDto));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.