text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZdravoKorporacija.DTO { class ExaminationDTO { public int Id { get; set; } public string TypeOfExamination { get; set; } public string Date { get; set; } public string Time { get; set; } public string Doctor { get; set; } public ExaminationDTO(int id, string typeOfExamination, string date, string time, string doctor) { this.Id = id; this.TypeOfExamination = typeOfExamination; this.Date = date; this.Time = time; this.Doctor = doctor; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace LAOffsetUpdater { public class StringReference { public long Address { get; set; } public string Name { get; set; } public List<long> Usage { get; set; } public StringReference(long address, string name) { Address = address; Name = name; Usage = new List<long>(); } } public class FunctionReference { public long Address { get; set; } public string Name { get; set; } public List<long> Usage { get; set; } public FunctionReference(long address, string name) { Address = address; Name = name; Usage = new List<long>(); } } public class MyProcess : MemoryReader { private Process Process { get; set; } public ProcessModule Module { get; set; } public byte[] Dump_MainModule { get; set; } public Dictionary<long, StringReference> ASCII_StringReferences { get; set; } public Dictionary<long, StringReference> UTF16_StringReferences { get; set; } public Dictionary<long, FunctionReference> FunctionReferences { get; set; } public MyProcess(string name) { Process = Process.GetProcessesByName(name).FirstOrDefault(); Handle = (int)GetHandle(); if (Process == null) { Console.WriteLine("Cant find " + name); Console.ReadKey(); Environment.Exit(0); } Dump_MainModule = DumpModule("LOSTARK.exe"); ASCII_StringReferences = GetASCIIStringReferences(); UTF16_StringReferences = GetUTF16StringReferences(); FunctionReferences = new Dictionary<long, FunctionReference>(); GenerateStringReferenceUsages(); } private IntPtr GetHandle() { if (Process != null) return Win32.OpenProcess(0x1F0FFF, false, Process.Id); return IntPtr.Zero; } private byte[] DumpModule(string name) { Console.WriteLine("Dumping Module " + name); Module = null; foreach (ProcessModule m in Process.Modules) { if (m.ModuleName == name) Module = m; } if(Module == null) return null; byte[] dump = ReadByteArray((long)Module.BaseAddress, Module.ModuleMemorySize); return dump; } private Dictionary<long, StringReference> GetASCIIStringReferences() { Console.WriteLine("Collecting ASCII String-References"); Dictionary<long, StringReference> buffer = new Dictionary<long, StringReference>(); for (int i = 0; i < Dump_MainModule.Length; i+=4) { string s = ReadStringASCII(i, Dump_MainModule); if (s != "") { StringReference sr = new StringReference((long)Module.BaseAddress + i, s); buffer.Add(sr.Address, sr); } } return buffer; } private Dictionary<long, StringReference> GetUTF16StringReferences() { Console.WriteLine("Collecting UTF16 String-References"); Dictionary<long, StringReference> buffer = new Dictionary<long, StringReference>(); for (int i = 0; i < Dump_MainModule.Length; i += 4) { string s = ReadStringUnicode(i, Dump_MainModule); if (s != "") { StringReference sr = new StringReference((long)Module.BaseAddress + i, s); buffer.Add(sr.Address, sr); } } return buffer; } public void GenerateStringReferenceUsages() { Console.WriteLine("Generating String-Reference Usages"); for (int i = 0; i < Dump_MainModule.Length; i++) { var adr = ((long)Module.BaseAddress + i); if (ReadByte(i, Dump_MainModule) == 0x48 || ReadByte(i, Dump_MainModule) == 0x4C) { if (ReadByte(i + 1, Dump_MainModule) == 0x8D) { var value = (adr + 7) + ReadInt32(i + 3, Dump_MainModule); if(ASCII_StringReferences.ContainsKey(value)) ASCII_StringReferences[value].Usage.Add(adr); if (UTF16_StringReferences.ContainsKey(value)) UTF16_StringReferences[value].Usage.Add(adr); } else if (ReadByte(i + 1, Dump_MainModule) == 0x83) { var value = (adr + 8) + ReadInt32(i + 3, Dump_MainModule); if (ASCII_StringReferences.ContainsKey(value)) ASCII_StringReferences[value].Usage.Add(adr); if (UTF16_StringReferences.ContainsKey(value)) UTF16_StringReferences[value].Usage.Add(adr); } } } } public void GenerateFunctionCallReferenceUsages() { Console.WriteLine("Generating Function-Call-Reference Usages"); for (int i = 0; i < Dump_MainModule.Length; i++) { var adr = ((long)Module.BaseAddress + i); if (ReadByte(i, Dump_MainModule) == 0xE8) { var value = (adr + 5) + ReadInt32(i + 1, Dump_MainModule); if (FunctionReferences.ContainsKey(value)) FunctionReferences[value].Usage.Add(adr); } } } public List<long> FindFunctionCallUsage(long funcAdr, string name) { Console.WriteLine("Looking for Function-Call-Reference Usage of " + name); List<long> buffer = new List<long>(); for (int i = 0; i < Dump_MainModule.Length; i++) { var adr = ((long)Module.BaseAddress + i); if (ReadByte(i, Dump_MainModule) == 0xE8) { var value = ReadInt32(i + 1, Dump_MainModule); if ((adr + 5) + value == funcAdr) { buffer.Add(adr); Console.WriteLine("Usage found at " + adr.ToString("X")); } } } return buffer; } public List<long> FindStringReferenceUsage(long stringRef, string name) { Console.WriteLine("Looking for String-Reference Usage of " + name); List<long> buffer = new List<long>(); for (int i = 0; i < Dump_MainModule.Length; i++) { var adr = ((long) Module.BaseAddress + i); if (ReadByte(i, Dump_MainModule) == 0x48 || ReadByte(i, Dump_MainModule) == 0x4C) { if (ReadByte(i + 1, Dump_MainModule) == 0x8D) { var value = ReadInt32(i + 3, Dump_MainModule); if ((adr + 7) + value == stringRef) { buffer.Add(adr); Console.WriteLine("Usage found at " + adr.ToString("X")); } } else if (ReadByte(i + 1, Dump_MainModule) == 0x83) { var value = ReadInt32(i + 3, Dump_MainModule); if ((adr + 8) + value == stringRef) { buffer.Add(adr); Console.WriteLine("Usage found at " + adr.ToString("X")); } } } } return buffer; } public long GetQWordPointerValue(long address) { long offset = address - (long) Module.BaseAddress; int instrSize = 0; if (ReadByte((int) offset, Dump_MainModule) == 0x48 || ReadByte((int)offset, Dump_MainModule) == 0x4C) { if (ReadByte((int) offset + 1, Dump_MainModule) == 0x8B || ReadByte((int)offset + 1, Dump_MainModule) == 0x89 || ReadByte((int)offset + 1, Dump_MainModule) == 0x8D) { instrSize = 7; return address + instrSize + ReadInt32((int)offset + 3, Dump_MainModule); } else { instrSize = 8; return address + instrSize + ReadInt32((int)offset + 3, Dump_MainModule); } } else if (ReadByte((int)offset, Dump_MainModule) == 0x44) { if (ReadByte((int)offset + 1, Dump_MainModule) == 0x39) { instrSize = 7; return address + instrSize + ReadInt32((int)offset + 3, Dump_MainModule); } } else if (ReadByte((int)offset, Dump_MainModule) == 0xE8 || ReadByte((int)offset, Dump_MainModule) == 0xE9) { instrSize = 5; return address + instrSize + ReadInt32((int)offset + 1, Dump_MainModule); } else if (ReadByte((int)offset, Dump_MainModule) == 0x39) { instrSize = 6; return address + instrSize + ReadInt32((int)offset + 2, Dump_MainModule); } else if (ReadByte((int)offset, Dump_MainModule) == 0x88) { instrSize = 6; return address + instrSize + ReadInt32((int)offset + 2, Dump_MainModule); } return 0; } public long GetQWordPointerValue(long address, long[] offsets) { long _base = address; foreach (var offset in offsets) { if (_base == 0) break; _base = GetQWordPointerValue(_base + offset); } return _base; } public List<long> FindBytePattern(byte[] pattern, string[] mask) { List<long> buffer = new List<long>(); int startOffset = 0; for (int i = 0; i < Dump_MainModule.Length; i++) { if (Dump_MainModule[i] == pattern[0]) { startOffset = i; bool found = true; for (int x = 1; x < pattern.Length; x++) { if (Dump_MainModule[i + x] != pattern[x] && mask[x] == "x") { found = false; break; } } if(found) buffer.Add((long)Module.BaseAddress + startOffset); } } return buffer; } } }
// AUTHOR - BEN PALLADINO - ONSHORE OUTSOURCING using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Data.Sql; using System.Data.SqlClient; using System.IO; using System.Data; using UtilityLogger; using DataAccessLayer; using DataAccessLayer.DataObjects; using BusinessLogicLayer; namespace DataAccessLayer { public class HeroDataAccess { public static string ConnectionString = ConfigurationManager.ConnectionStrings["OverwatchStatTracker"].ConnectionString; static ErrorLogger Logger = new ErrorLogger(); //------------------------------------// //ADD HEROES //------------------------------------// public bool AddHero(HeroesDAO heroToAdd) { bool success = false; try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand("sp_HeroesTable_AddHero", connection)) { command.CommandType = System.Data.CommandType.StoredProcedure; command.Parameters.AddWithValue("@HeroName", heroToAdd.HeroName); command.Parameters.AddWithValue("@HeroType", heroToAdd.HeroType); connection.Open(); command.ExecuteNonQuery(); } } } catch (Exception error) { success = false; Logger.LogError(error); } return success; } //------------------------------------// //VIEW HEROES //------------------------------------// public List<HeroesDAO> GetAllHeroes() { List<HeroesDAO> heroList = new List<HeroesDAO>(); try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand("sp_HeroesTable_GetAllHeroes", connection)) { command.CommandType = CommandType.StoredProcedure; connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { HeroesDAO heroToList = new HeroesDAO(); heroToList.HeroID = reader.GetInt32(0); heroToList.HeroName = reader.GetString(1); heroToList.HeroType = reader.GetString(2); heroList.Add(heroToList); } } } } } catch (Exception error) { Logger.LogError(error); } return heroList; } //------------------------------------// //UPDATE HEROES //------------------------------------// //THIS METHOD UPDATES HEROES FROM THE SQL USER TABLE public bool UpdateHero(HeroesDAO userToUpdate) { //CHECKS TO SEE IF THE METHOD WAS SUCCESSFUL OR NOT bool success = false; //THIS TRY ATTEMPTS TO OPEN A CONNECTION. IF IT SUCCEEDS, IT CLOSES THE CONNECTION. try { //TRY TO EXECUTE THE CODE HERE, IF IT COMPLETES THEN THE BOOL SUCCESS = TRUE //OPENS CONNECTION TO THE SQL DATABASE using (SqlConnection connection = new SqlConnection(ConnectionString)) { //OPENS ACCESS TO SQL STORED PROCEDURE using (SqlCommand command = new SqlCommand("sp_HeroesTable_UpdateHero", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@HeroID", userToUpdate.HeroID); command.Parameters.AddWithValue("@HeroName", userToUpdate.HeroName); command.Parameters.AddWithValue("@HeroType", userToUpdate.HeroType); connection.Open(); command.ExecuteNonQuery(); } } } catch (Exception error) { success = false; Logger.LogError(error); } return success; } //------------------------------------// //DELETE HEROES //------------------------------------// public bool DeleteHero(int HeroID) { bool success = false; //THIS TRY ATTEMPTS TO OPEN A CONNECTION. IF IT SUCCEEDS, IT CLOSES THE CONNECTION. try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand("sp_HeroesTable_DeleteHero", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@HeroID", HeroID); connection.Open(); command.ExecuteNonQuery(); } } } catch (Exception error) { success = false; Logger.LogError(error); } return success; } //------------------------------------// //GET HEROES BY ID //------------------------------------// public HeroesDAO GetHeroByID(int HeroID) { HeroesDAO heroToReturn = new HeroesDAO(); try { using (SqlConnection connection = new SqlConnection(ConnectionString)) { using (SqlCommand command = new SqlCommand("sp_HeroesTable_GetHeroByID", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@HeroID", HeroID); connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { heroToReturn.HeroID = reader.GetInt32(0); heroToReturn.HeroName = reader.GetString(1); heroToReturn.HeroType = reader.GetString(2); } } } } } catch (Exception error) { Logger.LogError(error); } return heroToReturn; } } }
namespace AxiEndPoint.EndPointServer.MessageHandlers { public interface IMessageProcessor { void ProcessMessage(object sender, MessageEventArgs e); } }
using Predictr.Models; using Predictr.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Predictr.Services { public class PredictionHandler { private const int CORRECT_SCORE_POINTS = 3; private const int CORRECT_RESULT_POINTS = 1; private List<Prediction> _predictions; private Fixture _fixture; private String _user; public PredictionHandler(List<Prediction> predictions, Fixture fixture) { _predictions = predictions; _fixture = fixture; } public PredictionHandler(List<Prediction> predictions, String user) { _predictions = predictions; _user = user; } public Boolean CorrectResult(Prediction _prediction, Fixture _fixture) { if (_prediction.HomeScore > _prediction.AwayScore && this._fixture.HomeScore > this._fixture.AwayScore || _prediction.HomeScore < _prediction.AwayScore && this._fixture.HomeScore < this._fixture.AwayScore || _prediction.HomeScore == _prediction.AwayScore && this._fixture.HomeScore == this._fixture.AwayScore // correct result: +1 pt ) return true; else { return false; } } public List<Prediction> updatePredictions() { foreach (Prediction _prediction in _predictions) { // correct score? if (CorrectScore(_prediction, _fixture)) { _prediction.Points = CORRECT_SCORE_POINTS; } // correct result else if (CorrectResult(_prediction, _fixture)) { _prediction.Points = CORRECT_RESULT_POINTS; } // nothing else { _prediction.Points = 0; } // joker? if (CorrectResult(_prediction, _fixture) && JokerPlayed(_prediction)) { _prediction.Points = CORRECT_SCORE_POINTS; } // double-up if (CorrectResult(_prediction, _fixture) && DoubleUpPlayed(_prediction)) { _prediction.Points = _prediction.Points * 2; } } return _predictions; } public Boolean CorrectScore(Prediction _prediction, Fixture _fixture) { if (_prediction.HomeScore == _fixture.HomeScore && _prediction.AwayScore == _fixture.AwayScore) { return true; } else { return false; } } public Boolean JokerPlayed(Prediction _prediction) { if (_prediction.Joker == true) { return true; } else { return false; } } public Boolean DoubleUpPlayed(Prediction _prediction) { if (_prediction.DoubleUp == true) { return true; } else { return false; } } public int CountDoublesPlayed() { return _predictions .Where(p => p.ApplicationUserId == _user) .Where(p => p.DoubleUp == true) .Count(); } public int CountJokersPlayed() { return _predictions .Where(p => p.ApplicationUserId == _user) .Where(p => p.Joker == true) .Count(); } public VM_CreatePrediction BuildCreateVMPrediction() { VM_CreatePrediction vm = new VM_CreatePrediction(); int doublesUsed = CountDoublesPlayed(); int jokersUsed = CountJokersPlayed(); vm.HomeTeam = _fixture.Home; vm.AwayTeam = _fixture.Away; if (jokersUsed < 3) { vm.JokerDisabled = false; } else { vm.JokerDisabled = true; } if (doublesUsed < 3) { vm.DoubleUpDisabled = false; } else { vm.DoubleUpDisabled = true; } return vm; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; using TY.SPIMS.Controllers; using TY.SPIMS.Controllers.Interfaces; namespace TY.SPIMS.Client.Inventory { public partial class EditAutoPartForm : ComponentFactory.Krypton.Toolkit.KryptonForm { private readonly IAutoPartController autoPartController; public int AutoPartId { get; set; } public string PartName { get; set; } public EditAutoPartForm() { this.autoPartController = IOC.Container.GetInstance<AutoPartController>(); InitializeComponent(); } private void EditAutoPartForm_Load(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(PartName)) { AutoPartTextbox.Text = PartName; } } private void SaveButton_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(AutoPartTextbox.Text)) { this.autoPartController.UpdateAutoPartName(this.AutoPartId, this.AutoPartTextbox.Text); ClientHelper.ShowSuccessMessage("Auto part updated successfully."); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.ComponentModel.DataAnnotations; namespace dotnet_webpack.Pages { public class ContactModel : PageModel { [Required] [StringLength(30, MinimumLength = 3)] public string Subject { get; set; } [Required(ErrorMessage = "Please enter a message.")] public string Message { get; set; } public void OnGet() { } public IActionResult OnPost() { return RedirectToPage("/Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KamenNuzkyPapir { partial class Program { private static Random random = new Random(); private static void Main(string[] args) { Console.WriteLine("Kamen Nuzky Papir"); while (true) { Console.WriteLine("-----------------------------------------------------"); Console.WriteLine("Kamen - k\nNuzky - n\nPapir - p\n"); Console.WriteLine("Zadejte svoji figuru:"); char userInput = Console.ReadKey().KeyChar; char pcInput = GenerateRandomFigure(); Console.WriteLine(); Console.WriteLine(); if (userInput != pcInput) { if (userInput == 'k' && pcInput == 'n') Console.WriteLine("Kámen ztupí nůžky, vyhrál jsi"); else if (userInput == 'n' && pcInput == 'k') Console.WriteLine("Kámen ztupí nůžky, prohrál jsi"); else if (userInput == 'p' && pcInput == 'k') Console.WriteLine("Papír zabalí kámen, vyhrál jsi"); else if (userInput == 'k' && pcInput == 'p') Console.WriteLine("Papír zabalí kámen, prohrál jsi"); else if (userInput == 'n' && pcInput == 'p') Console.WriteLine("Nůžky přestřihnou papír, vyhrál jsi"); else if (userInput == 'p' && pcInput == 'n') Console.WriteLine("Nůžky přestřihnou papír, prohrál jsi"); } else Console.WriteLine("Remíza"); Console.ReadKey(true); Console.Clear(); } } private static char GenerateRandomFigure() { switch (random.Next(0, 3)) { case 0: return 'k'; case 1: return 'n'; default: return 'k'; } } } }
using System; using System.Configuration; namespace Pe.GyM.SGC.Cross.Core.Base { /// <summary> /// Clase My Credencial /// </summary> [Serializable] public class ReporteCredencial : Microsoft.Reporting.WebForms.IReportServerCredentials { private static readonly string Usuario = ConfigurationManager.AppSettings["SrvReportingUser"]; public static readonly string Clave = ConfigurationManager.AppSettings["SrvReportingPassword"]; public static readonly string Domain = ConfigurationManager.AppSettings["SrvReportingDomain"]; /// <summary> /// Método pa obtener las credenciales de forma /// </summary> /// <param name="authCookie">Creador de la cookie</param> /// <param name="userName">Nombre del usuario</param> /// <param name="password">Contraseña</param> /// <param name="authority">Cargo</param> /// <returns>Verdadero o Falso</returns> public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority) { authCookie = null; userName = null; password = null; authority = null; return false; } /// <summary> /// ImpersonationUser /// </summary> public System.Security.Principal.WindowsIdentity ImpersonationUser { get { return null; } } /// <summary> /// NetworkCredentials /// </summary> public System.Net.ICredentials NetworkCredentials { get { return new System.Net.NetworkCredential(Usuario, Clave, Domain); } } } }
using Newtonsoft.Json; namespace DevilDaggersCore.Game { [JsonObject(MemberSerialization.OptIn)] public class Enemy : DevilDaggersEntity { [JsonProperty] public int HP { get; set; } [JsonProperty] public int Gems { get; set; } [JsonProperty] public Death Death { get; set; } [JsonProperty] public float? Homing3 { get; set; } [JsonProperty] public float? Homing4 { get; set; } [JsonProperty] public bool RegisterKill { get; set; } [JsonProperty] public Enemy[] SpawnedBy { get; set; } public int GemHP => HP / Gems; public Enemy(string name, string colorCode, int hp, int gems, Death death, float? homing3, float? homing4, bool registerKill, params Enemy[] spawnedBy) : base(name, colorCode) { HP = hp; Gems = gems; Death = death; Homing3 = homing3; Homing4 = homing4; RegisterKill = registerKill; SpawnedBy = spawnedBy; } public string GetGemHPString() { return $"({GemHP} x {Gems})"; } public Enemy Copy() { return new Enemy(Name, ColorCode, HP, Gems, Death, Homing3, Homing4, RegisterKill, SpawnedBy); } } }
using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; using TestApplication.Interfaces; using TestApplication.Services; namespace TestApplication { class Program { private static ServiceProvider _serviceProvider; static async Task Main(string[] args) { var isSuccess = true; var collection = new ServiceCollection(); RegisterServices(collection); using (_serviceProvider = collection.BuildServiceProvider()) { var wordProcessor = CreateCompoundWordProcessor(); try { await wordProcessor.SplitWords(); } catch (Exception ex) { Console.WriteLine(ex); isSuccess = false; } } var message = isSuccess ? "Input words have been split successfuly!" : "Input words haven't been split! Please see an error for more details."; Console.WriteLine(message); Console.ReadLine(); } private static void RegisterServices(ServiceCollection collection) { collection.AddScoped<ICompoundWordProcessor, CompoundWordProcessor>(); collection.AddScoped<IFileService<string>, TextFileService>(); collection.AddScoped<IParseService, ParseService>(); } private static ICompoundWordProcessor CreateCompoundWordProcessor() { return _serviceProvider.GetService<ICompoundWordProcessor>(); } } }
using Spire.Barcode; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Visitors.DAO; using Visitors.DAOImpl; using Visitors.entity; namespace Visitors.View { /// <summary> /// Interaction logic for ViewVisitorDetails.xaml /// </summary> public partial class ViewVisitorDetails : UserControl { public ViewVisitorDetails() { InitializeComponent(); } private void dataGridUser_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void searchUserNameBtn_Click_1(object sender, RoutedEventArgs e) { if(UserNameTxt.Text.Trim()=="") { MessageBox.Show("Please enter user name!"); } else { UserMaster usrmasterRef = new UserMaster(); usrmasterRef.username = UserNameTxt.Text.Trim(); RoleMaster rolemasterRef = new RoleMaster(); rolemasterRef.roleName = null; usrmasterRef.designationRef = rolemasterRef; UserMasterDAO userMasterDaoRef = new UserMasterDAOImpl(); List<string> listNm = new List<string>(); listNm.Add("user Id"); listNm.Add("User Name"); listNm.Add("Mobile No"); listNm.Add("Address"); listNm.Add("gender"); listNm.Add("Email Id"); listNm.Add("DOB"); listNm.Add("password"); listNm.Add("designation"); List<List<string>> itemList = new List<List<string>>(); List<ArrayList> usrList = new List<ArrayList>(); usrList = userMasterDaoRef.getUsrList(usrmasterRef); if (usrList.Count == 0) { Console.WriteLine("inside if null"); QRCodeBtn.Visibility = Visibility.Hidden; dataGridUser.ItemsSource = null; image1.Visibility = Visibility.Hidden; } else { Console.WriteLine("inside else null"); DataTable dt = CreateDataTable(listNm, usrList); dataGridUser.ItemsSource = dt.DefaultView; } } } private System.Data.DataTable CreateDataTable(List<string> columnDefinitions, List<ArrayList> rows) { QRCodeBtn.Visibility = Visibility.Visible; DataTable table = new DataTable(); foreach (string colDef in columnDefinitions) { DataColumn column; column = new DataColumn(); column.DataType = typeof(string); column.ColumnName = colDef; table.Columns.Add(column); } // Create DataRow and Add it to table foreach (ArrayList rowData in rows) { DataRow row = table.NewRow(); // rowData is in same order as columnDefinitions for (int i = 0; i < rowData.Count; i++) { row[i] = rowData[i]; } table.Rows.Add(row); } return table; } private void RadButton_Click(object sender, RoutedEventArgs e) { UserNameTxt.Text = ""; UserMasterDAO userMasterDaoRef = new UserMasterDAOImpl(); List<string> listNm = new List<string>(); listNm.Add("user Id"); listNm.Add("User Name"); listNm.Add("Mobile No"); listNm.Add("Address"); listNm.Add("gender"); listNm.Add("Email Id"); listNm.Add("DOB"); listNm.Add("password"); listNm.Add("designation"); // List<List<string>> itemList = new List<List<string>>(); List<ArrayList> usrList = new List<ArrayList>(); usrList = userMasterDaoRef.getUsrList(null); DataTable dt = CreateDataTable(listNm, usrList); dataGridUser.ItemsSource = dt.DefaultView; dataGridUser.Columns[0].IsReadOnly = true; dataGridUser.Columns[1].IsReadOnly = false; dataGridUser.Columns[2].IsReadOnly = false; dataGridUser.Columns[3].IsReadOnly = false; dataGridUser.Columns[4].IsReadOnly = false; dataGridUser.Columns[5].IsReadOnly = false; dataGridUser.Columns[6].IsReadOnly = false; dataGridUser.Columns[7].IsReadOnly = false; dataGridUser.Columns[8].IsReadOnly = true; } private void QRCodeBtn_Click(object sender, RoutedEventArgs e) { // if (dataGridUser.ItemsSource == "") // { // MessageBox.Show("No Data!"); // } // else { UserMaster usrMasterRef = new UserMaster(); UserMasterDAO usrMasterDAORef = new UserMasterDAOImpl(); DataRowView row = (DataRowView)dataGridUser.SelectedItems[0]; int id = Convert.ToInt32(row["user Id"]); usrMasterRef = usrMasterDAORef.findbyprimaryKey(id); QrCodegenerator(usrMasterRef); image1.Visibility = Visibility.Visible; } } private void QrCodegenerator(UserMaster usrMasterRef) { BarcodeSettings.ApplyKey("your key");//you need a key from e-iceblue, otherwise the watermark 'E-iceblue' will be shown in barcode BarcodeSettings settings = new BarcodeSettings(); settings.Type = BarCodeType.QRCode; settings.Unit = GraphicsUnit.Pixel; settings.ShowText = false; settings.ResolutionType = ResolutionType.UseDpi; string data = "UserName :" + usrMasterRef.username + "\nMobileNo : " + usrMasterRef.mobileNo + "\ngender : " + usrMasterRef.gender+"\nAddress : "+usrMasterRef.address+"\nEmail Id : "+usrMasterRef.emailId; // Console.WriteLine("Usren mae:{0} password:{1} Mobile No={2} gender={3}", u.username, u.pwd, u.mobileNo, u.gender); settings.Data = data; string foreColor = "Black"; string backColor = "White"; settings.ForeColor = System.Drawing.Color.FromName(foreColor); settings.BackColor = System.Drawing.Color.FromName(backColor); settings.X = Convert.ToInt16(30); short leftMargin = 1; settings.LeftMargin = leftMargin; short rightMargin = 1; settings.RightMargin = rightMargin; short topMargin = 1; settings.TopMargin = topMargin; short bottomMargin = 1; settings.BottomMargin = bottomMargin; settings.QRCodeECL = QRCodeECL.L; BarCodeGenerator generator = new BarCodeGenerator(settings); System.Drawing.Image QRbarcode = generator.GenerateImage(); image1.Source = BitmapToImageSource(QRbarcode); } private ImageSource BitmapToImageSource(System.Drawing.Image bitmap) { //throw new NotImplementedException(); using (MemoryStream memory = new MemoryStream()) { bitmap.Save(memory, ImageFormat.Bmp); memory.Position = 0; BitmapImage bitmapimage = new BitmapImage(); bitmapimage.BeginInit(); bitmapimage.StreamSource = memory; bitmapimage.CacheOption = BitmapCacheOption.OnLoad; bitmapimage.EndInit(); return bitmapimage; } } } }
using Datalayer.Domain; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; namespace Datalayer.EFConfigurations { public class CourseConfiguration : IEntityTypeConfiguration<Course> { public void Configure(EntityTypeBuilder<Course> builder) { builder.HasKey(c => c.Id); builder.Property(c => c.Id).UseIdentityColumn(); builder.Property(c => c.Description).HasMaxLength(250); builder.Property(c => c.InstructorId).IsRequired(true); builder.HasOne(c => c.Instructor).WithMany(I => I.Courses).HasForeignKey(c => c.InstructorId); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using TimeTableApi.Application.Shared.EventManagement; using TimeTableApi.Application.Shared.EventManagement.Dtos; namespace TimeTableApi.Controllers { [Route("Event")] [Authorize] public class EventController : Controller { private readonly IEventAppService _eventAppService; public EventController(IEventAppService eventAppService) { _eventAppService = eventAppService; } [HttpGet] [Route("GetAll")] public List<EventDto> GetAll() { var user = User.Claims.FirstOrDefault(); return _eventAppService.GetAll(user.Value); } [HttpGet] [Route("GetById/{id}")] public EventDto GetById(string id) { return _eventAppService.GetById(id); } [HttpPost] [Route("CreateOrUpdate")] public bool CreateOrUpdate([FromBody] CreateOrEditEventInputDto input) { return _eventAppService.CreateOrUpdate(input); } [HttpDelete] [Route("delete/{id}")] public void Delte(string id) { _eventAppService.Remove(id); } [HttpPost] [Route("UploadEventImage")] public async Task UploadEventImage([FromForm] ImageDto input) { if (input == null) return; var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot/content", input.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await input.Image.CopyToAsync(stream); } return; } } }
using AutoFixture; using MediatR; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Controllers; using SFA.DAS.ProviderUrlHelper; using System.Threading.Tasks; using System.Threading; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.Authorization.Services; using SFA.DAS.Encoding; using SFA.DAS.ProviderCommitments.Web.Authentication; using SFA.DAS.ProviderCommitments.Interfaces; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.CohortControllerTests { [TestFixture] public class WhenIPostDeleteCohortViewModel { [Test] public async Task PostDeleteCohortViewModel_WithValidModel_WithConfirmFalse_ShouldRedirectToSelectEmployer() { var fixture = new PostDeleteCohortFixture() .WithConfirmFalse(); var result = await fixture.Act(); result.VerifyReturnsRedirectToActionResult().WithActionName("Details"); ; } [Test] public async Task PostDeleteCohortViewModel_WithValidModel_WithConfirmTrue_ShouldDeleteCohort() { var fixture = new PostDeleteCohortFixture() .WithConfirmTrue(); await fixture.Act(); fixture.VerifyCohortDeleted(); } [Test] public async Task PostDeleteCohortViewModel_WithValidModel_WithConfirmTrue_ShouldRedirectToCohortsPage() { var fixture = new PostDeleteCohortFixture() .WithConfirmTrue(); var result = await fixture.Act(); result.VerifyReturnsRedirectToActionResult().WithActionName("Review"); } } public class PostDeleteCohortFixture { public CohortController Sut { get; set; } public string RedirectUrl; private readonly Mock<ILinkGenerator> _linkGenerator; private readonly Mock<IModelMapper> _mockModelMapper; private readonly Mock<ICommitmentsApiClient> _commitmentApiClient; private readonly DeleteCohortViewModel _viewModel; private readonly UserInfo _userInfo; private readonly Mock<IAuthenticationService> _authenticationService; public PostDeleteCohortFixture() { var fixture = new Fixture(); _viewModel = fixture.Create<DeleteCohortViewModel>(); _userInfo = fixture.Create<UserInfo>(); _commitmentApiClient = new Mock<ICommitmentsApiClient>(); _mockModelMapper = new Mock<IModelMapper>(); _authenticationService = new Mock<IAuthenticationService>(); _authenticationService.Setup(x => x.UserInfo).Returns(_userInfo); _commitmentApiClient .Setup(x => x.DeleteCohort(_viewModel.CohortId, _userInfo , It.IsAny<CancellationToken>())).Returns(Task.FromResult(0)); RedirectUrl = $"{_viewModel.ProviderId}/apprentices/{_viewModel.CohortReference}/Details"; _linkGenerator = new Mock<ILinkGenerator>(); _linkGenerator.Setup(x => x.ProviderApprenticeshipServiceLink(RedirectUrl)).Returns(RedirectUrl); Sut = new CohortController(Mock.Of<IMediator>(), _mockModelMapper.Object, _linkGenerator.Object, _commitmentApiClient.Object, Mock.Of<IAuthorizationService>(), Mock.Of<IEncodingService>(), Mock.Of<IOuterApiService>()); } public PostDeleteCohortFixture WithConfirmFalse() { _viewModel.Confirm = false; return this; } public PostDeleteCohortFixture WithConfirmTrue() { _viewModel.Confirm = true; return this; } public PostDeleteCohortFixture VerifyCohortDeleted() { _commitmentApiClient.Verify(x => x.DeleteCohort(_viewModel.CohortId, _userInfo, It.IsAny<CancellationToken>()), Times.Once); return this; } public async Task<IActionResult> Act() => await Sut.Delete(_authenticationService.Object, _viewModel); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using BookLibrary.Data; using BookLibrary.Services; using BookLibrary.ViewModels; namespace BookLibrary.Controllers { [Route("api/books")] [ApiController] public class BooksApiController : ControllerBase { private readonly BooksService _booksService; public BooksApiController(ApplicationDbContext db, IMapper mapper) { _booksService = new BooksService(db, mapper); } // GET: api/books [HttpGet] public async Task<IActionResult> Index() { IEnumerable<BookViewModel> booksList; try { booksList = await _booksService.GetBooksCollection(); } catch (Exception e) { return BadRequest(e.Message); } return Ok(booksList); } // GET: api/books/5 [HttpGet("{id}")] public async Task<IActionResult> Details(int? id) { BookViewModel bookViewModel; try { bookViewModel = await _booksService.GetBookDetails(id); } catch (ArgumentException e) { return NotFound(e.Message); } catch (Exception e) { return BadRequest(e.Message); } return Ok(bookViewModel); } // POST: api/books [HttpPost] public async Task<IActionResult> Create(BookViewModel bookViewModel) { try { int bookId = await _booksService.CreateBook(bookViewModel); bookViewModel = await _booksService.GetBookDetails(bookId); } catch (Exception e) { return BadRequest(e.Message); } return Ok(bookViewModel); } // PUT: api/books/5 [HttpPut("{id}")] public async Task<IActionResult> Edit(int id, BookViewModel bookViewModel) { try { if (id == bookViewModel.Id) { int bookId = await _booksService.EditBook(bookViewModel); bookViewModel = await _booksService.GetBookDetails(bookId); } else { return BadRequest("Parameters are not valid."); } } catch (ArgumentException e) { return NotFound(e.Message); } catch (Exception e) { return BadRequest(e.Message); } return Ok(bookViewModel); } // DELETE: api/books/5 [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { try { await _booksService.DeleteBook(id); } catch (ArgumentException e) { return NotFound(e.Message); } catch (Exception e) { return BadRequest(e.Message); } return Ok(); } } }
using DropDowny.Models; using System.Collections.Generic; namespace DropDowny.CzlowiekFormViewModel { public class CzlowiekFormViewModel { public string Imie { get; set; } public string Nazwisko { get; set; } public int Wyksztalcenie { get; set; } public IEnumerable<Wyksztalcenie> Wyksztalcenies { get; set; } public int Zatrudnienie { get; set; } public IEnumerable<Zatrudnienie> Zatrudnienies { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using MusicIO; public class InstrumentController : MonoBehaviour { //Singleton references private static InstrumentController m_instance; public static InstrumentController Instance{ get { return m_instance; }} //Instrument references protected List<BaseInstrument> m_instruments; protected BaseInstrument m_selectedInstrument; protected GameObject m_lastSelectedGameInstrument = null; // Unity //------------------------------------- void Awake () { m_instruments = new List<BaseInstrument>(); m_instance = this; } void Update () { foreach(BaseInstrument instrument in m_instruments){ instrument.update(); } } /* * Instrument reset */ public void ResetInstrumentParameters(BaseInstrument instrument){ instrument.Reset(); foreach(GenericMusicParam param in instrument.paramList){ param.setEnabled(false); } } public void ResetInstrument(BaseInstrument instrument){ ResetInstrumentParameters(instrument); } //Instrument selection //-------------------- public BaseInstrument SelectedInstrument{ get { return m_selectedInstrument; } } /* * Adds an instrument */ public void AddInstrument(BaseInstrument instrument){ m_instruments.Add(instrument); } /* * Gets instrument by name */ public BaseInstrument GetInstrumentByName(string targetInstrument){ foreach(BaseInstrument instrument in m_instruments){ if(instrument.Name == targetInstrument) return instrument; } return null; } public BaseInstrument GetInstrumentByTrackindex(int trackindex) { foreach (BaseInstrument instrument in m_instruments) { if (instrument.trackIndex == trackindex) return instrument; } return null; } /* * Finds a specific parameter by index */ public BaseInstrumentParam FindParameter(int trackindex, int deviceindex, int parameterindex){ foreach (BaseInstrument instrument in m_instruments) { if (instrument.trackIndex == trackindex) { foreach (BaseInstrumentParam param in instrument.paramList) { if (param.deviceIndex == deviceindex && param.parameterIndex == parameterindex) { return param; } } } } return null; } /* * Find a specific clip by index */ public InstrumentClip FindClip(int trackindex, int clipindex) { foreach (BaseInstrument instrument in m_instruments) { if (instrument.trackIndex == trackindex) { foreach (InstrumentClip clip in instrument.clipList) { if (clip.scene == clipindex) { return clip; } } } } return null; } /* * Remembers last selected isntrument */ public void SetLastSelectedGameInstrument(GameObject gameInstrument){ m_lastSelectedGameInstrument = gameInstrument; } /* * Gets last selected isntrument */ public GameObject LastSelectedGameInstrument{ get { return m_lastSelectedGameInstrument; }} }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using SqlServerRunnerNet.Controls.DirectoryTreeView.Data; namespace SqlServerRunnerNet.Controls.DirectoryTreeView.ViewModel { public class DirectoryModelCollection { public List<DirectoryTreeViewItemViewModel> Roots { get; private set; } public DirectoryModelCollection() { Roots = new List<DirectoryTreeViewItemViewModel>(); Roots.AddRange( DriveInfo.GetDrives() .Where(drive => drive.DriveType == DriveType.Fixed) .Select(drive => new DriveViewModel(new Folder(drive.RootDirectory.FullName)))); var firstRoot = Roots.FirstOrDefault(); if (firstRoot != null) firstRoot.IsExpanded = true; } public void SetSelectedFolder(string selectedPath) { if (!Directory.Exists(selectedPath)) return; var folder = EnsureFolder(selectedPath); if (folder != null) folder.IsSelected = true; } public void SetCheckedFolders(List<string> paths) { var firstSelected = false; foreach (var path in paths) { var folder = EnsureFolder(path); if (folder == null) continue; folder.IsChecked = true; if (folder.Parent != null) folder.Parent.IsExpanded = true; if (!firstSelected) { firstSelected = true; folder.IsSelected = true; } } } public DirectoryTreeViewItemViewModel EnsureFolder(string path) { var dirInfo = new DirectoryInfo(path); var segments = GetPathSegments(dirInfo); var currentRoots = new List<DirectoryTreeViewItemViewModel>(Roots); DirectoryTreeViewItemViewModel currentSegment = null; foreach (var segment in segments) { currentSegment = currentRoots.FirstOrDefault( vm => vm.DisplayPath.Equals(segment, StringComparison.InvariantCultureIgnoreCase)); if (currentSegment == null) break; currentSegment.EnsureItemsLoaded(); currentRoots = new List<DirectoryTreeViewItemViewModel>(currentSegment.Children); } return currentSegment; } private static string[] GetPathSegments(DirectoryInfo dirInfo) { var pathStack = new Stack<string>(); DirectoryInfo currentDirInfo = dirInfo; do { pathStack.Push(currentDirInfo.Name); currentDirInfo = currentDirInfo.Parent; } while (currentDirInfo != null); return pathStack.ToArray(); } public List<DirectoryTreeViewItemViewModel> GetCheckedFolders() { return Roots.SelectMany(GetCheckedFolders).ToList(); } private static IEnumerable<DirectoryTreeViewItemViewModel> GetCheckedFolders(DirectoryTreeViewItemViewModel node) { if (node.IsChecked == true) yield return node; if (node.HasDummyChild) yield break; foreach (var subnode in node.Children.SelectMany(GetCheckedFolders)) { yield return subnode; } } } }
using ENTIDAD; using NEGOCIO; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WEB_PROYECTOS.Controllers { public class ProyectoController : Controller { // GET: Proyecto public ActionResult Index() { var proyectos = ProyectoCN.ListarProyectos(); return View(proyectos); } public ActionResult Crear() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Crear(Proyecto proyecto) { try { if(proyecto.NombreProyecto == null) return Json(new { ok = false, toRedirect = "Debe ingresar el nombre del proyecto" }, JsonRequestBehavior.AllowGet); ProyectoCN.Agregar(proyecto); return Json(new { ok = true, toRedirect = "Index" }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new { ok = false, msj = ex.Message }, JsonRequestBehavior.AllowGet); //ModelState.AddModelError("", "Ocurrió un error al agregar un Proyecto"); //return View(); } } } }
namespace Shipwreck.TypeScriptModels { public interface IStatementOwner { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using UseFul.ClientApi; using UseFul.Forms.Welic; namespace UseFul.Forms.Welic { public partial class FormConsulta : FormWelic { public FormConsulta() { InitializeComponent(); } /// <summary> /// Construtor com bloqueio para múltiplas instâncias do formulário /// </summary> /// <param name="frmP">Formulário principal do projeto.</param> public FormConsulta(Form frmP):base(frmP) { InitializeComponent(); } protected void LiberaTelaPermissao() { if (string.IsNullOrEmpty(this.IdProgram)) toolStripBtnPermissao.Visible = false; else toolStripBtnPermissao.Visible = true; } private void FormConsulta_Load(object sender, EventArgs e) { LiberaTelaPermissao(); } private void toolStripBtnBusca_Click(object sender, EventArgs e) { toolStripOpcoes.Focus(); } private void toolStripBtnLimpar_Click(object sender, EventArgs e) { toolStripOpcoes.Focus(); } private void toolStripBtnDetalhar_Click(object sender, EventArgs e) { toolStripOpcoes.Focus(); } private void toolStripBtnExcel_Click(object sender, EventArgs e) { toolStripOpcoes.Focus(); } private void toolStripBtnPermissao_Click(object sender, EventArgs e) { //TODO: Permissão //toolStripOpcoes.Focus(); //frmManutencaoPermissoes frmMP = new frmManutencaoPermissoes(); //frmMP.UsuarioLogado = Globals.Usuario; //frmMP.CodPrograma = this.CodigoSeguranca; //frmMP.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems.LeetCode { public class Problem010 : LeetCodeBase { public override string ProblemName => "Leet Code 10: Regular Expression Matching"; public override string GetAnswer() { Check(IsMatch("aa", "a"), false); Check(IsMatch("aa", "a*"), true); Check(IsMatch("ab", ".*"), true); Check(IsMatch("mississippi", "mis*is*ip*."), true); Check(IsMatch("aaa", "aaaa"), false); Check(IsMatch("a", "ab*a"), false); Check(IsMatch("a", ".*..a*"), false); return ""; } public bool IsMatch(string s, string p) { return IsMatch(s, p, 0, 0); } private bool IsMatch(string s, string p, int sIndex, int pIndex) { for (; pIndex < p.Length; pIndex++) { bool isRepeater = pIndex < p.Length - 1 && p[pIndex + 1] == '*'; if (p[pIndex] == '.') { if (!isRepeater) { if (sIndex > p.Length - 1) return false; } else { return FindRepeatBlank(s, p, sIndex, pIndex + 2); } } else { if (!isRepeater) { if (sIndex == s.Length || s[sIndex] != p[pIndex]) return false; } else { return FindRepeatDigit(s, p, sIndex, pIndex + 2, p[pIndex]); } } if (isRepeater) { sIndex += 2; } else { sIndex++; } } return sIndex == s.Length; } private bool FindRepeatDigit(string s, string p, int sIndex, int pIndex, char digit) { do { var result = IsMatch(s, p, sIndex, pIndex); if (result) return true; sIndex++; if (sIndex >= s.Length) break; if (s[sIndex - 1] != digit) return false; } while (true); return pIndex == p.Length; } private bool FindRepeatBlank(string s, string p, int sIndex, int pIndex) { do { var result = IsMatch(s, p, sIndex, pIndex); if (result) return true; sIndex++; } while (sIndex < s.Length); return pIndex == p.Length; } } }
using KartObjects; namespace KartLib.Entities { public class AxiParam : SimpleDbEntity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Параметры системы"; } } public string Name { get; set; } public string Description { get; set; } public int Status { get; set; } } }
using BlueSky.Commands.File; using BlueSky.Services; using BlueSky.Windows; using BSky.ConfigService.Services; using BSky.ConfService.Intf.Interfaces; using BSky.Interfaces; using BSky.Interfaces.Interfaces; using BSky.Lifetime; using BSky.Lifetime.Interfaces; using BSky.Lifetime.Services; using BSky.RecentFileHandler; using BSky.ServerBridge; using BSky.Statistics.Common; using BSky.Statistics.Service.Engine.Interfaces; using Microsoft.Practices.Unity; using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Windows; using System.Windows.Input; using System.Xml; namespace BlueSky { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { UnityContainer container = new UnityContainer(); public App() { //25Aug2017 To see how Date fomatting changes in the Datagrid Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");//US English Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); //Calling order found was:: Dispatcher -> Main Window -> XAML Application Dispatcher -> Unhandeled AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Dispatcher.UnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException); Application.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Application_DispatcherUnhandledException); MainWindow mwindow = container.Resolve<MainWindow>(); container.RegisterInstance<MainWindow>(mwindow);///new line mwindow.Show(); mwindow.Visibility = Visibility.Hidden; ShowProgressbar(); bool BlueSkyFound = true; string upath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BlueSky"); ;//Per User path string applogpath = BSkyAppData.RoamingUserBSkyLogPath ; DirectoryHelper.UserPath = upath ; LifetimeService.Instance.Container = container; container.RegisterInstance<ILoggerService>(new LoggerService(applogpath)); //Check if user profies has got old files. If so overwrite all(dialogs, modelclasses and other xmls, txt etc.) bool hasOldUserContent = CheckIfOldInUserProfile(); //Copy folders inside Bin/Config to User profile BlueSky\config. if(hasOldUserContent) CopyL18nDialogsToUserRoamingConfig(); //copy config file to user profile. CopyNewAndRetainOldSettings(string.Format(@"{0}BlueSky.exe.config", "./"), string.Format(@"{0}BlueSky.exe.config", BSkyAppData.RoamingUserBSkyConfigPath)); container.RegisterInstance<IConfigService>(new ConfigService());//For App Config file container.RegisterInstance<IAdvancedLoggingService>(new AdvancedLoggingService());//For Advanced Logging ////////////// TRY LOADING BSKY R PACKAGES HERE ///////// ILoggerService logService = container.Resolve<ILoggerService>(); logService.SetLogLevelFromConfig();//loading log level from config file logService.WriteToLogLevel("R.Net,Logger and Config loaded:", LogLevelEnum.Info);/// ////Recent default packages. This code must appear before loading any R package. (including BlueSky R package) XMLitemsProcessor defaultpackages = container.Resolve<XMLitemsProcessor>();//06Feb2014 defaultpackages.MaxRecentItems = 100; if(hasOldUserContent) CopyIfNotExistsOrOld(string.Format(@"{0}DefaultPackages.xml", BSkyAppData.BSkyAppDirConfigPath), string.Format(@"{0}DefaultPackages.xml", BSkyAppData.RoamingUserBSkyConfigPath)); defaultpackages.XMLFilename = string.Format(@"{0}DefaultPackages.xml", BSkyAppData.RoamingUserBSkyConfigPath);//23Apr2015 ;BSkyAppData.BSkyDataDirConfigFwdSlash defaultpackages.RefreshXMLItems(); container.RegisterInstance<XMLitemsProcessor>("defaultpackages", defaultpackages); //Recent user packages. This code must appear before loading any R package. (including uadatapackage) RecentItems userpackages = container.Resolve<RecentItems>();//06Feb2014 userpackages.MaxRecentItems = 100; userpackages.XMLFilename = string.Format(@"{0}UserPackages.xml", BSkyAppData.RoamingUserBSkyConfigPath);//23Apr2015 @"./Config/UserPackages.xml"; userpackages.RefreshXMLItems(); container.RegisterInstance<RecentItems>(userpackages); ////User listed model classes. XMLitemsProcessor modelClasses = container.Resolve<XMLitemsProcessor>();// modelClasses.MaxRecentItems = 100; if (hasOldUserContent) CopyIfNotExistsOrOld(string.Format(@"{0}ModelClasses.xml", BSkyAppData.BSkyAppDirConfigPath), string.Format(@"{0}ModelClasses.xml", BSkyAppData.RoamingUserBSkyConfigPath)); modelClasses.XMLFilename = string.Format(@"{0}ModelClasses.xml", BSkyAppData.RoamingUserBSkyConfigPath);//23Apr2015 ;BSkyAppData.BSkyDataDirConfigFwdSlash modelClasses.RefreshXMLItems(); container.RegisterInstance<XMLitemsProcessor>("modelClasses", modelClasses); if (hasOldUserContent) CopyIfNotExistsOrOld(string.Format(@"{0}GraphicCommandList.txt", BSkyAppData.BSkyAppDirConfigPath), string.Format(@"{0}GraphicCommandList.txt", BSkyAppData.RoamingUserBSkyConfigPath)); try { BridgeSetup.ConfigureContainer(container); } catch (Exception ex) { string s1 = "\n" + BSky.GlobalResources.Properties.Resources.MakeSureRInstalled; string s2 = "\n" + BSky.GlobalResources.Properties.Resources.MakeSure32x64Compatibility; string s3 = "\n" + BSky.GlobalResources.Properties.Resources.MakeSureAnotherBSkySession; string s4 = "\n" + BSky.GlobalResources.Properties.Resources.MakeSureRHOME2LatestR; string s5 = "\n" + BSky.GlobalResources.Properties.Resources.PleaseMakeSure; string mboxtitle0 = "\n" + BSky.GlobalResources.Properties.Resources.CantLaunchBSkyApp; MessageBox.Show(s5 + s1 + s2 + s3 + s4, mboxtitle0, MessageBoxButton.OK, MessageBoxImage.Stop); #region R Home Dir edit prompt HideMouseBusy(); HideProgressbar(); ChangeConfigForRHome(); #endregion logService.WriteToLogLevel("Unable to launch the BlueSky Statistics Application." + s1 + s3, LogLevelEnum.Error); logService.WriteToLogLevel("Exception:" + ex.Message, LogLevelEnum.Fatal); Environment.Exit(0); } finally { HideProgressbar(); } container.RegisterInstance<IDashBoardService>(container.Resolve<XmlDashBoardService>()); container.RegisterInstance<IDataService>(container.Resolve<DataService>()); IOutputWindowContainer iowc = container.Resolve<OutputWindowContainer>(); container.RegisterInstance<IOutputWindowContainer>(iowc); SessionDialogContainer sdc = container.Resolve<SessionDialogContainer>();//13Feb2013 //Recent Files settings RecentDocs rdoc = container.Resolve<RecentDocs>();//21Feb2013 rdoc.MaxRecentItems = 7; rdoc.XMLFilename = string.Format(@"{0}Recent.xml", BSkyAppData.RoamingUserBSkyConfigPath);//23Apr2015 @"./Config/Recent.xml"; container.RegisterInstance<RecentDocs>(rdoc); Window1 window = container.Resolve<Window1>(); container.RegisterInstance<Window1>(window);///new line window.Closed += new EventHandler(window_Closed); //28Jan2013 window.Owner = mwindow; //28Jan2013 //17Apr2017 Showing version number on titlebar of main window Version ver = Assembly.GetExecutingAssembly().GetName().Version; string strfullversion = ver.ToString(); //Full version with four parts string shortversion = string.Format("{0}.{1}", ver.Major.ToString(), ver.Minor.ToString()); string titlemsg = string.Empty; titlemsg = string.Format("BlueSky Statistics (Open Source Desktop Edition. Ver- {0})", shortversion); window.Title = titlemsg; window.Show(); window.Activate(); ShowMouseBusy();//02Apr2015 show mouse busy //// one Syntax Editor window for one session ////29Jan2013 SyntaxEditorWindow sewindow = container.Resolve<SyntaxEditorWindow>(); container.RegisterInstance<SyntaxEditorWindow>(sewindow);///new line sewindow.Owner = mwindow; #region Create Column Significance codes List SignificanceCodesHandler.CreateSignifColList(); #endregion //load default packages window.setLMsgInStatusBar(BSky.GlobalResources.Properties.Resources.StatMsgPkgLoad); IAnalyticsService IAService = LifetimeService.Instance.Container.Resolve<IAnalyticsService>(); BridgeSetup.LoadDefaultRPackages(IAService); string PkgLoadStatusMessage = BridgeSetup.PkgLoadStatusMessage; if (PkgLoadStatusMessage != null && PkgLoadStatusMessage.Trim().Length > 0) { StringBuilder sb = new StringBuilder(); string[] defpacklist = PkgLoadStatusMessage.Split('\n'); foreach (string s in defpacklist) { if (s != null && (s.ToLower().Contains("error")))//|| s.ToLower().Contains("warning"))) { //sb.Append(s.Substring(0, s.IndexOf(". ")) + "\n"); sb.Append(s.Replace("Error loading R package:", "") + "\n"); } } if (sb.Length > 0) { sb.Remove(sb.Length - 1, 1);//removing last comma string defpkgs = sb.ToString(); string firstmsg = BSky.GlobalResources.Properties.Resources.ErrLoadingRPkg + "\n\n"; string msg = "\n\n" + BSky.GlobalResources.Properties.Resources.InstallReqRPkgFrmCRAN + "\n" + BSky.GlobalResources.Properties.Resources.RegPkgsMenuPath;// + HideMouseBusy(); string mboxtitle1 = BSky.GlobalResources.Properties.Resources.ErrReqRPkgMissing; MessageBox.Show(firstmsg + defpkgs + msg, mboxtitle1, MessageBoxButton.OK, MessageBoxImage.Error); Window1.DatasetReqPackages = defpkgs; BlueSkyFound = false; } } //deimal default should be set here as now BlueSky is loaded window.SetRDefaults(); IAdvancedLoggingService advlog = container.Resolve<IAdvancedLoggingService>(); ;//01May2015 advlog.RefreshAdvancedLogging(); window.setInitialAllModels();//select All_Models in model class dropdown. window.setLMsgInStatusBar(""); HideMouseBusy();//02Apr2015 hide mouse busy if (BlueSkyFound) { try { FileNewCommand newds = new FileNewCommand(); newds.NewFileOpen(""); } catch (Exception ex) { string so = BSky.GlobalResources.Properties.Resources.ErrLoadingNewDS; string mboxtitle2 = BSky.GlobalResources.Properties.Resources.BSkyPkgMissing; logService.WriteToLogLevel("ERROR: " + ex.Message, LogLevelEnum.Error); MessageBox.Show(so, mboxtitle2, MessageBoxButton.OK, MessageBoxImage.Error); } } } #region Check a flag if new files are copied to user profile private string[] GetAppVersionParts() { string appversion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); string[] verparts = appversion.Split('.'); return verparts; } private bool CheckIfOldInUserProfile() { ILoggerService logService = container.Resolve<ILoggerService>(); bool CopyfilesToUserProfile = true; string appversion = string.Empty; string[] verparts = GetAppVersionParts(); if (verparts != null && verparts.Length >= 3) { appversion = verparts[0] + verparts[1]+ verparts[2]; } else { return CopyfilesToUserProfile; } string versionline= "0000";//putting low version number string verfile = string.Format(@"{0}ver.txt", BSkyAppData.RoamingUserBSkyConfigPath); bool verfileExists = File.Exists(verfile); string[] lines = null; try { if (verfileExists) lines = System.IO.File.ReadAllLines(@verfile); } catch (Exception ex) { logService.WriteToLogLevel("Error reading user profile version-file", LogLevelEnum.Error); logService.WriteToLogLevel("ERROR: " + ex.Message, LogLevelEnum.Error); } if (!verfileExists) { createUserProfileVerFile(); CopyfilesToUserProfile = true; } else { int numOflines = lines.Length; if (numOflines >= 2) { string[] parts = lines[1].Split('.'); if (parts != null) versionline = parts[0] + parts[1] + parts[2];//no dots; } //conver to numeric long appver, verline; bool appversuccess = long.TryParse(appversion, out appver); bool verlinesuccess = long.TryParse(versionline, out verline); if (appver > verline) { CopyfilesToUserProfile = true; createUserProfileVerFile(); } else { CopyfilesToUserProfile = false; } } return CopyfilesToUserProfile; } private void createUserProfileVerFile() { ILoggerService logService = container.Resolve<ILoggerService>(); string ver = Assembly.GetExecutingAssembly().GetName().Version.ToString();//"5.35.12345"; string[] lines = { "Do not modify this file.", ver }; string verfile = string.Format(@"{0}ver.txt", BSkyAppData.RoamingUserBSkyConfigPath); System.IO.StreamWriter file = null; try { file = new System.IO.StreamWriter(verfile,false); foreach (string line in lines) { file.WriteLine(line); } } catch (Exception ex) { logService.WriteToLogLevel("Error creating user profile version-file", LogLevelEnum.Error); logService.WriteToLogLevel("ERROR: " + ex.Message, LogLevelEnum.Error); } finally { file.Close(); } } #endregion #region Copy config private void CopyL18nDialogsToUserRoamingConfig() { string sourceDirectory = @".\Config"; string targetDirectory = BSkyAppData.RoamingUserBSkyConfigPath; DirectoryInfo diSource = new DirectoryInfo(sourceDirectory); DirectoryInfo diTarget = new DirectoryInfo(targetDirectory); foreach (DirectoryInfo diSourceSubDir in diSource.GetDirectories()) { DirectoryInfo nextTargetSubDir = diTarget.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir); } } public static void CopyAll(DirectoryInfo source, DirectoryInfo target) { if (Directory.Exists(target.FullName) == false) { Directory.CreateDirectory(target.FullName); } foreach (FileInfo fi in source.GetFiles()) { fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); } } #endregion //copy xml files private void CopyIfNotExistsOrOld(string source, string destination) { ILoggerService logService = container.Resolve<ILoggerService>(); try { if (!File.Exists(destination)) { File.Copy(source, destination); } else { File.Copy(source, destination, true); } } catch (Exception ex) { logService.WriteToLogLevel("Error copying " + Path.GetFileName(source) + " to Roaming", LogLevelEnum.Error); logService.WriteToLogLevel("ERROR: " + ex.Message, LogLevelEnum.Error); } } private void CopyNewAndRetainOldSettings(string source, string destination) { bool userconfigexists = File.Exists(destination); if (userconfigexists) { NameValueCollection usrconfigs; usrconfigs = ReadUserProfConfig(destination) as NameValueCollection; NameValueCollection binconfigs; binconfigs = ReadUserProfConfig(source) as NameValueCollection; string usrconfigver = usrconfigs.Get("version"); string binconfigver = binconfigs.Get("version"); double usrver = 0.0; bool usrsuccess = Double.TryParse(usrconfigver, out usrver); double binver = 0.0; bool binsuccess = Double.TryParse(binconfigver, out binver); bool isbinnew = false; if (usrsuccess && binsuccess) { if (binver > 0 && binver > usrver) { //bin has newer version isbinnew = true; } } else { isbinnew = true; } if (isbinnew) { //copy bin config to user profile. File.Copy(source, destination, true); SaveConfigToFile(usrconfigs, destination); } } else { File.Copy(source, destination); } } //read config from user profile and get all settings private NameValueCollection ReadUserProfConfig(string destination) { NameValueCollection kvpairs = new NameValueCollection(); XmlDocument xmldoc = new XmlDocument(); XmlNodeList xmlnode; int i = 0; string str = null; string appConfigFullPathFilename = @destination; FileStream fs = new FileStream(appConfigFullPathFilename, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.SelectNodes("/configuration/appSettings/add"); for (i = 0; i <= xmlnode.Count - 1; i++) { string attrkey = xmlnode[i].Attributes["key"].Value; string attrVal = xmlnode[i].Attributes["value"].Value; kvpairs.Add(attrkey, attrVal); } fs.Close(); return kvpairs; } //save config setting to a file private void SaveConfigToFile(NameValueCollection _appSettings, string destination) { XmlDocument xmldoc = new XmlDocument(); string appConfigFullPathFilename = destination; xmldoc.Load(appConfigFullPathFilename); XmlNodeList xmlnode = xmldoc.SelectNodes("/configuration/appSettings/add"); string key = string.Empty; string vals = string.Empty; string binvals = string.Empty; //user configuration is overwritten with bin config value. for (int i = 0; i <= xmlnode.Count - 1; i++) { key = xmlnode[i].Attributes["key"].Value; if(key.Equals("version")) { continue; } vals = _appSettings.Get(key); binvals = xmlnode[i].Attributes["value"].Value; if (binvals != null && binvals.Contains("BSkyOverwrite")) { vals = binvals.Replace("BSkyOverwrite", "").Trim(); } xmlnode[i].Attributes["value"].Value = vals; } xmldoc.Save(appConfigFullPathFilename); } private void ChangeConfigForRHome() { IConfigService confService = container.Resolve<IConfigService>(); string rhome = confService.GetConfigValueForKey("rhome"); RHomeConfigWindow rhmconfwin = new RHomeConfigWindow(); //rhmconfwin.Owner = rhmconfwin.WindowStartupLocation = WindowStartupLocation.CenterScreen; rhmconfwin.RHomeText.Text = rhome; rhmconfwin.ShowDialog(); string newRHome = rhmconfwin.RHomeText.Text; confService.ModifyConfig("rhome", newRHome); } #region Exit/Close related // App-win closed. Now close invisible owner(parent). void window_Closed(object sender, EventArgs e)//28Jan2013 { MainWindow mwindow = LifetimeService.Instance.Container.Resolve<MainWindow>(); mwindow.Close();//close invisible parent and all child windows(app-window, out-win, syntax-win) should go. } void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { ILoggerService logService = LifetimeService.Instance.Container.Resolve<ILoggerService>(); logService.WriteToLogLevel("Unhandled Exception Occured :", LogLevelEnum.Fatal, e.ExceptionObject as Exception); MessageBox.Show("Unhandled:" + e.ExceptionObject.ToString(), "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error); //LifetimeService.Instance.Container.Dispose(); //logService.WriteToLogLevel("Lifetime Service Disposed!", LogLevelEnum.Info); GracefulExit(); Environment.Exit(0);//We can remove this and can try to recover APP and keep it running. } static void CurrentDomain_ProcessExit(object sender, EventArgs e) { //ILoggerService logService = LifetimeService.Instance.Container.Resolve<ILoggerService>(); //LifetimeService.Instance.Container.Dispose(); //logService.WriteToLogLevel("Lifetime Service Disposed!", LogLevelEnum.Info); } private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { ILoggerService logService = LifetimeService.Instance.Container.Resolve<ILoggerService>(); logService.WriteToLogLevel("XAML Application Dispatcher Unhandled Exception Occured :", LogLevelEnum.Fatal, e.Exception); MessageBox.Show("XAML Application Dispatcher:" + e.Exception.ToString()); e.Handled = true;/// if you false this and comment following line, then, exception goes to Unhandeled GracefulExit(); Environment.Exit(0);//We can remove this and can try to recover APP and keep it running. } private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { ILoggerService logService = LifetimeService.Instance.Container.Resolve<ILoggerService>(); logService.WriteToLogLevel("Dispatcher Unhandled Exception Occured :", LogLevelEnum.Fatal, e.Exception); MessageBox.Show("Dispatcher:" + e.Exception.ToString(), "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error); e.Handled = true;/// if you false this and comment following line, then, exception goes to App's main window GracefulExit(); Environment.Exit(0); //We can remove this and can try to recover APP and keep it running. } //19Feb2013 For closing mainwindow which should close child and each child should ask for "save". This is not working this way. private void GracefulExit() { System.Windows.Input.Mouse.OverrideCursor = null;//make mouse free Window1 mwindow = LifetimeService.Instance.Container.Resolve<Window1>(); mwindow.IsException = true; mwindow.Close(); } #endregion #region Progressbar SplashWindow sw = null; Cursor defaultcursor; //Shows Progressbar private void ShowProgressbar() { sw = new SplashWindow("Please wait. Loading BSky Environment..."); sw.Owner = (Application.Current.MainWindow); //bw.WindowStartupLocation = WindowStartupLocation.CenterOwner; //bw.Visibility = Visibility.Visible; sw.Show(); sw.Activate(); defaultcursor = Mouse.OverrideCursor; Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; } //Hides Progressbar private void HideProgressbar() { if (sw != null) { sw.Close(); // close window if it exists //sw.Visibility = Visibility.Hidden; //sw = null; } Mouse.OverrideCursor = defaultcursor; } #endregion #region Mouse Busy //Cursor defaultcursor; //Shows busy mouse private void ShowMouseBusy() { defaultcursor = Mouse.OverrideCursor; Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait; } //Hides busy mouse private void HideMouseBusy() { Mouse.OverrideCursor = defaultcursor; } #endregion #region Citrix Server private bool IsCitrixServer() { bool isCitrix = false; XmlDocument xmldoc = new XmlDocument(); if (File.Exists("CSettings.xml")) { xmldoc.Load("CSettings.xml"); XmlNodeList xnlist = xmldoc.SelectNodes("configuration/appSettings/add[@key='BSkyCServer']"); if (xnlist.Count > 0) { string boolstr = xnlist[0].Attributes[1].Value; if (boolstr.Equals("true")) isCitrix = true; } } return isCitrix; } #endregion } }
 using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; namespace Anywhere2Go.DataAccess.Entity { public class RolePermission { public int permissionId { get; set; } public int roleId { get; set; } public bool? userView { get; set; } public bool? userAdd { get; set; } public bool? userEdit { get; set; } public bool? userDelete { get; set; } public bool? blogView { get; set; } public bool? blogAdd { get; set; } public bool? blogEdit { get; set; } public bool? blogDelete { get; set; } public DateTime? createDate { get; set; } public DateTime? updateDate { get; set; } public string createBy { get; set; } public string updateBy { get; set; } //public virtual Role Role { get; set; } public virtual Permission Permission { get; set; } //public virtual Role Role { get; set; } /* //public virtual ICollection<Role> Roles { get; set; } //public virtual ICollection<Permission> Permissions { get; set; } */ } public class RolePermissionConfig : EntityTypeConfiguration<RolePermission> { public RolePermissionConfig() { // Table & Column Mappings ToTable("RolePermission"); Property(t => t.permissionId).HasColumnName("permission_id"); Property(t => t.roleId).HasColumnName("role_id"); Property(t => t.userView).HasColumnName("user_view"); Property(t => t.userAdd).HasColumnName("user_add"); Property(t => t.userEdit).HasColumnName("user_edit"); Property(t => t.userDelete).HasColumnName("user_delete"); Property(t => t.blogView).HasColumnName("blog_view"); Property(t => t.blogAdd).HasColumnName("blog_add"); Property(t => t.blogEdit).HasColumnName("blog_edit"); Property(t => t.blogDelete).HasColumnName("blog_delete"); Property(t => t.createDate).HasColumnName("create_date"); Property(t => t.updateDate).HasColumnName("update_date"); Property(t => t.createBy).HasColumnName("create_by"); Property(t => t.updateBy).HasColumnName("update_by"); // Primary Key HasKey(t => new { t.permissionId, t.roleId }); // Foreign keys // HasRequired(a => a.Permission).WithMany(b => b.RolePermissions).HasForeignKey(c => c.permissionId); // FK_RolePermissions_Permissions //HasRequired(a => a.Role).WithMany(b => b.RolePermissions).HasForeignKey(c => c.roleId); // FK_RolePermissions_Roles } } }
using SciVacancies.ReadModel.Core; using System; using System.Collections.Generic; using NPoco; using MediatR; namespace SciVacancies.WebApp.Queries { public class ResearcherQueriesHandler : IRequestHandler<SingleResearcherQuery, Researcher>, IRequestHandler<SelectResearcherPublicationsQuery, IEnumerable<Publication>>, IRequestHandler<SelectResearcherEducationsQuery, IEnumerable<Education>> { private readonly IDatabase _db; public ResearcherQueriesHandler(IDatabase db) { _db = db; } public Researcher Handle(SingleResearcherQuery message) { if (message.ResearcherGuid == Guid.Empty) throw new ArgumentNullException($"ResearcherGuid is empty: {message.ResearcherGuid}"); Researcher researcher = _db.SingleOrDefaultById<Researcher>(message.ResearcherGuid); return researcher; } public IEnumerable<Publication> Handle(SelectResearcherPublicationsQuery msg) { IEnumerable<Publication> resPublications = _db.Fetch<Publication>(new Sql($"SELECT * FROM res_publications rp WHERE rp.researcher_guid = @0", msg.ResearcherGuid)); return resPublications; } public IEnumerable<Education> Handle(SelectResearcherEducationsQuery msg) { IEnumerable<Education> resEducations = _db.Fetch<Education>(new Sql($"SELECT * FROM res_educations re WHERE re.researcher_guid = @0", msg.ResearcherGuid)); return resEducations; } } }
namespace Sila.Models.Rest.Requests { using System; /// <summary> /// The structure of a create assembly request. /// </summary> public class CreateAssemblyRequest { /// <summary> /// The name of the assembly. /// </summary> public String Name { get; } /// <summary> /// Instantiate a create assembly request. /// </summary> /// <param name="name">The name of the assembly.</param> public CreateAssemblyRequest(String name) { Name = name; } } }
using System; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference of type `Collision2D`. Inherits from `AtomEventReference&lt;Collision2D, Collision2DVariable, Collision2DEvent, Collision2DVariableInstancer, Collision2DEventInstancer&gt;`. /// </summary> [Serializable] public sealed class Collision2DEventReference : AtomEventReference< Collision2D, Collision2DVariable, Collision2DEvent, Collision2DVariableInstancer, Collision2DEventInstancer>, IGetEvent { } }
namespace Airelax.Infrastructure.ThirdPartyPayment.ECPay.Definitions { /// <summary> /// 欲使用的付款方式 /// </summary> public enum ChoosePayment { /// <summary> /// 全部付款方式 /// </summary> AllPayment = 0, /// <summary> /// 信用卡一次付清 /// </summary> CreditCardPayAllAtOnce = 1, /// <summary> /// 信用卡分期付款 /// </summary> CreditCardInstallment = 2, /// <summary> /// ATM /// </summary> ATM = 3, /// <summary> /// 超商代碼 /// </summary> CVS = 4, /// <summary> /// 超商條碼 /// </summary> BarCode = 5 } }
using Bolster.API.Status.Stateless; using Bolster.Base; namespace Bolster.API { public abstract class Result { public abstract bool IsSuccess { get; } public abstract bool IsFailure { get; } } }
using Alabo.Domains.Services; using Alabo.Tool.Payment.MiniProgram.Dtos; using ZKCloud.Open.ApiBase.Models; namespace Alabo.Tool.Payment.MiniProgram.Services { /// <summary> /// </summary> /// <seealso cref="Alabo.Domains.Services.IService" /> public interface IMiniProgramService : IService { /// <summary> /// Logins the specified login input. /// </summary> /// <param name="loginInput">The login input.</param> ApiResult<LoginOutput> Login(LoginInput loginInput); ApiResult<LoginOutput> PubLogin(LoginInput loginInput); } }
using System; using System.Collections.Generic; namespace com.Sconit.Entity.SI.SD_ACC { [Serializable] public class User { #region O/R Mapping Properties public Int32 Id { get; set; } public string Code { get; set; } public string Password { get; set; } public string FirstName { get; set; } public string LastName { get; set; } //public TypeEnum Type { get; set; } public string Email { get; set; } public string TelPhone { get; set; } public string MobilePhone { get; set; } public string Language { get; set; } public Boolean IsActive { get; set; } //public Boolean AccountLocked { get; set; } //public DateTime PasswordExpired { get; set; } //public DateTime AccountExpired { get; set; } //public bool IsAuthenticated { get; set; } //public Int32 CreateUserId { get; set; } //public string CreateUserName { get; set; } //public DateTime CreateDate { get; set; } //public Int32 LastModifyUserId { get; set; } //public string LastModifyUserName { get; set; } //public DateTime LastModifyDate { get; set; } #endregion public List<Permission> Permissions { get; set; } public List<BarCodeType> BarCodeTypes { get; set; } } public class BarCodeType { public string PreFixed { get; set; } public OrdType Type { get; set; } } public enum OrdType { ORD, ASN, PIK, STT, INS, SEQ, MIS, } }
using LocusNew.Core.Models; namespace LocusNew.Core.ViewModels { public class ListingsListViewModel { public int Id { get; set; } public string Address { get; set; } public decimal? Price { get; set; } public bool isSold { get; set; } public PropertyType PropertyType { get; set; } public int? Bedrooms { get; set; } public int? Bathrooms { get; set; } public int? SquareMeters { get; set; } public ListingImage Image { get; set; } public int LotSquareMeters { get; set; } public CityPart CityPart { get; set; } public bool isReserved { get; set; } public bool MultiBedrooms { get; set; } public bool MultiBathrooms { get; set; } public bool MultiSquareMeters { get; set; } public int? MultiBedroomsFrom { get; set; } public int? MultiBedroomsTo { get; set; } public int? MultiBathFrom { get; set; } public int? MultiBathTo { get; set; } public int? MultiSquareMetersFrom { get; set; } public int? MultiSquareMetersTo { get; set; } public bool MultiPrice { get; set; } public decimal? MultiPriceFrom { get; set; } public decimal? MultiPriceTo { get; set; } public AdType AdType { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); this.Hide(); } private void Form1_Load(object sender, EventArgs e) { this.Text = "Find Charachter"; this.MinimizeBox = false; this.MaximizeBox = false; Image img = new Bitmap(@"C:\Users\H.S\Downloads\turtle.png"); this.BackgroundImage = img; this.button1.Text = "Start Game"; this.button2.Text = "Exit"; this.button1.BackColor = Color.SlateGray; this.button2.BackColor = Color.SlateGray; this.button1.Font=new Font ("Times New Roman",25); this.button2.Font = new Font("Times New Roman", 25); this.button1.ForeColor = Color.White ; } private void button2_Click(object sender, EventArgs e) { Application.Exit(); } private void button1_Click_1(object sender, EventArgs e) { } private void button1_Click_2(object sender, EventArgs e) { } } }
using gView.Framework.Carto.Rendering.UI; using gView.Framework.Data; using gView.Framework.Data.Filters; using gView.Framework.Geometry; using gView.Framework.IO; using gView.Framework.Symbology; using gView.Framework.system; using gView.Framework.UI; using System; using System.Collections.Generic; using System.Reflection; namespace gView.Framework.Carto.Rendering { [gView.Framework.system.RegisterPlugIn("646386E4-D010-4c7d-98AA-8C1903A3D5E4")] public class SimpleRenderer : Cloner, IFeatureRenderer2, IPropertyPage, ILegendGroup, ISymbolCreator { public enum CartographicMethod { Simple = 0, SymbolOrder = 1 } private ISymbol _symbol; private SymbolRotation _symbolRotation; private bool _useRefScale = true, _rotate = false; private CartographicMethod _cartoMethod = CartographicMethod.Simple, _actualCartoMethod = CartographicMethod.Simple; private List<IFeature> _features = null; public SimpleRenderer() { _symbolRotation = new SymbolRotation(); } public void Dispose() { if (_symbol != null) { _symbol.Release(); } _symbol = null; } public ISymbol Symbol { get { return _symbol; } set { _symbol = value; _rotate = (_symbol is ISymbolRotation && _symbolRotation != null && _symbolRotation.RotationFieldName != ""); } } public ISymbol CreateStandardSymbol(GeometryType type) { return RendererFunctions.CreateStandardSymbol(type); } public ISymbol CreateStandardSelectionSymbol(GeometryType type) { return RendererFunctions.CreateStandardSelectionSymbol(type); } public ISymbol CreateStandardHighlightSymbol(GeometryType type) { return RendererFunctions.CreateStandardHighlightSymbol(type); } public SymbolRotation SymbolRotation { get { return _symbolRotation; } set { if (value == null) { _symbolRotation.RotationFieldName = ""; } else { _symbolRotation = value; } _rotate = (_symbol is ISymbolRotation && _symbolRotation != null && _symbolRotation.RotationFieldName != ""); } } public CartographicMethod CartoMethod { get { return _cartoMethod; } set { _cartoMethod = value; } } #region IFeatureRenderer public bool CanRender(IFeatureLayer layer, IMap map) { if (layer == null) { return false; } if (layer.FeatureClass == null) { return false; } /* if (layer.FeatureClass.GeometryType == geometryType.Unknown || layer.FeatureClass.GeometryType == geometryType.Network) return false; * */ if (layer.LayerGeometryType == GeometryType.Unknown || layer.LayerGeometryType == GeometryType.Network) { return false; } return true; } public bool HasEffect(IFeatureLayer layer, IMap map) { return true; } public bool UseReferenceScale { get { return _useRefScale; } set { _useRefScale = value; } } public void PrepareQueryFilter(IFeatureLayer layer, IQueryFilter filter) { if (!(_symbol is ISymbolCollection) || ((ISymbolCollection)_symbol).Symbols.Count < 2) { _actualCartoMethod = CartographicMethod.Simple; } else { _actualCartoMethod = _cartoMethod; } if (_rotate && layer.FeatureClass.FindField(_symbolRotation.RotationFieldName) != null) { filter.AddField(_symbolRotation.RotationFieldName); } } /* public void Draw(IDisplay disp,IFeatureCursor fCursor,DrawPhase drawPhase,ICancelTracker cancelTracker) { if(_symbol==null) return; IFeature feature; try { while((feature=fCursor.NextFeature)!=null) { //_symbol.Draw(disp,feature.Shape); if(cancelTracker!=null) if(!cancelTracker.Continue) return; disp.Draw(_symbol,feature.Shape); } } catch(Exception ex) { string msg=ex.Message; } } * */ public void Draw(IDisplay disp, IFeature feature) { /* if (feature.Shape is IPolyline) { ISymbol symbol = RendererFunctions.CreateStandardSymbol(geometryType.Polygon); disp.Draw(symbol, ((ITopologicalOperation)feature.Shape).Buffer(30)); } if (feature.Shape is IPoint) { ISymbol symbol = RendererFunctions.CreateStandardSymbol(geometryType.Polygon); disp.Draw(symbol, ((ITopologicalOperation)feature.Shape).Buffer(30)); } if (feature.Shape is IPolygon) { IPolygon buffer = ((ITopologicalOperation)feature.Shape).Buffer(4.0); if (buffer != null) disp.Draw(_symbol, buffer); }*/ if (_actualCartoMethod == CartographicMethod.Simple) { if (_rotate) { object rot = feature[_symbolRotation.RotationFieldName]; if (rot != null && rot != DBNull.Value) { ((ISymbolRotation)_symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot)); } else { ((ISymbolRotation)_symbol).Rotation = 0; } } disp.Draw(_symbol, feature.Shape); } else if (_actualCartoMethod == CartographicMethod.SymbolOrder) { if (_features == null) { _features = new List<IFeature>(); } _features.Add(feature); } } public void StartDrawing(IDisplay display) { } public void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker) { if (cancelTracker == null) { cancelTracker = new CancelTracker(); } try { if (_actualCartoMethod == CartographicMethod.SymbolOrder && _features != null && cancelTracker.Continue) { ISymbolCollection sColl = (ISymbolCollection)_symbol; foreach (ISymbolCollectionItem symbolItem in sColl.Symbols) { if (symbolItem.Visible == false || symbolItem.Symbol == null) { continue; } ISymbol symbol = symbolItem.Symbol; bool isRotatable = symbol is ISymbolRotation; int counter = 0; if (!cancelTracker.Continue) { break; } foreach (IFeature feature in _features) { if (_rotate && isRotatable) { object rot = feature[_symbolRotation.RotationFieldName]; if (rot != null && rot != DBNull.Value) { ((ISymbolRotation)symbol).Rotation = (float)_symbolRotation.Convert2DEGAritmetic(Convert.ToDouble(rot)); } else { ((ISymbolRotation)symbol).Rotation = 0; } } disp.Draw(symbol, feature.Shape); counter++; if (counter % 100 == 0 && !cancelTracker.Continue) { break; } } } } } finally { if (_features != null) { _features.Clear(); } _features = null; } } public string Name { get { return "Single Symbol"; } } public string Category { get { return "Features"; } } public bool RequireClone() { return _symbol != null && _symbol.RequireClone(); } #endregion #region IPropertyPage Member public object PropertyPageObject() { return this; } public object PropertyPage(object initObject) { if (initObject is IFeatureLayer) { if (((IFeatureLayer)initObject).FeatureClass == null) { return null; } if (_symbol == null) { _symbol = RendererFunctions.CreateStandardSymbol(((IFeatureLayer)initObject).LayerGeometryType/*((IFeatureLayer)initObject).FeatureClass.GeometryType*/); } string appPath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Assembly uiAssembly = Assembly.LoadFrom(appPath + @"/gView.Win.Carto.Rendering.UI.dll"); IPropertyPanel p = uiAssembly.CreateInstance("gView.Framework.Carto.Rendering.UI.PropertyForm_SimpleRenderer") as IPropertyPanel; if (p != null) { return p.PropertyPanel(this, (IFeatureLayer)initObject); } } return null; } #endregion #region IPersistable Member public string PersistID { get { return null; } } public void Load(IPersistStream stream) { _symbol = (ISymbol)stream.Load("Symbol"); _symbolRotation = (SymbolRotation)stream.Load("SymbolRotation", _symbolRotation, _symbolRotation); _rotate = ((_symbol is ISymbolRotation) && _symbolRotation != null && _symbolRotation.RotationFieldName != ""); _cartoMethod = (CartographicMethod)stream.Load("CartographicMethod", (int)CartographicMethod.Simple); } public void Save(IPersistStream stream) { stream.Save("Symbol", _symbol); if (_symbolRotation.RotationFieldName != "") { stream.Save("SymbolRotation", _symbolRotation); } stream.Save("CartographicMethod", (int)_cartoMethod); } #endregion #region ILegendGroup Members public int LegendItemCount { get { return (_symbol == null) ? 0 : 1; } } public ILegendItem LegendItem(int index) { if (index == 0) { return _symbol; } return null; } public void SetSymbol(ILegendItem item, ISymbol symbol) { if (_symbol == null) { return; } if (item == symbol) { return; } if (item == _symbol) { if (symbol is ILegendItem && _symbol is ILegendItem) { ((ILegendItem)symbol).LegendLabel = ((ILegendItem)_symbol).LegendLabel; } _symbol.Release(); _symbol = symbol; } } #endregion #region IClone2 public object Clone(CloneOptions options) { SimpleRenderer renderer = new SimpleRenderer(); if (_symbol != null) { renderer._symbol = (ISymbol)_symbol.Clone(_useRefScale ? options : null); } renderer._symbolRotation = (SymbolRotation)_symbolRotation.Clone(); renderer._rotate = _rotate; renderer._cartoMethod = _cartoMethod; renderer._actualCartoMethod = _actualCartoMethod; return renderer; } public void Release() { Dispose(); } #endregion #region IRenderer Member public List<ISymbol> Symbols { get { return new List<ISymbol>(new ISymbol[] { _symbol }); } } public bool Combine(IRenderer renderer) { if (renderer is SimpleRenderer && renderer != this) { if (_symbol is ISymbolCollection) { ((ISymbolCollection)_symbol).AddSymbol( ((SimpleRenderer)renderer).Symbol); } else { ISymbolCollection symCol = PlugInManager.Create(new Guid("062AD1EA-A93C-4c3c-8690-830E65DC6D91")) as ISymbolCollection; symCol.AddSymbol(_symbol); symCol.AddSymbol(((SimpleRenderer)renderer).Symbol); _symbol = (ISymbol)symCol; } return true; } return false; } #endregion } }
using libairvidproto; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace aairvid.ServerAndFolder { [Serializable] public class CachedServerItem { protected CachedServerItem() { } public CachedServerItem(IServer ser) { IsManual = ser.IsManual; Name = ser.Name; Addr = ser.Address; Port = ser.Port; } public bool IsManual { get; set; } public string Name { get; set; } public string Addr { get; set; } public ushort Port { get; set; } public string ServerPassword { get; set; } public DateTime LastUsedTime { get; set; } } }
using ModelTransformationComponent.SystemRules; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ModelTransformationComponent { /// <summary> /// БНФ правило /// </summary> [System.Serializable] public class BNFRule : NamedRule, IList<BasicBNFRule> { /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> public BNFRule(string name) : base(name) { OrSplits = new List<BasicBNFRule>(); } /// <summary> /// /// </summary> protected readonly List<BasicBNFRule> OrSplits; /// <summary> /// /// </summary> public int Count => OrSplits.Count; /// <summary> /// /// </summary> /// <returns></returns> public bool IsReadOnly => ((ICollection<BasicBNFRule>)OrSplits).IsReadOnly; /// <summary> /// /// </summary> /// <value></value> public BasicBNFRule this[int index] { get => OrSplits[index]; set => OrSplits[index] = value; } /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator<BasicBNFRule> GetEnumerator() { return ((IEnumerable<BasicBNFRule>)OrSplits).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<BasicBNFRule>)OrSplits).GetEnumerator(); } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { var result = "BNFRule " + Name + "\n"; bool first = true; foreach (var i in OrSplits) if (first) { first = false; result += i.ToString(); } else result += " | " + i.ToString(); return result; } //TO DO: could be a bit optimized /// <summary> /// /// </summary> /// <value></value> public bool SelfReferenced { get { foreach (var item in this) { foreach (var item2 in item) { if (item2 is BNFReference refr && refr.Name == Name) return true; } } return false; } } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return (obj is BNFRule r) && (!(obj is TypeRule)) && (Name.Equals(r.Name)) && OrSplits.SequenceEqual(r.OrSplits); } /// <summary> /// /// </summary> /// <param name="item"></param> public void Add(BasicBNFRule item) { OrSplits.Add(item); } /// <summary> /// /// </summary> public void Clear() { OrSplits.Clear(); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(BasicBNFRule item) { return OrSplits.Contains(item); } /// <summary> /// /// </summary> /// <param name="array"></param> /// <param name="arrayIndex"></param> public void CopyTo(BasicBNFRule[] array, int arrayIndex) { OrSplits.CopyTo(array, arrayIndex); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(BasicBNFRule item) { return OrSplits.Remove(item); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public int IndexOf(BasicBNFRule item) { return OrSplits.IndexOf(item); } /// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="item"></param> public void Insert(int index, BasicBNFRule item) { OrSplits.Insert(index, item); } /// <summary> /// /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { OrSplits.RemoveAt(index); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domen { [Serializable] public class LinijaStanica { Linija linija; Stanica stanica; [Browsable(false)] public Linija Linija { get => linija; set => linija = value; } [DisplayName("Naziv medjustanice:")] public Stanica Stanica { get => stanica; set => stanica = value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text; using UnityEngine.XR.iOS.Utils; namespace UnityEngine.XR.iOS { #if UNITY_EDITOR || !UNITY_IOS public class ARFaceGeometry { private serializableFaceGeometry sFaceGeometry; public ARFaceGeometry (serializableFaceGeometry ufg) { sFaceGeometry = ufg; } public int vertexCount { get { return sFaceGeometry.Vertices.Length; } } public int triangleCount { get { return sFaceGeometry.TriangleIndices.Length; } } public int textureCoordinateCount { get { return sFaceGeometry.TexCoords.Length; } } public Vector3 [] vertices { get { return sFaceGeometry.Vertices; } } public Vector2 [] textureCoordinates { get { return sFaceGeometry.TexCoords; } } public int [] triangleIndices { get { return sFaceGeometry.TriangleIndices; } } } public class ARFaceAnchor { serializableUnityARFaceAnchor m_sfa; public ARFaceAnchor(serializableUnityARFaceAnchor sfa) { m_sfa = sfa; } public string identifierStr { get { return Encoding.UTF8.GetString (m_sfa.identifierStr); } } public Matrix4x4 transform { get { return m_sfa.worldTransform; } } public ARFaceGeometry faceGeometry { get { return new ARFaceGeometry (m_sfa.faceGeometry); } } public Dictionary<string, float> blendShapes { get { return m_sfa.arBlendShapes; } } } #endif }
using Framework.Extensions; using Framework.Logging.Service; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; using WebApi.GlobalExceptionHandling; namespace WebApi.Middleware { public class ExceptionHandlerMiddleware { private readonly RequestDelegate _next; private readonly ILoggingService _loggingService; private readonly IExceptionHandler _exceptionHandler; public ExceptionHandlerMiddleware(RequestDelegate next, ILoggingService loggingService, IExceptionHandler exceptionHandler) { this._next = next; this._loggingService = loggingService; this._exceptionHandler = exceptionHandler; } public async Task Invoke(HttpContext context) { try { await this._next(context); } catch (Exception ex) { Action<ILogger> logError = (ILogger logger) => logger.LogError(ex.ToString()); logError.SafeExecution(this._loggingService.DbLogger); logError.SafeExecution(this._loggingService.FileLogger); await this._exceptionHandler.HandleExceptionAsync(context, ex); } } } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphicalEditor.Repository { public class ContractResolver : DefaultContractResolver { private List<String> _propertiesForElimination; public ContractResolver(){ _propertiesForElimination = new List<String>(); _propertiesForElimination.Add("FocusVisualStyle"); _propertiesForElimination.Add("Dispatcher"); _propertiesForElimination.Add("AllMapObjectTypes"); _propertiesForElimination.Add("AllMapObjectTypesAvailableToChange"); } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); properties = properties.Where(p => !_propertiesForElimination.Contains(p.PropertyName)).ToList(); return properties; } } }
using System; using System.Collections.Generic; using System.Reflection; using Dapper; using System.Data; using System.Data.SqlClient; using Microsoft.Extensions.Configuration; using Embraer_Backend.Models; namespace Embraer_Backend.Models { public class Porta { public long? IdColetaPorta { get; set; } public long? IdLocalColeta { get; set; } public string DescLocalMedicao { get; set; } public DateTime? DtColeta{get;set;} public long? IdSensores{get;set;} public string DescSensor{get;set;} public string Valor {get;set;} public string DescPorta{get;set;} public bool CorDashboard{get;set;} public string horaTv {get;set;} } public class PortaModel { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(PortaModel)); public IEnumerable<Porta> SelectPorta(IConfiguration _configuration,long? IdLocalColeta,string dtIni, string dtFim,string status) { try { string sSql = string.Empty; sSql = "SELECT IdColetaPorta,IdLocalColeta,L.DescLocalMedicao,DtColeta,Valor,DescPorta,P.IdSensores,Descricao AS DescSensor"; sSql += " FROM TB_COLETA_PORTA P INNER JOIN TB_SENSORES S ON P.IdSensores=S.IdSensores"; sSql += " INNER JOIN TB_LOCAL_MEDICAO L ON P.IdLocalColeta = L.IdLocalMedicao"; sSql += " WHERE 1=1"; if(IdLocalColeta !=null) sSql += " AND IdLocalColeta=" + IdLocalColeta; if(dtIni !=null && dtIni!="" && dtFim!=null && dtFim!="") sSql += " AND DtColeta BETWEEN '" + dtIni + "' AND '" + dtFim + "'"; if(status !=null && status!="") sSql += " AND Valor ='" + status + "'"; log.Debug(sSql); IEnumerable <Porta> _portas; using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa"))) { _portas = db.Query<Porta>(sSql,commandTimeout:0); } return _portas; } catch (Exception ex) { log.Error("Erro PortaModel-SelectPorta:" + ex.Message.ToString()); return null; } } public IEnumerable<Porta> SelectPorta(IConfiguration _configuration,long IdLocalColeta,long IdSensores) { try { string sSql = string.Empty; sSql = "SELECT TOP 1 IdColetaPorta,IdLocalColeta,L.DescLocalMedicao, DtColeta,Valor,DescPorta,P.IdSensores,Descricao AS DescSensor"; sSql += " FROM TB_COLETA_PORTA P INNER JOIN TB_SENSORES S ON P.IdSensores=S.IdSensores"; sSql += " INNER JOIN TB_LOCAL_MEDICAO L ON P.IdLocalColeta = L.IdLocalMedicao"; sSql += " WHERE 1=1"; if(IdLocalColeta!=0) sSql += " AND IdLocalColeta=" + IdLocalColeta; if(IdSensores!=0) sSql += " AND P.IdSensores=" + IdSensores; sSql+= " ORDER BY DtColeta DESC"; log.Debug(sSql); IEnumerable <Porta> _portas; using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa"))) { _portas = db.Query<Porta>(sSql,commandTimeout:0); } return _portas; } catch (Exception ex) { log.Error("Erro PortaModel-SelectPorta:" + ex.Message.ToString()); return null; } } } }
using UnityEngine; using UnityEngine.Tilemaps; #if UNITY_EDITOR using UnityEditor; #endif [CreateAssetMenu(fileName = "Cell", menuName = "MS49/Cell/Cell", order = 1)] public class CellData : ScriptableObject { [SerializeField] private string _cellName = "???"; [SerializeField, Tooltip("If true, the floor is not drawn below and an edge will surround this tile.")] private bool _isSolid = false; [SerializeField] private TileBase _floorOverlayTile = null; [SerializeField] private TileBase _objectTile = null; [SerializeField] private TileBase _objectOverlayTile = null; [SerializeField] private bool _rotationalOverride = false; [SerializeField, HideInInspector] private RotationOverride up = null; [SerializeField, HideInInspector] private RotationOverride right = null; [SerializeField, HideInInspector] private RotationOverride down = null; [SerializeField, HideInInspector] private RotationOverride left = null; [Space] [SerializeField, Tooltip("-1 = not walkable, 0 = walkable, greater than 1 is walkable with a penalty"), Min(-1)] private int _movementCost = 0; [SerializeField, Tooltip("If ture, this Cell we be treated as empty space and Cell will be able to be built in this Cell's place.")] private bool _canBuildOver = false; [SerializeField, Tooltip("If true, this Cell will be able to be destroyed and converted to air.")] private bool _isDestroyable = false; [SerializeField] private EnumZMoveDirection _zMoveDirections = EnumZMoveDirection.NEITHER; [SerializeField, Tooltip("If true, the Cell will burn")] private bool _flammable = false; [SerializeField] private float _temperatureOutput = 0f; [SerializeField] private bool _supportsCeiling = false; [SerializeField, Tooltip("If true, the fog from this cell will be lifted if an adjacent cell has it's fog lifted.")] private bool _includeInFogFloodLift = false; [Space] [SerializeField, Tooltip("If true, the Object Tile will be tinted.")] private bool _tintObjectTile = false; [Space] [SerializeField, Tooltip("The associate Prefab that will be spawned when this Cell is placed.")] private GameObject _behaviorPrefab = null; public string displayName => this._cellName; public bool isSolid => this._isSolid; public bool rotationalOverride => this._rotationalOverride; public int movementCost => this._movementCost; public bool isWalkable => this.movementCost >= 0; public bool canBuildOver => this._canBuildOver; public bool isDestroyable => this._isDestroyable; public EnumZMoveDirection zMoveDirections => this._zMoveDirections; public bool isFlammable => this._flammable; public float temperatureOutput => this._temperatureOutput; public bool supportsCeiling => this._supportsCeiling; public bool includeInFogFloodLift => this._includeInFogFloodLift; public bool recieveHardnessColorMod => this._tintObjectTile; public GameObject behaviorPrefab => this._behaviorPrefab; public TileRenderData getRenderData(Rotation rotation) { if(this.rotationalOverride) { RotationOverride rotOverride = this.overrideFromRotation(rotation); if(rotOverride.isOverrideEnabled) { // If the rotational override is missing data, pull from the defaults. return new TileRenderData( rotOverride.floorOverlay == null ? this._floorOverlayTile : rotOverride.floorOverlay, rotOverride.objectTile == null ? this._objectTile : rotOverride.objectTile, rotOverride.overlayTile == null ? this._objectOverlayTile : rotOverride.overlayTile, rotOverride.effect); } } return new TileRenderData(this._floorOverlayTile, this._objectTile, this._objectOverlayTile, RotationEffect.NOTHING); } public bool isRotationOverrideEnabled(Rotation rotation) { return this.overrideFromRotation(rotation).isOverrideEnabled; } private RotationOverride overrideFromRotation(Rotation rotation) { if(rotation == Rotation.UP) { return this.up; } else if(rotation == Rotation.RIGHT) { return this.right; } else if(rotation == Rotation.DOWN) { return this.down; } else { return this.left; } } #if UNITY_EDITOR [CustomEditor(typeof(CellData), true)] [CanEditMultipleObjects] public class CellDataEditor : Editor { private SerializedProperty up; private SerializedProperty right; private SerializedProperty down; private SerializedProperty left; private void OnEnable() { this.up = this.serializedObject.FindProperty("up"); this.right = this.serializedObject.FindProperty("right"); this.down = this.serializedObject.FindProperty("down"); this.left = this.serializedObject.FindProperty("left"); } public override void OnInspectorGUI() { this.serializedObject.Update(); this.DrawDefaultInspector(); CellData script = (CellData)this.target; if(script.rotationalOverride) { // Show rotation properties EditorGUILayout.Space(16); EditorGUILayout.LabelField(" ----- Rotation Overrides ----- ", EditorStyles.boldLabel); this.func(this.up); this.func(this.right); this.func(this.down); this.func(this.left); } this.serializedObject.ApplyModifiedProperties(); } private void func(SerializedProperty prop) { SerializedProperty p1 = prop.FindPropertyRelative("_enableOverride"); EditorGUILayout.BeginHorizontal(); prop.isExpanded = EditorGUILayout.Foldout(prop.isExpanded, prop.name.ToUpper()); p1.boolValue = EditorGUILayout.Toggle("Enable override", p1.boolValue); EditorGUILayout.EndHorizontal(); if(prop.isExpanded && p1.boolValue) { EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(prop.FindPropertyRelative("_floorOverlayTile")); EditorGUILayout.PropertyField(prop.FindPropertyRelative("_objectTile")); EditorGUILayout.PropertyField(prop.FindPropertyRelative("_overlayTile")); EditorGUILayout.PropertyField(prop.FindPropertyRelative("_effect")); EditorGUI.indentLevel = 0; } } public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height) { CellData cell = (CellData)this.serializedObject.targetObject; if(cell == null) { return null; } Texture2D tex = new Texture2D(width, height); Texture2D[] textures = new Texture2D[] { this.func(cell._floorOverlayTile), this.func(cell._objectTile), this.func(cell._objectOverlayTile), }; Vector2Int texSize = Vector2Int.zero; Color[] rootCols = null; for(int i = 0; i < textures.Length; i++) { if(textures[i] == null) { continue; } if(rootCols == null) { rootCols = textures[i].GetPixels(); texSize = new Vector2Int(textures[i].width, textures[i].height); } else { // Add texture to the base Color[] cols1 = textures[i].GetPixels(); if(rootCols.Length != cols1.Length) { Debug.LogWarning("[" + this.name + "] Can't make preview, tile sizes do not match."); Debug.LogWarning(rootCols.Length + " " + cols1.Length); return tex; } for(int j = 0; j < cols1.Length; ++j) { if(cols1[j].a != 0) { rootCols[j] = cols1[j]; } } } } if(rootCols != null) { Texture2D root = new Texture2D(texSize.x, texSize.y); root.SetPixels(rootCols); root.Apply(); EditorUtility.CopySerialized(root, tex); return tex; } else { return null; } } /// <summary> /// Returns null if there is no assigned Tile. /// </summary> private Texture2D func(TileBase tile) { Sprite s = TileSpriteGetter.retrieveSprite(tile); if(s != null) { return SpriteToTexture.convert(s); } return null; } } #endif }
using System.Collections.Generic; namespace ShowsTracker.Models { public class ShowSearchResult { public List<Show> Search { get; set; } public int TotalResults { get; set; } } public class EmptySearchResult : ShowSearchResult { public new List<Show> Search = new List<Show>(); public new int TotalResults = 0; } }
using System; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using CouponMerchant.Data; using CouponMerchant.Models; using CouponMerchant.Models.ViewModel; using CouponMerchant.Utility; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace CouponMerchant.Pages.Deals { [Authorize] public class IndexModel : PageModel { private readonly ApplicationDbContext _db; [BindProperty] public DealsViewModel DealsVM { get; set; } [TempData] public string StatusMessage { get; set; } public IndexModel(ApplicationDbContext db) { _db = db; } private async Task<ApplicationUser> GetUser() { var claimsIdentity = (ClaimsIdentity)User.Identity; var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier); return await _db.ApplicationUser.FirstOrDefaultAsync(u => u.Id == claim.Value); } public async Task<IActionResult> OnGet(int productPage = 1, string searchName = null, string searchStartDate = null, string searchEndDate = null) { var user = await GetUser(); DealsVM = new DealsViewModel { Deals = await _db.Deal.Where(x => x.MerchantId == user.MerchantId || user.IsAdmin).ToListAsync() }; var param = new StringBuilder(); param.Append("/Merchants?productPage=:"); param.Append("&searchName="); if (searchName != null) { param.Append(searchName); } param.Append("&searchCity="); if (searchStartDate != null) { param.Append(searchStartDate); } param.Append("&searchState="); if (searchEndDate != null) { param.Append(searchEndDate); } if (searchName != null) { DealsVM.Deals = await _db.Deal .Where(x => x.Name.ToLower().Contains(searchName.ToLower()) && (user.IsAdmin || x.MerchantId == user.MerchantId)).ToListAsync(); } else { if (searchStartDate != null) { var startDate = DateTime.TryParse(searchStartDate, out var result) ? result : default; DealsVM.Deals = await _db.Deal .Where(x => x.StartDate == startDate && (user.IsAdmin || x.MerchantId == user.MerchantId)).ToListAsync(); } else { if (searchEndDate != null) { var endDate = DateTime.TryParse(searchEndDate, out var result) ? result : default; DealsVM.Deals = await _db.Deal .Where(x => x.EndDate == endDate && (user.IsAdmin || x.MerchantId == user.MerchantId)).ToListAsync(); } } } var count = DealsVM.Deals.Count; DealsVM.PagingInfo = new PagingInfo { CurrentPage = productPage, ItemsPerPage = SD.PaginationUsersPageSize, TotalItems = count, UrlParam = param.ToString() }; DealsVM.Deals = DealsVM.Deals.OrderBy(p => p.Name) .Skip((productPage - 1) * SD.PaginationUsersPageSize) .Take(SD.PaginationUsersPageSize).ToList(); return Page(); } } }
using System; using UnityEngine; using TouchScript.Gestures; using TMPro; namespace Project.Testing { [RequireComponent(typeof(TapGesture)), RequireComponent(typeof(SpriteRenderer))] public class StackeableContainerUI : MonoBehaviour { public string itemName_; public StackeableContainer container_; public LevelProgress currentLvlAsset; private TapGesture tapGesture_; private SpriteRenderer render_; [SerializeField] public TextMeshPro text_; private void Awake() { tapGesture_ = GetComponent<TapGesture>(); render_ = GetComponent<SpriteRenderer>(); render_.color = currentLvlAsset.lvlColor; container_.Set(); container_.OnAvailableChange += SetStatus; container_.OnCountChange += SetCount; SetStatus(container_.Available); SetCount(container_.Count); } private void OnEnable() { tapGesture_.Tapped += TakeItem; container_.OnAvailableChange += SetStatus; container_.OnCountChange += SetCount; SetStatus(container_.Available); SetCount(container_.Count); } private void OnDisable() { tapGesture_.Tapped -= TakeItem; container_.OnAvailableChange -= SetStatus; container_.OnCountChange -= SetCount; } private void OnDestroy() { tapGesture_.Tapped -= TakeItem; container_.OnAvailableChange -= SetStatus; container_.OnCountChange -= SetCount; } private void TakeItem(object sender, EventArgs e) { InventoryManager.Instance.selector.SelectItem(container_, transform); } private void SetStatus(bool available) { GetComponent<TapGesture>().enabled = available; //tapGesture_.enabled = available; render_.enabled = available; text_.enabled = available; } private void SetCount(int count) { if (count > 1) text_.text = "x" + count.ToString(); else text_.text = ""; } } }
using Cs_Gerencial.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Gerencial.Dominio.Interfaces.Servicos { public interface IServicoTabelaCustas: IServicoBase<TabelaCustas> { List<TabelaCustas> CalcularItensCustasComValor(decimal baseCalculo, int ano); List<TabelaCustas> CalcularItensCustas(string tipo, int ano); bool AtualizarCustas(int ano); } }
using System.Collections.Generic; using UnityEngine; public class Explode : MonoBehaviour { [SerializeField] float removeTime = 0.4f; [SerializeField] float rangeMultiplier = 1.0f; float time = 0f; void Update() { UpdateRemove(); } void UpdateRemove() { time += Time.deltaTime; if (time <= removeTime) { var t = time / removeTime; var factor = Mathf.Lerp(1f, 0f, t); transform.localScale *= factor; return; } Destroy(gameObject); } }
using System; using SocketProxy.Decoders; namespace SocketProxy.Handlers { public class UserPacket { private readonly Packet _packet; private readonly Auth _auth; public UserPacket(Packet packet, Auth auth) { _packet = packet; _auth = auth; } public int UserId => _auth.UserId; public object CommandKey => _packet.CommandKey; public Type ContentType => _packet.ContentType; public object Content => _packet.Content; public T ContentAs<T>() where T : class { return _packet.ContentAs<T>(); } } public class UserPacket<T> where T : class { private readonly UserPacket _userPacket; public UserPacket(UserPacket userPacket) { _userPacket = userPacket; } public Type ContentType => _userPacket.ContentType; public int UserId => _userPacket.UserId; public object CommandKey => _userPacket.CommandKey; public T Content => _userPacket.ContentAs<T>(); } }
using UnityEngine; using System.Collections; using DEngine.Utils; using DEngine.Utils.TexturePaint; using DGPE.Math.FixedPoint.Geometry2D; using DGPE.Math.FixedPoint; public class TextureGeneration : MonoBehaviour { public Material material = null;// Use this for initialization public int textureSize = 2048; public Color clear,figure; public int shapeType = 0; public float updateTime = 1; private float currentUpdateTime = 0; private FixedShape2D shape = null; FixedVector2 rotationPivot = FixedVector2.CreateZeroVector(); FixedTexturePaintManager pm = null; Texture2D text; void Start () { int texSizeD2 = textureSize/2; int texSizeD4 = textureSize/4; switch(shapeType){ case 0: shape = new FixedCircle2D(new FixedVertex2D(textureSize/2,textureSize/2),(Fixed)textureSize/4); break; case 1: FixedVector2 a = new FixedVector2(texSizeD2-texSizeD4,texSizeD2-texSizeD4); FixedVector2 b = new FixedVector2(texSizeD2+texSizeD4,texSizeD2-texSizeD4); FixedVector2 c = new FixedVector2(texSizeD2,texSizeD2+texSizeD4); shape = new FixedTriangle2D(a,b,c); break; case 2: Fixed bot = (Fixed)(texSizeD2-texSizeD4); Fixed l = (Fixed)(texSizeD2-texSizeD4); Fixed s = (Fixed)(texSizeD2); shape = new FixedRectangle2D(l,bot,s,s); break; default: shape = new FixedCircle2D(new FixedVertex2D(textureSize/2,textureSize/2),(Fixed)textureSize/4); break; } text = new Texture2D(textureSize,textureSize); pm = new FixedTexturePaintManager(text); pm.Clear(clear); pm.DrawPixels(shape,figure); text.Apply(); material.mainTexture = text; } // Update is called once per frame void Update () { if(currentUpdateTime<updateTime){ currentUpdateTime+=Time.deltaTime; return; } shape.RotateZAxe(1,new FixedVector2(textureSize/2,textureSize/2)); pm.Clear(clear); pm.DrawPixels(shape,figure); text.Apply(); material.mainTexture = text; currentUpdateTime = 0; } }
using System.Windows; using MainTool.ViewModels; namespace MainTool { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var viewModel = new MainWindowViewModel(); DataContext = viewModel; viewModel.WindowDrag += (sender, args) => DragMove(); viewModel.WindowClose += (sender, args) => Close(); viewModel.GraphZoomToFill += (sender, args) => graphZoom.ZoomToFill(); } } }
public class Solution { public int[][] GenerateMatrix(int n) { int[][] res = new int[n][]; for (int i = 0; i < n; i ++) res[i] = new int[n]; int k = 1, offsetX = 0, offsetY = 0; while (offsetX < (n+1)/2 && offsetY < (n+1)/2) { for (int j = offsetY; j < n - offsetY; j ++) { res[offsetX][j] = k ++; } for (int i = offsetX + 1; i < n - offsetX - 1; i ++) { res[i][n - offsetY - 1] = k ++; } if (offsetX == n / 2) break; for (int j = n - offsetY - 1; j >= offsetY; j --) { res[n - offsetX - 1][j] = k ++; } for (int i = n - offsetX - 2; i >= offsetX + 1; i --) { res[i][offsetY] = k ++; } offsetX ++; offsetY ++; } return res; } }
using AutoMapper; using Library.API.Entities; using Library.API.Helpers; using Library.API.Models; using Library.API.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Net.Http.Headers; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Library.API.Controllers { /// <summary> /// author /// </summary> [Route("api/authors")] [ApiController] public class AuthorController : ControllerBase { public AuthorController(IMapper mapper, IDistributedCache distributedCache, IAuthorRepository authorRepository) { Mapper = mapper; DistributedCache = distributedCache; AuthorRepository = authorRepository; } public IMapper Mapper { get; } public IDistributedCache DistributedCache { get; } public IAuthorRepository AuthorRepository { get; } /// <summary> /// 获取所有author资源 /// </summary> /// <returns></returns> [HttpGet(Name = nameof(GetAuthorsAsync))] [ResponseCache(Duration = 15, Location = ResponseCacheLocation.Any, VaryByQueryKeys = new string[] { "searchQuery" })] public async Task<ActionResult<ResourceCollect<AuthorDto>>> GetAuthorsAsync([FromQuery] AuthorResourceParameters parameters) { PagedList<Author> pagedList = null; //= await AuthorRepository.GetAllAsync(parameters); // 为了简单,仅当其不包含过滤和搜索时进行缓存 if (string.IsNullOrWhiteSpace(parameters.Name) && string.IsNullOrWhiteSpace(parameters.SearchQuery)) { string cacheKey = $"authors_page_{parameters.PageNumber}_pageSize_{parameters.PageSize}_sort_{parameters.SortBy}"; string cachedContent = await DistributedCache.GetStringAsync(cacheKey); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Converters.Add(new PagedListConverter<Author>()); settings.Formatting = Formatting.Indented; if (string.IsNullOrWhiteSpace(cachedContent)) { pagedList = await AuthorRepository.GetAllAsync(parameters); DistributedCacheEntryOptions options = new DistributedCacheEntryOptions { // 缓存超过2分钟没有被访问,则被移除 SlidingExpiration = TimeSpan.FromMinutes(2) }; var serializedContent = JsonConvert.SerializeObject(pagedList, settings); await DistributedCache.SetStringAsync(cacheKey, serializedContent); } else { pagedList = JsonConvert.DeserializeObject<PagedList<Author>>(cachedContent, settings); } } else { pagedList = await AuthorRepository.GetAllAsync(parameters); } var paginationMetadata = new { totalCount = pagedList.TotalCount, pageSize = pagedList.PageSize, currentPage = pagedList.CurrentPage, totalPages = pagedList.TotalPages, previousPageLink = pagedList.HasPrevious ? Url.Link(nameof(GetAuthorsAsync), new { pageNumber = pagedList.CurrentPage - 1, pageSize = pagedList.PageSize, name = parameters.Name, searchQuery = parameters.SearchQuery, sortBy = parameters.SortBy }) : null, nextPageLink = pagedList.HasNext ? Url.Link(nameof(GetAuthorsAsync), new { pageNumber = pagedList.CurrentPage + 1, pageSize = pagedList.PageSize, name = parameters.Name, searchQuery = parameters.SearchQuery, sortBy = parameters.SortBy }) : null }; Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationMetadata)); var authorDtoList = Mapper.Map<IEnumerable<AuthorDto>>(pagedList); authorDtoList = authorDtoList.Select(author => CreateLinkForAuthor(author)); var resourceList = new ResourceCollect<AuthorDto>(authorDtoList.ToList()); return CreateLinksForAuthors(resourceList); } /// <summary> /// 获取author资源 /// </summary> /// <param name="authorId"></param> /// <returns></returns> [HttpGet("{authorId}", Name = nameof(GetAuthorAsync))] [ResponseCache(CacheProfileName = "Never")] public async Task<ActionResult<AuthorDto>> GetAuthorAsync([FromRoute] Guid authorId) { var author = await AuthorRepository.GetByIdAsync(authorId); if (author == null) { return NotFound(); } var entityHash = HashFactory.GetHash(author); Response.Headers[HeaderNames.ETag] = entityHash; if (Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var requestETag) && entityHash == requestETag) { return StatusCode((int)HttpStatusCode.NotModified); } var authorDto = Mapper.Map<AuthorDto>(author); return CreateLinkForAuthor(authorDto); } /// <summary> /// 创建author资源 /// </summary> /// <returns></returns> [HttpPost(Name = nameof(CreateAuthorAsync))] public async Task<ActionResult> CreateAuthorAsync([FromBody] AuthorForCreationDto authorForCreationDto) { var author = Mapper.Map<Author>(authorForCreationDto); author.Id = Guid.NewGuid(); AuthorRepository.Create(author); var result = await AuthorRepository.SaveAsync(); if (!result) { throw new Exception("创建资源author失败"); } var authorDto = Mapper.Map<AuthorDto>(author); return CreatedAtRoute(nameof(GetAuthorAsync), new { authorId = authorDto.Id }, authorDto); } /// <summary> /// 删除author资源 /// </summary> /// <param name="authorId"></param> /// <returns></returns> [HttpDelete("{authorId}", Name = nameof(DeleteAuthorAsync))] public async Task<ActionResult> DeleteAuthorAsync([FromRoute] Guid authorId) { var author = await AuthorRepository.GetByIdAsync(authorId); if (author == null) { return NotFound(); } AuthorRepository.Delete(author); var result = await AuthorRepository.SaveAsync(); if (!result) { throw new Exception("删除资源author失败"); } return NoContent(); } private AuthorDto CreateLinkForAuthor(AuthorDto author) { author.Links.Clear(); author.Links.Add(new Link(HttpMethod.Get.ToString(), "self", Url.Link(nameof(GetAuthorAsync), new { authorId = author.Id }))); author.Links.Add(new Link(HttpMethod.Delete.ToString(), "delete author", Url.Link(nameof(DeleteAuthorAsync), new { authorId = author.Id }))); author.Links.Add(new Link(HttpMethod.Get.ToString(), "author's books", Url.Link(nameof(BookController.GetBooksAsync), new { authorId = author.Id }))); return author; } private ResourceCollect<AuthorDto> CreateLinksForAuthors(ResourceCollect<AuthorDto> authors, AuthorResourceParameters parameters = null, dynamic paginationData = null) { authors.Links.Clear(); authors.Links.Add(new Link(HttpMethod.Get.ToString(), "self", Url.Link(nameof(GetAuthorsAsync), parameters))); authors.Links.Add(new Link(HttpMethod.Post.ToString(), "create author", Url.Link(nameof(CreateAuthorAsync), null))); if (paginationData != null) { if (paginationData.previousePageLink != null) { authors.Links.Add(new Link(HttpMethod.Get.ToString(), "previous page", paginationData.previousePageLink)); } if (paginationData.nextPageLink != null) { authors.Links.Add(new Link(HttpMethod.Get.ToString(), "next page", paginationData.nextPageLink)); } } return authors; } } }
using System; using TraceWizard.Entities; using TraceWizard.Classification; using TraceWizard.Entities.Adapters.Arff; namespace TraceWizard.Classification.Classifiers.J48 { public class J48IsolatedLeakClassifier : J48Classifier { public override string Name { get { return "J48 Isolated Leak Classifier"; } } public override string Description { get { return "Classifies using J48 algorithm and also classifies isolated predicted Leaks as Faucets"; } } public override FixtureClass Classify(Event @event) { FixtureClass fixtureClass = base.Classify(@event); if (fixtureClass == FixtureClasses.Leak && Analysis.Events.IsIsolated(@event, new TimeSpan(0, 20, 0))) fixtureClass = FixtureClasses.Faucet; return fixtureClass; } } public class J48IndoorClassifier : J48Classifier { public override string Name { get { return "J48 Indoor Classifier"; } } public override string Description { get { return "Classifies using J48 algorithm but no Irrigations are predicted"; } } public override FixtureClass Classify(Event @event) { FixtureClass fixtureClass = base.Classify(@event); if (fixtureClass == FixtureClasses.Irrigation) fixtureClass = FixtureClasses.Unclassified; return fixtureClass; } } public class J48ClothesWasherTopClassifier : J48Classifier { public override string Name { get { return "J48 Clothes Washer Top Classifier"; } } public override string Description { get { return "Classifies using J48 algorithm for Top-Loading Clothes Washers"; } } public override FixtureClass Classify(Event @event) { FixtureClass fixtureClass; if (@event.Peak <= 0.3) { fixtureClass = FixtureClasses.Leak; } else if (@event.Peak <= 2.07) { if (@event.Volume <= 1.237) { fixtureClass = FixtureClasses.Faucet; } else if (@event.Volume <= 1.819) { if (@event.Peak <= 1.15) { fixtureClass = FixtureClasses.Dishwasher; } else if (@event.Peak <= 1.86) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Toilet; } } else if (@event.Volume <= 4.424) { if (@event.Duration.TotalSeconds <= 100) { if (@event.Mode <= 1.71) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Toilet; } } else { fixtureClass = FixtureClasses.Faucet; } } else if (@event.Volume <= 7.081) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Shower; } } else { if (@event.Volume <= 1.285) { if (@event.Peak <= 2.88) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Clotheswasher; } } else if (@event.Volume <= 5.992) { if (@event.Duration.TotalSeconds <= 90) { fixtureClass = FixtureClasses.Toilet; } else { if (@event.Volume <= 3.391) { fixtureClass = FixtureClasses.Toilet; } else { fixtureClass = FixtureClasses.Faucet; } } } else if (@event.Volume <= 31.949) { if (@event.Mode <= 2.8) { fixtureClass = FixtureClasses.Shower; } else { fixtureClass = FixtureClasses.Clotheswasher; } } else { fixtureClass = FixtureClasses.Irrigation; } } return fixtureClass; } } public class J48ClothesWasherFrontClassifier : J48Classifier { public override string Name { get { return "J48 Clothes Washer Front Classifier"; } } public override string Description { get { return "Classifies using J48 algorithm for Front-Loading Clothes Washers"; } } public override FixtureClass Classify(Event @event) { FixtureClass fixtureClass; if (@event.Peak <= 0.3) { if (@event.Volume <= 0.279) { fixtureClass = FixtureClasses.Leak; } else { if (@event.Mode <= 0.09) { fixtureClass = FixtureClasses.Leak; } else { if (@event.Peak <= 0.16) { fixtureClass = FixtureClasses.Cooler; } else { fixtureClass = FixtureClasses.Leak; } } } } else { if (@event.Volume <= 1.167) { if (@event.Peak <= 0.75) { fixtureClass = FixtureClasses.Faucet; } else { if (@event.Volume <= 0.237) { if (@event.Peak <= 0.77) { fixtureClass = FixtureClasses.Leak; } else if (@event.Peak <= 0.84) { fixtureClass = FixtureClasses.Faucet; } else if (@event.Peak <= 0.86) { fixtureClass = FixtureClasses.Leak; } else { fixtureClass = FixtureClasses.Faucet; } } else { fixtureClass = FixtureClasses.Faucet; } } } else if (@event.Volume <= 3.697) { if (@event.Peak <= 1.17) { fixtureClass = FixtureClasses.Dishwasher; } else if (@event.Peak <= 2.04) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Toilet; } } else { if (@event.Peak <= 6.08){ if (@event.Volume <= 7.426) { if (@event.Peak <= 1.86) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Clotheswasher; } } else { if (@event.Mode <= 2.36) { fixtureClass = FixtureClasses.Shower; } else { fixtureClass = FixtureClasses.Irrigation; } } } else { fixtureClass = FixtureClasses.Irrigation; } } } return fixtureClass; } } public class J48Classifier : Classifier { public override string Name { get { return "J48 Classifier"; } } public override string Description { get { return "Classifies using J48 algorithm"; } } //public override Analysis Classify() { // foreach (Event @event in Analysis.Events) // @event.FixtureClass = Classify(@event); // return Analysis; //} // FIXUP COMMENTED OUT, this code is useful for classifiers using "extended" attributes // the kind that we don't calculate when loading analysis //public override Analysis Classify() { // var analysisAdapterArff = new AnalysisAdapterArff(); // var analysis = new Analysis(); // EventsArff eventsArff = analysisAdapterArff.Load(Analysis.Events); // foreach (EventArff eventArff in eventsArff) { // eventArff.FixtureClass = Classify(eventArff); // analysis.Events.Add(eventArff); // } // return analysis; //} public override FixtureClass Classify(Event @event) { FixtureClass fixtureClass; if (@event.Peak <= 0.3) { fixtureClass = FixtureClasses.Leak; } else { if (@event.Volume <= 1.237) { if (@event.Mode <= 2.88) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Clotheswasher; } } else if (@event.Volume <= 4.659) { if (@event.Peak <= 2.07) { if (@event.Volume <= 1.819) { if (@event.Peak <= 1.18) { fixtureClass = FixtureClasses.Dishwasher; } else { fixtureClass = FixtureClasses.Faucet; } } else if (@event.Volume <= 3.595) { if (@event.Mode <= 1.02) { fixtureClass = FixtureClasses.Faucet; } else if (@event.Mode <= 1.8) { if (@event.Volume <= 2.528) { if (@event.Peak <= 1.4) { fixtureClass = FixtureClasses.Faucet; } else { if (@event.Volume <= 2.162) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Toilet; } } } else { fixtureClass = FixtureClasses.Faucet; } } else { fixtureClass = FixtureClasses.Toilet; } } else { fixtureClass = FixtureClasses.Faucet; } } else if (@event.Volume <= 3.5) { fixtureClass = FixtureClasses.Toilet; } else { if (@event.Duration.TotalSeconds <= 90) { fixtureClass = FixtureClasses.Toilet; } else { fixtureClass = FixtureClasses.Clotheswasher; } } } else if (@event.Volume <= 31.949) { if (@event.Mode <= 2.4) { if (@event.Volume <= 7.081) { fixtureClass = FixtureClasses.Faucet; } else { fixtureClass = FixtureClasses.Shower; } } else { fixtureClass = FixtureClasses.Clotheswasher; } } else { fixtureClass = FixtureClasses.Irrigation; } } return fixtureClass; } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace DB.Migrations { public partial class _13 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "CatalogDescription", table: "Catalogs"); migrationBuilder.AlterColumn<string>( name: "Name", table: "Type", maxLength: 40, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Value", table: "FieldValue", nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "Field", maxLength: 40, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "Catalogs", maxLength: 100, nullable: false, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AddColumn<string>( name: "Description", table: "Catalogs", maxLength: 1000, nullable: false, defaultValue: ""); migrationBuilder.AlterColumn<string>( name: "RoleDescription", table: "AspNetRoles", maxLength: 1000, nullable: false, oldClrType: typeof(string), oldNullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Description", table: "Catalogs"); migrationBuilder.AlterColumn<string>( name: "Name", table: "Type", nullable: true, oldClrType: typeof(string), oldMaxLength: 40, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Value", table: "FieldValue", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "Name", table: "Field", nullable: true, oldClrType: typeof(string), oldMaxLength: 40, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "Catalogs", nullable: true, oldClrType: typeof(string), oldMaxLength: 100); migrationBuilder.AddColumn<string>( name: "CatalogDescription", table: "Catalogs", nullable: true); migrationBuilder.AlterColumn<string>( name: "RoleDescription", table: "AspNetRoles", nullable: true, oldClrType: typeof(string), oldMaxLength: 1000); } } }
using Android.App; using Android.Widget; using Android.OS; using Android.Content; using Android.Support.V7.App; using CC.Mobile.Services.MonoDroid; using Groceries.Domain; using Groceries.ViewModels; using CC.Mobile.Routing; using System.Threading.Tasks; using CC.Infrastructure; using Groceries.MonoDroid.Services; using Groceries.Services; namespace Groceries.MonoDroid { [Activity (MainLauncher = true)] public class LoginActivity : BaseAppCompatActivity { Button btnContinue; EditText userName; EditText password; LoginViewModel Model; GroceriesRouter appRouter; IServiceFactory factory; protected override int LayoutId => Resource.Layout.Main; async protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate(savedInstanceState); await Initalize(); Model = Resolve<LoginViewModel>(); appRouter = Resolve<GroceriesRouter>(); factory = Resolve<IServiceFactory>(); Model.LoginFinished += LoginFinished; btnContinue = FindViewById<Button>(Resource.Id.login); userName = FindViewById<EditText>(Resource.Id.userName); password = FindViewById<EditText>(Resource.Id.password); btnContinue.Click += (s,e) => Model.Login(new User(userName.Text, password.Text)); } async Task Initalize () { Register.RegisterTypes (Injector.Container); Injector.Container.Init(); Injector.Container.SetSingleton<IScreenFactory, ScreenFactory> (); var factory = Injector.Container.Resolve<IServiceFactory> (); await factory.Configuration.Init (); } void LoginFinished (object sender, LoginFinishedEventArgs e) { if (e.LoginSucceed) { var home = new HomeViewModel(Factory); GoTo(home); } else { Factory.Messages.ShowMessage ("Invalid Format"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightingBook.Tests.Api.Product.Dto.Car { public class Vehicle { public string Code { get; set; } public string Class { get; set; } public string Title { get; set; } } }
using XH.Infrastructure.MultiTenancy; namespace XH.Domain.Services.Authentication.Models { public class FlatPermission { public string Code { get; set; } public string DisplayName { get; set; } public string Description { get; set; } public MultiTenancySides MultiTenancySides { get; set; } public int Level { get; set; } } }
using System; using System.Collections.Generic; using Accounts.Domain.Events.Private; using PublicEvents = Accounts.Domain.Events.Public; using PrivateEvents = Accounts.Domain.Events.Private; using System.Text; using Accounts.Domain; namespace EventPublisher { public static class AccountEventsTranslationExtensions { internal static PublicEvents.AccountCreated ToPublic(this PrivateEvents.AccountCreated persistedEvent) { return new PublicEvents.AccountCreated (persistedEvent.AccountId, persistedEvent.Amount); } internal static PublicEvents.AccountCredited ToPublic(this PrivateEvents.AccountCredited persistedEvent) { return new PublicEvents.AccountCredited(persistedEvent.AccountId,persistedEvent.Amount); } internal static PublicEvents.AccountDebited ToPublic(this PrivateEvents.AccountDebited persistedEvent) { return new PublicEvents.AccountDebited(persistedEvent.AccountId, persistedEvent.Amount); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Block: MonoBehaviour { // floor public GameObject Original; private GameObject Clone; private float f, move = 1.0f; // BlockPatarns is // * Created of 10*10 size // * until 1 child public GameObject[] BlockPatarns; private GameObject temp; private int i; public int stageLength = 200; // bomb private Vector2 Me, Enemy; private List<GameObject> allBlocks = new List<GameObject>(); private List<GameObject> destroyBlocks = new List<GameObject>(); private bool mouseUpDown = true; // Use this for initialization void Start () { for(f=0; f<stageLength; f+=move){ Clone = Instantiate(Original, new Vector3(transform.localPosition.x+f, transform.localPosition.y, 0), transform.rotation)as GameObject; Clone.transform.parent = transform; Clone = Instantiate(Original, new Vector3(transform.localPosition.x+f, transform.localPosition.y-1.0f, 0), transform.rotation)as GameObject; Clone.transform.parent = transform; Clone = Instantiate(Original, new Vector3(transform.localPosition.x+f, transform.localPosition.y+11.0f, 0), transform.rotation)as GameObject; Clone.transform.parent = transform; } for(i=11; i<stageLength; i++){ if(i%10 == 0){ temp = Instantiate(BlockPatarns[Random.Range(0, BlockPatarns.Length)], new Vector3(i, 0, 0), transform.rotation)as GameObject; temp.transform.parent = transform; allBlocks.Add(temp); } } } // Update is called once per frame void Update () { if(Input.GetKey(KeyCode.A) && Input.GetMouseButtonUp(0) && mouseUpDown){ mouseUpDown = false; var ray = Camera.main.ScreenPointToRay(Input.mousePosition); foreach(var block in allBlocks){ RaycastHit raycastHit; for(i=0; i < block.transform.childCount; i++){ bool hit = block.transform.GetChild(i).GetComponent<BoxCollider>().Raycast(ray,out raycastHit,100); if(hit){ Me = new Vector2(block.transform.GetChild(i).localPosition.x, block.transform.GetChild(i).localPosition.y); for(i=0; i<block.transform.childCount; i++){ Enemy = new Vector2(block.transform.GetChild(i).localPosition.x, block.transform.GetChild(i).localPosition.y); if(Me.x+2.5f >= Enemy.x && Me.x-2.5f <= Enemy.x && Me.y+2.5f >= Enemy.y && Me.y-2.5f <= Enemy.y){ destroyBlocks.Add(block.transform.GetChild(i).gameObject); } else if(Me.x+3.0f >= Enemy.x && Me.x-3.0f <= Enemy.x && Me.y+2.0f >= Enemy.y && Me.y-2.0f <= Enemy.y){ destroyBlocks.Add(block.transform.GetChild(i).gameObject); } else if(Me.x+2.0f >= Enemy.x && Me.x-2.0f <= Enemy.x && Me.y+3.0f >= Enemy.y && Me.y-3.0f <= Enemy.y){ destroyBlocks.Add(block.transform.GetChild(i).gameObject); } } } } } foreach(var dustbin in destroyBlocks){ Destroy(dustbin); } } else if(Input.GetKeyUp(KeyCode.A)){ mouseUpDown = true; } } }
using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Shapes; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; using System.Globalization; using System.Windows.Input; using System.IO; using System.ComponentModel; using System.Windows.Media.Imaging; using TraceWizard.Entities; using TraceWizard.Analyzers; using TraceWizard.Adoption; using TraceWizard.Adoption.Adopters.Null; using TraceWizard.Adoption.Adopters.Naive; using TraceWizard.Classification; using TraceWizard.Classification.Classifiers.FixtureList; using TraceWizard.Classification.Classifiers.J48; using TraceWizard.Disaggregation; using TraceWizard.Disaggregation.Disaggregators.Tw4; using TraceWizard.Notification; namespace TraceWizard.TwApp { public static class ResourceLocator { public static object FindResource(object key) { if (Application.Current != null) return Application.Current.FindResource(key); else return null; } } [Obsolete] public class GradientBrushFromFixtureClass : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return TwBrushes.GradientBrush(((FixtureClass)value).Color); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class FrozenSolidColorBrushFromFixtureClass : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return TwBrushes.FrozenSolidColorBrush(((FixtureClass)value).Color); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class ImageFromFixtureClass : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return TwGui.GetImage(((FixtureClass)value).ImageFilename); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class ScrollViewerHorizontalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return -1 * (double)value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class ScrollViewerVerticalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return -1 * (double)value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class StyledFixtureLabel : UserControl { public FixtureClass FixtureClass; UIElement BuildToolTip(Event @event) { var panel = new StackPanel(); var text = new TextBlock(); text.Text = "Selected Event is " + @event.FixtureClass.FriendlyName; panel.Children.Add(text); { text = new TextBlock(); var tick = new ClassificationTick(); tick.VerticalAlignment = VerticalAlignment.Center; tick.Padding = new Thickness(0, 0, 3, 0); if (@event.ManuallyClassified) { tick.TickClassifiedUsingFixtureList.Visibility = Visibility.Collapsed; tick.TickClassifiedUsingMachineLearning.Visibility = Visibility.Collapsed; text.Text = "Manually Classified"; } else if (@event.ClassifiedUsingFixtureList) { tick.TickManuallyClassified.Visibility = Visibility.Collapsed; tick.TickClassifiedUsingMachineLearning.Visibility = Visibility.Collapsed; text.Text = "Classified Using Fixture List"; } else { tick.TickManuallyClassified.Visibility = Visibility.Collapsed; tick.TickClassifiedUsingFixtureList.Visibility = Visibility.Collapsed; text.Text = "Classified Using Machine Learning"; } var panelInner = new StackPanel(); panelInner.Orientation = Orientation.Horizontal; panelInner.Children.Add(tick); panelInner.Children.Add(text); panel.Children.Add(panelInner); } if (@event.ManuallyApproved) { var panelInner = new StackPanel(); panelInner.Orientation = Orientation.Horizontal; var tick = new ApprovalTick(); tick.VerticalAlignment = VerticalAlignment.Center; tick.Padding = new Thickness(0, 0, 3, 0); panelInner.Children.Add(tick); text = new TextBlock(); text.Text = "Manually Approved"; panelInner.Children.Add(text); panel.Children.Add(panelInner); } if (@event.FirstCycle) { text = new TextBlock(); if (@event.ManuallyClassifiedFirstCycle) text.Text = "Manually Classified As 1st Cycle"; else text.Text = "Classified As 1st Cycle Using Machine Learning"; panel.Children.Add(text); } else if (@event.ManuallyClassifiedFirstCycle) { text = new TextBlock(); text.Text = "Manually Classified As Not 1st Cycle"; panel.Children.Add(text); } return panel; } public StyledFixtureLabel(Event @event, bool showFriendlyName, bool activateCommand) { this.Focusable = false; this.IsTabStop = false; if (activateCommand) this.InputBindings.Add(new MouseBinding(AnalysisPanel.BringSelectedEventIntoViewCommand, new MouseGesture(MouseAction.LeftDoubleClick, ModifierKeys.None))); FixtureClass = @event.FixtureClass; this.ToolTip = BuildToolTip(@event); var panel = new StackPanel(); panel.Orientation = Orientation.Horizontal; var panelTicks = new StackPanel(); { var tick = new ClassificationTick(); tick.Padding = new Thickness(0, 1, 4, 1); tick.VerticalAlignment = VerticalAlignment.Center; if (@event.ManuallyClassified) { tick.TickClassifiedUsingFixtureList.Visibility = Visibility.Collapsed; tick.TickClassifiedUsingMachineLearning.Visibility = Visibility.Collapsed; } else if (@event.ClassifiedUsingFixtureList) { tick.TickManuallyClassified.Visibility = Visibility.Collapsed; tick.TickClassifiedUsingMachineLearning.Visibility = Visibility.Collapsed; } else { tick.TickManuallyClassified.Visibility = Visibility.Collapsed; tick.TickClassifiedUsingFixtureList.Visibility = Visibility.Collapsed; } panelTicks.Children.Add(tick); } if (@event.ManuallyApproved) { var tick = new ApprovalTick(); tick.Padding = new Thickness(0, 1, 4, 1); tick.VerticalAlignment = VerticalAlignment.Center; panelTicks.Children.Add(tick); } panel.Children.Add(panelTicks); Image image = new Image(); image.Style = (Style)ResourceLocator.FindResource("ImageStyle"); image.Source = TwGui.GetImage(@event.FixtureClass.ImageFilename); Border border = new Border(); border.Margin = new Thickness(3, 0, 0, 0); border.Style = (Style)ResourceLocator.FindResource("FixtureBorderStyle"); border.Background = TwBrushes.FrozenSolidColorBrush(@event.FixtureClass.Color); border.VerticalAlignment = VerticalAlignment.Top; border.Child = image; panel.Children.Add(border); var label = new TextBlock(); label.Text = showFriendlyName ? @event.FixtureClass.FriendlyName : @event.FixtureClass.ShortName; label.Padding = new Thickness(3, 0, 0, 0); panel.Children.Add(label); if (@event.FirstCycle) { label = new TextBlock(); label.FontSize = 8; label.BaselineOffset = 10; label.Text = "1"; if (!@event.ManuallyClassifiedFirstCycle) label.FontStyle = FontStyles.Italic; label.Padding = new Thickness(3, 0, 0, 0); panel.Children.Add(label); } else if (@event.ManuallyClassifiedFirstCycle) { label = new TextBlock(); label.FontSize = 8; label.BaselineOffset = 10; label.Text = "0"; label.Padding = new Thickness(3, 0, 0, 0); panel.Children.Add(label); } //if (!string.IsNullOrEmpty(@event.UserNotes)) { // label = new TextBlock(); // label.Padding = new Thickness(3, 0, 0, 0); // label.Text = "N"; // panel.Children.Add(label); //} this.Content = panel; } public StyledFixtureLabel(FixtureClass fixtureClass, FontWeight fontWeight, bool showKey, bool manuallyClassified, bool firstCycle, bool firstCycleManuallyClassified, bool showFriendlyName, bool singleRow, bool showHasNotes) { this.Focusable = false; this.IsTabStop = false; this.InputBindings.Add(new MouseBinding(AnalysisPanel.BringSelectedEventIntoViewCommand, new MouseGesture(MouseAction.LeftDoubleClick, ModifierKeys.None))); FixtureClass = fixtureClass; Grid grid = new Grid(); ColumnDefinition coldefText = new ColumnDefinition(); coldefText.Width = GridLength.Auto; grid.ColumnDefinitions.Add(coldefText); ColumnDefinition coldefImage = new ColumnDefinition(); coldefImage.Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions.Add(coldefImage); Image image = new Image(); image.Style = (Style)ResourceLocator.FindResource("ImageStyle"); image.Source = TwGui.GetImage(fixtureClass.ImageFilename); Border border = new Border(); border.Style = (Style)ResourceLocator.FindResource("FixtureBorderStyle"); border.Background = TwBrushes.FrozenSolidColorBrush(fixtureClass.Color); border.VerticalAlignment = VerticalAlignment.Top; border.Child = image; Grid.SetColumn(border, 0); grid.Children.Add(border); var stackPanel = new StackPanel(); var label = new TextBlock(); var name = showFriendlyName ? fixtureClass.FriendlyName : fixtureClass.ShortName; if (showKey) label.Text = name + " (" + fixtureClass.Character + ")"; else label.Text = name; if (singleRow) grid.ToolTip = "Selected Event is " + fixtureClass.FriendlyName; if (manuallyClassified) { label.Text += "*"; if (singleRow) grid.ToolTip += "\r\n* = Manually classified"; } label.Margin = new Thickness(6, 0, 0, 0); label.FontWeight = fontWeight; label.HorizontalAlignment = HorizontalAlignment.Left; label.VerticalAlignment = VerticalAlignment.Center; stackPanel.Children.Add(label); if (firstCycle) { label = new TextBlock(); label.Text = "(1st Cycle)"; label.Margin = new Thickness(6, 0, 0, 0); label.FontWeight = fontWeight; label.HorizontalAlignment = HorizontalAlignment.Left; label.VerticalAlignment = VerticalAlignment.Center; stackPanel.Children.Add(label); if (singleRow) { stackPanel.Orientation = Orientation.Horizontal; label.Text = "1"; if (singleRow) grid.ToolTip += "\r\n1 = 1st Cycle"; } if (firstCycleManuallyClassified) { label.Text += "*"; } } if (showHasNotes) { label = new TextBlock(); label.Text = "Notes"; label.Margin = new Thickness(6, 0, 0, 0); label.FontWeight = fontWeight; label.HorizontalAlignment = HorizontalAlignment.Left; label.VerticalAlignment = VerticalAlignment.Center; stackPanel.Children.Add(label); if (singleRow) { stackPanel.Orientation = Orientation.Horizontal; label.Text = "N"; grid.ToolTip += "\r\nN = Has User Notes"; } } Grid.SetColumn(stackPanel, 1); grid.Children.Add(stackPanel); this.Content = grid; } } public static class TwGui { public static ImageSource GetIcon32() { string uri = @"pack://application:,,,/Images/" + "TraceWizard.ico"; using (Stream iconStream = Application.GetResourceStream(new Uri(uri)).Stream) { using (System.Drawing.Icon icon = new System.Drawing.Icon(iconStream, 32, 32)) { using (System.Drawing.Bitmap bitmap = icon.ToBitmap()) { MemoryStream memoryStream = new MemoryStream(); bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); memoryStream.Seek(0, SeekOrigin.Begin); PngBitmapDecoder pbd = new PngBitmapDecoder(memoryStream, BitmapCreateOptions.None, BitmapCacheOption.Default); return pbd.Frames[0]; } } } } public static ImageSource GetImage(string fileName) { if (string.IsNullOrEmpty(fileName)) return null; Uri uri = new Uri("pack://application:,,,/Images/" + fileName); return BitmapFrame.Create(uri); } public static UIElement CreateAnalyzerToolTip(Type type, Analyzer analyzer) { if (typeof(FixtureListClassifier).IsAssignableFrom(type)) return CreateTitledFixtureProfiles((FixtureListClassifier)(analyzer)); else { TextBlock textBlock = new TextBlock(); textBlock.TextWrapping = TextWrapping.Wrap; textBlock.Text = analyzer.GetDescription(); return textBlock; } } static UIElement CreateTitledFixtureProfiles(FixtureListClassifier classifier) { StackPanel stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Vertical; TextBlock textBlock = new TextBlock(); textBlock.Text = classifier.GetDescription(); stackPanel.Children.Add(textBlock); var fixtureProfilesPanel = new FixtureProfilesPanel(); fixtureProfilesPanel.ItemsSource = classifier.FixtureProfiles; stackPanel.Children.Add(fixtureProfilesPanel); return stackPanel; } public static Grid FixtureWithImageLeftMenu(FixtureClass fixtureClass) { Grid grid = new Grid(); grid.Margin = new Thickness(1, 0, 1, 0); grid.Tag = fixtureClass; ColumnDefinition columnDefinition = new ColumnDefinition(); columnDefinition.Width = GridLength.Auto; grid.ColumnDefinitions.Add(columnDefinition); columnDefinition = new ColumnDefinition(); columnDefinition.Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions.Add(columnDefinition); Image image = new Image(); image.Style = (Style)ResourceLocator.FindResource("ImageStyle"); image.Source = TwGui.GetImage(fixtureClass.ImageFilename); Border border = new Border(); border.Style = (Style)ResourceLocator.FindResource("FixtureBorderStyle"); border.Background = TwBrushes.FrozenSolidColorBrush(fixtureClass.Color); border.Child = image; Grid.SetColumn(border, 0); grid.Children.Add(border); var label = new Label(); label.Content = fixtureClass.LabelName; label.FontWeight = FontWeights.Normal; label.HorizontalAlignment = HorizontalAlignment.Left; label.VerticalAlignment = VerticalAlignment.Top; label.Padding = new Thickness(1, 0, 1, 0); label.Margin = new Thickness(5, 0, 5, 0); Grid.SetColumn(label, 1); grid.Children.Add(label); return grid; } public static StyledFixtureLabel FixtureWithImageLeft(FixtureClass fixtureClass) { return FixtureWithImageLeft(fixtureClass, FontWeights.Normal); } public static StyledFixtureLabel FixtureWithImageLeft(FixtureClass fixtureClass, bool showKey) { return FixtureWithImageLeft(fixtureClass, FontWeights.Normal, showKey); } public static StyledFixtureLabel FixtureWithImageLeft(FixtureClass fixtureClass, FontWeight fontWeight) { return FixtureWithImageLeft(fixtureClass, fontWeight, false); } public static Border FixtureImage(FixtureClass fixtureClass) { Image image = new Image(); image.Style = (Style)ResourceLocator.FindResource("ImageStyle"); image.Source = TwGui.GetImage(fixtureClass.ImageFilename); Border border = new Border(); border.Style = (Style)ResourceLocator.FindResource("FixtureBorderStyle"); border.Background = TwSingletonBrushes.Instance.FrozenSolidColorBrush(fixtureClass.Color); border.Child = image; return border; } public static StyledFixtureLabel FixtureWithImageLeft(FixtureClass fixtureClass, FontWeight fontWeight, bool showKey) { return FixtureWithImageLeft(fixtureClass, fontWeight, showKey, false, false); } public static StyledFixtureLabel FixtureWithImageLeft(FixtureClass fixtureClass, FontWeight fontWeight, bool showKey, bool manuallyClassified, bool firstCycleManuallyClassified) { return new StyledFixtureLabel(fixtureClass, fontWeight, showKey, manuallyClassified, false, false, true, false, false); } public static Grid FixtureWithImageRight(FixtureClass fixtureClass) { Grid grid = new Grid(); grid.Margin = new Thickness(1, 1, 1, 1); var coldefImage = new ColumnDefinition(); coldefImage.Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions.Add(coldefImage); var coldefText = new ColumnDefinition(); coldefText.Width = GridLength.Auto; grid.ColumnDefinitions.Add(coldefText); Image image = new Image(); image.Style = (Style)ResourceLocator.FindResource("ImageStyle"); image.Source = TwGui.GetImage(fixtureClass.ImageFilename); Border border = new Border(); border.Style = (Style)ResourceLocator.FindResource("FixtureBorderStyle"); border.Background = TwBrushes.FrozenSolidColorBrush(fixtureClass.Color); border.Child = image; Grid.SetColumn(border, 1); grid.Children.Add(border); TextBlock textBlock = new TextBlock(); textBlock.Text = fixtureClass.FriendlyName; textBlock.Margin = new Thickness(0, 0, 6, 0); textBlock.TextAlignment = TextAlignment.Right; textBlock.HorizontalAlignment = HorizontalAlignment.Right; textBlock.VerticalAlignment = VerticalAlignment.Center; Grid.SetColumn(textBlock, 0); grid.Children.Add(textBlock); return grid; } public static Grid FixtureWithNoImageRight(string text) { Grid grid = new Grid(); grid.Margin = new Thickness(1, 1, 1, 1); var coldefImage = new ColumnDefinition(); coldefImage.Width = new GridLength(1, GridUnitType.Star); grid.ColumnDefinitions.Add(coldefImage); var coldefText = new ColumnDefinition(); coldefText.Width = GridLength.Auto; grid.ColumnDefinitions.Add(coldefText); TextBlock textBlock = new TextBlock(); textBlock.Text = text; textBlock.Margin = new Thickness(0, 0, 6, 0); textBlock.TextAlignment = TextAlignment.Right; textBlock.HorizontalAlignment = HorizontalAlignment.Right; textBlock.VerticalAlignment = VerticalAlignment.Center; Grid.SetColumn(textBlock, 0); grid.Children.Add(textBlock); return grid; } public static Grid FixtureWithNoImageBottom(string text) { Grid grid = new Grid(); grid.Margin = new Thickness(1, 1, 1, 1); RowDefinition rowdef = new RowDefinition(); rowdef.Height = new GridLength(1, GridUnitType.Star); grid.RowDefinitions.Add(rowdef); rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; grid.RowDefinitions.Add(rowdef); TextBlock textBlock = new TextBlock(); textBlock.Text = text; textBlock.Margin = new Thickness(0, 0, 0, 6); textBlock.HorizontalAlignment = HorizontalAlignment.Center; textBlock.VerticalAlignment = VerticalAlignment.Bottom; textBlock.LayoutTransform = new RotateTransform(-90); Grid.SetRow(textBlock, 0); Grid.SetColumn(textBlock, 0); grid.Children.Add(textBlock); return grid; } public static Grid FixtureWithNoLabel(FixtureClass fixtureClass) { Grid grid = new Grid(); grid.Margin = new Thickness(1, 1, 1, 1); RowDefinition rowdef = new RowDefinition(); rowdef.Height = new GridLength(1, GridUnitType.Star); grid.RowDefinitions.Add(rowdef); rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; grid.RowDefinitions.Add(rowdef); Image image = new Image(); image.Style = (Style)ResourceLocator.FindResource("ImageStyle"); image.Source = TwGui.GetImage(fixtureClass.ImageFilename); Border border = new Border(); border.Style = (Style)ResourceLocator.FindResource("FixtureBorderStyle"); border.Background = TwBrushes.FrozenSolidColorBrush(fixtureClass.Color); border.Child = image; Grid.SetRow(border, 1); grid.Children.Add(border); grid.ToolTip = fixtureClass.FriendlyName; return grid; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using TinhLuongDAL; namespace TinhLuongBLL { public class LuongLanhDaoBLL { LuongLanhDaoDAL dal = new LuongLanhDaoDAL(); public DataTable GetSourceRptLD(decimal nam, decimal thang) { return dal.GetSourceRptLD(nam,thang); } public DataTable GetSourceRpt(decimal nam, decimal thang) { return dal.GetSourceRpt(nam, thang); } } }
using System; using System.Collections; using System.Collections.Generic; using DChild.Gameplay.Combat; using DChild.Gameplay.Systems.Subroutine; using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public class BookWorm : Minion { [SerializeField][MinValue(0f)] private float m_patrolSpeed; [SerializeField] private AttackDamage m_attackDamage; [SerializeField] private AttackDamage m_devourHeadDPS; [SerializeField] private GameObject m_acidProjectile; private bool m_isAttachedToHead; public bool isAttachedToHead => m_isAttachedToHead; protected override CharacterAnimation animation => null; public void SpitAcid(IDamageable target) { } public void DevourHead(IDamageable target) { } public void LetGoOfHead() { } public void DealDPSTo(IDamageable target) => GameplaySystem.GetRoutine<ICombatRoutine>().ApplyDamage(target, DamageFXType.Pierce, m_devourHeadDPS); public void PatrolTo(Vector2 position) { } public void Turn() { } protected override void GetAttackInfo(out AttackInfo attackInfo, out DamageFXType fxType) { attackInfo = new AttackInfo(m_attackDamage, 0, null, null); fxType = DamageFXType.None; } protected override void InitializeMinion() { m_isAttachedToHead = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PROnline.Models.Users { //角色菜单权限 public class RoleMenu { public Guid Id { get; set; } //角色 public String RoleId { get; set; } public Role Role { get; set; } //菜单ID public String menuId { get; set; } } }
using System; class Arrow { static void Main() { int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { if (i == 0) { Console.WriteLine("{0}{1}{0}",new String('.',((n*2)-1-n)/2),new string('#',n)); } else if (i == n-1) { Console.WriteLine("{0}{1}{0}",new string('#',(((n * 2) - 1 - n) / 2)+1), new string('.',n-2)); } else { Console.WriteLine("{0}#{1}#{0}", new String('.',((n*2)-1-n)/2),new string('.',n-2)); } } int leftSide = 1; int rightSide = n*2 - 1 - 1 - 1; for (int row = 0; row < n-2; row++) { for (int col = 0; col < n*2-1; col++) { if (col == leftSide) { Console.Write("#"); } else if (col == rightSide) { Console.Write("#"); } else { Console.Write("."); } } Console.WriteLine(); leftSide++; rightSide--; } Console.WriteLine("{0}#{0}",new String('.',(n*2-2)/2)); } }
using PlayerController.Movement; using UnityEngine; using Zenject; namespace PlayerController.Input { public class SwipeDetector : MonoBehaviour { [SerializeField] private float _minimumDistance = 0.2f; [SerializeField] private float _maximumTimer = 1f; private InputHandler _inputHandler; private PlayerMovement _playerMovement; private Vector2 _startPosition; private Vector2 _endPosition; private float _startTime; private float _endTime; [Inject] private void Construct(InputHandler inputHandler, PlayerMovement playerMovement) { _inputHandler = inputHandler; _playerMovement = playerMovement; } private void OnEnable() { _inputHandler.OnStartTouch += StartTouchHandler; _inputHandler.OnEndTouch += EndTouchHandler; } private void StartTouchHandler(Vector2 position, float time) { _startPosition = position; _startTime = time; } private void EndTouchHandler(Vector2 position, float time) { _endPosition = position; _endTime = time; DetectSwipe(); } private void DetectSwipe() { if (Vector3.Distance(_startPosition, _endPosition) >= _minimumDistance && (_endTime - _startTime) <= _maximumTimer) { var direction = (_endPosition - _startPosition).normalized; CheckSwipeDirection(direction); } } private void CheckSwipeDirection(Vector2 direction) { if (Vector2.Dot(new Vector2(-0.5f,0f),direction) > 0.4f) { Debug.Log("left"); _playerMovement.MoveLeftInput(); } else if (Vector2.Dot(new Vector2(0.5f,0f),direction) > 0.4f) { Debug.Log("right"); _playerMovement.MoveRightInput(); } } private void OnDisable() { _inputHandler.OnStartTouch -= StartTouchHandler; _inputHandler.OnEndTouch -= EndTouchHandler; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Video; public class AttractScreen: MonoBehaviour { public RawImage rawImage; public VideoPlayer videoPlayer; public AudioSource audioSource; public float videoStartDelayTime = 0.1f; // Use this for initialization void Start () { StartCoroutine(PlayVideo()); } IEnumerator PlayVideo() { videoPlayer.Prepare(); WaitForSeconds waitForSeconds = new WaitForSeconds(videoStartDelayTime); while (!videoPlayer.isPrepared) { yield return waitForSeconds; break; } rawImage.texture = videoPlayer.texture; videoPlayer.Play(); audioSource.Play(); } public void StopVideo() { rawImage.CrossFadeAlpha(0f,3f,true); rawImage.color = Color.black; videoPlayer.Stop(); audioSource.Stop(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Xero.Api.Core.Model.Types { [DataContract(Namespace = "")] public enum SourceType { [EnumMember(Value = "ACCREC")] AccountsReceivableInvoice = 1, [EnumMember(Value = "ACCPAY")] AccountsPayableInvoice = 2, [EnumMember(Value = "ACCRECCREDIT")] AccountsReceivableCreditNote = 3, [EnumMember(Value = "ACCPAYCREDIT")] AccountsPayableCreditNote = 4, [EnumMember(Value = "ACCRECPAYMENT")] PaymentOnAnAccountsReceivableInvoice = 5, [EnumMember(Value = "ACCPAYPAYMENT")] PaymentOnAnAccountsPayableInvoice = 6, [EnumMember(Value = "ARCREDITPAYMENT")] AccountsReceivableCreditNotePayment = 7, [EnumMember(Value = "APCREDITPAYMENT")] AccountsPayableCreditNotePayment = 8, [EnumMember(Value = "CASHREC")] ReceiveMoneyBankTransaction = 9, [EnumMember(Value = "CASHPAID")] SpendMoneyBankTransaction = 10, [EnumMember(Value = "TRANSFER")] BankTransfer = 11, [EnumMember(Value = "ARPREPAYMENT")] AccountsReceivablePrepayment = 12, [EnumMember(Value = "APPREPAYMENT")] AccountsPayablePrepayment = 13, [EnumMember(Value = "AROVERPAYMENT")] AccountsReceivableOverpayment = 14, [EnumMember(Value = "APOVERPAYMENT")] AccountsPayableOverpayment = 15, [EnumMember(Value = "EXPCLAIM")] ExpenseClaim = 16, [EnumMember(Value = "EXPPAYMENT")] ExpenseClaimPayment = 17, [EnumMember(Value = "MANJOURNAL")] ManualJournal = 18, [EnumMember(Value = "PAYSLIP")] Payslip = 19, [EnumMember(Value = "WAGEPAYABLE")] PayrollPayable = 20, [EnumMember(Value = "INTEGRATEDPAYROLLPE")] PayrollExpense = 21, [EnumMember(Value = "INTEGRATEDPAYROLLPT")] PayrollPayment = 22, [EnumMember(Value = "EXTERNALSPENDMONEY")] ExternalSpendMoney = 23, [EnumMember(Value = "INTEGRATEDPAYROLLPTPAYMENT")] PayrollTaxPayment = 24, [EnumMember(Value = "INTEGRATEDPAYROLLCN")] PayrollCreditNote = 25, [EnumMember(Value = "INTEGRATEDPAYROLLPLL")] PayrollLeaveLiability = 26 } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LookieLooks.Api.Domain { [BsonCollection("users")] public class User : Document { public string UserName { get; set; } public string AvatarImageUrl { get; set; } public int Score { get; set; } public Model.User GetUserDTO() { return new Model.User() { AvatarImageUrl = AvatarImageUrl, Score = Score, UserName = UserName }; } } }
using System.Configuration; using System.Net.Http.Formatting; using System.Web.Http; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Service.AppStart { public class WebApiConfig { public const string ApiRoot = "api/"; public const string GwApiRoot = "api/"; public static void Register(HttpConfiguration config) { #region Define Routes config.Routes.MapHttpRoute( name: "ValuesRoute", routeTemplate: ApiRoot + "values/{action}/{id}", defaults: new { controller = "values", id = RouteParameter.Optional}); #endregion #region Media Formatters config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); JsonMediaTypeFormatter json = config.Formatters.JsonFormatter; json.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter()); // Serialize enums as strings instead of Integers #endregion Media Formatters #region Handlers /* config.Filters.Add(new NoCacheResponseFilter()); config.MessageHandlers.Add(new ApiLoggingHandler()); config.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger()); */ config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly; #endregion } } }
using Model.Migrations; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Service.Interfaces.IUsers { public interface ILoginService { /// <summary> /// 取得Users /// </summary> /// <param name="usersId"></param> /// <returns></returns> Task<Users> GetUsersByIdAsync(string usersId); /// <summary> /// 新增使用者 /// </summary> /// <param name="nickName"></param> /// <returns></returns> Task<Users> InsertUsersAsync(string nickName); /// <summary> /// 取得Users 暱稱 /// </summary> /// <param name="nickName"></param> /// <returns></returns> Task<Users> GetUsersByNickNameAsync(string nickName); } }
using Com.Colin.EfDataAccess; namespace Com.Colin.BusinessLayer { public class BusinessSettings { public static void SetBusiness() { DatabaseSettings.SetDatabase(); } } }
using System; namespace EasyConsoleNG { public class EasyConsoleOutput { private EasyConsole _console; public EasyConsoleOutput(EasyConsole console) { _console = console; } public void WriteLine(ConsoleColor color, string format, params object[] args) { _console.ForegroundColor = color; _console.WriteLine(format, args); _console.ResetColor(); } public void WriteLine(ConsoleColor color, string value) { _console.ForegroundColor = color; _console.WriteLine(value); _console.ResetColor(); } public void WriteLine(string format, params object[] args) { _console.WriteLine(format, args); } public void DisplayPrompt(string format, params object[] args) { format = format.Trim().TrimEnd(':') + ": "; _console.Write(format, args); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Security.Cryptography; using System.Web; using ModelLibrary; namespace HotelRestAPI.DBUtil { public class ManagerRoom { private const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HotelDbtest2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; private const string GET_ALL = "select * from room"; private const string GET_ONE = "select * from room where Room_No = @RoomNo and Hotel_No = @HotelNo"; private const string INSERT = "Insert into room values(@RoomNo, @HotelNo, @Types, @Price)"; private const string UPDATE = "update room set Room_No = @RoomNo, Hotel_No = @HotelNo, Types = @Types, Price =@Price where Room_No = @Id and Hotel_No = @IdHotel"; private const string DELETE = "delete from room where Room_No = @Id and Hotel_No = @IdHotel"; public IEnumerable<Room> Get() { List<Room> liste = new List<Room>(); SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(GET_ALL, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Room room = readRoom(reader); liste.Add(room); } conn.Close(); return liste; } private Room readRoom(SqlDataReader reader) { Room room = new Room(); room.RoomNo = reader.GetInt32(0); room.HotelNo = reader.GetInt32(1); room.Types = reader.GetString(2); room.Price = reader.GetDouble(3); return room; } public Room Get(int id, int hotelNo) { Room room = null; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(GET_ONE, conn); cmd.Parameters.AddWithValue("@RoomNo", id); cmd.Parameters.AddWithValue("@HotelNo", hotelNo); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { room = readRoom(reader); } conn.Close(); return room; } public bool Post(Room room) { bool ok = false; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(INSERT, conn); cmd.Parameters.AddWithValue("@RoomNo", room.RoomNo); cmd.Parameters.AddWithValue("@HotelNo", room.HotelNo); cmd.Parameters.AddWithValue("@Types", room.Types); cmd.Parameters.AddWithValue("@Price", room.Price); int noOfRowsAffected = cmd.ExecuteNonQuery(); ok = noOfRowsAffected == 1 ? true : false; conn.Close(); return ok; } public bool Put(int id, int hotelNo, Room room) { bool ok = false; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(UPDATE, conn); cmd.Parameters.AddWithValue("@RoomNo", room.RoomNo); cmd.Parameters.AddWithValue("@HotelNo", room.HotelNo); cmd.Parameters.AddWithValue("@Types", room.Types); cmd.Parameters.AddWithValue("@Price", room.Price); cmd.Parameters.AddWithValue("@Id", id); cmd.Parameters.AddWithValue("@IdHotel", hotelNo); int noOfRowsAffected = cmd.ExecuteNonQuery(); ok = noOfRowsAffected == 1 ? true : false; conn.Close(); return ok; } public bool Delete(int id, int hotelNo) { bool ok = false; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); SqlCommand cmd = new SqlCommand(DELETE, conn); cmd.Parameters.AddWithValue("@Id", id); cmd.Parameters.AddWithValue("@IdHotel", hotelNo); int noOfRowsAffected = cmd.ExecuteNonQuery(); ok = noOfRowsAffected == 1 ? true : false; conn.Close(); return ok; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _004_Parse_Input { class Program { static void Main(string[] args) { Console.WriteLine("I can calculate, I can divide and multiplie!"); Console.WriteLine(""); Console.Write("First number: "); int num1 = int.Parse(Console.ReadLine()); Console.Write("Second number: "); int num2 = int.Parse(Console.ReadLine()); Console.WriteLine(""); Console.WriteLine("Dividing " + num1 + " and " + num2 + " = " + num1 / num2); Console.WriteLine("Multiplying " + num1 + " and " + num2 + " = " + num1 * num2); Console.WriteLine("Press any key to continue"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Windows.Forms; namespace SocketLite { public abstract class RequestHandler { protected RequestHandler(RequestContext context) { Context = context; } public RequestContext Context { get; private set; } public abstract Type Type { get; } class TypeHandler { public string Type { get; set; } public string Handler { get; set; } } public static RequestHandler GetHandler(RequestContext context) { var path = string.Format(@"{0}\RequestHandlers.json", Application.StartupPath); var json = File.ReadAllText(path); var typeHandlers = Utils.Deserialize<List<TypeHandler>>(json); if (typeHandlers == null || typeHandlers.Count == 0) return null; TypeHandler typeHandler = null; foreach (var item in typeHandlers) { if (item.Type == context.Request.Handler) { typeHandler = item; break; } } if (typeHandler == null) return null; var type = Type.GetType(typeHandler.Handler); if (type == null) return null; return Activator.CreateInstance(type, context) as RequestHandler; } public ResponseInfo Execute() { var method = Type.GetMethod(Context.Request.Action); if (method == null) return CreateResponse($"{Context.Request.Handler}不支持{Context.Request.Action}操作!"); return method.Invoke(this, new object[] { Context.Request.ParamJson }) as ResponseInfo; } protected ResponseInfo CreateResponse(object data) { return ResponseInfo.Create(Context.Request, data); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Bit8Piano.Model.Sequencer.ADSR { enum InstrumentDuration { Attack = 1 / 2, Decay = 1 / 9, Sustain = 1 / 4, Release = 1 / 6 } enum InstrumentStrength { Attack = 32767, Decay = 18000, Sustain = 14000, Release = 0 } }
/* * Featured in another game, as the title suggests, this was a script that tested movement * but it was then hijacked for another purpose. throwing fish... so yeah... when the * person playing taps the screen, they toggle movement. * (note for future me, Toggle Movement is a goodname for a function) */ using UnityEngine; using System.Collections; public class movementTestScript : MonoBehaviour { public bool isMoving; private Rigidbody rb; private Camera cam; [Range(0, 10)] public float speed = 2.0f; /* * The game object that get's fired out.. really needs to be a fish in the game it was made for */ public GameObject projectile; // Use this for initialization void Start () { rb = GetComponentInParent<Rigidbody>(); cam = GetComponent<Camera>(); } // Update is called once per frame void Update () { Vector3 dir = cam.transform.forward; /* if the player is in VR (which they always are really) and the screen is touched....*/ if(GvrViewer.Instance.VRModeEnabled && GvrViewer.Instance.Triggered) { /* Toggle movement... (should really call the function that...)*/ setIsMoving(); /*also, instantiate a fish object... not at all relevant to this script.*/ GameObject fish = Instantiate(projectile, transform.position, transform.rotation) as GameObject; fish.GetComponent<Rigidbody>().velocity = new Vector3(dir.x * 7, dir.y * 7, dir.z * 7); fish.tag = "fish"; } /* if the player isMoving (IE movement is enabled) then move the player.*/ if(isMoving) { rb.velocity = new Vector3(dir.x*speed, 0, dir.z*speed); } else { rb.velocity = Vector3.zero; } } public void setIsMoving() { if(isMoving) { isMoving = false; } else { isMoving = true; } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace LinqToSqlWrongDistinctClauseReproduction.Models { [Table("Property")] public class Property { [Key] [Column("Id")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; protected set; } [Required] [Column("Source")] public DataSource Source { get; set; } [Required] [Column("ForeignId")] public string ForeignId { get; set; } [Required] [Column("CreationDate")] public DateTime CreationDate { get; set; } [Column("LastUpdate")] public DateTime? LastUpdate { get; set; } public DateTime? RemovalDate { get; set; } [Column("Details")] public string Details { get; set; } [Column("IsRemoved")] public bool IsRemoved { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Step_165 { class Program { static void Main(string[] args) { DateTime todaysDate = DateTime.Now.Date; int yy = todaysDate.Year; try { Console.WriteLine("How old are you?"); int age = Convert.ToInt32(Console.ReadLine()); if (age >= 1) { int yearBorn = yy - age; Console.WriteLine(yearBorn); Console.ReadLine(); } else { throw new ArgumentOutOfRangeException(); } } catch (FormatException) { Console.WriteLine("Please enter numbers for your age."); Console.ReadLine(); } catch (ArgumentOutOfRangeException) { Console.WriteLine("Cannot enter 0 or a negative number. Please try again!"); Console.ReadLine(); } } } }
using ArkSavegameToolkitNet.Types; using log4net; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet.Arrays { public sealed class ArkArrayRegistry { private static ILog _logger = LogManager.GetLogger(typeof(ArkArrayRegistry)); private static readonly ArkName _object = ArkName.Create("ObjectProperty"); private static readonly ArkName _struct = ArkName.Create("StructProperty"); private static readonly ArkName _uint32 = ArkName.Create("UInt32Property"); private static readonly ArkName _int = ArkName.Create("IntProperty"); private static readonly ArkName _uint16 = ArkName.Create("UInt16Property"); private static readonly ArkName _int16 = ArkName.Create("Int16Property"); private static readonly ArkName _byte = ArkName.Create("ByteProperty"); private static readonly ArkName _int8 = ArkName.Create("Int8Property"); private static readonly ArkName _str = ArkName.Create("StrProperty"); private static readonly ArkName _uint64 = ArkName.Create("UInt64Property"); private static readonly ArkName _bool = ArkName.Create("BoolProperty"); private static readonly ArkName _float = ArkName.Create("FloatProperty"); private static readonly ArkName _double = ArkName.Create("DoubleProperty"); private static readonly ArkName _name = ArkName.Create("NameProperty"); public static IArkArray read(ArkArchive archive, ArkName arrayType, int size) { if (arrayType.Equals(_object)) return new ArkArrayObjectReference(archive, size); else if (arrayType.Equals(_struct)) return new ArkArrayStruct(archive, size); else if (arrayType.Equals(_uint32) || arrayType.Equals(_int)) return new ArkArrayInteger(archive, size); else if (arrayType.Equals(_uint16) || arrayType.Equals(_int16)) return new ArkArrayInt16(archive, size); else if (arrayType.Equals(_byte)) return new ArkArrayByte(archive, size); else if (arrayType.Equals(_int8)) return new ArkArrayInt8(archive, size); else if (arrayType.Equals(_str)) return new ArkArrayString(archive, size); else if (arrayType.Equals(_uint64)) return new ArkArrayLong(archive, size); else if (arrayType.Equals(_bool)) return new ArkArrayBool(archive, size); else if (arrayType.Equals(_float)) return new ArkArrayFloat(archive, size); else if (arrayType.Equals(_double)) return new ArkArrayDouble(archive, size); else if (arrayType.Equals(_name)) return new ArkArrayName(archive, size); else { _logger.Warn($"Unknown Array Type {arrayType} at {archive.Position:X}"); return null; } } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Embraer_Backend.Models; using Microsoft.Extensions.Configuration; using System; using Microsoft.AspNetCore.Cors; using System.Linq; namespace Embraer_Backend.Controllers { [Route("api/[controller]/[action]")] [EnableCors("CorsPolicy")] public class GeralController : Controller { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(GeralController)); private readonly IConfiguration _configuration; IEnumerable<LocalMedicao> _local; LocalMedicaoModel _localMedicaoModel= new LocalMedicaoModel(); IEnumerable<Equipamentos> _equips; EquipamentosModel _equipsModel= new EquipamentosModel(); IEnumerable<ControleApontamento> _ctrl; ControleApontamentoModel _ctrlModel= new ControleApontamentoModel(); IEnumerable<Sensores> _senso; SensoresModel _senModel= new SensoresModel(); public GeralController(IConfiguration configuration) { _configuration = configuration; } [HttpGet] public IActionResult LocalMedicao() { log.Debug("Get Dos Locais de Apontamento"); _local = _localMedicaoModel.SelectLocalMedicao(_configuration); if (_local.Count()>0) return Ok(_local); else return StatusCode(505,"Não foi encotrado nenhum local de Apontamento verifique o log de erros do sistema!"); } [HttpGet] public IActionResult ControleApontamento(string DescApont) { log.Debug("Get de quantos pontos de coleta terá um Apontamento."); _ctrl = _ctrlModel.SelectControleApontamento(_configuration,DescApont); if (_ctrl.Count()>0) return Ok(_ctrl); else return StatusCode(505,"Não foi encotrado nenhum controle de apontamento para a descrição informada verifique o log de erros do sistema!"); } [HttpGet] public IActionResult Equipamentos() { log.Debug("Get Dos Equipamentos"); _equips= _equipsModel.SelectEquipamentos(_configuration,null); if (_equips.Count()>0) return Ok(_equips); else return StatusCode(505,"Não foi encotrado nenhum equipamento verifique o log de erros do sistema!"); } [HttpGet] public IActionResult Sensores() { log.Debug("Get Dos Sensores"); _senso= _senModel.SelectSensor(_configuration,0,0,"Temperatura"); if (_senso.Count()>0) return Ok(_senso); else return StatusCode(505,"Não foi encotrado nenhum sensor verifique o log de erros do sistema!"); } } }
using System; using System.Collections.Generic; namespace Algorithms.LeetCode { public class Sum4 { public IList<IList<int>> FourSum(int[] nums, int target) { if (nums.Length < 4) return new List<IList<int>>(); Array.Sort(nums); var res = new List<IList<int>>(); for (int i = 0; i < nums.Length - 3; ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue; for (int j = i + 1; j < nums.Length - 2; ++j) { if (j > i + 1 && nums[j] == nums[j - 1]) continue; var l = j + 1; var r = nums.Length - 1; var sum = target - nums[i] - nums[j]; while (l < r) { if (nums[l] + nums[r] < sum) ++l; else if (nums[l] + nums[r] > sum) --r; else { res.Add(new List<int>() { nums[i], nums[j], nums[l], nums[r] }); while (l < r && nums[l] == nums[l + 1]) ++l; while (l < r && nums[r] == nums[r + -1]) --r; ++l; --r; } } } } return res; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameButtons : MonoBehaviour { public GameObject G_ToMainText; public static GameButtons G_GameButtonsClass; public static Text T_ToMainText; public GameObject G_ToMainButton; public static Button B_ToMainButton; public GameObject G_RestartButton; public static Image I_RestartButton; public static Button B_RestartButton; private void Awake() { G_GameButtonsClass = this; I_RestartButton = gameObject.GetComponent<Image>(); B_RestartButton = gameObject.GetComponent<Button>(); B_ToMainButton = G_ToMainButton.GetComponent<Button>(); T_ToMainText = G_ToMainText.GetComponent<Text>(); } private void Start() { I_RestartButton.color = new Color32(255, 255, 255, 0); B_RestartButton.enabled = false; B_ToMainButton.enabled = false; } public void OnRestartButton() { StartCoroutine(I_OnRestartButtonCur()); } public IEnumerator I_OnRestartButtonCur() { SoundManagerGame.V_PlaySoundRestartGame(); yield return new WaitForSeconds(0.2f); SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void OnMainButton() { StartCoroutine(I_OnMaintButtonCur()); } public IEnumerator I_OnMaintButtonCur() { SoundManagerGame.V_PlaySoundToHome(); yield return new WaitForSeconds(0.2f); SceneManager.LoadScene("Main"); } public static IEnumerator I_RestartButtonCur(byte C_ToColor, float F_OverTime) { float F_StartTime = Time.time; while (Time.time < F_StartTime + F_OverTime) { I_RestartButton.color = Color32.Lerp( a: I_RestartButton.color, b: new Color32((byte)(I_RestartButton.color.r * 255), (byte)(I_RestartButton.color.g * 255), (byte)(I_RestartButton.color.b * 255), C_ToColor), t: (Time.time - F_StartTime) / F_OverTime); yield return null; } I_RestartButton.color = new Color32((byte)(I_RestartButton.color.r * 255), (byte)(I_RestartButton.color.g * 255), (byte)(I_RestartButton.color.b * 255), C_ToColor); B_RestartButton.enabled = true; B_ToMainButton.enabled = true; G_GameButtonsClass.StartCoroutine(I_Timer()); } public static IEnumerator I_Timer() { yield return new WaitForSeconds(5); G_GameButtonsClass.StartCoroutine(I_ToMainTextCur(255, 3f)); } public static IEnumerator I_ToMainTextCur(byte C_ToColor, float F_OverTime) { float F_StartTime = Time.time; while (Time.time < F_StartTime + F_OverTime) { T_ToMainText.color = Color32.Lerp( a: T_ToMainText.color, b: new Color32((byte)(T_ToMainText.color.r * 255), (byte)(T_ToMainText.color.g * 255), (byte)(T_ToMainText.color.b * 255), C_ToColor), t: (Time.time - F_StartTime) / F_OverTime); yield return null; } T_ToMainText.color = new Color32((byte)(T_ToMainText.color.r * 255), (byte)(T_ToMainText.color.g * 255), (byte)(T_ToMainText.color.b * 255), C_ToColor); } }
using UnityEngine; using System.Collections.Generic; using UnityEditor; using System.IO; public class AssetBundleBuilder { public const string AssetBundlesOutputPath = "AssetBundles"; [MenuItem("Assets/AssetBundles/Build AssetBundles")] public static void BuildAssetBundles() { AssetDatabase.RemoveUnusedAssetBundleNames(); string outputPath = Path.Combine(AssetBundlesOutputPath, Utility.PlatformName); if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); BuildPipeline.BuildAssetBundles(outputPath, BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.IgnoreTypeTreeChanges, EditorUserBuildSettings.activeBuildTarget); Debug.Log("打包完成."); } }
using EddiDataDefinitions; using System; using Utilities; namespace EddiEvents { [PublicAPI] public class NextDestinationEvent : Event { public const string NAME = "Next destination"; public const string DESCRIPTION = "Triggered when selecting an in-system destination"; public static NextDestinationEvent SAMPLE = new NextDestinationEvent(DateTime.UtcNow, 8879744226018, 59, "$MULTIPLAYER_SCENARIO14_TITLE;", "Resource Extraction Site"); [PublicAPI("The name of the next in-system destination")] public string name { get; private set; } [PublicAPI("The localized name of the next in-system destination, if known")] public string localizedName { get; private set; } [PublicAPI("If the destination is an body")] public bool isBody => body != null; [PublicAPI("If the destination is an station (including megaship or fleet carrier)")] public bool isStation => station != null; [PublicAPI("If the destination is a signal source")] public bool isSignalSource => signalSource != null; [PublicAPI("If the destination is a Point of Interest / miscellaneous location")] public bool isPOI => body == null && station == null && signalSource == null; // Not intended to be user facing public ulong? systemAddress { get; private set; } public int? bodyId { get; private set; } public Body body { get; private set; } public Station station { get; private set; } public SignalSource signalSource { get; private set; } public NextDestinationEvent(DateTime timestamp, ulong? systemAddress, int? bodyId, string name, string localizedName = null, Body body = null, Station station = null, SignalSource signalSource = null) : base(timestamp, NAME) { this.systemAddress = systemAddress; this.bodyId = bodyId; this.name = name; this.localizedName = localizedName; this.body = body; this.station = station; this.signalSource = signalSource; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Users.Mapeamentos; using Welic.Dominio.Patterns.Service.Pattern; namespace Welic.Dominio.Models.Users.Servicos { public interface IServiceUser: IService<AspNetUser> { //UserDto Save(UserDto userDto); //UserDto GetById(string id); //List<UserDto> GetAll(); //void Delete(string id); //UserDto GetByEmail(string email); //UserDto GetByName(string name); //Users.Entidades.User Autenticar(ComandUser comando); //IEnumerable<GroupUserDto> GetGroupUser(); } }
namespace MySurveys.Controllers.Tests { using System.Collections.Generic; using Models; using Moq; using NUnit.Framework; using Services.Contracts; using TestStack.FluentMVCTesting; using Web.Areas.Surveys.Controllers; using Web.Areas.Surveys.ViewModels.Filling; using Web.Infrastructure.Mapping; [TestFixture] public class SurveysControllerTests { private const string SurveyTitle = "Test survey title"; private const string UserEmail = "user@test.com"; private const string UserName = "user"; private SurveysController controller; [SetUp] public void SetUp() { var autoMapperConfig = new AutoMapperConfig(); autoMapperConfig.Execute(typeof(SurveysController).Assembly); var surveysServiceMock = new Mock<ISurveyService>(); var userServiceMock = new Mock<IUserService>(); var questionServiceMock = new Mock<IQuestionService>(); var responseServiceMock = new Mock<IResponseService>(); userServiceMock .Setup(x => x.GetById(It.IsAny<string>())) .Returns(new User { Email = UserEmail, UserName = UserName, PasswordHash = "123" }); surveysServiceMock .Setup(x => x.GetById(It.IsAny<string>())) .Returns(new Survey { Id = 1, Title = SurveyTitle, Author = userServiceMock.Object.GetById("dsds"), AuthorId = userServiceMock.Object.GetById("dsss").Id, IsPublic = true, Questions = new List<Question> { new Question { } } }); questionServiceMock.Setup(x => x.GetNext(It.IsAny<Question>(), It.IsAny<string>())).Returns(new Question { Content = string.Empty }); responseServiceMock.Setup(x => x.Update(It.IsAny<Response>())).Returns(new Response { }); this.controller = new SurveysController(surveysServiceMock.Object, userServiceMock.Object, questionServiceMock.Object, responseServiceMock.Object); } [Test] public void FillingUpShoudRenderCorrectView() { this.controller .WithCallTo(x => x.FillingUp("fewt")) .ShouldRenderView("FillingUp") .WithModel<QuestionViewModel>() .AndNoModelErrors(); } } }
namespace DataAccess.Migrations.UsersContextMigrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.ChatLines", c => new { ChatLineId = c.Int(nullable: false, identity: true), UserChatId = c.Int(nullable: false), MsgDateTime = c.DateTime(nullable: false), MsgText = c.String(), FromUserName = c.String(), }) .PrimaryKey(t => t.ChatLineId) .ForeignKey("dbo.UserChats", t => t.UserChatId, cascadeDelete: true) .Index(t => t.UserChatId); CreateTable( "dbo.UserChats", c => new { UserChatId = c.Int(nullable: false, identity: true), Collocutors = c.String(), }) .PrimaryKey(t => t.UserChatId); CreateTable( "dbo.UserProfile", c => new { UserId = c.Int(nullable: false, identity: true), UserName = c.String(), }) .PrimaryKey(t => t.UserId); } public override void Down() { DropForeignKey("dbo.ChatLines", "UserChatId", "dbo.UserChats"); DropIndex("dbo.ChatLines", new[] { "UserChatId" }); DropTable("dbo.UserProfile"); DropTable("dbo.UserChats"); DropTable("dbo.ChatLines"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Korzh.EasyQuery; namespace ApartmentApps.Data { //[EqEntity(UseInConditions = false, UseInResult = false)] public class Property : IBaseEntity { [EqEntityAttr(UseInConditions = false)] public TimeZoneInfo TimeZone { get { return TimeZoneInfo.FindSystemTimeZoneById(TimeZoneIdentifier ?? TimeZoneInfo.Local.Id); } } [Key] [EqEntityAttr(UseInConditions = false)] public int Id { get; set; } public DateTime? CreateDate { get; set; } // public DateTime? UpdateDate { get; set; } [Searchable] public string Name { get; set; } [EqEntityAttr(UseInConditions = false)] public int CorporationId { get; set; } [ForeignKey("CorporationId")] public virtual Corporation Corporation { get; set; } public virtual ICollection<PropertyAddon> PropertyAddons { get; set; } public virtual ICollection<Building> Buildings { get; set; } [NotMapped] public virtual IEnumerable<MaitenanceRequest> MaitenanceRequests { get { return Users.SelectMany(p=>p.MaitenanceRequests); } } public string TimeZoneIdentifier { get; set; } public virtual ICollection<ApplicationUser> Users { get; set; } [Searchable] public PropertyState State { get; set; } } public enum PropertyState { Active, Suspended, Archived, TestAccount, Pending } }
 using Windows.UI.Xaml.Controls; using Welic.App.Implements; using Xamarin.Forms.Platform.UWP; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Xaml.Media; [assembly: ExportRenderer(typeof(VideoPlayer), typeof(Welic.App.UWP.VideoPlayerRenderer))] namespace Welic.App.UWP { public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, MediaElement> { //protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args) //{ // base.OnElementChanged(args); // if (args.NewElement != null) // { // if (Control == null) // { // MediaElement mediaElement = new MediaElement(); // SetNativeControl(mediaElement); // mediaElement.MediaOpened += OnMediaElementMediaOpened; // mediaElement.CurrentStateChanged += OnMediaElementCurrentStateChanged; // } // } //} //protected override void Dispose(bool disposing) //{ // if (Control != null) // { // Control.MediaOpened -= OnMediaElementMediaOpened; // Control.CurrentStateChanged -= OnMediaElementCurrentStateChanged; // } // base.Dispose(disposing); //} } }
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.Net.Sockets; using System.Threading; namespace chatClient { public partial class Form1 : Form { public Form1() { InitializeComponent(); } chatClient chat; System.Windows.Forms.Timer bgworker = new System.Windows.Forms.Timer(); private void Form1_Load(object sender, EventArgs e) { chat = new chatClient(); bgworker.Interval = 100; bgworker.Start(); bgworker.Tick += bgworker_Tick; } protected override void OnClosing(CancelEventArgs e) { chat.Stop(); base.OnClosing(e); } void bgworker_Tick(object sender, EventArgs e) { string s = chat.getMessage(); if (s != "") { listBox1.Items.Insert(0, s); } } private void send_Click(object sender, EventArgs e) { chat.sendMessage(textBox1.Text); textBox1.Text = ""; } private void Form1_Leave(object sender, EventArgs e) { } } // chat client class public class chatClient { int port = 12312; TcpClient client = new TcpClient(); // списки с очередями сообщений List<string> Msgs = new List<string>(); List<string> SendMessages = new List<string>(); // вырубем поток чата при закрытии проги public void Stop() { cThread.Abort(); } // получаем первый месседж из очереди месседжей public string getMessage() { if (Msgs.Count > 0) { lock(Msgs) { string s = Msgs[0]; Msgs.RemoveAt(0); return s; } } return ""; } // добавляем месседж в очередть на отправку public void sendMessage(string str) { SendMessages.Add(str); } Thread cThread; // поток клиента public chatClient() // конструктор класса { client.Connect("localhost", port); if (client.Connected) { cThread = new Thread(new ParameterizedThreadStart(chatThread)); cThread.Start(client); } } // тело треда чата void chatThread(object client) { TcpClient Client = (TcpClient)client; NetworkStream ns = Client.GetStream(); while (Client.Connected) // { try { // если есть что читать if(ns.DataAvailable) { byte[] buf = new byte [4096]; int read = ns.Read(buf, 0, 4096); string input = UTF8Encoding.UTF8.GetString(buf, 0, read); lock(Msgs) { Msgs.Add(input); } } // если в очереди на запись что-то есть if (SendMessages.Count > 0) { byte[] buff = UTF8Encoding.UTF8.GetBytes( SendMessages[0] ); lock(SendMessages){ SendMessages.RemoveAt(0); } ns.Write(buff, 0, buff.Length); } } catch { // отрубаемся на ошибке Msgs.Add("disconnected ><"); return; } Thread.Sleep(100); } } } }
using System; using System.Collections.Generic; namespace Hatchet { public static class HatchetTypeRegistry { private static readonly Dictionary<string, Type> TypeLookup = new Dictionary<string, Type>( StringComparer.OrdinalIgnoreCase); public static void Clear() { TypeLookup.Clear(); } public static void Add<T>() where T : class { var type = typeof(T); Add(type); } public static void Add(Type type) { var name = type.Name; if (!type.IsClass) throw new ArgumentException($"Type {type} must be a class type", nameof(type)); if (type.IsAbstract) throw new ArgumentException($"Type {type} cannot be an abstract type", nameof(type)); if (TypeLookup.ContainsKey(name)) throw new HatchetException($"Type {type} is already registered with name {name}"); TypeLookup[type.Name] = type; } /// <summary> /// Retrieve type by name, return null if no type is found. /// </summary> /// <param name="name"></param> /// <returns></returns> public static Type GetType(string name) { Type result; TypeLookup.TryGetValue(name, out result); return result; } } }
using Fbtc.Domain.Entities; namespace Fbtc.Domain.Interfaces.Repositories { public interface IPagSeguroRepository { // string GetNotificationCode(string notificationCode); string NotificationTransacao(string notificationCode, string notificationType); string UpdateRecebimentoPagSeguro(TransacaoPagSeguro transacaoPagSeguro); string SaveDadosTransacaoPagSeguro(TransacaoPagSeguro transacaoPagSeguro); int UpdateRecebimentosPeriodoPagSeguro(TransactionSearchResult transactionSearchResult); CheckOutPagSeguro getDadosParaCheckOutPagSeguro(int associadoId, string tipoEndereco, int anoInicio, int anoTermino, bool enderecoRequerido, bool isAnuidade); } }
using System; using System.IO; using learningWindowsForms.Models; using Dapper; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SQLite; using System.Windows.Forms; using learningWindowsForms.Interfaces; namespace learningWindowsForms.DAL.Repositories { public class RequestRepository : BaseRepository, IRequestRepo { public RequestRepository() { RemoveOldFile(); CreateDatabaseTables(); LoadData(); } #region Initialize Database public void InitializeDatabase() { RemoveOldFile(); CreateDatabaseTables(); } public void RemoveOldFile() { string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "WebServiceUI"); //Delete old directory/file if (Directory.Exists(filePath)) { try { var dir = new DirectoryInfo(filePath); dir.Delete(true); } catch (IOException ex) { MessageBox.Show(ex.Message); } } //Create new directory/file Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "WebServiceUI")); } public void CreateDatabaseTables() { using (var connection = SimpleDbConnection()) { connection.Open(); connection.Execute( @"CREATE TABLE Request ( RequestID INTEGER PRIMARY KEY, Name varchar(50) NOT NULL ); CREATE TABLE UriOption ( UriOptionID INTEGER PRIMARY KEY, Name varchar(50) NOT NULL, Value varchar(50) NOT NULL, ThereIsQuery boolean NOT NULL, RequestID INTEGER NOT NULL, FOREIGN KEY (RequestID) REFERENCES Request(RequestID) ); CREATE TABLE Parameter ( ParameterID INTEGER PRIMARY KEY, Name varchar(30) NOT NULL, PreQuery boolean NOT NULL, Required boolean, UriOptionID INTEGER NOT NULL, FOREIGN KEY (UriOptionID) REFERENCES UriOption(UriOptionID) );"); } } private void LoadData() { //TODO: Update UriOption/Database to account for Uris that have dual segments: /messsages/{MESSAGESID}/attachment/{ImageSID} //Affects: //MessageWebService.svc //RouteWebService.svc List<Request> requests = new List<Request>() { //BlackBoxWebService.svc new Request() { Name = "/BlackBoxWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/blackboxsummary/", Value = "/blackboxsummary/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "StartDate", PreQuery = false }, new Parameter() { Name = "EndDate", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "IncludeHistory", PreQuery = false }, new Parameter() { Name = "OnlyShowEventsWithVideo", PreQuery = false }, new Parameter() { Name = "OrderDirection", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, } }, new UriOption() { Name = "/blackboxsummary/driver/{DriverID}", Value = "/blackboxsummary/driver/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "DriverID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false }, new Parameter() { Name = "EndDate", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "IncludeHistory", PreQuery = false }, new Parameter() { Name = "OnlyShowEventsWithVideo", PreQuery = false }, new Parameter() { Name = "OrderDirection", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, } }, new UriOption() { Name = "/blackboxsummary/vehicle/{VehicleID}", Value = "/blackboxsummary/vehicle/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "VehicleID", PreQuery = true}, new Parameter() { Name = "StartDate", PreQuery = false }, new Parameter() { Name = "EndDate", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "IncludeHistory", PreQuery = false }, new Parameter() { Name = "OnlyShowEventsWithVideo", PreQuery = false }, new Parameter() { Name = "OrderDirection", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, } }, } }, //DelayDetailReportWebService.svc new Request() { Name = "/DelayDetailReportWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/DelayDetail/", Value = "/DelayDetail/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, new Parameter() { Name = "DriverID", PreQuery = false }, new Parameter() { Name = "RouteID", PreQuery = false }, new Parameter() { Name = "DelayReason", PreQuery = false }, new Parameter() { Name = "StartDateTime", PreQuery = false }, new Parameter() { Name = "EndDateTime", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, new Parameter() { Name = "Recurse", PreQuery = false }, } } } }, //DelaySummaryReportWebService.svc new Request() { Name = "/DelaySummaryReportWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/DelaySummary/", Value = "/DelaySummary/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, new Parameter() { Name = "DriverID", PreQuery = false }, new Parameter() { Name = "RouteID", PreQuery = false }, new Parameter() { Name = "DelayReason", PreQuery = false }, new Parameter() { Name = "StartDateTime", PreQuery = false }, new Parameter() { Name = "EndDateTime", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, new Parameter() { Name = "Recurse", PreQuery = false }, } } } }, //DeviceWebService.svc new Request() { Name = "/DeviceWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/device/{PhoneNumber}", Value = "/device/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "PhoneNumber", PreQuery = true, Required = true }, } }, new UriOption() { Name = "/devices/", Value = "/devices/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, new Parameter() { Name = "IsActive", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, } } } }, //DriverLogWebService.svc new Request() { Name = "/DriverLogWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/driverlog/", Value = "/driverlog/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false, Required = true}, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, new Parameter() { Name = "Edits", PreQuery = false }, new Parameter() { Name = "StartDate", PreQuery = false }, new Parameter() { Name = "EndDate", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, } }, new UriOption() { Name = "/driverlog/{DriverID}", Value = "/driverlog/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "DriverID", PreQuery = true, Required = true }, new Parameter() { Name = "Edits", PreQuery = false }, new Parameter() { Name = "StartDate", PreQuery = false }, new Parameter() { Name = "EndDate", PreQuery = false }, } }, new UriOption() { Name = "/driverlogdetails/", Value = "/driverlogdetails/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, } }, new UriOption() { Name = "/driverlogdetails/{DriverID}", Value = "/driverlogdetails/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "DriverID", PreQuery = true, Required = true }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, } } } }, //DriverStatusWebService.svc new Request() { Name = "/DriverStatusWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/driverstate/{DriverID}", Value = "/driverstate/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "DriverID", PreQuery = true, Required = true }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, } }, new UriOption() { Name = "/driverstatus/", Value = "/driverstatus/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationSID", PreQuery = false}, new Parameter() { Name = "ResourceGroupSID", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "Options", PreQuery = false}, } }, new UriOption() { Name = "/driverstatus/{DriverSID}", Value = "/driverstatus/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "DriverSID", PreQuery = true, Required = true }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, } }, } }, //DriverWebService.svc new Request() { Name = "/DriverWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/driver/{DriverID}", Value = "/driver/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "DriverID", PreQuery = false} } }, new UriOption() { Name = "/drivers/", Value = "/drivers/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "ResourceGroupSID", PreQuery = false}, new Parameter() { Name = "OrganizationSID", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, } }, new UriOption() { Name = "/drivers/{DriverSID}", Value = "/drivers/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "DriverSID", PreQuery = true, Required = true} } }, } }, //DVIRWebService.svc new Request() { Name = "/DVIRWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/DVIR/", Value = "/DVIR/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "DriverID", PreQuery = false}, new Parameter() { Name = "AssetType", PreQuery = false}, new Parameter() { Name = "InspectionsWithDefectsOnly", PreQuery = false}, new Parameter() { Name = "IncludeNonDefects", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/DVIR/trailer/{TrailerID}", Value = "/DVIR/trailer/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "TrailerID", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "DriverID", PreQuery = false}, new Parameter() { Name = "InspectionsWithDefectsOnly", PreQuery = false}, new Parameter() { Name = "IncludeNonDefects", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/DVIR/trailer/{VehicleID}", Value = "/DVIR/trailer/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "DriverID", PreQuery = false}, new Parameter() { Name = "InspectionsWithDefectsOnly", PreQuery = false}, new Parameter() { Name = "IncludeNonDefects", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, } }, //FaultCodeWebService.svc new Request() { Name = "/FaultCodeWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/FaultCodes/", Value = "/FaultCodes/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/FaultCodes/vehicle/{VehicleID}", Value = "/FaultCodes/vehicle/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, } }, //FormTemplateCategoryWebService.svc new Request() { Name = "/FormTemplateCategoryWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/formcategories/", Value = "/formcategories/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/formcategories/{FormTemplateCategorySID}", Value = "/formcategories/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "FormTemplateCategorySID", PreQuery = true, Required = true}, } }, new UriOption() { Name = "/formcategory/{FormTemplateCategoryID}", Value = "/formcategory/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "FormTemplateCategoryID", PreQuery = true, Required = true}, } }, } }, //FormTemplateContentWebService.svc new Request() { Name = "/FormTemplateContentWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/formtemplatecontent/", Value = "/formtemplatecontent/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "FormCategorySID", PreQuery = false}, new Parameter() { Name = "InProduction", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "FormCategoryID", PreQuery = false}, } }, new UriOption() { Name = "/formtemplatecontent/{FormNumber}", Value = "/formtemplatecontent/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "FormNumber", PreQuery = true, Required = true}, } }, } }, //FormTemplateHeaderWebService.svc new Request() { Name = "/FormTemplateHeaderWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/formtemplateheader/", Value = "/formtemplateheader/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "FormCategorySID", PreQuery = false}, new Parameter() { Name = "InProduction", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "FormCategoryID", PreQuery = false}, } }, new UriOption() { Name = "/formtemplateheader/{FormNumber}", Value = "/formtemplateheader/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "FormNumber", PreQuery = true, Required = true}, } }, } }, //IFTAWebService.svc new Request() { Name = "/IFTAWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/Distances/", Value = "/Distances/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "StartDateTime", PreQuery = false}, new Parameter() { Name = "EndDateTime", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "StateProvince", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "FormCategoryID", PreQuery = false}, } }, new UriOption() { Name = "/Distances/{vehicleId}", Value = "/Distances/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDateTime", PreQuery = false}, new Parameter() { Name = "EndDateTime", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/FuelReceipts/", Value = "/FuelReceipts/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationId", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "StateProvince", PreQuery = false}, new Parameter() { Name = "Vendor", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/FuelReceipts/{vehicleId}", Value = "/FuelReceipts/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleId", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/JurisdictionCrossings/", Value = "/JurisdictionCrossings/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationId", PreQuery = true, Required = true}, new Parameter() { Name = "StartDateTime", PreQuery = false}, new Parameter() { Name = "EndDateTime", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/JurisdictionCrossings/{vehicleId}", Value = "/JurisdictionCrossings/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleId", PreQuery = true, Required = true}, new Parameter() { Name = "StartDateTime", PreQuery = false}, new Parameter() { Name = "EndDateTime", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, } }, //TODO: Update UriOption/Database to account for Uris that have dual segments: /messsages/{MESSAGESID}/attachment/{ImageSID} //MessageWebService.svc new Request() { Name = "/MessageWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/messages/", Value = "/messages/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "MessageType", PreQuery = false}, new Parameter() { Name = "FormNumber", PreQuery = false}, new Parameter() { Name = "IncludeImageData", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrderDirection", PreQuery = false}, } }, new UriOption() { Name = "/messages/{MessageSID}", Value = "/messages/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "MessageSID", PreQuery = true, Required = true}, new Parameter() { Name = "IncludeImageData", PreQuery = false}, } }, new UriOption() { Name = "/messages/read", Value = "/messages/read", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "MessageType", PreQuery = false}, new Parameter() { Name = "FormNumber", PreQuery = false}, new Parameter() { Name = "IncludeImageData", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrderDirection", PreQuery = false}, new Parameter() { Name = "MessageSID", PreQuery = false}, new Parameter() { Name = "ImageSID", PreQuery = false}, new Parameter() { Name = "StartDateTime", PreQuery = false}, new Parameter() { Name = "EndDateTime", PreQuery = false}, } }, new UriOption() { Name = "/messages/status/", Value = "/messages/status/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "MessageType", PreQuery = false}, new Parameter() { Name = "FormNumber", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/messages/status/{MessageSID}", Value = "/messages/status/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "MessageSID", PreQuery = true, Required = true}, } }, } }, //OperationWebService.svc new Request() { Name = "/OperationWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/Profile/", Value = "/Profile/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "GroupBy", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "IncludeHistory", PreQuery = false}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/Profile/driver/{DriverID}", Value = "/Profile/driver/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "DriverID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, } }, new UriOption() { Name = "/Profile/vehicle/{VehicleID}", Value = "/Profile/vehicle/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, } }, new UriOption() { Name = "/Summary/", Value = "/Summary/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "GroupBy", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "IncludeHistory", PreQuery = false}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/Summary/driver/{DriverID}", Value = "/Summary/driver/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "DriverID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, } }, new UriOption() { Name = "/Summary/vehicle/{VehicleID}", Value = "/Summary/vehicle/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true}, new Parameter() { Name = "StartDate", PreQuery = false}, new Parameter() { Name = "EndDate", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, } }, } }, //OrganizationWebService.svc new Request() { Name = "/OrganizationWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/organization/{SID}", Value = "/organization/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationSID", PreQuery = true, Required = true} } }, new UriOption() { Name = "/organizations/", Value = "/organizations/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationSid", PreQuery = false}, new Parameter() { Name = "Status", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrganizationId", PreQuery = false} } }, new UriOption() { Name = "/organizations/{ID}", Value = "/organizations/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = true, Required = true} } } } }, //OutOfRouteWebService.svc new Request() { Name = "/OutOfRouteWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/OORR/", Value = "/OORR/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "FromDate", PreQuery = false}, new Parameter() { Name = "ToDate", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false} } }, } }, //PlanVsActualWebService.svc new Request() { Name = "/PlanVsActualWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/PVAR/", Value = "/PVAR/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "FromDate", PreQuery = false}, new Parameter() { Name = "ToDate", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false} } }, new UriOption() { Name = "/PVAVLSR/", Value = "/PVAVLSR/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "FromDate", PreQuery = false}, new Parameter() { Name = "ToDate", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false} } } } }, //ResourceGroupWebService.svc new Request() { Name = "/ResourceGroupWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/resourcegroup/{ResourceGroupId}", Value = "/resourcegroup/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "ResourceGroupId", PreQuery = true, Required = true}, } }, new UriOption() { Name = "/resourcegroups/", Value = "/resourcegroups/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationSID", PreQuery = false}, new Parameter() { Name = "ResourceGroupSID", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false} } }, new UriOption() { Name = "/resourcegroup/{ResourceGroupSid}", Value = "/resourcegroup/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "ResourceGroupSid", PreQuery = true, Required = true}, } }, } }, //RouteStatusWebService.svc new Request() { Name = "/RouteStatusWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/RSTR/", Value = "/RSTR/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "FromDate", PreQuery = false}, new Parameter() { Name = "ToDate", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false}, } }, } }, //TODO: Update UriOption/Database to account for Uris that have dual segments: /messsages/{MESSAGESID}/attachment/{ImageSID} //RouteWebService.svc new Request() { Name = "/RouteWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/route", Value = "/route", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "organizationID", PreQuery = false}, new Parameter() { Name = "resourceGroupID", PreQuery = false}, new Parameter() { Name = "asOfDateTime", PreQuery = false}, new Parameter() { Name = "limit", PreQuery = false}, new Parameter() { Name = "offset", PreQuery = false}, new Parameter() { Name = "recurse", PreQuery = false} } } //TODO: Update UriOption //new UriOption() //{ // Name = "/route/{organizationID}/{routeID}", // Value = "/route/{organizationID}/{routeID}", // ThereIsQuery = false, // Parameters = new List<Parameter> // { // new Parameter() { Name = "organizationID", PreQuery = false}, // new Parameter() { Name = "resourceGroupID", PreQuery = false}, // new Parameter() { Name = "asOfDateTime", PreQuery = false}, // new Parameter() { Name = "limit", PreQuery = false}, // new Parameter() { Name = "offset", PreQuery = false}, // new Parameter() { Name = "recurse", PreQuery = false} // } //}, } }, //SiteActivityWebService.svc new Request() { Name = "/SiteActivityWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/SITR/", Value = "/SITR/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "FromDate", PreQuery = false}, new Parameter() { Name = "ToDate", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false} } } //TODO: Update UriOption //new UriOption() //{ // Name = "/route/{organizationID}/{routeID}", // Value = "/route/{organizationID}/{routeID}", // ThereIsQuery = false, // Parameters = new List<Parameter> // { // new Parameter() { Name = "organizationID", PreQuery = false}, // new Parameter() { Name = "resourceGroupID", PreQuery = false}, // new Parameter() { Name = "asOfDateTime", PreQuery = false}, // new Parameter() { Name = "limit", PreQuery = false}, // new Parameter() { Name = "offset", PreQuery = false}, // new Parameter() { Name = "recurse", PreQuery = false} // } //}, } }, //SiteWebService.svc new Request() { Name = "/SiteWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/sites/", Value = "/sites/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false} } }, new UriOption() { Name = "/sites/{SiteID}", Value = "/sites/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "SiteID", PreQuery = true, Required = true} } } } }, //TrailerWebService.svc new Request() { Name = "/TrailerWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/trailer/{trailerID}", Value = "/trailer/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "TrailerID", PreQuery = true, Required = true}, } }, new UriOption() { Name = "/trailers", Value = "/trailers", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "Status", PreQuery = false}, new Parameter() { Name = "asOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false}, } } } }, //TripWebService.svc new Request() { Name = "/TripWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/trip", Value = "/trip", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "RouteID", PreQuery = false}, new Parameter() { Name = "TripID", PreQuery = false}, new Parameter() { Name = "asOfDateTime", PreQuery = false}, new Parameter() { Name = "FromDateTime", PreQuery = false}, new Parameter() { Name = "ToDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false}, } }, new UriOption() { Name = "/tripV2", Value = "/tripV2", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "RouteID", PreQuery = false}, new Parameter() { Name = "TripID", PreQuery = false}, new Parameter() { Name = "asOfDateTime", PreQuery = false}, new Parameter() { Name = "FromDateTime", PreQuery = false}, new Parameter() { Name = "ToDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "TripStatus", PreQuery = false}, new Parameter() { Name = "StopStatus", PreQuery = false}, new Parameter() { Name = "ChangesOnly", PreQuery = false}, new Parameter() { Name = "Recurse", PreQuery = false}, } } } }, //UserWebService.svc new Request() { Name = "/UserWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/users/", Value = "/users/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false}, new Parameter() { Name = "ResourceGroupID", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/users/{UserID}", Value = "/users/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "UserID", PreQuery = true, Required = false}, } } } }, //VehicleBreadcrumbWebService.svc new Request() { Name = "/VehicleBreadcrumbWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/vehiclebreadcrumb/", Value = "/vehiclebreadcrumb/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, new Parameter() { Name = "IsActive", PreQuery = false }, new Parameter() { Name = "AsOfDateTime", PreQuery = false }, new Parameter() { Name = "StartDateTime", PreQuery = false }, new Parameter() { Name = "EndDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false }, new Parameter() { Name = "Offset", PreQuery = false }, new Parameter() { Name = "OrganizationSID", PreQuery = false}, new Parameter() { Name = "ResourceGroupSID", PreQuery = false}, } }, new UriOption() { Name = "/vehiclebreadcrumbs/{VehicleID}", Value = "/vehiclebreadcrumbs/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "StartDateTime", PreQuery = false }, new Parameter() { Name = "EndDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, new UriOption() { Name = "/vehiclebreadcrumb/{VehicleSID}", Value = "/vehiclebreadcrumb/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "VehicleSID", PreQuery = true, Required = true}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "StartDateTime", PreQuery = false }, new Parameter() { Name = "EndDateTime", PreQuery = false }, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, } }, } }, //VehicleStatusWebService.svc new Request() { Name = "/VehicleStatusWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/vehiclestate/{VehicleID}", Value = "/vehiclestate/", ThereIsQuery = true, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true }, new Parameter() { Name = "AsOfDateTime", PreQuery = false } } }, new UriOption() { Name = "/vehiclestatus/", Value = "/vehiclestatus/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "OrganizationSID", PreQuery = false}, new Parameter() { Name = "ResourceGroupSID", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, } }, new UriOption() { Name = "/vehiclestatus/{VehicleSID}", Value = "/vehiclestatus/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "VehicleSID", PreQuery = true, Required = true}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, } }, } }, //VehicleWebService.svc new Request() { Name = "/VehicleWebService.svc", UriOptions = new List<UriOption>() { new UriOption() { Name = "/vehicle/{VehicleID}", Value = "/vehicle/", ThereIsQuery = false, Parameters = new List<Parameter> { new Parameter() { Name = "VehicleID", PreQuery = true, Required = true }, } }, new UriOption() { Name = "/vehicles/", Value = "/vehicles/", ThereIsQuery = true, Parameters = new List<Parameter>() { new Parameter() { Name = "OrganizationSID", PreQuery = false}, new Parameter() { Name = "ResourceGroupSID", PreQuery = false}, new Parameter() { Name = "IsActive", PreQuery = false}, new Parameter() { Name = "AsOfDateTime", PreQuery = false}, new Parameter() { Name = "Limit", PreQuery = false}, new Parameter() { Name = "Offset", PreQuery = false}, new Parameter() { Name = "OrganizationID", PreQuery = false }, new Parameter() { Name = "ResourceGroupID", PreQuery = false }, } }, new UriOption() { Name = "/vehicles/{VehicleSID}", Value = "/vehicles/", ThereIsQuery = false, Parameters = new List<Parameter>() { new Parameter() { Name = "VehicleSID", PreQuery = true, Required = true}, } }, } } }; foreach (var request in requests) { AddCompleteRequest(request); } } #endregion #region Add Record Methods public void AddCompleteRequest(Request newRequest) { long requestID; const string insertSql = "INSERT INTO Request (RequestID, Name) VALUES (NULL, @RequestName);"; using (var connection = SimpleDbConnection()) { connection.Open(); var parameters = new DynamicParameters(); parameters.Add("@RequestName", newRequest.Name); connection.Execute(insertSql, parameters); requestID = connection.LastInsertRowId; connection.Close(); } AddUriOption(requestID, newRequest.UriOptions); } private void AddUriOption(long requestID, List<UriOption> uriOptions) { long uriOptionId; const string insertSql = "INSERT INTO UriOption (UriOptionID, Name, Value, ThereIsQuery, RequestID) VALUES (NULL, @Name, @Value, @ThereIsQuery, @RequestID); SELECT last_insert_rowid();"; foreach (var uri in uriOptions) { using (var connection = SimpleDbConnection()) { connection.Open(); var parameters = new DynamicParameters(); parameters.Add("@Name", uri.Name); parameters.Add("@Value", uri.Value); parameters.Add("@ThereIsQuery", uri.ThereIsQuery); parameters.Add("@RequestID", requestID); connection.Execute(insertSql, parameters); uriOptionId = connection.LastInsertRowId; connection.Close(); } AddParameters(uriOptionId, uri.Parameters); } } private void AddParameters(long uriOptionID, List<Parameter> newParameters) { const string insertSQL = "INSERT INTO Parameter (Name, PreQuery, Required, UriOptionID) VALUES (@Name, @PreQUery, @Required, @UriOption)"; using (var connection = SimpleDbConnection()) { connection.Open(); foreach (var param in newParameters) { var sqlParameter = new DynamicParameters(); sqlParameter.Add("@Name", param.Name); sqlParameter.Add("@PreQuery", param.PreQuery); sqlParameter.Add("@Required", param.Required); sqlParameter.Add("@UriOption", uriOptionID); connection.Execute(insertSQL, sqlParameter); } connection.Close(); } } #endregion #region GET Record Methods public List<Request> GetAllRequestsWithUriOptionsAndParameters() { if (!File.Exists(DbFile)) { CreateDatabaseTables(); LoadData(); } var allRequests = GetAllRequests(); foreach (var request in allRequests) { request.UriOptions = GetUriOptions(request.RequestID); foreach (var uriOption in request.UriOptions) { uriOption.Parameters = GetParameters(uriOption.UriOptionID); } } return allRequests; } private List<Parameter> GetParameters(int uriOptionID) { var parameters = new List<Parameter>(); using (var connection = SimpleDbConnection()) { connection.Open(); var dynParameters = new DynamicParameters(); dynParameters.Add("@UriOptionID", uriOptionID); parameters = connection.Query<Parameter>("SELECT * FROM Parameter WHERE UriOptionID = @UriOptionID", dynParameters).ToList(); connection.Close(); } return parameters; } private List<UriOption> GetUriOptions(int requestId) { var uriOptions = new List<UriOption>(); using (var connection = SimpleDbConnection()) { connection.Open(); var parameters = new DynamicParameters(); parameters.Add("@RequestID", requestId); uriOptions = connection.Query<UriOption>("SELECT * FROM UriOption WHERE RequestID = @RequestID ", parameters).ToList(); connection.Close(); } return uriOptions; } private List<Request> GetAllRequests() { var requests = new List<Request>(); using (var connection = SimpleDbConnection()) { connection.Open(); requests = connection.Query<Request>("SELECT * FROM Request").ToList(); connection.Close(); } return requests; } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace App.Model { public class PagingItems<T> { public int CurrentPage { get; set; } public int RecordPerPage { get; set; } public int TotalRecordRest { get; set; } public int TotalRecord { get; set; } public IList<T> ListItems { get; set; } } }
using MoneyExchangerApp.Domain.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace MoneyExchangerApp.Services.Interfaces { public interface IExchangeService { Task<double> CalculateExchangeAsync(string fromCurrency, double fromAmount, string toCurrency); Task<IEnumerable<ExchangeEntity>> GetExchangeEntitiesAsync(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using lsc.Common; using System.IO; using System.Text; using Microsoft.AspNetCore.Hosting; using OfficeOpenXml; using lsc.Bll; using lsc.Model; namespace lsc.crm.Controllers { public class UploadApiController : Controller { private IHostingEnvironment hostingEnv; public UploadApiController(IHostingEnvironment env) { this.hostingEnv = env; } [HttpPost] public async Task<IActionResult> uploadImage() { JsonResult<PicMsg> result = new JsonResult<PicMsg>(); result.code = 1; result.msg = ""; string url = string.Empty; // 定义允许上传的文件扩展名 const string fileTypes = "gif,jpg,jpeg,png,bmp"; // 最大文件大小(200KB) const int maxSize = 505000; // 获取附带POST参数值 for (var fileId = 0; fileId < Request.Form.Files.Count; fileId++) { var curFile = Request.Form.Files[fileId]; if (curFile.Length < 1) { continue; } else if (curFile.Length > maxSize) { result.msg = "上传文件中有图片大小超出500KB!"; return Json(result); } var fileExt = Path.GetExtension(curFile.FileName); if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) { result.msg = "上传文件中包含不支持文件格式!"; return Json(result); } else { // 存储文件名 string FileName = DateTime.Now.ToString("yyyyMMddhhmmssff") + CreateRandomCode(8) + fileExt; // 存储路径(绝对路径) string virtualPath = Path.Combine(hostingEnv.WebRootPath, "img"); if (!Directory.Exists(virtualPath)) { Directory.CreateDirectory(virtualPath); } string filepath = Path.Combine(virtualPath, FileName); try { using (FileStream fs = System.IO.File.Create(filepath)) { await curFile.CopyToAsync(fs); fs.Flush(); } result.code = 0; result.msg = "OK"; result.data = new PicMsg(); result.data.src = "/img/"+ FileName; result.data.title = FileName; } catch (Exception exception) { result.msg = "上传失败:" + exception.Message; } } } return Json(result); } /// <summary> /// 上传客户信息 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> uploadEnterCustom() { JsonResult<PicMsg> result = new JsonResult<PicMsg>(); result.code = 1; result.msg = ""; int UserID = Request.Form["UserID"].TryToInt(); string UserName = string.Empty; UserBll userBll = new UserBll(); UserInfo user = await userBll.GetByID(UserID); if (user!=null) { UserName = user.Name; } // 获取附带POST参数值 for (var fileId = 0; fileId < Request.Form.Files.Count; fileId++) { var curFile = Request.Form.Files[fileId]; if (curFile.Length < 1) { continue; } var fileExt = Path.GetExtension(curFile.FileName); if (String.IsNullOrEmpty(fileExt) || fileExt!= ".xlsx") { result.msg = "上传文件中包含不支持文件格式!"; return Json(result); } else { // 存储文件名 string FileName = DateTime.Now.ToString("yyyyMMddhhmmssff") + CreateRandomCode(8) + fileExt; // 存储路径(绝对路径) string virtualPath = Path.Combine(hostingEnv.WebRootPath, "file"); if (!Directory.Exists(virtualPath)) { Directory.CreateDirectory(virtualPath); } string filepath = Path.Combine(virtualPath, FileName); try { using (FileStream fs = System.IO.File.Create(filepath)) { await curFile.CopyToAsync(fs); fs.Flush(); } FileInfo file = new FileInfo(filepath); using (ExcelPackage package = new ExcelPackage(file)) { StringBuilder sb = new StringBuilder(); ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; int rowCount = worksheet.Dimension.Rows; int ColCount = worksheet.Dimension.Columns; if (rowCount<2 || ColCount<17) { result.msg = "Excel模板不正确"; return Json(result); } StringBuilder stringBuilder = new StringBuilder(); Dictionary<string, int> enteridDIc = new Dictionary<string, int>(); #region 客户信息 EnterCustomerBll bll = new EnterCustomerBll(); //EnterCustPhaseLogBll logbll = new EnterCustPhaseLogBll(); for (int row =2; row < rowCount; row++) { EnterCustomer enterCustomer = new EnterCustomer(); for (int col = 1;col<ColCount;col++) { string value = worksheet.Cells[row, col].Value.TryToString().Trim(); switch (col) { case 1: enterCustomer.EnterName = value; break; case 2: enterCustomer.Province = value; break; case 3: enterCustomer.City = value; break; case 4: enterCustomer.Telephone = value; break; case 5: enterCustomer.Landline = value; break; case 6: enterCustomer.FaxNumber = value; break; case 7: enterCustomer.ZipCode = value; break; case 8: enterCustomer.Email = value; break; case 9: enterCustomer.WebSit = value; break; case 10: enterCustomer.Address = value; break; case 11: enterCustomer.CustAbstract = value; break; case 12: if (value.IsNull()) break; switch (value) { case "代理经销商": enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Dealer; break; case "普通客户": enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Ordinary; break; case "集团大客户": enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.BigCustomer; break; case "业务合作商": enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Cooperation; break; case "怀疑同行": enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Same; break; case "其他客户": enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Other; break; } break; case 13: if (value.IsNull()) break; switch (value) { case "密切": enterCustomer.Relationship = Model.Enume.RelationshipEnume.Intimate; break; case "较好": enterCustomer.Relationship = Model.Enume.RelationshipEnume.Better; break; case "一般": enterCustomer.Relationship = Model.Enume.RelationshipEnume.Commonly; break; case "较差": enterCustomer.Relationship = Model.Enume.RelationshipEnume.Poor; break; } break; case 14: if (value.IsNull()) break; switch (value) { case "高": enterCustomer.ValueGrade = Model.Enume.ValueGradeEnume.Senior; break; case "中": enterCustomer.ValueGrade = Model.Enume.ValueGradeEnume.Intermediate; break; case "低": enterCustomer.ValueGrade = Model.Enume.ValueGradeEnume.Lower; break; } break; case 15: if (value.IsNull()) break; switch (value) { case "客户来电": enterCustomer.Source = Model.Enume.CustSource.CustTelephone; break; case "主动挖掘": enterCustomer.Source = Model.Enume.CustSource.Excavate; break; case "网站咨询": enterCustomer.Source = Model.Enume.CustSource.WebConsulting; break; case "客户介绍": enterCustomer.Source = Model.Enume.CustSource.Introduction; break; case "其他来源": enterCustomer.Source = Model.Enume.CustSource.Other; break; } break; case 16: if (value.IsNull()) break; switch (value) { case "售前跟踪": enterCustomer.Phase = Model.Enume.PhaseEnume.Pre_sale; break; case "需求确定": enterCustomer.Phase = Model.Enume.PhaseEnume.Demand_Confirmation; break; case "售中跟单": enterCustomer.Phase = Model.Enume.PhaseEnume.In_Sales; break; case "签约洽谈": enterCustomer.Phase = Model.Enume.PhaseEnume.Sign_Contract; break; case "成交售后": enterCustomer.Phase = Model.Enume.PhaseEnume.After_Sale; break; case "跟单失败": enterCustomer.Phase = Model.Enume.PhaseEnume.Invalid; break; case "暂且搁置": enterCustomer.Phase = Model.Enume.PhaseEnume.Shelve; break; case "其他阶段": enterCustomer.Phase = Model.Enume.PhaseEnume.Other; break; } break; case 17: if (value.IsNull()) break; switch (value) { case "是": enterCustomer.IsHeat = true; break; case "否": enterCustomer.IsHeat = false; break; } break; case 18: if (value.IsNull()) break; switch (value) { case "低热": enterCustomer.DegreeOfHeat = Model.Enume.DegreeOfHeatEnume.Lower; break; case "中热": enterCustomer.DegreeOfHeat = Model.Enume.DegreeOfHeatEnume.Intermediate; break; case "高热": enterCustomer.DegreeOfHeat = Model.Enume.DegreeOfHeatEnume.Senior; break; } break; case 19: if (value.IsNull()) break; switch (value) { case "高意向客户": enterCustomer.HeatTYPE = Model.Enume.HeatTypeEnum.Intentional; break; case "重点跟踪客户": enterCustomer.HeatTYPE = Model.Enume.HeatTypeEnum.Key_Account; break; case "有望签单客户": enterCustomer.HeatTYPE = Model.Enume.HeatTypeEnum.Hopeful; break; } break; case 20: enterCustomer.CreateTime = value.TryToDateTime(); break; } } enterCustomer.CreateUserID = UserID; enterCustomer.UpdateTime = DateTime.Now; enterCustomer.UserID = UserID; bool flag = await bll.ExistsEnterNameAsync(0, enterCustomer.EnterName); if (flag) { stringBuilder.AppendLine(string.Format("{0}已存在", enterCustomer.EnterName)); continue; } int id = await bll.AddEnterCustomer(enterCustomer); if (id > 0) { enteridDIc[enterCustomer.EnterName] = id; } else { stringBuilder.AppendLine(string.Format("企业【{0}】|添加失败", enterCustomer.EnterName)); } } #endregion #region 联系人信息 EnterCustContactsBll enterCustContactsBll = new EnterCustContactsBll(); ExcelWorksheet worksheet1 = package.Workbook.Worksheets[2]; int rowCount1 = worksheet1.Dimension.Rows; int colCount1 = worksheet1.Dimension.Columns; if (rowCount1<2 || colCount1<11) { result.msg = "客户联系人信息格式不正确"; return Json(result); } for (int row=2;row<rowCount1;row++) { EnterCustContacts enterCustContacts = new EnterCustContacts(); for (int col=1;col<colCount1;col++) { string value = worksheet1.Cells[row, col].Value.TryToString().Trim(); switch (col) { case 1: if (enteridDIc.ContainsKey(value)) { enterCustContacts.EnterCustID = enteridDIc[value]; } break; case 2: enterCustContacts.Name = value; break; case 3: if (value == "男") enterCustContacts.Sex = Model.Enume.SexEnum.Man; else if (value == "女") enterCustContacts.Sex = Model.Enume.SexEnum.Woman; break; case 4: enterCustContacts.Business = value; break; case 5: enterCustContacts.Department = value; break; case 6: enterCustContacts.Duties = value; break; case 7: enterCustContacts.Landline = value; break; case 8: enterCustContacts.Telephone = value; break; case 9: enterCustContacts.Email = value; break; case 10: enterCustContacts.QQ = value; break; case 11: enterCustContacts.WeChart = value; break; case 12: enterCustContacts.Address = value; break; case 13: enterCustContacts.Rem = value; break; } } if (enterCustContacts.EnterCustID > 0) { int id = await enterCustContactsBll.Add(enterCustContacts); if (id <= 0) stringBuilder.AppendLine(string.Format("企业联系人【{0}】信息保存失败", enterCustContacts.Name)); } } #endregion if (stringBuilder.Length>0) { string errorfile = DateTime.Now.ToString("yyyyMMddhhmmssff") + UserID + ".txt"; string errorfilePath = Path.Combine(virtualPath, errorfile); try { FileStream filestream = new FileStream(errorfilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); StreamWriter writer = new StreamWriter(filestream, System.Text.Encoding.UTF8); writer.BaseStream.Seek(0, SeekOrigin.End); await writer.WriteAsync(stringBuilder.ToString()); writer.Flush(); writer.Close(); filestream.Close(); result.data = new PicMsg(); result.data.src = "/file/" + errorfile; result.data.title = errorfile; } catch { } } } result.code = 0; result.msg = "OK"; } catch (Exception exception) { result.msg = "上传失败:" + exception.Message; } } } return Json(result); } /// <summary> /// 上传目标邮箱 /// </summary> /// <returns></returns> [HttpPost] public async Task<IActionResult> uploadTagEmail() { JsonResult<PicMsg> result = new JsonResult<PicMsg>(); result.code = 1; result.msg = ""; // 获取附带POST参数值 for(var fileId = 0; fileId < Request.Form.Files.Count; fileId++) { var curFile = Request.Form.Files[fileId]; if (curFile.Length < 1) { continue; } var fileExt = Path.GetExtension(curFile.FileName); if (String.IsNullOrEmpty(fileExt) || fileExt != ".xlsx") { result.msg = "上传文件中包含不支持文件格式!"; return Json(result); } else { // 存储文件名 string FileName = DateTime.Now.ToString("yyyyMMddhhmmssff") + CreateRandomCode(8) + fileExt; // 存储路径(绝对路径) string virtualPath = Path.Combine(hostingEnv.WebRootPath, "file"); if (!Directory.Exists(virtualPath)) { Directory.CreateDirectory(virtualPath); } string filepath = Path.Combine(virtualPath, FileName); try { using (FileStream fs = System.IO.File.Create(filepath)) { await curFile.CopyToAsync(fs); fs.Flush(); } FileInfo file = new FileInfo(filepath); using (ExcelPackage package = new ExcelPackage(file)) { StringBuilder sb = new StringBuilder(); ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; int rowCount = worksheet.Dimension.Rows; int ColCount = worksheet.Dimension.Columns; if (rowCount < 2 || ColCount < 2) { result.msg = "Excel模板不正确"; return Json(result); } StringBuilder stringBuilder = new StringBuilder(); Dictionary<string, int> enteridDIc = new Dictionary<string, int>(); TargetEmailBll bll = new TargetEmailBll(); for (int row = 2; row <= rowCount; row++) { TargetEmail targetEmail = new TargetEmail(); for (int col = 1; col <= ColCount; col++) { string value = worksheet.Cells[row, col].Value.TryToString().Trim(); switch (col) { case 1: targetEmail.Name = value; break; case 2: targetEmail.Email = value; break; } } bool flag = await bll.Exists(targetEmail.Name); if (flag) { stringBuilder.AppendLine(string.Format("{0}已存在", targetEmail.Name)); continue; } int id = await bll.AddAsync(targetEmail); if (id <= 0) { stringBuilder.AppendLine(string.Format("邮箱【{0}】|添加失败", targetEmail.Name)); } } if (stringBuilder.Length > 0) { string errorfile = DateTime.Now.ToString("yyyyMMddhhmmssff")+ "error.txt"; string errorfilePath = Path.Combine(virtualPath, errorfile); try { FileStream filestream = new FileStream(errorfilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); StreamWriter writer = new StreamWriter(filestream, System.Text.Encoding.UTF8); writer.BaseStream.Seek(0, SeekOrigin.End); await writer.WriteAsync(stringBuilder.ToString()); writer.Flush(); writer.Close(); filestream.Close(); result.data = new PicMsg(); result.data.src = "/file/" + errorfile; result.data.title = errorfile; } catch(Exception ex) { ClassLoger.Error("uploadTagEmail", ex); } } } result.code = 0; result.msg = "OK"; } catch (Exception exception) { result.msg = "上传失败:" + exception.Message; } } } return Json(result); } class PicMsg { public string src { get; set; } public string title { get; set; } } /// <summary> /// 生成指定长度的随机码。 /// </summary> private string CreateRandomCode(int length) { string[] codes = new string[36] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; StringBuilder randomCode = new StringBuilder(); Random rand = new Random(); for (int i = 0; i < length; i++) { randomCode.Append(codes[rand.Next(codes.Length)]); } return randomCode.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using API.Model; using API.BL; namespace coucheAPI.Controllers { [Route("api/[controller]")] public class StudentController : Controller { [HttpGet] public int Get(string login) { return BL_Api.FindIdUser(login); } } }