text
stringlengths 13
6.01M
|
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hoofdstuk_7_Facade
{
public class Projector
{
public void On()
{
Console.WriteLine("Projector has turned on");
}
public void WideScreenMode()
{
Console.WriteLine("Projector set to wide screen mode");
}
public void Off()
{
Console.WriteLine("Projector has turned off");
}
}
}
|
using System;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Event Reference of type `float`. Inherits from `AtomEventReference<float, FloatVariable, FloatEvent, FloatVariableInstancer, FloatEventInstancer>`.
/// </summary>
[Serializable]
public sealed class FloatEventReference : AtomEventReference<
float,
FloatVariable,
FloatEvent,
FloatVariableInstancer,
FloatEventInstancer>, IGetEvent
{ }
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled.
// If you have enabled NRTs for your project, then un-comment the following line:
// #nullable disable
namespace Project3.Models
{
public partial class TblOrderedLaptop
{
public int Oid { get; set; }
public int? Lid { get; set; }
public int? SellerId { get; set; }
public int? CustomerId { get; set; }
public virtual TblCustomer Customer { get; set; }
public virtual AvailableLaptop L { get; set; }
public virtual TblSeller Seller { get; set; }
}
}
|
namespace API.Repositories
{
using System.Collections.Concurrent;
using System.Collections.Generic;
using API.Models;
public class ValueRepository : IValueRepository
{
private readonly ConcurrentDictionary<int, Value> store = new ConcurrentDictionary<int, Value>();
public IEnumerable<Value> Get()
{
return this.store.Values;
}
public Value Get(int id)
{
this.store.TryGetValue(id, out var value);
return value;
}
public Value Upsert(Value value)
{
this.store.AddOrUpdate(value.Id, value, (key, oldValue) => value);
return value;
}
public void Delete(int id)
{
this.store.TryRemove(id, out _);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Xml.Serialization;
using DBDiff.Schema.Model;
namespace DBDiff.Schema.Sybase.Model
{
public class Column : SybaseSchemaBase
{
private Boolean identity;
private string type;
private int size;
private Boolean nullable;
private int precision;
private int scale;
private Boolean hasIndexDependencies;
private int position;
public Column(Table parent):base(StatusEnum.ObjectTypeEnum.Column)
{
this.Parent = parent;
}
/// <summary>
/// Clona el objeto Column en una nueva instancia.
/// </summary>
public Column Clone(Table parent)
{
Column col = new Column(parent);
col.Id = this.Id;
col.Identity = this.Identity;
col.HasIndexDependencies = this.HasIndexDependencies;
col.Name = this.Name;
col.Nullable = this.Nullable;
col.Precision = this.Precision;
col.Scale = this.Scale;
col.Size = this.Size;
col.Status = this.Status;
col.Type = this.Type;
col.Position = this.Position;
//col.Constraints = this.Constraints.Clone(this);
return col;
}
public int Position
{
get { return position; }
set { position = value; }
}
/// <summary>
/// Cantidad de digitos que permite el campo (solo para campos Numeric).
/// </summary>
public int Scale
{
get { return scale; }
set { scale = value; }
}
/// <summary>
/// Cantidad de decimales que permite el campo (solo para campos Numeric).
/// </summary>
public int Precision
{
get { return precision; }
set { precision = value; }
}
/// <summary>
/// Indica si el campos permite valores NULL o no.
/// </summary>
public Boolean Nullable
{
get { return nullable; }
set { nullable = value; }
}
/// <summary>
/// Indica en bytes, el tamaņo del campo.
/// </summary>
public int Size
{
get { return size; }
set { size = value; }
}
/// <summary>
/// Nombre del tipo de dato del campo.
/// </summary>
public string Type
{
get { return type; }
set { type = value; }
}
/// <summary>
/// Indica si la columna es usada en un indice.
/// </summary>
public Boolean HasIndexDependencies
{
get { return hasIndexDependencies; }
set { hasIndexDependencies = value; }
}
/// <summary>
/// Indica si es campo es Identity o no.
/// </summary>
public Boolean Identity
{
get { return identity; }
set { identity = value; }
}
/*public Constraints DependenciesConstraint(string columnName)
{
Table ParenTable = (Table)Parent;
Constraints cons = new Constraints(ParenTable);
for (int index = 0; index < ParenTable.Constraints.Count; index++)
{
if (ParenTable.Constraints[index].Columns.Find(columnName) != null)
{
cons.Add(ParenTable.Constraints[index]);
}
}
return cons;
}*/
/// <summary>
/// Devuelve el schema de la columna en formato SQL.
/// </summary>
public string ToSQL(Boolean sqlConstraint)
{
string sql = "";
sql += "[" + Name + "] ";
sql += Type;
if (Type.Equals("varbinary") || Type.Equals("varchar") || Type.Equals("char") || Type.Equals("nchar") || Type.Equals("nvarchar"))
{
if (Type.Equals("nchar") || Type.Equals("nvarchar"))
sql += " (" + (Size / 2).ToString(CultureInfo.InvariantCulture) + ")";
else
sql += " (" + Size.ToString(CultureInfo.InvariantCulture) + ")";
}
if (Type.Equals("numeric") || Type.Equals("decimal")) sql += " (" + Precision.ToString(CultureInfo.InvariantCulture) + "," + Scale.ToString(CultureInfo.InvariantCulture) + ")";
if (Identity) sql += " IDENTITY ";
if (Nullable)
sql += " NULL";
else
sql += " NOT NULL";
return sql;
}
/// <return>
/// Compara dos campos y devuelve true si son iguales, false en caso contrario.
/// </summary>
/// <param name="destino">
/// Objeto Column con el que se desea comparar.
/// </param>
public StatusEnum.ObjectStatusType CompareStatus(Column destino)
{
if (destino != null)
{
StatusEnum.ObjectStatusType status = StatusEnum.ObjectStatusType.OriginalStatus;
if (!Compare(this, destino))
{
if (destino.Identity == this.Identity)
{
}
}
return status;
}
else
throw new ArgumentNullException("destino");
}
/// <summary>
/// Compara solo las propiedades de dos campos relacionadas con los Identity. Si existen
/// diferencias, devuelve falso, caso contrario, true.
/// </summary>
public static Boolean CompareIdentity(Column origen, Column destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if (origen.Identity != destino.identity) return false;
return true;
}
/// <summary>
/// Compara dos campos y devuelve true si son iguales, caso contrario, devuelve false.
/// </summary>
public static Boolean Compare(Column origen, Column destino)
{
if (destino == null) throw new ArgumentNullException("destino");
if (origen == null) throw new ArgumentNullException("origen");
if (origen.Nullable != destino.nullable) return false;
if (origen.Precision != destino.precision) return false;
if (origen.Scale != destino.scale) return false;
//Si el tamaņo de un campo Text cambia, entonces por la opcion TextInRowLimit.
if ((origen.Size != destino.size) && (origen.Type.Equals(destino.Type)) && (!origen.Type.Equals("text"))) return false;
if (!origen.Type.Equals(destino.type)) return false;
return CompareIdentity(origen, destino);
}
}
}
|
using DrugMgmtSys.codes;
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 DrugMgmtSys
{
public partial class Main : Form
{
private int KEY;
private bool canOrder=false;
Order order = null;
public bool CanOrder
{
get
{
return canOrder;
}
set
{
canOrder = value;
}
}
public Main()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ForbidSortColumn(dataGridView_K);
//显示
BindAll_X();
}
#region 查询按钮
/// <summary>
/// 药品销售页面查询按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//查询
BindByTrim_X();
}
/// <summary>
/// 库存页面查询按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button6_Click(object sender, EventArgs e)
{
BindByTrim_K();
}
#endregion
#region 显示全部按钮
/// <summary>
/// 销售页面显示全部按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
BindAll_X();
}
/// <summary>
/// 库存页面显示全部按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button7_Click(object sender, EventArgs e)
{
BindAll_K();
}
#endregion
#region 出售按钮
private void dataGridView_X_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex != 0 || e.RowIndex == -1)
{
return;
}
if (CanOrder)
{
double num = getIntputNum();
//获取当前行的索引
int index = dataGridView_X.CurrentCell.RowIndex;
//获取当前行对应的“编号”列的值(主键)
int key = Int32.Parse(dataGridView_X.Rows[index].Cells["编号"].Value.ToString());
//更新库存
updateReserve(num, key);
Drug drug = new Drug(key);
//向订单添加
order.add(drug);
order.setNum(num);
BindAll_X();
}
else
{
MessageBox.Show("请先点击上方“开处药方”按钮,建立新的药方再行出售!","温馨提示");
}
}
#endregion
#region 查询所有并绑定
/// <summary>
/// 销售页面查询所有并绑定
/// </summary>
protected void BindAll_X()
{
string sql_select_drug_X = "SELECT d_id,d_name,u_name,d_spec,d_reserve,d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id";
DataSet ds = MySqlTools.GetDataSet(sql_select_drug_X);
dataGridView_X.DataSource = ds.Tables[0];
}
/// <summary>
/// 库存页面查询所有并绑定
/// </summary>
protected void BindAll_K()
{
string sql_select_drug_K = "SELECT d_id,d_name,u_name,d_spec,d_origin,d_lot_num,d_reserve,d_w_price,d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id";
DataSet ds = MySqlTools.GetDataSet(sql_select_drug_K);
DataTable dt = ds.Tables[0];
//添加一列“tb_progit”
dt.Columns.Add("tb_progit");
//为该列的每一行赋值
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["tb_progit"] = Convert.ToDouble(dt.Rows[i][8]) - Convert.ToDouble(dt.Rows[i][7]);
}
dataGridView_K.DataSource = dt;
getSum();
}
/// <summary>
/// 销售记录查询
/// </summary>
protected void BindAndShow()
{
DateTime dt = dateTimePicker1.Value;
string time=dt.ToLongDateString().ToString();
string sql =string .Format("SELECT o_id,o_name,o_num,o_r_price,o_money FROM tb_order where o_time='{0}'", time);
DataSet ds = MySqlTools.GetDataSet(sql);
DataTable dataTable = ds.Tables[0];
dataGridView_M.DataSource=dataTable;
//求和
double sum_m = 0;
double sum_r = 0;
for (int i = 0; i < dataGridView_M.Rows.Count; i++)
{
sum_m += Convert.ToDouble(dataGridView_M.Rows[i].Cells["利润"].Value);
sum_r += Convert.ToDouble(dataGridView_M.Rows[i].Cells["售价"].Value);
}
lb_r.Text = sum_r.ToString()+"元";
lb_m.Text = sum_m.ToString() + "元";
}
#endregion
#region 条件查询并绑定
/// <summary>
/// 销售页面按条件绑定
/// </summary>
private void BindByTrim_X()
{
string d_name = string.Format("'%{0}%'", textBox_select_X.Text);
string sql_select_by_d_name = "SELECT d_id,d_name,u_name,d_spec,d_reserve,d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id AND d_name LIKE " + d_name;
DataSet ds = MySqlTools.GetDataSet(sql_select_by_d_name);
dataGridView_X.DataSource = ds.Tables[0];
}
/// <summary>
/// 库存页面按条件绑定
/// </summary>
private void BindByTrim_K()
{
string d_name = string.Format("'%{0}%'", textBox_select_K.Text);
string sql_select_by_d_name = "SELECT d_id, d_name, u_name, d_spec, d_origin, d_lot_num, d_reserve, d_w_price, d_r_price FROM tb_drug INNER JOIN tb_unit ON d_unit = u_id WHERE d_unit = u_id AND d_name LIKE " + d_name;
DataSet ds = MySqlTools.GetDataSet(sql_select_by_d_name);
DataTable dt = ds.Tables[0];
//添加一列“tb_progit”
dt.Columns.Add("tb_progit");
//为该列的每一行赋值
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["tb_progit"] = Convert.ToDouble(dt.Rows[i][8]) - Convert.ToDouble(dt.Rows[i][7]);
}
dataGridView_K.DataSource = dt;
getSum();
}
#endregion
/// <summary>
/// 计算库存合计信息
/// </summary>
private void getSum()
{
double sum_w = 0;
double sum_r = 0;
double sum_money = 0;
for (int i = 0; i < dataGridView_K.Rows.Count; i++)
{
sum_w += Convert.ToDouble(dataGridView_K.Rows[i].Cells["批发价"].Value)*Convert.ToDouble(dataGridView_K.Rows[i].Cells["库存"].Value);
sum_r += Convert.ToDouble(dataGridView_K.Rows[i].Cells["零售"].Value) * Convert.ToDouble(dataGridView_K.Rows[i].Cells["库存"].Value);
sum_money += Convert.ToDouble(dataGridView_K.Rows[i].Cells["利"].Value) * Convert.ToDouble(dataGridView_K.Rows[i].Cells["库存"].Value);
}
lb_w_sum.Text = sum_w.ToString() + "元";
lb_r_sum.Text = sum_r.ToString() + "元";
lb_money.Text = sum_money.ToString() + "元";
}
#region 清空文本框
private void textBox_select_X_MouseClick(object sender, MouseEventArgs e)
{
textBox_select_X.Text = "";
}
private void textBox_select_K_MouseClick(object sender, MouseEventArgs e)
{
textBox_select_K.Text = "";
}
#endregion
#region 获取输入
/// <summary>
/// 获取用户输入数量
/// </summary>
/// <returns>输入的值</returns>
private double getIntputNum()
{
InputNumDiaLog form = new InputNumDiaLog();
form.ShowDialog();
return form.Input;
}
#endregion
/// <summary>
/// 更新库存方法
/// </summary>
/// <param name="num">用户输入</param>
/// <param name="key">主键</param>
/// <param name="b">true为增加,false为减少</param>
private void updateReserve(double num,int key)
{
if (num==0)
{
return;
}
string sql_SelectReserve = "SELECT d_reserve FROM tb_drug WHERE d_id=" + key;
double reserve = (double)MySqlTools.ExecuteScalar(sql_SelectReserve);
if (reserve - num<0)
{
MessageBox.Show(" 该药品剩余库存为:" + reserve + "\n 库存不足,请尽快补货!", "温馨提示");
}
else
{
string sql_updateReserve = string.Format("UPDATE tb_drug SET d_reserve={0} WHERE d_id={1}", reserve - num, key);
// sql_select_r_price = "SELECT d_r_price FROM tb_drug WHERE d_id=" + key;
//double money =num*(double)MySqlTools.ExecuteScalar(sql_select_r_price);
if (MySqlTools.ExecuteNonQuery(sql_updateReserve) == 1)
{
MessageBox.Show("出库成功!", "温馨提示");
}
else
{
MessageBox.Show("出库失败!", "温馨提示");
}
}
//}
}
#region 库存页面删除、修改按钮
/// <summary>
/// 修改药品信息按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (KEY==0)
{
MessageBox.Show("请先选中一行数据!", "温馨提示");
return;
}
//创建drug,获取当前信息
Drug drug = new Drug(KEY);
InfoMgmtForm infoForm = new InfoMgmtForm(KEY);
//为组件赋值:当前值
infoForm.setValue(drug.Name, drug.Unit, drug.Spec, drug.Origin, drug.Lot_num, drug.Reserve, drug.W_price, drug.R_price);
infoForm.asChange();//更改按钮
infoForm.ShowDialog();
BindAll_K();
}
/// <summary>
/// 删除按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
string caption = "温馨提示";
string message = "是否删除该条数据?";
MessageBoxButtons btn = MessageBoxButtons.YesNo;
DialogResult result = new DialogResult();
result = MessageBox.Show(message, caption, btn);
if (result == System.Windows.Forms.DialogResult.Yes)
{
string sql = "delete from tb_drug where d_id=" + KEY;
if (MySqlTools.ExecuteNonQuery(sql) > 0)
{
MessageBox.Show("成功删除该条记录!", "温馨提示");
BindAll_K();
}
}
}
#endregion
#region 添加数据
/// <summary>
/// 添加药品
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
InfoMgmtForm infoForm = new InfoMgmtForm();
infoForm.ShowDialog();
//BindAll_K();
tabControl_main.SelectedIndex = 0;
tabControl_main.SelectedIndex = 1;
}
#endregion
#region 选项卡切换处理
/// <summary>
/// 更改选项卡后触发的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tabControl_main_SelectedIndexChanged(object sender, EventArgs e)
{
string i = tabControl_main.SelectedTab.Text;
switch (i)
{
case "药品销售":
BindAll_X();
break;
case "药品库存信息管理":
BindAll_K();
break;
case "销售记录":
BindAndShow();
break;
}
}
#endregion
#region 处理操作
/// <summary>
/// 点击单元格时,获取当前行索引
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView_K_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex==-1)
{
return;
}
this.dataGridView_K.Rows[e.RowIndex].Selected = true;//是否选中当前行
int index = e.RowIndex;
//获取当前行对应的“编号”列的值(主键)
DataTable dt =(DataTable)dataGridView_K.DataSource;
KEY = (int)dt.Rows[index][0];
}
/// <summary>
/// 禁止DataGrideView排序 加载时调用
/// </summary>
/// <param name="dgv"></param>
public static void ForbidSortColumn(DataGridView dgv)
{
for (int i = 0; i < dgv.Columns.Count; i++)
{
dgv.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
/// <summary>
/// 检索时间改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
BindAndShow();
}
#endregion
/// <summary>
/// 版权方网站
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void label14_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://www.llanc.cn/");
}
/// <summary>
/// 开处药方
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button8_Click(object sender, EventArgs e)
{
if (button8.Text=="开处药方")
{
button8.Text = "结算";
button8.ForeColor = Color.Red;
CanOrder = true;//可以出售
order = new Order();//新建订单
MessageBox.Show("创建药方成功,请点击“出售”按钮添加药品", "温馨提示");
}
else if (button8.Text == "结算")
{
button8.Text = "开处药方";
button8.ForeColor = Color.Green;
CanOrder = false;//不可出售
ShowOrder showOrderForm = new ShowOrder(order.getMessage());
showOrderForm.ShowDialog();
}
}
#region 登录处理
/// <summary>
/// 登录按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_login_Click(object sender, EventArgs e)
{
string pwd = tb_pwd.Text;
string sql = string.Format("SELECT * FROM tb_pwd WHERE pwd='{0}'", pwd);
try
{
if ((int)MySqlTools.ExecuteScalar(sql) == 1)
{
panl_Login.Visible = false;
}
}
catch (Exception)
{
MessageBox.Show("您的密码输入有误,请重新输入!", "温馨提示");
}
}
/// <summary>
/// 修改密码按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void bun_ch_Click(object sender, EventArgs e)
{
string sql = string.Format("UPDATE tb_pwd SET pwd='{0}' where id=1",tb_pwdCh.Text);
if ((int)MySqlTools.ExecuteNonQuery(sql)==1)
{
MessageBox.Show("密码更改成功,请牢记!\n" + tb_pwdCh.Text, "温馨提示");
}
else
{
MessageBox.Show("密码更改失败!", "温馨提示");
}
}
#endregion
private void lb__Click(object sender, EventArgs e)
{
}
#region 药品销售记录删除
private void button9_Click(object sender, EventArgs e)
{
string caption = "温馨提示";
string message = "是否删除该记录?";
MessageBoxButtons btn = MessageBoxButtons.YesNo;
DialogResult result = new DialogResult();
result = MessageBox.Show(message, caption, btn);
if (result == System.Windows.Forms.DialogResult.Yes)
{
DateTime dt = dateTimePicker1.Value;
string time = dt.ToLongDateString().ToString();
string sql_day = string.Format("delete from tb_order where o_time='{0}'", time);
if (MySqlTools.ExecuteNonQuery(sql_day) > 0)
{
MessageBox.Show("成功删除该记录!", "温馨提示");
BindAndShow();
}
}
}
private void button10_Click(object sender, EventArgs e)
{
string caption = "温馨提示";
string message = "是否删除该记录?";
MessageBoxButtons btn = MessageBoxButtons.YesNo;
DialogResult result = new DialogResult();
result = MessageBox.Show(message, caption, btn);
if (result == System.Windows.Forms.DialogResult.Yes)
{
DateTime dt = dateTimePicker1.Value;
string time = dt.ToLongDateString().ToString();
string sql ="delete from tb_order";
if (MySqlTools.ExecuteNonQuery(sql) > 0)
{
MessageBox.Show("成功删除该记录!", "温馨提示");
BindAndShow();
}
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MethodsExercise
{
class Program
{
static void Main(string[] args)
{
////Method One
ClassNum Dog = new ClassNum();
//int input1 = 8;
//int Results = Dog.NumMethod(input1);
//Console.WriteLine(Results);
//Console.ReadLine();
//Method Two
float input2 = 4.25f;
float Results2 = Dog.NumMethod(input2);
Console.WriteLine(Results2);
Console.ReadLine();
//Method Three
string input3 = "20";
//int ren = Convert.ToInt32(input3);
int Results3 = Dog.NumMethod(input3);
Console.WriteLine(Results3);
Console.ReadLine();
}
}
}
|
namespace DataLayer
{
using System;
using System.Data;
using System.Data.SqlClient;
public class TravelManager
{
public DataSet SearchTravelDetails(string tr_no)
{
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@tr_no", tr_no) };
return clsConnectionString.returnConnection.executeSelectQueryDataSet("usp_trl_travel_details", CommandType.StoredProcedure, parameterArray);
}
public DataTable SearchTravelQuery(string trav_name, string destination, string dateFrom, string dateTo, string capacity, string travel_type, string tr_no, string travel_mode, string is_emergency)
{
DateTime time = (dateFrom != "") ? Convert.ToDateTime(dateFrom) : Convert.ToDateTime("1753-01-01");
DateTime time2 = (dateTo != "") ? Convert.ToDateTime(dateTo) : DateTime.MaxValue;
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@traveller_name", trav_name.Trim()), new SqlParameter("@destination", destination.Trim()), new SqlParameter("@start_date", time), new SqlParameter("@end_date", time2), new SqlParameter("@capacity", capacity), new SqlParameter("@travel_type", travel_type), new SqlParameter("@tr_no", tr_no.Trim()), new SqlParameter("@travel_mode", travel_mode), new SqlParameter("@is_emergency", is_emergency) };
return clsConnectionString.returnConnection.executeSelectQuery("usp_trl_travel_query", CommandType.StoredProcedure, parameterArray);
}
public DataTable SearchTRLAsOfDate(string source_name)
{
SqlParameter[] parameterArray = new SqlParameter[] { new SqlParameter("@source_name", source_name) };
return clsConnectionString.returnConnection.executeSelectQuery("usp_upload_log_list", CommandType.StoredProcedure, parameterArray);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace FileIO
{
class Program
{
static void Main(string[] args)
{
string input = ""; // nuskaityk failą į input kintamąjį
FindSportsmenWithLongestFullname(input);
FindSportsmenWithLongestFullnameLikeAPro(input);
SortSportsmenByFullnameLength(input);
}
public static void FindSportsmenWithLongestFullname(string input)
{
//sukarpyk input į string[]
//surask ilgiausią vardą
//išvesk į failą longestNameV1.txt
}
public static void FindSportsmenWithLongestFullnameLikeAPro(string input)
{
//sukarpyk input į List<string>
//surask ilgiausią vardą
//išvesk į failą longestNameV2.txt
}
public static void SortSportsmenByFullnameLength(string input)
{
//sukarpyk input į List<string>
//surūšiuok pagal vardo ilgį
//išvesk į failą sortedNames.txt
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AtendimentoProntoSocorro.Data;
using AtendimentoProntoSocorro.Models;
using AtendimentoProntoSocorro.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AtendimentoProntoSocorro.Controllers
{
public class DadosClinicosController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IDadosClinicosRepository dadosClinicosRepository;
public DadosClinicosController(ApplicationDbContext context, IDadosClinicosRepository dadosClinicosRepository)
{
_context = context;
this.dadosClinicosRepository = dadosClinicosRepository;
}
public IActionResult Atender(int idFicha)
{
if (ModelState.IsValid)
{
var dados = dadosClinicosRepository.GetDadosClinicos(idFicha);
return View(dados);
}
return View();
}
[HttpPost]
public async Task<IActionResult> GravarDadosClinicos(DadoClinico dadosClinicos)
{
if (ModelState.IsValid)
{
//var _idFicha =
//Ficha ficha = fichaRepository.GetFicha(_idFicha);
_context.Add(dadosClinicos);
await _context.SaveChangesAsync();
return RedirectToAction("Aguardando", "Ficha");
}
return View(dadosClinicos);
}
// GET: DadosClinicos
public ActionResult Index()
{
return View();
}
}
}
|
#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BP12;
using DChild.Gameplay.Objects;
using DChild.Gameplay.Objects.Characters.Enemies;
using Sirenix.OdinInspector;
using UnityEngine;
namespace DChildDebug
{
public class DebugMinionSpawner : SingletonBehaviour<DebugMinionSpawner>
{
public DebugMinionDatabase database;
public Transform spawnPoint;
public Transform m_target;
public static TypeCache<Minion> m_minionCache;
private static Dictionary<Type, Type> m_controllerCache;
private static GameObject m_minionInstance;
public static int m_minionIndex;
public static Transform target => m_instance.m_target;
public static void NextMinion()
{
DestroyMinion();
IterateIndex(1);
SpawnMinion();
}
public static void PreviousMinion()
{
DestroyMinion();
IterateIndex(-1);
SpawnMinion();
}
public static void SpawnMinion(string minionName)
{
DestroyMinion();
var minionType = m_minionCache.GetType(minionName);
m_minionIndex = m_instance.database.GetIndexOfMinionType(minionType);
SpawnMinion();
}
private static void DestroyMinion()
{
if (m_minionInstance != null)
{
Destroy(m_minionInstance);
Destroy(m_instance.GetComponent<MinionAttackDebugger>());
}
}
private static void IterateIndex(int iteration) => m_minionIndex = (int)Mathf.Repeat(m_minionIndex + iteration, m_instance.database.Count);
private static void SpawnMinion()
{
var spawnPoint = m_instance.spawnPoint;
m_minionInstance = Instantiate(m_instance.database.GetMinion(m_minionIndex), spawnPoint.position, Quaternion.identity);
var minionSentience = m_minionInstance.GetComponent<ISentientBeing>();
minionSentience.EnableBrain(false);
var controller = (MinionAttackDebugger)m_instance.gameObject.AddComponent(m_controllerCache[minionSentience.GetType()]);
controller.Set(m_minionInstance.GetComponent<Minion>());
}
protected override void Awake()
{
base.Awake();
m_minionCache = new TypeCache<Minion>();
InstantiateControllerCache();
}
private static void InstantiateControllerCache()
{
var controllerGO = new GameObject("Something");
m_controllerCache = new Dictionary<Type, Type>();
var attackDebuggers = Reflection.GetDerivedClasses(typeof(MinionAttackDebugger));
for (int i = 0; i < attackDebuggers.Length; i++)
{
var type = attackDebuggers[i];
var controller = (MinionAttackDebugger)controllerGO.AddComponent(type);
m_controllerCache.Add(controller.monsterType, type);
}
Destroy(controllerGO);
}
}
}
#endif
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelftTools.Controls.Swf.Test.Table.TestClasses
{
public class ClassWithTwoProperties
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using cyrka.api.common.events;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace cyrka.api.infra.stores.events
{
public class MongoEventStore : IEventStore, IDisposable
{
const string CollectionKeyName = "events";
public string NexterChannelKey => CollectionKeyName;
public MongoEventStore(IMongoDatabase mongoDatabase, IEnumerable<IDbMapping> maps)
{
foreach (var map in maps)
{
map.DefineMaps();
}
_eventsChannel = new Subject<Event>();
_mDb = mongoDatabase;
try
{
_eventsCollection = _mDb.GetCollection<Event>(CollectionKeyName);
}
catch (Exception e)
{
throw e;
}
}
public async Task<ulong> GetLastStoredId()
{
try
{
return (
await _eventsCollection.AsQueryable()
.OrderByDescending(e => e.Id)
.FirstOrDefaultAsync()
)?
.Id ?? 0;
}
catch (Exception e)
{
throw e;
}
}
public async Task<Event[]> FindAllAfterId(ulong id)
{
return (
await _eventsCollection.AsQueryable()
.Where(e => e.Id > id)
.OrderBy(e => e.Id)
.ToListAsync()
)
.ToArray();
}
public async Task<Event[]> FindAllOfAggregateById<TAggregate>(string aggregateId)
where TAggregate : class
{
var aggregateName = typeof(TAggregate).Name;
var query = _eventsCollection.AsQueryable()
.Where(e => e.EventData.AggregateType == aggregateName && e.EventData.AggregateId == aggregateId);
return (await query.OrderBy(e => e.Id).ToListAsync()).ToArray();
}
public async Task<Event[]> FindLastNWithDataOf<TEventData>(int n, Expression<Func<Event, bool>> eventDataPredicate = null)
where TEventData : EventData
{
var query = _eventsCollection.AsQueryable()
.Where(e => e.EventData is TEventData);
if (eventDataPredicate != null)
query = query.Where(eventDataPredicate);
return (await query.OrderByDescending(e => e.Id).Take(n).ToListAsync()).ToArray();
}
public async Task Store(Event @event)
{
try
{
await _eventsCollection.InsertOneAsync(@event);
_eventsChannel.OnNext(@event);
}
catch (Exception e)
{
throw e;
}
}
public IObservable<Event> AsObservable(bool fromStart = false)
{
if (fromStart)
{
var storedEvents = _eventsCollection.AsQueryable()
.OrderBy(e => e.Id)
.ToObservable();
return storedEvents.Concat(_eventsChannel.AsObservable());
}
return _eventsChannel.AsObservable();
}
public void Dispose()
{
if (_eventsChannel != null && !_eventsChannel.IsDisposed)
{
_eventsChannel.OnCompleted();
_eventsChannel.Dispose();
}
}
private readonly IMongoDatabase _mDb;
private readonly IMongoCollection<Event> _eventsCollection;
private readonly Subject<Event> _eventsChannel;
}
}
|
using System;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography.X509Certificates;
namespace assign_cab301
{
class Program
{
//Create objects of the class that we have written
private static MovieCollection movieCollectionObj;
private static MemberCollection memberCollectionObj;
private static Member memberObj;
/// <summary>
/// This is the main method and is the starting point for the program
/// This is the place where everything gets called.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
int userInputs = -1;
movieCollectionObj = new MovieCollection();
memberCollectionObj = new MemberCollection();
do
{
Console.WriteLine(
"\nWelcome to the Community Library\n" +
"===========Main Menu============\n" +
" 1. Staff Login\n" +
" 2. Membr Login\n" +
" 0. Exit\n" +
"================================\n");
userInputs = getUserInputsInt(" Please make a selection (1-2, or 0 to exit): ", 0, 2);
if (userInputs == 1 || userInputs == 2)
{
Console.Write("Enter Username: (LastnameFirstname): ");
string uName = Console.ReadLine();
Console.Write("Enter Password: ");
string uPass = Console.ReadLine();
if (userInputs == 1)
{
if (uName == "staff" && uPass == "today123")
{
Console.WriteLine();
menuForStaffAndItsOperation();
Console.WriteLine();
}
else
{
Console.WriteLine("Incorrect Password or Username! Try again\n");
}
}
if (userInputs == 2)
{
memberObj = memberCollectionObj.userLoginToLibrary(uName, uPass);
if (memberObj != null)
{
Console.WriteLine();
menuForMemberAndItsOperation();
Console.WriteLine();
}
else
{
Console.WriteLine("Incorrect Password or Username! Try again.\n");
}
}
}
} while (userInputs != 0);
}
/// <summary>
/// This function is for the member's menu to allow members do the
/// operation of displaying, borrowing, returning, listing,
/// displaying top 10 movies and retuning to main menu.
/// </summary>
public static void menuForMemberAndItsOperation()
{
int userInputs = -1;
while (userInputs != 0)
{
Console.WriteLine(
"\n\n" +
"===========Member Menu============\n" +
"1. Display all movies\n" +
"2. Borrow a movie DVD\n" +
"3. Return a movie DVD\n" +
"4. List current borrowed movie DVDs\n" +
"5. Display top 10 most popular movies\n" +
"0. Return to main menu\n" +
"==================================\n");
userInputs = getUserInputsInt(" Please make a selection (1-5 or 0 to return to main menu): ", 0, 5);
switch (userInputs)
{
case 0:
//exit to main menu
break;
case 1:
memberDisplayEntireAddedMovies();
break;
case 2:
memberBorrowingMovies();
break;
case 3:
memberReturnsMovieToLibrary();
break;
case 4:
showAListForEachMemberOfCurrentlyBorrowedMovies();
break;
case 5:
showTheTopTenPopularMovies();
break;
}
}
}
/// <summary>
/// This function is a helper function which helps the member-menu functionality and helping in showing top ten moives
/// </summary>
private static void showTheTopTenPopularMovies()
{
movieCollectionObj.showingPopularMoviesRentedTenTimes();
}
/// <summary>
/// This function shows a list of movies each member have borrowed.
/// </summary>
private static void showAListForEachMemberOfCurrentlyBorrowedMovies()
{
memberObj.showMovieDVDsCurrentlyBorrowed();
}
/// <summary>
/// This function is also a member functionality which allow the member to return movies to the library.
/// </summary>
private static void memberReturnsMovieToLibrary()
{
Console.Write("Enter movie title: ");
string userInput = Console.ReadLine();
if (memberObj.checkIsMovieBorrowed(userInput))
{
memberObj.memberReturnedMovie(userInput);
Console.WriteLine("You have successfully returned Movie DVD \n");
}
else
{
Console.WriteLine("You have not borrowed movie now.\n\n");
}
}
/// <summary>
/// This function allow the members to borrow movies which is a helper function of the member-menu functionality.
/// </summary>
public static void memberBorrowingMovies()
{
Console.Write("Enter movie title: ");
string userInput = Console.ReadLine();
if (!memberObj.checkIsMovieBorrowed(userInput))
{
if (movieCollectionObj.movieBorrowingProcess(userInput)){
memberObj.borrowingMovie(userInput);
Console.WriteLine("You borrowed " + userInput + "\n");
}
}
else
{
Console.WriteLine("You have already borrowed movie.\n");
}
}
/// <summary>
/// This function is a helper function for the member-menu which allow users to display all available movies.
/// </summary>
public static void memberDisplayEntireAddedMovies()
{
movieCollectionObj.showMoviesInOrder();
}
/// <summary>
/// This method/function is for staff menu and it's operationss, its display and its error handling.
/// </summary>
private static void menuForStaffAndItsOperation()
{
int userInputs = -1;
while(userInputs != 0)
{
Console.WriteLine(
"\n===========Staff Menu============\n" +
"1. Add a new movie DVD\n" +
"2. Remove a movie DVD\n" +
"3. Register a new member\n" +
"4. Find a registered member's phone number\n" +
"0. Return to main menu\n" +
"==================================\n");
userInputs = getUserInputsInt(" Please make a selection (1-4 or 0 to return to main menu): ", 0, 4);
switch (userInputs)
{
case 0:
//exit to main menu
break;
case 1:
functionalityOfNewMovieAddition();
break;
case 2:
staffRemoveMovie();
break;
case 3:
staffRegisteringNewMembersToSystem();
break;
case 4:
phoneNumberLookUpForMembers();
break;
}
}
}
/// <summary>
/// This function is a helper function of the staff-menu functionality, which allow the staff member to
/// look up a member's phone number by typing their first and last name.
/// </summary>
private static void phoneNumberLookUpForMembers()
{
Console.Write("Enter member's first name: ");
string fName = Console.ReadLine();
Console.Write("Enter member's last name: ");
string lName = Console.ReadLine();
Member objMember = memberCollectionObj.membersPhoneNumberFinder(fName, lName);
if (objMember != null)
{
Console.WriteLine(fName + " " + lName + "'s phone number is: " + objMember.UserPhoneNumber + "\n");
}
else
{
Console.WriteLine("This member does not exist." + "\n");
}
}
/// <summary>
/// This function is a helper function of the staff-menu functionality which allows the staff to
/// register new members to the system.
/// </summary>
private static void staffRegisteringNewMembersToSystem()
{
Console.Write("Enter member's first name: ");
string fName = Console.ReadLine();
Console.Write("Enter member's last name: ");
string lName = Console.ReadLine();
if (!memberCollectionObj.memberIsAddedAlready(fName, lName))
{
Console.Write("Enter member's address: ");
string userAddr = Console.ReadLine();
Console.Write("Enter member's phone number: ");
string userPhoneNo = Console.ReadLine();
string userPassword = "";
while (!inputedCorrectPass(userPassword))
{
Console.Write("Enter member's password(4 digits): ");
userPassword = Console.ReadLine();
}
memberCollectionObj.memberAdder(new Member(fName, lName, userAddr, userPhoneNo, userPassword));
Console.WriteLine("Successfully added " + fName + " " + lName + "\n");
}
else
{
Console.WriteLine(fName + " " + lName + " has already registered." + "\n");
}
}
/// <summary>
/// This function is a helper function of the staff-menu. Which checks the staff members password to see its correct or not.
/// </summary>
/// <param name="userInputPassword"></param>
/// <returns></returns>
private static bool inputedCorrectPass(string userInputPassword)
{
if (userInputPassword.Length != 4) {
return false;
}
for (int i = 0; i < userInputPassword.Length; i++) {
if (Char.IsLetter(userInputPassword[i])) {
return false;
}
}
return true;
}
/// <summary>
/// This function is a helper function which help staff to remove movies that they have added to the system.
/// </summary>
private static void staffRemoveMovie()
{
Console.Write("Enter movie title: ");
string movieTitle = Console.ReadLine();
if (!movieCollectionObj.deleteMovie(movieTitle))
{
Console.WriteLine(movieTitle + " was deleted successfully.\n");
}
else
{
Console.WriteLine(movieTitle+ " does not exist.\n");
}
}
/// <summary>
/// This method is for adding new movies by staff members and it is a helper function of the staff menu.
/// </summary>
private static void functionalityOfNewMovieAddition()
{
string[] movieClassificationInfo = {"General (G)", "Parental Guidance (PG)", "Mature (M15+)", "Mature Accompanied (MA15+)"};
string[] movieGenreInfo = { "Drama", "Adventure", "Family", "Action", "Sci-Fi", "Comedy", "Thriller", "Other"};
int choiceOfClassification = 0;
int choiceOfGenre = 0;
//These are console application notes asking the staff member on what to do.
Console.Write("Enter the movie title: ");
string movieTitle = Console.ReadLine();
Console.Write("Enter the starring actor(s): ");
string star = Console.ReadLine();
Console.Write("Enter the director(s): ");
string directorNames = Console.ReadLine();
Console.WriteLine("Select the genre: ");
for (int i = 0; i < movieGenreInfo.Length; i++)
{
Console.WriteLine((i + 1).ToString() + ". " + movieGenreInfo[i]);
}
choiceOfGenre = getUserInputsInt("Make selection(1-8): ", 1, 8);
Console.WriteLine("Select the classification: ");
for (int i = 0; i < movieClassificationInfo.Length; i++) {
Console.WriteLine((i + 1).ToString() + ". " + movieClassificationInfo[i]);
}
choiceOfClassification = getUserInputsInt("Make selection(l - 4): ", 1, 4);
int movieDuration = getUserInputsInt("Enter the duration (minutes): ", 0, 20000);
int movieReleaseDate = getUserInputsInt("Enter the release date (year): ", 1, 2030);
int movieCopiesAvailable = getUserInputsInt("Enter the number of copies available: ", 0, 2000000);
if (movieCollectionObj.BinarySearchAddMovie(new Movie(movieCopiesAvailable, movieDuration, 0,
movieReleaseDate, movieTitle,
movieClassificationInfo[choiceOfClassification - 1],
movieGenreInfo[choiceOfGenre - 1], directorNames, star))){
Console.WriteLine(movieTitle + " was added." + "\n");
}
else
{
Console.WriteLine("Movie " + movieTitle + " already exists." + "\n");
}
Console.WriteLine();
}
/// <summary>
/// This method will get user inputs and then convert it to an integer type of data.
/// Then it will check if they have entered inputs other than 0, 1, or 2 or any number of inputs
/// </summary>
/// <param name="mesg"></param>
/// <param name="minimum"></param>
/// <param name="maximum"></param>
/// <returns></returns>
private static int getUserInputsInt( string mesg, int minimum, int maximum)
{
int userInputs = -1;
bool running = false;
while (!running)
{
try
{
Console.Write(mesg);
userInputs = int.Parse(Console.ReadLine());
if(userInputs >= minimum && userInputs <= maximum)
{
running = true;
}
}
catch
{
}
}
return userInputs;
}
}
}
|
using System;
namespace CameraClassTest
{
public class Program
{
static void Main(string[] args)
{
ActionResult result;
Console.WriteLine("**************************************************************************************************");
Console.WriteLine("Esercitazione Classe Base e Classe Derivata con nuove proprieta e nuovi metodi - Vargas");
Console.WriteLine("***********************************");
CameraClass myCamF = new CameraClass("Samsung", TypeCamera.FRONT, false);
Console.WriteLine($"Samsung Camera Initial state: {myCamF.NameCamera} type Camera {myCamF.TypeCamera} activation state: {myCamF.IsActive.ToString()}");
result = myCamF.Activate(TypeCamera.FRONT);
Console.WriteLine($"after call Activate Camera message {result.Message} and Result {result.Result}");
Console.WriteLine($"After activate: {myCamF.NameCamera} type Camera {myCamF.TypeCamera}");
Console.WriteLine("************************************");
// DEACTIVATE
result = myCamF.DeActivate(TypeCamera.FRONT);
Console.WriteLine($" after call DeActivate Camera message {result.Message} and Result activation state {result.Result}");
Console.WriteLine($" after disactivate: {myCamF.NameCamera} type Camera {myCamF.TypeCamera}");
Console.WriteLine("**************************************************************************************************");
//
//ACTIVATE deacttivate error ?
result = myCamF.DeActivate(TypeCamera.FRONT);
Console.WriteLine($" after call New Deactivate Camera message {result.Message} and deactivate state Result {result.Result}");
Console.WriteLine($" after disactivate *** {myCamF.NameCamera} type Camera {myCamF.TypeCamera}");
Console.WriteLine("**************************************");
//CON LA CLASSE DERIVATA
PhoneI myPhone = new PhoneI("Iphone", TypeCamera.REAR, true, 12);
Console.WriteLine($"Iphone Camera Initial state {myPhone.NameCamera} camera type {myPhone.TypeCamera} camera state: {myPhone.IsActive.ToString()}");
int number = myPhone.Calcolate(12);
Console.WriteLine($"was Calcolated brightnes ? {myPhone.Calcolate(12).ToString()} camera type {myPhone.TypeCamera} il suo stato è {myPhone.IsActive.ToString()}");
result = myPhone.Activate(TypeCamera.REAR);
Console.WriteLine($" after call Activate Camera message {result.Message} and Result {result.Result}");
//Console.WriteLine($"After activate: {myPhone.NameCamera} tipo {myPhone.TypeCamera} il suo stato è {myPhone.IsActive.ToString()}");
result = myPhone.DeActivate(TypeCamera.REAR);
Console.WriteLine($" after disactivate IPHONE. {myPhone.NameCamera} camera type {myPhone.TypeCamera} camera state: {myPhone.IsActive.ToString()}");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OcTur.Model;
namespace OcTur.Control
{
class ControlePermissaoControl
{
public List<string> CarregarPapeis()
{
return new List<string>();
}
public List<string> CarregarPermissoes()
{
return new List<string>();
}
public bool SalvarAssociassoes (string papelSelecionado, List<string> permissoesSelecionadas)
{
return true;
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
public class GoogleAdController : MonoBehaviour {
public static GoogleAdController instance;
public int instancesBetweenInterstitialAds = 3;
public PhaseDelayedEventScheduler phaseDelayedEventScheduler;
bool registeredForEvents;
bool adsEnabled = true;
BannerView bannerView;
InterstitialAd interstitialAd;
public string iosBannerViewAdId;
public string androidBannerViewAdId;
public string iosInterstitialAdId;
public string androidInterstitialAdId;
void Awake() {
instance = this;
bannerView = new BannerView (GetBannerAdUnitId(),
AdSize.SmartBanner,
AdPosition.Bottom);
bannerView.LoadAd (MakeAdRequest());
bannerView.AdLoaded += OnBannerAdLoaded;
bannerView.Hide ();
PrepInterstitialAd ();
}
void PrepInterstitialAd() {
if (Debug.isDebugBuild) {
Debug.Log ("Setting up interstitialAd");
}
interstitialAd = new InterstitialAd (GetInterstitialAdUnitId());
interstitialAd.AdLoaded += OnInterstitialAdLoaded;
interstitialAd.AdOpened += OnInterstitialAdOpened;
interstitialAd.AdClosed += OnInterstitialAdClosed;
interstitialAd.AdFailedToLoad += OnInterstitialAdFailedToLoad;
interstitialAd.LoadAd (MakeAdRequest ());
}
AdRequest MakeAdRequest() {
AdRequest.Builder builder =
new AdRequest.Builder();
builder.AddKeyword("game");
builder.AddKeyword("cat");
builder.TagForChildDirectedTreatment (true);
return builder.Build();
}
string GetInterstitialAdUnitId() {
if (Application.platform == RuntimePlatform.IPhonePlayer) {
return iosInterstitialAdId;
} else if (Application.platform == RuntimePlatform.Android) {
return androidInterstitialAdId;
} else {
return "badid";
}
}
string GetBannerAdUnitId() {
if (Application.platform == RuntimePlatform.IPhonePlayer) {
return iosBannerViewAdId;
} else if (Application.platform == RuntimePlatform.Android) {
return androidBannerViewAdId;
} else {
return "badid";
}
}
// Use this for initialization
void Start () {
RegisterForEvents ();
UpdateBanner ();
UpdateAdsAvailability ();
}
void UpdateAdsAvailability() {
if (StoreController.instance.IsUpgradePurchased ()) {
adsEnabled = false;
}
}
void OnDestroy() {
UnregisterForEvents ();
}
void OnBannerAdLoaded(object sender, EventArgs args) {
if (Debug.isDebugBuild) {
Debug.Log ("OnBannerAdLoaded");
}
}
void OnInterstitialAdLoaded(object sender, EventArgs args) {
if (Debug.isDebugBuild) {
Debug.Log ("OnInterstitialAdLoaded");
}
}
void OnInterstitialAdOpened(object sender, EventArgs args) {
if (Debug.isDebugBuild) {
Debug.Log ("OnInterstitialAdOpened");
}
// Quiet the music.
SoundController.instance.SuppressSounds ();
}
void OnInterstitialAdFailedToLoad(object sender, EventArgs args) {
if (Debug.isDebugBuild) {
Debug.Log ("OnInterstitialAdFailedToLoad");
Debug.Log ("args = " + args);
}
}
void OnInterstitialAdClosed(object sender, EventArgs args) {
if (Debug.isDebugBuild) {
Debug.Log ("OnInterstitialAdClosed");
}
SoundController.instance.UnsuppressSounds ();
// Load another one.
PrepInterstitialAd ();
}
void RegisterForEvents() {
if (registeredForEvents) {
return;
}
registeredForEvents = true;
GamePhaseState.instance.GamePhaseChanged +=
new GamePhaseState.GamePhaseChangedEventHandler (OnGamePhaseChanged);
StoreController.instance.StoreChanged +=
new StoreController.StoreChangedHandler (OnStoreChanged);
}
void UnregisterForEvents() {
if (registeredForEvents) {
GamePhaseState.instance.GamePhaseChanged -=
new GamePhaseState.GamePhaseChangedEventHandler (OnGamePhaseChanged);
StoreController.instance.StoreChanged +=
new StoreController.StoreChangedHandler (OnStoreChanged);
}
}
void OnGamePhaseChanged() {
UpdateBanner ();
UpdateInterstialAd ();
}
void OnStoreChanged() {
UpdateAdsAvailability ();
}
void UpdateInterstialAd() {
phaseDelayedEventScheduler.OnPhaseChanged (MaybeShowAd);
}
bool MaybeShowAd() {
bool shouldShowAd = ShouldShowInterstitialAd ();
if (!shouldShowAd) {
return false;
}
PersistentStorage.instance.SetIntValue ("lastInstanceAdShown",
GamePhaseState.instance.instancesFinishedThisSession);
ShowInterstitialAd ();
return true;
}
void ShowInterstitialAd() {
if (!adsEnabled) {
return;
}
if (interstitialAd.IsLoaded ()) {
interstitialAd.Show ();
}
}
bool ShouldShowInterstitialAd() {
if (!adsEnabled) {
return false;
}
if (GamePhaseState.instance.gamePhase != GamePhaseState.GamePhaseType.GAME_OVER) {
return false;
}
int lastInstanceAdShown = PersistentStorage.instance.GetIntValue ("lastInstanceAdShown",
0);
if (GamePhaseState.instance.instancesFinishedThisSession <
lastInstanceAdShown + instancesBetweenInterstitialAds) {
return false;
}
if (!interstitialAd.IsLoaded ()) {
return false;
}
return true;
}
void UpdateBanner() {
if (!adsEnabled) {
bannerView.Hide ();
return;
}
switch(GamePhaseState.instance.gamePhase) {
case GamePhaseState.GamePhaseType.LEVEL_PLAY:
case GamePhaseState.GamePhaseType.PENDING:
if (!DebugConfig.instance.IsDebugFlagSet(DebugConfig.DEBUG_HIDE_ADS)) {
bannerView.Show ();
}
break;
default:
bannerView.Hide ();
break;
}
switch (GamePhaseState.instance.gamePhase) {
case GamePhaseState.GamePhaseType.WELCOME:
case GamePhaseState.GamePhaseType.LEVEL_END:
if (Debug.isDebugBuild) {
Debug.Log("Loading new banner ad");
}
bannerView.LoadAd (MakeAdRequest ());
break;
}
}
public static float GetBannerHeight() {
// Logic from
// https://developers.google.com/admob/android/banner#smart
float longSide;
float screenHeight = Screen.height;
float screenWidth = Screen.width;
longSide = Mathf.Max (screenHeight, screenWidth);
if (longSide < 400) {
return 32;
}
if (longSide <= 720) {
return 50;
}
return 90;
}
public void DebugInterstitialAds() {
ShowInterstitialAd ();
}
}
|
using UnityEngine;
using System.Collections;
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Runtime.Serialization;
using stSaveFileInfo = CSaveAndLoadTypes.stSaveFileInfo;
[System.Serializable]
public sealed class _SALContainer : ISaveAndLoadContainer {
#region Private fileds
private static ArrayList _instances = new ArrayList();
private static _SALContainer _instance_load;
#endregion
#region Public Fields
#endregion
#region Properties
public new static _SALContainer Instance_Save{
get{
return (_SALContainer)CSingleton.GetSingletonInstance(
ref _instances,
typeof(_SALContainer)
);
}
}
public new static _SALContainer Instance_Load{
get{
return _instance_load;
}
set{
_instance_load = value;
}
}
#endregion
#region Constructors
public _SALContainer() base(){
//singleton system
_instances.Add(this);
CSingleton.DestroyExtraInstances(_instances);
}
//Serializatoin counstructor. call when Deserialize function called.
//Must be private and call base constructor.
private _SALContainer(SerializationInfo info, StreamingContext context) : base(info, context){
}
#endregion
#region Public Methods
//This method will call when save event happend.
//All data that need to be save must store here.
public override void GetObjectData (SerializationInfo info, StreamingContext context){
throw new System.NotImplementedException ();
}
#endregion
}
|
using System;
namespace lab2
{
interface IPrint
{
void Print();
}
abstract class GeomFigure
{
public abstract double Area();
}
class Rectangle : GeomFigure, IPrint
{
public double height { get; set; }
public double width { get; set; }
public Rectangle(double width, double height)
{
this.height = height;
this.width = width;
}
public override double Area()
{
return height * width;
}
public override string ToString()
{
return ("Прямоугольник:\n ширина: " + width + "\n высота: " + height + "\n площадь: " + Area());
}
public void Print()
{
Console.WriteLine(ToString());
}
}
class Square : Rectangle
{
public double sideLength { get; set; }
public Square(double sideLength) : base(sideLength, sideLength)
{
this.sideLength = sideLength;
}
public override double Area()
{
return sideLength * sideLength;
}
public override string ToString()
{
return ("Квадрат:\n длина стороны: " + sideLength + "\n площадь: " + Area());
}
}
class Circle : GeomFigure, IPrint
{
public double radius { get; set; }
public Circle(double radius)
{
this.radius = radius;
}
public override double Area()
{
return radius * radius * 3.14;
}
public override string ToString()
{
return ("Круг:\n радиус: " + radius + "\n площадь: " + Area());
}
public void Print()
{
Console.WriteLine(ToString());
}
}
public static class Program {
public static void Main()
{
Rectangle r = new Rectangle(2, 3);
Square s = new Square(5);
Circle c = new Circle(7);
r.Print();
s.Print();
c.Print();
}
}
}
|
using System;
namespace twpx.Model
{
class SadminModel
{
public int id
{
get;
set;
}
public string username
{
get;
set;
}
public string password
{
get;
set;
}
public string name
{
get;
set;
}
public string phone
{
get;
set;
}
}
}
|
using UnityEngine;
/// <summary>
/// A GUI control for configuring the solid color shader.
/// This class encapsulates the underlying GUI controls
/// needed to configure the shader, allowing it to present
/// a simplified interface to receive the shader's configuration.
/// </summary>
public class SolidColorShaderConfigGui : MaterialConfiguration
{
/// <summary>
/// The material for the solid color shader.
/// </summary>
public Material SolidColorShaderMaterial = null;
/// <summary>
/// The selector for the solid color.
/// </summary>
private ColorSelector m_colorSelector = null;
/// <summary>
/// The example game object that gets updated with new shader
/// settings configured in this GUI control.
/// </summary>
private PlayerExampleGameObject m_exampleGameObject = null;
/// <summary>
/// Initializes the configuration GUI to have
/// access to the selector of the solid color
/// for the shader and knowledge about the example
/// game object.
/// </summary>
/// <param name="exampleGameObject">The example game object
/// to update with new solid color settings configured
/// in this control.</param>
public void Initialize(GameObject exampleGameObject)
{
// STORE THE EXAMPLE GAME OBJECT.
m_exampleGameObject = exampleGameObject.GetComponent<PlayerExampleGameObject>();
// CLONE THE ATTACHED MATERIAL SO THAT WE DON'T MODIFY THE UNDERLYING MATERIAL ASSET.
SolidColorShaderMaterial = new Material(SolidColorShaderMaterial);
// REGISTER WITH THE COLOR SELECTOR TO BE NOTIFIED WHEN THE COLOR CHANGES.
m_colorSelector = transform.Find("ColorSelector").GetComponent<ColorSelector>();
m_colorSelector.Initialize();
m_colorSelector.AddOnColorChangedListener(UpdateDisplayedColor);
// INITIALIZE THE EXAMPLE GAME OBJECT WITH THE CURRENT SELECTED COLOR.
UpdateDisplayedColor(m_colorSelector.Color);
}
/// <summary>
/// Updates the color displayed in the example object based
/// the provided color.
/// </summary>
/// <param name="color">The new solid color for the example object.</param>
public void UpdateDisplayedColor(Color color)
{
// UPDATE THE SOLID COLOR IN THE MATERIAL.
SolidColorShaderMaterial.SetColor("_Color", color);
m_exampleGameObject.SetMaterial(SolidColorShaderMaterial);
}
/// <summary>
/// Creates a copy of the configured solid color shader material.
/// </summary>
/// <returns>The configured solid color shader material.</returns>
public override Material CreateMaterial()
{
return new Material(SolidColorShaderMaterial);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using gMediaTools.Services;
using gMediaTools.Services.AviSynth;
using gMediaTools.Services.AviSynth.VideoSource;
namespace gMediaTools.Factories
{
public class AviSynthSourceFactory
{
public IAviSynthVideoSourceService GetAviSynthSourceService(string fileContainerFormat)
{
string container = fileContainerFormat.Trim().ToLower();
if (container.Equals("matroska"))
{
// MKV => FFMS2
return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>();
}
else if (container.Equals("windows media"))
{
// WMV => FFMS2
return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>();
}
else if (container.Equals("mpeg-4"))
{
// MP4 or MOV => FFMS2
return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>();
}
else if (container.Equals("avi"))
{
// AVI => AviSource
return ServiceFactory.GetService<AviSynthAviSourceService>();
}
else if (container.Equals("flash video"))
{
// FLV => FFMS2
return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>();
}
else if (container.Equals("realmedia"))
{
// RM => FFMS2
return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>();
}
else if (container.Equals("mpeg-ts"))
{
// TS => FFMS2
return ServiceFactory.GetService<AviSynthFfms2VideoSourceService>();
}
else
{
// Could not identify container/format
// Let's play it safe and use DirectShowSource
return ServiceFactory.GetService<AviSynthDirectShowVideoSourceService>();
}
}
}
}
|
using Common.Data;
using Common.Exceptions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Entity
{
/// <summary>
/// Class for performing operations on the Staging table.
/// </summary>
public partial class Staging
{
#region Public Methods
/// <summary>
/// Adds a record to the database.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="userName">The user making the request.</param>
/// <param name="id">The ID to add.</param>
/// <param name="instance">The current instance.</param>
/// <returns>True if successful; otherwise false.</returns>
public bool Add(string connectionString, string userName, int id, int instance)
{
bool result = false;
if (Exists(connectionString, userName, id, instance))
return true;
string sql = "insert into staging (id, username, instance_num) values (" + id + ", '" + userName + "', " +
instance + ")";
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteNonQuery(sql);
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
/// <summary>
/// Deletes items from the Staging table.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="userName">The user making the request.</param>
/// <param name="instance">The current instance.</param>
/// <returns>True if successful; otherwise false.</returns>
public bool ClearClipboard(string connectionString, string userName, int instance)
{
bool result = false;
//delete from staging where username = @Username and instance_num = @Instance_Num
string sql = "P_Staging_Main_Clear_Clear2";
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@Username", userName));
parameters.Add(new SqlParameter("@Instance_Num", instance));
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteNonQuery(sql, parameters: parameters.ToArray());
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameters.Clear();
}
}
return result;
}
/// <summary>
/// Deletes a record from the database.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="id">The ID to delete.</param>
/// <param name="userName">The user making the request.</param>
/// <param name="instance">The Clipboard instance to delete from.</param>
/// <returns>True if successful; otherwise false.</returns>
public bool DeleteRecord(string connectionString, int id, string userName, int instance)
{
//delete from staging where id = @ID and username = @Username and instance_num = @Instance_Num
string sql = "P_Staging_Main_Remove_Delete2";
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@ID", id));
parameters.Add(new SqlParameter("@Username", userName));
parameters.Add(new SqlParameter("@Instance_Num", instance));
using (Database database = new Database(connectionString))
{
try
{
return database.ExecuteNonQuery(sql, parameters: parameters.ToArray());
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameters.Clear();
}
}
}
/// <summary>
/// Gets the notes for the selected ID from the database.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="id">The ID to delete.</param>
/// <param name="userName">The user making the request.</param>
/// <param name="instance">The current instance.</param>
/// <returns>The notes text.</returns>
public string GetNotes(string connectionString, int id, string userName, int instance)
{
string result = String.Empty;
//select notes from staging where id = @ID and username = @Username and instance_num = @Instance_Num
string sql = "P_Staging_GetNotes2";
List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@ID", id));
parameters.Add(new SqlParameter("@Username", userName));
parameters.Add(new SqlParameter("@Instance_Num", instance));
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectString(sql, CommandType.StoredProcedure, parameters.ToArray());
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
finally
{
parameters.Clear();
}
}
return result;
}
/// <summary>
/// Gets the IDs to display in the form's grid.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="userName">The user making the request.</param>
/// <param name="instance">The current instance.</param>
/// <returns>The IDs to load.</returns>
public List<int> GetStagingIds(string connectionString, string userName, int instance)
{
List<int> result = new List<int>();
string sql = "Select distinct ID from Staging where username = '" + userName + "' " +
"and instance_num = " + instance.ToString();
//List<SqlParameter> parameters = new List<SqlParameter>();
//parameters.Add(new SqlParameter("@Username", userName));
//parameters.Add(new SqlParameter("@Instance_Num", instance));
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectIntList(sql);//, CommandType.StoredProcedure, parameters.ToArray());
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
//finally
//{
// parameters.Clear();
//}
}
return result;
}
/// <summary>
/// Saves the current instance to the database.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <returns>True if successful; otherwise false.</returns>
public bool Save(string connectionString)
{
bool result = false;
using (Database database = new Database(connectionString))
{
string sql = "";
try
{
Mapper<Staging> m = new Mapper<Staging>();
sql = m.MapSingleUpdate(this);
result = database.ExecuteNonQuery(sql);
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public List<int> GetIds(string connectionString, string userName, int instance)
{
List<int> result = new List<int>();
string sql = "Select ID from Staging where username= '" + userName + "' and instance_num = " +
instance.ToString();
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectIntList(sql);
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
#endregion
#region Private Methods
/// <summary>
/// Checks to see if a record exists on the Staging table.
/// </summary>
/// <param name="connectionString">The connection string to use.</param>
/// <param name="userName">The current user.</param>
/// <param name="id">The ID to check.</param>
/// <param name="instance">The current instance.</param>
/// <returns>True if the record exists; otherwise false.</returns>
private bool Exists(string connectionString, string userName, int id, int instance)
{
bool result = false;
string sql = "Select count(*) from Staging where id = " + id + " and username = '" + userName + "' and " +
"instance_num = " + instance;
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0;
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
#endregion
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
using System;
using System.Collections.Generic;
using System.Text;
namespace FiiiChain.Node
{
public class NodeConfig
{
public string Ip { get; set; }
public string User { get; set; }
public string Password { get; set; }
public string Port { get; set; }
public string WalletNotify { get; set; }
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Table;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DoodleReplacement
{
public static class InsertAnswer
{
[FunctionName("InsertAnswer")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
try
{
var partition = req.Query["partition"];
var service = new EntriesBL();
var config = await service.GetEntryConfig(partition);
if(config == null) {
return new BadRequestResult();
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var model = JsonConvert.DeserializeObject<AnswerAM>(requestBody);
if(!model.IsValid)
{
return new BadRequestObjectResult("Model is invalid! Name or dates missing.");
}
var entity = new AnswerEntity(partition, model.Name)
{
Name = model.Name,
AdditionalMessage = model.AdditionalMessage,
SelectedDatesString = string.Join(',', model.SelectedDates.Select(sd => sd.ToString("yyyy-MM-dd")))
};
var table = await StorageService.GetStorageTableReference();
await table.ExecuteAsync(TableOperation.Insert(entity));
if(!string.IsNullOrEmpty(config.WebHookUrl)) {
using (var client = new HttpClient()) {
await client.PostAsync(config.WebHookUrl, null);
}
}
return new OkObjectResult(entity);
}
catch(Exception ex)
{
log.LogError(ex.Message, ex);
return new BadRequestObjectResult(ex.Message);
}
}
}
}
|
using System;
namespace DoublePermutationMethod.Command
{
class HelpCommand : BaseCommand
{
public override string Name => "help";
public override void Execute()
{
Console.WriteLine("<encode> - Command to encrypt a sentence with a custom key");
Console.WriteLine("<encodeRND> - Command to encrypt a sentence with a random key");
Console.WriteLine("<decode> - Command for decrypting a sentence with a custom key");
}
}
}
|
using System;
using System.Linq;
using VetClinicPublic.Web.Models;
namespace VetClinicPublic.Web.Interfaces
{
public interface ISendConfirmationEmails
{
void SendConfirmationEmail(AppointmentDTO appointment);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LibreriaClases
{
public class EjecutarQuery
{
static string connectionString = @"Server = YouServerName; Database=Usuarios;Trusted_Connection=True";
public static List<usuario> listaUsuarios;
public static List<EstadoCivil> listaEstados;
#region InsertSQL
public static void insertSQL( string nombre,string apellido)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(null, connection);
// Create and prepare an SQL statement.
command.CommandText = "INSERT INTO usuario (nombre, apellido) VALUES (@nombre, @apellido)";
command.Parameters.AddWithValue("@nombre", nombre);
command.Parameters.AddWithValue("@apellido", apellido);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
connection.Close();
}
}
public static void insertSQL(string nombre)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(null, connection);
// Create and prepare an SQL statement.
command.CommandText = "INSERT INTO usuario (nombre) VALUES (@nombre)";
command.Parameters.AddWithValue("@nombre", nombre);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
connection.Close();
}
}
#endregion InsertSQL
#region SelectSQL
//se obtiene 1 usuario utilizando el id
public static List<usuario> selectSQL(int id)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(null, connection);
DataTable dt = new DataTable();
// Create and prepare an SQL statement.
command.CommandText = $"select * from usuario where id_usuario = {id}";
try
{
connection.Open();
var DataAdapter = new SqlDataAdapter(command);
DataAdapter.Fill(dt);
usuario _usuario = new usuario();
listaUsuarios = new List<usuario>();
_usuario.id_usuario = int.Parse((dt.Rows[0]["id_usuario"].ToString()));
_usuario.nombre = dt.Rows[0]["nombre"].ToString();
_usuario.apellido = dt.Rows[0]["apellido"].ToString();
listaUsuarios.Add(_usuario);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
connection.Close();
}
return listaUsuarios;
}
//se obtienen todos los usuarios en la BD
public static List<usuario> selectAllUsuariosSQL()
{
var dt = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
//command nos prepara la query a ejecutar
SqlCommand command = new SqlCommand(null, connection);
command.CommandText = "select * from usuario";
connection.Open();
var DataAdapter = new SqlDataAdapter(command);
DataAdapter.Fill(dt);
listaUsuarios = new List<usuario>();
foreach (DataRow row in dt.Rows)
{
usuario usuarioTemp = new usuario();
usuarioTemp.id_usuario = int.Parse(row["id_usuario"].ToString());
usuarioTemp.nombre = row["nombre"].ToString();
usuarioTemp.apellido = row["apellido"].ToString();
listaUsuarios.Add(usuarioTemp);
}
}
return listaUsuarios;
}
//se obtienen todos los usuarios en la BD
public static List<EstadoCivil> selectAllEstadoCivilSQL()
{
var dt = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
//command nos prepara la query a ejecutar
SqlCommand command = new SqlCommand(null, connection);
command.CommandText = "select * from EstadoCivil";
connection.Open();
var DataAdapter = new SqlDataAdapter(command);
DataAdapter.Fill(dt);
listaEstados = new List<EstadoCivil>();
foreach (DataRow row in dt.Rows)
{
EstadoCivil estadoCivil = new EstadoCivil();
estadoCivil.id_estadoCivil = int.Parse(row["IdEstadoCivil"].ToString());
estadoCivil.descripcion = row["Descripcion"].ToString();
listaEstados.Add(estadoCivil);
}
}
return listaEstados;
}
#endregion SelectSQL
}
}
|
using Microsoft.AspNet.Http;
using SciVacancies.WebApp.ViewModels.Base;
namespace SciVacancies.WebApp.ViewModels
{
public class ResearcherEditPhotoViewModel: PageViewModelBase
{
public IFormFile PhotoFile { get; set; }
public string ImageName { get; set; }
public long? ImageSize { get; set; }
public string ImageExtension { get; set; }
private string _imageUrl;
public string ImageUrl
{
get { return _imageUrl ?? string.Empty; }
set { _imageUrl = value; }
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour {
public int player1Health;
public int player2Health;
// Access to LastManStanding script
public GameObject lastManStandingGameObj;
public LastManStanding lastManStandingScript;
// Display the player's health
public Text player1HealthDisplay;
public Text player2HealthDisplay;
// Play victory sound
public GameObject audioControllerObj;
public AudioFileController audioControllerScript;
private bool playVictorySound;
// Use this for initialization
void Start () {
player1Health = 100;
player2Health = 100;
lastManStandingGameObj = GameObject.Find("GameController");
lastManStandingScript = lastManStandingGameObj.GetComponent<LastManStanding>();
//audioControllerObj = GameObject.Find("AudioController");
//audioControllerScript = audioControllerObj.GetComponent<AudioFileController>();
playVictorySound = false;
}
// Update is called once per frame
void Update () {
// Delete player one object if the health threshold gets to 0
if (player1Health <= 0 && playVictorySound == false)
{
player1Health = 0;
lastManStandingScript.isPlayer1Alive = false;
Destroy(GameObject.FindWithTag("PlayerOne"));
playVictorySound = true;
audioControllerScript.PlaySound(audioControllerScript.victorySound);
}
// Do not let the players get more than 100% health
if (player1Health >= 100)
{
player1Health = 100;
}
// Do not let the players get less than 0% health
if (player1Health <= 0)
{
player1Health = 0;
}
// Delete player two object if the health threshold gets to 0
if (player2Health <= 0 && playVictorySound == false)
{
player2Health = 0;
lastManStandingScript.isPlayer2Alive = false;
Destroy(GameObject.FindWithTag("PlayerTwo"));
playVictorySound = true;
audioControllerScript.PlaySound(audioControllerScript.victorySound);
}
// Do not let the players get more than 100% health
if (player2Health >= 100)
{
player2Health = 100;
}
// Update the health text
player1HealthDisplay.text = (player1Health.ToString("0"));
player2HealthDisplay.text = (player2Health.ToString("0"));
}
}
|
using mec.Database.Presentees;
using mec.Model;
using mec.Model.Processes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace mec.Cleint.Portal.Controllers
{
public class ProcessController : ApiController
{
[HttpPost]
public HttpResponseMessage GetNotices(NoticeParam param)
{
ProcessPresenter pre = new ProcessPresenter();
var vms = pre.GetNotices(param);
if (vms != null)
{
return Request.CreateResponse(HttpStatusCode.OK, vms);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "取得工站預警資訊錯誤!!");
}
//setNotice
[HttpPost]
public HttpResponseMessage SetNotice(NoticeViewModel vm)
{
ProcessPresenter pre = new ProcessPresenter();
int eCode = pre.SetNotice(vm);
if (eCode > 0)
{
return Request.CreateResponse(HttpStatusCode.OK, eCode);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "設定工站預警資訊錯誤!!");
}
[HttpPost]
public HttpResponseMessage GetTraces(TraceParam param)
{
ProcessPresenter pre = new ProcessPresenter();
var vms = pre.GetTraces(param);
if (vms != null)
{
return Request.CreateResponse(HttpStatusCode.OK, vms);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "取得追溯資訊錯誤!!");
}
//GetTraceOptions
[HttpPost]
public HttpResponseMessage GetTraceOptions()
{
ProcessPresenter pre = new ProcessPresenter();
var vms = pre.GetTraceOptions();
if (vms != null)
{
return Request.CreateResponse(HttpStatusCode.OK, vms);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "取得追溯查詢條件錯誤!!");
}
}
}
|
using MediaProtector.App_Plugins.MediaProtector.Controllers;
using Umbraco.Core;
using Umbraco.Core.Composing;
namespace MediaProtector.App_Plugins.MediaProtector.Components {
public class Composer:IUserComposer {
public void Compose(Composition composition) {
//Append our component to the collection of Components
// It will be the last one to be run
composition.Components().Append<InitializePlan>();
composition.Components().Append<EventBlocker>();
composition.Register<MediaProtectorApiController>();
}
}
}
|
*** Start programmer edit section *** (EduProgram.Number CustomAttributes)
*** End programmer edit section *** (EduProgram.Number CustomAttributes)
*** Start programmer edit section *** (EduProgram.Number Get)
return null;
*** End programmer edit section *** (EduProgram.Number Get)
*** Start programmer edit section *** (EduProgram.Number Set)
*** End programmer edit section *** (EduProgram.Number Set)
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace isukces.code.vssolutions
{
public sealed class FrameworkVersion : IComparable<FrameworkVersion>, IComparable
{
public FrameworkVersion(string shortName, string version, string profile)
{
shortName = shortName.ToLower();
FrameworkGroup = RecognizeFrameworkVersionGroup(shortName);
ShortName = shortName;
Version = version;
Profile = profile;
VersionCompare = version.Replace(".", "");
}
public static bool operator >(FrameworkVersion left, FrameworkVersion right)
{
return Comparer<FrameworkVersion>.Default.Compare(left, right) > 0;
}
public static bool operator >=(FrameworkVersion left, FrameworkVersion right)
{
return Comparer<FrameworkVersion>.Default.Compare(left, right) >= 0;
}
public static bool operator <(FrameworkVersion left, FrameworkVersion right)
{
return Comparer<FrameworkVersion>.Default.Compare(left, right) < 0;
}
public static bool operator <=(FrameworkVersion left, FrameworkVersion right)
{
return Comparer<FrameworkVersion>.Default.Compare(left, right) <= 0;
}
public static FrameworkVersion[] Parse(string x)
{
{
var portable = "portable-";
if (x.StartsWith(portable))
{
var xx = x.Substring(portable.Length).Split('+');
return xx.Select(Parse1).ToArray();
}
}
{
var portable = "portable40-";
if (x.StartsWith(portable))
{
var xx = x.Substring(portable.Length).Split('+');
return xx.Select(Parse1).ToArray();
}
}
return new[] {Parse1(x)};
}
public static FrameworkVersion Parse1(string x)
{
var m = VersionRegex.Match(x);
if (m.Success)
{
var type = m.Groups[1].Value;
var version = m.Groups[2].Value;
var profile = m.Groups[3].Value;
if (type == "v")
type = "net";
return new FrameworkVersion(type, version, profile);
}
return null;
}
private static FrameworkVersionGroup RecognizeFrameworkVersionGroup(string shortName)
{
// https://docs.microsoft.com/pl-pl/nuget/reference/target-frameworks
if (shortName.StartsWith("xamarin", StringComparison.Ordinal))
return FrameworkVersionGroup.Xamarin;
switch (shortName)
{
case "net":
return FrameworkVersionGroup.Framework;
case "netcore":
return FrameworkVersionGroup.NetCore;
case "netcoreapp":
case "aspnet": // Deprecated
case "aspnetcore": // Deprecated
case "dnx": // Deprecated
case "dnxcore": // Deprecated
return FrameworkVersionGroup.NetCoreApp;
case "netstandard":
case "dotnet": // Deprecated
return FrameworkVersionGroup.NetStandard;
case "wp":
case "wpa":
return FrameworkVersionGroup.WindowsPhone;
case "sl":
return FrameworkVersionGroup.Silverlight;
case "win":
case "winrt": // Deprecated
return FrameworkVersionGroup.Windows;
case "netmf":
return FrameworkVersionGroup.MicroFramework;
case "uap":
return FrameworkVersionGroup.UniversalWindowsPlatform;
case "tizen":
return FrameworkVersionGroup.Tizen;
default:
return FrameworkVersionGroup.Other;
}
}
public NugetLoadCompatibility CanLoad(FrameworkVersion nuget)
{
if (FrameworkGroup == nuget.FrameworkGroup)
{
var g = string.Compare(VersionCompare, nuget.VersionCompare, StringComparison.OrdinalIgnoreCase);
return g == 0
? NugetLoadCompatibility.Full
: g > 0
? NugetLoadCompatibility.Possible
: NugetLoadCompatibility.None;
}
if (FrameworkGroup == FrameworkVersionGroup.UniversalWindowsPlatform)
switch (nuget.FrameworkGroup)
{
case FrameworkVersionGroup.Windows:
case FrameworkVersionGroup.WindowsPhone:
return nuget.VersionCompare == "81"
? NugetLoadCompatibility.Partial
: NugetLoadCompatibility.None;
case FrameworkVersionGroup.NetCore:
return nuget.VersionCompare == "50"
? NugetLoadCompatibility.Partial
: NugetLoadCompatibility.None;
}
return NugetLoadCompatibility.None;
}
public int CompareTo(FrameworkVersion other)
{
if (ReferenceEquals(this, other)) return 0;
if (ReferenceEquals(null, other)) return 1;
var compareTypeComparison = FrameworkGroup.CompareTo(other.FrameworkGroup);
if (compareTypeComparison != 0) return compareTypeComparison;
return string.Compare(VersionCompare, other.VersionCompare, StringComparison.Ordinal);
}
public int CompareTo(object obj)
{
if (ReferenceEquals(null, obj)) return 1;
if (ReferenceEquals(this, obj)) return 0;
return obj is FrameworkVersion other
? CompareTo(other)
: throw new ArgumentException($"Object must be of type {nameof(FrameworkVersion)}");
}
public override string ToString()
{
return Name;
}
public FrameworkVersionGroup FrameworkGroup { get; }
public string ShortName { get; }
public string Version { get; }
public string Profile { get; }
public string VersionCompare { get; }
public string Name
{
get
{
var name = ShortName + Version;
if (string.IsNullOrEmpty(Profile))
return name;
return name + "-" + Profile;
}
}
private static readonly Regex VersionRegex =
new Regex(VersionFilter, RegexOptions.IgnoreCase | RegexOptions.Compiled);
const string VersionFilter = @"^([a-z]+)(\d+(?:\.\d+(?:\.\d+)?)?)(?:-([a-z]+))?$";
}
#if OLD
^([a-z]+)
(\d+(?:\.\d+(?:\.\d+)?)?)
(?:-([a-z]+))?$
#endif
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using VeterinariaT1.BD;
using VeterinariaT1.Modelo;
namespace VeterinariaT1.Controller
{
class ControladorTratamiento
{
public List<Modelo.Tratamientos> AllTramientos()
{
List<Tratamientos> vjs = new List<Tratamientos>();
Tratamientos ctemp = null;
Conexion conn = new Conexion();
string sqlConsulta = "sp_Tratamientos";
SqlCommand comando = new SqlCommand(sqlConsulta, conn.AbrirC());
SqlDataReader reader = comando.ExecuteReader();
while (reader.Read())
{
ctemp = new Tratamientos();
ctemp.Id = reader.GetInt32(reader.GetOrdinal("Id"));
ctemp.Tratamiento = reader.GetString(reader.GetOrdinal("Tratamiento"));
ctemp.Telefonos = reader.GetString(reader.GetOrdinal("Sucursal"));
ctemp.Tamaño = reader.GetString(reader.GetOrdinal("Tamaño"));
ctemp.Precio = reader.GetInt32(reader.GetOrdinal("Precio"));
ctemp.Sucursal = reader.GetString(reader.GetOrdinal("Sucursal"));
ctemp.Tipo = reader.GetString(reader.GetOrdinal("Tipo"));
ctemp.IdEstatus = reader.GetInt32(reader.GetOrdinal("Estatus"));
vjs.Add(ctemp);
}
conn.CerrarC();
return vjs;
}
public void AgregarTratamientos(Tratamientos ani)
{
SqlDataReader reader = null;
Conexion conn = new Conexion();
string sql1 = "sp_AgregarTratamientos";
SqlCommand comando1 = new SqlCommand(sql1, conn.AbrirC());
comando1.CommandType = System.Data.CommandType.StoredProcedure;
comando1.Parameters.AddWithValue("@Precio", System.Data.SqlDbType.Float).Value = ani.Precio;
comando1.Parameters.AddWithValue("@Sucursal", System.Data.SqlDbType.VarChar).Value = ani.Sucursal;
comando1.Parameters.AddWithValue("@Tratamientos", System.Data.SqlDbType.VarChar).Value = ani.Tratamiento;
comando1.Parameters.AddWithValue("@Telefono", System.Data.SqlDbType.VarChar).Value = ani.Telefonos;
comando1.Parameters.AddWithValue("@Tamaño", System.Data.SqlDbType.VarChar).Value = ani.Tamaño;
comando1.Parameters.AddWithValue("@Tipo", System.Data.SqlDbType.VarChar).Value = ani.Tipo;
comando1.ExecuteNonQuery();
conn.CerrarC();
MessageBox.Show("Se agrego nuevo Servicio");
}
public void ModificarTratamientos(Tratamientos ani)
{
SqlDataReader reader = null;
Conexion conn = new Conexion();
string sql1 = "sp_ModificarTratamientos";
SqlCommand comando1 = new SqlCommand(sql1, conn.AbrirC());
comando1.CommandType = System.Data.CommandType.StoredProcedure;
comando1.Parameters.AddWithValue("@Precio", System.Data.SqlDbType.Float).Value = ani.Precio;
comando1.Parameters.AddWithValue("@Sucursal", System.Data.SqlDbType.VarChar).Value = ani.Sucursal;
comando1.Parameters.AddWithValue("@Tratamientos", System.Data.SqlDbType.VarChar).Value = ani.Tratamiento;
comando1.Parameters.AddWithValue("@Telefono", System.Data.SqlDbType.VarChar).Value = ani.Telefonos;
comando1.Parameters.AddWithValue("@Tamaño", System.Data.SqlDbType.VarChar).Value = ani.Tamaño;
comando1.Parameters.AddWithValue("@Tipo", System.Data.SqlDbType.VarChar).Value = ani.Tipo;
comando1.Parameters.AddWithValue("@IdVal", System.Data.SqlDbType.Int).Value = ani.Id;
comando1.ExecuteNonQuery();
conn.CerrarC();
MessageBox.Show("Se modifico el Tratamiento");
}
public void EliminarTratamientos(Tratamientos ani)
{
SqlDataReader reader = null;
Conexion conn = new Conexion();
string sql1 = "sp_EliminarTratamientos";
SqlCommand comando1 = new SqlCommand(sql1, conn.AbrirC());
comando1.CommandType = System.Data.CommandType.StoredProcedure;
comando1.Parameters.AddWithValue("@IdVal", System.Data.SqlDbType.Int).Value = ani.Id;
comando1.ExecuteNonQuery();
conn.CerrarC();
MessageBox.Show("Se elimino el Tratamientos");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace AndroidAirHockey
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class Puck : Microsoft.Xna.Framework.GameComponent
{
SpriteBatch spriteBatch;
Texture2D texturePuck;
Vector2 puckPosition = Vector2.Zero;
Table table;
int puckRadius = 16;
int intMass = 1;
float fltSpeedX = 2;
float fltSpeedY = 2;
public Puck(Game game)
: base(game)
{
// TODO: Construct any child components here
table = new Table(game);
Initialize();
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
spriteBatch = new SpriteBatch(Game.GraphicsDevice);
//texturePuck = Game.Content.Load<Texture2D>("PuckMed");
texturePuck = Game.Content.Load<Texture2D>("PuckSmallBlack");
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
base.Update(gameTime);
}
public void DrawPuck()
{
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
spriteBatch.Draw(texturePuck, puckPosition, Color.White);
spriteBatch.End();
}
public void DrawPuck(string strStartingPosition)
{
if (strStartingPosition == "StartPosition")
{
puckPosition.X = 240;
puckPosition.Y = 240;
}
else if (strStartingPosition == "PlayerAStart")
{
puckPosition.X = 240;
puckPosition.Y = 305;
}
else if (strStartingPosition == "PlayerBStart")
{
puckPosition.X = 240;
puckPosition.Y = 165;
}
DrawPuck();
}
public void DrawPuck(int x, int y)
{
Vector2 vectorPoint = new Vector2(x, y);
DrawPuck(vectorPoint);
}
public void DrawPuck(float x, float y)
{
Vector2 vectorPoint = new Vector2(x, y);
DrawPuck(vectorPoint);
}
public void DrawPuck(Point point)
{
Vector2 vectorPoint = new Vector2(point.X, point.Y);
DrawPuck(vectorPoint);
}
public void DrawPuck(Vector2 vectorPosition)
{
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
spriteBatch.Draw(texturePuck, vectorPosition, Color.White);
spriteBatch.End();
}
public void Friction()
{
fltSpeedX = fltSpeedX * 0.9979f;
fltSpeedY = fltSpeedY * 0.9979f;
}
public float X { get { return puckPosition.X; } set { puckPosition.X = value; } }
public float Y { get { return puckPosition.Y; } set { puckPosition.Y = value; } }
public float CenterX { get { return puckPosition.X + puckRadius; } set { puckPosition.X = value - puckRadius; } }
public float CenterY { get { return puckPosition.Y + puckRadius; } set { puckPosition.Y = value - puckRadius; } }
public int Radius { get { return puckRadius; } }
public int Mass { get { return intMass; } }
public float SpeedX { get { return fltSpeedX; } set { fltSpeedX = value; } }
public float SpeedY { get { return fltSpeedY; } set { fltSpeedY = value; } }
}
}
|
using Niusys.WebAPI.Common.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Niusys.WebAPI.Models
{
public class SessionObject
{
public string SessionKey { get; set; }
public User LogonUser { get; set; }
}
public class User : IUser<int>
{
public int UserId { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
public string DisplayName { get; set; }
public bool IsActive { get; internal set; }
}
public class UserDevice
{
public int UserId { get; internal set; }
public DateTime ActiveTime { get; internal set; }
public DateTime ExpiredTime { get; internal set; }
public DateTime CreateTime { get; internal set; }
public int DeviceType { get; internal set; }
public string SessionKey { get; internal set; }
}
}
|
namespace _09._UserLogs
{
using System;
using System.Collections.Generic;
public class Startup
{
public static void Main()
{
string input = Console.ReadLine();
SortedDictionary<string, Dictionary<string, int>> users = new SortedDictionary<string, Dictionary<string, int>>();
while (input != "end")
{
string[] inputParts = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
string[] ipParts = inputParts[0].Split('=');
string[] userParts = inputParts[2].Split('=');
string ip = ipParts[1];
string user = userParts[1];
if (!users.ContainsKey(user))
{
users[user] = new Dictionary<string, int>();
}
if (!users[user].ContainsKey(ip))
{
users[user][ip] = 0;
}
users[user][ip]++;
input = Console.ReadLine();
}
foreach (KeyValuePair<string, Dictionary<string, int>> user in users)
{
string username = user.Key;
List<string> ips = new List<string>();
foreach (KeyValuePair<string, int> kvp in user.Value)
{
string ip = $"{kvp.Key} => {kvp.Value}";
ips.Add(ip);
}
Console.WriteLine($"{username}:");
Console.WriteLine($"{string.Join(", ", ips)}.");
}
}
}
}
|
using PopulationFitness.Models.FastMaths;
using PopulationFitness.Models.Genes.BitSet;
using System;
namespace PopulationFitness.Models.Genes.LocalMinima
{
public class AckleysGenes : NormalizingBitSetGenes
{
private class NormalizationRatioCalculator : IValueCalculator<Double> {
public double CalculateValue(long n)
{
/*
{f left (x right )} over {20 left (1- {e} ^ {-0.2α} right ) +e- {e} ^ {-1}}
*/
return 20.0 * (1.0 - Math.Exp(-0.2 * Alpha)) + Math.E - Math.Exp(-1.0);
}
}
private static readonly ExpensiveCalculatedValues<double> NormalizationRatios = new ExpensiveCalculatedValues<double>(new NormalizationRatioCalculator());
private const double Alpha = 4.5;
private const double TwentyPlusE = 20.0 + Math.E;
private const double TwoPi = 2.0 * Math.PI;
public AckleysGenes(Config config) : base(config, 5.0) { }
protected override double CalculateNormalizationRatio(int n)
{
return NormalizationRatios.FindOrCalculate(n);
}
protected override double CalculateFitnessFromIntegers(long[] integer_values)
{
/*
http://www.cs.unm.edu/~neal.holts/dga/benchmarkFunction/ackley.html
f left (x right ) =-20 exp {left (-0.2 sqrt {{1} over {n} sum from {i=1} to {n} {{x} rsub {i} rsup {2}}} right )} - exp {left ({1} over {n} sum from {i=1} to {n} {cos {left ({2πx} rsub {i} right )}} right ) +20+ exp (1)}
*/
double firstSum = 0.0;
double secondSum = 0.0;
foreach (long integer_value in integer_values)
{
double x = Interpolate(integer_value);
firstSum += x * x;
secondSum += CosSineCache.Cos(TwoPi * x);
}
double n = integer_values.Length;
return -20.0 * Math.Exp(-0.2 * Math.Sqrt(firstSum / n)) - Math.Exp(secondSum / n) + TwentyPlusE;
}
}
}
|
public class Solution {
public IList<string> FindWords(char[][] board, string[] words) {
var res = new List<string>();
Trie t = new Trie();
foreach(string word in words) {
t.Insert(word);
}
int m = board.Length, n = board[0].Length;
bool[][] visited = new bool[m][];
for (int i = 0; i < m; i ++) {
visited[i] = new bool[n];
}
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
DFSHelper(board, i, j, t.root, res, visited);
}
}
return res;
}
private void DFSHelper(char[][] board, int i, int j, TrieNode curr, IList<string> res, bool[][] visited) {
if (curr.str != null) {
res.Add(curr.str);
curr.str = null; // this is to avoid duplicates in the result
}
if (i < 0 || i >= board.Length || j < 0 || j >= board[0].Length || curr.children[board[i][j] - 'a'] == null || visited[i][j]) return;
TrieNode next = curr.children[board[i][j] - 'a'];
visited[i][j] = true;
DFSHelper(board, i+1, j, next, res, visited);
DFSHelper(board, i-1, j, next, res, visited);
DFSHelper(board, i, j+1, next, res, visited);
DFSHelper(board, i, j-1, next, res, visited);
visited[i][j] = false;
}
}
public class TrieNode {
public TrieNode[] children;
public string str;
public TrieNode() {
children = new TrieNode[26];
}
}
public class Trie {
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void Insert(string word) {
TrieNode curr = root;
for (int i = 0; i < word.Length; i ++) {
char c = word[i];
if (curr.children[c - 'a'] == null) {
curr.children[c - 'a'] = new TrieNode();
}
curr = curr.children[c - 'a'];
}
curr.str = word;
}
}
|
using System;
using System.Runtime.Serialization;
namespace Phenix.Business
{
/// <summary>
/// 校验限制保存时异常
/// </summary>
[Serializable]
public class CheckSaveException : Exception
{
/// <summary>
/// 校验限制保存时异常
/// </summary>
public CheckSaveException()
: base() { }
/// <summary>
/// 校验限制保存时异常
/// </summary>
public CheckSaveException(string message)
: base(message) { }
/// <summary>
/// 校验限制保存时异常
/// </summary>
public CheckSaveException(string message, Exception innerException)
: base(message, innerException) { }
/// <summary>
/// 校验限制保存时异常
/// </summary>
public CheckSaveException(IBusiness business)
: base(business == null ? null : String.Format(Phenix.Business.Properties.Resources.CheckSaveException, business.Caption))
{
_business = business;
}
/// <summary>
/// 校验限制保存时异常
/// </summary>
public CheckSaveException(IBusiness business, string message)
: base(business == null ? message : String.Format(Phenix.Business.Properties.Resources.CheckSaveException + '\n' + message, business.Caption))
{
_business = business;
}
/// <summary>
/// 校验限制保存时异常
/// </summary>
public CheckSaveException(IBusiness business, Exception exception)
: base(business == null ? exception.Message : String.Format(Phenix.Business.Properties.Resources.CheckSaveException + '\n' + exception.Message, business.Caption), exception)
{
_business = business;
}
#region Serialization
/// <summary>
/// 序列化
/// </summary>
protected CheckSaveException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info == null)
throw new ArgumentNullException("info");
_business = (IBusiness)info.GetValue("_business", typeof(IBusiness));
}
/// <summary>
/// 反序列化
/// </summary>
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue("_business", _business);
}
#endregion
#region 属性
private readonly IBusiness _business;
/// <summary>
/// 业务对象
/// </summary>
public IBusiness Business
{
get { return _business; }
}
#endregion
}
}
|
namespace SOLIDPrinciples.OCP.Example1.Good
{
public class CalculadoraDePrecos
{
private readonly ITabelaDePreco tabela;
private readonly IServicoDeEntrega entrega;
public CalculadoraDePrecos(
ITabelaDePreco tabela,
IServicoDeEntrega entrega) =>
(this.tabela, this.entrega) = (tabela, entrega);
public double Calcular(Compra produto)
{
double desconto = tabela.DescontoPara(produto.Valor);
double frete = entrega.Para(produto.Cidade);
return produto.Valor * (1 - desconto) + frete;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Functions.Filters;
using DelftTools.Functions.Generic;
using DelftTools.Units;
using DelftTools.Utils.Aop.NotifyPropertyChange;
namespace DelftTools.Functions.Conversion
{
/// <summary>
/// Convert a certain variable within a variable (for example x(t) convert t-t')
/// Here x is variable, t is sourcevariable, t' is target variable
/// </summary>
/// <typeparam name="TVariable">Type of resulting variable</typeparam>
/// <typeparam name="TTarget">Type of converted variable</typeparam>
/// <typeparam name="TSource">Type of source variable</typeparam>
public class ConvertedVariable<TVariable, TTarget, TSource> : ConvertedFunction<TTarget, TSource>, IVariable<TVariable>
where TTarget : IComparable where TSource : IComparable where TVariable : IComparable
{
public ConvertedVariable(IVariable parent,IVariable<TSource> variableToConvert, Func<TTarget, TSource> toSource, Func<TSource, TTarget> toTarget)
:base(parent,variableToConvert,toSource,toTarget)
{
if (variableToConvert.Arguments.Count > 0)
throw new NotImplementedException("Conversion of non-arguments not supported yet");
//convertedVariable = this;
}
public void SetValues<T>(IEnumerable<T> values, params IVariableFilter[] filters)
{
//convert values to parent values
IEnumerable<TTarget> targetValues = (IEnumerable<TTarget>)values;
Parent.SetValues(targetValues.Select(s=>toSource(s)),ConvertFilters(filters));
}
public new IVariable Parent
{
get
{
return (IVariable) base.Parent;
}
set
{
base.Parent = value;
}
}
public IMultiDimensionalArray<TVariable> GetValues(params IVariableFilter[] filters)
{
return GetValues<TVariable>();
}
IVariable<TVariable> IVariable<TVariable>.Clone()
{
throw new NotImplementedException();
}
//TODO: get this addvalues mess out.
public void AddValues<T>(IEnumerable<T> values)
{
throw new NotImplementedException();
}
[NoNotifyPropertyChange]
public bool GenerateUniqueValueForDefaultValue { get; set; }
public InterpolationType InterpolationType { get; set; }
public ExtrapolationType ExtrapolationType { get; set; }
public NextValueGenerator<TVariable> NextValueGenerator
{
get; set;
}
object IVariable.MaxValue
{
get { return MaxValue; }
}
public IMultiDimensionalArray<TVariable> AllValues
{
get { return Values; }
}
object IVariable.MinValue
{
get { return MinValue; }
}
public TVariable MinValue
{
get
{
if ((variableToConvert == Parent) && typeof(TVariable) == typeof(TTarget))
{
//no nice cast here :(
return (TVariable)(object)toTarget((TSource)Parent.MinValue);
}
return (TVariable)Parent.MinValue;
}
}
public TVariable MaxValue
{
get
{
if ((variableToConvert == Parent) && typeof(TVariable) == typeof(TTarget))
{
//no nice cast here :(
return (TVariable)(object)toTarget((TSource)Parent.MaxValue);
}
return (TVariable)Parent.MaxValue;
}
}
public void AddValues<T>(IEnumerable<TVariable> values)
{
IEnumerable<TTarget> targetValues = (IEnumerable<TTarget>)values;
Parent.AddValues(targetValues.Select(s => toSource(s)));
}
public void AddValues(IEnumerable values)
{
//TODO redirect parent?
IEnumerable<TTarget> targetValues = (IEnumerable<TTarget>)values;
Parent.AddValues(targetValues.Select(s => toSource(s)));
}
public IMultiDimensionalArray CreateStorageArray()
{
return new MultiDimensionalArray<TTarget>();
}
public IMultiDimensionalArray CreateStorageArray(IMultiDimensionalArray values)
{
return new MultiDimensionalArray<TTarget>(values.Cast<TTarget>().ToList(), values.Shape);
}
public bool IsAutoSorted
{
get
{
if (variableToConvert == null)
{
return true;//a wild guess :(
}
return variableToConvert.IsAutoSorted;
}
set { throw new NotImplementedException(); }
}
/*
public TVariable MinValue
{
get { throw new NotImplementedException(); }
}
public TVariable MaxValue
{
get { throw new NotImplementedException(); }
}
object IVariable.MaxValue
{
get { return MaxValue; }
}
object IVariable.MinValue
{
get { return MinValue; }
}
*/
public override IMultiDimensionalArray<T> GetValues<T>(params IVariableFilter[] filters)
{
return (IMultiDimensionalArray<T>) base.GetValues(filters);
}
private IVariableFilter[] ConvertFilters(IEnumerable<IVariableFilter> filters)
{
//rewrite variable value filter to the domain of the source.
IList<IVariableFilter> filterList = new List<IVariableFilter>();
foreach (var filter in filters)
{
//TODO: rewrite to IEnumerable etc
if (filter is IVariableValueFilter && filter.Variable == convertedVariable)
{
var variableValueFilter = filter as IVariableValueFilter;
IList values = new List<TSource>();
foreach (TTarget obj in variableValueFilter.Values)
{
values.Add(toSource(obj));
}
filterList.Add(variableToConvert.CreateValuesFilter(values));
}
else
{
filterList.Add(filter);
}
}
return filterList.ToArray();
}
private IUnit unit;
public virtual IUnit Unit
{
get
{
return Parent != null ? Parent.Unit : unit;
}
set
{
if (Parent == null)
{
unit = value;
}
else
{
throw new Exception("Can't set unit for a filtered function.");
}
}
}
public Type ValueType
{
get
{
if (variableToConvert == Parent)
return typeof(TTarget);
return Parent.ValueType;
}
set
{
throw new NotImplementedException();
}
}
public TVariable DefaultValue
{
get
{
if ((variableToConvert == Parent) && typeof(TVariable) == typeof(TTarget))
{
//no nice cast here :(
return (TVariable)(object)toTarget((TSource) Parent.DefaultValue);
}
return (TVariable) Parent.DefaultValue;
}
set { throw new NotImplementedException(); }
}
public IList<TVariable> NoDataValues
{
get;
set;
}
public virtual object NoDataValue
{
get
{
return NoDataValues.Count != 0 ? (object)NoDataValues[0] : null;
}
set
{
NoDataValues.Clear();
NoDataValues.Add((TVariable)value);
}
}
public IMultiDimensionalArray<TVariable> Values
{
get
{
return GetValues<TVariable>();
}
set
{
SetValues(value);
}
}
object IMeasurable.DefaultValue
{
get ; set;
}
object IMeasurable.MinValidValue { get; set; }
object IMeasurable.MaxValidValue { get; set; }
IMeasurable IMeasurable.Clone()
{
return Clone();
}
IMultiDimensionalArray IVariable.Values
{
get
{
return base.GetValues();
}
set
{
SetValues((IEnumerable<TVariable>) value);
}
}
public object DefaultStep
{
get; set;
}
IList IVariable.NoDataValues
{
get;
set;
}
public IDictionary<string, string> Attributes
{
get;
set;
}
public IVariable Filter(params IVariableFilter[] filters)
{
return (IVariable)base.Filter(filters);
}
public int FixedSize
{
get
{
if (Parent != null)
{
return Parent.FixedSize;
}
return 0;
}
set { Parent.FixedSize = value; }
}
public bool IsFixedSize
{
get { return Parent.IsFixedSize; }
}
public IVariable Clone()
{
throw new NotImplementedException();
}
#region IMeasurable Members
public virtual string DisplayName
{
get { return string.Format("{0} [{1}]", Name, ((Unit != null) ? Unit.Symbol : "-")); }
}
#endregion
public IVariableValueFilter CreateValueFilter(object value)
{
return new VariableValueFilter<TVariable>(this, new[] { (TVariable)value });
}
public IVariableValueFilter CreateValuesFilter(IEnumerable values)
{
return new VariableValueFilter<TVariable>(this, values.Cast<TVariable>());
}
public IMultiDimensionalArray CachedValues
{
get;
set;
}
public bool AllowSetInterpolationType { get; set; }
public bool AllowSetExtrapolationType { get; set; }
public bool SkipUniqueValuesCheck
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public void CopyFrom(object source)
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CarRental.API.BL.Models.Reservations
{
public class CreateReservationModel
{
public Guid ClientId { get; set; }
public Guid CarId { get; set; }
public DateTime RentalStartDate { get; set; }
public DateTime RentalEndDate { get; set; }
public Guid PickUpLocation { get; set; }
public Guid DropOffLocation { get; set; }
public int TotalPrice { get; set; }
}
}
|
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Configuration;
using System.Security.Cryptography;
using System.IO;
namespace CIPMSBC
{
public class CamperApplication
{
//AG 1/27/2009
//to fill genders values to the dropdown
public DataSet get_Genders()
{
CIPDataAccess dal = new CIPDataAccess();
try
{
DataSet dsGenders;
dsGenders = dal.getDataset("USP_GetAllGenders", null);
return dsGenders;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to fill the state values to the dropdown
public DataSet get_States()
{
CIPDataAccess dal = new CIPDataAccess();
try
{
DataSet dsStates;
dsStates = dal.getDataset("USP_GetAllStates", null);
return dsStates;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to fill the state values depending on the Federation
public DataSet get_FederationStates(int FederationID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
DataSet dsStates;
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FederationID", FederationID);
dsStates = dal.getDataset("usp_GetFederationStates", param);
return dsStates;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to fill the state values to the dropdown
public DataSet get_CountryStates(int countryID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@Country", countryID);
DataSet dsStates;
dsStates = dal.getDataset("usp_GetCountryStates", param);
return dsStates;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get all the cities based on the state selected
public DataSet get_Cities(string stateId)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@State", stateId);
DataSet dsCities;
dsCities = dal.getDataset("[USP_GetCities]", param);
return dsCities;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to Insert the parent info (step 3 of camper application)
public int UpdateFederationId(string FJCID, string FEDID)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@FederationID", FEDID);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateFederationID]", param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int InsertCamperInfo(UserDetails UserInfo, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[18];
param[0] = new SqlParameter("@First_Name", UserInfo.FirstName);
param[1] = new SqlParameter("@Last_Name", UserInfo.LastName);
param[2] = new SqlParameter("@Street_Address", UserInfo.Address);
param[3] = new SqlParameter("@City", UserInfo.City);
param[4] = new SqlParameter("@State", UserInfo.State);
param[5] = new SqlParameter("@Country", UserInfo.Country);
param[6] = new SqlParameter("@Zip_Code", UserInfo.ZipCode);
param[7] = new SqlParameter("@Home_Phone", UserInfo.HomePhone);
param[8] = new SqlParameter("@Email", UserInfo.PersonalEmail);
param[9] = new SqlParameter("@DAte_Of_Birth", UserInfo.DateofBirth);
param[10] = new SqlParameter("@Age", UserInfo.Age);
param[11] = new SqlParameter("@OFJCID", SqlDbType.NVarChar, 50);
param[11].Direction = ParameterDirection.Output;
param[12] = new SqlParameter("@Gender", UserInfo.Gender);
param[13] = new SqlParameter("@IsJewish", UserInfo.IsJewish);
param[14] = new SqlParameter("@CMART_MiiP_ReferalCode", UserInfo.CMART_MiiP_ReferalCode);
param[15] = new SqlParameter("@PJLCode", UserInfo.PJLCode);
param[16] = new SqlParameter("@NLCode", UserInfo.NLCode);
param[17] = new SqlParameter("@SpecialCode", UserInfo.SpecialCode);
rowsaffected = dal.ExecuteNonQuery("[USP_InsertCamperApplication]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to Insert the parent info (step 3 of camper application)
public int UpdateCamperInfo(UserDetails CamperInfo)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[20];
param[0] = new SqlParameter("@First_Name", CamperInfo.FirstName);
param[1] = new SqlParameter("@Last_Name", CamperInfo.LastName);
param[2] = new SqlParameter("@Street_Address", CamperInfo.Address);
param[3] = new SqlParameter("@City", CamperInfo.City);
param[4] = new SqlParameter("@State", CamperInfo.State);
param[5] = new SqlParameter("@Country", CamperInfo.Country);
param[6] = new SqlParameter("@Zip_Code", CamperInfo.ZipCode);
param[7] = new SqlParameter("@Home_Phone", CamperInfo.HomePhone);
param[8] = new SqlParameter("@Personal_Email", CamperInfo.PersonalEmail);
param[9] = new SqlParameter("@DAte_Of_Birth", CamperInfo.DateofBirth);
param[10] = new SqlParameter("@Age", CamperInfo.Age);
param[11] = new SqlParameter("@FJCID", CamperInfo.FJCID);
param[12] = new SqlParameter("@User", CamperInfo.ModifiedBy);
param[13] = new SqlParameter("@Comment", CamperInfo.Comments);
param[14] = new SqlParameter("@Gender", CamperInfo.Gender);
param[15] = new SqlParameter("@IsJewish", CamperInfo.IsJewish);
param[16] = new SqlParameter("@CMART_MiiP_ReferalCode", CamperInfo.CMART_MiiP_ReferalCode);
param[17] = new SqlParameter("@PJLCode", CamperInfo.PJLCode);
param[18] = new SqlParameter("@NLCode", CamperInfo.NLCode);
param[19] = new SqlParameter("@SpecialCode", CamperInfo.SpecialCode);
rowsaffected = dal.ExecuteNonQuery("[usp_UpadteCamperApplication]", param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get the Camper Info from the database (step 1 of camper application)
public UserDetails getCamperInfo(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
UserDetails UserInfo = new UserDetails();
DataSet dsUserInfo = new DataSet();
SqlParameter[] param = new SqlParameter[1];
DataRow dr;
try
{
param[0] = new SqlParameter("@FJCID", FJCID);
dsUserInfo = dal.getDataset("usp_GetCamperApplication", param);
if (dsUserInfo.Tables[0].Rows.Count > 0)
{
dr = dsUserInfo.Tables[0].Rows[0];
UserInfo.FirstName = dr["FirstName"].ToString();
UserInfo.LastName = dr["LastName"].ToString();
UserInfo.ZipCode = dr["Zip"].ToString();
UserInfo.Address = dr["Street"].ToString();
UserInfo.Country = dr["Country"].ToString();
UserInfo.State = dr["State"].ToString();
UserInfo.City = dr["City"].ToString();
UserInfo.PersonalEmail = dr["PersonalEmail"].ToString();
UserInfo.DateofBirth = dr["DateOfBirth"].ToString();
UserInfo.Age = dr["Age"].ToString();
UserInfo.FJCID = dr["FJCID"].ToString();
UserInfo.Gender = dr["Gender"].ToString();
UserInfo.HomePhone = dr["HomePhone"].ToString();
UserInfo.IsJewish = dr["IsJewish"].ToString();
UserInfo.CMART_MiiP_ReferalCode = dr["CMART_MiiP_ReferalCode"].ToString();
UserInfo.PJLCode= dr["PJLCode"].ToString();
UserInfo.NLCode = dr["NLCode"].ToString();
UserInfo.SpecialCode = dr["SpecialCode"].ToString();
}
return UserInfo;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
dsUserInfo.Dispose();
dsUserInfo = null;
param = null;
}
}
//to get the Parent Info from the database (step 3 of camper application)
public UserDetails getParentInfo(string FJCID, string IsParentInfo1)
{
CIPDataAccess dal = new CIPDataAccess();
UserDetails ParentInfo = new UserDetails();
DataSet dsParentInfo = new DataSet();
SqlParameter[] param = new SqlParameter[2];
DataRow dr;
try
{
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Flag", IsParentInfo1);
dsParentInfo = dal.getDataset("[usp_GetParentInfo]", param);
if (dsParentInfo.Tables[0].Rows.Count > 0)
{
dr = dsParentInfo.Tables[0].Rows[0];
ParentInfo.FirstName = dr["FirstName"].ToString();
ParentInfo.LastName = dr["LastName"].ToString();
ParentInfo.ZipCode = dr["Zip"].ToString();
ParentInfo.Address = dr["Street"].ToString();
ParentInfo.Country = dr["Country"].ToString();
ParentInfo.State = dr["State"].ToString();
ParentInfo.City = dr["City"].ToString();
ParentInfo.PersonalEmail = dr["PersonalEmail"].ToString();
ParentInfo.WorkEmail = dr["WorkEmail"].ToString();
ParentInfo.HomePhone = dr["HomePhone"].ToString();
ParentInfo.WorkPhone = dr["WorkPhone"].ToString();
if (IsParentInfo1 == "Y")
ParentInfo.Parent1Id = dr["ID"].ToString();
else
ParentInfo.Parent2Id = dr["ID"].ToString();
}
return ParentInfo;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
dsParentInfo.Dispose();
dsParentInfo = null;
param = null;
}
}
//to Insert the parent info (step 3 of camper application)
public int InsertParentInfo(UserDetails UserInfo)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[13];
param[0] = new SqlParameter("@FJCID", UserInfo.FJCID);
param[1] = new SqlParameter("@First_Name", UserInfo.FirstName);
param[2] = new SqlParameter("@Last_Name", UserInfo.LastName);
param[3] = new SqlParameter("@Street_Address", UserInfo.Address);
param[4] = new SqlParameter("@City", UserInfo.City);
param[5] = new SqlParameter("@State", UserInfo.State);
param[6] = new SqlParameter("@Country", UserInfo.Country);
param[7] = new SqlParameter("@Zip_Code", UserInfo.ZipCode);
param[8] = new SqlParameter("@Home_Phone", UserInfo.HomePhone);
param[9] = new SqlParameter("@Personal_Email", UserInfo.PersonalEmail);
param[10] = new SqlParameter("@Work_Phone", UserInfo.WorkPhone);
param[11] = new SqlParameter("@Work_Email", UserInfo.WorkEmail);
param[12] = new SqlParameter("@Flag", UserInfo.IsParentInfo1);
rowsaffected = dal.ExecuteNonQuery("USP_InsertParentInfo", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//added by sandhya
public int validateNLCode(string NLCode)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds=new DataSet();
DataRow dr;
int rowsaffected=-1;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@NLCode", NLCode);
ds= dal.getDataset("[usp_ValidateNLCode]", param);
if (ds.Tables[0].Rows.Count > 0)
{
//dr = ds.Tables[0].Rows[0];
string valid = ds.Tables[0].Rows[0][0].ToString();
rowsaffected = Convert.ToInt32(valid);
}
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void updateNLCode(string NLCode)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
DataRow dr;
int rowsaffected = -1;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@NLCode", NLCode);
dal.ExecuteNonQuery("[usp_UpdateNLCode]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public string CheckEligibility(string FJCID,string LastFed,string strCampYear)
{
DataSet dsPersonal = new DataSet();
DataSet dsMiiPReferalCodeDetails = new DataSet();
UserDetails Info = getCamperInfo(FJCID);
General objGeneral=new General();
string strFedId = string.Empty, strNextURL = string.Empty,strCampId=string.Empty;
if (Info.CMART_MiiP_ReferalCode != string.Empty)
dsMiiPReferalCodeDetails = objGeneral.GetMiiPReferalCode(Info.CMART_MiiP_ReferalCode, strCampYear);
DataSet dsFed = objGeneral.GetFederationForZipCode(Info.ZipCode);
if (dsFed.Tables.Count > 0)
{
if (dsFed.Tables[0].Rows.Count > 0)
{
strFedId = dsFed.Tables[0].Rows[0][0].ToString();
}
}
if (LastFed == "JWest" && strFedId == "72")
{
strNextURL = "~/Enrollment/SanDiego/Summary.aspx" + "," + "72" + "," + strCampId;
return strNextURL;
}
else if ((dsMiiPReferalCodeDetails.Tables.Count > 0) && (Info.CMART_MiiP_ReferalCode != string.Empty) && (!LastFed.Contains("MidWest")))
{
if (dsMiiPReferalCodeDetails.Tables[0].Rows.Count > 0)
{
DataRow drMiiP = dsMiiPReferalCodeDetails.Tables[0].Rows[0];
strFedId = drMiiP["FederationID"].ToString();
strNextURL = drMiiP["NavigationURL"].ToString();
strCampId = drMiiP["CampID"].ToString();
if (drMiiP["CampID"].ToString() == "1146")
{
if (strNextURL.ToUpper().Contains("URJ/"))
strNextURL = strNextURL.Replace("URJ/", "URJ/Acadamy");
strNextURL = strNextURL + "," + strFedId + "," + strCampId;
LastFed = "MidWest";
return strNextURL;
}
LastFed = "MidWest";
strNextURL = strNextURL + "," + "48" + "," + "";
}
else if ((Info.PJLCode != string.Empty) && (!LastFed.Contains("PJL")))
{
char ch = ',';
//string[] PJLCode = ConfigurationManager.AppSettings["PJLCode"].ToString().Split(ch);
DataTable dtCampYearPJLCodes = objGeneral.GetPJLCodes(strCampYear).Tables[0];
string[] PJLCode = new string[dtCampYearPJLCodes.Rows.Count];
//dtCampYearPJLCodes.Rows.CopyTo(PJLCode, 0);
for (int i = 0; i < dtCampYearPJLCodes.Rows.Count; i++)
{
PJLCode[i] = dtCampYearPJLCodes.Rows[i][0].ToString();
}
for (int i = 0; i < PJLCode.Length; i++)
{
if (Info.PJLCode.Trim().ToUpper() == PJLCode[i].ToUpper())
{
strNextURL = "~/Enrollment/PJL/Summary.aspx";
strNextURL = strNextURL + "," + ConfigurationManager.AppSettings["PJL"].ToString() + "," + "";
LastFed = "PJL";
strFedId = ConfigurationManager.AppSettings["PJL"].ToString();
return strNextURL;
}
}
}
else //if ((LastFed.Contains("NL")))
{
strNextURL = "Step1_NL.aspx" + "," + "" + "," + ""; //to be redirected to National Landing page
}
}
else if ((Info.PJLCode != string.Empty) && (!LastFed.Contains("PJL")))
{
char ch = ',';
//string[] PJLCode = ConfigurationManager.AppSettings["PJLCode"].ToString().Split(ch);
DataTable dtCampYearPJLCodes = objGeneral.GetPJLCodes(strCampYear).Tables[0];
string[] PJLCode = new string[dtCampYearPJLCodes.Rows.Count];
for (int i = 0; i < dtCampYearPJLCodes.Rows.Count; i++)
{
PJLCode[i] = dtCampYearPJLCodes.Rows[i][0].ToString();
}
//dtCampYearPJLCodes.Rows.CopyTo(PJLCode, 0);
for (int i = 0; i < PJLCode.Length; i++)
{
if (Info.PJLCode.Trim().ToUpper() == PJLCode[i].ToUpper())
{
strNextURL = "~/Enrollment/PJL/Summary.aspx";
strNextURL = strNextURL + "," + ConfigurationManager.AppSettings["PJL"].ToString() + "," + "";
LastFed = "PJL";
strFedId = ConfigurationManager.AppSettings["PJL"].ToString();
return strNextURL;
}
}
}
else //if ((LastFed.Contains("NL")))
{
strNextURL = "Step1_NL.aspx" + "," + "" + "," + ""; //to be redirected to National Landing page
}
return strNextURL;
}
//to Update the parent info (step 3 of camper application)
public int UpdateParentInfo(UserDetails ParentInfo)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[15];
param[0] = new SqlParameter("@FJCID", ParentInfo.FJCID);
param[1] = new SqlParameter("@First_Name", ParentInfo.FirstName);
param[2] = new SqlParameter("@Last_Name", ParentInfo.LastName);
param[3] = new SqlParameter("@Street_Address", ParentInfo.Address);
param[4] = new SqlParameter("@City", ParentInfo.City);
param[5] = new SqlParameter("@State", ParentInfo.State);
param[6] = new SqlParameter("@Country", ParentInfo.Country);
param[7] = new SqlParameter("@Zip_Code", ParentInfo.ZipCode);
param[8] = new SqlParameter("@Home_Phone", ParentInfo.HomePhone);
param[9] = new SqlParameter("@Personal_Email", ParentInfo.PersonalEmail);
param[10] = new SqlParameter("@Work_Phone", ParentInfo.WorkPhone);
param[11] = new SqlParameter("@Work_Email", ParentInfo.WorkEmail);
param[12] = new SqlParameter("@Flag", ParentInfo.IsParentInfo1);
param[13] = new SqlParameter("@User", ParentInfo.ModifiedBy);
param[14] = new SqlParameter("@Comment", ParentInfo.Comments);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateParentInfo]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to Insert the Camper Answers (step 2 and 4)
public int InsertCamperAnswers(string FJCID, string Answers, string ModifiedBy, string Comments)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Answers", Answers);
param[2] = new SqlParameter("@userID", ModifiedBy);
param[3] = new SqlParameter("@Comment", Comments);
param[4] = new SqlParameter("@originalValue", DBNull.Value.ToString());
param[5] = new SqlParameter("@changedValue", DBNull.Value.ToString());
rowsaffected = dal.ExecuteNonQuery("[USP_InsertCamperAnswers]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int InsertHoldingCamper(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
rowsaffected = dal.ExecuteNonQuery("[usp_InsertHoldingCamper]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get the Camper Answers (step 2 and 4)
public DataSet getCamperAnswers(string FJCID, string FromQuestionId, string ToQuestionId, string IsAllQuestions)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet dsCamperAnswers;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@FromQ", FromQuestionId);
param[2] = new SqlParameter("@ToQ", ToQuestionId);
param[3] = new SqlParameter("@ALL", IsAllQuestions);
dsCamperAnswers = dal.getDataset("[usp_GetCamperAnswers]", param);
return dsCamperAnswers;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get all the cities based on the state selected
public DataSet getCamperApplication(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
DataSet dsCamperApplications;
dsCamperApplications = dal.getDataset("[usp_GetCamperApplication]", param);
return dsCamperApplications;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get all the cities based on the state selected
public DataSet getCamperGrantInfo(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
DataSet dsCamperGrant;
dsCamperGrant = dal.getDataset("[usp_GetCamperGrantInfo]", param);
return dsCamperGrant;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int getDaysInCamp(string FJCID)
{
int days = 0;
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
DataSet dsDaysInCamp;
dsDaysInCamp = dal.getDataset("[usp_GetDaysInCamp]", param);
if (dsDaysInCamp.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(dsDaysInCamp.Tables[0].Rows[0]["Days"]))
days = Convert.ToInt32(dsDaysInCamp.Tables[0].Rows[0]["Days"]);
}
return days;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int getTimeInCamp(string FJCID)
{
int timeInCamp = 0;
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
DataSet dsTimeInCamp;
dsTimeInCamp = dal.getDataset("[usp_GetTimeInCamp]", param);
if (dsTimeInCamp.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(dsTimeInCamp.Tables[0].Rows[0]["TimeInCamp"]))
timeInCamp = Convert.ToInt32(dsTimeInCamp.Tables[0].Rows[0]["TimeInCamp"]);
}
return timeInCamp;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public decimal getCamperGrantForDays(string FJCID, int Days)
{
decimal StandardGrant = 0;
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Days", Days);
DataSet dsCamperGrant;
dsCamperGrant = dal.getDataset("[usp_GetCamperGrantForDays]", param);
if (dsCamperGrant.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(dsCamperGrant.Tables[0].Rows[0]["StandardGrant"]))
StandardGrant = Convert.ToDecimal(dsCamperGrant.Tables[0].Rows[0]["StandardGrant"]);
}
return StandardGrant;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public decimal getCamperGrantForTimeInCamp(string FJCID, int Days, int TimeInCamp)
{
decimal StandardGrant = 0;
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Days", Days);
param[2] = new SqlParameter("@TimeInCamp", TimeInCamp);
DataSet dsCamperGrant;
dsCamperGrant = dal.getDataset("[usp_GetCamperGrantForTimeInCamp]", param);
if (dsCamperGrant.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(dsCamperGrant.Tables[0].Rows[0]["StandardGrant"]))
StandardGrant = Convert.ToDecimal(dsCamperGrant.Tables[0].Rows[0]["StandardGrant"]);
}
return StandardGrant;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public decimal getCamperDefaultAmount(string FJCID, int Days)
{
decimal StandardGrant = 0;
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Days", Days);
DataSet dsCamperGrant;
dsCamperGrant = dal.getDataset("[usp_GetCamperDefaultGrantAmount]", param);
if (dsCamperGrant.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(dsCamperGrant.Tables[0].Rows[0]["StandardGrant"]))
StandardGrant = Convert.ToDecimal(dsCamperGrant.Tables[0].Rows[0]["StandardGrant"]);
}
return StandardGrant;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get all the cities based on the state selected
public structThresholdInfo GetFedThresholdInfo(int FederationID)
{
CIPDataAccess dal = new CIPDataAccess();
structThresholdInfo structThresholdInfo = new structThresholdInfo();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FederationID", FederationID);
DataSet dsThresholdInfo;
dsThresholdInfo = dal.getDataset("[usp_GetFedThresholdInfo]", param);
if (!Convert.IsDBNull(dsThresholdInfo.Tables[0].Rows[0]["NbrOfPmtRequested1"]))
structThresholdInfo.NbrOfPmtRequested1 = Convert.ToInt32(dsThresholdInfo.Tables[0].Rows[0]["NbrOfPmtRequested1"]);
if (!Convert.IsDBNull(dsThresholdInfo.Tables[0].Rows[0]["NbrOfPmtRequested2"]))
structThresholdInfo.NbrOfPmtRequested2 = Convert.ToInt32(dsThresholdInfo.Tables[0].Rows[0]["NbrOfPmtRequested2"]);
if (!Convert.IsDBNull(dsThresholdInfo.Tables[0].Rows[0]["ThresholdType"]))
structThresholdInfo.ThresholdType = Convert.ToString(dsThresholdInfo.Tables[0].Rows[0]["ThresholdType"]);
if (!Convert.IsDBNull(dsThresholdInfo.Tables[0].Rows[0]["ThresholdTypeDescription"]))
structThresholdInfo.ThresholdTypeDescription = Convert.ToString(dsThresholdInfo.Tables[0].Rows[0]["ThresholdTypeDescription"]);
if (!Convert.IsDBNull(dsThresholdInfo.Tables[0].Rows[0]["Threshold1"]))
structThresholdInfo.Threshold1 = Convert.ToInt32(dsThresholdInfo.Tables[0].Rows[0]["Threshold1"]);
if (!Convert.IsDBNull(dsThresholdInfo.Tables[0].Rows[0]["Threshold2"]))
structThresholdInfo.Threshold2 = Convert.ToInt32(dsThresholdInfo.Tables[0].Rows[0]["Threshold2"]);
return structThresholdInfo;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to Update the parent info (step 3 of camper application)
public int submitCamperApplication(String FJCID, String Comment,int ModifiedBy, int Status)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Comment", Comment);
param[2] = new SqlParameter("@User", ModifiedBy);
param[3] = new SqlParameter("@Status", Status);
rowsaffected = dal.ExecuteNonQuery("[usp_SubmitCamperApplication]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update the status of the Camper Application.
public int UpdateStatus(String FJCID, int Status, String Comment, int ModifiedBy)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Status", Status);
param[2] = new SqlParameter("@Reason", Comment);
param[3] = new SqlParameter("@User", ModifiedBy);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateStatus]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//added by sandhya
public int updtaeCampYear(String FJCID, int CampYear, String Comment, int ModifiedBy)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@CampYear", CampYear);
param[2] = new SqlParameter("@Reason", Comment);
param[3] = new SqlParameter("@User", ModifiedBy);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateCampYear]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//inserts record into tblApplicationChangeHistory table
//none parameters are nullable
public int InsertApplicationChangeHistory( string FJCID,
string OriginalValue,
string ChangedValue,
string Comment,
string Type,
int ModifiedBy)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@OriginalValue", OriginalValue);
param[2] = new SqlParameter("@changedValue", ChangedValue);
param[3] = new SqlParameter("@comment", Comment);
param[4] = new SqlParameter("@Type", Type);
param[5] = new SqlParameter("@ModifiedBy", ModifiedBy);
rowsaffected = dal.ExecuteNonQuery("[usp_InsertApplicationChangeHistory]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update the status of the Camper Application.
public int updateCamp(String FJCID, int Camp, String Reason, int ModifiedBy)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Camp", Camp);
param[2] = new SqlParameter("@Reason", Reason);
param[3] = new SqlParameter("@User", ModifiedBy);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateCamp]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void UpdateTimeInCampInApplication(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
dal.ExecuteNonQuery("[usp_UpdateTimeInCampInApplication]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update amount for the Camper Application
public void UpdateTimeInCamp(int FederationID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FederationID", FederationID);
dal.ExecuteNonQuery("[usp_UpdateTimeInCamp]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void UpdateTimeInCamp_PaymentReport(int FederationID, int campYear)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FederationID", FederationID);
param[1] = new SqlParameter("@CampYear", campYear);
dal.ExecuteNonQuery("[usp_UpdateTimeInCamp_PaymentReport]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update amount for the Camper Application
public void UpdateAmount(string strFJCID, double Amt, int iUser, string strReason)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", strFJCID);
param[1] = new SqlParameter("@Amt", Amt);
param[2] = new SqlParameter("@User", iUser);
param[3] = new SqlParameter("@Reason", strReason);
dal.ExecuteNonQuery("[usp_UpdateAmount]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update No. of Days for the Camper Application
public void UpdateDays(string strFJCID, int iDays, int iUser, string strReason)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", strFJCID);
param[1] = new SqlParameter("@Days", iDays);
param[2] = new SqlParameter("@User", iUser);
param[3] = new SqlParameter("@Reason", strReason);
dal.ExecuteNonQuery("[usp_UpdateDays]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//Sets the SecondApproval flag to true
public void SetSecondApproval(string strFJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", strFJCID);
dal.ExecuteNonQuery("[usp_AdminUpdateStatus]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//Sets the SecondApproval flag to true
public void ReverceSecondApprovalFlag(string strFJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", strFJCID);
dal.ExecuteNonQuery("[usp_ReverceSecondApprovalFlag]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update WorkQueue flag for Camper Application
public void UpdateWorkQueueFlag(string strFJCID, bool blnWrkQueueFlag)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCID", strFJCID);
param[1] = new SqlParameter("@WorkQueue", (blnWrkQueueFlag == true ? "Y" : "N"));
dal.ExecuteNonQuery("[usp_UpdateWorkQueue]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to update the Grade of the Camper Application.
public int updateGrade(String FJCID, int Grade, String Reason, int ModifiedBy)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Grade", Grade);
param[2] = new SqlParameter("@Reason", Reason);
param[3] = new SqlParameter("@User", ModifiedBy);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateGrade]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to check whether any basic camper infomation is changed
public int IsCamperBasicInfoUpdated(UserDetails UserInfo, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[19];
param[0] = new SqlParameter("@First_Name", UserInfo.FirstName);
param[1] = new SqlParameter("@Last_Name", UserInfo.LastName);
param[2] = new SqlParameter("@Street_Address", UserInfo.Address);
param[3] = new SqlParameter("@City", UserInfo.City);
param[4] = new SqlParameter("@State", UserInfo.State);
param[5] = new SqlParameter("@Country", UserInfo.Country);
param[6] = new SqlParameter("@Zip_Code", UserInfo.ZipCode);
param[7] = new SqlParameter("@Home_Phone", UserInfo.HomePhone);
param[8] = new SqlParameter("@Personal_Email", UserInfo.PersonalEmail);
param[9] = new SqlParameter("@Date_Of_Birth", UserInfo.DateofBirth);
param[10] = new SqlParameter("@Age", UserInfo.Age);
param[11] = new SqlParameter("@FJCID", UserInfo.FJCID);
param[12] = new SqlParameter("@IsChanged", SqlDbType.NVarChar, 1);
param[12].Direction = ParameterDirection.Output;
param[13] = new SqlParameter("@Gender", UserInfo.Gender);
param[14] = new SqlParameter("@IsJewish", UserInfo.IsJewish);
param[15] = new SqlParameter("@CMART_MiiP_ReferalCode", UserInfo.CMART_MiiP_ReferalCode);
param[16] = new SqlParameter("@PJLCode", UserInfo.PJLCode);
param[17] = new SqlParameter("@NLCode", UserInfo.NLCode);
param[18] = new SqlParameter("@SpecialCode", UserInfo.SpecialCode);
rowsaffected = dal.ExecuteNonQuery("[usp_IsCamperApplicationUpdated]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to check whether anything related to camper parents infomation is changed
public int IsParentInfoUpdated(UserDetails UserInfo, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[14];
param[0] = new SqlParameter("@First_Name", UserInfo.FirstName);
param[1] = new SqlParameter("@Last_Name", UserInfo.LastName);
param[2] = new SqlParameter("@Street_Address", UserInfo.Address);
param[3] = new SqlParameter("@City", UserInfo.City);
param[4] = new SqlParameter("@State", UserInfo.State);
param[5] = new SqlParameter("@Country", UserInfo.Country);
param[6] = new SqlParameter("@Zip_Code", UserInfo.ZipCode);
param[7] = new SqlParameter("@Home_Phone", UserInfo.HomePhone);
param[8] = new SqlParameter("@Personal_Email", UserInfo.PersonalEmail);
param[9] = new SqlParameter("@Work_Phone", UserInfo.WorkPhone);
param[10] = new SqlParameter("@Work_Email", UserInfo.WorkEmail);
param[11] = new SqlParameter("@FJCID", UserInfo.FJCID);
param[12] = new SqlParameter("@Flag", UserInfo.IsParentInfo1);
param[13] = new SqlParameter("@IsChanged", SqlDbType.NVarChar, 1);
param[13].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_IsParentInfoUpdated]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to check whether camper's applications could be cloned
public bool CouldApplcationsBeCloned(string CamperId)
{
return false;
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
string OutValue;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@CamperId", CamperId);
param[1] = new SqlParameter("@CouldBeCloned", SqlDbType.NVarChar, 1);
param[1].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_CouldBeCloned]", out OutValue, param);
return OutValue == "1";
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to check whether anything changes to camper answers
public int IsCamperAnswersUpdated(string FJCID, string Answers, string ModifiedBy,string PageId, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[5];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Answers", Answers);
param[2] = new SqlParameter("@userID", ModifiedBy);
param[3] = new SqlParameter("@PageID", PageId);
param[4] = new SqlParameter("@IsChanged", SqlDbType.NVarChar, 1);
param[4].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_IsCamperAnswersUpdated]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void CamperAnswersServerValidation(string CamperAnswers, string Comments, string FJCID, string ModifiedBy,string PageId, string CamperUserId, out Boolean bArgsValid, out Boolean bPerformUpdate)
{
string strRetVal;
Boolean bArgs = false, bPerform = false;
IsCamperAnswersUpdated(FJCID, CamperAnswers, ModifiedBy,PageId, out strRetVal);
if (ModifiedBy != CamperUserId) //then the user is admin user
{
switch (strRetVal)
{
case "0": //data has been modified
if (Comments == "")
{
bArgs = false;
bPerform = false;
}
else
{
bArgs = true;
bPerform = true;
}
break;
case "1": //data is not modified
bArgs = true;
bPerform = false;
break;
}
}
else //the user is camper
{
switch (strRetVal)
{
case "0": //data has been modified
bPerform = true;
break;
case "1": //data is not modified
bPerform = false;
break;
}
bArgs = true;
}
bArgsValid = bArgs;
bPerformUpdate = bPerform;
}
//Sets the ConfirmAcceptance flag
public void ConfirmAcceptance(string strFJCID, bool blnAcceptedFlag)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCID", strFJCID);
param[1] = new SqlParameter("@AcceptedFlag", (blnAcceptedFlag == true ? "Y" : "N"));
dal.ExecuteNonQuery("[usp_ConfirmAcceptance]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//Sets the ConfirmAcceptance flag
public void SetTermsandConditionsAcceptance(string strFJCID, Boolean AcceptOption1, Boolean AcceptOption2, Boolean AcceptOption3 )
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", strFJCID);
param[1] = new SqlParameter("@AcceptOption1", AcceptOption1);
param[2] = new SqlParameter("@AcceptOption2", AcceptOption2);
param[3] = new SqlParameter("@AcceptOption3", AcceptOption3);
dal.ExecuteNonQuery("[usp_SetTermsandConditionsAcceptance]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//Sets the ConfirmAcceptance flag
public void SetAcknowledgeFlag(string strFJCID, Boolean AcknowledgeFlag)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCID", strFJCID);
param[1] = new SqlParameter("@Flag", AcknowledgeFlag);
dal.ExecuteNonQuery("[usp_SetAcknowledgementFlag]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get all the School Details
public DataSet GetSchool(int SchoolID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@SchoolID", SchoolID);
DataSet dsSchool;
dsSchool = dal.getDataset("[usp_GetSchool]", param);
return dsSchool;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get the Application submitted info for a particular FJCID (SubmittedDate and ModifiedByUser)
//and making the questionnaire readonly
public DataSet GetApplicationSubmittedInfo(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
SqlParameter[] param = new SqlParameter[1];
DataSet ds;
try
{
param[0] = new SqlParameter("@FJCID", FJCID);
ds = dal.getDataset("[usp_GetApplicationSubmittedInfo]", param);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
param = null;
}
}
//to copy the camper application - to start new application (National landing) when camper ineligible.
public int CopyCamperApplication(string FJCID, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@oldFJCID", FJCID);
param[1] = new SqlParameter("@OFJCID", SqlDbType.NVarChar, 50);
param[1].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_CopyCamperApplication]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to copy the camper application - to start new application (National landing) when camper ineligible.
public int CloneCamperApplication(string FJCID, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("@oldFJCID", FJCID);
param[1] = new SqlParameter("@OFJCID", SqlDbType.NVarChar, 50);
param[1].Direction = ParameterDirection.Output;
param[2] = new SqlParameter("@checkToDel", "1");
rowsaffected = dal.ExecuteNonQuery("[usp_CloneCamperApplication]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public bool CamperStatusDetectived(string FJCID, int StatusValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
string OutValue;
try
{
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@StatusID", StatusValue);
param[2] = new SqlParameter("@Detected", SqlDbType.NVarChar, 1);
param[2].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_CamperStatusDetective]", out OutValue, param);
if (OutValue.Equals("1"))
return true;
else
return false;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//Added By Ram (10/13/2009)
/// <summary>
/// Verifies if the options (marketing section) has been changed
/// </summary>
/// <param name="presentSetOfSelectedAnswers"></param>
/// <param name="previousSetOfSelectedOptions"></param>
/// <returns>returns true if changed else false</returns>
public bool VerifyCamperAnswersSelectionHasChanged(string presentSetOfSelectedAnswers, string previousSetOfSelectedOptions)
{
if(!presentSetOfSelectedAnswers.Equals(previousSetOfSelectedOptions))
return true;
return false;
}
public static string KEY = "N!u8#m2a";
// Encrypt a Querystring
public string EncryptQueryString(string stringToEncrypt)
{
byte[] key = { };
byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 };
try
{
key = Encoding.UTF8.GetBytes(KEY);
using (DESCryptoServiceProvider oDESCrypto = new DESCryptoServiceProvider())
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
MemoryStream oMemoryStream = new MemoryStream();
CryptoStream oCryptoStream = new CryptoStream(oMemoryStream,
oDESCrypto.CreateEncryptor(key, IV), CryptoStreamMode.Write);
oCryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
oCryptoStream.FlushFinalBlock();
return Convert.ToBase64String(oMemoryStream.ToArray());
}
}
catch (Exception ex)
{
throw ex;
}
}
// Decrypt a Querystring
public string DecryptQueryString(string stringToDecrypt)
{
byte[] key = { };
byte[] IV = { 0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78 };
stringToDecrypt = stringToDecrypt.Replace(" ", "+");
byte[] inputByteArray = new byte[stringToDecrypt.Length];
try
{
key = Encoding.UTF8.GetBytes(KEY);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(stringToDecrypt);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
public DataSet GetCamperInfo(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
return dal.getDataset("usp_GetCamperInfo", param);
}
catch (Exception ex)
{
throw ex;
}
}
public decimal GetGrantFromDaysCamp(string FJCID, string days, string campID, string timeInCamp)
{
decimal grantAmount = 0;
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Days", days);
param[2] = new SqlParameter("@CampID", campID);
param[3] = new SqlParameter("@TimeInCamp", timeInCamp);
DataSet dsCamperGrant;
dsCamperGrant = dal.getDataset("usp_GetGrantFromDaysCamp", param);
if (dsCamperGrant.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(dsCamperGrant.Tables[0].Rows[0]["GrantAmount"]))
grantAmount = Convert.ToDecimal(dsCamperGrant.Tables[0].Rows[0]["GrantAmount"]);
}
return grantAmount;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void UpdateChangeDetails(structChangeDetails ChangeInfo)
{
CIPDataAccess dal = new CIPDataAccess();
SqlParameter[] param = new SqlParameter[21];
int rowsaffected;
param[0] = new SqlParameter("@FJCID", ChangeInfo.FJCID);
param[1] = new SqlParameter("@RequestType", ChangeInfo.RequestType);
param[2] = new SqlParameter("@Cancellation_Reason", ChangeInfo.Cancellation_Reason);
param[3] = new SqlParameter("@OldSession", ChangeInfo.OldSession);
param[4] = new SqlParameter("@OldSession_StartDate", ChangeInfo.OldSession_StartDate);
param[5] = new SqlParameter("@OldSession_EndDate", ChangeInfo.OldSession_EndDate);
param[6] = new SqlParameter("@NewSession", ChangeInfo.NewSession);
param[7] = new SqlParameter("@NewSession_StartDate", ChangeInfo.NewSession_StartDate);
param[8] = new SqlParameter("@NewSession_EndDate", ChangeInfo.NewSession_EndDate);
param[9] = new SqlParameter("@Original_Status", ChangeInfo.Original_Status);
param[10] = new SqlParameter("@Current_Status", ChangeInfo.Current_Status);
param[11] = new SqlParameter("@OldGrantAmount", ChangeInfo.OldGrantAmount);
param[12] = new SqlParameter("@NewGrantAmount", ChangeInfo.NewGrantAmount);
param[13] = new SqlParameter("@NewFJCID", ChangeInfo.NewFJCID == 0 ? DBNull.Value.ToString() : ChangeInfo.NewFJCID.ToString());
param[14] = new SqlParameter("@CampYearID", ChangeInfo.CampYearID);
param[15] = new SqlParameter("@CreatedDate", ChangeInfo.CreatedDate);
param[16] = new SqlParameter("@SubmittedDate", ChangeInfo.SubmittedDate);
param[17] = new SqlParameter("@ModifiedDate", ChangeInfo.ModifiedDate);
param[18] = new SqlParameter("@ModifiedBy", ChangeInfo.ModifiedBy);
param[19] = new SqlParameter("@RequestStatus", ChangeInfo.RequestStatus);
param[20] = new SqlParameter("@RequestID", ChangeInfo.RequestID);
rowsaffected = dal.ExecuteNonQuery("[usp_UpdateChangeRequestDetails]", param);
//rowsaffected = 0;
}
public DataSet GetChangeRequestDetails(string strFJCID)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet dsChangeDetails = new DataSet();
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", strFJCID);
dsChangeDetails = dal.getDataset("[usp_getChangeRequestDetails]", param);
return dsChangeDetails;
}
public void InsertChangeDetails(structChangeDetails ChangeInfo, out int requestID)
{
CIPDataAccess dal = new CIPDataAccess();
SqlParameter[] param = new SqlParameter[21];
requestID = 0;
int rowsaffected;
param[0] = new SqlParameter("@FJCID", ChangeInfo.FJCID);
param[1] = new SqlParameter("@RequestType", ChangeInfo.RequestType);
param[2] = new SqlParameter("@Cancellation_Reason", ChangeInfo.Cancellation_Reason);
param[3] = new SqlParameter("@OldSession", ChangeInfo.OldSession);
param[4] = new SqlParameter("@OldSession_StartDate", ChangeInfo.OldSession_StartDate);
param[5] = new SqlParameter("@OldSession_EndDate", ChangeInfo.OldSession_EndDate);
param[6] = new SqlParameter("@NewSession", ChangeInfo.NewSession);
param[7] = new SqlParameter("@NewSession_StartDate", ChangeInfo.NewSession_StartDate);
param[8] = new SqlParameter("@NewSession_EndDate", ChangeInfo.NewSession_EndDate);
param[9] = new SqlParameter("@Original_Status", ChangeInfo.Original_Status);
param[10] = new SqlParameter("@Current_Status", ChangeInfo.Current_Status);
param[11] = new SqlParameter("@OldGrantAmount", ChangeInfo.OldGrantAmount);
param[12] = new SqlParameter("@NewGrantAmount", ChangeInfo.NewGrantAmount);
param[13] = new SqlParameter("@NewFJCID", ChangeInfo.NewFJCID == 0 ? DBNull.Value.ToString() : ChangeInfo.NewFJCID.ToString());
param[14] = new SqlParameter("@CampYearID", ChangeInfo.CampYearID);
param[15] = new SqlParameter("@CreatedDate", ChangeInfo.CreatedDate);
param[16] = new SqlParameter("@SubmittedDate", ChangeInfo.SubmittedDate);
param[17] = new SqlParameter("@ModifiedDate", ChangeInfo.ModifiedDate);
param[18] = new SqlParameter("@ModifiedBy", ChangeInfo.ModifiedBy);
param[19] = new SqlParameter("@RequestStatus", ChangeInfo.RequestStatus);
param[20] = new SqlParameter("@RequestID", requestID);
param[20].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_InsertChangeRequestDetails]", param);
//rowsaffected = 0;
}
public structChangeDetails SetChangeDetailsFromDataRow(DataRow drChangeDetails)
{
structChangeDetails structChangeDetails = new structChangeDetails();
structChangeDetails.RequestID = drChangeDetails["RequestID"]!= null?Int32.Parse(drChangeDetails["RequestID"].ToString()):0;
structChangeDetails.FJCID = long.Parse(drChangeDetails["FJCID"].ToString());
structChangeDetails.RequestType = Int32.Parse(drChangeDetails["RequestType"].ToString());
structChangeDetails.Cancellation_Reason = drChangeDetails["Cancellation_Reason"].ToString();
structChangeDetails.OldSession = drChangeDetails["OldSession"].ToString();
structChangeDetails.OldSession_StartDate = drChangeDetails["OldSession_StartDate"].ToString();
structChangeDetails.OldSession_EndDate = drChangeDetails["OldSession_EndDate"].ToString();
structChangeDetails.NewSession = drChangeDetails["NewSession"].ToString();
structChangeDetails.NewSession_StartDate = drChangeDetails["NewSession_StartDate"].ToString();
structChangeDetails.NewSession_EndDate = drChangeDetails["NewSession_EndDate"].ToString();
structChangeDetails.Original_Status = Int32.Parse(drChangeDetails["Original_Status"].ToString());
structChangeDetails.Current_Status = Int32.Parse(drChangeDetails["Current_Status"].ToString());
structChangeDetails.OldGrantAmount = double.TryParse(drChangeDetails["OldGrantAmount"].ToString(), out structChangeDetails.OldGrantAmount) ? double.Parse(drChangeDetails["OldGrantAmount"].ToString()) : 0.0;
structChangeDetails.NewGrantAmount = double.TryParse(drChangeDetails["NewGrantAmount"].ToString(), out structChangeDetails.NewGrantAmount) ? double.Parse(drChangeDetails["NewGrantAmount"].ToString()) : 0.0;
structChangeDetails.NewFJCID = long.TryParse(drChangeDetails["NewFJCID"].ToString(), out structChangeDetails.NewFJCID) ? long.Parse(drChangeDetails["NewFJCID"].ToString()) : 0;
structChangeDetails.CampYearID = Int32.Parse(drChangeDetails["CampYearID"].ToString());
structChangeDetails.CreatedDate = drChangeDetails["CreatedDate"].ToString();
structChangeDetails.SubmittedDate = drChangeDetails["SubmittedDate"].ToString();
structChangeDetails.ModifiedDate = drChangeDetails["ModifiedDate"].ToString();
structChangeDetails.ModifiedBy = long.TryParse(drChangeDetails["ModifiedBy"].ToString(), out structChangeDetails.ModifiedBy) ? long.Parse(drChangeDetails["ModifiedBy"].ToString()) : 0;
structChangeDetails.RequestStatus = Int32.TryParse(drChangeDetails["RequestStatus"].ToString(), out structChangeDetails.RequestStatus) ? Int32.Parse(drChangeDetails["RequestStatus"].ToString()) : 0;
return structChangeDetails;
}
//to copy the camper application - to start new application (National landing) when camper ineligible.
public int CopyCamperApplicationForSessionChange(string FJCID, out string OutValue, int newAppStatus, int setOriginalAppStatus)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@oldFJCID", FJCID);
param[1] = new SqlParameter("@OFJCID", SqlDbType.NVarChar, 50);
param[2] = new SqlParameter("@NewStatus", SqlDbType.Int,newAppStatus);
param[3] = new SqlParameter("@OldApplicationStatus", SqlDbType.Int,setOriginalAppStatus);
param[1].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_CopyCamperApplicationForSessionChange]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int InsertCamperAnswers_RequestedForChange(string FJCID, string Answers, string ModifiedBy, string Comments, string originalValue, string changedValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@Answers", Answers);
param[2] = new SqlParameter("@userID", ModifiedBy);
param[3] = new SqlParameter("@Comment", Comments);
param[4] = new SqlParameter("@originalValue", originalValue);
param[5] = new SqlParameter("@changedValue", changedValue);
rowsaffected = dal.ExecuteNonQuery("[USP_InsertCamperAnswers]", param);
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public bool UpdateDetailsOnRequestType(string FJCID, string strNewFJCID, int iRequestID, string strAnswers, string Comments, int iUserID, string strOriginalValue, string strChangedValue, int iRequestStatus)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[9];
param[0] = new SqlParameter("@FJCID", FJCID);
param[1] = new SqlParameter("@RequestID", iRequestID);
param[2] = new SqlParameter("@Answers", strAnswers);
param[3] = new SqlParameter("@Comments", Comments);
param[4] = new SqlParameter("@userID", iUserID);
param[5] = new SqlParameter("@originalValue", strOriginalValue);
param[6] = new SqlParameter("@changedValue", strChangedValue);
param[7] = new SqlParameter("@RequestStatus", iRequestStatus);
param[8] = new SqlParameter("@NewFJCID", strNewFJCID);
rowsaffected = dal.ExecuteNonQuery("[usp_AlterChangeRequestDetails]", param);
return rowsaffected > 1 ?true:false;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int IsPaymentDone(String FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
int rowsAffected;
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
ds = dal.getDataset("usp_IsPaymentDone", param);
return Convert.ToInt32(ds.Tables[0].Rows[0][0]);
}
public string SetNextUrl(string strFJCID,string strCampYear)
{
UserDetails Info = new UserDetails();
Info = getCamperInfo(strFJCID);
string strFedID = "0";
string strNextURL=string.Empty;
DataSet dsMiiPReferalCodeDetails = new DataSet();
General objGeneral = new General();
if (Info.CMART_MiiP_ReferalCode != string.Empty)
dsMiiPReferalCodeDetails = objGeneral.GetMiiPReferalCode(Info.CMART_MiiP_ReferalCode, strCampYear);
if ((dsMiiPReferalCodeDetails.Tables.Count > 0) && (Info.CMART_MiiP_ReferalCode != string.Empty))
{
if (dsMiiPReferalCodeDetails.Tables[0].Rows.Count > 0)
{
DataRow drMiiP = dsMiiPReferalCodeDetails.Tables[0].Rows[0];
strNextURL = drMiiP["NavigationURL"].ToString();
if (drMiiP["CampID"].ToString() == "1146")
{
if (strNextURL.ToUpper().Contains("URJ/"))
strNextURL = strNextURL.Replace("URJ/", "URJ/Acadamy");
}
strFedID = ConfigurationManager.AppSettings["CMART"].ToString();
}
}
else if (Info.PJLCode != string.Empty)
{
char ch = ',';
//string[] PJLCode = ConfigurationManager.AppSettings["PJLCode"].ToString().Split(ch);
DataTable dtCampYearPJLCodes = objGeneral.GetPJLCodes(strCampYear).Tables[0];
string[] PJLCode = new string[dtCampYearPJLCodes.Rows.Count];
//dtCampYearPJLCodes.Rows.CopyTo(PJLCode, 0);
for (int i = 0; i < dtCampYearPJLCodes.Rows.Count; i++)
{
PJLCode[i] = dtCampYearPJLCodes.Rows[i][0].ToString();
}
for (int i = 0; i < PJLCode.Length; i++)
{
if (Info.PJLCode.ToUpper() == PJLCode[i].ToUpper())
{
strNextURL = "~/Enrollment/PJL/Summary.aspx";
strFedID = ConfigurationManager.AppSettings["PJL"].ToString();
break;
}
}
}
if(strNextURL=="")
{
strNextURL = "~/Enrollment/Step1_NL.aspx";
}
return strNextURL;
}
public int UpdatePJLCamperStatus(string FJCIDs, int status)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
int rowsAffected = 0;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCIDs", FJCIDs);
param[1] = new SqlParameter("@Status", status);
ds = dal.getDataset("UpdatePJLCamperStatus", param);
if (ds.Tables.Count > 0)
if (ds.Tables[0].Rows.Count > 0)
return Int32.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());
return 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
ds = null;
}
}
public int IsNationalLandingCamp(string FederationId)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
int rowsAffected = 0;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FederationId", FederationId);
return Convert.ToInt32(dal.getDataset("usp_IsNationalLandingCamp", param).Tables[0].Rows[0][0]);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
ds = null;
}
}
public int UpdateANStatus(String FJCIDs, int Status)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
int rowsAffected = 0;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@FJCIDs", FJCIDs);
param[1] = new SqlParameter("@Status", Status);
return dal.ExecuteNonQuery("usp_UpdateANStatus", param);
//if (ds.Tables.Count > 0)
// if (ds.Tables[0].Rows.Count > 0)
// return Int32.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());
//return 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
ds = null;
}
}
public int ResetANStatus(String FJCIDs)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
int rowsAffected = 0;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCIDs", FJCIDs);
return dal.ExecuteNonQuery("ResetANStatus", param);
//if (ds.Tables.Count > 0)
// if (ds.Tables[0].Rows.Count > 0)
// return Int32.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());
//return 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
ds = null;
}
}
public DataSet getSurveyCode(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
SqlParameter [] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
ds = dal.getDataset("usp_getSurveyCode", param);
return ds;
}
public DataSet usp_GetANReport(int recCount, string campyear, int ANReportID, string type)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@RecCount", recCount);
param[1] = new SqlParameter("@ANReportID", ANReportID);
param[2] = new SqlParameter("@CampYear", campyear);
param[3] = new SqlParameter("@Type", type);
return dal.getDataset("[usp_GetANReport]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int GetExistingCountOfANPremilinaryRecords(string campyear)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@CampYear", campyear);
ds = dal.getDataset("[usp_GetExistingCountOfANPremilinaryRecords]", param);
return Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public DataSet RunFinalMode(string campyear, string type)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@CampYear", campyear);
param[1] = new SqlParameter("@Type", type);
return dal.getDataset("[usp_RunFinalMode]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public DataSet GetANFinalModeCampersOnReportID(string campyear, string ANReportID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@CampYear", campyear);
param[1] = new SqlParameter("@ANReportID", ANReportID);
return dal.getDataset("[usp_GetANFinalModeCampersOnReportID]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//Added by sandhya
//to get the status based on the FJCID
public DataSet getStatus(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
DataSet ds = new DataSet();
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
ds = dal.getDataset("usp_GetStatus", param);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int GetJWestFirsttimersCountBasedonStatus()
{
CIPDataAccess dal = new CIPDataAccess();
int jwestcount = 0;
try
{
DataSet ds = new DataSet();
//SqlParameter[] param = new SqlParameter[1];
//param[0] = new SqlParameter("@Status", status);
//param[1] = new SqlParameter("@FJCID", fjcid);
ds = dal.getDataset("JWestFirsttimersCountBasedonStatus", null);
if (ds.Tables[0].Rows.Count > 0)
{
if (!Convert.IsDBNull(ds.Tables[0].Rows[0]["jwestcount"]))
jwestcount = Convert.ToInt32(ds.Tables[0].Rows[0]["jwestcount"]);
}
return jwestcount;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public structJWestReportInfo GetJWestReportInfo(int CampYear)
{
CIPDataAccess dal = new CIPDataAccess();
structJWestReportInfo structJWestReportInfo = new structJWestReportInfo();
try
{
DataSet dsJWestReportInfo;
string sp = "";
if (CampYear == 2011)
sp = "[usp_GetReportCounts]";
else if (CampYear == 2012)
sp = "[usp_GetReportCounts2012]";
dsJWestReportInfo = dal.getDataset(sp, null);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2010Campers"]))
structJWestReportInfo.NoOf2010Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2010Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201012Campers"]))
structJWestReportInfo.NoOf201012Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201012Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["Noof201018Campers"]))
structJWestReportInfo.Noof201018Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["Noof201018Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2011Campers"]))
structJWestReportInfo.NoOf2011Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2011Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2010notreturnedCampers"]))
structJWestReportInfo.NoOf2010notreturnedCampers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2010notreturnedCampers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201012returned201112Campers"]))
structJWestReportInfo.NoOf201012returned201112Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201012returned201112Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201012returned201118Campers"]))
structJWestReportInfo.NoOf201012returned201118Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201012returned201118Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201018returned201112Campers"]))
structJWestReportInfo.NoOf201018returned201112Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201018returned201112Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201018returned201118Campers"]))
structJWestReportInfo.NoOf201018returned201118Campers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf201018returned201118Campers"]);
if (!Convert.IsDBNull(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2010returnedCampers"]))
structJWestReportInfo.NoOf2010returnedCampers = Convert.ToInt32(dsJWestReportInfo.Tables[0].Rows[0]["NoOf2010returnedCampers"]);
return structJWestReportInfo;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public DataSet CheckSecondQuestion(int FederationId)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
DataSet ds = new DataSet();
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FederationID", FederationId);
ds = dal.getDataset("CheckQuestion2", param);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//added by sandhya
//to insert the camper holding details
public void InsertCamperHoldingDetails(string Firstname, string Lastname, string Email, string Zipcode, string FedName, string CampName, bool isPJL, int SchoolTypeID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[8];
param[0] = new SqlParameter("@FirstName", Firstname);
param[1] = new SqlParameter("@LastName", Lastname);
param[2] = new SqlParameter("@EmailAddress", Email);
param[3] = new SqlParameter("@ZipCode", Zipcode);
param[4] = new SqlParameter("@FedName", FedName);
param[5] = new SqlParameter("@CampName", CampName);
param[6] = new SqlParameter("@isPJL", isPJL);
param[7] = new SqlParameter("@SchoolTypeID", SchoolTypeID);
dal.ExecuteNonQuery("[usp_InsertCamperHoldingDetails]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
internal DataSet GetCamperTimeInCampWithOutCamp(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
return dal.getDataset("[usp_GetCamperTimeInCampWithOutCamp]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to copy the camper application but not the camperanswers- to start new application (Sandiego) when camper ineligible .
public int CopyCamperApplicationWithoutCamperAnswers(string FJCID, out string OutValue)
{
CIPDataAccess dal = new CIPDataAccess();
int rowsaffected;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@oldFJCID", FJCID);
param[1] = new SqlParameter("@OFJCID", SqlDbType.NVarChar, 50);
param[1].Direction = ParameterDirection.Output;
rowsaffected = dal.ExecuteNonQuery("[usp_CopyCamperApplicationWithoutCamperAnswers]", out OutValue, param);
//rowsaffected = 0;
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//to get all the cities based on the state selected
public DataSet GetCamperApplicationsFromCamperID(string camperID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@CamperID", camperID);
DataSet dsCamperApplications;
dsCamperApplications = dal.getDataset("[usp_GetCamperApplicationsFromCamperID]", param);
return dsCamperApplications;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void DeleteCamperAnswerUsingFJCID(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
dal.ExecuteNonQuery("[usp_DeleteCamperAnswerUsingFJCID]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public int validateIsUsedPJLDSCode(string FJCID)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
DataRow dr;
int rowsaffected = -1;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@FJCID", FJCID);
ds = dal.getDataset("[usp_ValidateIsUsedPJLDSCode]", param);
if (ds.Tables[0].Rows.Count > 0)
{
string valid = ds.Tables[0].Rows[0][0].ToString();
rowsaffected = Convert.ToInt32(valid);
}
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//added by sreevani for pjl day school codes validation and updation
public int validatePJLDSCode(string PJLDSCode)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
DataRow dr;
int rowsaffected = -1;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@PJLDSCode", PJLDSCode);
ds = dal.getDataset("[usp_ValidatePJLDSCode]", param);
if (ds.Tables[0].Rows.Count > 0)
{
//dr = ds.Tables[0].Rows[0];
string valid = ds.Tables[0].Rows[0][0].ToString();
rowsaffected = Convert.ToInt32(valid);
}
return rowsaffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public void updatePJLDSCode(string PJLDSCode, string fjcid)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
DataRow dr;
int rowsaffected = -1;
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@PJLDSCode", PJLDSCode);
param[1] = new SqlParameter("@fjcid", fjcid);
dal.ExecuteNonQuery("[usp_UpdatePJLDSCode]", param);
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
public string validateFJCID(string fjcid)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
DataRow dr;
string dallasCode = null;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@fjcid", fjcid);
ds = dal.getDataset("[usp_getDallasCode]", param);
if (ds.Tables[0].Rows.Count > 0)
{
//dr = ds.Tables[0].Rows[0];
dallasCode = ds.Tables[0].Rows[0][0].ToString();
}
return dallasCode;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
//end of addition for dallas code validation
//added by sreevani to get campyearid based on fjcid
public string getCampYearId(string fjcid)
{
CIPDataAccess dal = new CIPDataAccess();
DataSet ds = new DataSet();
DataRow dr;
string campYearId = null;
try
{
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@Fjcid", fjcid);
ds = dal.getDataset("[usp_GetCampYearId]", param);
if (ds.Tables[0].Rows.Count > 0)
{
//dr = ds.Tables[0].Rows[0];
campYearId = ds.Tables[0].Rows[0][0].ToString();
}
return campYearId;
}
catch (Exception ex)
{
throw ex;
}
finally
{
dal = null;
}
}
}
public struct structChangeDetails
{
public int RequestID;
public long FJCID;
public int RequestType;
public string Cancellation_Reason;
public string OldSession;
public string OldSession_StartDate;
public string OldSession_EndDate;
public string NewSession;
public string NewSession_StartDate;
public string NewSession_EndDate;
public int Original_Status;
public int Current_Status;
public double OldGrantAmount;
public double NewGrantAmount;
public long NewFJCID;
public int CampYearID;
public string CreatedDate;
public string SubmittedDate;
public string ModifiedDate;
public long ModifiedBy;
public int RequestStatus;
public bool Equals(structChangeDetails obj)
{
//if (this.FJCID == obj.FJCID && this.RequestType == obj.RequestType && this.Cancellation_Reason == obj.Cancellation_Reason && this.NewSession == obj.NewSession && this.NewSession_StartDate == obj.NewSession_StartDate && this.NewSession_EndDate == obj.NewSession_EndDate && this.Original_Status == obj.Original_Status && this.NewGrantAmount == obj.NewGrantAmount && this.CampYearID == obj.CampYearID && this.IsSubmitted == obj.IsSubmitted)
if (this.FJCID == obj.FJCID && this.RequestType == obj.RequestType && this.Cancellation_Reason == obj.Cancellation_Reason && this.NewSession == obj.NewSession && this.NewSession_StartDate == obj.NewSession_StartDate && this.NewSession_EndDate == obj.NewSession_EndDate && this.NewGrantAmount == obj.NewGrantAmount && this.CampYearID == obj.CampYearID)
return true;
else
return false;
}
}
//struct which is being used for Camper Info, Parent Info
public struct structThresholdInfo
{
public int NbrOfPmtRequested1;
public int NbrOfPmtRequested2;
public string ThresholdType;
public string ThresholdTypeDescription;
public int Threshold1;
public int Threshold2;
}
public struct structJWestReportInfo
{
public int NoOf2010Campers;
public int NoOf201012Campers;
public int Noof201018Campers;
public int NoOf2011Campers;
public int NoOf2010notreturnedCampers;
public int NoOf201012returned201112Campers;
public int NoOf201012returned201118Campers;
public int NoOf201018returned201112Campers;
public int NoOf201018returned201118Campers;
public int NoOf2010returnedCampers;
}
public enum RequestStatus
{
Saved = 0,
Submitted = 1,
Rejected = 2,
ClosedOrApproved = 3
}
}
|
using Common.Data;
using Common.Exceptions;
using Common.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
namespace Entity
{
[DataContract]
public class LTO : IMappable
{
#region Constructors
public LTO()
{ }
#endregion
#region Public Properties
/// <summary>
/// Gets the name of the table to which this object maps.
/// </summary>
public string TableName
{
get { return "LTO"; }
}
[DataMember]
public Int32? Index_CTR { get; set; }
[DataMember]
public Int32? ID { get; set; }
[DataMember]
public string Filename { get; set; }
[DataMember]
public string Path_LTO { get; set; }
[DataMember]
public string Path_Windows { get; set; }
[DataMember]
public Int32? On_Disk { get; set; }
[DataMember]
public Int32? On_Tape { get; set; }
[DataMember]
public Int32? A_M { get; set; }
[DataMember]
public Int32? Can_Delete { get; set; }
[DataMember]
public DateTime? File_Date { get; set; }
[DataMember]
public Int32? File_Size { get; set; }
[DataMember]
public Int32? Media_ID { get; set; }
#endregion
#region Public Methods
public bool CheckMOVExists(string connectionString, int id)
{
bool result = false;
string sql = "select count(*) from lto where filename = '" + id.ToString().PadLeft(8, '0') + ".mov' " +
"and on_tape = 1";
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0;
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public LTO GetLTOInfo(string connectionString, int id, string track)
{
string sql = "";
if (track.Equals("B"))
sql = "select * from lto where filename = '" + id.ToString().PadLeft(8, '0') + ".mov'";
else
sql = "select * from lto where id = " + id.ToString();
return GetRecord(connectionString, sql);
}
public List<LTO> GetList(string connectionString, string sql, SqlParameter[] parameters = null)
{
List<LTO> result = new List<LTO>();
using (Database database = new Database(connectionString))
{
try
{
CommandType commandType = CommandType.Text;
if (parameters != null)
commandType = CommandType.StoredProcedure;
using (DataTable table = database.ExecuteSelect(sql, commandType, parameters))
{
if (table.HasRows())
{
Mapper<LTO> m = new Mapper<LTO>();
result = m.MapListSelect(table);
}
}
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public LTO GetRecord(string connectionString, string sql, SqlParameter[] parameters = null)
{
LTO result = null;
using (Database database = new Database(connectionString))
{
try
{
CommandType commandType = CommandType.Text;
if (parameters != null)
commandType = CommandType.StoredProcedure;
using (DataTable table = database.ExecuteSelect(sql, commandType, parameters))
{
if (table.HasRows())
{
Mapper<LTO> m = new Mapper<LTO>();
result = m.MapSingleSelect(table);
}
}
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public List<Tuple<string, string>> GetRelatedFiles(string connectionString, int id, string track)
{
List<Tuple<string, string>> result = new List<Tuple<string, string>>();
string sql = "select path_windows, filename from lto ";
if (track.Equals("FCP") || track.Equals("DMG"))
sql += "where path_windows like '%" + id.ToString().PadLeft(8, '0') + "%'";
if (track.Equals("B"))
sql += "where filename = '" + id.ToString().PadLeft(8, '0') + ".mov'";
sql += "and a_m = 1";
using (Database database = new Database(connectionString))
{
try
{
using (DataTable table = database.ExecuteSelect(sql))
{
if (table.HasRows())
{
foreach (DataRow row in table.Rows)
{
result.Add(new Tuple<string, string>(row["path_windows"].ToString(),
row["filename"].ToString()));
}
}
}
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public LTO GetStatus(string connectionString, string fileName)
{
string sql = "Select * from LTO where filename like '%" + fileName + "%'";
return GetRecord(connectionString, sql);
}
public string GetWindowsPath(string connectionString, int id)
{
string result = "";
string sql = "select path_windows, filename from LTO where filename = '" + id.ToString().PadLeft(8, '0') + ".mov'";
using (Database database = new Database(connectionString))
{
try
{
using (DataTable dt = database.ExecuteSelect(sql))
{
if (dt.HasRows())
{
result = dt.Rows[0]["path_windows"].ToString();
}
}
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public bool IsOnDisk(string connectionString, string fileName)
{
bool result = false;
string sql = "Select count(*) from lto where filename = '" + fileName + "' and on_disk = 1";
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0;
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
public bool IsOnTape(string connectionString, string fileName)
{
bool result = false;
string sql = "Select on_tape from lto where filename = '" + fileName + "'";
using (Database database = new Database(connectionString))
{
try
{
result = database.ExecuteSelectInt(sql).GetValueOrDefault() > 0;
}
catch (Exception e)
{
throw new EntityException(sql, e);
}
}
return result;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
namespace Ejercicio_21
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<string> listaPalindromo = new List<string>();
List<string> listaPalabras = new List<string>();
string ruta = string.Empty;
string linea = string.Empty;
char[] separadores = { '-', '.', ',', ';', ':', ' ' };
int posicionLinea = 0;
string palabraLarga = string.Empty;
string palabraCorta = " ";
long nLineaPalabraLarga = 0;
long nLineaPalabraCorta = 0;
string palabraRepMax = string.Empty;
string palabraRepMin = string.Empty;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
lbxResultado.Items.Clear();
ruta = tbxRuta.Text;
string[] tmpLinea = null;
using(FileStream flujo = new FileStream(ruta,FileMode.Open,FileAccess.Read))
using (StreamReader lector = new StreamReader(flujo, UTF8Encoding.UTF8))
{
while ((linea = lector.ReadLine()) != null)
{
tmpLinea = linea.Split(separadores, StringSplitOptions.RemoveEmptyEntries);
posicionLinea++;
foreach (string palabra in tmpLinea)
{
if (palabra.Length > palabraLarga.Length)
{
palabraLarga = palabra;
nLineaPalabraLarga = posicionLinea;
}
if (palabra.Length < palabraCorta.Length)
{
palabraCorta = palabra;
nLineaPalabraCorta = posicionLinea;
}
if (esPalindromo(palabra))
listaPalindromo.Add(palabra);
listaPalabras.Add(palabra);
if (listaPalabras.Count(n => n == palabra) > listaPalabras.Count(n => n == palabraRepMax))
palabraRepMax = palabra;
if (listaPalabras.Count(n => n == palabra) < listaPalabras.Count(n => n == palabraRepMin))
palabraRepMin = palabra;
}
}
}
lbxResultado.Items.Add(string.Format("La palabra más larga: {0}, su longitud: {1}\n y en que linea aparece: {2}", palabraLarga, palabraLarga.Length, nLineaPalabraLarga));
lbxResultado.Items.Add(string.Format("La palabra más corta: {0}, su longitud: {1}\n y en que linea aparece: {2}", palabraCorta, palabraCorta.Length, nLineaPalabraCorta));
lbxResultado.Items.Add(string.Format("La palabra que más se repite: {0}",palabraRepMax));
lbxResultado.Items.Add(string.Format("La palabra que menos se repite: {0}",palabraRepMin));
lbxResultado.Items.Add(string.Format("Palabras palindromos: \n"));
for (int i = 0; i < listaPalindromo.Count; i++)
{
lbxResultado.Items.Add(listaPalindromo[i]);
}
}
public bool esPalindromo(string palabra)
{
string tmpPalabra = string.Empty;
for (int i = palabra.Length-1; i > 0; i--)
{
tmpPalabra += palabra[i];
}
return tmpPalabra.Equals(palabra);
}
private void TbxRuta_GotFocus(object sender, RoutedEventArgs e)
{
OpenFileDialog ventana = new OpenFileDialog();
ventana.ShowDialog();
tbxRuta.Text = ventana.FileName;
}
}
}
|
using System;
using WebApp9CronScheduledBackgroudService.Server.BGService.CronExtension;
namespace WebApp9CronScheduledBackgroudService.Server.BGService.Repository
{
public class Promotions
{
public int Id { get; internal set; }
public string ClientId { get; set; }
//public virtual Client Client { get; set; }
public string TemplateId { get; set; }
//public virtual Template Template { get; set; }
public string TagId { get; set; }
//public virtual Tag Tag { get; set; }
public string Name { get; internal set; }
public string Cron { get; set; }
public RecurringJob ReccuringJob { get; set; }
public bool CompletedToday { get; set; } = false;
public bool Enabled { get; set; } = true;
public DateTime StartDate { get; internal set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using EQS.AccessControl.Application.ViewModels.Input;
using EQS.AccessControl.Application.ViewModels.Output;
using EQS.AccessControl.Application.ViewModels.Output.Base;
using EQS.AccessControl.Application.ViewModels.Output.Register;
using EQS.AccessControl.Domain.Entities;
namespace EQS.AccessControl.Application.Interfaces
{
public interface IRegisterAppService
{
ResponseModelBase<RegisterPersonOutput> Create(PersonInput entity);
ResponseModelBase<RegisterPersonOutput> Update(PersonInput entity);
ResponseModelBase<RegisterPersonOutput> GetById(int id);
ResponseModelBase<List<RegisterPersonOutput>> GetAll();
ResponseModelBase<List<RegisterPersonOutput>> GetByExpression(SearchObjectInput predicate);
ResponseModelBase<RegisterPersonOutput> Delete(int id);
}
}
|
using Xunit;
using Xunit.Abstractions;
public partial class WithScalpelConstantTests :
XunitLoggingBase
{
[Fact]
public void ApprovalTestsIsRemoved()
{
Assert.DoesNotContain(result.Assembly.GetReferencedAssemblies(), x => x.Name == "ApprovalTests");
}
[Fact]
public void ApprovalUtilitiesIsRemoved()
{
Assert.DoesNotContain(result.Assembly.GetReferencedAssemblies(), x => x.Name == "ApprovalUtilities");
}
[Fact]
public void WithApprovalTestsUseReporterRemoved()
{
Assert.DoesNotContain(result.Assembly.GetTypes(), x => x.Name == "WithApprovalTestsUseReporterAttribute");
}
public WithScalpelConstantTests(ITestOutputHelper output) :
base(output)
{
}
}
|
namespace FormulaBuilder
{
using System;
public class Field : IField
{
private Guid id;
public Field (Guid id)
{
this.id = id;
}
public Guid GetId ()
{
return this.id;
}
public override string ToString ()
{
return this.id.ToString ();
}
}
}
|
using Chess.v4.Models;
using Chess.v4.Models.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Chess.v4.Engine.Extensions
{
public static class SquareExtensions
{
public static List<T> Clone<T>(this IList<T> listToClone) where T : ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
/// <summary>
/// Might not return the piece you want if there are more than one of that type and color.
/// </summary>
/// <param name="squares"></param>
/// <param name="pieceType"></param>
/// <param name="pieceColor"></param>
/// <returns></returns>
public static Square FindPiece(this List<Square> squares, PieceType pieceType, Color pieceColor)
{
return squares.Where(a => a.Occupied && a.Piece.PieceType == pieceType && a.Piece.Color == pieceColor).FirstOrDefault();
}
public static IEnumerable<Square> FindPieces(this List<Square> squares, PieceType pieceType, Color pieceColor)
{
return squares.Where(a => a.Occupied && a.Piece.PieceType == pieceType && a.Piece.Color == pieceColor);
}
public static Piece GetPiece(this List<Square> squares, int piecePosition)
{
return squares.Where(a => a.Index == piecePosition).First().Piece;
}
public static Square GetSquare(this List<Square> squares, int piecePosition)
{
return squares.Where(a => a.Index == piecePosition).First();
}
public static bool Intersects(this List<Square> squares, int[] positions)
{
return positions.Intersect<int>(squares.Select(a => a.Index)).Any();
}
//public static bool Intersects(this List<Square> squares, int position) {
// return squares.Where(a => a.Index == position).Any();
//}
public static IEnumerable<Square> Occupied(this List<Square> squares)
{
return squares.Where(a => a.Piece != null);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Tools
{
public static class Methods
{
public static void ShuffleArray<T>(this T[] arr)
{
var rnd = new Random();
int n = arr.Length;
int index;
while (n > 1)
{
index = rnd.Next(n--);
Swap(ref arr[n], ref arr[index]);
}
}
public static void SwapRight<T>(this T[] array, int index)
{
Swap(ref array[index], ref array[index + 1]);
}
public static void SwapLeft<T>(this T[] array, int index)
{
Swap(ref array[index], ref array[index - 1]);
}
public static void Swap<T>(this T[] array, int first, int second)
{
Swap(ref array[first], ref array[second]);
}
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
public static IEnumerable<int[]> GetPermutations(this int[] array)
{
return Permutations.ProducePermutations(array);
}
public static int SumOfDigits(this int n)
{
return NumUtils.SumOfDigits(n);
}
public static int SumOfDigits(this long n)
{
return NumUtils.SumOfDigits(n);
}
public static int Factorial(int n)
{
int res = 1;
while (n > 0)
{
res *= n;
n--;
}
return res;
}
}
}
|
using Ibit.Core.Serial;
using Ibit.Core.Util;
using UnityEngine;
namespace Ibit.CakeGame
{
public class Player : MonoBehaviour
{
public Candles candle;
public Stat flow;
public float picoExpiratorio;
public Stars score;
public ScoreMenu scoreMenu;
public float sensorValue;
public bool stopedFlow;
private void OnMessageReceived(string msg)
{
if (msg.Length < 1)
return;
sensorValue = Parsers.Float(msg);
if (sensorValue > 0 && picoExpiratorio < sensorValue)
picoExpiratorio = sensorValue;
}
private void Start()
{
FindObjectOfType<SerialController>().OnSerialMessageReceived += OnMessageReceived;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Profiling2.Domain.Contracts.Queries;
using Profiling2.Domain.Contracts.Tasks;
using Profiling2.Domain.Prf.Persons;
namespace Profiling2.Tasks
{
public class WantedTasks : IWantedTasks
{
protected readonly IPersonTasks personTasks;
protected readonly ICareerTasks careerTasks;
protected readonly IActionTakenTasks actionTasks;
public WantedTasks(IPersonTasks personTasks,
ICareerTasks careerTasks,
IActionTakenTasks actionTasks)
{
this.personTasks = personTasks;
this.careerTasks = careerTasks;
this.actionTasks = actionTasks;
}
public IList<Person> GetWantedCommanders()
{
IList<Person> commanders = this.careerTasks.GetCommanders().Select(x => x.Person).Distinct().ToList<Person>();
IList<Person> wantedPersonsByBackground = this.personTasks.GetPersonsWanted();
IList<Person> wantedSubjectsByAction = this.actionTasks.GetWantedActionsTaken().Select(x => x.SubjectPerson).ToList<Person>();
IList<Person> wantedObjectsByAction = this.actionTasks.GetWantedActionsTaken().Select(x => x.ObjectPerson).ToList<Person>();
return commanders.Intersect(
wantedPersonsByBackground
.Concat(wantedSubjectsByAction)
.Concat(wantedObjectsByAction)
)
.Distinct()
.ToList<Person>();
}
}
}
|
namespace LikDemo.Models
{
public class Debtor
{
public RelationshipIdentification Data { get; set; }
}
}
|
using ApiTemplate.Infrastructure.Extensions.Startup;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ApiTemplate
{
public class Startup
{
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _hostingEnvironment;
public ILifetimeScope AutofacContainer { get; private set; }
public Startup(IConfiguration configuration, IWebHostEnvironment hostingEnvironment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
.AddEnvironmentVariables();
_configuration = builder.Build();
_hostingEnvironment = hostingEnvironment;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationServices(_configuration);
}
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
builder.DependencyRegistrar();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
AutofacContainer = app.ApplicationServices.GetAutofacRoot();
app.ConfigureRequestPipeline();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WormController : MonoBehaviour
{
public GameObject bazooka;
public GameObject canon;
public Transform canonPosition;
public Vector3 shootSpeed;
public Rigidbody rb;
public Vector3 jump;
public Vector3 move;
public Text healthDisplay;
public int health = 10;
void Start() {
healthDisplay.text = health.ToString();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
Debug.Log("W is to jump");
rb.AddForce(jump);
}
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("A is to move to the left");
rb.AddForce(-move);
}
if (Input.GetKeyDown(KeyCode.D))
{
Debug.Log("D is to move to the right");
rb.AddForce(move);
}
if (Input.GetKeyDown(KeyCode.C))
{
Debug.Log("C is to shoot");
GameObject sphere = Instantiate(canon, canonPosition.transform.position, Quaternion.identity);
Rigidbody rigid = sphere.GetComponent<Rigidbody>();
rigid.AddForce(shootSpeed);
}
if (Input.GetKey(KeyCode.Q))
{
Debug.Log("Q is to rotate left");
bazooka.transform.Rotate(0, 0, 5, Space.Self);
}
if (Input.GetKey(KeyCode.E))
{
Debug.Log("E is to rotate right");
bazooka.transform.Rotate(0, 0, -5, Space.Self);
}
}
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "DamageZone")
{
Debug.Log("You hit the DamageZone");
health = health - 2;
healthDisplay.text = health.ToString();
}
else
{
Debug.Log("You hit something besides the DamageZone");
}
if(collision.gameObject.tag == "HealthPackage")
{
Debug.Log("You got a Health Package!");
health = health + 1;
Destroy(collision.gameObject);
healthDisplay.text = health.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core.BIZ;
using Core.DAL;
namespace WinForm.Views
{
public partial class frmChiTietHoaDonNXB : Form
{
public frmChiTietHoaDonNXB(Form parent)
{
InitializeComponent();
_frmParent = parent;
}
public frmChiTietHoaDonNXB(Form parent, HoaDonNXB hd)
: this(parent)
{
_CurrentHD = hd;
}
#region Private Properties
private Form _frmParent;
private HoaDonNXB _CurrentHD;
#endregion
#region Form Control Listener
private void frmChiTietHoaDonNXB_Load(object sender, EventArgs e)
{
createGridViewColumns();
if (_CurrentHD != null)
{
gdvChiTiet.DataSource = _CurrentHD.ChiTiet;
lbMaSoHoaDon.Text = _CurrentHD.MaSoHoaDon + "";
lbMaSoNXB.Text = _CurrentHD.MaSoNXB + "";
lbTenNXB.Text = _CurrentHD.NXB.TenNXB;
lbNgayLap.Text = _CurrentHD.NgayLap.ToString();
lbTongTien.Text = _CurrentHD.TongTien.ToString();
}
}
private void btnThoat_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Bạn có muốn thoát", "Thông báo", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
this.Close();
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
private void createGridViewColumns()
{
gdvChiTiet.AutoGenerateColumns = false; // Bỏ auto generate Columns
gdvChiTiet.ColumnCount = 5; // Xác định số columns có
setColumn(gdvChiTiet.Columns[0]
, nameof(HoaDonNXBManager.ChiTiet.Properties.MaSoSach)
, HoaDonNXBManager.ChiTiet.Properties.MaSoSach);
setColumn(gdvChiTiet.Columns[1]
, nameof(HoaDonNXBManager.ChiTiet.Properties.Sach)
, HoaDonNXBManager.ChiTiet.Properties.Sach);
setColumn(gdvChiTiet.Columns[2]
, nameof(HoaDonNXBManager.ChiTiet.Properties.SoLuong)
, HoaDonNXBManager.ChiTiet.Properties.SoLuong);
setColumn(gdvChiTiet.Columns[3]
, nameof(HoaDonNXBManager.ChiTiet.Properties.DonGia)
, HoaDonNXBManager.ChiTiet.Properties.DonGia);
setColumn(gdvChiTiet.Columns[4]
, nameof(HoaDonNXBManager.ChiTiet.Properties.ThanhTien)
, HoaDonNXBManager.ChiTiet.Properties.ThanhTien);
gdvChiTiet.Columns[0].Width = 150;
gdvChiTiet.Columns[1].Width = 150;
gdvChiTiet.Columns[2].Width = 150;
gdvChiTiet.Columns[3].Width = 150;
gdvChiTiet.Columns[4].Width = 150;
}
private void setColumn(DataGridViewColumn column, string propertyName, string name)
{
column.Name = propertyName;
column.DataPropertyName = propertyName;
column.HeaderText = name;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;
namespace AsteroidsGame
{
public class Music
{
static Song introMusic;
static Song[] musicList = new Song[4];
static int track = 0;
public static float volume = 0.4f;
public static float fade = 0;
public static void loadMusic(ContentManager content)
{
introMusic = content.Load<Song>("Music\\Techno");
musicList[0] = content.Load<Song>("Music\\Talk");
musicList[1] = content.Load<Song>("Music\\Breaking The Habbit");
musicList[2] = content.Load<Song>("Music\\Square One");
musicList[3] = content.Load<Song>("Music\\StarLight");
MediaPlayer.Volume = volume;
}
public static void Update()
{
if (MediaPlayer.Volume >= volume)
fade = 0;
if (!TitleScreen.gameStarted)
{
if (MediaPlayer.State == MediaState.Stopped)
MediaPlayer.Play(introMusic);
else if (MediaPlayer.Queue.ActiveSong != introMusic)
if (MediaPlayer.Volume == 0)
MediaPlayer.Play(introMusic);
else
fade = -0.01f;
}
else
{
if (MediaPlayer.State == MediaState.Stopped)
playNextTrack();
else if (MediaPlayer.Queue.ActiveSong == introMusic)
if (MediaPlayer.Volume == 0)
MediaPlayer.Play(musicList[new Random().Next(musicList.Length)]);
else
fade = -0.01f;
}
if (MediaPlayer.Volume == 0)
fade = 0.01f;
MediaPlayer.Volume += fade;
}
public static void playNextTrack()
{
if (track == musicList.Length - 1)
track = 0;
else
track++;
MediaPlayer.Play(musicList[track]);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using ReflectionIT.Mvc.Paging;
using System;
using System.Diagnostics;
using System.Linq;
using Trendyol.Case.Models;
using Trendyol.Case.Service;
namespace Trendyol.Case.Controllers
{
public class HomeController : BaseController
{
private readonly IProductService _productService;
public HomeController(IMemoryCache memoryCache, IProductService productService) : base(memoryCache, productService)
{
_productService = productService;
}
//this action can be also cached with output caching by page parameter in need.
public IActionResult Index(int page = 1)
{
var products = Products().OrderBy(p => p.Id).Skip((page - 1) * 10).Take(10).ToList();
return View(new ListPageModel { Products = products, PageCount = PageCount(Products().Count, 10) });
}
private int PageCount(int total, int perPage)
{
int temp;
return Math.DivRem(total, perPage, out temp) +1;
}
public IActionResult RunInterval()
{
CheckProductCacheStatus();
return RedirectToAction("Index");
}
public IActionResult AddNewProduct()
{
_productService.AddNewProduct();
return RedirectToAction("Index");
}
public IActionResult UpdateProduct(int id)
{
_productService.UpdateProduct(id);
return RedirectToAction("Index");
}
#region MyRegion
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
public Transform player;
private Vector3 lastPosition;
private Vector3 newFocusPos;
public bool cameraLocked = true;
public bool cameraFocused = false;
[Range(0, 2.0f)] [SerializeField] float smoothFactor;
[Range(0, 1.0f)] [SerializeField] float focusModifier;
[Range(0, 2.0f)] [SerializeField] float panSpeed;
[Range(0, 200f)] [SerializeField] float rotateSpeed;
[Range(0, 10f)] [SerializeField] float scrollSpeed;
[SerializeField] float zoomMaxClamp;
private float zoomAmount;
CameraRaycaster cameraRaycaster;
void Start()
{
cameraRaycaster = Camera.main.GetComponent<CameraRaycaster>();
}
void Update()
{
if (!cameraFocused)
{
if (Input.GetKeyDown(KeyCode.L))
{
cameraLocked = !cameraLocked;
}
if (Input.GetAxis("Vertical") != 0 || Input.GetAxis("Horizontal") != 0)
{
CameraPanning();
}
if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
CameraZooming();
}
}
if (Input.GetMouseButtonDown(2))
{
lastPosition = Input.mousePosition;
}
if (Input.GetMouseButton(2))
{
CameraRotating();
}
}
void FixedUpdate()
{
if (!cameraFocused)
{
if (!cameraLocked)
{
CorrectCameraHeight();
}
if (cameraLocked)
{
CameraFollow();
}
}
// Locks Camera to focus object position
if (cameraFocused)
{
transform.position = Vector3.Lerp(transform.position, newFocusPos, smoothFactor);
}
}
//Pan camera with on axis input
void CameraPanning()
{
float verticalPan = Input.GetAxis("Vertical");
float horizontalPan = Input.GetAxis("Horizontal");
cameraLocked = false;
Vector3 move = new Vector3(horizontalPan * panSpeed, 0, verticalPan * panSpeed);
transform.Translate(move, Space.Self);
}
//Rotate camera on middle mouse button drag
void CameraRotating()
{
Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - lastPosition);
Vector3 move = new Vector3(0, pos.x * rotateSpeed * focusModifier, 0);
transform.Rotate(move);
lastPosition = Input.mousePosition;
}
//Zoom camera on mouse scroll
void CameraZooming()
{
zoomAmount += Input.GetAxis("Mouse ScrollWheel");
zoomAmount = Mathf.Clamp(zoomAmount, -zoomMaxClamp, zoomMaxClamp);
float translate = Mathf.Min(Mathf.Abs(Input.GetAxis("Mouse ScrollWheel")), zoomMaxClamp - Mathf.Abs(zoomAmount));
Camera.main.transform.Translate(0, 0, translate * scrollSpeed * Mathf.Sign(Input.GetAxis("Mouse ScrollWheel")) * focusModifier);
}
//Lock Camera to Player position
void CameraFollow()
{
Vector3 newLockedPos = player.position;
transform.position = Vector3.Lerp(transform.position, newLockedPos, smoothFactor);
}
// Constrain camera to walkable layer level
void CorrectCameraHeight()
{
Vector3 correctedPosition = new Vector3(transform.position.x, cameraRaycaster.groundPoint.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, correctedPosition, smoothFactor);
}
//Focus camera on focusObject
public void FocusCamera(Transform focusObject)
{
focusModifier = 0.5f;
newFocusPos = focusObject.position;
cameraFocused = true;
}
//Defocus camera from focus object
public void DefocusCamera()
{
focusModifier = 1f;
cameraFocused = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace MyWebshopContract
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant,UseSynchronizationContext = false)]
//[CallbackBehavior(UseSynchronizationContext = false)]
public class Cwebshop : IWebshop,IBackoffice
{
public List<item> items;
public List<Order> order;
public static IWebshopCallback callback;
public static Action<string,DateTime> m_event = delegate{};
IMyEvents subscriber;
public Cwebshop()
{
items = new List<item>();
order = new List<Order>();
items.Add(new item("0001", "Book1", 100.00, 19, false));
items.Add(new item("0002", "Book2", 10.00, 122, false));
items.Add(new item("0003", "Book3", 90.00, 120, false));
items.Add(new item("0004", "Book4", 80.1, 10, false));
}
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public string GetWebshopName()
{
return "Obaid Book Shop";
}
public List<item> GetProductList()
{
return items;
}
public string GetProductInfo(string ProductId)
{
foreach (item i in items)
{
if (i.ProductId==ProductId)
{
return i.ProductInfo;
}
}
return "No item found";
}
public bool BuyProduct(string productId)
{
foreach (item i in items)
{
if (productId == i.ProductId)
{
i.Stock = i.Stock - 1 ;
callback =OperationContext.Current.GetCallbackChannel<IWebshopCallback>();
order.Add(new Order(productId, DateTime.Now,callback));
FireEvent(i.ProductId,DateTime.Now);
return true;
}
}
return false;
}
public static void FireEvent(string pid ,DateTime date)
{
m_event(pid , date);
}
public void Add(item s)
{
throw new NotImplementedException();
}
public List<Order> GetOrderList()
{
return order;
}
public bool ShipOrder(string ProductId)
{
foreach (Order o in order)
{
if (ProductId == o.ProductId)
{
o.WebshopCallback.productShipped(ProductId, DateTime.Now);
removeorder(o);
return true;
}
}
return false;
}
public void removeorder(Order o)
{
order.Remove(o);
}
public void Subscribe()
{
subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
m_event += subscriber.OnEvent;
}
}
}
|
using CapaDatos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tulpep.NotificationWindow;
namespace CapaUsuario.Compras.Cuenta_corriente
{
public partial class FrmCuentasCorriente : Form
{
private DCuentaCorriente cuentaCorriente;
private DProveedores dProveedores;
DFacturasProv dFacturas;
DNotaCredito dNotaCredito;
private bool nueva;
private bool modifSaldos;
private int codCuentaCorriente;
public FrmCuentasCorriente()
{
InitializeComponent();
}
private void FrmCuentasCorriente_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
CargarCuentas();
ProveedorComboBox.SelectedIndex = -1;
}
private void CargarCuentas()
{
cuentaCorriente = new CapaDatos.DCuentaCorriente();
DgvCuentas.DataSource = cuentaCorriente.SelectCuentasCorriente();
DgvCuentas.Refresh();
}
private void FrmCuentasCorriente_SizeChanged(object sender, EventArgs e)
{
DgvCuentas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
DgvFacturas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
DgvNotas.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
private void HabilitarCampos()
{
ProveedorComboBox.Enabled = true;
DebeTextBox.ReadOnly = true;
HaberTextBox.ReadOnly = true;
BorrarCuentaButton.Enabled = false;
ModificarCuentaButton.Enabled = false;
ModificarSaldosButton.Enabled = false;
NuevaCuentaButton.Enabled = false;
GuardarDatosButton.Enabled = true;
CancelarNuevoButton.Enabled = true;
ProveedorComboBox.Focus();
}
private void DeshabilitarCampos()
{
ProveedorComboBox.Enabled = false;
DebeTextBox.ReadOnly = true;
HaberTextBox.ReadOnly = true;
BorrarCuentaButton.Enabled = true;
ModificarCuentaButton.Enabled = true;
ModificarSaldosButton.Enabled = true;
NuevaCuentaButton.Enabled = true;
GuardarDatosButton.Enabled = false;
CancelarNuevoButton.Enabled = false;
ProveedorComboBox.Focus();
}
private void LimpiarCampos()
{
ProveedorComboBox.SelectedIndex = -1;
DebeTextBox.Text = string.Empty;
HaberTextBox.Text = string.Empty;
}
private void NuevaCuentaButton_Click(object sender, EventArgs e)
{
CargarComboProveedores();
HabilitarCampos();
nueva = true;
materialTabControl1.SelectedTab = TabNuevaCuenta;
}
private void CargarComboProveedores()
{
dProveedores = new DProveedores();
ProveedorComboBox.DataSource = dProveedores.SelectCodAndRazonProveedoresSinCuentaCorriente();
ProveedorComboBox.DisplayMember = "RazonSocial";
ProveedorComboBox.ValueMember = "CodProveedor";
}
private void CancelarNuevoButton_Click(object sender, EventArgs e)
{
LimpiarCampos();
DeshabilitarCampos();
VaciarGrids();
}
private void GuardarDatosButton_Click(object sender, EventArgs e)
{
if (!modifSaldos)
{
if (ProveedorComboBox.SelectedIndex == -1)
{
MessageBox.Show("Seleccione un proveedor", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
var rta = MessageBox.Show("¿Guardar datos?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (rta == DialogResult.No) return;
cuentaCorriente = new DCuentaCorriente();
if (!modifSaldos)
{
var codProv = (int)ProveedorComboBox.SelectedValue;
if (nueva)
{
var msg = cuentaCorriente.InsertCuentaProveedor(codProv, 0, 0);
var popup1 = new PopupNotifier()
{
Image = msg == "Se ingresó la cuenta correctamente"
? Properties.Resources.sql_success1 : Properties.Resources.sql_error,
TitleText = "Mensaje",
ContentText = msg,
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(10)
};
popup1.Popup();
}
else
{
var msg = cuentaCorriente.UpdateCuentaProveedor(codProv);
var popup1 = new PopupNotifier()
{
Image = msg == "Se actualizó la cuenta correctamente"
? Properties.Resources.info100 : Properties.Resources.sql_error,
TitleText = "Mensaje",
ContentText = msg,
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(0)
};
popup1.Popup();
}
}
else
{
var debe = decimal.Parse(DebeTextBox.Text);
var haber = decimal.Parse(HaberTextBox.Text);
var msg = cuentaCorriente.UpdateDebeHaberCuentaProveedor(codCuentaCorriente, debe, haber);
var popup1 = new PopupNotifier()
{
Image = msg == "Se actualizó la cuenta correctamente"
? Properties.Resources.info100 : Properties.Resources.sql_error,
TitleText = "Mensaje",
ContentText = msg,
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(0)
};
popup1.Popup();
}
VaciarGrids();
LimpiarCampos();
DeshabilitarCampos();
CargarCuentas();
}
private void ModificarCuentaButton_Click(object sender, EventArgs e)
{
if (IsGridEmpty(DgvCuentas, "cuentas")) return;
nueva = false;
CargarComboProveedores();
HabilitarCampos();
materialTabControl1.SelectedTab = TabNuevaCuenta;
}
private void CargarFacturas()
{
dFacturas = new DFacturasProv();
DgvFacturas.DataSource = dFacturas.SelectFacturasNoRegistradas();
DgvFacturas.Refresh();
}
private void CargarNotasCredito()
{
dNotaCredito = new DNotaCredito();
DgvNotas.DataSource = dNotaCredito.SelectNotasCreditoNoRegistradas();
DgvNotas.Refresh();
}
private void BorrarCuentaButton_Click(object sender, EventArgs e)
{
if (IsGridEmpty(DgvCuentas, "cuentas")) return;
var rta = MessageBox.Show("¿Borrar cuenta?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (rta == DialogResult.No) return;
var codProv = (int)ProveedorComboBox.SelectedValue;
var msg = cuentaCorriente.DeleteCuentaProveedor(codProv);
var popup1 = new PopupNotifier()
{
Image = msg == "Se borró la cuenta correctamente"
? Properties.Resources.info100 : Properties.Resources.sql_error,
TitleText = "Mensaje",
ContentText = msg,
ContentFont = new Font("Segoe UI Bold", 11F),
TitleFont = new Font("Segoe UI Bold", 10F),
ImagePadding = new Padding(0)
};
popup1.Popup();
CargarCuentas();
}
private bool IsGridEmpty(DataGridView dgv, string entidad)
{
if (dgv.RowCount == 0)
{
MessageBox.Show($"No hay {entidad}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return true;
}
return false;
}
private void ModificarSaldosButton_Click(object sender, EventArgs e)
{
materialTabControl1.SelectedTab = TabSaldos;
ModificarManualButton.Enabled = true;
ModifDebeFacturaButton.Enabled = true;
ModifHaberNotaButton.Enabled = true;
codCuentaCorriente = (int)DgvCuentas.SelectedRows[0].Cells[0].Value;
CargarFacturas();
CargarNotasCredito();
DeshabilitarCampos();
}
private void ModificarManualButton_Click(object sender, EventArgs e)
{
ModifDebeFacturaButton.Enabled = false;
ModifHaberNotaButton.Enabled = false;
ModificarManualButton.Enabled = false;
materialTabControl1.SelectedTab = TabNuevaCuenta;
DebeTextBox.ReadOnly = false;
HaberTextBox.ReadOnly = false;
CancelarNuevoButton.Enabled = true;
GuardarDatosButton.Enabled = true;
modifSaldos = true;
DebeTextBox.Text = DgvCuentas.SelectedRows[0].Cells[2].Value.ToString();
HaberTextBox.Text = DgvCuentas.SelectedRows[0].Cells[3].Value.ToString();
DebeTextBox.Focus();
}
private void ModifDebeFacturaButton_Click(object sender, EventArgs e)
{
if (IsGridEmpty(DgvFacturas, "facturas")) return;
try
{
var debe = (decimal)DgvCuentas.SelectedRows[0].Cells[2].Value;
cuentaCorriente = new DCuentaCorriente();
dFacturas = new DFacturasProv();
cuentaCorriente.UpdateDebeCuenta(debe, codCuentaCorriente);
dFacturas.RegistrarFactura((int)DgvFacturas.SelectedRows[0].Cells[0].Value, codCuentaCorriente);
}
catch (Exception ex )
{
MessageBox.Show($"ERROR: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("Cuenta modificada y factura registrada con éxito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
VaciarGrids();
}
private void VaciarGrids()
{
try
{
DgvFacturas.DataSource = null;
DgvFacturas.Refresh();
DgvNotas.DataSource = null;
DgvNotas.Refresh();
}
catch (Exception)
{
return;
}
}
private void ModifHaberNotaButton_Click(object sender, EventArgs e)
{
if (IsGridEmpty(DgvNotas, "notas")) return;
try
{
var haber = (decimal)DgvCuentas.SelectedRows[0].Cells[3].Value;
cuentaCorriente = new DCuentaCorriente();
dNotaCredito = new DNotaCredito();
cuentaCorriente.UpdateHaberCuenta(haber, codCuentaCorriente);
dNotaCredito.RegistrarNotaCredito((int)DgvNotas.SelectedRows[0].Cells[0].Value, codCuentaCorriente);
}
catch (Exception ex)
{
MessageBox.Show($"ERROR: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("Cuenta modificada y nota de crédito registrada con éxito", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
VaciarGrids();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace collectionsPractice
{
class Program
{
static void Main(string[] args)
{
// Create an array to hold integer values 0 through 9.
int[] arr1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// Create an array of the names "Tim", "Martin", "Nikki", & "Sara"
string[] names = {"Tim", "Martin", "Nikki", "Sara"};
Console.WriteLine(names[3]);
// Create an array of length 10 that alternates between true and false values, starting with true.
bool[] array = {true, false, true, false, true, false, true, false, true, false};
Console.WriteLine(array[3]);
// Create a list of ice cream flavors that holds at least 5 different flavors (feel free to add more than 5!)
List<string> flavors = new List<string>();
flavors.Add("Butterscotch");
flavors.Add("Vanilla");
flavors.Add("Chocolate");
flavors.Add("Strawberry");
flavors.Add("Rocky Road");
// Output the length of this list after building it.
Console.WriteLine(flavors.Count);
// Output the third flavor in the list, then remove this value.
Console.WriteLine(flavors[2]);
flavors.RemoveAt(2);
Console.WriteLine(flavors[2]);
// Output the new length of the list
Console.WriteLine(flavors.Count);
// Create a dictionary that will store both string keys as well as string values.
Dictionary<string,string> dict1 = new Dictionary<string,string>();
// For each name in the array of names you made previously, add it as a new key in this dictionary with value null.
foreach (string name in names){
dict1.Add(name, null);
}
}
}
}
|
using System.ComponentModel.DataAnnotations;
using Profiling2.Domain.Prf;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels
{
public class TagViewModel
{
public int Id { get; set; }
[Required]
public string TagName { get; set; }
public string Notes { get; set; }
public bool Archive { get; set; }
public TagViewModel() { }
public TagViewModel(Tag tag)
{
if (tag != null)
{
this.Id = tag.Id;
this.TagName = tag.TagName;
this.Notes = tag.Notes;
this.Archive = tag.Archive;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace iGarson_App.Security
{
class Encryption
{
private int i = 0, TOR = 0;
private Int64 sum = 0;
public void ChangeintoAscii(string SerialNumber, int SerialLength)
{
string lst;
for (i = 0; i < SerialLength; i++)
{
lst = SerialNumber.Substring(i, 1);
char c = char.Parse(lst);
int ascii = Convert.ToInt32(c);
AsciiSumArea(ascii);
}
sum *= 5;
sum /= 3;
sum *= 34;
sum += 2365148;
sum *= 65;
}
public void AsciiSumArea(int Ascii)
{
if (i == 5)
sum += (Ascii * 3);
else if (i == 2)
sum += (Ascii * 7);
else if (i == 6)
sum += (Ascii * 13);
else if (i == 10)
sum -= (Ascii * 2);
else
sum += Ascii;
}
public string Md5Sum(string strToEncrypt)
{
UTF8Encoding ue = new UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
public string Sha1Sum(string strToEncrypt)
{
UTF8Encoding ue = new UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hashBytes = sha.ComputeHash(bytes);
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
public string sha256_hash(string value)
{
StringBuilder Sb = new StringBuilder();
using (SHA256 hash = SHA256Managed.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
public int[] MySecurityEncrypt(string strToEncrypt)
{
char[] charArray = strToEncrypt.ToCharArray();
int[] intArray = new int[charArray.Length];
for (int i = 0; i < charArray.Length; i++)
{
intArray[i] = charArray[i];
}
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = ((((intArray[i] * 3) + 5) * 25) - 67);
}
return intArray;
}
public string MySecurityDecrypt(int[] intToDecrypt)
{
char[] charArray = new char[intToDecrypt.Length];
for (int i = 0; i < intToDecrypt.Length; i++)
{
intToDecrypt[i] = ((((intToDecrypt[i] - 67) / 25) - 5) / 3) + 2;
}
for (int i = 0; i < intToDecrypt.Length; i++)
{
charArray[i] = Convert.ToChar(intToDecrypt[i]);
}
return charArray.ToString();
}
public Int64 ShowSum()
{
return sum;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class TowerLevel {
public int cost;
public GameObject visualization;
public GameObject bullet;
public float attackSpeed; //fireRate;
public float attackDamage;
public float healthPoints;
public float attackRange;
}
public class TowerData : MonoBehaviour {
public List<TowerLevel> levels;
private TowerLevel currentLevel;
public TowerLevel CurrentLevel {
get {
return currentLevel;
}
set {
currentLevel = value;
int currentLevelIndex = levels.IndexOf(currentLevel);
GameObject levelVisualization = levels[currentLevelIndex].visualization;
for (int i = 0; i < levels.Count; i++) {
if (levelVisualization != null) {
if (i == currentLevelIndex) {
levels[i].visualization.SetActive(true);
} else {
levels[i].visualization.SetActive(false);
}
}
}
}
}
private Vector3Int cellPosition;
public Vector3Int CellPosition {
set {
cellPosition = value;
SetAdjacentTiles(value);
}
}
private List<Vector3Int> adjacentCellPositions = new List<Vector3Int>();
public List<Vector3Int> AdjacentCellPositions { get; private set; }
public Action<Vector3Int,PlayerTag> invokeOnDisable;
public PlayerTag playerTag;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
}
void OnEnable() {
CurrentLevel = levels[0];
}
void OnDisable(){
invokeOnDisable?.Invoke(cellPosition,playerTag);
}
public TowerLevel GetNextLevel() {
int currentLevelIndex = levels.IndexOf(currentLevel);
int maxLevelIndex = levels.Count - 1;
if (currentLevelIndex < maxLevelIndex) {
return levels[currentLevelIndex + 1];
} else {
return null;
}
}
public void IncreaseLevel() {
int currentLevelIndex = levels.IndexOf(currentLevel);
if (currentLevelIndex < levels.Count - 1) {
CurrentLevel = levels[currentLevelIndex + 1];
}
}
private void SetAdjacentTiles(Vector3Int cellPosition) {
adjacentCellPositions.Add(cellPosition + new Vector3Int(1, 0, 0));
adjacentCellPositions.Add(cellPosition + new Vector3Int(-1, 0, 0));
adjacentCellPositions.Add(cellPosition + new Vector3Int(0, 1, 0));
adjacentCellPositions.Add(cellPosition + new Vector3Int(0, -1, 0));
// Vertical axis has offset, so neighbor coordinates change in dependancy of odd/even row
if (IsRowEven(cellPosition)) {
adjacentCellPositions.Add(cellPosition + new Vector3Int(-1, -1, 0));
adjacentCellPositions.Add(cellPosition + new Vector3Int(-1, 1, 0));
} else {
adjacentCellPositions.Add(cellPosition + new Vector3Int(1, -1, 0));
adjacentCellPositions.Add(cellPosition + new Vector3Int(1, 1, 0));
}
}
private bool IsRowEven(Vector3Int cellPosition) {
if (cellPosition.y % 2 == 0) {
return true;
}
return false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task1_NewtonMethod
{
/// <summary>
/// Class for work with user
/// </summary>
class Input
{
public double Value { get; set; }
public double Root { get; set; }
/// <summary>
/// Method reuests user input and saves it.
/// </summary>
public void GetUserInput()
{
try
{
Console.WriteLine("Введите число");
Value = double.Parse(Console.ReadLine());
Console.WriteLine("Введите корень вычисляемого числа");
Root = double.Parse(Console.ReadLine());
}
catch (FormatException)
{
throw new FormatException("Введите корректное число");
}
}
}
}
|
using System.Runtime.Serialization;
using DiffMatchPatch;
namespace GraderBot.ProblemTypes
{
public class DiffProxy
{
private readonly Diff _diff;
public DiffProxy(Diff diff)
{
_diff = diff;
}
[DataMember(Name = "text")]
public string Text => _diff.text.ToString();
[DataMember(Name = "operation")]
public char Operation => _diff.operation.ToString()[0];
}
}
|
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
using System.Threading;
namespace Bubble_Bash
{
public partial class MainWindow : Window
{
#region Properties
private KinectSensor kinectSensor = null;
private ColorFrameReader colorFrameReader = null;
private BodyFrameReader bodyFrameReader = null;
private CoordinateMapper coordinateMapper = null;
public double HandSize { get; set; }
private static readonly Brush handClosedBrush = new SolidColorBrush(Color.FromArgb(128, 255, 0, 0));
private static readonly Brush handOpenBrush = new SolidColorBrush(Color.FromArgb(128, 0, 255, 0));
private static readonly Brush handLassoBrush = new SolidColorBrush(Color.FromArgb(128, 0, 0, 255));
public Body[] Bodies { get; internal set; }
private int displayWidth;
private int displayHeight;
private DrawingGroup drawingGroup;
//displays color camera
private WriteableBitmap colorBitmap = null;
//constant for depth
private const float InferredZPositionClamp = 0.1f;
private GameController gameController;
private Thread gameThread;
private Typeface typeFace;
private SolidColorBrush textBrush;
public ImageSource ImageSource { get; internal set; }
#endregion
/// <summary>
/// constructor
/// </summary>
public MainWindow()
{
HandSize = 50;
this.gameController = new GameController(this);
typeFace = new Typeface(new FontFamily("Verdana"), FontStyles.Normal, FontWeights.Heavy, FontStretches.Normal);
textBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
startGameThread();
InitializeKinect();
InitializeComponent();
}
/// <summary>
/// starts game logic
/// </summary>
private void startGameThread()
{
this.gameThread = new Thread(this.gameController.run);
this.gameThread.Start();
}
/// <summary>
/// Aborts the game thread and disposes & closes kinect when window is closed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
this.gameThread.Abort();
if (this.colorFrameReader != null)
{
this.colorFrameReader.Dispose();
this.colorFrameReader = null;
}
if (this.bodyFrameReader != null)
{
this.bodyFrameReader.Dispose();
this.bodyFrameReader = null;
}
if (this.kinectSensor != null)
{
this.kinectSensor.Close();
this.kinectSensor = null;
}
}
/// <summary>
/// Initializes the kinect
/// </summary>
private void InitializeKinect()
{
this.kinectSensor = KinectSensor.GetDefault();
this.coordinateMapper = this.kinectSensor.CoordinateMapper;
FrameDescription colorFrameDescription = this.kinectSensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
this.colorFrameReader = this.kinectSensor.ColorFrameSource.OpenReader();
this.colorFrameReader.FrameArrived += this.Reader_ColorFrameArrived;
this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();
this.bodyFrameReader.FrameArrived += this.Reader_BodyFrameArrived;
this.colorBitmap = new WriteableBitmap(colorFrameDescription.Width, colorFrameDescription.Height, 96.0, 96.0, PixelFormats.Bgr32, null);
this.displayWidth = colorFrameDescription.Width;
this.displayHeight = colorFrameDescription.Height;
this.kinectSensor.Open();
this.drawingGroup = new DrawingGroup();
this.ImageSource = new DrawingImage(this.drawingGroup);
this.DataContext = this;
}
/// <summary>
/// Retrieves color frame from kinect and display the frame in the colorBitmap
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Reader_ColorFrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
// ColorFrame is IDisposable
using (ColorFrame colorFrame = e.FrameReference.AcquireFrame())
{
if (colorFrame != null)
{
FrameDescription colorFrameDescription = colorFrame.FrameDescription;
using (KinectBuffer colorBuffer = colorFrame.LockRawImageBuffer())
{
this.colorBitmap.Lock();
// verify data and write the new color frame data to the display bitmap
if ((colorFrameDescription.Width == this.colorBitmap.PixelWidth) && (colorFrameDescription.Height == this.colorBitmap.PixelHeight))
{
colorFrame.CopyConvertedFrameDataToIntPtr(
this.colorBitmap.BackBuffer,
(uint)(colorFrameDescription.Width * colorFrameDescription.Height * 4),
ColorImageFormat.Bgra);
this.colorBitmap.AddDirtyRect(new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight));
}
this.colorBitmap.Unlock();
}
}
}
}
/// <summary>
/// Retrieves body from persons and draws them in the colorBitmap and draws the overlay
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Reader_BodyFrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (this.Bodies == null)
{
this.Bodies = new Body[bodyFrame.BodyCount];
}
// The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
// As long as those body objects are not disposed and not set to null in the array,
// those body objects will be re-used.
bodyFrame.GetAndRefreshBodyData(this.Bodies);
dataReceived = true;
}
}
if (dataReceived)
{
using (DrawingContext dc = this.drawingGroup.Open())
{
// draws on our ColorFrame bitmap
dc.DrawImage(this.colorBitmap, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
drawPlayerHands(gameController.PlayerOne,1, dc);
drawPlayerHands(gameController.PlayerTwo,2, dc);
bool noHandTracked = true;
foreach (Body body in this.Bodies)
{
if (body.IsTracked)
{
if (!this.gameController.hasPlayerFor(body))
{
this.gameController.addPlayer(new Player(body));
}
noHandTracked = false;
// starts the game from main menu
if (body.HandLeftState == HandState.Lasso && body.HandRightState == HandState.Lasso)
{
this.imageMenuScreen.Opacity = 0;
this.imageMenuScreenBG.Opacity = 0;
this.gameController.GameState = GameController.State.RUNNING;
}
}
}
switch (gameController.GameState)
{
case GameController.State.PAUSE:
case GameController.State.RUNNING:
drawBubbles(dc);
drawScore(dc);
drawTimer(dc);
break;
case GameController.State.SCOREBOARD:
drawScore(dc);
drawScoreboard(dc);
break;
}
//pauses the game if no body is detected
if (noHandTracked && gameController.GameState == GameController.State.RUNNING)
{
this.gameController.GameState = GameController.State.PAUSE;
}
// prevent drawing outside of our render area
this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
}
}
}
/// <summary>
/// draws the game timer in top mid on the screen
/// </summary>
/// <param name="dc"></param>
private void drawTimer(DrawingContext dc)
{
String timer = gameController.getGameTime().ToString();
dc.DrawText(new FormattedText(timer, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 58, textBrush), new Point(displayWidth / 2, 0));
}
/// <summary>
/// draws the game scoreboard at the end of the game
/// </summary>
/// <param name="dc"></param>
private void drawScoreboard(DrawingContext dc)
{
if (gameController.PlayerOne != null && gameController.PlayerTwo != null)
{
String winnerText = "Winner is Player ";
if (gameController.PlayerOne.score > gameController.PlayerTwo.score)
{
winnerText += "1\nwith " + gameController.PlayerOne.score + " points!";
}
else
{
winnerText += "2\nwith " + gameController.PlayerTwo.score + " points!"; ;
}
dc.DrawText(new FormattedText(winnerText, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 72, textBrush), new Point(displayWidth / 2 - 350, displayHeight / 2 - 100));
}
else
{
dc.DrawText(new FormattedText("Your Score:\n" + gameController.PlayerOne.score, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 72, textBrush), new Point(displayWidth / 2 - 410, displayHeight / 2 - 100));
}
}
/// <summary>
/// handles player number for multiplayer and singleplayer
/// </summary>
/// <param name="player"></param>
/// <param name="playerNumber"></param>
/// <param name="dc"></param>
private void drawPlayerHands(Player player, int playerNumber, DrawingContext dc)
{
if (player == null)
return;
Body body = player.body;
DrawHand(body.HandLeftState, getPoint(JointType.HandLeft, body), playerNumber, dc);
DrawHand(body.HandRightState, getPoint(JointType.HandRight, body), playerNumber, dc);
}
/// <summary>
/// draws score for the players
/// </summary>
/// <param name="dc"></param>
private void drawScore(DrawingContext dc)
{
String playerOneScore = "Player 1\n";
if (gameController.PlayerOne != null)
{
playerOneScore += gameController.PlayerOne.score;
}
dc.DrawText(new FormattedText(playerOneScore, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 58, textBrush), new Point(0, 0));
String playerTwoScore = "Player 2\n";
if (gameController.PlayerTwo != null)
{
playerTwoScore += gameController.PlayerTwo.score;
}
dc.DrawText(new FormattedText(playerTwoScore, CultureInfo.CurrentCulture, FlowDirection.RightToLeft, typeFace, 58, textBrush), new Point(displayWidth, 0));
if (gameController.GameState == GameController.State.PAUSE)
{
dc.DrawText(new FormattedText("Paused", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 58, textBrush), new Point(displayWidth / 2 - 110, displayHeight / 2));
}
}
/// <summary>
/// calls the DrawBubble function to draw bubbles
/// </summary>
/// <param name="dc"></param>
private void drawBubbles(DrawingContext dc)
{
var bubbles = this.gameController.Bubbles;
lock (bubbles)
{
foreach (Bubble bubble in bubbles)
{
DrawBubble(bubble, dc);
}
}
}
/// <summary>
/// draws bubbles on the colorFrame
/// </summary>
/// <param name="bubble"></param>
/// <param name="drawingContext"></param>
private static void DrawBubble(Bubble bubble, DrawingContext drawingContext)
{
Color white = new Color();
white = Color.FromArgb(100, 255, 255, 255);
Brush brush = new RadialGradientBrush(white, bubble.BubbleColor);
Pen pen = new Pen(new SolidColorBrush(Color.FromArgb(150, 0, 0, 0)), 5);
drawingContext.DrawEllipse(brush, pen, new Point(bubble.BubblePosition.X, bubble.BubblePosition.Y), bubble.BubbleSize, bubble.BubbleSize);
}
/// <summary>
/// joints the body and hand
/// </summary>
/// <param name="type"></param>
/// <param name="body"></param>
/// <returns></returns>
public Point getPoint(JointType type, Body body)
{
CameraSpacePoint jointPosition = body.Joints[type].Position;
if (jointPosition.Z < 0)
{
jointPosition.Z = InferredZPositionClamp;
}
//solves z-angle displacement
ColorSpacePoint jointColorSpacePoint = this.coordinateMapper.MapCameraPointToColorSpace(jointPosition);
return new Point(jointColorSpacePoint.X, jointColorSpacePoint.Y);
}
/// <summary>
/// draws the hand, according to the handstate on the body
/// </summary>
/// <param name="handState"></param>
/// <param name="handPosition"></param>
/// <param name="playerNumber"></param>
/// <param name="drawingContext"></param>
private void DrawHand(HandState handState, Point handPosition, int playerNumber, DrawingContext drawingContext)
{
Point p = handPosition;
p.X -= 10;
p.Y -= 20;
switch (handState)
{
case HandState.Closed:
drawingContext.DrawEllipse(handClosedBrush, null, handPosition, HandSize, HandSize);
drawingContext.DrawText(new FormattedText(playerNumber.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 30, textBrush), p);
break;
case HandState.Open:
drawingContext.DrawEllipse(handOpenBrush, null, handPosition, HandSize, HandSize);
drawingContext.DrawText(new FormattedText(playerNumber.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 30, textBrush), p);
break;
case HandState.Lasso:
drawingContext.DrawEllipse(handLassoBrush, null, handPosition, HandSize, HandSize);
drawingContext.DrawText(new FormattedText(playerNumber.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeFace, 30, textBrush), p);
break;
}
}
}
}
|
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 JobDatabase;
namespace JobMon
{
public partial class EditorForm : Form
{
JobDatabase.JobDatabase iJobDb;
string iFilterType;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aJobDb">Interface to Job database</param>
/// <param name="aName">Name of item which may be added to the filter</param>
/// <param name="aFilter">The filter type</param>
public EditorForm(JobDatabase.JobDatabase aJobDb, string aName, string aFilter)
{
InitializeComponent();
iJobDb = aJobDb;
iFilterType = aFilter;
this.Text = "Edit " + iFilterType;
newTextBox.Text = aName.Trim();
List<string> existingItems = iJobDb.GetFilterItems(aFilter);
existingListBox.Items.AddRange(existingItems.ToArray());
}
/// <summary>
/// Add the text in the text box as a new item for the filter
/// </summary>
private void buttonAdd_Click(object sender, EventArgs e)
{
string item = newTextBox.Text;
if (!iJobDb.AddFilterItem(iFilterType, item))
{
string diagnostic = string.Format("Failed to add item {0} to filter {1}\n{2}",
item, iFilterType, iJobDb.Diagnostic);
MessageBox.Show(diagnostic, "JobMon");
return;
}
// Easiest way of refreshing the list box to include the new item
existingListBox.Items.Clear();
List<string> existingItems = iJobDb.GetFilterItems(iFilterType);
existingListBox.Items.AddRange(existingItems.ToArray());
int itemNumber = existingListBox.Items.IndexOf(item);
if ((itemNumber >= 0) && (itemNumber < existingListBox.Items.Count))
{
existingListBox.SelectedIndex = itemNumber;
}
}
private void existingListBox_MouseDown(object sender, MouseEventArgs e)
{
// Mouse button selects the current item
int itemNumber = existingListBox.IndexFromPoint(e.X, e.Y);
if ((itemNumber >= 0) && (itemNumber < existingListBox.Items.Count))
{
existingListBox.SelectedIndex = itemNumber;
existingListBox.Refresh();
// For right-click, show the context menu
if (e.Button == MouseButtons.Right)
{
int listX = e.X + existingListBox.ClientRectangle.Left;
int listY = e.Y + existingListBox.ClientRectangle.Top;
editMenuStrip.Show(new Point(listX, listY));
}
}
}
// Want to recognise right-click rather than left-click
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
int itemNumber = existingListBox.SelectedIndex;
if ((itemNumber >= 0) && (itemNumber < existingListBox.Items.Count))
{
string item = existingListBox.Items[itemNumber].ToString();
DialogResult res = MessageBox.Show("Delete <" + item + ">?", iFilterType,
MessageBoxButtons.OKCancel);
if (res == DialogResult.OK)
{
if (!iJobDb.DeleteFilterItem(iFilterType, item))
{
string diagnostic =
string.Format("Failed to delete item {0} from filter {1}\n{2}",
item, iFilterType, iJobDb.Diagnostic);
MessageBox.Show(diagnostic, "JobMon");
return;
}
// Easiest way of refreshing the list box to exclude the deleted item
existingListBox.Items.Clear();
List<string> existingItems = iJobDb.GetFilterItems(iFilterType);
existingListBox.Items.AddRange(existingItems.ToArray());
if (itemNumber < existingListBox.Items.Count)
{
existingListBox.SelectedIndex = itemNumber;
}
}
}
}
private void cancelToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void buttonExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System;
namespace Roog
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World, my student number is 17N9007!");
}
}
}
|
using PopulationFitness.Models.FastMaths;
using PopulationFitness.Models.Genes.BitSet;
using System;
namespace PopulationFitness.Models.Genes.LocalMinima
{
public class RastriginGenes : NormalizingBitSetGenes
{
private const long RastriginTermA = 10; // The A term in f{x}=sum _{i=1}^{n}[t[x_{i}^{2}-A\cos(2\pi x_{i})]
private const double TwoPi = 2 * Math.PI;
public RastriginGenes(Config config) : base(config, 5.12) { }
protected override double CalculateNormalizationRatio(int n)
{
return 40.25 * n;
}
protected override double CalculateFitnessFromIntegers(long[] integer_values)
{
/*
This is a tunable Rastrigin function: https://en.wikipedia.org/wiki/Rastrigin_function
f(x)=sum{i=1 to n}[x{i}^2- A cos(2pi x{i})]
The '2pi' term is replaced by 'fitness_factor * pi' to make the function tunable
*/
return GetRastriginFitnessUsingCos(RastriginTermA * integer_values.Length, integer_values);
}
private double GetRastriginFitnessUsingCos(double fitness, long[] integer_values)
{
foreach (long integer_value in integer_values)
{
double x = Interpolate(integer_value);
fitness += x * x - RastriginTermA * CosSineCache.Cos(TwoPi * x);
}
return fitness;
}
}
}
|
using PhotonInMaze.Common;
using PhotonInMaze.Common.Controller;
using UnityEngine;
namespace PhotonInMaze.Provider {
public class MazeObjectsProvider : SceneSingleton<MazeObjectsProvider> {
[SerializeField]
private GameObject maze = null;
[SerializeField]
private GameObject floor = null;
[SerializeField]
private GameObject wall = null;
[SerializeField]
private GameObject blackHole = null;
[SerializeField]
private GameObject whiteHole = null;
public GameObject GetMaze() {
LogIfObjectIsNull(maze, "Maze");
return maze;
}
public IMazeConfiguration GetMazeConfiguration() {
var script = maze.GetComponent<IMazeConfiguration>();
LogIfObjectIsNull(script, "MazeConfiguration");
return script;
}
public IMazeController GetMazeController() {
var script = maze.GetComponent<IMazeController>();
LogIfObjectIsNull(script, "MazeController");
return script;
}
public IPathToGoalManager GetPathToGoalManager() {
var script = maze.GetComponent<IPathToGoalManager>();
LogIfObjectIsNull(script, "PathToGoalManager");
return script;
}
public IMazeCellManager GetMazeCellManager() {
var script = maze.GetComponent<IMazeCellManager>();
LogIfObjectIsNull(script, "MazeCellManager");
return script;
}
public GameObject GetFloor() {
LogIfObjectIsNull(floor, "Floor");
return floor;
}
public GameObject GetWall() {
LogIfObjectIsNull(wall, "Wall");
return wall;
}
public GameObject GetWhiteHole() {
LogIfObjectIsNull(whiteHole, "WhiteHole");
return whiteHole;
}
public GameObject GetBlackHole() {
LogIfObjectIsNull(blackHole, "BlackHole");
return blackHole;
}
private void LogIfObjectIsNull(object o, string name) {
if(o == null) {
Debug.LogError(name + " is null!");
}
}
}
}
|
using Aria.Core.Interfaces;
namespace Aria.Engine.Interfaces
{
public interface ISceneManager : IDisposableServiceProvider, IUpdatable
{
IScene ActiveScene { get; }
void ChangeScene(IScene scene);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Windows;
namespace MyAlgorithmStudy
{
class Program
{
static void Main(string[] args)
{
//string addStr = addString("10",3,'0');
//Console.WriteLine(addStr);
var ss= "[{\"BUGUID\":1001,\"BUName\":\"明源\",\"HierarchyCode\":0001,\"ParentGUID\":001,\"BUType\":0},{\"BUGUID\":1002,\"BUName\":\"武汉\",\"HierarchyCode\":0002,\"ParentGUID\":002,\"BUType\":0},{\"BUGUID\":1003,\"BUName\":\"武源\",\"HierarchyCode\":0003,\"ParentGUID\":003,\"BUType\":0}]";
var tt = "{\"BUGUID\":1001,\"BUName\":\"武汉明源\",\"HierarchyCode\":0001,\"ParentGUID\":001,\"BUType\":0}";
string resultJson=MyJson(ss);
Console.WriteLine(resultJson);
Console.ReadKey();
}
/// <summary>
/// 要求返回字符串的长度至少为minLength,不够的用padChar在前面附加
/// </summary>
/// <param name="str">原始字符串</param>
/// <param name="minLength">最小长度</param>
/// <param name="padChar">用来附加的字符</param>
/// <returns>返回更改后的字符串(可能没有变化)</returns>
private static string addString(String str,int minLength,char padChar)
{
string strResult="";
int length = str.Length;
if (length >= minLength)
{
return str;
}
else
{
for(int i=0;i<minLength-length;i++)
{
strResult+=padChar;
}
}
return strResult+str;
}
/// <summary>
/// 对JSON字符串进行操作
/// </summary>
/// <param name="strJson"></param>
private static string MyJson(string strJson)
{
JArray array = JArray.Parse(strJson);
//JObject obj = JObject.Parse(strJson);
return array[0]["BUName"].ToString();
}
}
}
|
namespace MeeToo.Services.MessageSending.Email.Options
{
public class EmailOptions
{
public string UserName { get; set; }
public string Password { get; set; }
public TemplateSource TemplateSource { get; set; }
}
public class TemplateSource
{
public BlobSource Blob { get; set; }
}
public class BlobSource
{
public string Container { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using Assets.Scripts;
using UnityEngine;
using UnityStandardAssets.Water;
public class WorldController : MonoBehaviour
{
public Gradient TreesGradient;
public List<Material> TreesMaterials;
public Gradient WaterGradient;
public Gradient WaterBaseGradient;
public Material Water;
public TOD_Time Time;
public TOD_Sky Sky;
public TOD_WeatherManager Weather;
public WaterBase WaterController;
public GameManager GameManager;
public float DayLength;
public float NightLength;
public GameObject RainLichtingAndSound;
public Vector2 RainDelay;
public Vector2 RainTime;
public GameObject Grass;
public bool IsRain { get; private set; }
void Start ()
{
if (RainLichtingAndSound != null)
RainLichtingAndSound.SetActive(false);
StartCoroutine(DelayInit());
StartCoroutine(Rain());
}
private IEnumerator DelayInit()
{
yield return new WaitForSeconds(2.0f);
Time.DayLengthInMinutes = TOD_Sky.Instance.IsDay ? DayLength : NightLength;
Time.OnSunset += SunSet;
Time.OnSunrise += SunRise;
}
private IEnumerator Rain()
{
while (true)
{
var delay = Random.Range((int)RainDelay.x, (int)RainDelay.y);
yield return new WaitForSeconds(delay);
Weather.Atmosphere = TOD_WeatherManager.AtmosphereType.Storm;
yield return new WaitForSeconds(10.0f);
GameManager.Player.Rain.SetActive(true);
if (RainLichtingAndSound != null)
RainLichtingAndSound.SetActive(true);
IsRain = true;
yield return new WaitForSeconds(Random.Range((int)RainTime.x, (int)RainTime.y));
Weather.Atmosphere = TOD_WeatherManager.AtmosphereType.Clear;
GameManager.Player.Rain.SetActive(false);
if (RainLichtingAndSound != null)
RainLichtingAndSound.SetActive(false);
IsRain = false;
}
}
private void SunSet()
{
Time.DayLengthInMinutes = NightLength;
}
private void SunRise()
{
Time.DayLengthInMinutes = DayLength;
GameCenterManager.ReportScore(GameCenterManager.RatingAmountLivedDays, 1);
GooglePlayServicesController.ReportScore(GPGSIds.leaderboard_amount_lived_days, 1);
}
void Update ()
{
var curTimePercent = TOD_Sky.Instance.Cycle.Hour / 24.0f;
foreach (var material in TreesMaterials)
{
if (material != null)
material.SetColor("_Color", TreesGradient.Evaluate(curTimePercent));
}
if (Water != null)
{
Water.SetColor("_ReflectionColor", WaterGradient.Evaluate(curTimePercent));
Water.SetColor("_BaseColor", WaterBaseGradient.Evaluate(curTimePercent));
}
}
void OnDestroy()
{
Time.OnSunset -= SunSet;
Time.OnSunrise -= SunRise;
}
}
|
using System;
using System.Xml;
using Microsoft.Xna.Framework;
using SuperMario.Entities.Blocks;
using SuperMario.Entities.Mario;
namespace SuperMario
{
public class LevelLoading
{
public LevelData LevelObjectsData { get; private set; }
public void LoadLevel()
{
using (XmlReader levelFile = XmlReader.Create("Content/MarioTestAreaLevel.xml"))
{
levelFile.ReadToFollowing("LevelHeight");
int levelHeight = levelFile.ReadElementContentAsInt();
levelFile.ReadToNextSibling("LevelWidth");
int levelWidth = levelFile.ReadElementContentAsInt();
LevelObjectsData = new LevelData(levelHeight, levelWidth);
levelFile.ReadToFollowing("ObjectData");
while (!levelFile.EOF)
{
LevelObject levelObject = new LevelObject();
levelFile.ReadToDescendant("ObjectType");
levelObject.ObjectType = levelFile.ReadElementContentAsString();
levelFile.ReadToNextSibling("ObjectName");
levelObject.ObjectName = levelFile.ReadElementContentAsString();
levelFile.ReadToNextSibling("Location");
string location = levelFile.ReadElementContentAsString();
int i = location.IndexOf(' ');
int xPos = int.Parse(location.Substring(0, i));
int yPos = int.Parse(location.Substring(i));
levelObject.Location = new Vector2(xPos, yPos);
if (levelObject.ObjectType == "Blocks")
{
levelFile.ReadToNextSibling("BlockItemType");
levelObject.BlockItemType = (BlockItemType)Enum.Parse(typeof(BlockItemType), levelFile.ReadElementContentAsString());
}
if (levelObject.ObjectType.Equals("Mario"))
{
levelFile.ReadToNextSibling("Lives");
levelObject.Lives = levelFile.ReadElementContentAsInt();
levelFile.ReadToNextSibling("PlayerType");
levelObject.PlayerType = (PlayerSkin)Enum.Parse(typeof(PlayerSkin), levelFile.ReadElementContentAsString());
}
LevelObjectsData.ObjectData.Add(levelObject);
levelFile.ReadToFollowing("Item");
}
}
EntityStorage.Instance.PopulateEntityList(LevelObjectsData);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Ricky.Infrastructure.Core;
using Ricky.Infrastructure.Core.Caching;
using Ricky.Infrastructure.Core.Configuration;
using VnStyle.Services.Data;
using VnStyle.Services.Data.Domain;
namespace VnStyle.Services.Business
{
public class SettingService : ISettingService
{
private readonly ICacheManager _cacheManager;
private readonly IBaseRepository<Setting> _settingRepository;
public SettingService(ICacheManager cacheManager, IBaseRepository<Setting> settingRepository)
{
_cacheManager = cacheManager;
_settingRepository = settingRepository;
}
#region Nested classes
[Serializable]
public class SettingForCaching
{
public int Id { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
#endregion
public void DeleteConfiguration(long configurationId)
{
_settingRepository.DeleteRange(p => p.Id == configurationId);
_cacheManager.RemoveByPattern(CachingKey.SettingServicePattern);
}
public T GetConfigurationByKey<T>(string key, T defaultValue = default(T))
{
if (String.IsNullOrEmpty(key))
return defaultValue;
var settings = GetAllSettingsCached();
key = key.Trim().ToLowerInvariant();
if (settings.ContainsKey(key))
{
var settingsByKey = settings[key];
var setting = settingsByKey.FirstOrDefault();
if (setting != null) return CommonHelper.To<T>(setting.Value);
}
return defaultValue;
}
public void SetConfiguration<T>(string key, T value, bool clearCache = true)
{
if (key == null)
throw new ArgumentNullException("key");
key = key.Trim().ToLowerInvariant();
string valueStr = CommonHelper.GetCustomTypeConverter(typeof(T)).ConvertToInvariantString(value);
var allSettings = GetAllSettingsCached();
var settingForCaching = allSettings.ContainsKey(key) ?
allSettings[key].FirstOrDefault() : null;
if (settingForCaching != null)
{
//update
//var setting = ConfigurationRepository.GetById(settingForCaching.Id);
//setting.Value = valueStr;
//DbContext.SaveChanges();
var oldSetting = _settingRepository.GetById(settingForCaching.Id);
//DbContext.Set<DAL.Models.Configuration>().Attach(oldSetting);
oldSetting.Value = valueStr;
_settingRepository.SaveChanges();
}
else
{
var settingObj = new Setting
{
Key = key,
Value = valueStr,
};
_settingRepository.Insert(settingObj);
_settingRepository.SaveChanges();
}
if (clearCache) _cacheManager.RemoveByPattern(CachingKey.SettingServicePattern);
}
public IList<Setting> GetAllConfigurations()
{
var settings = _settingRepository.Table.ToList();
return settings;
}
public bool ConfigurationExists<T, TPropType>(T configurations, Expression<Func<T, TPropType>> keySelector) where T : ISetting, new()
{
var member = keySelector.Body as MemberExpression;
if (member == null)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
keySelector));
}
var propInfo = member.Member as PropertyInfo;
if (propInfo == null)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
keySelector));
}
string key = typeof(T).Name + "." + propInfo.Name;
string setting = GetConfigurationByKey<string>(key);
return setting != null;
}
public T LoadConfiguration<T>() where T : ISetting, new()
{
var settings = Activator.CreateInstance<T>();
foreach (var prop in typeof(T).GetProperties())
{
// get properties we can read and write to
if (!prop.CanRead || !prop.CanWrite)
continue;
var key = typeof(T).Name + "." + prop.Name;
//load by store
string setting = GetConfigurationByKey<string>(key);
if (setting == null) continue;
if (!CommonHelper.GetCustomTypeConverter(prop.PropertyType).CanConvertFrom(typeof(string))) continue;
if (!CommonHelper.GetCustomTypeConverter(prop.PropertyType).IsValid(setting)) continue;
object value = CommonHelper.GetCustomTypeConverter(prop.PropertyType).ConvertFromInvariantString(setting);
//set property
prop.SetValue(settings, value, null);
}
return settings;
}
public void SaveConfiguration<T>(T configurations) where T : ISetting, new()
{
/* We do not clear cache after each setting update.
* This behavior can increase performance because cached settings will not be cleared
* and loaded from database after each update */
foreach (var prop in typeof(T).GetProperties())
{
// get properties we can read and write to
if (!prop.CanRead || !prop.CanWrite)
continue;
if (!CommonHelper.GetCustomTypeConverter(prop.PropertyType).CanConvertFrom(typeof(string)))
continue;
string key = typeof(T).Name + "." + prop.Name;
//Duck typing is not supported in C#. That'_settingRepository why we're using dynamic type
dynamic value = prop.GetValue(configurations, null);
if (value != null)
SetConfiguration(key, value, false);
else
SetConfiguration(key, string.Empty, false);
}
//and now clear cache
ClearCache();
}
public void SaveConfiguration<T, TPropType>(T configurations, Expression<Func<T, TPropType>> keySelector, bool clearCache = true) where T : ISetting, new()
{
var member = keySelector.Body as MemberExpression;
if (member == null)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
keySelector));
}
var propInfo = member.Member as PropertyInfo;
if (propInfo == null)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
keySelector));
}
string key = typeof(T).Name + "." + propInfo.Name;
//Duck typing is not supported in C#. That'_settingRepository why we're using dynamic type
dynamic value = propInfo.GetValue(configurations, null);
if (value != null)
SetConfiguration(key, value, clearCache);
else
SetConfiguration(key, "", clearCache);
}
public void DeleteConfiguration<T>() where T : ISetting, new()
{
var settingsToDelete = new List<int>();
var allSettings = GetAllConfigurations();
foreach (var prop in typeof(T).GetProperties())
{
string key = typeof(T).Name + "." + prop.Name;
settingsToDelete.AddRange(allSettings.Where(x => x.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)).Select(p => p.Id));
}
if (settingsToDelete.Any())
_settingRepository.DeleteRange(p => settingsToDelete.Contains(p.Id));
ClearCache();
}
public void DeleteConfiguration<T, TPropType>(T configurations, Expression<Func<T, TPropType>> keySelector) where T : ISetting, new()
{
var member = keySelector.Body as MemberExpression;
if (member == null)
{
throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.", keySelector));
}
var propInfo = member.Member as PropertyInfo;
if (propInfo == null)
{
throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.", keySelector));
}
string key = typeof(T).Name + "." + propInfo.Name;
key = key.Trim().ToLowerInvariant();
var allSettings = GetAllSettingsCached();
var settingForCaching = allSettings.ContainsKey(key) ?
allSettings[key].FirstOrDefault() : null;
if (settingForCaching != null)
{
//var setting = ConfigurationRepository.GetById(settingForCaching.Id);
////DbContext.Set<DAL.Models.Configuration>().Attach(setting);
//setting.IsDeleted = true;
//DbContext.SaveChanges();
_settingRepository.DeleteRange(p => p.Id == settingForCaching.Id);
_settingRepository.SaveChanges();
ClearCache();
}
}
#region "Private functions"
protected virtual IDictionary<string, IList<SettingForCaching>> GetAllSettingsCached()
{
string key = string.Format(CachingKey.SettingServicePattern);
return _cacheManager.Get(key, () =>
{
var settings = _settingRepository.GetAll().ToList();
var dictionary = new Dictionary<string, IList<SettingForCaching>>();
foreach (var s in settings)
{
var resourceName = s.Key.ToLowerInvariant();
var settingForCaching = new SettingForCaching()
{
Id = s.Id,
Key = s.Key,
Value = s.Value
};
if (!dictionary.ContainsKey(resourceName))
{
//first setting
dictionary.Add(resourceName, new List<SettingForCaching>()
{
settingForCaching
});
}
else
{
//already added
//most probably it'_settingRepository the setting with the same name but for some certain store (storeId > 0)
dictionary[resourceName].Add(settingForCaching);
}
}
return dictionary;
});
}
private void ClearCache()
{
_cacheManager.RemoveByPattern(CachingKey.SettingServicePattern);
}
#endregion
public void Dispose()
{
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class SignPost : MonoBehaviour
{
public void ResetScene()
{
// Reset the scene when the user clicks the sign post
SceneManager.LoadScene("Maze");
//reset key
Key.keyCollected = false;
//reset counter
Coin.counter = 0;
//reset play door unlocked sound
Key.playDoorUnlockedSound = true;
}
}
|
using System;
using System.Linq;
namespace Spool.Harlowe
{
partial class BuiltInMacros
{
public Number abs(double x) => new Number(Math.Abs(x));
public Number cos(double x) => new Number(Math.Cos(x));
public Number exp(double x) => new Number(Math.Exp(x));
public Number log(double x) => new Number(Math.Log(x));
public Number log10(double x) => new Number(Math.Log10(x));
public Number log2(double x) => new Number(Math.Log(x, 2));
public Number sign(double x) => new Number(Math.Sign(x));
public Number sin(double x) => new Number(Math.Sin(x));
public Number sqrt(double x) => new Number(Math.Sqrt(x));
public Number tan(double x) => new Number(Math.Tan(x));
public Number pow(double x, double y) => new Number(Math.Pow(x, y));
public Number min(params double[] values) => new Number(values.Min());
public Number max(params double[] values) => new Number(values.Max());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightBoxRectSubForm.data {
public class ModelWaitTime {
private double waitMM;
private double waitSS;
public ModelWaitTime() {
}
/// <summary>
/// 灯箱停留时间分钟数
/// </summary>
/// <value>The wait M.</value>
public double WaitMM {
get {
return waitMM;
}
set {
waitMM = value;
}
}
/// <summary>
/// 灯箱停留时间秒数
/// </summary>
/// <value>The wait S.</value>
public double WaitSS {
get {
return waitSS;
}
set {
waitSS = value;
}
}
public override string ToString() {
return string.Format("{0}:{1}", WaitMM, WaitSS);
}
}
}
|
using DapperExtensions;
using System.Collections.Generic;
namespace AbiokaScrum.Api.Data.Transactional
{
public interface IRepository
{
/// <summary>
/// Add an entity
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="entity">Entity</param>
void Add<T>(T entity) where T : class, new();
/// <summary>
/// Update an entity
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="entity">Entity</param>
/// <returns></returns>
bool Update<T>(T entity) where T : class, new();
/// <summary>
/// Remove an entity
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="entity">Entity</param>
/// <returns></returns>
bool Remove<T>(T entity) where T : class, new();
/// <summary>
/// Get an entity with key
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="entity">Entity</param>
/// <returns></returns>
T GetByKey<T>(object key) where T : class, new();
/// <summary>
/// Get all entities
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="entity">Entity</param>
IEnumerable<T> GetAll<T>() where T : class, new();
/// <summary>
/// Get entities with predicate and order
/// </summary>
/// <typeparam name="T">Type of entity</typeparam>
/// <param name="predicate"></param>
/// <param name="order"></param>
IEnumerable<T> GetBy<T>(IPredicate predicate, IList<ISort> sort = null) where T : class, new();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prestamos_Bancos
{
class Prestamo
{
private const double INTERES = 1.10;
private const double CARGOEXTRA = 1.01;
private double _cantidad;
private int _meses;
private bool _esRiesgo;
public bool EsRiesgo
{
get { return _esRiesgo; }
set { _esRiesgo = value; }
}
public int Meses
{
get { return _meses; }
set { _meses = value; }
}
public double Cantidad
{
get { return _cantidad; }
set { _cantidad = value; }
}
public Prestamo()
{ }
public Prestamo(double cantidad, int meses)
{
Cantidad = cantidad;
Meses = meses;
EsRiesgo = false;
}
public double CalcularCantidadMensual()
{
if (EsRiesgo)
{
return ((Cantidad * CARGOEXTRA) * INTERES) / Meses;
}
else
{
return (Cantidad * INTERES) / Meses;
}
}
}
}
|
using ReactMusicStore.Core.Data.Repository.EntityFramework.Common;
using ReactMusicStore.Core.Domain.Entities;
using ReactMusicStore.Core.Domain.Interfaces.Repository;
namespace ReactMusicStore.Core.Data.Repository.EntityFramework
{
public class OrderDetailRepository : Repository<OrderDetail>, IOrderDetailRepository
{
}
}
|
using Common;
using IBLLService;
using MODEL;
using MODEL.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BLLService
{
public partial class YX_weiXinMenus_MANAGER : BaseBLLService<YX_weiXinMenus>, IYX_weiXinMenus_MANAGER
{
public List<MODEL.WeChat.WeChatMenus> GetMainMenus()
{
return MODEL.WeChat.WeChatMenus.ToListViewModel( base.GetListBy(m => m.WX_Fid.Value == 0, m => m.flat2, false)).ToList();
}
public List<MODEL.WeChat.WeChatMenus> GetChildMenus()
{
return MODEL.WeChat.WeChatMenus.ToListViewModel(base.GetListBy(m => m.WX_Fid.Value != 0, m => m.flat2, false)).ToList();
}
public MODEL.DataTableModel.DataTableGrid GetWeChatMenusForGrid(MODEL.DataTableModel.DataTableRequest request)
{
try
{
var predicate = PredicateBuilder.True<YX_weiXinMenus>();
DateTime time = TypeParser.ToDateTime("1975-1-1");
int total = 0;
//predicate = predicate.And(p => p.isdelete != 1);
var data = VIEW_YX_weiXinMenus.ToListViewModel(base.LoadPagedList(request.PageNumber, request.PageSize, ref total, predicate, request.Model, p =>true , request.SortOrder, request.SortName));
//var list = ViewModelProduct.ToListViewModel(data);
return new MODEL.DataTableModel.DataTableGrid()
{
draw = request.Draw,
data = data,
total = total
};
}
catch (Exception)
{
throw;
}
}
public MODEL.DataTableModel.DataTableGrid GetWeChatMsgSetForGrid(MODEL.DataTableModel.DataTableRequest request)
{
try
{
var predicate = PredicateBuilder.True<YX_Event>();
DateTime time = TypeParser.ToDateTime("1975-1-1");
int total = 0;
//predicate = predicate.And(p => p.isdelete != 1);
IBLLService.IYX_Event_MANAGER YX_Event_MANAGER =new BLLService.YX_Event_MANAGER();
var data = VIEW_YX_Event.ToListViewModel(YX_Event_MANAGER.LoadPagedList(request.PageNumber, request.PageSize, ref total, predicate, request.Model, p => true, request.SortOrder, request.SortName));
//var list = ViewModelProduct.ToListViewModel(data);
return new MODEL.DataTableModel.DataTableGrid()
{
draw = request.Draw,
data = data,
total = total
};
}
catch (Exception)
{
throw;
}
}
public List<MODEL.WeChat.WeChatMenus> GetClickMenus()
{
return MODEL.WeChat.WeChatMenus.ToListViewModel(base.GetListBy(m => m.WX_MenuType== "1", m => m.flat2, false)).ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace clinic_project
{
public partial class Add_medicine : Form
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\USERS\20102\Clinic_DB.MDF;Integrated Security=True;Connect Timeout=30");
public Add_medicine()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter checkpat = new SqlDataAdapter("Select Count(*) From patient where idpat= '" + textBox1.Text + "' and iddoc= '" + textBox3.Text + "'", con);
DataTable checkdpatt = new DataTable();
checkpat.Fill(checkdpatt);
if (checkdpatt.Rows[0][0].ToString() == "0")
{
MessageBox.Show("Patient or Doctor is not Found ");
con.Close();
}
else
{
//Retrive Date from database !
SqlCommand Retrive = new SqlCommand("SELECT medicine FROM patient WHERE idpat='" + textBox1.Text + "' and iddoc= '" + textBox3.Text + "'", con);
SqlDataReader re = Retrive.ExecuteReader();
string str1 = "";
if (re.Read())
{
str1 = re["medicine"].ToString();
str1 += (Environment.NewLine + '/' + textBox2.Text);
}
con.Close();
con.Open();
SqlDataAdapter update_Medicine = new SqlDataAdapter("UPDATE patient SET medicine='" + str1.ToString() + "' WHERE idpat='" + textBox1.Text + "' and iddoc= '" + textBox3.Text + "'", con);
//SqlDataAdapter up = new SqlDataAdapter("UPDATE Doctor SET h1=1 WHERE idDoctor= ", con);
update_Medicine.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show("Done");
}
}
catch(Exception eee)
{
MessageBox.Show("invalid input");
}
}
private void Button2_Click(object sender, EventArgs e)
{
textBox1.Text = textBox2.Text = "";
this.Hide();
}
private void Add_medicine_Load(object sender, EventArgs e)
{
}
}
}
|
using Coldairarrow.Business.Base_SysManage;
using Coldairarrow.Entity.Base_SysManage;
using Coldairarrow.Util;
using System;
using System.Web.Mvc;
namespace Coldairarrow.Web
{
public class Base_DepartmentController : BaseMvcController
{
Base_DepartmentBusiness _base_DepartmentBusiness = new Base_DepartmentBusiness();
#region 视图功能
public ActionResult Index()
{
return View();
}
public ActionResult Form(string id)
{
var theData = id.IsNullOrEmpty() ? new Base_Department() : _base_DepartmentBusiness.GetTheData(id);
return View(theData);
}
#endregion
#region 获取数据
/// <summary>
/// 获取数据列表
/// </summary>
/// <param name="condition">查询类型</param>
/// <param name="keyword">关键字</param>
/// <returns></returns>
public ActionResult GetDataList(string condition, string keyword, Pagination pagination)
{
var dataList = _base_DepartmentBusiness.GetDataList(condition, keyword, pagination);
return Content(pagination.BuildTableResult_DataGrid(dataList).ToJson());
}
/// <summary>
/// 获取角色列表
/// 注:无分页
/// </summary>
/// <returns></returns>
public ActionResult GetDataList_NoPagin()
{
Pagination pagination = new Pagination
{
PageIndex = 1,
PageRows = int.MaxValue
};
var dataList = _base_DepartmentBusiness.GetDataList(null, null, pagination);
return Content(dataList.ToJson());
}
#endregion
#region 提交数据
/// <summary>
/// 保存
/// </summary>
/// <param name="theData">保存的数据</param>
public ActionResult SaveData(Base_Department theData)
{
if(theData.Id.IsNullOrEmpty())
{
theData.Id = Guid.NewGuid().ToSequentialGuid();
theData.CreateTime = DateTime.Now;
theData.ChildCount = 0;
_base_DepartmentBusiness.AddData(theData);
}
else
{
_base_DepartmentBusiness.UpdateData(theData);
}
return Success();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="theData">删除的数据</param>
public ActionResult DeleteData(string ids)
{
_base_DepartmentBusiness.DeleteData(ids.ToList<string>());
return Success("删除成功!");
}
#endregion
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Data.Filters;
using gView.Framework.FDB;
using gView.Framework.Geometry;
using gView.Framework.Network;
using gView.Framework.Network.Algorthm;
using gView.Framework.Network.Build;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Threading.Tasks;
namespace gView.DataSources.Fdb.SQLite
{
public class SQLiteFDBNetworkFeatureClass : IFeatureClass, INetworkFeatureClass
{
private SQLiteFDB _fdb;
private IDataset _dataset;
private string _name = String.Empty, _aliasname = String.Empty;
private FieldCollection _fields;
private GeometryDef _geomDef;
private IFeatureClass _nodeFc = null;
private Dictionary<int, IFeatureClass> _edgeFcs = new Dictionary<int, IFeatureClass>();
private int _fcid = -1;
private GraphWeights _weights = null;
private NetworkObjectSerializer.PageManager _pageManager = null;
private SQLiteFDBNetworkFeatureClass() { }
async static public Task<SQLiteFDBNetworkFeatureClass> Create(SQLiteFDB fdb, IDataset dataset, string name, GeometryDef geomDef)
{
var fc = new SQLiteFDBNetworkFeatureClass();
fc._fdb = fdb;
fc._fcid = await fc._fdb.FeatureClassID(await fc._fdb.DatasetID(dataset.DatasetName), name);
fc._dataset = dataset;
fc._geomDef = (geomDef != null) ? geomDef : new GeometryDef();
if (fc._geomDef != null && fc._geomDef.SpatialReference == null && dataset is IFeatureDataset)
{
fc._geomDef.SpatialReference = await ((IFeatureDataset)dataset).GetSpatialReference();
}
fc._fields = new FieldCollection();
fc._name = fc._aliasname = name;
IDatasetElement element = await fc._dataset.Element(fc._name + "_Nodes");
if (element != null)
{
fc._nodeFc = element.Class as IFeatureClass;
}
element = await fc._dataset.Element(fc._name + "_ComplexEdges");
if (element != null && element.Class is IFeatureClass)
{
fc._edgeFcs.Add(-1, (IFeatureClass)element.Class);
}
DataTable tab = await fc._fdb.Select("FCID", "FDB_NetworkClasses", "NetworkId=" + fc._fcid);
if (tab != null && tab.Rows.Count > 0)
{
StringBuilder where = new StringBuilder();
where.Append("\"GeometryType\"=" + ((int)GeometryType.Polyline).ToString() + " AND \"ID\" in(");
for (int i = 0; i < tab.Rows.Count; i++)
{
if (i > 0)
{
where.Append(",");
}
where.Append(tab.Rows[i]["FCID"].ToString());
}
where.Append(")");
tab = await fc._fdb.Select("ID,Name", "FDB_FeatureClasses", where.ToString());
if (tab != null)
{
foreach (DataRow row in tab.Rows)
{
element = await fc._dataset.Element(row["name"].ToString());
if (element != null && element.Class is IFeatureClass)
{
fc._edgeFcs.Add(Convert.ToInt32(row["id"]), element.Class as IFeatureClass);
}
}
}
}
fc._weights = await fc._fdb.GraphWeights(name);
Dictionary<Guid, string> weightTableNames = null;
Dictionary<Guid, GraphWeightDataType> weightDataTypes = null;
if (fc._weights != null && fc._weights.Count > 0)
{
weightTableNames = new Dictionary<Guid, string>();
weightDataTypes = new Dictionary<Guid, GraphWeightDataType>();
foreach (IGraphWeight weight in fc._weights)
{
if (weight == null)
{
continue;
}
weightTableNames.Add(weight.Guid, fc._fdb.TableName(fc._name + "_Weights_" + weight.Guid.ToString("N").ToLower()));
weightDataTypes.Add(weight.Guid, weight.DataType);
}
}
fc._pageManager = new NetworkObjectSerializer.PageManager(
gView.Framework.Db.DataProvider.SQLiteProviderFactory,
fc._fdb.ConnectionString, fc._name,
fc._fdb.TableName("FC_" + fc._name),
fc._fdb.TableName(fc._name + "_Edges"),
fc._fdb.TableName("FC_" + name + "_Nodes"),
weightTableNames, weightDataTypes, fc._fdb
);
return fc;
}
#region IFeatureClass Member
public string ShapeFieldName
{
get { return String.Empty; }
}
public gView.Framework.Geometry.IEnvelope Envelope
{
get
{
gView.Framework.Geometry.Envelope env = null;
if (_edgeFcs != null)
{
foreach (IFeatureClass edgeFc in _edgeFcs.Values)
{
if (edgeFc != null)
{
if (env == null)
{
env = new Envelope(edgeFc.Envelope);
}
else
{
env.Union(edgeFc.Envelope);
}
}
}
}
if (_nodeFc != null)
{
if (env == null)
{
env = new Envelope(_nodeFc.Envelope);
}
else
{
env.Union(_nodeFc.Envelope);
}
}
return (env != null) ? env : new Envelope();
}
}
async public Task<int> CountFeatures()
{
int c = 0;
if (_edgeFcs != null)
{
foreach (IFeatureClass edgeFc in _edgeFcs.Values)
{
if (edgeFc != null)
{
c += await edgeFc.CountFeatures();
}
}
}
if (_nodeFc != null)
{
c += await _nodeFc.CountFeatures();
}
return c;
}
public Task<IFeatureCursor> GetFeatures(IQueryFilter filter)
{
List<IFeatureClass> edgeFcs = new List<IFeatureClass>();
if (_edgeFcs != null)
{
foreach (IFeatureClass fc in _edgeFcs.Values)
{
edgeFcs.Add(fc);
}
}
return Task.FromResult<IFeatureCursor>(new NetworkFeatureCursor(_fdb, _name, edgeFcs, _nodeFc, filter));
}
#endregion
#region ITableClass Member
async public Task<ICursor> Search(IQueryFilter filter)
{
return await GetFeatures(filter);
}
public Task<ISelectionSet> Select(IQueryFilter filter)
{
return Task.FromResult<ISelectionSet>(null);
}
public IFieldCollection Fields
{
get { return _fields; }
}
public IField FindField(string name)
{
return _fields.FindField(name);
}
public string IDFieldName
{
get { return "FDB_OID"; }
}
#endregion
#region IClass Member
public string Name
{
get { return _name; }
}
public string Aliasname
{
get { return _aliasname; }
}
public IDataset Dataset
{
get { return _dataset; }
}
#endregion
#region IGeometryDef Member
public bool HasZ
{
get { return _geomDef.HasZ; }
}
public bool HasM
{
get { return _geomDef.HasM; }
}
public GeometryType GeometryType
{
get { return _geomDef.GeometryType; }
}
public ISpatialReference SpatialReference
{
get
{
return _geomDef.SpatialReference;
}
set
{
_geomDef.SpatialReference = value;
}
}
//public GeometryFieldType GeometryFieldType
//{
// get
// {
// return _geomDef.GeometryFieldType;
// }
//}
#endregion
#region HelperClasses
private class NetworkFeatureCursor : IFeatureCursor
{
private SQLiteFDB _fdb;
private string _networkName;
private List<IFeatureClass> _edgeFcs = new List<IFeatureClass>();
private IFeatureClass _nodeFc = null;
private int _edgeFcIndex = 0, _fcid = -1;
private IFeatureCursor _edgeCursor = null, _nodeCursor = null;
private IQueryFilter _filter;
public NetworkFeatureCursor(SQLiteFDB fdb, string networkName, List<IFeatureClass> edgeFcs, IFeatureClass nodeFc, IQueryFilter filter)
{
_fdb = fdb;
_networkName = networkName;
_edgeFcs = edgeFcs;
_nodeFc = nodeFc;
_filter = filter;
}
#region IFeatureCursor Member
async public Task<IFeature> NextFeature()
{
if (_edgeCursor == null && _edgeFcs != null && _edgeFcIndex < _edgeFcs.Count)
{
IFeatureClass fc = _edgeFcs[_edgeFcIndex++];
_fcid = await _fdb.FeatureClassID(await _fdb.DatasetID(fc.Dataset.DatasetName), fc.Name);
if (_fcid < 0)
{
return await NextFeature();
}
if (fc.Name == _networkName + "_ComplexEdges")
{
_fcid = -1;
}
IQueryFilter f = (IQueryFilter)_filter.Clone();
if (f.SubFields != "*")
{
f.AddField(fc.IDFieldName);
f.AddField(fc.ShapeFieldName);
}
_edgeCursor = await fc.GetFeatures(f);
if (_edgeCursor == null)
{
return await NextFeature();
}
}
if (_edgeCursor != null)
{
IFeature feature = await _edgeCursor.NextFeature();
if (feature != null)
{
feature.Fields.Add(new FieldValue("NETWORK#FCID", _fcid));
return feature;
}
_edgeCursor.Dispose();
_edgeCursor = null;
return await NextFeature();
}
if (_nodeCursor == null && _nodeFc != null)
{
_nodeCursor = await _nodeFc.GetFeatures(_filter);
}
if (_nodeCursor != null)
{
return await _nodeCursor.NextFeature();
}
return null;
}
#endregion
#region IDisposable Member
public void Dispose()
{
if (_edgeCursor != null)
{
_edgeCursor.Dispose();
_edgeCursor = null;
}
if (_nodeCursor != null)
{
_nodeCursor.Dispose();
_nodeCursor = null;
}
}
#endregion
}
private class SQLiteFDBGraphTableAdapter : IGraphTableAdapter
{
private string _name, _connString;
private SQLiteFDBNetworkFeatureClass _nfc;
private Dictionary<int, NetworkObjectSerializer.GraphPage> _pages = new Dictionary<int, NetworkObjectSerializer.GraphPage>();
public SQLiteFDBGraphTableAdapter(SQLiteFDB fdb, SQLiteFDBNetworkFeatureClass nfc)
{
_connString = fdb.ConnectionString;
_nfc = nfc;
_name = _nfc.Name; //name;
}
#region IGraphTableAdapter Member
public GraphTableRows QueryN1(int n1)
{
if (_nfc != null && _nfc._pageManager != null)
{
return _nfc._pageManager.QueryN1(n1);
}
return new GraphTableRows();
}
public IGraphTableRow QueryN1ToN2(int n1, int n2)
{
foreach (IGraphTableRow row in QueryN1(n1))
{
if (row.N2 == n2)
{
return row;
}
}
return null;
}
public IGraphEdge QueryEdge(int eid)
{
if (_nfc != null && _nfc._pageManager != null)
{
return _nfc._pageManager.GetEdge(eid);
}
return null;
}
public double QueryEdgeWeight(Guid weightGuid, int eid)
{
if (_nfc != null && _nfc._pageManager != null)
{
return _nfc._pageManager.GetEdgeWeight(weightGuid, eid);
}
return 0.0;
}
public bool SwitchState(int nid)
{
if (_nfc != null && _nfc._pageManager != null)
{
return _nfc._pageManager.GetSwitchState(nid);
}
return false;
}
public int GetNodeFcid(int nid)
{
if (_nfc != null && _nfc._pageManager != null)
{
return _nfc._pageManager.GetNodeFcid(nid);
}
return -1;
}
public NetworkNodeType GetNodeType(int nid)
{
if (_nfc != null && _nfc._pageManager != null)
{
return _nfc._pageManager.GetNodeType(nid);
}
return NetworkNodeType.Unknown;
}
async public Task<Features> QueryNodeEdgeFeatures(int n1)
{
Features features = new Features();
GraphTableRows rows = QueryN1(n1);
if (rows == null)
{
return features;
}
foreach (GraphTableRow row in rows)
{
IFeature feature = await _nfc.GetEdgeFeature(row.EID);
if (feature != null)
{
feature.Fields.Add(new FieldValue("NETWORK#EID", row.EID));
features.Add(feature);
}
}
return features;
}
async public Task<Features> QueryNodeFeatures(int n1)
{
Features features = new Features();
IFeature feature = await _nfc.GetNodeFeature(n1);
if (feature != null)
{
features.Add(feature);
}
return features;
}
#endregion
}
#endregion
#region INetworkFeatureClass Member
public IGraphTableAdapter GraphTableAdapter()
{
return new SQLiteFDBGraphTableAdapter(_fdb, this);
}
async public Task<IFeatureCursor> GetNodeFeatures(IQueryFilter filter)
{
if (_nodeFc != null)
{
return await _nodeFc.GetFeatures(filter);
}
return null;
}
async public Task<IFeatureCursor> GetEdgeFeatures(IQueryFilter filter)
{
if (_edgeFcs.Count == 0)
{
return null;
}
if (filter is SpatialFilter)
{
List<IFeatureClass> edgeFcs = new List<IFeatureClass>();
if (_edgeFcs != null)
{
foreach (IFeatureClass fc in _edgeFcs.Values)
{
edgeFcs.Add(fc);
}
}
return new NetworkFeatureCursor(_fdb, _name, edgeFcs, null, filter);
}
if (filter is RowIDFilter)
{
RowIDFilter idFilter = (RowIDFilter)filter;
Dictionary<int, QueryFilter> rfilters = new Dictionary<int, QueryFilter>();
Dictionary<int, Dictionary<int, List<FieldValue>>> additionalFields = new Dictionary<int, Dictionary<int, List<FieldValue>>>();
foreach (int eid in idFilter.IDs)
{
IGraphEdge edge = _pageManager.GetEdge(eid);
if (edge == null || _edgeFcs.ContainsKey(edge.FcId) == false)
{
continue;
}
if (!rfilters.ContainsKey(edge.FcId))
{
string idFieldName = "FDB_OID";
string shapeFieldName = "FDB_SHAPE";
IFeatureClass fc = edge.FcId >= 0 ? await _fdb.GetFeatureclass(edge.FcId) : null;
if (fc != null)
{
idFieldName = fc.IDFieldName;
shapeFieldName = fc.ShapeFieldName;
}
RowIDFilter rfilter = new RowIDFilter(edge.FcId >= 0 ? idFieldName : "EID");
rfilter.fieldPostfix = rfilter.fieldPrefix = "\"";
rfilters.Add(edge.FcId, rfilter);
additionalFields.Add(edge.FcId, new Dictionary<int, List<FieldValue>>());
rfilter.IgnoreUndefinedFields = true;
rfilters[edge.FcId].AddField(shapeFieldName);
if (filter.SubFields.IndexOf("*") != -1 || fc == null)
{
rfilters[edge.FcId].AddField("*");
}
else
{
foreach (string field in filter.SubFields.Split(' '))
{
if (field == shapeFieldName)
{
continue;
}
if (fc.Fields.FindField(field) != null)
{
rfilter.AddField(fc.Fields.FindField(field).name);
}
}
}
}
((RowIDFilter)rfilters[edge.FcId]).IDs.Add(edge.FcId >= 0 ? edge.Oid : edge.Eid);
additionalFields[edge.FcId].Add(edge.FcId >= 0 ? edge.Oid : edge.Eid, new List<FieldValue>()
{
new FieldValue("_eid",edge.Eid)
});
}
if (rfilters.ContainsKey(-1))
{
RowIDFilter complexEdgeFilter = (RowIDFilter)rfilters[-1];
QueryFilter ceFilter = new QueryFilter(complexEdgeFilter);
ceFilter.WhereClause = complexEdgeFilter.RowIDWhereClause;
rfilters[-1] = ceFilter;
}
return new CursorCollection<int>(_edgeFcs, rfilters, additionalFields);
}
return null;
}
async public Task<IFeature> GetNodeFeature(int nid)
{
QueryFilter filter = new QueryFilter();
filter.WhereClause = _fdb.DbColName("FDB_OID") + "=" + nid;
filter.AddField("*");
try
{
using (IFeatureCursor cursor = await GetNodeFeatures(filter))
{
if (cursor == null)
{
return null;
}
return await cursor.NextFeature();
}
}
catch { return null; }
}
async public Task<IFeature> GetEdgeFeature(int eid)
{
RowIDFilter filter = new RowIDFilter(String.Empty);
filter.IDs.Add(eid);
filter.AddField("*");
IFeature feature = null;
using (IFeatureCursor cursor = await GetEdgeFeatures(filter))
{
feature = await cursor.NextFeature();
}
if (feature != null && feature.FindField("FCID") != null && feature.FindField("OID") != null &&
_edgeFcs.ContainsKey(Convert.ToInt32(feature["FCID"])))
{
IGraphEdge edge = _pageManager.GetEdge(eid);
try
{
if (edge != null && edge.FcId == -1) // Complex Edge
{
filter = new RowIDFilter("FDB_OID");
filter.IDs.Add(Convert.ToInt32(feature["OID"]));
filter.AddField("*");
IFeatureClass fc = _edgeFcs[Convert.ToInt32(feature["FCID"])];
using (IFeatureCursor c = await fc.GetFeatures(filter))
{
return await c.NextFeature();
}
}
}
catch { }
}
return feature;
}
async public Task<IFeature> GetNodeFeatureAttributes(int nodeId, string[] attributes)
{
try
{
QueryFilter filter = new QueryFilter();
filter.WhereClause = _fdb.DbColName("FDB_OID") + "=" + nodeId;
filter.AddField("FCID");
filter.AddField("OID");
IFeature feature;
using (IFeatureCursor cursor = await GetNodeFeatures(filter))
{
feature = await cursor.NextFeature();
}
if (feature == null)
{
return null;
}
string fcName = await _fdb.GetFeatureClassName(Convert.ToInt32(feature["FCID"]));
IDatasetElement element = await _dataset.Element(fcName);
if (element == null)
{
return null;
}
IFeatureClass fc = element.Class as IFeatureClass;
if (fc == null)
{
return null;
}
filter = new QueryFilter();
if (fc is IDatabaseNames)
{
filter.WhereClause = ((IDatabaseNames)fc).DbColName(fc.IDFieldName) + "=" + Convert.ToInt32(feature["OID"]);
}
else
{
filter.WhereClause = _fdb.DbColName(fc.IDFieldName) + "=" + Convert.ToInt32(feature["OID"]);
}
if (attributes == null)
{
filter.AddField("*");
}
else
{
foreach (string attribute in attributes)
{
if (attribute == "*")
{
filter.AddField(attribute);
}
else if (fc.FindField(attribute) != null)
{
filter.AddField(attribute);
}
}
}
using (IFeatureCursor cursor = await fc.GetFeatures(filter))
{
feature = await cursor.NextFeature();
}
if (feature != null)
{
feature.Fields.Add(new FieldValue("_classname", fc.Name));
}
return feature;
}
catch
{
return null;
}
}
async public Task<IFeature> GetEdgeFeatureAttributes(int edgeId, string[] attributes)
{
//RowIDFilter filter = new RowIDFilter(String.Empty);
//filter.IDs.Add(edgeId);
return await GetEdgeFeature(edgeId);
}
public int MaxNodeId
{
get
{
try
{
DbProviderFactory factory = System.Data.SQLite.SQLiteFactory.Instance;
using (DbConnection connection = factory.CreateConnection())
using (DbCommand command = factory.CreateCommand())
{
connection.ConnectionString = _fdb.ConnectionString;
command.CommandText = "SELECT MAX(" + _fdb.DbColName("FDB_OID") + ") FROM " + _fdb.TableName("FC_" + _nodeFc.Name);
command.Connection = connection;
connection.Open();
return Convert.ToInt32(command.ExecuteScalar());
}
}
catch { return -1; }
}
}
public GraphWeights GraphWeights
{
get { return _weights; }
}
public bool HasDisabledSwitches
{
get
{
try
{
DbProviderFactory factory = System.Data.SQLite.SQLiteFactory.Instance;
using (DbConnection connection = factory.CreateConnection())
using (DbCommand command = factory.CreateCommand())
{
connection.ConnectionString = _fdb.ConnectionString;
command.CommandText = "SELECT COUNT(" + _fdb.DbColName("FDB_OID") + ") FROM " + _fdb.TableName("FC_" + _nodeFc.Name) + " WHERE [switch]=1 AND [state]=0";
command.Connection = connection;
connection.Open();
return Convert.ToInt32(command.ExecuteScalar()) > 0;
}
}
catch
{
return false;
}
}
}
async public Task<IGraphEdge> GetGraphEdge(IPoint point, double tolerance)
{
if (point == null)
{
return null;
}
SpatialFilter filter = new SpatialFilter();
filter.Geometry = new Envelope(point.X - tolerance, point.Y - tolerance,
point.X + tolerance, point.Y + tolerance);
filter.AddField("FDB_SHAPE");
filter.AddField("FDB_OID");
using (IFeatureCursor cursor = await GetEdgeFeatures(filter))
{
IFeature feature, selected = null;
double selectedDist = double.MaxValue;
int selectedFcId = int.MinValue;
IPoint snappedPoint = null;
while ((feature = await cursor.NextFeature()) != null)
{
if (!(feature.Shape is IPolyline) ||
feature.FindField("NETWORK#FCID") == null)
{
continue;
}
int fcid = Convert.ToInt32(feature["NETWORK#FCID"]);
double dist, stat;
IPoint spoint = gView.Framework.SpatialAlgorithms.Algorithm.Point2PolylineDistance((IPolyline)feature.Shape, point, out dist, out stat);
if (spoint == null)
{
continue;
}
if (selected == null || dist <= selectedDist)
{
if (fcid != -1)
{
#region Do complex Edge exists
IFeatureClass complexEdgeFc = _edgeFcs[-1];
if (complexEdgeFc != null)
{
QueryFilter complexEdgeFilter = new QueryFilter();
complexEdgeFilter.WhereClause = "FCID=" + fcid + " AND OID=" + feature.OID;
complexEdgeFilter.AddField("FDB_OID");
using (IFeatureCursor complexEdgeCursor = await complexEdgeFc.GetFeatures(complexEdgeFilter))
{
if (await complexEdgeCursor.NextFeature() != null)
{
continue;
}
}
}
#endregion
}
selected = feature;
selectedDist = dist;
selectedFcId = fcid;
snappedPoint = spoint;
}
}
if (selected == null)
{
return null;
}
int eid = -1;
if (selectedFcId == -1)
{
#region Complex Edge
object eidObj = await _fdb._conn.QuerySingleField("SELECT eid FROM " + _fdb.TableName("FC_" + _name + "_ComplexEdges") + " WHERE " + _fdb.DbColName("FDB_OID") + "=" + selected.OID, "eid");
if (eidObj != null)
{
eid = Convert.ToInt32(eidObj);
}
#endregion
}
else
{
object eidObj = await _fdb._conn.QuerySingleField("SELECT eid FROM " + _fdb.TableName(_name + "_EdgeIndex") + " WHERE FCID=" + selectedFcId + " AND OID=" + selected.OID, "eid");
if (eidObj != null)
{
eid = Convert.ToInt32(eidObj);
}
}
if (eid != -1)
{
point.X = snappedPoint.X;
point.Y = snappedPoint.Y;
IGraphTableAdapter gt = this.GraphTableAdapter();
return gt.QueryEdge(eid);
}
return null;
}
}
async public Task<List<IFeatureClass>> NetworkClasses()
{
if (_fdb == null)
{
return new List<IFeatureClass>();
}
return await _fdb.NetworkFeatureClasses(this.Name);
}
async public Task<string> NetworkClassName(int fcid)
{
if (_fdb == null)
{
return String.Empty;
}
return await _fdb.GetFeatureClassName(fcid);
}
async public Task<int> NetworkClassId(string className)
{
if (_fdb == null || _dataset == null)
{
return -1;
}
return await _fdb.FeatureClassID(await _fdb.DatasetID(_dataset.DatasetName), className);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RestSharp
{
public static class ExecuteExtensions
{
public static Task<IRestResponse> ExecuteWithTaskAsync(this IRestClient client, IRestRequest request)
{
var cSource = new TaskCompletionSource<IRestResponse>();
client.ExecuteAsync(request, res => cSource.SetResult(res));
return cSource.Task;
}
}
}
|
using System.Windows;
namespace CODE.Framework.Wpf.TestBench
{
/// <summary>
/// Interaction logic for ColumnComboBox.xaml
/// </summary>
public partial class ColumnComboBox : Window
{
public ColumnComboBox()
{
InitializeComponent();
var model = new MyModel(25);
DataContext = model;
combo.ItemsSource = model.OtherModels;
}
}
}
|
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AppShell.ViewModels
{
public class PaneContentViewModel : BindableBase
{
public PaneContentViewModel()
{
}
}
}
|
using UnityEngine;
using System.Collections;
public class PlayerAimMarkData : MonoBehaviour
{
public bool IsRunToEndPoint;
public int RankNo;
bool IsPlayer;
bool IsGameOver;
bool IsActiveDingShen;
NetworkView viewNet;
public WaterwheelPlayerNetCtrl playerNetScript;
public WaterwheelAiPlayerNet AiNetScript;
bool IsActiveHuanWei;
bool IsActiveDianDao;
public GameObject DingShenWater;
public GameObject HuanWeiFuTeXiao;
void Start()
{
if (GlobalData.GetInstance().gameMode == GameMode.OnlineMode) {
viewNet = GetComponent<NetworkView>();
if (viewNet != null) {
viewNet.stateSynchronization = NetworkStateSynchronization.Off;
}
playerNetScript = GetComponent<WaterwheelPlayerNetCtrl>();
if (playerNetScript != null) {
DingShenWater = playerNetScript.GetWaterPlayerDt().DingShenWater;
HuanWeiFuTeXiao = playerNetScript.GetWaterPlayerDt().HuanWeiFuTeXiao;
}
AiNetScript = GetComponent<WaterwheelAiPlayerNet>();
if (AiNetScript != null) {
DingShenWater = AiNetScript.DingShenWater;
HuanWeiFuTeXiao = AiNetScript.HuanWeiFuTeXiao;
}
/*if (AiNetScript == null && playerNetScript == null) {
ScreenLog.LogError("*****************AiNetScript or playerNetScript is null, name -> "+gameObject.name);
}
ScreenLog.Log("test ************** name "+gameObject.name);*/
}
}
public void SetDingShenWater(GameObject obj)
{
if (obj == null) {
return;
}
DingShenWater = obj;
}
public void SetIsRunToEndPoint()
{
if (IsRunToEndPoint) {
return;
}
IsRunToEndPoint = true;
Invoke("DelaySetIsKinematic", 1f);
if (Network.peerType != NetworkPeerType.Disconnected) {
viewNet.RPC("SendPlayerSetIsRunToEndPoint", RPCMode.OthersBuffered);
}
}
[RPC]
void SendPlayerSetIsRunToEndPoint()
{
if (IsRunToEndPoint) {
return;
}
IsRunToEndPoint = true;
Invoke("DelaySetIsKinematic", 1f);
}
void DelaySetIsKinematic()
{
Rigidbody rigObj = GetComponent<Rigidbody>();
rigObj.isKinematic = true;
ChuanLunZiCtrl lunZiScript = GetComponentInChildren<ChuanLunZiCtrl>();
if (lunZiScript != null) {
lunZiScript.CloseLunZiAction();
}
}
public bool GetIsActiveDianDao()
{
return IsActiveDianDao;
}
void OpenDianDaoTeXiao()
{
if (playerNetScript != null && playerNetScript.GetIsHandlePlayer()) {
AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioFuMianBuff);
}
//DianDaoTeXiao ChuLi
IsActiveDianDao = true;
if (playerNetScript != null) {
playerNetScript.ShowDianDaoFuSprite();
}
CancelInvoke("CloseDianDaoState");
Invoke("CloseDianDaoState", 3f);
}
public void ActiveDianDaoState()
{
if (playerNetScript == null) {
return;
}
if (IsActiveDianDao) {
return;
}
OpenDianDaoTeXiao();
if (viewNet != null && Network.peerType != NetworkPeerType.Disconnected) {
viewNet.RPC("SendAimMarkActiveDianDao", RPCMode.OthersBuffered);
}
}
[RPC]
void SendAimMarkActiveDianDao()
{
if (playerNetScript == null) {
return;
}
OpenDianDaoTeXiao();
}
void CloseDianDaoState()
{
IsActiveDianDao = false;
if (playerNetScript != null) {
playerNetScript.HiddenDianDaoFuSprite();
}
}
public void OpenHuanWeiFuTeXiao()
{
ShowHuanWeiFuTeXiao();
if (Network.peerType != NetworkPeerType.Disconnected) {
viewNet.RPC("SendOpenPlayerHuanWeiFuTeXiao", RPCMode.OthersBuffered);
}
}
[RPC]
void SendOpenPlayerHuanWeiFuTeXiao()
{
ShowHuanWeiFuTeXiao();
}
void ShowHuanWeiFuTeXiao()
{
if (HuanWeiFuTeXiao == null) {
if (AiNetScript != null) {
HuanWeiFuTeXiao = AiNetScript.HuanWeiFuTeXiao;
}
if (HuanWeiFuTeXiao != null) {
HuanWeiFuTeXiao.SetActive(true);
}
else {
ScreenLog.LogError("*****************HuanWeiFuTeXiao is null, name -> "+gameObject.name);
}
}
else {
if (HuanWeiFuTeXiao.activeSelf) {
return;
}
HuanWeiFuTeXiao.SetActive(true);
}
DelayCloseHuanWeiFuTeXiao();
}
void DelayCloseHuanWeiFuTeXiao()
{
CancelInvoke("CloseHuanWeiFuTeXiao");
Invoke("CloseHuanWeiFuTeXiao", 3f);
}
void CloseHuanWeiFuTeXiao()
{
if (HuanWeiFuTeXiao == null) {
ScreenLog.LogError("*****************HuanWeiFuTeXiao is null, name -> "+gameObject.name);
}
else {
if (!HuanWeiFuTeXiao.activeSelf) {
return;
}
HuanWeiFuTeXiao.SetActive(false);
}
}
public void ActiveHuanWeiState(Vector3 playerPos, int countPath, int countMark)
{
if (playerNetScript == null && AiNetScript == null) {
return;
}
//OpenHuanWeiFuTeXiao();
bool isSendMsg = false;
if (playerNetScript != null && !playerNetScript.GetIsHandlePlayer()) {
isSendMsg = true;
}
else if (AiNetScript != null && !AiNetScript.GetIsHandlePlayer()) {
isSendMsg = true;
}
if (!isSendMsg) {
//Debug.Log(gameObject.name + " is actived huanWeiState...");
if (playerNetScript != null) {
AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioFuMianBuff);
}
else {
SetAiPlayerHuanWeiFuInfo(countPath, countMark);
}
transform.position = playerPos;
//HuanWeiTeXiao ChuLi
IsActiveHuanWei = true;
CancelInvoke("CloseHuanWeiState");
Invoke("CloseHuanWeiState", 3f);
}
else {
if (viewNet != null && Network.peerType != NetworkPeerType.Disconnected) {
viewNet.RPC("SendAimMarkActiveHuanWei", RPCMode.OthersBuffered, playerPos, countPath, countMark);
}
}
}
void SetAiPlayerHuanWeiFuInfo(int countPath, int countMark)
{
if (AiNetScript != null && AiNetScript.GetIsHandlePlayer()) {
AiNetScript.SetHuanWeiFuActiveInfo(countPath, countMark);
}
}
[RPC]
void SendAimMarkActiveHuanWei(Vector3 playerPos, int countPath, int countMark)
{
if (playerNetScript == null && AiNetScript == null) {
return;
}
bool isActive = false;
if (playerNetScript != null && playerNetScript.GetIsHandlePlayer()) {
isActive = true;
AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioFuMianBuff);
}
else if (AiNetScript != null && AiNetScript.GetIsHandlePlayer()) {
isActive = true;
SetAiPlayerHuanWeiFuInfo(countPath, countMark);
}
if (!isActive) {
return;
}
//Debug.Log(gameObject.name + " is actived huanWeiState...");
transform.position = playerPos;
//HuanWeiTeXiao ChuLi
IsActiveHuanWei = true;
CancelInvoke("CloseHuanWeiState");
Invoke("CloseHuanWeiState", 3f);
}
void CloseHuanWeiState()
{
if (!IsActiveHuanWei) {
return;
}
IsActiveHuanWei = false;
}
public bool GetIsActiveDingShen()
{
return IsActiveDingShen;
}
void OpenDingShenState()
{
//Debug.LogError("OpenDingShenState -> name " + gameObject.name);
if (playerNetScript != null && playerNetScript.GetIsHandlePlayer()) {
AudioListCtrl.PlayAudio(AudioListCtrl.GetInstance().AudioFuMianBuff);
}
if (AiNetScript != null && AiNetScript.GetIsHandlePlayer()) {
AiNetScript.SetIsRunMoveAiPlayer(false);
}
IsActiveDingShen = true;
if (DingShenWater == null) {
if (AiNetScript != null) {
DingShenWater = AiNetScript.DingShenWater;
if (DingShenWater != null) {
DingShenWater.SetActive(true);
}
}
if (DingShenWater == null) {
ScreenLog.LogError("*****************DingShenWater is null, name -> "+gameObject.name);
}
}
else {
DingShenWater.SetActive(true);
}
transform.position += new Vector3(0f, 3f, 0f);
CancelInvoke("CloseDingShenState");
Invoke("CloseDingShenState", 3f);
}
public void ActiveDingShenState()
{
if (playerNetScript == null && AiNetScript == null) {
return;
}
if (IsActiveDingShen) {
return;
}
OpenDingShenState();
if (viewNet != null && Network.peerType != NetworkPeerType.Disconnected) {
viewNet.RPC("SendAimMarkActiveDingShen", RPCMode.OthersBuffered);
}
}
[RPC]
void SendAimMarkActiveDingShen()
{
if (playerNetScript == null && AiNetScript == null) {
return;
}
if (IsActiveDingShen) {
return;
}
OpenDingShenState();
}
void CloseDingShenState()
{
//Debug.LogError("CloseDingShenState -> name " + gameObject.name);
if (AiNetScript != null && AiNetScript.GetIsHandlePlayer()) {
AiNetScript.SetIsRunMoveAiPlayer(true);
}
IsActiveDingShen = false;
if (DingShenWater == null) {
ScreenLog.LogError("*****************DingShenWater is null, name -> "+gameObject.name);
}
else {
DingShenWater.SetActive(false);
}
//transform.position -= new Vector3(0f, 3f, 0f);
}
public void SetIsPlayer()
{
IsPlayer = true;
}
public bool GetIsPlayer()
{
if (AiNetScript != null) {
IsPlayer = false;
}
else if (playerNetScript != null) {
IsPlayer = true;
}
return IsPlayer;
}
public bool CheckIsHandlePlayer()
{
bool isHandlePlayer = false;
if (playerNetScript != null) {
isHandlePlayer = playerNetScript.GetIsHandlePlayer();
}
return isHandlePlayer;
}
public void SetIsGameOver()
{
IsGameOver = true;
if (Network.peerType != NetworkPeerType.Disconnected) {
viewNet.RPC("SendPlayerSetIsGameOver", RPCMode.OthersBuffered);
}
}
[RPC]
void SendPlayerSetIsGameOver()
{
IsGameOver = true;
}
public bool GetIsGameOver()
{
return IsGameOver;
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace BeatmapDownloader.Database.Migrations
{
public partial class InitializeMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "DownloadedBeatmapSets",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
BeatmapId = table.Column<int>(nullable: false),
BeatmapSetId = table.Column<int>(nullable: false),
DownloadProviderId = table.Column<string>(nullable: true),
DownloadProviderName = table.Column<string>(nullable: true),
DownloadTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DownloadedBeatmapSets", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_DownloadedBeatmapSets_DownloadProviderId",
table: "DownloadedBeatmapSets",
column: "DownloadProviderId");
migrationBuilder.CreateIndex(
name: "IX_DownloadedBeatmapSets_DownloadProviderName",
table: "DownloadedBeatmapSets",
column: "DownloadProviderName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DownloadedBeatmapSets");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Week4.ZoekertjesApp.DataAccess;
using Week4.ZoekertjesApp.Models;
using ZoekertjesModels;
namespace Week4.ZoekertjesApp.Controllers
{
public class ZoekertjesAPIController : ApiController
{
public List<Zoekertje> Get()
{
List<Zoekertje> zoekertjes = Data.GetZoekertjes();
return zoekertjes;
}
public HttpResponseMessage Post(Zoekertje newZoekertje)
{
HttpResponseMessage response = new HttpResponseMessage();
//controleren of parameter in orde is
if (newZoekertje == null)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
try
{
Data.AddZoekertje(newZoekertje);
string url = string.Format("{0}{1}", HttpContext.Current.Request.Url.ToString(), newZoekertje.Id);
response.Headers.Location = new Uri(url);
response.StatusCode = HttpStatusCode.Created;
return response;
}
catch (Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
}
}
|
using UnityEngine;
using UnityEngine.Tilemaps;
public class TargetedSquareTilemapRenderer : MonoBehaviour {
[SerializeField]
private Tilemap _tilemap = null;
[SerializeField]
private TileBase _tileNormalPriority = null;
[SerializeField]
private TileBase _tileHighPriority = null;
public void clear() {
this._tilemap.ClearAllTiles();
}
public void setTile(int x, int y, TargetedSquare ts) {
TileBase tile;
if(ts == null) {
tile = null;
} else {
if(ts.isPriority) {
tile = this._tileHighPriority;
}
else {
tile = this._tileNormalPriority;
}
}
this._tilemap.SetTile(new Vector3Int(x, y, 0), tile);
}
}
|
using System;
namespace week06b
{
class MainClass
{
public static void Main (string[] args)
{
int add = Add (5, 6);
Console.WriteLine (add);
Console.WriteLine(readNumber ());
}
/*
* All functions have to have a return type, up until now we've used
* void which effectively means no return type.
* A return type specifies what a function should spit back out.
* In this first example it will return an integer which wil be the result of a sum
*/
public static int Add(int a, int b)
{
return a + b;
}
public static int readNumber()
{
int number = int.Parse(Console.ReadLine ());
return number;
}
public static int minus(int a, int b)
{
return a - b;
}
public static int minus(int a, int b)
{
return a * b;
}
public static int divide(int a, int b)
{
return a / b;
}
public static int remainder(int a, int b)
{
return a % b;
}
public static int average(int a, int b, int c, int d, int e)
{
return (a + b + c + d + e) / 5;
}
public static int returnHigher(int a, int b)
{
if (a > b) {
return a;
} else if (b > a) {
return b;
}
}
public static int returnHigher(int a, int b)
{
if (a < b) {
return a;
} else if (b < a) {
return b;
}
}
}
}
|
using System.Collections;
namespace Shipwreck.TypeScriptModels
{
internal interface IHasParentInternal : IHasParent
{
void SetParent(IOwnedCollection value);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.