text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
namespace Pes.Core
{
public partial class GameResult
{
public static GameResult GetGameResultByID(int id)
{
GameResult gameResult = (from g in All()
where g.GameResultID == id
select g).SingleOrDefault<GameResult>();
return gameResult;
}
public static void InsertGameResult(GameResult gameResult)
{
Add(gameResult);
}
public static void DeleteGameResult(GameResult gameResult)
{
Delete(gameResult.GameResultID);
}
public static void UpdateGameResult(GameResult gr)
{
Update(gr);
}
public static void InsertOrUpdateGameResult(int gameID, int UserID, int score)
{
GameResult rs = (from grs in All().ToList()
where grs.GameID == gameID &&
grs.AccountID== UserID
select grs).SingleOrDefault();
if (rs != null) // Update
{
if (rs.GameScores < score)
{
rs.GameScores = score;
UpdateGameResult(rs);
}
}
else // Insert
{
rs = new GameResult();
rs.GameScores = score;
rs.GameID = gameID;
rs.AccountID =UserID;
InsertGameResult(rs);
}
}
public static void InsertOrUpdateGameResult1(int gameID, int profileDI, int score)
{
GameResult rs = (from grs in All().ToList()
where grs.GameID == gameID &&
Profile.Single(p => p.AccountID == grs.AccountID).ProfileID== profileDI
select grs).SingleOrDefault();
if (rs != null) // Update
{
if (rs.GameScores < score)
{
rs.GameScores = score;
UpdateGameResult(rs);
}
}
else // Insert
{
rs = new GameResult();
rs.GameScores = score;
rs.GameID = gameID;
rs.AccountID = Profile.Single(profileDI).AccountID;
InsertGameResult(rs);
}
}
public static List<GameResult> Get(IQueryable<GameResult> table, int start, int end)
{
if (start <= 0)
start = 1;
List<GameResult> l = table.Skip(start - 1).Take(end - start + 1).ToList<GameResult>();
return l;
}
public static List<GameResult> GetRandomTopGameResult(int num)
{
List<Game> lstGames = Game.GetRandomXGame(num);
List<GameResult> lstGameResults = new List<GameResult>();
foreach (Game game in lstGames)
lstGameResults.Add(All().Where
(result => result.GameID == game.GameID).OrderByDescending(result => result.GameScores).Take(1).SingleOrDefault());
return lstGameResults;
}
}
} |
using Entities.Entities.Enums;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.Entities
{
public class ApplicationUser : IdentityUser
{
[Column("USR_CPF")]
[MaxLength(50)]
[Display(Name ="CPF")]
public string CPF { get; set; }
[Column("USR_IDADE")]
[Display(Name ="Idade")]
public int Idade { get; set; }
[Column("USR_NOME")]
[MaxLength(255)]
[Display(Name ="Nome")]
public string Nome { get; set; }
[Column("USR_CEP")]
[MaxLength(15)]
[Display(Name = "CEP")]
public string CEP { get; set; }
[Column("USR_ENDERECO")]
[MaxLength(255)]
[Display(Name = "Endereço")]
public string Endereço { get; set; }
[Column("URS_COMPLEMENTO_ENDERECO")]
[MaxLength(450)]
[Display(Name = "Complemento de Endereço")]
public string ComplementoEndereco { get; set; }
[Column("USR_CELULAR")]
[MaxLength(20)]
[Display(Name = "Celular")]
public string Celular { get; set; }
[Column("USR_TELEFONE")]
[MaxLength(20)]
[Display(Name = "Telefone")]
public string Telefone { get; set; }
[Column("USR_ESTADO")]
[Display(Name ="Estado")]
public bool Estado { get; set; }
[Column("USR_TIPO")]
[Display(Name = "Tipo")]
public TipoUsuario? Tipo { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BUS;
using DAL;
using DevExpress.XtraGrid.Views.Grid;
using ControlLocalizer;
namespace GUI
{
public partial class f_ketchuyentk : DevExpress.XtraBars.Ribbon.RibbonForm
{
KetNoiDBDataContext db = new KetNoiDBDataContext();
t_cttk tk = new t_cttk();
void load()
{
var lst = (from a in db.ct_tks
where (a.tk_no.StartsWith("5") || a.tk_no.StartsWith("6") || a.tk_no.StartsWith("7") || a.tk_no.StartsWith("8")
|| a.tk_co.StartsWith("5") || a.tk_co.StartsWith("6") || a.tk_co.StartsWith("7") || a.tk_co.StartsWith("8")
)
&& (a.kc != "Yes" || a.kc == null)
select new data_tk()
{
id = a.id,
iddv = a.iddv,
loaichungtu = a.loaichungtu,
machungtu = a.machungtu,
ngaychungtu = a.ngaychungtu,
ngaylchungtu = a.ngaylchungtu,
sochungtu = a.sochungtu,
diengiai = a.diengiai,
tk_no = a.tk_no,
tk_co = a.tk_co,
PS = a.PS,
tiente = a.tiente,
tygia = a.tygia,
PS_nt = a.PS_nt,
//a.idsp,
//a.id2,
idnv = a.idnv,
loai = a.loai,
idcv = a.idcv,
idmuccp = a.idmuccp,
//a.ghichu,
//a.tendt,
kc = a.kc
}).ToList();
gridControl1.DataSource = lst;
}
public f_ketchuyentk()
{
InitializeComponent();
load();
}
// phân quyền
//protected override void OnActivated(EventArgs e)
//{
// base.OnActivated(e);
// var q = Biencucbo.QuyenDangChon;
// if (q == null) return;
// btnthem.Enabled = (bool)q.Them;
// btnsua.Enabled = (bool)q.Sua;
// btnxoa.Enabled = (bool)q.Xoa;
//}
private void gridView1_DoubleClick(object sender, EventArgs e)
{
Biencucbo.hddmtk = 1;
Biencucbo.ma = gridView1.GetFocusedRowCellValue("id").ToString();
}
private void btnthem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void btnsua_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void btnxoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
if (!gridView1.IsGroupRow(e.RowHandle)) //Nếu không phải là Group
{
if (e.Info.IsRowIndicator) //Nếu là dòng Indicator
{
if (e.RowHandle < 0)
{
e.Info.ImageIndex = 0;
e.Info.DisplayText = string.Empty;
}
else
{
e.Info.ImageIndex = -1; //Không hiển thị hình
e.Info.DisplayText = (e.RowHandle + 1).ToString(); //Số thứ tự tăng dần
}
SizeF _Size = e.Graphics.MeasureString(e.Info.DisplayText, e.Appearance.Font); //Lấy kích thước của vùng hiển thị Text
Int32 _Width = Convert.ToInt32(_Size.Width) + 20;
BeginInvoke(new MethodInvoker(delegate { cal(_Width, gridView1); })); //Tăng kích thước nếu Text vượt quá
}
}
else
{
e.Info.ImageIndex = -1;
e.Info.DisplayText = string.Format("[{0}]", (e.RowHandle * -1)); //Nhân -1 để đánh lại số thứ tự tăng dần
SizeF _Size = e.Graphics.MeasureString(e.Info.DisplayText, e.Appearance.Font);
Int32 _Width = Convert.ToInt32(_Size.Width) + 20;
BeginInvoke(new MethodInvoker(delegate { cal(_Width, gridView1); }));
}
}
bool cal(Int32 _Width, GridView _View)
{
_View.IndicatorWidth = _View.IndicatorWidth < _Width ? _Width : _View.IndicatorWidth;
return true;
}
private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
}
private void f_dmtk_Load(object sender, EventArgs e)
{
LanguageHelper.Translate(this);
LanguageHelper.Translate(barManager1);
this.Text = LanguageHelper.TranslateMsgString("." + Name + "_title", "Kết Chuyển Tài Khoản").ToString();
changeFont.Translate(this);
changeFont.Translate(barManager1);
}
private void btnKetChuyen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
var lst = (from a in db.ct_tks
where (a.tk_no.StartsWith("5") || a.tk_no.StartsWith("6") || a.tk_no.StartsWith("7") || a.tk_no.StartsWith("8")
|| a.tk_co.StartsWith("5") || a.tk_co.StartsWith("6") || a.tk_co.StartsWith("7") || a.tk_co.StartsWith("8")
)
&& (a.kc != "Yes" || a.kc == null)
select new data_tk()
{
id = a.id,
iddv = a.iddv,
loaichungtu = a.loaichungtu,
machungtu = a.machungtu,
ngaychungtu = a.ngaychungtu,
ngaylchungtu = a.ngaylchungtu,
sochungtu = a.sochungtu,
diengiai = a.diengiai,
tk_no = a.tk_no,
tk_co = a.tk_co,
PS = a.PS,
tiente = a.tiente,
tygia = a.tygia,
PS_nt = a.PS_nt,
//a.idsp,
//a.id2,
idnv = a.idnv,
loai = a.loai,
idcv = a.idcv,
idmuccp = a.idmuccp,
//a.ghichu,
//a.tendt,
kc = a.kc
}).ToList();
for (int i = 0; i < lst.Count(); i++)
{
var row1 = lst.ElementAt(i) as data_tk;
if (row1.tk_no.Substring(0, 1) == "5" || row1.tk_no.Substring(0, 1) == "6" || row1.tk_no.Substring(0, 1) == "7" || row1.tk_no.Substring(0, 1) == "8")
{
tk.moi(row1.id + "no", row1.iddv, "KC", row1.machungtu, row1.ngaychungtu.Value, DateTime.Now, -1, "", "", row1.tk_no + "->> 911", "911", row1.tk_no, row1.PS.Value, row1.tiente, row1.tygia.Value, row1.PS_nt.Value, "", "", row1.idnv, "", row1
.idcv, row1.idmuccp, "", "",0.0);
tk.sua(row1.id, "Yes");
tk.sua(row1.id + "no", "Yes");
}
if (row1.tk_co.Substring(0, 1) == "5" || row1.tk_co.Substring(0, 1) == "6" || row1.tk_co.Substring(0, 1) == "7" || row1.tk_co.Substring(0, 1) == "8")
{
tk.moi(row1.id + "co", row1.iddv, "KC", row1.machungtu, row1.ngaychungtu.Value, DateTime.Now, -1, "", "", row1.tk_co + "->> 911", row1.tk_co, "911", row1.PS.Value, row1.tiente, row1.tygia.Value, row1.PS_nt.Value, "", "", row1.idnv, "", row1
.idcv, row1.idmuccp, "", "",0.0);
tk.sua(row1.id, "Yes");
tk.sua(row1.id + "co", "Yes");
}
}
load();
}
private void btnds_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
var lst = (from a in db.ct_tks
where (a.tk_no.StartsWith("5") || a.tk_no.StartsWith("6") || a.tk_no.StartsWith("7") || a.tk_no.StartsWith("8")
|| a.tk_co.StartsWith("5") || a.tk_co.StartsWith("6") || a.tk_co.StartsWith("7") || a.tk_co.StartsWith("8")
)
&& a.kc == "Yes" && a.loaichungtu == "KC"
select a).ToList();
gridControl1.DataSource = lst;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UserSessionsControllerTest.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using CGI.Reflex.Core.Tests;
using CGI.Reflex.Web.Controllers;
using CGI.Reflex.Web.Models.UserSessions;
using FluentAssertions;
using NUnit.Framework;
namespace CGI.Reflex.Web.Tests.Controllers
{
public class UserSessionsControllerTest : BaseControllerTest<UserSessionsController>
{
[Test]
public void Login_should_return_view()
{
var returnUrl = Rand.Url(local: true);
var result = Controller.Login(returnUrl);
result.Should().BeDefaultView();
result.Model<Login>().ReturnUrl.Should().Be(returnUrl);
}
[Test]
public void Boarding_should_return_view_when_token_valid()
{
var userAuth = new UserAuthentication { User = Factories.User.Save() };
NHSession.Save(userAuth);
var sat = userAuth.GenerateSingleAccessToken(TimeSpan.FromDays(2));
NHSession.Flush();
var result = Controller.Boarding(sat);
result.Should().BeDefaultView();
result.Model<Boarding>().SingleAccessToken.Should().Be(sat);
result.Model<Boarding>().UserName.Should().Be(userAuth.User.UserName);
}
[Test]
public void Boarding_should_return_notfound_when_token_doesnt_exist()
{
Controller.Boarding(Rand.String()).Should().BeHttpNotFound();
}
[Test]
public void Boarding_should_return_perished_when_token_is_perished_or_user_locked_out()
{
var userAuth = new UserAuthentication { User = Factories.User.Save() };
NHSession.Save(userAuth);
var sat = userAuth.GenerateSingleAccessToken(Rand.DateTime(future: false));
NHSession.Flush();
Controller.Boarding(sat).Should().BeView("BoardingPerished");
userAuth.User.IsLockedOut = true;
sat = userAuth.GenerateSingleAccessToken(TimeSpan.FromDays(2));
Controller.Boarding(sat).Should().BeView("BoardingPerished");
}
[Test]
public void ResetPassword_should_return_view()
{
var result = Controller.ResetPassword();
result.Should().BeDefaultView();
}
}
}
|
using FacultyV3.Core.Interfaces;
using FacultyV3.Core.Utilities;
using System;
namespace FacultyV3.Core.Models.Entities
{
public class Student : IBaseEntity
{
public Student()
{
Id = GuidComb.GenerateComb();
}
public Guid Id { get; set; }
public string FullName { get; set; }
public string Url_Image { get; set; }
public string Content { get; set; }
public string Course { get; set; }
public string Major { get; set; }
public string Graduation_Year { get; set; }
public string Current_Job { get; set; }
public string Work_Place { get; set; }
public int Serial { get; set; }
public DateTime Create_At { get; set; }
public DateTime Update_At { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace WinForms3DModelViewer
{
internal static class PointsCrossing
{
public static bool ArePointsCrossing(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
{
return ArePointsCrossing(p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p4.X, p4.Y);
}
public static bool ArePointsCrossing(Vector3 p1, Vector3 p2, Vector2 p3, Vector2 p4)
{
return ArePointsCrossing(p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p4.X, p4.Y);
}
public static bool ArePointsCrossing(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4)//проверка пересечения
{
return ArePointsCrossing(p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y, p4.X, p4.Y);
}
public static bool ArePointsCrossing(float p1X, float p1Y, float p2X, float p2Y, float p3X, float p3Y,
float p4X, float p4Y)
{
float v1 = VectorMultiplication(p4X - p3X, p4Y - p3Y, p1X - p3X, p1Y - p3Y);
float v2 = VectorMultiplication(p4X - p3X, p4Y - p3Y, p2X - p3X, p2Y - p3Y);
float v3 = VectorMultiplication(p2X - p1X, p2Y - p1Y, p3X - p1X, p3Y - p1Y);
float v4 = VectorMultiplication(p2X - p1X, p2Y - p1Y, p4X - p1X, p4Y - p1Y);
if ((v1 * v2) < 0 && (v3 * v4) < 0)
return true;
return false;
}
public static Vector2 CrossingPoint(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
{
float a1, b1, c1, a2, b2, c2;
(a1, b1, c1) = LineEquation(p1, p2);
(a2, b2, c2) = LineEquation(p3, p4);
return CrossingPoint(a1, b1, c1, a2, b2, c2);
}
public static Vector2 CrossingPoint(Vector3 p1, Vector3 p2, Vector2 p3, Vector2 p4)
{
float a1, b1, c1, a2, b2, c2;
(a1, b1, c1) = LineEquation(p1, p2);
(a2, b2, c2) = LineEquation(p3, p4);
return CrossingPoint(a1, b1, c1, a2, b2, c2);
}
public static Vector2 CrossingPoint(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4)
{
float a1, b1, c1, a2, b2, c2;
(a1, b1, c1) = LineEquation(p1, p2);
(a2, b2, c2) = LineEquation(p3, p4);
return CrossingPoint(a1, b1, c1, a2, b2, c2);
}
//поиск точки пересечения
public static Vector2 CrossingPoint(float a1, float b1, float c1, float a2, float b2, float c2)
{
Vector2 pt = new Vector2();
float d = a1 * b2 - b1 * a2;
float dx = -c1 * b2 + b1 * c2;
float dy = -a1 * c2 + c1 * a2;
pt.X = dx / d;
pt.Y = dy / d;
return pt;
}
//построение уравнения прямой
public static (float A, float B, float C) LineEquation(Vector3 p1, Vector3 p2)
{
return LineEquation(p1.X, p1.Y, p2.X, p2.Y);
}
//построение уравнения прямой
public static (float A, float B, float C) LineEquation(Vector2 p1, Vector2 p2)
{
return LineEquation(p1.X, p1.Y, p2.X, p2.Y);
}
//построение уравнения прямой
public static (float A, float B, float C) LineEquation(float p1X, float p1Y, float p2X, float p2Y)
{
var A = p2Y - p1Y;
var B = p1X - p2X;
var C = -p1X * (p2Y - p1Y) + p1Y * (p2X - p1X);
return (A, B, C);
}
private static float VectorMultiplication(float ax, float ay, float bx, float by) //векторное произведение
{
return ax * by - bx * ay;
}
}
}
|
using System;
using System.IO;
namespace SWT_20_ATM
{
public class FileLogger : ILogger
{
public StringWriter Writer { get; set; }
public bool UnderTest { get; set; }
public FileLogger( string filePath = "./SepLog.txt", StringWriter writer = null, bool underTest = false )
{
_filePath = filePath;
UnderTest = underTest;
if ( writer == null )
Writer = new StringWriter();
}
public bool AddToLog( string message )
{
var output = string.Format( "{0:YYY:HH:mm:ss}: {1}", DateTime.Now, message );
if ( UnderTest )
{
Stream ourStream = File.Open( _filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite );
Writer.WriteLine( output, ourStream );
}
else
{
String myString = "";
Writer.WriteLine( output, myString );
}
Writer.Flush();
//Console.WriteLine("Logged seperation event to file: {0}", DateTime.Now);
return true;
}
private string _filePath;
public string FilePath => _filePath;
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ImmedisHCM.Web.Models
{
public class CreateCompanyViewModel
{
[Required]
[Display(Name = "Company")]
public string Name { get; set; }
[Required]
[Display(Name = "Legal Name")]
public string LegalName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
namespace Idenz.Core.Data
{
public class Database
{
public Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase GetDatabase()
{
return EnterpriseLibraryContainer.Current.GetInstance<Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase>("TSquare");
}
}
}
|
using KPI.Model.DAO;
using KPI.Model.EF;
using KPI.Model.helpers;
using KPI.Web.helpers;
using KPI.Model.ViewModel;
using KPI.Web.Common;
using KPI.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using KPI.Web.Extension;
namespace KPI.Web.Controllers
{
public class LoginController : Controller
{
// GET: Login
//public ActionResult Index()
//{
// //var model= new LevelDAO().GetNode(97);
// return View();
//}
[AllowAnonymous]
public ActionResult Index(string returnUrl)
{
returnUrl = Request.UrlReferrer.ToSafetyString();
ViewBag.ReturnUrl = returnUrl;
return View();
}
private ActionResult RedirectToLocal(string returnUrl)
{
string[] routers = new[] { "Workplace", "CategoryKPILevel", "Favourite","ChartPeriod" };
var userprofile = Session["UserProfile"] as UserProfileVM;
//kiem tra neu la admin thi chuyen den router khac
if (!returnUrl.IsNullOrEmpty())
{
bool flag = false;
foreach (var item in routers)
{
//Khong nam trong router cua user flag = true
var check = returnUrl.ToLower().IndexOf(item.ToLower());
if (check != -1)
flag = true;
}
//Neu la admin va k router khong nam trong router cua user, Redirect home/index
//Neu KHONG la admin ,Redirect home/index
if (userprofile?.User.Permission == 1 && flag)
return RedirectToAction("Index", "Home");
else if (userprofile?.User.Permission != 1)
{
if (flag)
{
Uri myUri = new Uri(Request.UrlReferrer.ToSafetyString());
string returnUrl2 = HttpUtility.ParseQueryString(myUri.Query).Get("returnUrl");
return Redirect(returnUrl2);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
Uri myUri = new Uri(Request.UrlReferrer.ToSafetyString());
string returnUrl2 = HttpUtility.ParseQueryString(myUri.Query).Get("returnUrl");
return Redirect(returnUrl2);
}
}
else
{
if(Request.UrlReferrer != null)
{
Uri myUri = new Uri(Request.UrlReferrer.ToSafetyString());
string returnUrl2 = HttpUtility.ParseQueryString(myUri.Query).Get("returnUrl");
if(Request.FilePath == "/Login" && returnUrl2.IsNullOrEmpty())
{
return RedirectToAction("Index", "Home");
}
else
{
return Redirect(returnUrl2);
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(UserProfile objUser, string returnUrl)
{
if (ModelState.IsValid)
{
if(await new UserLoginDAO().CheckExistsUser(objUser.Username, objUser.Password))
{
var obj = await new UserLoginDAO().GetUserProfile(objUser.Username, objUser.Password);
if (obj != null)
{
Session["UserProfile"] = obj as UserProfileVM;
Session.Timeout = 525600;
return RedirectToLocal(returnUrl);
}
else
{
return RedirectToAction("Index", "Login");
}
}
ViewBag.Error = "Username or Pasword is wrong!";
ViewBag.Status = false;
// this.Response.Redirect(Server.UrlEncode(Request.QueryString["returnUrl"].ToString()));
return View(objUser);
}
ViewBag.ReturnUrl = returnUrl;
return View(objUser);
}
public ActionResult Logout()
{
Session.Abandon();
return Redirect("/");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AnimalDB
{
public partial class GyvunaiEdit : System.Web.UI.Page
{
public string conString = @"Data Source=localhost;port=3306;Initial catalog=animal; User Id= root; password=''";
public List<Lytis> lytysList = new List<Lytis>();
public List<Savininkas> savininkaiList = new List<Savininkas>();
public List<Isvaizda> isvaizdaList = new List<Isvaizda>();
public List<Mikro> mikrosList = new List<Mikro>();
public List<Registracija> regList = new List<Registracija>();
public List<Sveikata> sveikList = new List<Sveikata>();
public List<Veisle> veislList = new List<Veisle>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Gyvunas> bandymas = (List<Gyvunas>)Session["ArrayGyvunai"];
int edit = (int)Session["editId"];
TextBox1.Text = bandymas[edit].vardas;
TextBox2.Text = bandymas[edit].gimimo_data.ToShortDateString();
Kontekstas test = new Kontekstas(conString);
#region lytys
lytysList = test.GetLytis();
Dictionary<int, string> lytys = new Dictionary<int, string>();
foreach (Lytis lytis in lytysList)
{
lytys.Add(lytis.id, lytis.name);
}
DropDownList1.DataSource = lytys;
DropDownList1.DataTextField = "Value";
DropDownList1.DataValueField = "Key";
DropDownList1.DataBind();
DropDownList1.SelectedValue = bandymas[edit].lytis_id.ToString();
#endregion
#region savininkai
savininkaiList = test.GetSavininkas();
List<long> savId = new List<long>();
foreach (Savininkas sav in savininkaiList)
{
savId.Add(sav.id);
}
DropDownList2.DataSource = savId;
DropDownList2.DataBind();
DropDownList2.SelectedValue = bandymas[edit].savininko_kodas.ToString();
#endregion
#region isvaizda
isvaizdaList = test.GetIsvaizda();
List<int> isvId = new List<int>();
foreach (Isvaizda isv in isvaizdaList)
{
isvId.Add(isv.id);
}
DropDownList3.DataSource = isvId;
DropDownList3.DataBind();
DropDownList3.SelectedValue = bandymas[edit].fk_Isvaizda_id.ToString();
#endregion
#region mikroschema
mikrosList = test.GetMikro();
List<int> mikroList = new List<int>();
foreach (Mikro mik in mikrosList)
{
mikroList.Add(mik.numeris);
}
DropDownList6.DataSource = mikroList;
DropDownList6.DataBind();
DropDownList6.SelectedValue = bandymas[edit].fk_micro_id.ToString();
#endregion
#region registracija
regList = test.GetRegistracija();
List<int> registNr = new List<int>();
foreach (Registracija reg in regList)
{
registNr.Add(reg.numeris);
}
DropDownList7.DataSource = registNr;
DropDownList7.DataBind();
DropDownList7.SelectedValue = bandymas[edit].fk_reg_id.ToString();
#endregion
#region sveikata
sveikList = test.GetSveikata();
List<DateTime> datuList = new List<DateTime>();
foreach (Sveikata sveik in sveikList)
{
datuList.Add(sveik.Vizito_data.Date);
}
DropDownList5.DataSource = datuList;
DropDownList5.DataBind();
DropDownList5.SelectedValue = bandymas[edit].fk_vet_viz.ToShortDateString();
#endregion
#region veisle
veislList = test.GetVeisle();
List<string> veisles = new List<string>();
foreach (Veisle veis in veislList)
{
veisles.Add(veis.pavadinimas);
}
DropDownList4.DataSource = veisles;
DropDownList4.DataBind();
DropDownList4.SelectedValue = bandymas[edit].fk_veisle;
#endregion
}
}
protected void Main_Click1(object sender, EventArgs e)
{
Server.Transfer("HomePage.aspx");
}
protected void Klasės_Click1(object sender, EventArgs e)
{
Server.Transfer("KlaseList.aspx");
}
protected void Gyvunai_Click(object sender, EventArgs e)
{
Server.Transfer("GyvunaiList.aspx");
}
protected void Savininkai_Click(object sender, EventArgs e)
{
Server.Transfer("SavininkaiList.aspx");
}
protected void Veisle_Click(object sender, EventArgs e)
{
Server.Transfer("VeisleList.aspx");
}
protected void Registracijos_Click(object sender, EventArgs e)
{
Server.Transfer("RegistracijosList.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
Kontekstas test = new Kontekstas(conString);
test.EditGyvunas(TextBox1.Text, DateTime.Parse(TextBox2.Text), int.Parse(DropDownList1.SelectedValue), long.Parse(DropDownList2.SelectedValue), int.Parse(DropDownList3.SelectedValue),
DropDownList4.SelectedValue, DateTime.Parse(DropDownList5.SelectedValue), int.Parse(DropDownList6.Text), int.Parse(DropDownList7.SelectedValue));
Server.Transfer("GyvunaiList.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Server.Transfer("Ataskaitos.aspx");
}
}
} |
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 GameDoMin
{
public partial class EnterInformation : Form
{
public EnterInformation()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
SqlConnection connect = new SqlConnection(@"Data Source=DESKTOP-V4QPNQU\SQLEXPRESS;Initial Catalog=QuanLiDiem;Integrated Security=True");
connect.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text;
cmd.CommandText = System.String.Concat("insert into Diem values("+ "'"+ txtCode.Text.ToString() +"','" +txtName.Text.ToString() +"','"+ txtTime.Text.ToString() + "')");
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Thêm thành công");
}catch(SqlException){
MessageBox.Show("Không thêm được");
}
}
public string getTextBoxTime { get { return txtTime.Text; } }
public string setTextBoxTime { set { txtTime.Text = value; } }
private void EnterInformation_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _07._Truck_Tour
{
class TruckTour
{
static void Main(string[] args)
{
int numberPetrolPumps = int.Parse(Console.ReadLine());
Queue<int[]> pumps = new Queue<int[]>();
for (int i = 0; i < numberPetrolPumps; i++)
{
int[] dataForPump = Console.ReadLine().Split().Select(int.Parse).ToArray();
pumps.Enqueue(dataForPump);
}
int index = 0;
while (true)
{
int totalfuel = 0;
foreach (var pump in pumps)
{
int fuel = pump[0];
int distance = pump[1];
totalfuel += fuel - distance;
if (totalfuel < 0)
{
int[] currentPump = pumps.Dequeue();
pumps.Enqueue(currentPump);
index++;
break;
}
}
if (totalfuel >= 0)
{
break;
}
}
Console.WriteLine(index);
}
}
}
|
using UnityEngine;
using System.Collections;
public class DepthSorting : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void LateUpdate () {
foreach (Transform child in transform) {
OffsetPositionObject oPO = child.GetComponent<OffsetPositionObject>();
Vector3 pos = (oPO == null) ? child.position : child.TransformPoint (oPO.getOffsetPosition());
pos = new Vector3(child.position.x, child.position.y, pos.y * 0.25f);
child.position = pos;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float Speed = 0f;
private float movex = 0f;
private float movey = 0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate() {
move ();
turn ();
}
void move () {
movex = Input.GetAxis ("Horizontal");
movey = Input.GetAxis ("Vertical");
rigidbody2D.velocity = new Vector2 (movex * Speed, movey * Speed);
}
void turn () {
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos);
lookPos = lookPos - transform.position;
float angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace SampleApp.Samples
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NavigatingEvent : ContentPage
{
public NavigatingEventViewModel ViewModel = new NavigatingEventViewModel();
public NavigatingEvent()
{
BindingContext = ViewModel;
InitializeComponent();
}
public class NavigatingEventViewModel : INotifyPropertyChanged
{
string _uri = "https://www.google.co.uk";
public string Uri
{
get => _uri;
set
{
_uri = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Uri)));
}
}
Command _reloadCommand;
public Command ReloadCommand
{
get => _reloadCommand;
set
{
_reloadCommand = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ReloadCommand)));
}
}
public NavigatingEventViewModel()
{
ReloadCommand = new Command(() =>
{
if (Uri.Equals("https://www.google.co.uk"))
Uri = "https://www.xamarin.com";
else
Uri = "https://www.google.co.uk";
});
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
} |
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 sales_management_system
{
public partial class 商品詳細 : Form
{
public 商品詳細(string productName,
string publisherName,
string author,
DateTime publicationDate,
string genre,
string catagory,
string productCode,
int stock,
int price,
int genka,
bool isActive)
{
InitializeComponent();
txt_product_name.Text = productName;
txt_publisher_name.Text = publisherName;
txt_author_name.Text = author;
txt_publication_date.Text = publicationDate.ToString("yyyy/MM/dd");
txt_genre.Text = genre;
txt_category.Text = catagory;
txt_product_code.Text = productCode;
txt_stock.Text = stock.ToString();
txt_price.Text = price.ToString();
txt_genka.Text = genka.ToString();
if (isActive)
{
rdo_active.Checked = true;
}
else
{
rdo_no_active.Checked = true;
}
}
private void btn_back_code_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
namespace SchoolSystem.Common
{
using System;
using System.Text.RegularExpressions;
public class Validator
{
public static void ValidateIsStringNullOrWhiteSpace(string value, string objectName)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(objectName + "[ " + value + " ] " + ExceptionMessages.StringNullEmptyWhiteSpace);
}
}
public static void ValidateNameLength(string value, string objectName)
{
if (value.Length < GlobalConstants.NameMinLength || value.Length > GlobalConstants.NameMaxLength)
{
throw new ArgumentOutOfRangeException(objectName + "[ " + value + " ] " + ExceptionMessages.StringLength);
}
}
public static void ValidateNameCharacters(string value, string objectName)
{
string pattern = @"[^a-z^A-Z]+";
var regEx = new Regex(pattern);
var isNotValid = regEx.IsMatch(value);
if (isNotValid)
{
throw new ArgumentException(objectName + "[ " + value + " ] " + ExceptionMessages.LatinAlphabet);
}
}
public static void ValidateStidentMarksCount(int value)
{
if (value > GlobalConstants.StudentMarksMaxCount)
{
throw new ArgumentOutOfRangeException(ExceptionMessages.StidentMarksCountOutOfRange);
}
}
public static void ValidateGradeValue(int value)
{
if (value < GlobalConstants.GradeMinValue || value > GlobalConstants.GradeMaxValue)
{
throw new ArgumentOutOfRangeException(ExceptionMessages.GradeValueOutOfRange);
}
}
public static void ValidateMarkValue(float value)
{
if (value < GlobalConstants.MarksMinValue || value > GlobalConstants.MarksMaxValue)
{
throw new ArgumentOutOfRangeException(ExceptionMessages.MarkValueOutOfRange);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PleaseThem.Models
{
public class Resources
{
public int Food { get; set; }
public int Wood { get; set; }
public int Stone { get; set; }
public int Gold { get; set; }
/// <summary>
/// Get the sum of all resources
/// </summary>
public int GetTotal()
{
return Food +
Wood +
Stone +
Gold;
}
public void Reset()
{
Food = 0;
Wood = 0;
Stone = 0;
Gold = 0;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
//[CustomEditor(typeof(PathCreator))]
public class ButtonScript
{ }
|
using FindSelf.Domain.SeedWork;
using System;
namespace FindSelf.Domain.Entities.UserAggregate
{
public class SiteMessage : Entity
{
public int Id { get; }
public string Content { get; }
public DateTimeOffset SendTimesteamp { get; }
public Guid SnederId { get; }
public Guid ReceiverId { get; }
protected SiteMessage()
{
}
public SiteMessage(string content, Guid sneder, Guid receiver)
{
Content = content ?? throw new ArgumentNullException(nameof(content));
SnederId = sneder;
ReceiverId = receiver;
SendTimesteamp = DateTimeOffset.Now;
}
}
} |
using System;
namespace les2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
bool skyIsBlue = false;
skyIsBlue = ReverseBoolean(skyIsBlue);
Console.WriteLine(skyIsBlue);
Divide(4, 0);
}
static int Add(int i1, int i2)
{
int result = i1 + i2;
return result;
}
static bool ReverseBoolean(bool b1)
{
if(b1 == true)
{
b1 = false;
}
else
{
b1 = true;
}
return b1;
}
static void Divide(float a1, float a2)
{
float result = a1 / a2;
Console.WriteLine("Result = " + result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DAL;
using BUS;
namespace GUI.foodcourt
{
public partial class f_dspxuatvean : frm.frmmop
{
c_pxuatvean px = new c_pxuatvean();
t_history hs = new t_history();
public f_dspxuatvean()
{
InitializeComponent();
}
protected override void search()
{
gd.DataSource = new KetNoiDBDataContext().LayDsVeAn(Biencucbo.donvi,tungay.DateTime,denngay.DateTime,false);
}
protected override void searchall()
{
gd.DataSource = new KetNoiDBDataContext().LayDsVeAn(Biencucbo.donvi, tungay.DateTime, denngay.DateTime, true);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameCenter
{
abstract class Registracija
{
public Registracija(TipRegistracije tip)
{
Tip = tip;
}
public enum TipRegistracije { Bezreg, Mjesecna, Godisnja, AllTime }
public TipRegistracije Tip { get; set; }
public abstract decimal DajPopust();
}
}
|
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisDemo
{
public class RedisHelper
{
private static string _conn = "127.0.0.1:6379";
public static double StringIncrement(string key, double number)
{
try
{
using (var client = ConnectionMultiplexer.Connect(_conn))
{
return client.GetDatabase().StringIncrement(key, number);
}
}
catch (Exception)
{
return 0;
}
}
public static string StringGet(string key)
{
try
{
using (var client = ConnectionMultiplexer.Connect(_conn))
{
return client.GetDatabase().StringGet(key);
}
}
catch (Exception)
{
return string.Empty;
}
}
public static void StringSet(string key, string value)
{
try
{
using (var client = ConnectionMultiplexer.Connect(_conn))
{
client.GetDatabase().StringSet(key, value);
}
}
catch (Exception)
{
}
}
}
} |
using System;
namespace _08_Orange_Tree
{
public class OrangeTree
{
private int v1;
private int v2;
public OrangeTree(int v1, int v2)
{
this.Age = v1;
this.Height = v2;
}
public int Age { get; internal set; }
private string height;
public int Height { get; internal set; }
public int NumOranges { get; internal set; }
public bool TreeAlive { get; internal set; }
public int OrangesEaten { get; internal set; }
internal void OneYearPasses()
{
Age = Age + 1 ;
Height = Height + 2;
if (Age >= 2)
{
NumOranges = NumOranges + 5;
}
if (Age >= 80) TreeAlive = false;
}
internal void EatOrange(int v)
{
if (NumOranges - v <= 0) throw new IndexOutOfRangeException("You can't eat an orange that isn't there! There are 0 oranges available to eat");
else
NumOranges = NumOranges - v;
OrangesEaten = OrangesEaten + v;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MiniMapZoom : MonoBehaviour {
public Camera cam;
public void ZoomIn()
{
cam.orthographicSize += 5;
}
public void ZoomOut()
{
cam.orthographicSize -= 5;
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataSupervisorForModel
{
static class DataCollectionLibrary
{
static internal List<OptionSpreadExpression> optionSpreadExpressionList;
//= new List<OptionSpreadExpression>();
static internal ConcurrentDictionary<string, OptionSpreadExpression> optionSpreadExpressionHashTable_keySymbol;
//= new ConcurrentDictionary<string, OptionSpreadExpression>();
static internal ConcurrentDictionary<string, OptionSpreadExpression> optionSpreadExpressionHashTable_keyCQGInId;
//= new ConcurrentDictionary<string, OptionSpreadExpression>();
static internal ConcurrentDictionary<string, OptionSpreadExpression> optionSpreadExpressionHashTable_keyFullName;
//= new ConcurrentDictionary<string, OptionSpreadExpression>();
static internal Dictionary<long, OptionSpreadExpression> optionSpreadExpressionHashTable_keycontractId;
//= new Dictionary<long, OptionSpreadExpression>();
static internal Dictionary<long, Instrument_mongo> instrumentHashTable;
//= new Dictionary<long, Instrument>();
static internal Dictionary<long, List<Contract>> contractHashTableByInstId;
//= new Dictionary<long, List<Contract>>();
static internal List<Instrument_mongo> instrumentList;
//= new List<Instrument>();
static internal DataTable contractSummaryGridListDataTable = new DataTable();
public static void ResetAndInitializeData()
{
optionSpreadExpressionList = new List<OptionSpreadExpression>();
optionSpreadExpressionHashTable_keySymbol
= new ConcurrentDictionary<string, OptionSpreadExpression>();
optionSpreadExpressionHashTable_keyCQGInId
= new ConcurrentDictionary<string, OptionSpreadExpression>();
optionSpreadExpressionHashTable_keyFullName
= new ConcurrentDictionary<string, OptionSpreadExpression>();
optionSpreadExpressionHashTable_keycontractId
= new Dictionary<long, OptionSpreadExpression>();
instrumentHashTable
= new Dictionary<long, Instrument_mongo>();
contractHashTableByInstId
= new Dictionary<long, List<Contract>>();
instrumentList = new List<Instrument_mongo>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShieldScript : MonoBehaviour
{
int maximumShield = 10;
int currentShield = 0;
void Start()
{
currentShield = maximumShield;
}
public int getShield(){
return currentShield;
}
public int getMaxShield(){
return maximumShield;
}
public void Damage(int damageValue)
{
currentShield -= damageValue;
if (currentShield <= 0)
{
currentShield = 0;
}
else if(currentShield >= 10){
currentShield = 10; //Makes sure that the Players health can't go any higher than 100 even when using a health potion
}
}
}
|
using DDClassLibrary1;
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 DDWinFormCoreApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var platform = "Windows Forms(.NET Core)";
DDExcel.Create(platform);
DDPdf.Create(platform);
}
}
}
|
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
namespace AzureMessagingExplorer
{
public static class HttpTrigger
{
[FunctionName("HttpTrigger")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req,
[SignalR(HubName = "broadcast")]IAsyncCollector<SignalRMessage> signalRMessages,
TraceWriter log)
{
var requestContent = await req.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(requestContent))
{
return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Please pass a payload to broadcast in the request body.");
}
log.Info($"Message with payload {requestContent}");
await signalRMessages.AddAsync(new SignalRMessage()
{
Target = "notify",
Arguments = new object[] { requestContent }
});
return req.CreateResponse(HttpStatusCode.OK);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief 2D描画。入力フィールド。
*/
/** Render2D
*/
namespace NRender2D
{
/** InputField2D
*/
public class InputField2D : NDeleter.DeleteItem_Base
{
/** 状態。
*/
private State2D state;
/** 表示フラグ。
*/
private bool visible;
/** 削除フラグ。
*/
private bool deletereq;
/** 描画プライオリティ。
*/
private long drawpriority;
/** 矩形。
*/
private InputField2D_Rect rect;
/** パラメータ。
*/
private InputField2D_Param param;
/** constructor
*/
public InputField2D(NDeleter.Deleter a_deleter,State2D a_state,long a_drawpriority)
{
Render2D.GetInstance().AddInputField2D(this);
//状態。
this.state = a_state;
//表示フラグ。
this.visible = true;
//削除フラグ。
this.deletereq = false;
//描画プライオリティ。
this.drawpriority = a_drawpriority;
//位置。
//this.pos;
//パラメータ。
this.param.Initialze();
//削除管理。
if(a_deleter != null){
a_deleter.Register(this);
}
}
/** 削除。
*/
public void Delete()
{
this.deletereq = true;
//非表示。
this.visible = false;
//rawの削除。
this.param.Delete();
//更新リクエスト。
Render2D.GetInstance().UpdateInputFieldListRequest();
}
/** 削除チェック。
*/
public bool IsDelete()
{
return this.deletereq;
}
/** 矩形。設定。
*/
public void SetX(int a_x)
{
this.rect.SetX(a_x);
}
/** 矩形。設定。
*/
public void SetY(int a_y)
{
this.rect.SetY(a_y);
}
/** 矩形。設定。
*/
public void SetW(int a_w)
{
this.rect.SetW(a_w);
}
/** 矩形。設定。
*/
public void SetH(int a_h)
{
this.rect.SetH(a_h);
}
/** 矩形。取得。
*/
public int GetX()
{
return this.rect.GetX();
}
/** 矩形。取得。
*/
public int GetY()
{
return this.rect.GetY();
}
/** 矩形。取得。
*/
public int GetW()
{
return this.rect.GetW();
}
/** 矩形。取得。
*/
public int GetH()
{
return this.rect.GetH();
}
/** 矩形。設定。
*/
public void SetRect(ref Rect2D_R<int> a_rect)
{
this.rect.SetRect(ref a_rect);
}
/** 矩形。設定。
*/
public void SetRect(int a_x,int a_y,int a_w,int a_h)
{
this.rect.SetX(a_x);
this.rect.SetY(a_y);
this.rect.SetW(a_w);
this.rect.SetH(a_h);
}
/** クリップ。設定。
*/
public void SetClip(bool a_flag)
{
this.param.SetClip(a_flag);
}
/** クリップ。取得。
*/
public bool IsClip()
{
return this.param.IsClip();
}
/** クリップ矩形。設定。
*/
public void SetClipRect(ref NRender2D.Rect2D_R<int> a_rect)
{
this.param.SetClipRect(ref a_rect);
}
/** クリップ矩形。設定。
*/
public void SetClipRect(int a_x,int a_y,int a_w,int a_h)
{
this.param.SetClipRect(a_x,a_y,a_w,a_h);
}
/** クリップ矩形。取得。
*/
public int GetClipX()
{
return this.param.GetClipX();
}
/** クリップ矩形。取得。
*/
public int GetClipY()
{
return this.param.GetClipY();
}
/** クリップ矩形。取得。
*/
public int GetClipW()
{
return this.param.GetClipW();
}
/** クリップ矩形。取得。
*/
public int GetClipH()
{
return this.param.GetClipH();
}
/** カスタムテキストマテリアル。取得。
*/
public Material GetCustomTextMaterial()
{
return this.param.GetCustomTextMaterial();
}
/** カスタムイメージマテリアル。取得。
*/
public Material GetCustomImageMaterial()
{
return this.param.GetCustomImageMaterial();
}
/** 状態。設定。
*/
public void SetState(State2D a_state)
{
this.state = a_state;
}
/** 状態。取得。
*/
public State2D GetState()
{
return this.state;
}
/** 表示。設定。
*/
public void SetVisible(bool a_flag)
{
this.visible = a_flag;
}
/** 表示。取得。
*/
private bool IsVisible_State()
{
if(this.state != null){
return this.state.IsVisible();
}
return true;
}
/** 表示。取得。
*/
public bool IsVisible()
{
return this.visible && this.IsVisible_State();
}
/** 描画プライオリティ。設定。
*/
public void SetDrawPriority(long a_drawpriority)
{
if(this.drawpriority != a_drawpriority){
this.drawpriority = a_drawpriority;
//更新リクエスト。
Render2D.GetInstance().UpdateInputFieldListRequest();
}
}
/** 描画プライオリティ。取得。
*/
public long GetDrawPriority()
{
return this.drawpriority;
}
/** 描画プライオリティ。ソート関数。
*/
public static int Sort_DrawPriority(InputField2D a_test,InputField2D a_target)
{
return (int)(a_test.drawpriority - a_target.drawpriority);
}
/** テキスト。設定。
*/
public void SetText(string a_text)
{
this.param.SetText(a_text);
}
/** テキスト。取得。
*/
public string GetText()
{
return this.param.GetText();
}
/** マルチライン。設定。
*/
public void SetMultiLine(bool a_flag)
{
this.param.SetMultiLine(a_flag);
}
/** フォーカス。取得。
*/
public bool IsFocused()
{
return this.param.IsFocused();
}
/** フォーカス。設定。
*/
public void SetFocuse()
{
this.param.SetFocuse();
}
/** フォントサイズ。設定。
*/
public void SetFontSize(int a_fontsize)
{
this.param.SetFontSize(a_fontsize);
}
/** フォントサイズ。取得。
*/
public int GetFontSize()
{
return this.param.GetFontSize();
}
/** イメージ色。設定。
*/
public void SetImageColor(ref Color a_color)
{
this.param.SetImageColor(ref a_color);
}
/** イメージ色。設定。
*/
public void SetImageColor(float a_r,float a_g,float a_b,float a_a)
{
this.param.SetImageColor(a_r,a_g,a_b,a_a);
}
/** イメージ色。取得。
*/
public Color GetImageColor()
{
return this.param.GetImageColor();
}
/** テキスト色。設定。
*/
public void SetTextColor(ref Color a_color)
{
this.param.SetTextColor(ref a_color);
}
/** テキスト色。設定。
*/
public void SetTextColor(float a_r,float a_g,float a_b,float a_a)
{
this.param.SetTextColor(a_r,a_g,a_b,a_a);
}
/** テキスト色。取得。
*/
public Color GetTextColor()
{
return this.param.GetTextColor();
}
/** センター。設定。
*/
public void SetCenter(bool a_flag)
{
this.param.SetCenter(a_flag);
}
/** センター。設定。
*/
public bool IsCenter()
{
return this.param.IsCenter();
}
/** フォント。設定。
*/
public void SetFont(Font a_font)
{
this.param.SetFont(a_font);
}
/** フォント。取得。
*/
public Font GetFont()
{
return this.param.GetFont();
}
/** [内部からの呼び出し]サイズ。設定。
*/
public void Raw_SetRectTransformSizeDelta(ref Vector2 a_size)
{
this.param.Raw_SetRectTransformSizeDelta(ref a_size);
}
/** [内部からの呼び出し]サイズ。取得。
*/
public void Raw_GetRectTransformSizeDelta(out Vector2 a_size)
{
this.param.Raw_GetRectTransformSizeDelta(out a_size);
}
/** [内部からの呼び出し]位置。設定。
*/
public void Raw_SetRectTransformLocalPosition(ref Vector3 a_position)
{
this.param.Raw_SetRectTransformLocalPosition(ref a_position);
}
/** [内部からの呼び出し]フォントサイズ。設定。
*/
public void Raw_SetFontSize(int a_raw_fontsize)
{
this.param.Raw_SetFontSize(a_raw_fontsize);
}
/** [内部からの呼び出し]テキストマテリアル。設定。
*/
public void Raw_SetTextMaterial(Material a_material)
{
this.param.Raw_SetTextMaterial(a_material);
}
/** [内部からの呼び出し]イメージマテリアル。設定。
*/
public void Raw_SetImageMaterial(Material a_material)
{
this.param.Raw_SetImageMaterial(a_material);
}
/** [内部からの呼び出し]レイヤー。設定。
*/
public void Raw_SetLayer(Transform a_layer_transform)
{
this.param.Raw_SetLayer(a_layer_transform);
}
/** [内部からの呼び出し]有効。設定。
*/
public void Raw_SetEnable(bool a_flag)
{
this.param.Raw_SetEnable(a_flag);
}
/** [内部からの呼び出し]シェーダの変更が必要。取得。
*/
public bool Raw_IsChangeShader()
{
return this.param.Raw_IsChangeShader();
}
/** [内部からの呼び出し]シェーダの変更が必要。取得。
*/
public void Raw_SetChangeShaderFlag(bool a_flag)
{
this.param.Raw_SetChangeShaderFlag(a_flag);
}
/** [内部からの呼び出し]フォントのサイズの計算が必要。取得。
*/
public bool Raw_IsCalcFontSize()
{
return this.param.Raw_IsCalcFontSize();
}
/** [内部からの呼び出し]フォントのサイズの計算が必要。設定。
*/
public void Raw_SetCalcFontSizeFlag(bool a_flag)
{
this.param.Raw_SetCalcFontSizeFlag(a_flag);
}
}
}
|
using CMkvPropEdit.Helper;
using System.Collections.Generic;
using System.Windows.Forms;
namespace CMkvPropEdit.View
{
public partial class InsertText : Form
{
internal string NewText;
private readonly HashSet<string> PermittedNames;
private bool ReplaceSpecialCharacter;
internal InsertText(string header, string description, string oldName = "", bool replaceSpecialCharacter = true, HashSet<string> permittedNames = null)
{
InitializeComponent();
Text = header;
LblDescription.Text = description;
TxTName.Text = oldName;
PermittedNames = permittedNames;
ReplaceSpecialCharacter = replaceSpecialCharacter;
}
private void TxTName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Confirm();
}
}
private void Confirm()
{
DialogResult result = DialogResult.Yes;
if (ReplaceSpecialCharacter)
{
TxTName.Text = TxTName.Text.Replace('?', '?')
.Replace(" : ", ":")
.Replace(':', ':')
.Replace('\\', '\')
.Replace('>', '>')
.Replace('<', '<')
.Replace('*', '*')
.Replace("/", " ∕ ")
.Replace("\"", "''");
}
if (PermittedNames != null && PermittedNames.Contains(TxTName.Text))
{
result = MessageService.ShowQuestion("Name is already taken!\nDo you want to override it?");
}
if(result == DialogResult.Yes)
{
NewText = TxTName.Text;
DialogResult = DialogResult.OK;
}
}
private void BtnConfirm_Click(object sender, System.EventArgs e)
{
Confirm();
}
}
}
|
using System;
using DipDemo.Cataloguer.Infrastructure.EventAggregator;
using DipDemo.Cataloguer.Infrastructure.IoC;
namespace DipDemo.Cataloguer.Infrastructure.AppController
{
public class ApplicationController : IApplicationController
{
private readonly IDependencyResolver resolver;
private readonly IEventPublisher eventPublisher;
public ApplicationController(IDependencyResolver container, IEventPublisher eventPublisher)
{
resolver = container;
this.eventPublisher = eventPublisher;
resolver.Inject<IApplicationController>(this);
}
public void ProcessRequest<T>(T commandData) where T : IRequestData
{
var requestHandler = resolver.TryResolve<IRequestHandler<T>>();
if (requestHandler == null)
throw new ApplicationException("Request handler for [" + typeof (T).FullName + "] not found");
requestHandler.Execute(commandData);
}
public void ProcessRequest<T>() where T : IRequestData, new()
{
ProcessRequest(new T());
}
public void Raise<T>(T eventData)
{
eventPublisher.Publish(eventData);
}
public void Raise<T>() where T : new()
{
Raise(new T());
}
public TResponse RequestReply<TRequest, TResponse>(TRequest request) where TRequest : IRequestData<TResponse>
{
var handler = resolver.Resolve<IRequestHandler<TRequest, TResponse>>();
return handler.ProcessRequest(request);
}
}
} |
using UnityEngine;
using System.Collections;
public class FormationSetter : MonoBehaviour {
public int slot;
public TextMesh info;
public SpriteRenderer spriteRend;
public GameObject barrackScreen;
public GameObject targetObject;
public ScreenData screenData;
public GameObject heroLock;
private bool isReload = false;
public ProfileController profileController; // profile master
public HeroProfileController controller; // screen troops
public AudioClip sound;
private Vector3 tempPosition;
// Use this for initialization
void Start () {
FormationUnit u = GameData.profile.formationList [slot];
// Debug.Log ("at slot " + slot + " job " + GameData.profile.formationList [slot].UnitHeroId);
// Debug.Log (" curr " + u.Unit.JobList[u.Unit.CurrentJob]);
if (u.IsUnlocked) {
heroLock.SetActive (false);
}
if ( u.UnitHeroId != 99 ) // kalau form slot idnya gk 99
ReloadSprite(u.Unit.JobList[u.Unit.CurrentJob]);
else{
ReloadSprite(null);
}
}
void OnMouseDown(){
}
void OnMouseUp(){
tempPosition = targetObject.transform.position;
info.text = "Select unit";
if (GameData.readyToTween ) {
MusicManager.getMusicEmitter().audio.PlayOneShot(sound);
// kalau belum ke unlock
// Debug.Log("masuk 1 " + GameData.profile.formationList [slot].IsUnlocked + " " + GameData.profile.formationList [slot].Unit.HeroId);
// ketika id !=99, brarti sudah diset, bisa liat profilnya
if (GameData.profile.formationList [slot].IsUnlocked ){
// Debug.Log("masuk 2 " + GameData.profile.formationList [slot].IsUnlocked + " " + GameData.profile.formationList [slot].Unit.HeroId);
// view profile controller set gambar dan status
GameData.unitSlotYangDiSet = slot;
GameData.gameState = "SelectUnit";
iTween.MoveTo ( targetObject,iTween.Hash("position",barrackScreen.transform.position,"time", 0.1f,"oncomplete","ReadyTween","oncompletetarget",gameObject));
}
}
}
void ReadyTween(){
iTween.MoveTo ( barrackScreen,iTween.Hash("position",tempPosition,"time", 0.1f,"oncomplete","ReadyTween2","oncompletetarget",gameObject));
}
void ReadyTween2(){
GameData.readyToTween = true;
}
public void ReloadSprite(string path){
spriteRend.sprite = (Sprite)Resources.Load("Sprite/Character/Hero/"+path,typeof(Sprite));
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Kers.Models.Entities.KERScore
{
public partial class TaxExempt : IEntityBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public KersUser By {get;set;}
public PlanningUnit Unit {get;set;}
public string Name {get;set;}
public string Ein {get;set;}
public string BankName {get;set;}
public string BankAccountName {get;set;}
public string DonorsReceivedAck {get;set;}
public string AnnBudget {get;set;}
public string AnnFinancialRpt {get;set;}
public string AnnAuditRpt {get;set;}
public string AnnInvRpt {get;set;}
public Boolean GeographicAreaAll {get;set;}
public Boolean GeographicAreaDistricts {get;set;}
public Boolean GeographicAreaRegions {get;set;}
public Boolean GeographicAreaAreas {get;set;}
public Boolean GeographicAreaCounties {get;set;}
public List<TaxExemptArea> Areas {get;set;}
public TaxExemptFinancialYear TaxExemptFinancialYear {get;set;}
public int? TaxExemptFinancialYearId {get;set;}
public List<TaxExemptProgramCategory> TaxExemptProgramCategories {get;set;}
public int HandledId {get;set;}
public TaxExemptFundsHandled Handled {get;set;}
//INFORMATION SPECIFIC TO TAX EXEMPT STATUS DERIVED FROM COUNTY EXTENSION DISTRICT
public string DistrictName {get;set;}
public string DistrictEin {get;set;}
//INFORMATION SPECIFIC TO TAX EXEMPT STATUS DERIVED FROM 501(c) ORGANIZATION
public string OrganizationName {get;set;}
public string OrganizationEin {get;set;}
public int? OrganizationResidesId {get;set;}
public PlanningUnit OrganizationResides {get;set;}
public string OrganizationLetterDate {get;set;}
public string OrganizationSignedDate {get;set;}
public string OrganizationAppropriate {get;set;}
public DateTime Created {get;set;}
public DateTime Updated {get;set;}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
public class CharacterSelection : MonoBehaviour
{
private List<GameObject> AvailableCharacters = new List<GameObject>();
private int _currentModelIndex;
private Player _player;
void Awake()
{
var playerModel = transform.Find("SimplePeople").gameObject;
// -1 as model limbs are the last object in the list
for (var i = 0; i < playerModel.transform.childCount-1; i++)
{
AvailableCharacters.Add(playerModel.transform.GetChild(i).gameObject);
}
}
// Use this for initialization
public void Set(Player player)
{
_player = player;
DisableAll();
SetCharacter();
transform.GetChild(0).GetComponent<Animator>().SetFloat("Speed_f", 1f);
}
public void NextCharacter()
{
AvailableCharacters[_currentModelIndex].SetActive(false);
_currentModelIndex = _currentModelIndex >= AvailableCharacters.Count - 1 ? 0 : _currentModelIndex + 1;
SetCharacter();
}
public void PrevCharacter()
{
AvailableCharacters[_currentModelIndex].SetActive(false);
_currentModelIndex = _currentModelIndex <= 0 ? AvailableCharacters.Count - 1 : _currentModelIndex - 1;
SetCharacter();
}
public void SelectCharacter()
{
if (SP_Manager.Instance.IsSinglePlayer())
{
GameObject.Find("SinglePlayerManager").GetComponent<SP_GameManager>().SetModel(_currentModelIndex);
}
else
{
// Client needs to be ready to send command
if (!ClientScene.ready)
{
ClientScene.Ready(NetworkManager.singleton.client.connection);
}
_player.CmdSetModel(_currentModelIndex);
}
DisableAll();
GameObject.Find("MenuManager").GetComponent<MenuManager>().HideCharacterSelect();
}
private void DisableAll()
{
foreach (var availableCharacter in AvailableCharacters)
{
availableCharacter.SetActive(false);
}
}
private void SetCharacter()
{
AvailableCharacters[_currentModelIndex].SetActive(true);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Sunny.HttpReqeustServer
{
public class HiJackingHandler : IHttpHandler
{
string requestMethod = "";
string requestUrl = "";
string requestStr = "";
string responseStr = "";
NameValueCollection requestParameters = new NameValueCollection();
HttpResponseInfo response = new HttpResponseInfo { Status = 200 };
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
requestMethod = context.Request.HttpMethod;
switch (requestMethod.ToUpper())
{
case "POST":
requestUrl = context.Request.RawUrl;
//var form = context.Request.Form;
StreamReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8);
requestStr = reader.ReadToEnd();
break;
default:
requestUrl = context.Request.RawUrl;
requestStr = context.Request.QueryString.ToString();
break;
}
CommonHelper.WriteLog(string.Format("{0}.ProcessRequest", this.GetType().Name), context.ApplicationInstance.GetHashCode().ToString());
requestParameters = HttpUtility.ParseQueryString(requestStr);
responseStr = string.Format("HaHa, You was hijacked! if you don't believe, please check following information you send.{0}{0}Request Url:'{1}'{0}Request Paramters:'{2}'",
Environment.NewLine, requestUrl, requestParameters.ToString());
context.Response.StatusCode = 200;
context.Response.Write(responseStr);
context.Response.End();
}
}
}
|
using UnityEngine;
using System.Collections;
public class GizmoDrawer : MonoBehaviour {
public void OnDrawGizmos()
{
TextSize[] textsWithLimitedSize = FindObjectsOfType<TextSize> ();
for (int i = 0; i < textsWithLimitedSize.Length; i++) {
Gizmos.DrawWireCube (textsWithLimitedSize[i].gameObject.transform.position, new Vector3(0, 0.5f, textsWithLimitedSize[i].wantedWidth));
}
}
}
|
using System;
using System.Collections.Generic;
namespace AorFramework.NodeGraph
{
public class HierarchyObjSelectorData : NodeData
{
public HierarchyObjSelectorData() {}
public HierarchyObjSelectorData(long id) : base(id) {}
public readonly int[] SelectedInstanceIDs;
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using RGB.NET.Core;
using RGB.NET.Core.Layout;
namespace RGB.NET.Devices.MadLed
{
/// <inheritdoc />
/// <summary>
/// Represents a debug device.
/// </summary>
public class MadLedRGBDevice : AbstractRGBDevice<MadLedRGBDeviceInfo>
{
#region Properties & Fields
/// <inheritdoc />
public int Bank { get; set; }
public override MadLedRGBDeviceInfo DeviceInfo { get; }
private MadLedSerialDriver driver;
protected MadLedDeviceUpdateQueue DeviceUpdateQueue { get; set; }
private Func<Dictionary<LedId, Color>> _syncBackFunc;
private Action<IEnumerable<Led>> _updateLedsAction;
private bool toggle = true;
private FanModel fanModel;
#endregion
#region Constructors
/// <summary>
/// Internal constructor of <see cref="MadLedRGBDeviceInfo"/>.
/// </summary>
internal MadLedRGBDevice(FanModel fanModel, MadLedSerialDriver drv, Func<Dictionary<LedId, Color>> syncBackFunc = null, Action<IEnumerable<Led>> updateLedsAction = null)
{
this.driver = drv;
this._syncBackFunc = syncBackFunc;
this._updateLedsAction = updateLedsAction;
this.fanModel = fanModel;
//DeviceLayout layout = DeviceLayout.Load(layoutPath);
DeviceInfo = new MadLedRGBDeviceInfo(RGBDeviceType.Fan, "Mad Ninja","MadLed", RGBDeviceLighting.Key, syncBackFunc != null, fanModel.Name);
for (int i = 0; i < fanModel.NumberOfLeds; i++)
{
LedId ledid = ((LedId)0x00B00001 + i);
//Led led = new Led(this, ledid, new Point(1,1), new Size(1,1), i );
//LedMapping.Add(ledid, led);
InitializeLed(ledid, new Point(1, 1), new Size(1, 1));
}
Debug.WriteLine("Setup new fan on bank "+fanModel.Bank);
}
#endregion
#region Methods
internal void Initialize(string layoutPath, string imageLayout) => ApplyLayoutFromFile(layoutPath, imageLayout, true);
public void Initialize(MadLedDeviceUpdateQueue updateQueue)
{
DeviceUpdateQueue = updateQueue;
//InitializeLayout(ledCount);
if (Size == Size.Invalid)
{
Rectangle ledRectangle = new Rectangle(this.Select(x => x.LedRectangle));
Size = ledRectangle.Size + new Size(ledRectangle.Location.X, ledRectangle.Location.Y);
}
}
/// <inheritdoc />
public override void SyncBack()
{
try
{
Dictionary<LedId, Color> syncBackValues = _syncBackFunc?.Invoke();
if (syncBackValues == null) return;
foreach (KeyValuePair<LedId, Color> value in syncBackValues)
{
Led led = ((IRGBDevice)this)[value.Key];
SetLedColorWithoutRequest(led, value.Value);
}
}
catch {/* idc that's not my fault ... */}
}
/// <inheritdoc />
protected override void UpdateLeds(IEnumerable<Led> ledsToUpdate)
{
var uleds = ledsToUpdate.Where(x => (x.Color.A > 0));
DeviceUpdateQueue.SetData(uleds);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DomainTrigger : MonoBehaviour
{
public PatrollingEnemeyController enemy;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.GetComponent<PlayerController>() != null)
{
enemy.OnEnteringDomain(collision.gameObject);
}
}
void OnTriggerStay2D(Collider2D collision)
{
if (collision.GetComponent<PlayerController>() != null)
{
enemy.OnEnteringDomain(collision.gameObject);
}
}
void OnTriggerExit2D(Collider2D collision)
{
if (collision.GetComponent<PlayerController>() != null)
{
enemy.OnExitingDomain();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Stage2Talk : StageBase
{
public GameObject kiritanObject;
static GameObject kiritan, kiritanMask;
static GameObject kiritanChara = null;
Kiritan kiritanScript;
//GraphDiffer kiritanEyeBrows, kiritanEye, kiritanMouse, kiritanOption;
GraphDiffer kiritanBody;
protected CharaPicture kiritanPicture;
int firstObentouBulletCount;
int firstMaxHp;
// Start is called before the first frame update
void Start()
{
StaticValues.havingShooter = 1;
ResetSceneParameters();
step = StaticValues.stage2Step;
firstObentouBulletCount = StaticValues.obentouBulletMax;
firstMaxHp = StaticValues.maxHp;
kiritanChara = GameObject.Find("Kiritan");
if (kiritanChara != null)
kiritanScript = kiritanChara.GetComponent<Kiritan>();
if (StaticValues.isEXMode)
{
step = 9999;
GameObject.Find("door").SetActive(false);
}
AkariInstantiate();
KiritanInstantiate();
LoadACB("Stage2", "Stage2.acb");
PlayBGM("stage");
StaticValues.Save();
}
// Update is called once per frame
void Update()
{
bool forceNext = false;
time += Time.deltaTime;
// ボス撃破後に連打でページ送りしてしまうのを防止するため1秒入力を受け付けない
if (StaticValues.isTalkPause)
{
if (time >= 1.0f)
{
StaticValues.isTalkPause = false;
} else
{
return;
}
}
if (step == 0 && time >= 2.0f)
forceNext = true;
if (step <= 4)
StaticValues.isPause = true;
if (firstObentouBulletCount != StaticValues.obentouBulletMax)
{
firstObentouBulletCount = StaticValues.obentouBulletMax;
tmpStep = step;
step = 101;
forceNext = true;
}
if (firstMaxHp != StaticValues.maxHp)
{
firstMaxHp = StaticValues.maxHp;
tmpStep = step;
step = 201;
forceNext = true;
}
if (bossStageEntrance != null && bossStageEntrance.GetTrigger() && !isBossEnter)
{
if (StaticValues.isEXMode)
{
isBossEnter = true;
enemyGaugeScript.PlayGaugeAppear();
PlayBGM("boss");
}
else
{
StaticValues.isPause = true;
if (!cameraScript.IsFixPosMoving())
{
isBossEnter = true;
tmpStep = step;
step = 501;
forceNext = true;
}
}
}
if (kiritanScript != null && kiritanScript.IsDead() && !isBossDead)
{
if (StaticValues.isEXMode)
{
ChangeScene("Stage3-4");
}
else
{
isBossDead = true;
tmpStep = step;
step = 601;
forceNext = true;
}
}
if (kiritanChara != null && !isBossDead)
{
}
if (Input.GetButtonDown("Shot") || Input.GetButtonDown("Jump") || forceNext)
{
UpdateStep();
}
StaticValues.stage2Step = step;
}
void UpdateStep()
{
switch (step)
{
case 0:
akari.GetComponent<Animator>().SetBool("isOut", false);
akariPicture.SetSprite("sad", "normal", "omega");
AddTextWindow(speechWindowLeft, "森の中は結構暗いんだなぁ");
PlayVoice("Stage2Akari-0");
break;
case 1:
akariPicture.eye.SetSprite("half_open");
AddTextWindow(speechWindowLeft, "それになんだか雰囲気もだいぶ違うし...");
PlayVoice("Stage2Akari-1");
break;
case 2:
akariPicture.SetSprite("anger", "", "o");
AddTextWindow(speechWindowLeft, "ううん、\nそんなことで挫けていられない");
PlayVoice("Stage2Akari-2");
break;
case 3:
akariPicture.SetSprite("", "star", "mufu");
AddTextWindow(speechWindowLeft, "頑張るぞ!");
PlayVoice("Stage2Akari-3");
break;
case 4:
step++;
break;
case 5:
akari.GetComponent<Animator>().SetBool("isOut", true);
step++;
StaticValues.isPause = false;
break;
case 6:
step++;
break;
case 7:
break;
case 101:
StaticValues.isPause = true;
akariPicture.SetSprite("normal", "shiitake", "laugh");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "携帯食だ!");
PlayVoice("Stage2Akari-4");
break;
case 102:
akariPicture.SetSprite("", "smile", "omega");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "お弁当の量が\n増えました!");
PlayVoice("Stage2Akari-5");
break;
case 103:
step++;
break;
case 104:
StaticValues.isPause = false;
akari.GetComponent<Animator>().SetBool("isOut", true);
step = tmpStep;
break;
case 105:
break;
case 201:
StaticValues.isPause = true;
akariPicture.SetSprite("anger", "star", "laugh");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "パワーアップアイテムだ!");
PlayVoice("Stage2Akari-6");
break;
case 202:
StaticValues.isPause = true;
akariPicture.SetSprite("normal", "smile");
AddTextWindow(speechWindowLeft, "体力が少し増えました!");
PlayVoice("Stage2Akari-7");
break;
case 203:
step++;
break;
case 204:
StaticValues.isPause = false;
akari.GetComponent<Animator>().SetBool("isOut", true);
step = tmpStep;
break;
case 205:
break;
case 501:
StaticValues.isPause = true;
kiritan.GetComponent<Animator>().SetBool("isOut", false);
kiritanBody.SetSprite("kiritan");
kiritanPicture.SetSprite("anger", "normal", "omega");
AddTextWindow(speechWindowRight, "おや、\nあかりさんじゃないですか");
PlayVoice("Stage2Kiritan-0");
break;
case 502:
akariPicture.SetSprite("normal", "smile", "laugh", "oxtu");
akari.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowLeft, "あっ、きりたん!");
PlayVoice("Stage2Akari-8");
break;
case 503:
kiritanPicture.SetSprite("", "", "laugh");
AddTextWindow(speechWindowRight, "今年は参加してたんですね");
PlayVoice("Stage2Kiritan-1");
break;
case 504:
kiritanPicture.SetSprite("", "", "mu");
AddTextWindow(speechWindowRight, "なるほどその銃は\nゆかりさんのお下がりですか");
PlayVoice("Stage2Kiritan-2");
break;
case 505:
akariPicture.SetSprite("anger", "white", "", "exclamation");
AddTextWindow(speechWindowLeft, "すごい、知ってるんだね!");
PlayVoice("Stage2Akari-9");
break;
case 506:
kiritanPicture.SetSprite("sad");
AddTextWindow(speechWindowRight, "そりゃあまぁ、去年\nたくさんやられましたからね");
PlayVoice("Stage2Kiritan-3");
break;
case 507:
akariPicture.SetSprite("normal", "", "omega", "nothing");
AddTextWindow(speechWindowLeft, "きりたんはここで何してるの?");
PlayVoice("Stage2Akari-10");
break;
case 508:
kiritanPicture.SetSprite("normal", "", "");
AddTextWindow(speechWindowRight, "私ですか?\n私はですね...");
PlayVoice("Stage2Kiritan-4");
break;
case 509:
kiritanPicture.SetSprite("anger", "half_open", "omega");
AddTextWindow(speechWindowRight, "ずん姉さまの勝利のために\nここを通る挑戦者を\n蹴落としているんですよ");
PlayVoice("Stage2Kiritan-5");
break;
case 510:
akariPicture.mouse.SetSprite("o");
AddTextWindow(speechWindowLeft, "え?\nそれってつまり...");
PlayVoice("Stage2Akari-11");
AudioManager.Instance.StopBGM();
break;
case 511:
AddTextWindow(speechWindowRight, "ここは通しません。\n私とずん姉さまのために\n死んでください");
kiritanBody.SetSprite("kiritan7");
kiritanPicture.SetSprite("nothing", "nothing", "nothing");
PlayVoice("Stage2Kiritan-6");
PlayBGM("boss");
break;
case 512:
akariPicture.SetSprite("anger", "white_tears", "cat", "flash");
AddTextWindow(speechWindowLeft, "そんなあー!!");
PlayVoice("Stage2Akari-12");
break;
case 513:
step++;
break;
case 514:
akari.GetComponent<Animator>().SetBool("isOut", true);
kiritan.GetComponent<Animator>().SetBool("isOut", true);
enemyGaugeScript.PlayGaugeAppear();
step++;
break;
case 515:
break;
case 601:
StaticValues.isPause = true;
StaticValues.isTalkPause = true;
time = 0;
AudioManager.Instance.FadeInBGM("stage");
akari.GetComponent<Animator>().SetBool("isOut", false);
kiritan.GetComponent<Animator>().SetBool("isOut", false);
AddTextWindow(speechWindowRight, "ぐっ....\nやりますね!");
PlayVoice("Stage2Kiritan-7");
break;
case 602:
akariPicture.SetSprite("anger", "white_tears", "cat", "sweat3");
AddTextWindow(speechWindowLeft, "ハァハァ...\nど、どんなもんだい!");
PlayVoice("Stage2Akari-13");
break;
case 603:
AddTextWindow(speechWindowRight, "正直甘く見ていました。\n認識を改めます");
PlayVoice("Stage2Kiritan-8");
break;
case 604:
AddTextWindow(speechWindowRight, "仕方ないのでここは\n一旦引くことにしますが、");
kiritanBody.SetSprite("kiritan");
kiritanPicture.SetSprite("sad", "half_open", "gununu");
PlayVoice("Stage2Kiritan-9");
break;
case 605:
kiritanPicture.SetSprite("anger", "normal", "laugh");
AddTextWindow(speechWindowRight, "次会った時は必ず\n私が勝ちますからね!");
PlayVoice("Stage2Kiritan-10");
break;
case 606:
akariPicture.SetSprite("", "normal", "laugh", "nothing");
AddTextWindow(speechWindowLeft, "あっ、待ってきりたん");
PlayVoice("Stage2Akari-14");
break;
case 607:
akariPicture.SetSprite("sad", "smile", "", "sweat4");
AddTextWindow(speechWindowLeft, "この先って\nどう進んだらいいのかな...?");
PlayVoice("Stage2Akari-15");
break;
case 608:
kiritanPicture.SetSprite("sad", "half_open_light_off");
AddTextWindow(speechWindowRight, "...地理把握もせず\n進んでいたんですか");
PlayVoice("Stage2Kiritan-11");
break;
case 609:
kiritanPicture.SetSprite("", "normal");
AddTextWindow(speechWindowRight, "陸路で進む場合はそこの\n洞窟を通るしかないですよ");
PlayVoice("Stage2Kiritan-12");
break;
case 610:
kiritanPicture.SetSprite("normal", "half_open", "doya");
AddTextWindow(speechWindowRight, "まぁ私は飛んでいきますが");
PlayVoice("Stage2Kiritan-13");
break;
case 611:
akariPicture.SetSprite("anger", "white", "triangle", "nothing");
AddTextWindow(speechWindowLeft, "えっ、ずるい!");
PlayVoice("Stage2Akari-16");
break;
case 612:
kiritanScript.SetActive();
kiritanScript.SetState(Kiritan.State.GoOut);
kiritanPicture.SetSprite("anger", "smile", "laugh");
AddTextWindow(speechWindowRight, "それでは、お互い\n脱落してなかったらまた会いましょう");
PlayVoice("Stage2Kiritan-14");
break;
case 613:
akariPicture.SetSprite("sad", "white_tears", "mufu");
kiritan.GetComponent<Animator>().SetBool("isOut", true);
AddTextWindow(speechWindowLeft, "ああ...\nしれっと逃げられた...");
PlayVoice("Stage2Akari-17");
break;
case 614:
akariPicture.SetSprite("", "close", "omega");
AddTextWindow(speechWindowLeft, "仕方ない、言われた通り\n洞窟を進むとしましょう");
PlayVoice("Stage2Akari-18");
break;
case 615:
akari.GetComponent<Animator>().SetBool("isOut", true);
step++;
break;
case 616:
ChangeScene("Stage3-1");
step++;
break;
case 617:
break;
}
}
void PlayVoice(string seName)
{
AudioManager.Instance.PlayExVoice(seName);
}
protected override void ChangeScene(string sceneName) {
base.ChangeScene(sceneName);
Destroy(kiritan);
kiritan = null;
}
void KiritanInstantiate()
{
if (kiritan == null)
{
kiritan = Instantiate(kiritanObject);
kiritan.transform.SetParent(transform.parent);
kiritan.transform.localScale = new Vector2(1, 1);
kiritanBody = kiritan.GetComponent<GraphDiffer>();
kiritanMask = kiritan.transform.Find("BlackMask").gameObject;
kiritanMask.SetActive(false);
kiritanPicture = new CharaPicture(kiritan);
kiritan.transform.SetAsFirstSibling();
DontDestroyOnLoad(kiritan);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace BackTracking
{
public class Subset
{
bool finished;
List<string> results;
public Subset (int n)
{
finished = false;
int[] A = new int[100];
results = new List<string> ();
SolveSubset (A,0,n);
}
void SolveSubset(int[] a,int k, int input)
{
int[] c= new int[100];
int nCandidates;
if (is_a_solution (a, k, input)) {
process_solution (a, k);
} else {
k = k + 1;
construct_candidates (a,k,input,c,out nCandidates);
for (int i = 0; i < nCandidates; i++) {
a[k] = c[i];
SolveSubset (a,k,input);
if (finished) {
return;
}
}
}
}
void construct_candidates(int[] a,int k,int input,int[] c,out int nCandidates)
{
c [0] = 0;
c [1] = 1;
nCandidates = 2;
}
bool is_a_solution(int[] a, int k, int n)
{
return (k == n);
}
void process_solution(int[] a, int k)
{
string s = string.Empty;
for (int i = 1; i < k + 1; i++) {
if (a[i] == 1) {
s += i.ToString();
}
}
results.Add (s);
}
}
}
|
using Caliburn.Light;
using Microsoft.UI.Xaml.Controls;
namespace Demo.HelloSpecialValues
{
public sealed class ClickedItem : ISpecialValue
{
public object Resolve(CommandExecutionContext context)
{
return context.EventArgs is ItemClickEventArgs args
? args.ClickedItem
: null;
}
}
}
|
using Kowalski.BusinessLayer.Extensions;
using Kowalski.BusinessLayer.Models;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace Kowalski.BusinessLayer.Services
{
public class WeatherService : IWeatherService
{
private readonly AppSettings settings;
private readonly IHttpClientFactory httpClientFactory;
public WeatherService(IOptions<AppSettings> settings, IHttpClientFactory httpClientFactory)
{
this.settings = settings.Value;
this.httpClientFactory = httpClientFactory;
}
public async Task<string> GetWeatherAsync(string location)
{
var url = string.Format(settings.WeatherServiceUri, Uri.EscapeDataString(location));
try
{
var client = httpClientFactory.CreateClient();
var json = await client.GetStringAsync(url);
if (string.IsNullOrWhiteSpace(json))
{
return null;
}
var weather = JsonConvert.DeserializeObject<CurrentWeather>(json);
// Checks the correct message to use.
var message = Messages.WeatherSingular;
switch (weather.WeatherInfo.FirstOrDefault().Id)
{
case 801:
case 802:
case 803:
case 804:
message = Messages.WeatherPlural;
break;
}
message = string.Format(message, location, weather.WeatherInfo.FirstOrDefault().Description, Math.Round(weather.WeatherDetail.Temperature, 0));
return message;
}
catch
{
return null;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseInteraction : MonoBehaviour {
Camera myCamera;
[SerializeField]
float interactionDistance = 2;
void Update() {
if (Input.GetButtonDown("Fire1")) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2, 0));
if (Physics.Raycast(ray, out hit, interactionDistance)) {
MonoBehaviour script = isInteractable(hit.collider.gameObject);
if (script)
((Interactable)script).OnInteract();
}
}
}
MonoBehaviour isInteractable(GameObject target)
{
MonoBehaviour[] components = target.GetComponents<MonoBehaviour>();
foreach (MonoBehaviour component in components)
{
if (component is Interactable)
return component;
}
return null;
}
}
|
namespace FbPageManager.Models
{
public class PageManagerPageInfo
{
public string Id { get; set; }
public string Name { get; set; }
public string AccessToken { get; set; }
public string PictureUrl { get; set; }
public string NextPageUrl { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Minesweeper
{
public partial class WinForm : Form
{
public GameForm game;
public String filename;
public WinForm(GameForm game) {
this.game = game;
InitializeComponent();
}
[ExcludeFromCodeCoverage]
public WinForm()
{
InitializeComponent();
//for unit testing
}
private void WinForm_Load(object sender, EventArgs e)
{
filename = game.map.MyName;
if (filename == null)
{
label2.Visible = false;
label3.Visible = false;
label4.Visible = false;
HighScoresList.Visible = false;
textBox1.Visible = false;
button2.Visible = false;
button1.Left = 100;
Height = 200;
} else
{
int counter = 0;
List<Tuple<int, String>> OrderedScores = new List<Tuple<int, String>>();
foreach (String name in game.map.scores.Keys)
{
OrderedScores.Add(Tuple.Create(game.map.scores[name], name));
}
OrderedScores.Sort();
foreach (Tuple<int, String> tuple in OrderedScores)
{
HighScoresList.Items.Add(tuple.Item1 + " " + tuple.Item2);
counter += 1;
if (counter >= 10)
{
break;
}
}
}
}
[ExcludeFromCodeCoverage]
private void button1_Click(object sender, EventArgs e)
{
MainForm main = new MainForm();
main.Show();
game.Hide();
this.Hide();
}
public void button2_Click(object sender, EventArgs e)
{
TransferUtility utility = new TransferUtility(RegionEndpoint.USEast2);
if (game.map.scores.Keys.Contains(textBox1.Text))
{
game.map.scores[textBox1.Text] = game.Time;
} else
{
game.map.scores.Add(textBox1.Text, game.Time);
}
game.map.CreateMapFile(filename);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
request.BucketName = "eecs393minesweeper";
request.FilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Minesweeper\\" + filename;
utility.Upload(request);
MainForm main = new MainForm();
main.Show();
game.Hide();
this.Hide();
}
}
}
|
/*
DotNetMQ - A Complete Message Broker For .NET
Copyright (C) 2011 Halil ibrahim KALKAN
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System.Collections.Generic;
namespace MDS.Storage.MemoryStorage
{
/// <summary>
/// Performs all database/storing operations on memory. So, all stored informations are lost
/// on server shutdown.
/// </summary>
public class MemoryStorageManager : IStorageManager
{
/// <summary>
/// A list to store message records (Messages table).
/// </summary>
private readonly SortedList<int, MDSMessageRecord> _messages;
/// <summary>
/// Stores ID field of last inserted item to the _messages list.
/// </summary>
private volatile int _lastRecordId;
/// <summary>
/// Creates a new MemoryStorageManager.
/// </summary>
public MemoryStorageManager()
{
_messages = new SortedList<int, MDSMessageRecord>();
}
/// <summary>
/// Starts the storage manager.
/// </summary>
public void Start()
{
//No action
}
/// <summary>
/// Stops the storage manager.
/// </summary>
public void Stop(bool waitToStop)
{
_messages.Clear();
}
public void WaitToStop()
{
//No action
}
/// <summary>
/// Saves a MDSMessageRecord object.
/// </summary>
/// <param name="messageRecord"></param>
public int StoreMessage(MDSMessageRecord messageRecord)
{
lock (_messages)
{
messageRecord.Id = (++_lastRecordId);
_messages.Add(messageRecord.Id, messageRecord);
return messageRecord.Id;
}
}
/// <summary>
/// Gets waiting messages for an application.
/// </summary>
/// <param name="nextServer">Next server name</param>
/// <param name="destApplication">Destination application name</param>
/// <param name="minId">Minimum Id (as start Id)</param>
/// <param name="maxCount">Max record count to get</param>
/// <returns>Records gotten from database.</returns>
public List<MDSMessageRecord> GetWaitingMessagesOfApplication(string nextServer, string destApplication, int minId, int maxCount)
{
var results = new List<MDSMessageRecord>();
lock (_messages)
{
foreach (var record in _messages.Values)
{
if (record.NextServer.Equals(nextServer) && record.DestApplication.Equals(destApplication)
&& record.Id >= minId)
{
results.Add(record);
if (results.Count >= maxCount)
{
break;
}
}
}
}
return results;
}
/// <summary>
/// Gets last (biggest) Id of waiting messages for an application.
/// </summary>
/// <param name="nextServer">Next server name</param>
/// <param name="destApplication">Destination application name</param>
/// <returns>last (biggest) Id of waiting messages</returns>
public int GetMaxWaitingMessageIdOfApplication(string nextServer, string destApplication)
{
lock (_messages)
{
var messageRecords = _messages.Values;
for (var i = messageRecords.Count - 1; i >= 0; i--)
{
var record = messageRecords[i];
if (record.NextServer.Equals(nextServer) && record.DestApplication.Equals(destApplication))
{
return record.Id;
}
}
}
return 0;
}
/// <summary>
/// Gets waiting messages for an application.
/// </summary>
/// <param name="nextServer">Next server name</param>
/// <param name="minId">Minimum Id (as start Id)</param>
/// <param name="maxCount">Max record count to get</param>
/// <returns>Records gotten from database.</returns>
public List<MDSMessageRecord> GetWaitingMessagesOfServer(string nextServer, int minId, int maxCount)
{
var results = new List<MDSMessageRecord>();
lock (_messages)
{
foreach (var record in _messages.Values)
{
if (record.NextServer.Equals(nextServer) && record.Id >= minId)
{
results.Add(record);
if (results.Count >= maxCount)
{
break;
}
}
}
}
return results;
}
/// <summary>
/// Gets last (biggest) Id of waiting messages for an MDS server.
/// </summary>
/// <param name="nextServer">Next server name</param>
/// <returns>last (biggest) Id of waiting messages</returns>
public int GetMaxWaitingMessageIdOfServer(string nextServer)
{
lock (_messages)
{
var messageRecords = _messages.Values;
for (var i = messageRecords.Count - 1; i >= 0; i--)
{
var record = messageRecords[i];
if (record.NextServer.Equals(nextServer))
{
return record.Id;
}
}
}
return 0;
}
/// <summary>
/// Removes a message record.
/// </summary>
/// <param name="recordId">recordId to delete</param>
/// <returns>Effected rows count</returns>
public int RemoveMessage(int recordId)
{
lock (_messages)
{
if(_messages.ContainsKey(recordId))
{
_messages.Remove(recordId);
return 1;
}
}
return 0;
}
/// <summary>
/// This method is used to set Next Server for a Destination Server.
/// It is used to update database records when Server Graph changed.
/// </summary>
/// <param name="destServer">Destination server of messages</param>
/// <param name="nextServer">Next server of messages for destServer</param>
public void UpdateNextServer(string destServer, string nextServer)
{
lock (_messages)
{
foreach (var record in _messages.Values)
{
if (record.DestServer.Equals(nextServer))
{
record.NextServer = nextServer;
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LibraryProjectMvc.Models.Entity;
using System.Web.Security;
namespace LibraryProjectMvc.Controllers
{
[AllowAnonymous]
public class LoginController : Controller
{
LibraryProjectEntities db = new LibraryProjectEntities();
// GET: Login
public ActionResult GirisYap()
{
return View();
}
[HttpPost]
public ActionResult GirisYap(Users u)
{
var informations = db.Users.FirstOrDefault(x => x.UserName == u.UserName && x.Password == u.Password);
if (informations != null)
{
FormsAuthentication.SetAuthCookie(informations.UserName, false);
Session["UserName"] = informations.UserName.ToString();
return RedirectToAction("Index", "UserPanel");
}
else
{
return View();
}
}
}
} |
using AutoMapper;
using Quinelita.Entities;
using Quinelita.Entities.DTOs;
namespace Quinelita.EndPoints.Automapper
{
public class AutoMapping : Profile
{
public AutoMapping()
{
CreateMap<GroupBet, TblGroupBet>().ReverseMap();
CreateMap<Tournament, TblTournament>().ReverseMap();
}
}
} |
using System;
using Terrasoft.Core;
using Terrasoft.Core.DB;
using Terrasoft.Core.Entities;
using Terrasoft.Core.Entities.Events;
namespace ZoomIntegration
{
//https://academy.bpmonline.com/documents/technic-sdk/7-13/entity-event-layer
[EntityEventListener(SchemaName = "ZoomMeetingParticipant")]
public class ZoomMeetingParticipantEventListener : BaseEntityEventListener
{
private Entity _certificationParticipant;
private UserConnection _userConnection;
public override void OnInserting(object sender, EntityBeforeEventArgs e)
{
base.OnInserting(sender, e);
_certificationParticipant = (Entity)sender;
_userConnection = _certificationParticipant.UserConnection;
string hash = GetStringSha256Hash(StringToEncode());
_certificationParticipant.SetColumnValue("RecordHash", hash);
//check if record with this has already exists
string RecordId = (new Select(_userConnection)
.Column("Id")
.From("ZoomMeetingParticipant")
.Where("RecordHash").IsEqual(Column.Parameter(hash)) as Select)
.ExecuteScalar<string>();
if (!string.IsNullOrEmpty(RecordId)){
e.IsCanceled = true;
}
}
internal static string GetStringSha256Hash(string text)
{
if (String.IsNullOrEmpty(text))
return String.Empty;
using (var sha = new System.Security.Cryptography.SHA256Managed())
{
byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
byte[] hash = sha.ComputeHash(textData);
return BitConverter.ToString(hash).Replace("-", String.Empty);
}
}
private string StringToEncode()
{
return string.Format("Property:{0}, Value:{1}", "ParticipantName", _certificationParticipant.GetTypedColumnValue<String>("ParticipantName"))+"|"+
string.Format("Property:{0}, Value:{1}", "ParticipantEmail", _certificationParticipant.GetTypedColumnValue<String>("ParticipantEmail"))+"|"+
string.Format("Property:{0}, Value:{1}", "JoinTime", _certificationParticipant.GetTypedColumnValue<String>("JoinTime"))+"|"+
string.Format("Property:{0}, Value:{1}", "LeaveTime", _certificationParticipant.GetTypedColumnValue<String>("LeaveTime"))+"|"+
string.Format("Property:{0}, Value:{1}", "Duration", _certificationParticipant.GetTypedColumnValue<String>("Duration"))+"|"+
string.Format("Property:{0}, Value:{1}", "Attentiveness", _certificationParticipant.GetTypedColumnValue<String>("Attentiveness"))+"|"+
string.Format("Property:{0}, Value:{1}", "ZoomParticipantId", _certificationParticipant.GetTypedColumnValue<String>("ZoomParticipantId"))+"|"+
string.Format("Property:{0}, Value:{1}", "ParticipantUserId", _certificationParticipant.GetTypedColumnValue<String>("ParticipantUserId"));
}
}
} |
using System;
using System.Drawing;
using System.IO;
using Newtonsoft.Json;
using Pastel;
namespace LunarTrader.Utils
{
public class FileLoader
{
private readonly string _settingsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/AlpacaSettings/";
public Settings ReadSettings()
{
Console.WriteLine("Loading Settings".Pastel((Color.FromArgb(46, 151, 72))));
string json;
using (var r = new StreamReader(_settingsPath + "Settings.json"))
{
json = r.ReadToEnd();
}
var settings = JsonConvert.DeserializeObject<Settings>(json);
return settings;
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace SNN.Core
{
[CreateAssetMenu]
public class LabelMapper : ScriptableObject
{
[SerializeField]
List<Label> labels;
[Header("Test")]
[SerializeField]
float[] testActivations;
public string GetName(float[] activations)
{
float squareDistance = CostHelper.SquareDistance(activations, labels[0].Activations);
string name = labels[0].Name;
for (int i = 1; i < labels.Count; i++)
{
float tmpSquareDistance = CostHelper.SquareDistance(activations, labels[i].Activations);
if (tmpSquareDistance < squareDistance)
{
squareDistance = tmpSquareDistance;
name = labels[i].Name;
}
}
return name;
}
[ContextMenu("ComputeTest")]
public void ComputeTest()
{
Debug.Log(GetName(testActivations));
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using RestSharp;
using Riverside.Cms.Services.Core.Client;
using Riverside.Cms.Utilities.Net.RestSharpExtensions;
namespace Riverside.Cms.Services.Element.Client
{
public class PageHeaderElementSettings : ElementSettings
{
public long? PageId { get; set; }
public bool ShowName { get; set; }
public bool ShowDescription { get; set; }
public bool ShowImage { get; set; }
public bool ShowCreated { get; set; }
public bool ShowUpdated { get; set; }
public bool ShowOccurred { get; set; }
public bool ShowBreadcrumbs { get; set; }
}
public class PageHeaderElementContent : IElementContent
{
public Page Page { get; set; }
}
public interface IPageHeaderElementService : IElementSettingsService<PageHeaderElementSettings>, IElementContentService<PageHeaderElementContent>
{
}
public class PageHeaderElementService : IPageHeaderElementService
{
private readonly IOptions<ElementApiOptions> _options;
public PageHeaderElementService(IOptions<ElementApiOptions> options)
{
_options = options;
}
private void CheckResponseStatus<T>(IRestResponse<T> response) where T : new()
{
if (response.ErrorException != null)
throw new ElementClientException($"Element API failed with response status {response.ResponseStatus}", response.ErrorException);
}
public async Task<PageHeaderElementSettings> ReadElementSettingsAsync(long tenantId, long elementId)
{
try
{
RestClient client = new RestClient(_options.Value.ElementApiBaseUrl);
RestRequest request = new RestRequest("tenants/{tenantId}/elementtypes/1cbac30c-5deb-404e-8ea8-aabc20c82aa8/elements/{elementId}", Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("elementId", elementId);
IRestResponse<PageHeaderElementSettings> response = await client.ExecuteAsync<PageHeaderElementSettings>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (ElementClientException)
{
throw;
}
catch (Exception ex)
{
throw new ElementClientException("Element API failed", ex);
}
}
public async Task<PageHeaderElementContent> ReadElementContentAsync(long tenantId, long elementId, long pageId)
{
try
{
RestClient client = new RestClient(_options.Value.ElementApiBaseUrl);
RestRequest request = new RestRequest("tenants/{tenantId}/elementtypes/1cbac30c-5deb-404e-8ea8-aabc20c82aa8/elements/{elementId}/content", Method.GET);
request.AddUrlSegment("tenantId", tenantId);
request.AddUrlSegment("elementId", elementId);
request.AddQueryParameter("pageId", pageId.ToString());
IRestResponse<PageHeaderElementContent> response = await client.ExecuteAsync<PageHeaderElementContent>(request);
CheckResponseStatus(response);
return response.Data;
}
catch (ElementClientException)
{
throw;
}
catch (Exception ex)
{
throw new ElementClientException("Element API failed", ex);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using greenlife1.BLL;
using greenlife1.UI;
using Greenlife1;
namespace greenlife1
{
public partial class MDIParent1 : Form
{
private int childFormNumber = 0;
public MDIParent1()
{
InitializeComponent();
}
private void ShowNewForm(object sender, EventArgs e)
{
Form childForm = new Form();
childForm.MdiParent = this;
childForm.Text = "Window " + childFormNumber++;
childForm.Show();
}
private void OpenFile(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
string FileName = openFileDialog.FileName;
}
}
private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
{
string FileName = saveFileDialog.FileName;
}
}
private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void CutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStrip.Visible = toolBarToolStripMenuItem.Checked;
}
private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
{
statusStrip.Visible = statusBarToolStripMenuItem.Checked;
}
private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.Cascade);
}
private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileVertical);
}
private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileHorizontal);
}
private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.ArrangeIcons);
}
private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form childForm in MdiChildren)
{
childForm.Close();
}
}
private void MDIParent1_Load(object sender, EventArgs e)
{
}
private void showAllDoctorToolStripMenuItem_Click(object sender, EventArgs e)
{
var doctorList = new DoctorList();
doctorList.MdiParent = this;
formManager.DisposeAllButThis(doctorList, this);
doctorList.WindowState = FormWindowState.Maximized;
doctorList.Show();
}
private void newDoctorToolStripMenuItem_Click(object sender, EventArgs e)
{
var doctorRegistration = new DoctorRegisterForm();
formManager.DisposeAllButThis(doctorRegistration, this);
doctorRegistration.MdiParent = this;
doctorRegistration.WindowState = FormWindowState.Maximized;
doctorRegistration.Show();
}
FormManager formManager = new FormManager();
private void doctorHomeToolStripMenuItem_Click(object sender, EventArgs e)
{
var doctorLogin = new DoctorLoginForm();
doctorLogin.MdiParent = this;
formManager.DisposeAllButThis(doctorLogin, this);
doctorLogin.WindowState = FormWindowState.Maximized;
doctorLogin.Show();
}
private void newPatientToolStripMenuItem_Click(object sender, EventArgs e)
{
var newPatient = new PatientRegisterForm();
newPatient.MdiParent = this;
formManager.DisposeAllButThis(newPatient, this);
newPatient.WindowState = FormWindowState.Maximized;
newPatient.Show();
}
private void allPatientToolStripMenuItem_Click(object sender, EventArgs e)
{
var existingpatient = new ExistingPatientForm();
existingpatient.MdiParent = this;
formManager.DisposeAllButThis(existingpatient, this);
existingpatient.WindowState = FormWindowState.Maximized;
existingpatient.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Promact.Oauth.Server.Models.ApplicationClasses
{
public class UserDetailWithProjectListAc
{
public UserAc UserAc { get; set; }
public List<ProjectAc> ListOfProject { get; set; }
}
}
|
using AutoMapper;
using iCopy.Database.Context;
using iCopy.Model.Request;
using iCopy.Model.Response;
using iCopy.SERVICES.Extensions;
using iCopy.SERVICES.IServices;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace iCopy.SERVICES.Services
{
public class CopierService : CRUDService<Database.Copier, Model.Request.Copier, Model.Request.Copier, Model.Response.Copier, Model.Request.CopierSearch, int>, ICopierService
{
private readonly AuthContext auth;
private readonly IUserService UserService;
private readonly IProfilePhotoService ProfilePhotoService;
public CopierService(
DBContext ctx,
IMapper mapper,
AuthContext auth,
IUserService UserService,
IProfilePhotoService ProfilePhotoService) : base(ctx, mapper)
{
this.auth = auth;
this.UserService = UserService;
this.ProfilePhotoService = ProfilePhotoService;
}
public override async Task<Model.Response.Copier> GetByIdAsync(int id)
{
Model.Response.Copier copier = mapper.Map<Model.Response.Copier>(await ctx.Copiers.Include(x => x.City).ThenInclude(x => x.Country).Include(x => x.Company).FirstOrDefaultAsync(x => x.ID == id));
copier.User = mapper.Map<Model.Response.ApplicationUser>(await auth.Users.FindAsync(copier.ApplicationUserId));
copier.ProfilePhoto = mapper.Map<Model.Response.ProfilePhoto>((await ctx.ApplicationUserProfilePhotos.Include(x => x.ProfilePhoto).FirstOrDefaultAsync(x => x.ApplicationUserId == copier.ApplicationUserId && x.Active))?.ProfilePhoto);
return copier;
}
public override async Task<List<Model.Response.Copier>> TakeRecordsByNumberAsync(int take = 15)
{
List<Model.Response.Copier> items = mapper.Map<List<Model.Response.Copier>>(await ctx.Copiers.Include(x => x.Company).Include(x => x.City).ThenInclude(x => x.Country).ToListAsync());
return items;
}
public override async Task<Tuple<List<Model.Response.Copier>, int>> GetByParametersAsync(CopierSearch search, string order, string nameOfColumnOrder, int start, int length)
{
var query = ctx.Copiers.Include(x => x.Company).Include(x => x.City).ThenInclude(x => x.Country).AsQueryable();
if (search.CityID != null)
query = query.Where(x => x.CityId == search.CityID);
if (search.CountryID != null)
query = query.Where(x => x.City.CountryID == search.CountryID);
if (search.CompanyID != null)
query = query.Where(x => x.CompanyId == search.CompanyID);
if (search.Active != null)
query = query.Where(x => x.Active == search.Active);
if (!string.IsNullOrWhiteSpace(search.Name))
query = query.Where(x => x.Name.Contains(search.Name));
if (nameOfColumnOrder == nameof(Database.Copier.ID))
query = query.OrderByAscDesc(x => x.ID, order);
else if (nameOfColumnOrder == nameof(Database.Copier.Name))
query = query.OrderByAscDesc(x => x.Name, order);
else if(nameOfColumnOrder == nameof(Database.Copier.CityId))
query = query.OrderByAscDesc(x => x.CityId, order);
var data = mapper.Map<List<Model.Response.Copier>>(await query.Skip(start).Take(length).ToListAsync());
return new Tuple<List<Model.Response.Copier>, int>(data, await query.CountAsync());
}
public override async Task<Model.Response.Copier> DeleteAsync(int id)
{
Database.Copier copier = await ctx.Copiers.FindAsync(id);
try
{
IEnumerable<Database.ApplicationUserProfilePhoto> copierProfile = await ctx.ApplicationUserProfilePhotos.Where(x => x.ApplicationUserId == copier.ApplicationUserId).ToListAsync();
IEnumerable<Database.ProfilePhoto> profilePhotos = await ctx.ProfilePhotos.Where(x => copierProfile.Any(y => y.ProfilePhotoId == x.ID)).ToListAsync();
if (copierProfile != null)
{
ctx.ApplicationUserProfilePhotos.RemoveRange(copierProfile);
await ctx.SaveChangesAsync();
}
if (profilePhotos != null)
{
ctx.ProfilePhotos.RemoveRange(profilePhotos);
await ctx.SaveChangesAsync();
}
ctx.Copiers.Remove(copier);
await ctx.SaveChangesAsync();
await UserService.DeleteAsync(copier.ApplicationUserId);
// TODO: Dodati log operaciju
}
catch (Exception e)
{
//TODO: Dodati log operaciju
throw e;
}
return mapper.Map<Model.Response.Copier>(copier);
}
public override async Task<Model.Response.Copier> InsertAsync(Model.Request.Copier entity)
{
Database.Copier model = mapper.Map<Database.Copier>(entity);
try
{
Model.Response.ApplicationUser user = await UserService.InsertAsync(entity.User, Model.Enum.Enum.Roles.Copier);
model.ApplicationUserId = user.ID;
ctx.Copiers.Add(model);
await ctx.SaveChangesAsync();
if (entity.ProfilePhoto != null)
{
entity.ProfilePhoto.ApplicationUserId = user.ID;
await ProfilePhotoService.InsertAsync(entity.ProfilePhoto);
}
// TODO: Dodati log operaciju
}
catch (Exception e)
{
//TODO: Dodati log operaciju
throw e;
}
return mapper.Map<Model.Response.Copier>(model);
}
public override async Task<Model.Response.Copier> UpdateAsync(int id, Model.Request.Copier entity)
{
try
{
Model.Response.Copier copier = await base.UpdateAsync(id, entity);
if (entity.ProfilePhoto != null)
{
entity.ProfilePhoto.ApplicationUserId = copier.ApplicationUserId;
await ProfilePhotoService.InsertAsync(entity.ProfilePhoto);
}
// TODO: Dodati Log
return copier;
}
catch (Exception e)
{
// TODO: Dodati log
throw e;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class FlashSequence : MonoBehaviour
{
Color32 normalColor;
public Color32 flashColor;
public bool on = false;
// Start is called before the first frame update
void Start()
{
normalColor = this.GetComponent<TextMeshProUGUI>().color;
}
// Update is called once per frame
void Update()
{
if(on)
{
this.GetComponent<TextMeshProUGUI>().color = flashColor;
}
else
{
this.GetComponent<TextMeshProUGUI>().color = normalColor;
}
}
}
|
using HaloSharp.Model.Metadata;
namespace HaloHistory.Business.Entities.Metadata
{
public class WeaponData : BaseDataEntity<long, Weapon>
{
public WeaponData()
{
}
public WeaponData(long id, Weapon data) : base(id, data)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Animator))]
public class AnimationLayerController : MonoBehaviour {
public bool _useWhiteVersion;
private Animator _anim;
// Use this for initialization
void Start ()
{
_anim = GetComponent<Animator>();
float layerWeight = _useWhiteVersion ? 1f : 0f;
_anim.SetLayerWeight(1, layerWeight);
}
}
|
using System.Collections.Generic;
namespace Webshop.Data
{
public class SupplierDto
{
//Tárolt adatok
public int SupplierId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int Multiplier { get; set; }
// Egy beszállítóhoz több termék is tartozhat
}
} |
namespace NatilleraApiDataAccess
{
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using NatilleraApiDataAccessContract;
using NatilleraApiDataAccessContract.Entidades;
using System;
public class NatilleraDBContext : IdentityDbContext<ApplicationUser>, INatilleraDBContext
{
//cuando se hereda de IdentityDbContext<ApplicationUser>, se crean las tablas para
//el manejo de usuarios.
/// <summary>
/// Initializes a new instance of the <see cref="AplicationDbContext"/> class.
/// </summary>
/// <param name="opcion">The opcion<see cref="DbContextOptions{AplicationDbContext}"/></param>
public NatilleraDBContext(DbContextOptions<NatilleraDBContext> opcion) : base(opcion)
{
}
public DbSet<Natilleras> Natilleras { get; set; }
public DbSet<TiposDocumentos> TiposDocumentos { get; set; }
public DbSet<Prestamos> Prestamos { get; set; }
public DbSet<ActividadesRecaudos> ActividadesRecaudos { get; set; }
public DbSet<Socios> Socios { get; set; }
public DbSet<NatilleraSocios> NatilleraSocios { get; set; }
public DbSet<CuotasPrestamos> CuotasPrestamos { get; set; }
public DbSet<CuotasSocios> CuotasSocios { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
///controlar la concurrencia, se valida esta propiedad en el token.
///Tema pagina 2272 pdf core 2.2
//modelBuilder.Entity<Natilleras>().Property(p => p.RowVersion).IsConcurrencyToken();
//se agrega a la columna fecha creacion un valor por defecto.
modelBuilder.Entity<Natilleras>()
.Property(b => b.FechaCreacionRow)
.HasDefaultValueSql("getdate()");
}
}
}
|
namespace NopSolutions.NopCommerce.DataAccess.Orders
{
/// <summary>
/// Represents a shopping cart
/// </summary>
public partial class DBViewedItemsCollection : BaseDBEntityCollection<DBViewedItem>
{
}
} |
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Caliburn.Micro;
using Frontend.Core.Helpers;
using Frontend.Core.Model.PreferenceEntries.Interfaces;
using Frontend.Core.Model.Preferences.Interfaces;
namespace Frontend.Core.Model.Preferences
{
/// <summary>
/// Implementation of IPreference.
/// <remarks>
/// Also implements IDataErrorInfo, which is used for validating some user input in user interface, such as
/// minimum and maximum values.
/// </remarks>
/// </summary>
public class Preference<T> : PropertyChangedBase, IPreference, IDataErrorInfo
{
/// <summary>
/// </summary>
private IList<IPreferenceEntry> entries;
/// <summary>
/// </summary>
private IPreferenceEntry selectedEntry;
private T value;
/// <summary>
/// Gets or sets the minimum value.
/// </summary>
/// <value>
/// The minimum value.
/// </value>
public T MinValue { get; set; }
/// <summary>
/// Gets or sets the maximum value.
/// </summary>
/// <value>
/// The maximum value.
/// </value>
public T MaxValue { get; set; }
/// <summary>
/// Gets or sets the current value.
/// </summary>
/// <value>
/// The value.
/// </value>
public T Value
{
get { return value; }
set
{
if (NullableComparer.AreEqual(this.value, value))
{
return;
}
this.value = value;
NotifyOfPropertyChange(() => Value);
}
}
/// <summary>
/// Gets or sets the preference name. Must match the name of the preference in configuration.txt
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the friendly preference name. Usually more readable to humans than the normal name, which tends to
/// lack - for instance - spaces.
/// </summary>
/// <value>
/// The name of the friendly.
/// </value>
public string FriendlyName { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
public string Description { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this preference has a directly editable value (as opposed to pre-defined
/// choices, for instance)
/// </summary>
/// <value>
/// <c>true</c> if yes; otherwise, <c>false</c>.
/// </value>
public bool HasDirectlyEditableValue { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this preference should be output with curly brackets instead of quotes
/// </summary>
/// <value>
/// <c>true</c> if yes; otherwise, <c>false</c>.
/// </value>
public bool useCurlyBraces { get; set; }
/// <summary>
/// Gets a value indicating whether this preference has a set of predefined choices.
/// </summary>
/// <value>
/// <c>true</c> if yes; otherwise, <c>false</c>.
/// </value>
public bool HasPreDefinedChoices
{
get { return Entries.Count > 0; }
}
/// <summary>
/// Determines if selecting multiple entries is allowed, so frontend uses checkboxes instead of radio buttons.
/// </summary>
/// <value>
/// <c>true</c> if yes; otherwise, <c>false</c>.
/// </value>
public bool AllowMultipleSelections { get; set; }
/// <summary>
/// Gets the list of pre-defined IPreferenceEntry objects. These are the pre-defined user choices, if not null.
/// </summary>
/// <value>
/// The entries.
/// </value>
public IList<IPreferenceEntry> Entries
{
get { return entries ?? (entries = new List<IPreferenceEntry>()); }
}
/// <summary>
/// Gets or sets the selected entry. Only relevant if this list has a list of Entries to choose from.
/// </summary>
/// <value>
/// The selected entry.
/// </value>
public IPreferenceEntry SelectedEntry
{
get { return selectedEntry; }
set
{
if (selectedEntry == value)
{
return;
}
selectedEntry = value;
OnSelectedEntrySet(value); //.Name;
NotifyOfPropertyChange(() => SelectedEntry);
}
}
#region [ OnSelectedEntrySet handling ]
/// <summary>
/// Handler logic for when a new selected entry is set.
/// </summary>
/// <param name="entry"></param>
/// <returns></returns>
private void OnSelectedEntrySet(IPreferenceEntry entry)
{
if (this is IDatePreference)
{
((IDatePreference) this).Value = ((IDatePreferenceEntry) entry).Name;
}
else if (this is INumericPreference)
{
((INumericPreference) this).Value = ((INumericPreferenceEntry) entry).Name;
}
else if (this is IStringPreference)
{
((IStringPreference) this).Value = ((IStringPreferenceEntry) entry).Name;
}
//return (T)entry;
}
#endregion
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine("# " + FriendlyName + ": " + Description);
AppendEntries(sb);
if (useCurlyBraces)
{
sb.AppendLine("\t" + Name + " = {" + Value + "}");
}
else
{
sb.AppendLine("\t" + Name + " = \"" + Value + "\"");
}
return sb.ToString();
}
protected void AppendEntries(StringBuilder sb)
{
if (HasPreDefinedChoices)
{
foreach (var entry in Entries)
{
sb.AppendLine("\t#\t" + entry.FriendlyName + "\t - " + entry.Description);
}
}
}
#region [ Validation ]
/// <summary>
/// Gets an error message indicating what is wrong with this object.
/// </summary>
/// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
public string Error
{
get { return null; }
}
/// <summary>
/// Gets the <see cref="System.String" /> with the specified name. Used by IDataErrorInfo
/// </summary>
/// <value>
/// The <see cref="System.String" />.
/// </value>
/// <param name="name">The name.</param>
/// <returns></returns>
public string this[string name]
{
get
{
var result = OnValidateProperty(name);
return result;
}
}
/// <summary>
/// Called when [validate property].
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns></returns>
protected virtual string OnValidateProperty(string propertyName)
{
return null;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations.Schema;
using System.Threading.Tasks;
namespace GestDep.Entities
{
public partial class CityHall {
public virtual ICollection<Person> People {
get;
set;
}
public virtual ICollection<Payment> Payments
{
get;
set;
}
public virtual ICollection<Gym> Gyms
{
get;
set;
}
public int Id
{
get;
set;
}
public String Name
{
get;
set;
}
}
} |
namespace ConstraintsInGenerics.ConstraintsExamples.HelpMaterial
{
public class CustomSum : ISum<int>
{
public int Quantity {get; set;}
}
}
|
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using NtApiDotNet.Win32;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Get the final path name for a file.</para>
/// <para type="description">This cmdlet gets the final pathname for a file.</para>
/// </summary>
/// <example>
/// <code>Get-NtFileFinalPath -File $f</code>
/// <para>Get the path for the file.</para>
/// </example>
/// <example>
/// <code>Get-NtFileFinalPath -Path "\??\c:\windows\notepad.exe"</code>
/// <para>Get the path for the file by path.</para>
/// </example>
/// <example>
/// <code>Get-NtFileFinalPath -Path "c:\windows\notepad.exe" -Win32Path</code>
/// <para>Get the path for the file by win32 path.</para>
/// </example>
/// <example>
/// <code>Get-NtFileFinalPath -Path "\??\c:\windows\notepad.exe" -FormatWin32Path</code>
/// <para>Get the path as a win32 path.</para>
/// </example>
/// <example>
/// <code>Get-NtFileFinalPath -Path "\??\c:\windows\notepad.exe" -FormatWin32Path -Flags NameGuid</code>
/// <para>Get the path as a volume GUID win32 path.</para>
/// </example>
[Cmdlet(VerbsCommon.Get, "NtFileFinalPath", DefaultParameterSetName = "Default")]
[OutputType(typeof(string))]
public class GetNtFileFinalPathCmdlet : BaseNtFilePropertyCmdlet
{
/// <summary>
/// <para type="description">Specify to format the links as Win32 paths.</para>
/// </summary>
[Parameter]
public SwitchParameter FormatWin32Path { get; set; }
/// <summary>
/// <para type="description">Specify the name format when formatting as a Win32 path.</para>
/// </summary>
[Parameter]
public Win32PathNameFlags Flags { get; set; }
/// <summary>
/// Constructor.
/// </summary>
public GetNtFileFinalPathCmdlet()
: base(FileAccessRights.Synchronize, FileShareMode.None, FileOpenOptions.None)
{
}
private protected override void HandleFile(NtFile file)
{
WriteObject(FormatWin32Path ? file.GetWin32PathName(Flags) : file.FullPath);
}
}
}
|
namespace Plus.HabboHotel.Groups
{
public enum GroupType
{
Open = 0,
Locked = 1,
Private = 2
}
} |
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Utilities.Security;
using System;
namespace NtApiDotNet.Win32.DirectoryService
{
/// <summary>
/// Interface to convert a directory object to a tree for access checking.
/// </summary>
public interface IDirectoryServiceObjectTree
{
/// <summary>
/// The name of the object.
/// </summary>
string Name { get; }
/// <summary>
/// The ID of the object.
/// </summary>
Guid Id { get; }
/// <summary>
/// Convert the schema class to an object type tree.
/// </summary>
/// <returns>The tree of object types.</returns>
ObjectTypeTree ToObjectTypeTree();
}
}
|
using CleanArch.Domain.Models;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CleanArch.Application.ViewModels
{
public class CategoryViewModel
{
public int CategoryId { get; set; }
public IFormFile File { get; set; }
public string Image { get; set; }
public string Content { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Trik;
using Trik.Collections;
using Trik.Devices;
using Trik.Sensors;
using Trik.Reactive;
namespace Лестница
{
class Program
{
static void Main(string[] args)
{
var model = new Model();
var kind = new ServoKind(stop : 0, zero : 1505000, min : 800000, max : 2210000, period : 20000000);
//{ stop = 0; zero = 1550000; min = 800000; max = 2250000; period = 20000000 }
model.ServosConfig[ServoPort.E1] = kind;
//////////////////////Отключение по кнопке
var buttons = model.Buttons;
buttons.Start();
var isEnterPressed = false;
Action<ButtonEvent> enterFlagSetter = (ButtonEvent x) =>
{
if (x.Button == ButtonEventCode.Enter)
{
isEnterPressed = true;
}
else
{
isEnterPressed = false;
}
};
////Func<string, int> func1 = (x => 0);
////Func<string, int> func2 = (x => x.Length);
////Func<string, int> func3 = x =>
//// {
//// return x.Length;
//// };
////func2.Invoke("asdasd");
////func2("asdad");
buttons.ToObservable().Subscribe(enterFlagSetter);
//////////////////////////////////// Программа
////////// PD регулятор
double k1 = 0.5; //P
double k2 = 0.03; //D
double angserv = -100; // значение сервы
int angservout = (int) angserv; // для преобразования типов
model.Accel.Start();
model.Servos[ServoPort.E1].SetPower(angservout);
Thread.Sleep(500);
int time = 300; // период цикла
double angd; // значение угла по акселерометру
double ang = 90; // необходимое значение угла трика
double dev = 0; //производная
ang*=Math.PI/180;
angserv*=90/100*Math.PI/180;
//Console.WriteLine("Start");
while (!isEnterPressed)
{
angd = Math.Atan2(model.Accel.Read().X, model.Accel.Read().Z);
dev = (angd - dev) / time*1000;
angserv += k1 * (ang - angd) - k2 * dev;
dev = angd;
if (Math.Abs(angserv) > 100)
angserv = Math.Sign(angserv) * 100;
angservout = (int)(angserv * 180 / Math.PI * 100 / 90);
model.Servos[ServoPort.E1].SetPower(angservout);
//Console.Write("angd: "); Console.WriteLine(angd * 180 / Math.PI);
//Console.Write("angserv: "); Console.WriteLine(angserv * 180 / Math.PI);
Thread.Sleep(time);
}
model.Accel.Stop();
Thread.Sleep(300);
}
}
}
|
using Calculator.Equation;
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
MathObject eq = new MathObject();
GatheringInput(eq);
}
public static void GatheringInput(MathObject eq)
{
Console.WriteLine("Welcome to my VHS app \n");
Console.WriteLine("Type A - for Addition \n");
Console.WriteLine("Type B - for Subtraction \n");
Console.WriteLine("Type C - for Multiplication \n");
Console.WriteLine("Type D - for Division \n");
eq.op = Console.ReadLine().ToUpper();
eq.newOperation = DetermineOperation(eq.op);
Console.WriteLine("Thank you \n");
Console.WriteLine("Please enter your first value: ");
eq.value1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Thank you \n");
Console.WriteLine("Please enter your second value: ");
eq.value2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Thank you \n");
Console.WriteLine("Ok, your equation is " + eq.value1 + eq.newOperation + eq.value2);
Console.WriteLine("Hit Enter to continue");
Console.ReadLine();
}
public static string DetermineOperation(string op)
{
if (op == null)
{
throw new ArgumentNullException(nameof(op));
}
string opValue;
switch (op)
{
case "A":
opValue = " + ";
return opValue;
case "B":
opValue = " - ";
return opValue;
case "C":
opValue = " * ";
return opValue;
case "D":
opValue = " / ";
return opValue;
default:
throw new FormatException();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace LePapeoGenNHibernate.Exceptions
{
public class ModelException : SystemException, ISerializable
{
public ModelException()
: base ()
{
// Add implementation (if required)
}
public ModelException(string message)
: base (message)
{
// Add Implementation (if required)
}
public ModelException(string message, System.Exception inner)
: base (message, inner)
{
// Add implementation (if required)
}
protected ModelException(SerializationInfo info, StreamingContext context)
: base (info, context)
{
// Add implementation (if required)
}
}
}
|
using ReadyGamerOne.Script;
using ReadyGamerOne.MemorySystem;
namespace PurificationPioneer.Script
{
public partial class PurificationPioneerMgr : AbstractGameMgr<PurificationPioneerMgr>
{
protected override IResourceLoader ResourceLoader => ResourcesResourceLoader.Instance;
protected override IAssetConstUtil AssetConstUtil => Utility.AssetConstUtil.Instance;
partial void OnSafeAwake();
protected override void OnStateIsNull()
{
base.OnStateIsNull();
OnSafeAwake();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayInteractor : MonoBehaviour
{
public float interactionDistance = 3f;
Transform _selection;
public string selectableTag;
// Update is called once per frame
void Update()
{
if (_selection != null)
{
_selection.GetComponent<IInteractable>()?.OnHoverExit();
_selection = null;
}
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit,interactionDistance))
{
var selection = hit.transform;
if (selection.CompareTag(selectableTag))
{
selection.GetComponent<IInteractable>()?.OnHoverEnter();
selection.GetComponent<IInteractable>()?.OnClick();
}
_selection = selection;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace d07_adv_concept
{
class Program
{
static void Main(string[] args)
{
//DemoMethods d = new DemoMethods();
//d.demo_anonymous_method();
//Console.WriteLine("Nhap 1 chuoi ky tu bat ky : ");
//string s = Console.ReadLine().Trim();
//Console.WriteLine($"Chuoi sau khi goi ham: {s.FirstUpperCase()}");
}
}
}
|
using DapperDB.Dal.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.FtpClient;
using System.Text;
using System.Threading.Tasks;
namespace Tools
{
public class FtpHelper
{
/// <summary>
/// 连接FTP服务器函数
/// </summary>
/// <param name="strServer">服务器IP</param>
/// <param name="strUser">用户名</param>
/// <param name="strPassword">密码</param>
public bool FTPIsConnected(string strServer, string strUser, string strPassword)
{
using (FtpClient ftp = new FtpClient())
{
ftp.Host = strServer;
ftp.Credentials = new NetworkCredential(strUser, strPassword);
ftp.Connect();
return ftp.IsConnected;
}
}
/// <summary>
/// FTP下载文件
/// </summary>
/// <param name="strServer">服务器IP</param>
/// <param name="strUser">用户名</param>
/// <param name="strPassword">密码</param>
/// <param name="Serverpath">服务器路径,例子:"/Serverpath/"</param>
/// <param name="localpath">本地保存路径</param>
/// <param name="filetype">所下载的文件类型,例子:".rte"</param>
/// <param name="time">0:当天 1:前一天</param>
public FTPIsdownloadObj FTPIsdownload(int time, string strServer, string strUser, string strPassword, string Serverpath, string localpath, string filetype)
{
List<string> documentname = new List<string>();
bool DownloadStatus = false;
if (Directory.Exists(localpath))
FtpHelper.DelectDir(localpath);
FtpClient ftp = new FtpClient();
ftp.Host = strServer;
ftp.Credentials = new NetworkCredential(strUser, strPassword);
ftp.Connect();
string path = Serverpath;
string destinationDirectory = localpath;
if (Directory.Exists(destinationDirectory))
{
#region 从FTP服务器下载文件
foreach (var ftpListItem in ftp.GetListing(path, FtpListOption.Modify | FtpListOption.Size)
.Where(ftpListItem => string.Equals(Path.GetExtension(ftpListItem.Name), filetype)
&& isExist(ftpListItem.Name, time) && isDownloaded(ftpListItem.Name)))
{
string destinationPath = string.Format(@"{0}\{1}", destinationDirectory, ftpListItem.Name);
using (Stream ftpStream = ftp.OpenRead(ftpListItem.FullName))
using (FileStream fileStream = File.Create(destinationPath, (int)ftpStream.Length))
{
var buffer = new byte[200 * 1024];
int count;
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
documentname.Add(ftpListItem.Name);
}
#endregion
#region 验证本地文件数量是否匹配
string[] files = Directory.GetFiles(localpath, "*" + filetype);
int filenumber = 0;
foreach (string strfilename in files)
{
foreach (string strrecievefile in documentname)
{
if (strrecievefile == Path.GetFileName(strfilename))
{
filenumber++;
break;
}
}
}
if (filenumber == documentname.Count)
{
DownloadStatus = true;
}
#endregion
}
LogHelper.WriteLog("DownloadStatus", "STATUS:" + DownloadStatus);
return new FTPIsdownloadObj() { Status = DownloadStatus, DocumentName = documentname };
}
/// <summary>
/// 判断文件名是否正确
/// </summary>
/// <param name="fileName"></param>
/// <param name="time">0:当天 1:前一天</param>
/// <returns></returns>
private static bool isExist(string fileName, int time)
{
string str = "Geox2_L2W_" + DateTime.Now.Year + "y" + DateTime.Now.Month + "m" + (DateTime.Now.Day - time) + "d";
return fileName.Contains(str);
}
/// <summary>
/// 判断文件是否已下载
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool isDownloaded(string fileName)
{
return new SYS_FileDownloadLogDap().GetByName(fileName);
}
/// <summary>
/// 删除所有文件
/// </summary>
/// <param name="srcPath"></param>
public static void DelectDir(string srcPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
File.Delete(i.FullName); //删除指定文件
}
}
}
catch (Exception e)
{
throw;
}
}
/// <summary>
/// 判断文件是否占用
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public bool IsFileInUse(string path)
{
bool inUse = true;
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.None);
inUse = false;
}
catch
{
}
finally
{
if (fs != null)
fs.Close();
}
return inUse;//true表示正在使用,false没有使用
}
}
public class FTPIsdownloadObj
{
public bool Status { get; set; }
public List<string> DocumentName { get; set; }
}
}
|
using System.Collections.Generic;
using Abp.Runtime.Session;
using Abp.Timing.Timezone;
using eForm.DataExporting.Excel.EpPlus;
using eForm.EFlight.Dtos;
using eForm.Dto;
using eForm.Storage;
namespace eForm.EFlight.Exporting
{
public class FlightInformationsExcelExporter : EpPlusExcelExporterBase, IFlightInformationsExcelExporter
{
private readonly ITimeZoneConverter _timeZoneConverter;
private readonly IAbpSession _abpSession;
public FlightInformationsExcelExporter(
ITimeZoneConverter timeZoneConverter,
IAbpSession abpSession,
ITempFileCacheManager tempFileCacheManager) :
base(tempFileCacheManager)
{
_timeZoneConverter = timeZoneConverter;
_abpSession = abpSession;
}
public FileDto ExportToFile(List<GetFlightInformationForViewDto> flightInformations)
{
return CreateExcelPackage(
"FlightInformations.xlsx",
excelPackage =>
{
var sheet = excelPackage.Workbook.Worksheets.Add(L("FlightInformations"));
sheet.OutLineApplyStyle = true;
AddHeader(
sheet,
L("DestinationDeparture"),
L("DestinationArraival"),
L("Date"),
L("TImeDeparture"),
L("TimeArriaval"),
L("FlightId")
);
AddObjects(
sheet, 2, flightInformations,
_ => _.FlightInformation.DestinationDeparture,
_ => _.FlightInformation.DestinationArraival,
_ => _timeZoneConverter.Convert(_.FlightInformation.Date, _abpSession.TenantId, _abpSession.GetUserId()),
_ => _.FlightInformation.TImeDeparture,
_ => _.FlightInformation.TimeArriaval,
_ => _.FlightInformation.FlightId
);
var dateColumn = sheet.Column(3);
dateColumn.Style.Numberformat.Format = "yyyy-mm-dd";
dateColumn.AutoFit();
});
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace CHSystem.ViewModels.Locations
{
public class LocationsEditVM : EditVM
{
[Required, StringLength(60, MinimumLength = 3, ErrorMessage = "Name must be at least 3 symbols")]
public string Name { get; set; }
[Required]
public string Address { get; set; }
[Required]
public int Floor { get; set; }
[Required]
public int RoomNumber { get; set; }
}
} |
using AutoMapper.Mappers;
using Braspag.Api.Models;
using Braspag.Domain.DTO;
using Braspag.Domain.Entities;
namespace Braspag.Api.Mapper
{
public class AutoMapperConfig
{
public static void RegisterMappings()
{
AutoMapper.Mapper.Initialize(x => {
x.CreateMap<Adquirentes, AdquirenteModels>();
x.CreateMap<AdquirenteModels,AdquirentesDto >()
.ForMember(opt => opt._id, opt => opt.Ignore());
x.CreateMap<Adquirentes, AdquirentesDto>();
x.CreateMap<PagamentoModels, PagamentoDto>()
.ForMember(opt => opt._id, opt => opt.Ignore());
x.CreateMap<Pagamento, PagamentoModels>();
x.CreateMap<Pagamento, PagamentoRetornoModels>();
});
AutoMapper.Mapper.AssertConfigurationIsValid();
}
}
} |
using System;
using System.Collections.Generic;
using Models;
namespace Interfaces
{
public interface IWeatherForecast
{
DateTime Date { get; set; }
int TemperatureC { get; set; }
string Summary { get; set; }
public IEnumerable<WeatherForecast> GetWeatherForecasts();
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// If defined, the item has at least one socket.
/// </summary>
[DataContract]
public partial class DestinyDefinitionsDestinyItemSocketBlockDefinition : IEquatable<DestinyDefinitionsDestinyItemSocketBlockDefinition>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyDefinitionsDestinyItemSocketBlockDefinition" /> class.
/// </summary>
/// <param name="Detail">This was supposed to be a string that would give per-item details about sockets. In practice, it turns out that all this ever has is the localized word \"details\". ... that's lame, but perhaps it will become something cool in the future..</param>
/// <param name="SocketEntries">Each socket on an item is defined here. Check inside for more info..</param>
/// <param name="SocketCategories">A convenience property, that refers to the sockets in the \"sockets\" property, pre-grouped by category and ordered in the manner that they should be grouped in the UI. You could form this yourself with the existing data, but why would you want to? Enjoy life man..</param>
public DestinyDefinitionsDestinyItemSocketBlockDefinition(string Detail = default(string), List<DestinyDefinitionsDestinyItemSocketEntryDefinition> SocketEntries = default(List<DestinyDefinitionsDestinyItemSocketEntryDefinition>), List<DestinyDefinitionsDestinyItemSocketCategoryDefinition> SocketCategories = default(List<DestinyDefinitionsDestinyItemSocketCategoryDefinition>))
{
this.Detail = Detail;
this.SocketEntries = SocketEntries;
this.SocketCategories = SocketCategories;
}
/// <summary>
/// This was supposed to be a string that would give per-item details about sockets. In practice, it turns out that all this ever has is the localized word \"details\". ... that's lame, but perhaps it will become something cool in the future.
/// </summary>
/// <value>This was supposed to be a string that would give per-item details about sockets. In practice, it turns out that all this ever has is the localized word \"details\". ... that's lame, but perhaps it will become something cool in the future.</value>
[DataMember(Name="detail", EmitDefaultValue=false)]
public string Detail { get; set; }
/// <summary>
/// Each socket on an item is defined here. Check inside for more info.
/// </summary>
/// <value>Each socket on an item is defined here. Check inside for more info.</value>
[DataMember(Name="socketEntries", EmitDefaultValue=false)]
public List<DestinyDefinitionsDestinyItemSocketEntryDefinition> SocketEntries { get; set; }
/// <summary>
/// A convenience property, that refers to the sockets in the \"sockets\" property, pre-grouped by category and ordered in the manner that they should be grouped in the UI. You could form this yourself with the existing data, but why would you want to? Enjoy life man.
/// </summary>
/// <value>A convenience property, that refers to the sockets in the \"sockets\" property, pre-grouped by category and ordered in the manner that they should be grouped in the UI. You could form this yourself with the existing data, but why would you want to? Enjoy life man.</value>
[DataMember(Name="socketCategories", EmitDefaultValue=false)]
public List<DestinyDefinitionsDestinyItemSocketCategoryDefinition> SocketCategories { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyDefinitionsDestinyItemSocketBlockDefinition {\n");
sb.Append(" Detail: ").Append(Detail).Append("\n");
sb.Append(" SocketEntries: ").Append(SocketEntries).Append("\n");
sb.Append(" SocketCategories: ").Append(SocketCategories).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyDefinitionsDestinyItemSocketBlockDefinition);
}
/// <summary>
/// Returns true if DestinyDefinitionsDestinyItemSocketBlockDefinition instances are equal
/// </summary>
/// <param name="input">Instance of DestinyDefinitionsDestinyItemSocketBlockDefinition to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyDefinitionsDestinyItemSocketBlockDefinition input)
{
if (input == null)
return false;
return
(
this.Detail == input.Detail ||
(this.Detail != null &&
this.Detail.Equals(input.Detail))
) &&
(
this.SocketEntries == input.SocketEntries ||
this.SocketEntries != null &&
this.SocketEntries.SequenceEqual(input.SocketEntries)
) &&
(
this.SocketCategories == input.SocketCategories ||
this.SocketCategories != null &&
this.SocketCategories.SequenceEqual(input.SocketCategories)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Detail != null)
hashCode = hashCode * 59 + this.Detail.GetHashCode();
if (this.SocketEntries != null)
hashCode = hashCode * 59 + this.SocketEntries.GetHashCode();
if (this.SocketCategories != null)
hashCode = hashCode * 59 + this.SocketCategories.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using GAP.Seguros.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GAP.Procesos.Model.Repository.TipoCubrimientos
{
public interface ITipoCrubimientosRepository
{
List<TipoCubrimiento> ObtenerTipoCubrimientos();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using InfirmerieBO; // Référence la couche BO
using InfirmerieDAL; // Référence la couche DAL
namespace InfirmerieBLL
{
public class GestionMedicaments
{
private static GestionMedicaments uneGestionMedicaments; // objet BLL
// Accesseur en lecture
public static GestionMedicaments GetGestionUtilisateurs()
{
if (uneGestionMedicaments == null)
{
uneGestionMedicaments = new GestionMedicaments();
}
return uneGestionMedicaments;
}
// Définit la chaîne de connexion grâce à la méthode SetchaineConnexion de la DAL
public static void SetchaineConnexion(ConnectionStringSettings chset)
{
string chaine = chset.ConnectionString;
ConnexionBD.GetConnexionBD().SetChaineConnexion(chaine);
}
// Méthode qui renvoie un objet Medicament en faisant appel à la méthode GetMedicaments() de la DAL
public static int verifMedicament(string libelle)
{
Medicament unMedicament = new Medicament(libelle);
return MedicamentDAO.GetMedicament(unMedicament);
}
public List<string> recupererInfosMedicaments()
{
List<string> lesMedicaments = new List<string>();
MedicamentDAO infosMedicament = new MedicamentDAO();
lesMedicaments = infosMedicament.recupererMedicaments();
return lesMedicaments;
}
// Méthode qui renvoit un objet Medicament en faisant appel à la méthode GetMedicaments() de la DAL
public static int extractInfosMedicament(string libelle)
{
Medicament unMedicament = new Medicament(libelle);
return MedicamentDAO.GetMedicamentInfos(unMedicament);
}
public static string SuppressionMedicament(int idMedicament)
{
string MessageAlert;
MedicamentDAO.SupprimerMedicament(idMedicament);
MessageAlert = "L'élève a bien été supprimé.";
return MessageAlert;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessThatNumber
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("I want to play a game human...");
GuessThatNumber();
Console.WriteLine("Test your luck again human?");
string answer = Console.ReadLine();
string lower = answer.ToLower();
if (lower == "yes")
{
GuessThatNumber();
}
else
{
Console.WriteLine("Shame on you meat bag");
}
//keep the console open
Console.ReadKey();
}
static void GuessThatNumber()
{
Console.WriteLine("I have a number...");
//computer generates a random number between 1 and 100
Random compGuess = new Random();
int randomNum = compGuess.Next(1,101);
//counts the amount of guesses you make starting with 0
int count = 0;
//converting human guess string to an integer
int newInput = 0;
Console.WriteLine("What is your guess human?");
while (newInput != randomNum)
{
//reads the human guess
string yourGuess = Console.ReadLine();
//changes string to int
int input = int.Parse(yourGuess);
//seeing if yourGuess is less than the randomNum
if (input < randomNum)
{
//prints to the console to guess higher
Console.WriteLine("Guess higher minion.");
//adds 1 to the count
count++;
}
//if yourGuess is greater than randomNum
else if (input > randomNum)
{
//print out guess lower
Console.WriteLine("Guess lower minion.");
//add 1 to the count
count++;
}
else if (input == randomNum)
{
//print out you are a winner
Console.WriteLine("You guessed it. It only took you " + (count + 1) + " guesses meat bag.");
}
}
}
}
}
|
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using SKT.MES.Model;
using SKT.MES.DAL.Marshal;
using SKT.WMS.WMSBasicfile.Model;
namespace SKT.WMS.WMSBasicfile.BLL
{
public class WMSRdStyle
{
private Int32 recordCount = 0;
/// <summary>
/// 编辑(添加或更新) WMSRdStyle 信息。
/// </summary>
/// <param name="entity">WMSRdStyle 实体对象。</param>
public Int32 Edit(WMSRdStyleInfo entity)
{
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@Id", SqlDbType.Int),
new SqlParameter("@RdCode", SqlDbType.NVarChar, 5),
new SqlParameter("@RdName", SqlDbType.NVarChar, 12),
new SqlParameter("@RdFlag", SqlDbType.Int),
new SqlParameter("@CreatePerson", SqlDbType.Int),
new SqlParameter("@ModifyPerson", SqlDbType.Int)
};
parms[0].Value = entity.Id;
parms[1].Value = entity.RdCode;
parms[2].Value = entity.RdName;
parms[3].Value = entity.RdFlag;
parms[4].Value = entity.CreatePerson;
parms[5].Value = entity.ModifyPerson;
SQLHelper.ExecuteNonQueryStoredProcedure(SQLHelper.MESConnString, "WMSRdStyleEdit", parms);
return (Int32)parms[0].Value;
}
/// <summary>
/// 根据 WMSRdStyleId 字符串删除 WMSRdStyle 信息。
/// </summary>
/// <param name="idString">WMSRdStyleId 字符串。</param>
/// <returns>日志内容。</returns>
public void Delete(String idString, String userName)
{
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@IdString", SqlDbType.VarChar, 1000),
new SqlParameter("@UserName", SqlDbType.VarChar, 20)
};
parms[0].Value = idString;
parms[1].Value = userName;
SQLHelper.ExecuteNonQueryStoredProcedure(SQLHelper.MESConnString, "WMSRdStyleDelete", parms);
}
/// <summary>
/// 根据 WMSRdStyleId 获取实体信息。
/// </summary>
/// <param name="wMSRdStyleId">WMSRdStyleId。</param>
/// <returns>WMSRdStyle 实体对象。</returns>
public WMSRdStyleInfo GetInfo(Int32 wMSRdStyleId)
{
WMSRdStyleInfo entity = null;
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@FieldValue", SqlDbType.NVarChar, 50),
new SqlParameter("@IsByID", SqlDbType.Bit)
};
parms[0].Value = wMSRdStyleId;
parms[1].Value = true;
using (SqlDataReader rdr = SQLHelper.ExecuteReaderStoredProcedure(SQLHelper.MESConnString, "WMSRdStyleGetInfo", parms))
{
if (rdr.Read())
{
entity = new WMSRdStyleInfo(rdr.GetInt32(0), rdr.GetString(1), rdr.GetString(2), rdr.GetInt32(3), rdr.GetInt32(4),
rdr.GetDateTime(5), rdr.GetInt32(6), rdr.GetDateTime(7), rdr.GetString(8));
}
rdr.Close();
}
return entity;
}
/// <summary>
/// 根据 字段值 获取实体信息。
/// </summary>
/// <param name="fieldValue">字段值。</param>
/// <returns>WMSRdStyle 实体对象。</returns>
public WMSRdStyleInfo GetInfo(String fieldValue)
{
WMSRdStyleInfo entity = null;
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@FieldValue", SqlDbType.NVarChar, 50),
new SqlParameter("@IsByID", SqlDbType.Bit)
};
parms[0].Value = fieldValue;
parms[1].Value = false;
using (SqlDataReader rdr = SQLHelper.ExecuteReaderStoredProcedure(SQLHelper.MESConnString, "WMSRdStyleGetInfo", parms))
{
if (rdr.Read())
{
}
rdr.Close();
}
return entity;
}
/// <summary>
/// 分页获取 WMSRdStyle 资料。
/// </summary>
/// <param name="startRow">起始行。</param>
/// <param name="maxRows">最大行数。</param>
/// <param name="sortExpression">排序表达式。</param>
/// <param name="searchSettings">搜索配置信息。</param>
/// <param name="wMSRdStyleCount">wMSRdStyle 总数。</param>
/// <returns>WMSRdStyle 列表。</returns>
public List<WMSRdStyleInfo> GetAll(Int32 startRow, Int32 maxRows, String sortExpression, SearchSettings searchSettings)
{
List<WMSRdStyleInfo> list = new List<WMSRdStyleInfo>();
WMSRdStyleInfo entity = null;
SqlParameter[] parms = SQLHelper.CreateCommonPagingStoredProcedureParameters(startRow, maxRows, "WMSRdStyle", "Id",
"[Id], [RdCode], [RdName], [RdFlag], [CreatePerson], [CreateDateTime], [ModifyPerson], [ModifyDateTime], [Remark]", searchSettings, sortExpression);
using (SqlDataReader rdr = SQLHelper.ExecuteReaderStoredProcedure(SQLHelper.MESConnString, "Common_GetPageRecords", parms))
{
while (rdr.Read())
{
entity = new WMSRdStyleInfo(rdr.GetInt32(0), rdr.GetString(1), rdr.GetString(2), rdr.GetInt32(3), rdr.GetInt32(4),
rdr.GetDateTime(5), rdr.GetInt32(6), rdr.GetDateTime(7), rdr.GetString(8));
list.Add(entity);
}
rdr.Close();
}
recordCount = Convert.ToInt32(parms[parms.Length - 1].Value);
return list;
}
public Int32 GetCount(SearchSettings searchSettings)
{
return this.recordCount;
}
}
} |
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Framework.Db;
using Framework.Entity;
using Framework.Metadata;
using Framework.Remote.Mobile;
using Framework.Utils;
namespace Framework.Remote
{
public partial class CxAppServer
{
/// <summary>
/// Returns entity by primary keys.
/// </summary>
/// <param name="marker">Server operation identifier.</param>
/// <param name="prms">Query parameters.</param>
/// <returns>Initialized CxModel</returns>
public CxModel GetEntityFromPk(Guid marker, CxQueryParams prms)
{
try
{
CxEntityUsageMetadata entityUsage = m_Holder.EntityUsages[prms.EntityUsageId];
CxModel model = new CxModel(marker);
using (CxDbConnection conn = CxDbConnections.CreateEntityConnection())
{
// Recognizing if the request requires to create a new entity.
bool createNew = false;
foreach (KeyValuePair<string, object> pkPair in prms.PrimaryKeysValues)
{
if (pkPair.Value is int && (int)pkPair.Value == int.MinValue)
{
createNew = true;
break;
}
}
// Obtaining the parent entity.
CxBaseEntity parent = null;
if (prms.ParentEntityUsageId != null)
{
CxEntityUsageMetadata parentEntityUsage = m_Holder.EntityUsages[prms.ParentEntityUsageId];
IList<string> parentPkNames = parentEntityUsage.PrimaryKeyIds;
IxValueProvider parentVlProvider =
CxQueryParams.CreateValueProvider(prms.ParentPks);
parent = CxBaseEntity.CreateAndReadFromDb
(parentEntityUsage,
conn,
parentVlProvider);
}
// Obtaining the value provider.
IList<string> pkNames = entityUsage.PrimaryKeyIds;
// Obtaining the entity.
CxBaseEntity entityFromPk;
if (!createNew)
{
IxValueProvider paramsProvider;
if (prms.EntityValues != null && prms.EntityValues.Count > 0)
{
paramsProvider =
CxValueProviderCollection.Create(
CxQueryParams.CreateValueProvider(prms.EntityValues),
m_Holder.ApplicationValueProvider);
}
else
{
paramsProvider =
CxValueProviderCollection.Create(
CxQueryParams.CreateValueProvider(prms.PrimaryKeysValues),
m_Holder.ApplicationValueProvider);
}
entityFromPk = CxBaseEntity.CreateAndReadFromDb(entityUsage, conn, paramsProvider);
}
else
{
entityFromPk = CxBaseEntity.CreateWithDefaults(entityUsage, parent, conn);
}
CxBaseEntity[] entities = entityFromPk == null ? new CxBaseEntity[0] :
new[] { entityFromPk };
Dictionary<string, CxClientRowSource> unfilteredRowSources;
List<CxClientRowSource> filteredRowSources;
GetDynamicRowSources(out unfilteredRowSources, out filteredRowSources, entities, entityUsage);
model = new CxModel
{
Marker = marker,
EntityUsageId = entityUsage.Id,
UnfilteredRowSources = unfilteredRowSources,
FilteredRowSources = filteredRowSources,
TotalDataRecordAmount = entities.Length,
IsNewEntity = createNew
};
model.SetData(entityUsage, entities, conn);
model.EntityMarks = new CxClientEntityMarks();
if (!createNew)
{
UpdateRecentItems(conn, model);
CxAppServerContext context = new CxAppServerContext();
CxEntityMark alreadyPresents = context.EntityMarks.Find(entityFromPk, NxEntityMarkType.Recent,
context["APPLICATION$APPLICATIONCODE"].ToString());
if (alreadyPresents != null)
{
context.EntityMarks.RecentItems.Remove(alreadyPresents);
model.EntityMarks.RemovedRecentItems.Add(new CxClientEntityMark(alreadyPresents));
}
context.EntityMarks.AddMark(entityFromPk, NxEntityMarkType.Open, true, prms.OpenMode,
context["APPLICATION$APPLICATIONCODE"].ToString());
model.EntityMarks.AllRecentItems.Clear();
foreach (CxEntityMark recentItem in context.EntityMarks.RecentItems)
{
model.EntityMarks.AllRecentItems.Add(new CxClientEntityMark(recentItem));
}
}
else
{
CxAppServerContext context = new CxAppServerContext();
model.EntityMarks.AllRecentItems.Clear();
foreach (CxEntityMark recentItem in context.EntityMarks.RecentItems)
{
model.EntityMarks.AllRecentItems.Add(new CxClientEntityMark(recentItem));
}
}
}
InitApplicationValues(model.ApplicationValues);
return model;
}
catch (Exception ex)
{
CxExceptionDetails exceptionDetails = new CxExceptionDetails(ex);
CxModel model = new CxModel { Error = exceptionDetails };
return model;
}
}
//----------------------------------------------------------------------------
public void GetDynamicRowSources
(out Dictionary<string, CxClientRowSource> unfilteredRowSources,
out List<CxClientRowSource> filteredRowSources,
CxBaseEntity[] entities,
CxEntityUsageMetadata meta
)
{
unfilteredRowSources = new Dictionary<string, CxClientRowSource>();
filteredRowSources = new List<CxClientRowSource>();
using (CxDbConnection connection = CxDbConnections.CreateEntityConnection())
{
foreach (CxBaseEntity entity in entities)
{
foreach (CxAttributeMetadata attributeMetadata in meta.Attributes)
{
if ((meta.GetAttributeOrder(NxAttributeContext.Edit).OrderAttributes.Contains(attributeMetadata) ||
meta.GetAttributeOrder(NxAttributeContext.GridVisible).OrderAttributes.Contains(attributeMetadata)) &&
attributeMetadata.RowSource != null &&
!string.IsNullOrEmpty(attributeMetadata.RowSource.EntityUsageId))
{
if (unfilteredRowSources.ContainsKey(attributeMetadata.RowSourceId.ToUpper()))
{
continue;
}
IList<CxComboItem> items = attributeMetadata.RowSource.GetList(
null,
connection,
attributeMetadata.RowSourceFilter,
entity,
!CxEditController.GetIsMandatory(attributeMetadata, entity));
CxClientRowSource rs = new CxClientRowSource(items, entity, attributeMetadata);
if (rs.IsFilteredRowSource)
{
filteredRowSources.Add(rs);
}
else
{
unfilteredRowSources.Add(rs.RowSourceId.ToUpper(), rs);
}
}
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using truckeventsXamPL.Models;
using truckeventsXamPL.Util;
using truckeventsXamPL.ViewlCells;
using truckeventsXamPL.ViewModels;
using truckeventsXamPL.WS;
using Xamarin.Forms;
namespace truckeventsXamPL.Pages.Vendas
{
public class Nova_Venda_Page : ContentPage
{
StackLayout sl_principal;
StackLayout sl_hori_total;
Loading_Layout loading;
ListView listV_produtos;
Label l_total;
Label l_total_h;
ObservableCollection<ProdutoVendaViewModel> ProdutosVendaViewModel;
ToolbarItem toolbar_finalizar;
ToolbarItem toolbar_cancelar;
Venda _venda;
Evento _evento;
public Nova_Venda_Page(Venda venda, Evento evento)
{
this._venda = venda;
this._evento = evento;
this.Title = "Nova Venda";
VCell_Venda_Produto.AdicionaQuantidadeHandler += VCell_Venda_Produto_AdicionaQuantidadeHandler;
VCell_Venda_Produto.DiminuiQuantidadeHandler += VCell_Venda_Produto_DiminuiQuantidadeHandler;
loading = new Loading_Layout();
ProdutosVendaViewModel = new ObservableCollection<ProdutoVendaViewModel>();
l_total = new Label() { Text = "Total R$ 0 ", HorizontalOptions = LayoutOptions.CenterAndExpand, TextColor = Color.White, FontAttributes = FontAttributes.Bold };
listV_produtos = new ListView() { Margin = 5 };
listV_produtos.ItemsSource = ProdutosVendaViewModel;
listV_produtos.ItemTapped += ListV_produtos_ItemTapped;
listV_produtos.ItemTemplate = new DataTemplate(typeof(VCell_Venda_Produto));
sl_hori_total = new StackLayout() { Padding = 5, BackgroundColor = Color.ForestGreen, Orientation = StackOrientation.Horizontal, Children = { l_total } };
toolbar_finalizar = new ToolbarItem("Finalizar", "", Finalizar, ToolbarItemOrder.Default);
toolbar_cancelar = new ToolbarItem("Cancelar", "", Cancelar, ToolbarItemOrder.Default);
sl_principal = new StackLayout()
{
Children =
{
sl_hori_total,
listV_produtos
}
};
this.ToolbarItems.Add(toolbar_cancelar);
this.ToolbarItems.Add(toolbar_finalizar);
this.Content = sl_principal;
PopulaProdutos();
}
private async void Cancelar()
{
var resultado = await Utilidades.DialogReturn("Deseja cancelar esta venda?");
if (resultado)
{
Utilidades.removeDaStackPaginaAtualNavigation(App.Nav);
}
}
private void Finalizar()
{
double totalvenda = double.Parse(l_total.Text.Replace("Total R$ ", ""));
_venda.Total = totalvenda;
var produtosEscolhidos = ProdutosVendaViewModel.Where(vm => vm.Quantidade > 0);
var venda_produtos = from produtoViewModel in produtosEscolhidos
select new Venda_Produto
{
Produto = produtoViewModel.Produto,
Id_produto = produtoViewModel.Produto.Id.Value,
Quantidade = produtoViewModel.Quantidade,
ValorTotal = produtoViewModel.Total,
Id_venda = _venda.Id
};
_venda.Venda_Produtos = venda_produtos.ToList();
App.Nav.Navigation.PushAsync(new Resumo_Venda_Page(_venda, _evento));
}
private bool ValidacaoFinalizacaoVenda(Venda venda)
{
if (venda.Venda_Produtos == null || !venda.Venda_Produtos.Any()) return false;
return true;
}
private void ListV_produtos_ItemTapped(object sender, ItemTappedEventArgs e)
{
var listview = sender as ListView;
listview.SelectedItem = null;
}
private void VCell_Venda_Produto_DiminuiQuantidadeHandler(object sender, Events.AlteraQuantidadeProdutoArgs e)
{
CalculaTotais();
}
private void VCell_Venda_Produto_AdicionaQuantidadeHandler(object sender, Events.AlteraQuantidadeProdutoArgs e)
{
CalculaTotais();
}
private async void PopulaProdutos()
{
object result = null;
loading.Enable(this);
await Task.Factory.StartNew(async () =>
{
result = await WSOpen.Get<List<Produto>>(Constantes.WS_PRODUTOS);
});
if (result.GetType() == typeof(string)) { await DisplayAlert("Erro", (string)result, "Ok"); return; }
var produtos = result as List<Produto>;
if (produtos != null && produtos.Any())
foreach (var produto in produtos) ProdutosVendaViewModel.Add(new ProdutoVendaViewModel(produto));
loading.Disable(this, sl_principal);
}
private void CalculaTotais()
{
double total = ProdutosVendaViewModel.Where(vm => vm.Quantidade > 0).Sum(vm => vm.Total);
l_total.Text = string.Format("Total R$ {0}", total);
}
}
}
|
namespace Plus.Communication.Packets.Outgoing.Users
{
internal class UpdateUsernameComposer : MessageComposer
{
public string Username { get; }
public UpdateUsernameComposer(string username)
: base(ServerPacketHeader.UpdateUsernameMessageComposer)
{
Username = username;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(0);
packet.WriteString(Username);
packet.WriteInteger(0);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IncDecTestApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("증감연산자 테스트");
int result = 26;
Console.WriteLine($"현재 숫자는 {result}");
result += 3;
Console.WriteLine($"현재 숫자는 {result}");
result -= 10;
Console.WriteLine($"현재 숫자는 {result}");
Console.WriteLine($"현재 (후치증감)숫자는 {result++}");
Console.WriteLine($"현재 (전치증감)숫자는 {++result}");
}
}
} |
using Arch.Data.DbEngine.Providers;
using System;
namespace Arch.Data.Common.Cat
{
public interface ICatLogger
{
void AddData();
void LogEvent(String methodName, IDatabaseProvider databaseProvider, String connectionString);
void SetStatus();
void LogError(Exception ex);
void Complete();
void LogRecordCount(String name, Int64 count);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace APICrudOperations.Models
{
public class TableTravel
{
public string _cn6ca { get; set; }
public string accuracylocation { get; set; }
public string address { get; set; }
public string datasource { get; set; }
public string latlong { get; set; }
public string modeoftravel { get; set; }
public string pid { get; set; }
public string placename { get; set; }
public string timefrom { get; set; }
public string timeto { get; set; }
public string type { get; set; }
}
} |
#region License
/***
* Copyright © 2018-2025, 张强 (943620963@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* without warranties or conditions of any kind, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using NLog;
using System;
using System.IO;
using System.Reflection;
/****************************
* [Author] 张强
* [Date] 2020-05-24
* [Describe] 日志工具类
* **************************/
namespace ZqUtils.Helpers
{
/// <summary>
/// 日志工具类
/// </summary>
public class LogHelper
{
/// <summary>
/// Logger
/// </summary>
private static readonly Logger logger;
/// <summary>
/// Constructor
/// </summary>
static LogHelper()
{
var nlog = @"XmlConfig/NLog.config".GetFullPath();
if (!File.Exists(nlog))
{
//校验文件夹是否存在,不存在则创建XmlConfig文件夹
"XmlConfig".GetFullPath().CreateIfNotExists();
var assembly = Assembly.Load("ZqUtils");
var manifestResource = "ZqUtils.XmlConfig.NLog.config";
FileHelper.CreateFileFromManifestResource(assembly, manifestResource, nlog);
}
LogManager.LogFactory.LoadConfiguration(nlog);
logger = LogManager.GetCurrentClassLogger();
}
/// <summary>
/// Debug
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Debug(string message, params object[] args)
{
logger.Debug(message, args);
}
/// <summary>
/// Debug
/// </summary>
/// <param name="ex"></param>
/// <param name="message"></param>
public static void Debug(Exception ex, string message)
{
logger.Debug(ex, message);
}
/// <summary>
/// Info
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Info(string message, params object[] args)
{
logger.Info(message, args);
}
/// <summary>
/// Info
/// </summary>
/// <param name="ex"></param>
/// <param name="message"></param>
public static void Info(Exception ex, string message)
{
logger.Info(ex, message);
}
/// <summary>
/// Warn
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Warn(string message, params object[] args)
{
logger.Warn(message, args);
}
/// <summary>
/// Warn
/// </summary>
/// <param name="ex"></param>
/// <param name="message"></param>
public static void Warn(Exception ex, string message)
{
logger.Warn(ex, message);
}
/// <summary>
/// Trace
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Trace(string message, params object[] args)
{
logger.Trace(message, args);
}
/// <summary>
/// Trace
/// </summary>
/// <param name="ex"></param>
/// <param name="message"></param>
public static void Trace(Exception ex, string message)
{
logger.Trace(ex, message);
}
/// <summary>
/// Error
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Error(string message, params object[] args)
{
logger.Error(message, args);
}
/// <summary>
/// Error
/// </summary>
/// <param name="ex"></param>
/// <param name="message"></param>
public static void Error(Exception ex, string message)
{
logger.Error(ex, message);
}
/// <summary>
/// Fatal
/// </summary>
/// <param name="message"></param>
/// <param name="args"></param>
public static void Fatal(string message, params object[] args)
{
logger.Fatal(message, args);
}
/// <summary>
/// Fatal
/// </summary>
/// <param name="ex"></param>
/// <param name="message"></param>
public static void Fatal(Exception ex, string message)
{
logger.Fatal(ex, message);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int? timeoutMilliseconds = null)
{
if (timeoutMilliseconds != null)
LogManager.Flush(timeoutMilliseconds.Value);
else
LogManager.Flush();
}
}
} |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Testing
{
using System;
using System.Collections.Generic;
using Accord.Math;
/// <summary>
/// Two-way ANOVA model types.
/// </summary>
/// <remarks>
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Analysis_of_variance">
/// Wikipedia, The Free Encyclopedia. Analysis of variance. </a></description></item>
/// </list></para>
/// </remarks>
///
public enum TwoWayAnovaModel
{
/// <summary>
/// Fixed-effects model (Model 1).
/// </summary>
/// <remarks>
/// <para>
/// The fixed-effects model of analysis of variance, as known as model 1, applies
/// to situations in which the experimenter applies one or more treatments to the
/// subjects of the experiment to see if the response variable values change.</para>
/// <para>
/// This allows the experimenter to estimate the ranges of response variable values
/// that the treatment would generate in the population as a whole.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Analysis_of_variance">
/// Wikipedia, The Free Encyclopedia. Analysis of variance. </a></description></item>
/// </list></para>
/// </remarks>
///
Fixed = 1,
/// <summary>
/// Random-effects model (Model 2).
/// </summary>
/// <remarks>
/// <para>
/// Random effects models are used when the treatments are not fixed. This occurs when
/// the various factor levels are sampled from a larger population. Because the levels
/// themselves are random variables, some assumptions and the method of contrasting the
/// treatments differ from ANOVA model 1.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Analysis_of_variance">
/// Wikipedia, The Free Encyclopedia. Analysis of variance. </a></description></item>
/// </list></para>
/// </remarks>
///
Random = 2,
/// <summary>
/// Mixed-effects models (Model 3).
/// </summary>
/// <remarks>
/// <para>
/// A mixed-effects model contains experimental factors of both fixed and random-effects
/// types, with appropriately different interpretations and analysis for the two types.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Analysis_of_variance">
/// Wikipedia, The Free Encyclopedia. Analysis of variance. </a></description></item>
/// </list></para>
/// </remarks>
///
Mixed = 3,
}
/// <summary>
/// Two-way Analysis of Variance.
/// </summary>
///
/// <remarks>
/// <para>
/// The two-way ANOVA is an extension of the one-way ANOVA for two independent
/// variables. There are three classes of models which can also be used in the
/// analysis, each of which determining the interpretation of the independent
/// variables in the analysis.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Analysis_of_variance">
/// Wikipedia, The Free Encyclopedia. Analysis of variance. </a></description></item>
/// <item><description><a href="http://www.smi.hst.aau.dk/~cdahl/BiostatPhD/ANOVA.pdf">
/// Carsten Dahl Mørch, ANOVA. Aalborg Universitet. Available on:
/// http://www.smi.hst.aau.dk/~cdahl/BiostatPhD/ANOVA.pdf </a></description></item>
/// </list></para>
/// </remarks>
///
/// <see cref="TwoWayAnovaModel"/>
///
[Serializable]
public class TwoWayAnova : IAnova
{
private double totalMean;
private double[,] cellMeans;
private double[] aMean;
private double[] bMean;
/// <summary>
/// Gets the number of observations in the sample.
/// </summary>
///
public int Observations { get; private set; }
/// <summary>
/// Gets the number of samples presenting the first factor.
/// </summary>
///
public int FirstFactorSamples { get; private set; }
/// <summary>
/// Gets the number of samples presenting the second factor.
/// </summary>
public int SecondFactorSamples { get; private set; }
/// <summary>
/// Gets the number of replications of each factor.
/// </summary>
///
public int Replications { get; private set; }
/// <summary>
/// Gets or sets the variation sources obtained in the analysis.
/// </summary>
/// <value>The variation sources for the data.</value>
///
public TwoWayAnovaVariationSources Sources { get; private set; }
/// <summary>
/// Gets the ANOVA results in the form of a table.
/// </summary>
///
public AnovaSourceCollection Table { get; private set; }
/// <summary>
/// Gets or sets the type of the model.
/// </summary>
/// <value>The type of the model.</value>
///
public TwoWayAnovaModel ModelType { get; private set; }
/// <summary>
/// Constructs a new <see cref="TwoWayAnova"/>.
/// </summary>
///
/// <param name="samples">The samples.</param>
/// <param name="firstFactorLabels">The first factor labels.</param>
/// <param name="secondFactorLabels">The second factor labels.</param>
/// <param name="type">The type of the analysis.</param>
///
public TwoWayAnova(double[] samples, int[] firstFactorLabels, int[] secondFactorLabels,
TwoWayAnovaModel type = TwoWayAnovaModel.Mixed)
{
FirstFactorSamples = firstFactorLabels.Max() + 1;
SecondFactorSamples = secondFactorLabels.Max() + 1;
List<double>[][] groups = new List<double>[FirstFactorSamples][];
for (int i = 0; i < groups.Length; i++)
{
groups[i] = new List<double>[SecondFactorSamples];
for (int j = 0; j < groups[i].Length; j++)
groups[i][j] = new List<double>();
}
for (int i = 0; i < samples.Length; i++)
{
int f = firstFactorLabels[i];
int s = secondFactorLabels[i];
groups[f][s].Add(samples[i]);
}
// Transform into array
double[][][] sets = new double[FirstFactorSamples][][];
for (int i = 0; i < sets.Length; i++)
{
sets[i] = new double[SecondFactorSamples][];
for (int j = 0; j < sets[i].Length; j++)
sets[i][j] = groups[i][j].ToArray();
}
Replications = sets[0][0].Length;
// Assert equal number of replicates
for (int i = 0; i < sets.Length; i++)
for (int j = 0; j < sets[i].Length; j++)
if (sets[i][j].Length != Replications)
throw new ArgumentException("Samples do not have the same number of replicates.", "samples");
initialize(sets, type);
}
/// <summary>
/// Constructs a new <see cref="TwoWayAnova"/>.
/// </summary>
///
/// <param name="samples">The samples in grouped form.</param>
/// <param name="type">The type of the analysis.</param>
///
public TwoWayAnova(double[][][] samples, TwoWayAnovaModel type = TwoWayAnovaModel.Mixed)
{
FirstFactorSamples = samples.Length;
SecondFactorSamples = samples[0].Length;
Replications = samples[0][0].Length;
Observations = FirstFactorSamples * SecondFactorSamples * Replications;
// Assert equal number of replicates
for (int i = 0; i < samples.Length; i++)
for (int j = 0; j < samples[i].Length; j++)
if (samples[i][j].Length != Replications)
throw new ArgumentException("Samples do not have the same number of replicates.", "samples");
initialize(samples, type);
}
private void initialize(double[][][] samples, TwoWayAnovaModel type)
{
// References:
// - http://www.smi.hst.aau.dk/~cdahl/BiostatPhD/ANOVA.pdf
ModelType = type;
Observations = FirstFactorSamples * SecondFactorSamples * Replications;
// Step 1. Initialize all degrees of freedom
int cellDegreesOfFreedom = FirstFactorSamples * SecondFactorSamples - 1;
int aDegreesOfFreedom = FirstFactorSamples - 1;
int bDegreesOfFreedom = SecondFactorSamples - 1;
int abDegreesOfFreedom = cellDegreesOfFreedom - aDegreesOfFreedom - bDegreesOfFreedom;
int errorDegreesOfFreedom = FirstFactorSamples * SecondFactorSamples * (Replications - 1);
int totalDegreesOfFreedom = Observations - 1;
// Step 1. Calculate cell means
cellMeans = new double[FirstFactorSamples, SecondFactorSamples];
double sum = 0;
for (int i = 0; i < samples.Length; i++)
for (int j = 0; j < samples[i].Length; j++)
sum += cellMeans[i, j] = Measures.Mean(samples[i][j]);
// Step 2. Calculate the total mean (grand mean)
totalMean = sum / (FirstFactorSamples * SecondFactorSamples);
// Step 3. Calculate factor means
aMean = new double[FirstFactorSamples];
for (int i = 0; i < samples.Length; i++)
{
sum = 0;
for (int j = 0; j < samples[i].Length; j++)
for (int k = 0; k < samples[i][j].Length; k++)
sum += samples[i][j][k];
aMean[i] = sum / (SecondFactorSamples * Replications);
}
bMean = new double[SecondFactorSamples];
for (int j = 0; j < samples[0].Length; j++)
{
sum = 0;
for (int i = 0; i < samples.Length; i++)
for (int k = 0; k < samples[i][j].Length; k++)
sum += samples[i][j][k];
bMean[j] = sum / (FirstFactorSamples * Replications);
}
// Step 4. Calculate total sum of squares
double ssum = 0;
for (int i = 0; i < samples.Length; i++)
{
for (int j = 0; j < samples[i].Length; j++)
{
for (int k = 0; k < samples[i][j].Length; k++)
{
double u = samples[i][j][k] - totalMean;
ssum += u * u;
}
}
}
double totalSumOfSquares = ssum;
// Step 5. Calculate the cell sum of squares
ssum = 0;
for (int i = 0; i < FirstFactorSamples; i++)
{
for (int j = 0; j < SecondFactorSamples; j++)
{
double u = cellMeans[i, j] - totalMean;
ssum += u * u;
}
}
double cellSumOfSquares = ssum * Replications;
// Step 6. Compute within-cells error sum of squares
ssum = 0;
for (int i = 0; i < samples.Length; i++)
{
for (int j = 0; j < samples[i].Length; j++)
{
for (int k = 0; k < samples[i][j].Length; k++)
{
double u = samples[i][j][k] - cellMeans[i, j];
ssum += u * u;
}
}
}
double errorSumOfSquares = ssum;
// Step 7. Compute factors sum of squares
ssum = 0;
for (int i = 0; i < aMean.Length; i++)
{
double u = aMean[i] - totalMean;
ssum += u * u;
}
double aSumOfSquares = ssum * SecondFactorSamples * Replications;
ssum = 0;
for (int i = 0; i < bMean.Length; i++)
{
double u = bMean[i] - totalMean;
ssum += u * u;
}
double bSumOfSquares = ssum * FirstFactorSamples * Replications;
// Step 9. Compute interaction sum of squares
double abSumOfSquares = cellSumOfSquares - aSumOfSquares - bSumOfSquares;
// Step 10. Compute mean squares
double aMeanSquares = aSumOfSquares / aDegreesOfFreedom;
double bMeanSquares = bSumOfSquares / bDegreesOfFreedom;
double abMeanSquares = abSumOfSquares / abDegreesOfFreedom;
double errorMeanSquares = errorSumOfSquares / errorDegreesOfFreedom;
// Step 10. Create the F-Statistics
FTest aSignificance, bSignificance, abSignificance;
if (type == TwoWayAnovaModel.Fixed)
{
// Model 1: Factors A and B fixed
aSignificance = new FTest(aMeanSquares / abMeanSquares, aDegreesOfFreedom, abDegreesOfFreedom);
bSignificance = new FTest(bMeanSquares / abMeanSquares, bDegreesOfFreedom, abDegreesOfFreedom);
abSignificance = new FTest(abMeanSquares / errorMeanSquares, abDegreesOfFreedom, errorDegreesOfFreedom);
}
else if (type == TwoWayAnovaModel.Mixed)
{
// Model 2: Factors A and B random
aSignificance = new FTest(aMeanSquares / errorMeanSquares, aDegreesOfFreedom, errorDegreesOfFreedom);
bSignificance = new FTest(bMeanSquares / errorMeanSquares, bDegreesOfFreedom, errorDegreesOfFreedom);
abSignificance = new FTest(abMeanSquares / errorMeanSquares, abDegreesOfFreedom, errorDegreesOfFreedom);
}
else if (type == TwoWayAnovaModel.Random)
{
// Model 3: Factor A fixed, factor B random
aSignificance = new FTest(aMeanSquares / abMeanSquares, aDegreesOfFreedom, abDegreesOfFreedom);
bSignificance = new FTest(bMeanSquares / errorMeanSquares, bDegreesOfFreedom, errorDegreesOfFreedom);
abSignificance = new FTest(abMeanSquares / errorMeanSquares, abDegreesOfFreedom, errorDegreesOfFreedom);
}
else throw new ArgumentException("Unhandled analysis type.","type");
// Step 11. Create the ANOVA table and sources
AnovaVariationSource cell = new AnovaVariationSource(this, "Cells", cellSumOfSquares, cellDegreesOfFreedom);
AnovaVariationSource a = new AnovaVariationSource(this, "Factor A", aSumOfSquares, aDegreesOfFreedom, aMeanSquares, aSignificance);
AnovaVariationSource b = new AnovaVariationSource(this, "Factor B", bSumOfSquares, bDegreesOfFreedom, bMeanSquares, bSignificance);
AnovaVariationSource ab = new AnovaVariationSource(this, "Interaction AxB", abSumOfSquares, abDegreesOfFreedom, abMeanSquares, abSignificance);
AnovaVariationSource error = new AnovaVariationSource(this, "Within-cells (error)", errorSumOfSquares, errorDegreesOfFreedom, errorMeanSquares);
AnovaVariationSource total = new AnovaVariationSource(this, "Total", totalSumOfSquares, totalDegreesOfFreedom);
this.Sources = new TwoWayAnovaVariationSources()
{
Cells = cell,
FactorA = a,
FactorB = b,
Interaction = ab,
Error = error,
Total = total
};
this.Table = new AnovaSourceCollection(cell, a, b, ab, error, total);
}
}
/// <summary>
/// Variation sources associated with two-way ANOVA.
/// </summary>
///
public class TwoWayAnovaVariationSources
{
internal TwoWayAnovaVariationSources() { }
/// <summary>
/// Gets information about the first factor (A).
/// </summary>
///
public AnovaVariationSource FactorA { get; internal set; }
/// <summary>
/// Gets information about the second factor (B) source.
/// </summary>
///
public AnovaVariationSource FactorB { get; internal set; }
/// <summary>
/// Gets information about the interaction factor (AxB) source.
/// </summary>
///
public AnovaVariationSource Interaction { get; internal set; }
/// <summary>
/// Gets information about the error (within-variance) source.
/// </summary>
///
public AnovaVariationSource Error { get; internal set; }
/// <summary>
/// Gets information about the grouped (cells) variance source.
/// </summary>
///
public AnovaVariationSource Cells { get; internal set; }
/// <summary>
/// Gets information about the total source of variance.
/// </summary>
///
public AnovaVariationSource Total { get; internal set; }
}
}
|
using System;
using System.Security.Cryptography.X509Certificates;
using org.sola.webservices.digitalarchive;
using org.sola.webservices.digitalarchive.extra;
namespace org.sola.services.boundary.wsclients
{
public class DigitalArchiveServiceProxy: IDigitalarchiveService
{
private static readonly DigitalArchiveServiceProxy _instance = new DigitalArchiveServiceProxy();
private String pWord; // Might what to store this in SecureString class
private String uName;
public static DigitalArchiveServiceProxy Instance
{
get
{
return _instance;
}
}
private DigitalArchiveServiceProxy() { }
public void SetCredentials(string userName, string password)
{
uName = userName;
pWord = password;
}
public bool CheckConnection()
{
bool result = false;
using (DigitalArchiveClient client = new DigitalArchiveClient())
{
ConfigureClient(client);
try
{
client.Open();
result = client.CheckConnection();
client.Close();
}
catch (Exception ex)
{
client.Abort();
throw ex;
}
}
return result;
}
private void ConfigureClient(DigitalArchiveClient client)
{
// Load the certificate from the Project Resources.
// Note that this certificate has been generated from the default SOLA Development keystore.jks. Instructions on how to
// generate the cert using the Java keytool can be found here.
// http://stackoverflow.com/questions/5529541/developing-a-net-client-that-consumes-a-secure-metro-2-1-web-service
// Note that it is also necessary to add DNS identity configuration to the app.config. The default DNS identity in this
// certificate is xwssecurityserver.
X509Certificate2 cert = new X509Certificate2(org.sola.services.boundary.wsclients.Properties.Resources.ServerCertificate);
client.ClientCredentials.ServiceCertificate.DefaultCertificate = cert;
client.ClientCredentials.UserName.UserName = uName;
client.ClientCredentials.UserName.Password = pWord;
}
public webservices.digitalarchive.extra.documentTO CreateDocument(webservices.digitalarchive.extra.documentBinaryTO documentBinary)
{
documentTO result = null;
using (DigitalArchiveClient client= new DigitalArchiveClient())
{
ConfigureClient(client);
result = client.CreateDocument(documentBinary);
}
return result;
}
public webservices.digitalarchive.extra.documentTO CreateDocumentFromServer(webservices.digitalarchive.extra.documentBinaryTO documentBinary, string fileName)
{
documentTO result = null;
using (DigitalArchiveClient client = new DigitalArchiveClient())
{
ConfigureClient(client);
try
{
client.Open();
result = client.CreateDocument(documentBinary);
client.Close();
}
catch (Exception ex)
{
client.Abort();
throw ex;
}
}
return result;
}
public webservices.digitalarchive.extra.fileInfoTO[] GetAllFiles()
{
throw new NotImplementedException();
}
public webservices.digitalarchive.extra.documentBinaryTO GetDocument(string documentId)
{
documentBinaryTO result = null;
using (DigitalArchiveClient client = new DigitalArchiveClient())
{
ConfigureClient(client);
try
{
client.Open();
result = client.GetDocument(documentId);
client.Close();
}
catch (Exception ex)
{
client.Abort();
throw ex;
}
}
return result;
}
public webservices.digitalarchive.extra.fileInfoTO getFileBinary(string fileName)
{
throw new NotImplementedException();
}
public webservices.digitalarchive.extra.fileBinaryTO GetFileThumbnail(string fileName)
{
throw new NotImplementedException();
}
public webservices.digitalarchive.extra.documentTO SaveDocument(webservices.digitalarchive.extra.documentTO document)
{
documentTO result = null;
using (DigitalArchiveClient client = new DigitalArchiveClient())
{
ConfigureClient(client);
try
{
client.Open();
result = client.SaveDocument(document);
client.Close();
}
catch (Exception ex)
{
client.Abort();
throw ex;
}
}
return result;
}
}
}
|
using heitech.MediatorMessenger.Interface;
using System.Threading.Tasks;
namespace heitech.MediatorMessenger.Tests
{
internal class MediatorMock : IInternalMediatorMessenger<string>
{
internal IRequestObject<string> SentQuery { get; private set; }
internal IMessageObject<string> SentMessage { get; private set; }
public void Command(IMessageObject<string> message)
{
SentMessage = message;
}
public Task CommandAsync(IMessageObject<string> message)
{
SentMessage = message;
return Task.CompletedTask;
}
internal object Result;
public TResponse Query<TResponse>(IRequestObject<string> request)
{
SentQuery = request;
return (TResponse)Result;
}
public Task<TResponse> QueryAsync<TResponse>(IRequestObject<string> request)
{
SentQuery = request;
return Task.FromResult((TResponse)Result);
}
internal bool WasRegistererSet { get; private set; }
public void SetRegisterer(IRegisterer<string> registerer)
{
WasRegistererSet = true;
}
}
}
|
using System;
using Xamarin.Forms;
namespace App1.Renderers
{
public class CustomLabel : Label
{
public static readonly BindableProperty IsUnderlinedProperty = BindableProperty.Create<CustomLabel, bool>(p => p.IsUnderlined, false);
public CustomLabel() : base()
{ }
public bool IsUnderlined
{
get
{
return (bool)GetValue(IsUnderlinedProperty);
}
set
{
SetValue(IsUnderlinedProperty, value);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.RobinsonCrusoe_Game.Cards.HuntingCards
{
public interface IBeastCard
{
int GetMaterialNumber();
void Fight();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.