text
stringlengths
13
6.01M
using Microsoft.EntityFrameworkCore; using Repository.Models; using System; using System.Collections.Generic; using System.Text; using System.Linq; using ArticlesProject.Repository.Interfaces; using ArticlesProject.DBEntities; namespace ArticlesProject.Repository.Implementations { public class ProductRepository : Repository<Product>, IProductRepository { private DatabaseContext context { get { return _db as DatabaseContext; } } public ProductRepository(DbContext db) : base(db) { } public IEnumerable<ProductViewModel> GetProductList() { var products = (from prd in context.Products join cat in context.Categories on prd.CatId equals cat.CategoryId select new ProductViewModel { ProductId = prd.ProductId, Name = prd.Name, Description = prd.Description, CreatedDate = prd.CreatedDate, UnitPrice = prd.UnitPrice, Category = cat.Name }).ToList(); return products; } } }
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 CIS016_2.Week1 { public partial class ScrollbarsForm : Form { public ScrollbarsForm() { InitializeComponent(); } private void hScrollBar_Scroll(object sender, ScrollEventArgs e) { var red = hsbRed.Value; var green = hsbGreen.Value; var blue = hsbBlue.Value; pBox.BackColor = Color.FromArgb(red, green, blue); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Windows.Forms; using System.Data; using System.Xml; namespace BridgeProject { static public class DB { static public System.Data.SqlServerCe.SqlCeConnection sqlConnection = null; static public String connectionString = ""; static public void InitializeConnectionString(string path, string temp_dir) { connectionString = ("Data Source='" + path + "'") + (temp_dir.Length == 0 ? "" : ("; Temp File Directory='" + temp_dir + "'")); } static public bool CreateDatabase(string path) { System.Data.SqlServerCe.SqlCeEngine dbEngine = new System.Data.SqlServerCe.SqlCeEngine("Data Source='" + path + "'"); try { dbEngine.CreateDatabase(); return true; } catch (System.Data.SqlServerCe.SqlCeException e) { // error #25114 - База уже есть MessageBox.Show(e.Message, "db error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return false; } finally { dbEngine.Dispose(); } } static public void ReConnect() { if (sqlConnection == null) { sqlConnection = new System.Data.SqlServerCe.SqlCeConnection(connectionString); sqlConnection.Open(); } if (sqlConnection.State == ConnectionState.Closed) { sqlConnection.Open(); } else if (sqlConnection.State == ConnectionState.Broken) { sqlConnection.Close(); sqlConnection.Open(); } } static public void Disconnect() { if (sqlConnection != null) { sqlConnection.Close(); } } static public System.Data.SqlServerCe.SqlCeCommand CreateQuery() { ReConnect(); return sqlConnection.CreateCommand(); } static public void SafeTransRollback(System.Data.SqlServerCe.SqlCeTransaction trans) { try { trans.Rollback(); } catch (System.InvalidOperationException) { } } static public int GetLastInsertId(System.Data.SqlServerCe.SqlCeTransaction trans) { System.Data.SqlServerCe.SqlCeCommand sqlQuery = CreateQuery(); sqlQuery.CommandText = "SELECT @@IDENTITY"; if (trans != null) { sqlQuery.Transaction = trans; } object o = ExecuteScalar(sqlQuery); if (o == null || o == DBNull.Value) { return -1; } else { return (int)(decimal)o; } } static public int GetLastInsertId() { return GetLastInsertId(null); } static public System.Data.SqlServerCe.SqlCeDataReader ExecuteReader(System.Data.SqlServerCe.SqlCeCommand command) { bool retry = false; try { return command.ExecuteReader(); } catch (System.Data.SqlServerCe.SqlCeException ex) { if (ex.NativeError == 0) { retry = true; } else { throw; } } if (retry) { command.Connection.Close(); command.Connection.Open(); return command.ExecuteReader(); } else return null; } static public object ExecuteScalar(System.Data.SqlServerCe.SqlCeCommand command) { bool retry = false; try { return command.ExecuteScalar(); } catch (System.Data.SqlServerCe.SqlCeException ex) { if (ex.NativeError == 0) { retry = true; } else { throw; } } if (retry) { command.Connection.Close(); command.Connection.Open(); return command.ExecuteScalar(); } else return null; } static private int ExecuteNonQuery(System.Data.SqlServerCe.SqlCeCommand command, bool useTransaction, out int out__rowid, bool findoutLastInsertId) { bool retry = false; bool trans_started = false; System.Data.SqlServerCe.SqlCeTransaction trans = null; try { if (useTransaction) { trans = command.Connection.BeginTransaction(); trans_started = true; command.Transaction = trans; } int rows_aff = command.ExecuteNonQuery(); int row_id = -1; if (findoutLastInsertId) { if (useTransaction) row_id = GetLastInsertId(trans); else row_id = GetLastInsertId(); } if (useTransaction) { trans.Commit(System.Data.SqlServerCe.CommitMode.Immediate); trans_started = false; command.Transaction = null; } out__rowid = row_id; return rows_aff; } catch (System.Data.SqlServerCe.SqlCeException ex) { ////////MessageBox.Show(ex.Message + "\n" + "HRES = " + ex.HResult + "\n" + "ERRNO = " + ex.NativeError); if (useTransaction && trans_started) { SafeTransRollback(trans); trans.Dispose(); trans = null; command.Transaction = null; trans_started = false; } if (ex.NativeError == 0) { retry = true; } else { throw; } } if (retry) { command.Connection.Close(); command.Connection.Open(); if (useTransaction) { trans = command.Connection.BeginTransaction(); trans_started = true; command.Transaction = trans; } int rows_aff = command.ExecuteNonQuery(); int row_id = -1; if (findoutLastInsertId) { if (useTransaction) row_id = GetLastInsertId(trans); else row_id = GetLastInsertId(); } if (useTransaction) { trans.Commit(System.Data.SqlServerCe.CommitMode.Immediate); trans_started = false; command.Transaction = null; } out__rowid = row_id; return rows_aff; } else { out__rowid = -1; return 0; } } static public int ExecuteNonQuery(System.Data.SqlServerCe.SqlCeCommand command, bool useTransaction) { int fake; return ExecuteNonQuery(command, useTransaction, out fake, false); } static public int ExecuteNonQuery(System.Data.SqlServerCe.SqlCeCommand command, bool useTransaction, out int out__rowid) { return ExecuteNonQuery(command, useTransaction, out out__rowid, true); } //-------------------------------------------------------- create/modify db 'bridge' --------------------------------- /*static public bool CreateBridgeDB() { System.Data.SqlServerCe.SqlCeCommand sqlQuery = CreateQuery(); sqlQuery.CommandText = "CREATE DATABASE Bridge"; try { sqlQuery.ExecuteNonQuery(); return true; } catch (System.Data.SqlServerCe.SqlCeException e) { // error #25114 - База уже есть MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return false; } }*/ static public bool CreateTables(bool use_trans) { System.Data.SqlServerCe.SqlCeCommand sqlQuery = CreateQuery(); System.Data.SqlServerCe.SqlCeTransaction trans = null; if (use_trans) { trans = sqlConnection.BeginTransaction(); sqlQuery.Transaction = trans; } sqlQuery.CommandText = "CREATE TABLE Folders (id INT IDENTITY PRIMARY KEY, Name NVARCHAR(30))"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } /*sqlQuery.CommandText = "alter table folders alter column Name nvarchar(30)"; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "alter table players alter column Name nvarchar(50)"; sqlQuery.ExecuteNonQuery();*/ sqlQuery.CommandText = "CREATE TABLE Players (id INT IDENTITY PRIMARY KEY, Name NVARCHAR(50))"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "CREATE TABLE Games (id INT IDENTITY PRIMARY KEY, Type TINYINT NOT NULL, GameOptions TINYINT, DealsInMatch TINYINT, FirstDealer TINYINT, ZoneSwims BIT, fk_Folder_id INT, CONSTRAINT FK__Games__no1__Folders__id FOREIGN KEY(fk_Folder_id) REFERENCES Folders(id), fk_N INT, CONSTRAINT FK__Games__N__Players__id FOREIGN KEY(fk_N) REFERENCES Players(id), fk_S INT, CONSTRAINT FK__Games__S__Players__id FOREIGN KEY(fk_S) REFERENCES Players(id), fk_E INT, CONSTRAINT FK__Games__E__Players__id FOREIGN KEY(fk_E) REFERENCES Players(id), fk_W INT, CONSTRAINT FK__Games__W__Players__id FOREIGN KEY(fk_W) REFERENCES Players(id), Place NVARCHAR(30), Comment NVARCHAR(60), StartDate DATETIME)"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "CREATE TABLE Matches (id INT IDENTITY PRIMARY KEY, fk_Game_id INT, CONSTRAINT FK__Matches__no1__Games__id FOREIGN KEY(fk_Game_id) REFERENCES Games(id) ON UPDATE CASCADE ON DELETE CASCADE, SCORE_NS INT, SCORE_EW INT)"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "CREATE TABLE Deals_Rob (id INT IDENTITY PRIMARY KEY, fk_Match_id INT, CONSTRAINT FK__Deals_Rob__no1__Matches__id FOREIGN KEY(fk_Match_id) REFERENCES Matches(id) ON UPDATE CASCADE ON DELETE CASCADE, Pair BIT, Contract TINYINT, Oners TINYINT, Result TINYINT, CardsDistribution BINARY(20))"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "CREATE TABLE Deals_Sport (id INT IDENTITY PRIMARY KEY, fk_Match_id INT, CONSTRAINT FK__Deals_Sport__no1__Matches__id FOREIGN KEY(fk_Match_id) REFERENCES Matches(id) ON UPDATE CASCADE ON DELETE CASCADE, Pair BIT, Contract TINYINT, Result TINYINT, CardsDistribution BINARY(20), Figures TINYINT, Fits TINYINT, StrongestPair BIT)"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "CREATE TABLE Deals_Double (id INT IDENTITY PRIMARY KEY, fk_Match_id INT, CONSTRAINT FK__Deals_Double__no1__Matches__id FOREIGN KEY(fk_Match_id) REFERENCES Matches(id) ON UPDATE CASCADE ON DELETE CASCADE, CardsDistribution BINARY(20), Pair1 BIT, Contract1 TINYINT, Result1 TINYINT, Pair2 BIT, Contract2 TINYINT, Result2 TINYINT, IsSecondStarted BIT)"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } if (use_trans) { try { trans.Commit(System.Data.SqlServerCe.CommitMode.Immediate); return true; } catch (System.Data.SqlServerCe.SqlCeException e) { SafeTransRollback(trans); MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return false; } } else { return true; } } static public void ModifyTable() { System.Data.SqlServerCe.SqlCeCommand sqlQuery = CreateQuery(); System.Data.SqlServerCe.SqlCeDataReader dr; //--------- total score sqlQuery.CommandText = "ALTER TABLE Matches ADD SCORE_NS INT, SCORE_EW INT"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } //----------- on delete/update для констраинтов матчей и сдач sqlQuery.CommandText = "select CONSTRAINT_NAME from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS where (CONSTRAINT_TABLE_NAME = 'Matches' AND UNIQUE_CONSTRAINT_TABLE_NAME = 'Games')"; object o = sqlQuery.ExecuteScalar(); if (o != null && o != DBNull.Value) { sqlQuery.CommandText = "ALTER TABLE Matches DROP CONSTRAINT " + o; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Matches ADD FOREIGN KEY(fk_Game_id) REFERENCES Games(id) ON UPDATE CASCADE ON DELETE CASCADE"; sqlQuery.ExecuteNonQuery(); } sqlQuery.CommandText = "select CONSTRAINT_NAME from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS where (CONSTRAINT_TABLE_NAME = 'Deals_Rob' AND UNIQUE_CONSTRAINT_TABLE_NAME = 'Matches')"; o = sqlQuery.ExecuteScalar(); if (o != null && o != DBNull.Value) { sqlQuery.CommandText = "ALTER TABLE Deals_Rob DROP CONSTRAINT " + o; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Deals_Rob ADD FOREIGN KEY(fk_Match_id) REFERENCES Matches(id) ON UPDATE CASCADE ON DELETE CASCADE"; sqlQuery.ExecuteNonQuery(); } sqlQuery.CommandText = "select CONSTRAINT_NAME from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS where (CONSTRAINT_TABLE_NAME = 'Deals_Sport' AND UNIQUE_CONSTRAINT_TABLE_NAME = 'Matches')"; o = sqlQuery.ExecuteScalar(); if (o != null && o != DBNull.Value) { sqlQuery.CommandText = "ALTER TABLE Deals_Sport DROP CONSTRAINT " + o; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Deals_Sport ADD FOREIGN KEY(fk_Match_id) REFERENCES Matches(id) ON UPDATE CASCADE ON DELETE CASCADE"; sqlQuery.ExecuteNonQuery(); } sqlQuery.CommandText = "select CONSTRAINT_NAME from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS where (CONSTRAINT_TABLE_NAME = 'Deals_Double' AND UNIQUE_CONSTRAINT_TABLE_NAME = 'Matches')"; o = sqlQuery.ExecuteScalar(); if (o != null && o != DBNull.Value) { sqlQuery.CommandText = "ALTER TABLE Deals_Double DROP CONSTRAINT " + o; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Deals_Double ADD FOREIGN KEY(fk_Match_id) REFERENCES Matches(id) ON UPDATE CASCADE ON DELETE CASCADE"; sqlQuery.ExecuteNonQuery(); } //------------- удалить констраинты из Games sqlQuery.CommandText = "select CONSTRAINT_NAME from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS where (CONSTRAINT_TABLE_NAME = 'Games' AND UNIQUE_CONSTRAINT_TABLE_NAME = 'Folders')"; dr = sqlQuery.ExecuteReader(); while (dr.Read()) { if (!dr.IsDBNull(0)) { sqlQuery.CommandText = "ALTER TABLE Games DROP CONSTRAINT " + dr.GetString(0); sqlQuery.ExecuteNonQuery(); } } dr.Close(); //----------- folder sqlQuery.CommandText = "ALTER TABLE Games ADD fk_Folder_id INT"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "ALTER TABLE Games ADD FOREIGN KEY(fk_Folder_id) REFERENCES Folders(id)"; sqlQuery.ExecuteNonQuery(); //----------- n s e w sqlQuery.CommandText = "ALTER TABLE Games ADD fk_N INT, fk_S INT, fk_E INT, fk_W INT"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } sqlQuery.CommandText = "ALTER TABLE Games ADD FOREIGN KEY(fk_N) REFERENCES Players(id), FOREIGN KEY(fk_S) REFERENCES Players(id), FOREIGN KEY(fk_E) REFERENCES Players(id), FOREIGN KEY(fk_W) REFERENCES Players(id)"; sqlQuery.ExecuteNonQuery(); //---------- place & comment & sdate /*sqlQuery.CommandText = "ALTER TABLE Games DROP COLUMN Place"; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Games DROP COLUMN Comment"; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Games DROP COLUMN StartDate"; sqlQuery.ExecuteNonQuery();*/ sqlQuery.CommandText = "ALTER TABLE Games ADD Place NVARCHAR(30), Comment NVARCHAR(60), StartDate DATETIME"; try { sqlQuery.ExecuteNonQuery(); } catch (System.Data.SqlServerCe.SqlCeException e) { MessageBox.Show(e.Message, "Error #" + e.NativeError, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } //--------- cd if (MessageBox.Show("Изменить формат для распределения колоды?\nЭто удалит все сущ. колоды!", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { sqlQuery.CommandText = "ALTER TABLE Deals_Sport DROP COLUMN CardsDistribution"; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "ALTER TABLE Deals_Sport ADD CardsDistribution BINARY(20)"; sqlQuery.ExecuteNonQuery(); } /*sqlQuery.CommandText = "insert into folders (Name) values('тест')"; sqlQuery.ExecuteNonQuery(); sqlQuery.CommandText = "insert into folders (Name) values('ааа')"; sqlQuery.ExecuteNonQuery(); */ /*** справка по constaints *** sqlQuery.CommandText = "select * from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS"; dr = sqlQuery.ExecuteReader(); while (dr.Read()) { //dr.Read(); string s = ""; for (int i = 0; i < dr.FieldCount; i++) s += i + ">" + dr.GetName(i) + " ^ " + dr.GetValue(i).ToString() + "\n"; //MessageBox.Show(dr.GetName(i)); MessageBox.Show(s); } dr.Close(); */ } // ----------- Функции ------------- public static int DB_GetMaxLength(string table, string column) { System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "select DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='" + table + "' and COLUMN_NAME='" + column + "'"; System.Data.SqlServerCe.SqlCeDataReader sqlReader = ExecuteReader(sqlQuery); int len = 0; if (sqlReader.Read()) len = (int)sqlReader.GetSqlInt32(sqlReader.GetOrdinal("CHARACTER_MAXIMUM_LENGTH")); sqlReader.Close(); return len; } public static string DB_GetCuttedString(string str, string table, string column) { int column_len = DB_GetMaxLength(table, column); return (column_len != 0 && str.Length > column_len ? str.Substring(0, column_len) : str); } public static int DB_GetAttributeId(int selected_id, string selected_name, string table, string column_id, string column_name) { if (selected_id != -1) { return selected_id; } else { if (selected_name.Length == 0) { return -1; //т.е. NULL } else { string selected_name__cut = DB_GetCuttedString(selected_name, table, column_name); System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT " + column_id + " FROM " + table + " WHERE " + column_name + "='" + selected_name__cut + "'"; object o = ExecuteScalar(sqlQuery); if (o != null && o != DBNull.Value) { return (int)o; } else { sqlQuery.CommandText = "INSERT INTO " + table + "(" + column_name + ") VALUES('" + selected_name__cut + "')"; int inserted_id; ExecuteNonQuery(sqlQuery, true, out inserted_id); return inserted_id; } } } } } static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [MTAThread] static void Main() { String strExePath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName; ExeDir = strExePath.Substring(0, strExePath.LastIndexOf('\\') + 1); //ContractSelector.LoadGraphicsResources(); //ContractSelector.SetCoordinates(); // ------------------ start: XML ------------------ if (System.IO.File.Exists(Program.ExeDir + "BridgeNote.xml") == false) { MessageBox.Show("Не найден файл BridgeNote.xml!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } String strDBPath = ""; String strTempDir = ""; String strDBPath_final = ""; String strTempDir_final = ""; bool absDBPath = true; bool absTempDir = true; bool useTempDir = false; XmlReaderSettings xml_settings = new XmlReaderSettings(); xml_settings.ConformanceLevel = ConformanceLevel.Fragment; xml_settings.IgnoreWhitespace = true; xml_settings.IgnoreComments = true; XmlParserContext xml_context = new XmlParserContext(null, null, null, XmlSpace.Default, System.Text.Encoding.Default); XmlReader xml_reader = null; try { xml_reader = XmlReader.Create(Program.ExeDir + "BridgeNote.xml", xml_settings, xml_context); xml_reader.Read(); xml_reader.ReadStartElement("Settings"); xml_reader.ReadStartElement("Database"); if (xml_reader.IsStartElement("File")) { strDBPath = xml_reader.GetAttribute("path"); if (strDBPath == null || strDBPath.Length == 0) { xml_reader.Close(); MessageBox.Show("Не указан путь к файлу БД!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } try { absDBPath = bool.Parse(xml_reader.GetAttribute("absolute")); } catch (Exception e) { xml_reader.Close(); MessageBox.Show("Ошибка в Settings.Database.File.absolute:\n" + e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } } else { xml_reader.Close(); MessageBox.Show("Не найден тег File!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } xml_reader.Skip(); if (xml_reader.IsStartElement("TempDir")) { try { useTempDir = bool.Parse(xml_reader.GetAttribute("use")); } catch (Exception e) { xml_reader.Close(); MessageBox.Show("Ошибка в Settings.Database.TempDir.use:\n" + e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } try { absTempDir = bool.Parse(xml_reader.GetAttribute("absolute")); } catch (Exception e) { xml_reader.Close(); MessageBox.Show("Ошибка в Settings.Database.TempDir.absolute:\n" + e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } strTempDir = xml_reader.GetAttribute("path"); if (useTempDir && (strTempDir == null || absTempDir && strTempDir.Length == 0)) { xml_reader.Close(); MessageBox.Show("Не указана временная папка для БД!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } } else { xml_reader.Close(); MessageBox.Show("Не найден тег TempDir!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } xml_reader.Skip(); xml_reader.ReadEndElement(); xml_reader.ReadEndElement(); } catch(XmlException e) { if (xml_reader != null) xml_reader.Close(); MessageBox.Show(e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } xml_reader.Close(); // ------------------ end: XML ------------------ strDBPath_final = (absDBPath ? strDBPath : (Program.ExeDir + strDBPath)); strTempDir_final = (useTempDir ? (absTempDir ? strTempDir : (Program.ExeDir + strTempDir)) : ""); // Проверить временную папку if (useTempDir && System.IO.Directory.Exists(strTempDir_final) == false) { MessageBox.Show("Неправильно указана временная папка для БД!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } // Инициализировать строку подключения DB.InitializeConnectionString(strDBPath_final, strTempDir_final); // Создать БД, если нужно if (System.IO.File.Exists(strDBPath_final) == false) { if (MessageBox.Show("База данных не найдена!\nСоздать новую БД и проинициализировать ее?", "db create", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { if (DB.CreateDatabase(strDBPath_final) == false) { return; } DB.CreateTables(false); DB.Disconnect(); } else { return; } } // Подключиться к базе данных DB.ReConnect(); // Следить за подключением DB.sqlConnection.StateChange += new StateChangeEventHandler(sqlConnection_StateChange); // Запуск главной формы, большой try-catch если DEBUG #if DEBUG try { Application.Run(MainForm = new Form1()); } catch (Exception e) { System.IO.StreamWriter sw = System.IO.File.AppendText(Program.ExeDir + "debug.txt"); sw.Write(DateTime.Now.ToString() + "\n"); sw.Write(e.Message + "\n"); sw.Write(e.StackTrace + "\n"); if (e.GetType() == typeof(System.Data.SqlServerCe.SqlCeException)) { System.Data.SqlServerCe.SqlCeException ex = (System.Data.SqlServerCe.SqlCeException) e; sw.Write("[SQL] NativeError = " + ex.NativeError + "\n"); for (int i = 0; i < ex.Errors.Count; i++) { sw.Write("[SQL_err_" + i + "] " + ex.Errors[i].Message + " * " + ex.Errors[i].NativeError + "\n"); } } sw.Write("-------------" + "\n"); sw.Close(); throw; } #else Application.Run(MainForm = new Form1()); #endif } static void sqlConnection_StateChange(object sender, StateChangeEventArgs e) { if (MainForm != null) { switch (e.CurrentState) { case ConnectionState.Open: MainForm.Text = "BridgeNote"; break; case ConnectionState.Closed: MainForm.Text = "BridgeNote (c)"; break; case ConnectionState.Broken: MainForm.Text = "BridgeNote (b)"; break; } } } public static Form MainForm; public static String ExeDir; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InventoryManager.Data.Models { public class Clothes { [Key] public int Id { get; set; } [StringLength(30, MinimumLength = 2, ErrorMessage = "The name of the merchandise must be between 2 and 30 symbols long")] public string Name { get; set; } [StringLength(30, MinimumLength = 2, ErrorMessage = "The type of the merchandise must be between 2 and 30 symbols long")] public string Type { get; set; } [Range(0, int.MaxValue, ErrorMessage = "Thq quantity of the merchandise must be 0 or higher")] public int Quantity { get; set; } [StringLength(30, MinimumLength = 2, ErrorMessage = "The name of the merchandise must be between 2 and 30 symbols long")] public string Size { get; set; } [Range(0.0, double.MaxValue, ErrorMessage = "The Price of the merchandise must be higher than 0.0")] public decimal SinglePrice { get; set; } public string PictureUrl { get; set; } [StringLength(100, MinimumLength = 2, ErrorMessage = "The description of the merchandise must be between 2 and 100 symbols long")] public string Description { get; set; } } }
using Euler_Logic.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem211 : ProblemBase { private PrimeSieve _primes; private Dictionary<ulong, Dictionary<int, ulong>> _powerSums = new Dictionary<ulong, Dictionary<int, ulong>>(); /* The sum of the divisors of a number (n) can be quickly calculated by multiplying the sum of the powers of its prime factors. For example, if (n) = 12, then the prime factors are 2^2 * 3^1. The sum of the powers would be: (1+2+4) * (1 + 3) = 28. However, since we are looking for the squares of the divisors, that can be calculated (1^2+2^2+4^4) * (1^2+3^2) = 210. So I simply find the prime factors of all (n) up to 64,000,000 and calculate the sum of the squares of its divisor using the above method, and sum each (n) where the result is a perfect square. */ public override string ProblemName { get { return "211: Divisor Square Sum"; } } public override string GetAnswer() { ulong max = 64000000; _primes = new PrimeSieve(max); return Solve(max).ToString(); } private ulong Solve(ulong max) { ulong sum = 1; for (ulong num = 2; num < max; num++) { var divisorSum = CalcDivisorSum(num); var root = (ulong)Math.Sqrt(divisorSum); if (root * root == divisorSum) { sum += num; } } return sum; } private ulong CalcDivisorSum(ulong num) { ulong sum = 1; if (_primes.IsPrime(num)) { return num * num + 1; } foreach (var prime in _primes.Enumerate) { if (num % prime == 0) { int count = 0; do { num /= prime; count++; } while (num % prime == 0); sum *= GetPowerSum(prime, count); if (_primes.IsPrime(num)) { sum *= (1 + (num * num)); break; } else if (num == 1) { break; } } } return sum; } private ulong GetPowerSum(ulong prime, int power) { if (!_powerSums.ContainsKey(prime)) { _powerSums.Add(prime, new Dictionary<int, ulong>()); } if (!_powerSums[prime].ContainsKey(power)) { ulong num = 1; ulong sum = 1; for (int count = 1; count <= power; count++) { num *= prime; sum += num * num; } _powerSums[prime].Add(power, sum); } return _powerSums[prime][power]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using JustRipeFarm.ClassEntity; namespace JustRipeFarm { public class JobOp { public static int GetJobCountFor(bool isToday, string tableName) { string condition = isToday ? "=" : ">"; DateTime now = DateTime.Now; string date = now.ToString("yyyyMMdd"); List<int> datesRead = new List<int>(); MySqlDataReader rdr = null; try { string query = "SELECT * FROM `"+ tableName + "` WHERE " + tableName + ".date_start "+ condition + " CURRENT_DATE"; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); Console.WriteLine("get job => read in "+date); while (rdr.Read()) { int id = rdr.GetInt32("id"); DateTime dd = rdr.GetDateTime("date_start"); Console.WriteLine("get job => " + id + " => " + dd); datesRead.Add(id); } Console.WriteLine("get job => read out"); return datesRead.Count(); } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return 0; } public static int GetJobCountFor(bool isToday, string tableName, int employeeID) { string condition = isToday ? "=" : ">"; DateTime now = DateTime.Now; string date = now.ToString("yyyyMMdd"); List<int> datesRead = new List<int>(); MySqlDataReader rdr = null; try { string query = "SELECT * FROM `" + tableName + "` WHERE " + tableName + ".date_start " + condition + " CURRENT_DATE AND "+tableName+".employee_id = "+employeeID; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); Console.WriteLine("get job => read in " + date); while (rdr.Read()) { int id = rdr.GetInt32("id"); DateTime dd = rdr.GetDateTime("date_start"); Console.WriteLine("get job => " + id + " => " + dd); datesRead.Add(id); } Console.WriteLine("get job => read out"); return datesRead.Count(); } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return 0; } public static List<string> getOrderList() { Order order = new Order(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "orders"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { order.Description = rdr.GetString("description"); flist.Add(order.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getProductList() { Product prod = new Product(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "product"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { prod.Name = rdr.GetString("name"); flist.Add(prod.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getSowingJobList() { SowingJob sowing = new SowingJob(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "sowingjob"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { sowing.Description = rdr.GetString("description"); flist.Add(sowing.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getHarvestingJobList() { HarvestingJob harvesting = new HarvestingJob(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "harvestingjob"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { harvesting.Description = rdr.GetString("description"); flist.Add(harvesting.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getStoringJobList() { StoringJob storing = new StoringJob(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "storingjob"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { storing.Description = rdr.GetString("description"); flist.Add(storing.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getFertilisingList() { FertilisingJob fertilising = new FertilisingJob(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "fertilisingjob"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { fertilising.Description = rdr.GetString("description"); flist.Add(fertilising.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getPesticideJobList() { PesticideJob pest = new PesticideJob(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "pesticidejob"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { pest.Description = rdr.GetString("description"); flist.Add(pest.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getFarmList() { Farm farm = new Farm(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "farm"; string query = "SELECT * FROM " + tableName ; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { farm.Description = rdr.GetString("description"); flist.Add(farm.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getEmployeeList() { Employee employee = new Employee(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "employee"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { employee.First_name = rdr.GetString("first_name"); flist.Add(employee.First_name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getCustomerList() { Customer customer = new Customer(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "customer"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { customer.Name = rdr.GetString("name"); flist.Add(customer.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getStoreroomList() { Storeroom storeroom = new Storeroom(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "storeroom"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { storeroom.Description = rdr.GetString("description"); flist.Add(storeroom.Description); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getVehicleList() { Vehicle vehicle = new Vehicle(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "vehicle"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { vehicle.Name = rdr.GetString("name"); flist.Add(vehicle.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getCropList() { Crop crop = new Crop(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "crop"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { crop.Name = rdr.GetString("name"); flist.Add(crop.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getFertiliserList() { Fertiliser fertiliser = new Fertiliser(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "fertiliser"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { fertiliser.Name = rdr.GetString("name"); flist.Add(fertiliser.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getPesticideList() { Pesticide pesticide = new Pesticide(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "pesticide"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { pesticide.Name = rdr.GetString("name"); flist.Add(pesticide.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static List<string> getBoxList() { Box box = new Box(); List<string> flist = new List<string>(); MySqlDataReader rdr = null; try { string tableName = "box"; string query = "SELECT * FROM " + tableName; MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { box.Name = rdr.GetString("name"); flist.Add(box.Name); } } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return flist; } public static int GetAllJobCountFor(bool isToday,int employeeID) { int jobs = GetJobCountFor(isToday, "sowingjob", employeeID); jobs += GetJobCountFor(isToday, "harvestingjob", employeeID); jobs += GetJobCountFor(isToday, "storingjob", employeeID); jobs += GetJobCountFor(isToday, "fertilisingjob", employeeID); jobs += GetJobCountFor(isToday, "pesticidejob", employeeID); return jobs; } public static int GetAllJobCountFor(bool isToday) { int jobs = GetJobCountFor(isToday, "sowingjob"); jobs += GetJobCountFor(isToday, "harvestingjob"); jobs += GetJobCountFor(isToday, "storingjob"); jobs += GetJobCountFor(isToday, "fertilisingjob"); jobs += GetJobCountFor(isToday, "pesticidejob"); return jobs; } public static int GetOrderCountFor(string tableName) { List<int> ids = new List<int>(); MySqlDataReader rdr = null; try { string query = "SELECT * FROM `" + tableName + "` WHERE " + tableName + ".status <> 'Completed'"; Console.WriteLine("get order => read in"); MySqlCommand cmd = new MySqlCommand(query, MysqlDbc.Instance.getConn()); rdr = cmd.ExecuteReader(); while (rdr.Read()) { int id = rdr.GetInt32("id"); Console.WriteLine("get order => " + id + " <= "); ids.Add(id); } Console.WriteLine("get order => read out"); return ids.Count(); } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } } return 0; } public static int updateFieldStr(String tableName, int rowId, string field, string updateItem) { Console.WriteLine("updateFieldStr in"); MySqlCommand sqlComm = new MySqlCommand("UPDATE " +tableName+" SET "+field+" = "+updateItem+" WHERE id = "+rowId+" ", MysqlDbc.Instance.getConn()); Console.WriteLine("updateFieldStr out"); return sqlComm.ExecuteNonQuery(); } public static int UpdateOrder(int rowId,string status) { string query = "UPDATE orders SET status = @status " + "WHERE id = " + rowId; MySqlCommand sqlComm = new MySqlCommand(query, MysqlDbc.Instance.getConn()); sqlComm.Parameters.Add("@status", MySqlDbType.Text).Value = status; return sqlComm.ExecuteNonQuery(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameActionManager : MonoBehaviour { // Singleton // public static GameActionManager instance { get; protected set;} void Awake () { if (instance == null) { instance = this; } else if (instance != this) { Destroy (gameObject); } } // Singleton // public TileInteraction currentTileInteraction; // Use this for initialization public void Initialize () { EventsHandler.cb_spacebarPressed += OnSpacebarPressed; EventsHandler.cb_escapePressed += OnEscapePressed; EventsHandler.cb_playerHitTileInteraction += OnHitTileInteraction; EventsHandler.cb_playerLeaveTileInteraction += OnLeaveTileInteraction; EventsHandler.cb_inputStateChanged += ManageInputState; } public void OnDestroy() { EventsHandler.cb_spacebarPressed -= OnSpacebarPressed; EventsHandler.cb_escapePressed -= OnEscapePressed; EventsHandler.cb_playerHitTileInteraction -= OnHitTileInteraction; EventsHandler.cb_playerLeaveTileInteraction -= OnLeaveTileInteraction; EventsHandler.cb_inputStateChanged -= ManageInputState; } // Update is called once per frame void Update () { } // SPACEBAR PRESSED // public void OnSpacebarPressed () { switch (GameManager.instance.inputState) { case InputState.ActionBox: // If there is already an actionbox, activate interaction if (ActionBoxManager.instance.currentActionBox != null) { ActionBoxManager.instance.ActivateInteraction (); return; } break; case InputState.Inventory: switch (GameManager.userData.GetCurrentPlayerData().inventory.myState) { case InventoryState.UseItem: InventoryUI.instance.SelectItemToUse (); break; case InventoryState.Browse: InventoryUI.instance.ActivateInteraction (); break; case InventoryState.Combine: InventoryUI.instance.CombineItems (); break; } return; //case InputState.Cutscene: case InputState.DialogueBox: if (DialogueManager.instance.currentDialogueOption != null) { DialogueManager.instance.ActivateDialogueOption (); return; } break; case InputState.Character: // if there's no action box, create one if (ActionBoxManager.instance.currentPhysicalInteractable != null) { ActionBoxManager.instance.OpenActionBox (); } break; } } public void OnEscapePressed() { if (GameManager.instance.inputState == InputState.Inventory) { InventoryUI.instance.CloseInventory(); return; } if (GameManager.instance.inputState == InputState.Settings) { SettingsUI.instance.CloseSettings(); return; } if (GameManager.instance.inputState == InputState.Map) { MapUI.instance.CloseMap(); return; } ActionBoxManager.instance.CloseActionBox (); } // manage input stat public void ManageInputState() { if (NavigationManager.navigationInProcess == true) { GameManager.instance.inputState = InputState.NoInput; return; } if (CutsceneManager.inCutscene == true) { GameManager.instance.inputState = InputState.Cutscene; return; } if (GameManager.actionBoxActive == true) { GameManager.instance.inputState = InputState.ActionBox; return; } if (GameManager.dialogueTreeBoxActive == true) { if (DialogueManager.instance.dialogueTreeObject.gameObject.active == true) { GameManager.instance.inputState = InputState.DialogueBox; } else { GameManager.instance.inputState = InputState.Dialogue; } return; } if (GameManager.textBoxActive == true) { GameManager.instance.inputState = InputState.Dialogue; return; } if (GameManager.inventoryOpen == true) { GameManager.instance.inputState = InputState.Inventory; return; } if (GameManager.settingsOpen == true) { GameManager.instance.inputState = InputState.Settings; return; } if (GameManager.mapOpen == true) { GameManager.instance.inputState = InputState.Map; return; } GameManager.instance.inputState = InputState.Character; } // Tile Interaction // public void OnHitTileInteraction(Tile tile) { TileInteraction tileInt = tile.myTileInteraction; if (currentTileInteraction != tileInt) { currentTileInteraction = tileInt; if (currentTileInteraction != null) { // Check if passed the conditions if (Utilities.EvaluateConditions (tileInt.mySubInt.ConditionList)) { tileInt.mySubInt.SubInteract (); } } } } public void OnLeaveTileInteraction () { currentTileInteraction = null; } }
using System.IO; using SharpDox.Plugins.Chm.Templates; using SharpDox.Plugins.Chm.Templates.Sites; using SharpDox.Plugins.Chm.Templates.Nav; using System.Collections.Generic; using System.Linq; using SharpDox.UML; using SharpDox.Model.Documentation.Article; namespace SharpDox.Plugins.Chm.Steps { internal class TemplateStep : StepBase { public TemplateStep(int progressStart, int progressEnd) : base(new StepRange(progressStart, progressEnd)) { } public override void RunStep() { CreateStylesheet(); CreateTocFile(); CreateProjectFile(); CreateArticleFiles(); CreateIndexFile(); CreateApiIndexFiles(); CreateTypeFiles(); } private void CreateStylesheet() { ExecuteOnStepMessage(StepInput.ChmStrings.CreateStylesheet); var styleSheetFile = Path.Combine(StepInput.TmpPath, "css", "style.css"); var template = new StylesheetTemplate(); File.WriteAllText(styleSheetFile, template.TransformText()); } private void CreateTocFile() { ExecuteOnStepMessage(StepInput.ChmStrings.CreateToc); var tocHtmlFile = Path.Combine(StepInput.TmpPath, StepInput.SDProject.ProjectName.Replace(" ", "") + ".hhc"); var template = new HhcTemplate(); File.WriteAllText(tocHtmlFile, template.TransformText()); } private void CreateProjectFile() { ExecuteOnStepMessage(StepInput.ChmStrings.CreateProject); var projectFile = Path.Combine(StepInput.TmpPath, StepInput.SDProject.ProjectName.Replace(" ", "") + ".hhp"); var template = new HhpTemplate(); File.WriteAllText(projectFile, template.TransformText()); } private void CreateArticleFiles() { ExecuteOnStepMessage(StepInput.ChmStrings.CreateArticles); if (StepInput.SDProject.Articles.Count > 0) { var articles = StepInput.SDProject.Articles.ContainsKey(StepInput.CurrentLanguage) ? StepInput.SDProject.Articles[StepInput.CurrentLanguage] : StepInput.SDProject.Articles["default"]; CreateArticles(articles); } } private void CreateArticles(IEnumerable<SDArticle> articles) { foreach (var article in articles) { var articleHtmlFile = Path.Combine(StepInput.TmpPath, Helper.RemoveIllegalCharacters(article.Title.Replace(" ", "_")) + ".html"); var template = new ArticleTemplate { SDArticle = article }; File.WriteAllText(articleHtmlFile, template.TransformText()); CreateArticles(article.Children); } } private void CreateIndexFile() { ExecuteOnStepMessage(StepInput.ChmStrings.CreateIndex); var indexHtmlFile = Path.Combine(StepInput.TmpPath, StepInput.SDProject.ProjectName.Replace(" ", "") + "-Index.html"); var template = new IndexTemplate(); File.WriteAllText(indexHtmlFile, template.TransformText()); } private void CreateApiIndexFiles() { foreach(var solution in StepInput.SDProject.Solutions.Values) { var sdRepository = solution.Repositories.SingleOrDefault(r => r.TargetFx.Identifier == StepInput.CurrentTargetFx.Identifier); if(sdRepository != null) { foreach (var sdNamespace in sdRepository.GetAllNamespaces()) { ExecuteOnStepMessage(string.Format("{0}: {1}", StepInput.ChmStrings.CreateIndexFilesFor, sdNamespace.Fullname)); var namespaceHtmlFile = Path.Combine(StepInput.TmpPath, sdNamespace.Guid + ".html"); var template = new NamespaceTemplate { SDNamespace = sdNamespace }; File.WriteAllText(namespaceHtmlFile, template.TransformText()); foreach (var sdType in sdNamespace.Types) { var fieldsIndexHtmlFile = Path.Combine(StepInput.TmpPath, sdType.Guid + "-Fields.html"); var fieldsTemplate = new FieldsTemplate { SDType = sdType }; File.WriteAllText(fieldsIndexHtmlFile, fieldsTemplate.TransformText()); var eveIndexHtmlFile = Path.Combine(StepInput.TmpPath, sdType.Guid + "-Events.html"); var eventsTemplate = new EventsTemplate { SDType = sdType }; File.WriteAllText(eveIndexHtmlFile, eventsTemplate.TransformText()); var propertiesIndexHtmlFile = Path.Combine(StepInput.TmpPath, sdType.Guid + "-Properties.html"); var propertiesTemplate = new PropertiesTemplate { SDType = sdType }; File.WriteAllText(propertiesIndexHtmlFile, propertiesTemplate.TransformText()); var constructorsIndexHtmlFile = Path.Combine(StepInput.TmpPath, sdType.Guid + "-Constructors.html"); var constructorsTemplate = new ConstructorsTemplate { SDType = sdType }; File.WriteAllText(constructorsIndexHtmlFile, constructorsTemplate.TransformText()); var methodsIndexHtmlFile = Path.Combine(StepInput.TmpPath, sdType.Guid + "-Methods.html"); var methodsTemplate = new MethodsTemplate { SDType = sdType }; File.WriteAllText(methodsIndexHtmlFile, methodsTemplate.TransformText()); } } } } } private void CreateTypeFiles() { foreach (var solution in StepInput.SDProject.Solutions.Values) { var sdRepository = solution.Repositories.SingleOrDefault(r => r.TargetFx.Identifier == StepInput.CurrentTargetFx.Identifier); if (sdRepository != null) { foreach (var sdNamespace in sdRepository.GetAllNamespaces()) { foreach (var sdType in sdNamespace.Types) { ExecuteOnStepMessage(string.Format("{0}: {1}", StepInput.ChmStrings.CreateType, sdType.Name)); var typeHtmlFile = Path.Combine(StepInput.TmpPath, sdType.Guid + ".html"); var template = new TypeTemplate { SDType = sdType, SDRepository = sdRepository }; if (!sdType.IsClassDiagramEmpty()) { sdType.GetClassDiagram().ToPng(Path.Combine(StepInput.TmpPath, "diagrams", sdType.Guid + ".png")); } File.WriteAllText(typeHtmlFile, template.TransformText()); } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebTest.Code { /// <summary> /// 帐户管理 /// </summary> public class AccountManage : CRL.Account.AccountBusiness<AccountManage> { public static AccountManage Instance { get { return new AccountManage(); } } protected override CRL.DBExtend dbHelper { get { return GetDbHelper(this.GetType()); } } } }
namespace CarDealer.Data.Interfaces { using CarDealer.Models; public interface ISaleRepository : IRepository<Sale> { } }
using System; using System.Threading.Tasks; namespace WorldTimeAPI { internal static class SyncHelper { public static void TryInvokeMethodSync(Func<Task> method) { var task = Task.Run(async () => await method().ConfigureAwait(false)); task.Wait(); } public static T TryInvokeMethodSync<T>(Func<Task<T>> method) { var task = Task.Run(async () => await method().ConfigureAwait(false)); task.Wait(); return task.Result; } } }
/*********************************************** * * This class should only contain instructions for using weapons * and such by the player * * The class is functions is meant to be called by another class, * This class will act of the assumption that there is no restriction * on WHEN the player can attack * ***********************************************/ namespace DChild.Gameplay.Player { public interface IPlayerCombat { bool UseWeapon(Player.State state, Player.Focus focus); void ResetCombo(); } }
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual { /// <summary> /// Clase que representa la entidad consulta /// </summary> /// <remarks> /// Creación: GMD 20150710 <br /> /// Modificación: <br /> /// </remarks> public class ConsultaTrazabilidadEntity : Entity { /// <summary> /// Codigo de consulta Trazabilidad /// </summary> public Guid CodigoConsultaTrazabilidad { get; set; } /// <summary> /// Código de consulta /// </summary> public Guid CodigoConsulta { get; set; } /// <summary> /// Código de Remitente /// </summary> public Guid CodigoRemitente { get; set; } /// <summary> /// Código de destinatario /// </summary> public Guid CodigoDestinatario { get; set; } /// <summary> /// Fecha de envío /// </summary> public DateTime FechaEnvio { get; set; } } }
using Logger.Interfaces; using Logger.Messages; using System; using System.Collections.Generic; using System.Text; namespace Logger.Layouts { public class XMLLayout : ILayout { //<log> //<date>3/31/2015 5:33:07 PM</date> //<level>ERROR</level> //<message>Error parsing request</message> //</log> public string Implement(Message message) { return $@" <log> <date>{message.DateTime}</date> <level>{message.ReportLevel.ToString().ToUpper()}</level> <message>{message.Info}</message> </log>"; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class toptancı : Form { public toptancı() { InitializeComponent(); } SqlConnection baglanti = new SqlConnection("Server=DESKTOP-JMR7LFH;Database=pizza;User Id=sa;Password=123456;"); SqlCommand komut; DataSet dset = new DataSet(); private void toptancı_Load(object sender, EventArgs e) { listele(); } void listele() { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; textBox5.Text = ""; dset.Clear(); baglanti.Open(); SqlDataAdapter adtr = new SqlDataAdapter("select * From toptanci", baglanti); adtr.Fill(dset, "toptanci"); dataGridView1.DataSource = dset.Tables["toptanci"]; adtr.Dispose(); baglanti.Close(); } private void button1_Click(object sender, EventArgs e) { baglanti.Open(); komut = new SqlCommand("insert into toptanci(firma,mal,miktar,cins,tane_fiyat)values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')", baglanti); komut.ExecuteNonQuery(); MessageBox.Show("Kayıt Başarıyla Eklendi"); baglanti.Close(); listele(); } private void button2_Click(object sender, EventArgs e) { baglanti.Open(); try { komut = new SqlCommand("delete from toptanci where id='" + dataGridView1.CurrentRow.Cells["id"].Value.ToString() + "'", baglanti); komut.ExecuteNonQuery(); MessageBox.Show("Silme İşleme Başarıyla Tamamlandı"); baglanti.Close(); listele(); } catch (Exception hata) { MessageBox.Show(hata.Message); ; } } private void button6_Click(object sender, EventArgs e) { adminPaneli admin = new adminPaneli(); admin.Show(); this.Hide(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Text.RegularExpressions; namespace WebApplication2 { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected bool checkDetails(string email, string password) { SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\jack\Desktop\WebApplication2\WebApplication2\WebApplication2\App_Data\Database.mdf;Integrated Security=True"); SqlDataReader reader; bool valid = false; String[] parseID = email.Split('@'); String sql ="SELECT * FROM Customer WHERE EmailAddress = @email AND Password = @password"; connection.Open(); SqlCommand cmd = new SqlCommand(sql,connection); cmd.Parameters.Add("@email", SqlDbType.VarChar); cmd.Parameters["@email"].Value = email; cmd.Parameters.Add("@password", SqlDbType.VarChar); cmd.Parameters["@password"].Value = password; reader = cmd.ExecuteReader(); if(reader.HasRows) { valid = true; } connection.Close(); return valid; } protected void Login(object sender, EventArgs e) { if (checkDetails(txtEmail.Text, txtPassword.Text)) Response.Redirect("/Homepage.aspx", true); else loginSuccess.Text = "Username/Password Incorrect!"; } } }
using Pe.Stracon.SGC.Infraestructura.QueryModel.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual { /// <summary> /// Representa el objeto Logic de Flujo Aprobación Tipo de Contrato /// </summary> /// <remarks> /// Creación : GMD 20170621 <br /> /// Modificación : <br /> /// </remarks> public class FlujoAprobacionTipoContratoLogic { /// <summary> /// Código de Flujo de Aprobación Tipo de Contrato /// </summary> public Guid CodigoFlujoAprobacionTipoContrato { get; set; } /// <summary> /// Código de Flujo de Aprobación /// </summary> public Guid CodigoFlujoAprobacion { get; set; } /// <summary> /// Código de Tipo de Contrato /// </summary> public string CodigoTipoContrato { get; set; } /// <summary> /// Estadro de Registro /// </summary> public string EstadoRegistro { get; set; } } }
using Entitas; [Game] public sealed class MatchedComponent : IComponent { }
using System; using Entities; using Newtonsoft.Json; namespace Repository.DTOs { public class UserDTO { public int Id { get; set; } public string Email { get; set; } public string Password { get; set; } public string Type { get; set; } public string Name { get; set; } public string Surname { get; set; } public int ProfId { get; set; } public string EnrollmentNum { get; set; } public string EnrollmentType { get; set; } public string Phone { get; set; } public string Address { get; set; } public DateTime UpdatedAt { get; set; } public sbyte Status { get; set; } } }
using System.Collections.Generic; using HotelBooking.Models; namespace HotelBooking.ViewModels { public class RoomViewModel { public Room Room { get; set; } public IEnumerable<Reviews> Reviews { get; set; } public int FullStars { get; set; } public int EmptyStars { get; set; } public Favorites Favorites { get; set; } public User UserLoged { get; set; } public bool HasBooking { get; set; } public string CheckInDate { get; set; } public string CheckOutDate { get; set; } public RoomViewModel(Room room, IEnumerable<Reviews> reviews, int fullStars, int emptyStars, Favorites favorites, User userLoged, bool hasBooking, string checkInDate = null, string checkOutDate = null) { Room = room; Reviews = reviews; FullStars = fullStars; EmptyStars = emptyStars; Favorites = favorites; UserLoged = userLoged; HasBooking = hasBooking; CheckInDate = checkInDate; CheckOutDate = checkOutDate; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using Docller.Common; using Docller.Core.Common; using Docller.Core.Models; using Docller.Core.Services; using StructureMap; namespace Docller.Controllers { public abstract class DocllerControllerBase : Controller { private ViewBagWrapper _viewBagWrapper; public ViewBagWrapper ViewBagWrapper { get { return _viewBagWrapper ?? (_viewBagWrapper = new ViewBagWrapper(this)); } } public CookieData CurrentCookieData { get; set; } protected string CurrentDomain { get { return Utils.GetDomain(Request.Url ?? System.Web.HttpContext.Current.Request.Url); } } protected void SaveCurrentCookieData() { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName] ?? Response.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(authTicket.Version, authTicket.Name, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, this.CurrentCookieData.ToString()); string encryptedTicket = FormsAuthentication.Encrypt(newAuthTicket); authCookie.Value = encryptedTicket; Response.Cookies.Set(authCookie); } else { throw new NullReferenceException("Auth Cookie is null"); } } protected override void OnAuthorization(AuthorizationContext filterContext) { if (this.CurrentCookieData != null && this.CurrentCookieData.IsForceAccountUpdate) { if (!(filterContext.Controller is AccountController && filterContext.ActionDescriptor.ActionName.Equals("UpdateAccount"))) { filterContext.Result = this.RedirectToAction("UpdateAccount", "Account", routeValues: new { returnUrl = this.Request.Url.PathAndQuery}); } } EnsureUserCanAccessCurrentProjectOrFolder(filterContext); base.OnAuthorization(filterContext); } private void EnsureUserCanAccessCurrentProjectOrFolder(AuthorizationContext filterContext) { if (base.Request.IsAuthenticated && !filterContext.ActionDescriptor.ActionName.Equals("Error")) { if ((this.DocllerContext.ProjectId > 0 && !this.DocllerContext.Security.CanAccessCurrentProject) || (this.DocllerContext.FolderContext != null && this.DocllerContext.FolderContext.CurrentFolderId > 0 && !this.DocllerContext.Security.CanAccessCurrentFolder)) { filterContext.Result = this.RedirectToAction("Error", new { message = "Your not authorized" }); } } } protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); if (base.Request.IsAuthenticated) { ViewBagWrapper.HeaderBrand = "Docller"; HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); this.CurrentCookieData = new CookieData(authTicket.UserData); InjectContext(); } else { throw new NullReferenceException("Auth Cookie is null"); } } } protected ActionResult ContextDependentView(string masterLayout) { return ContextDependentView<object>(masterLayout, null); } protected ActionResult ContextDependentView() { return ContextDependentView<object>(null, null); } protected ActionResult ContextDependentView<T>(string masterLayout, T model) where T : class { string actionName = ControllerContext.RouteData.GetRequiredString("action"); if (Request.QueryString["content"] != null) { ViewBagWrapper.FormAction = "Json" + actionName; ViewBagWrapper.IsDlg = true; return PartialView(); } else { ViewResult view = model != null ? View(model) : View(); if(!string.IsNullOrEmpty(masterLayout)) { view.MasterName = masterLayout; } ViewBagWrapper.FormAction = actionName; return view; } } public IDocllerContext DocllerContext { get { return Core.Common.DocllerContext.Current; } } protected void EnsureAnonymousContext() { if (!this.Request.IsAuthenticated) { //See if we have Anonymous cookie //MachineKey.Protect(System.Text.ASCIIEncoding.ASCII.GetBytes(1.ToString()), "Anon CustomerId"); HttpCookie anonCookie = Request.Cookies[Constants.AnonymouseCookieName]; if (anonCookie == null) { anonCookie = new HttpCookie(Constants.AnonymouseCookieName); ISubscriptionService subscriptionService = ServiceFactory.GetSubscriptionService(); Customer customer = subscriptionService.GetCustomer(this.CurrentDomain); this.CurrentCookieData = new CookieData() {CustomerId = customer.CustomerId}; anonCookie.Value = Security.Encrypt(this.CurrentCookieData.ToString()); Response.Cookies.Add(anonCookie); } else { this.CurrentCookieData = new CookieData(Security.Decrypt<string>(anonCookie.Value)); } InjectContext(); } } protected void InjectContext() { Factory.GetInstance<IDocllerContext>().Inject(this); } protected void InjectContext(User user) { Factory.GetInstance<IDocllerContext>().Inject(this,user); } [HttpGet] [AllowAnonymous] public ActionResult Error(string message) { ViewBagWrapper.ErrorMessage = string.IsNullOrEmpty(message) ? "An Error has occured" : HttpUtility.HtmlEncode(message); return View(); } } }
/* Daniel Mitchel-Slentz * ReactiveTarget.cs * This is attached to babmbi. * the method, ReacToHit gets called by Chutem */ using UnityEngine; using System.Collections; public class ReactiveTarget : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void ReactToHit() // called when bambi gets shot { TargetWanderer behavior = GetComponent<TargetWanderer>(); if(behavior != null) { behavior.SetAlive(false); } StartCoroutine(Die()); // implement bambi's death } private IEnumerator Die() // coroutine for bambi's death thows { this.transform.Rotate(-75, 50, 0); yield return new WaitForSeconds(1.5f); Destroy(this.gameObject); } }
using System; public static class Hamming { public static int Distance(string s1, string s2) { if (s1.Length != s2.Length) throw new ArgumentException(); int hammingDistance = 0; for (int i = 0; i < s1.Length; i++) { if (s1[i] != s2[i]) hammingDistance++; } return hammingDistance; } }
/******************************************************************************\ * Copyright (C) Leap Motion, Inc. 2011-2014. * * Leap Motion proprietary. Licensed under Apache 2.0 * * Available at http://www.apache.org/licenses/LICENSE-2.0.html * \******************************************************************************/ using UnityEngine; using System.Collections; using Leap; /** * A finger object consisting of discrete, component parts for each bone. * * The graphic objects can include both bones and joints, but both are optional. */ public class SkeletalFinger : FingerModel { /** Initializes the finger bones and joints by setting their positions and rotations. */ public override void InitFinger() { SetPositions(); } /** Updates the finger bones and joints by setting their positions and rotations. */ public override void UpdateFinger() { SetPositions(); } public float angleChange(float angle1) { if (angle1 >= 355.0f) { angle1 = 360.0f - angle1; } return angle1; } public override void FingerStat(ref int cnt) { float firstDiff = angleChange(Mathf.Abs(this.bones [1].transform.eulerAngles.y - this.bones [2].transform.eulerAngles.y)); float secondDiff = angleChange(Mathf.Abs(this.bones [1].transform.eulerAngles.y - this .bones [3].transform.eulerAngles.y)); float thirdDiff = angleChange(Mathf.Abs(this.bones[2].transform.eulerAngles.y - this.bones[3].transform.eulerAngles.y)); if ((firstDiff >= 0 && firstDiff <= 5) && (secondDiff >= 0 && secondDiff <= 5) && (thirdDiff >= 0 && thirdDiff <= 5)) { if (this.fingerType == Finger.FingerType.TYPE_INDEX) { cnt += 1; } else if (this.fingerType == Finger.FingerType.TYPE_MIDDLE) { cnt += 2; } else { cnt += 10; } } } protected void SetPositions() { for (int i = 0; i < bones.Length; ++i) { if (bones[i] != null) { /*Renderer[] renderers = bones[3].GetComponentsInChildren<Renderer>(); foreach(Renderer renderer in renderers) { //Debug.Log ("Marked: " + renderer.gameObject.transform.parent.name + "/" + renderer.gameObject.name); renderer.material.color = Color.blue; }*/ bones[i].transform.position = GetBoneCenter(i); bones[i].transform.rotation = GetBoneRotation(i); } } for (int i = 0; i < joints.Length; ++i) { if (joints[i] != null) { joints[i].transform.position = GetJointPosition(i + 1); joints[i].transform.rotation = GetBoneRotation(i + 1); } } } }
using FunctionalProgramming.Monad.Outlaws; using System; namespace FunctionalProgramming.Monad.Transformer { public class IoStateTry<TState, TValue> { public readonly Io<State<TState, Try<TValue>>> Out; public IoStateTry(Io<State<TState, Try<TValue>>> io) { Out = io; } public IoStateTry(State<TState, Try<TValue>> state) : this(Io.Apply(() => state)) { } public IoStateTry(Try<TValue> @try) : this(@try.Insert<TState, Try<TValue>>()) { } public IoStateTry(TValue val) : this(Try.Attempt(() => val)) { } public IoStateTry<TState, TResult> FMap<TResult>(Func<TValue, TResult> f) { return new IoStateTry<TState, TResult>(Out.Select(state => state.Select(@try => @try.Select(f)))); } public IoStateTry<TState, TResult> Bind<TResult>(Func<TValue, IoStateTry<TState, TResult>> f) { return new IoStateTry<TState, TResult>(Out.SelectMany(state => Io.Apply(() => new State<TState, Try<TResult>>(s => { var result = state.Run(s); return result.Item2.Match( success: val => f(val).Out.UnsafePerformIo().Run(result.Item1), failure: ex => Tuple.Create(result.Item1, ex.Fail<TResult>())); })))); } } public static class IoStateTry { public static IoStateTry<TState, T> ToIoStateTry<TState, T>(this Io<State<TState, Try<T>>> ioT) { return new IoStateTry<TState, T>(ioT); } public static IoStateTry<TState, T> ToIoStateTry<TState, T>(this Io<T> io) { return new IoStateTry<TState, T>(io.Select(t => Try.Attempt(() => t).Insert<TState, Try<T>>())); } public static IoStateTry<TState, T> ToIoStateTry<TState, T>(this State<TState, T> state) { return new IoStateTry<TState, T>(state.Select(t => Try.Attempt(() => t))); } public static IoStateTry<TState, T> ToIoStateTry<TState, T>(this Io<Try<T>> ioTry) { return new IoStateTry<TState, T>(ioTry.Select(@try => @try.Insert<TState, Try<T>>())); } public static IoStateTry<TState, T> ToIoStateTry<TState, T>(this Io<State<TState, T>> ioState) { return new IoStateTry<TState, T>(ioState.Select(state => state.Select(t => Try.Attempt(() => t)))); } public static IoStateTry<TState, T> ToIoStateTry<TState, T>(this T t) { return new IoStateTry<TState, T>(t); } public static IoStateTry<TState, TResult> Select<TState, TValue, TResult>(this IoStateTry<TState, TValue> ioT, Func<TValue, TResult> f) { return ioT.FMap(f); } public static IoStateTry<TState, TResult> SelectMany<TState, TValue, TResult>(this IoStateTry<TState, TValue> ioT, Func<TValue, IoStateTry<TState, TResult>> f) { return ioT.Bind(f); } public static IoStateTry<TState, TSelect> SelectMany<TState, TValue, TResult, TSelect>( this IoStateTry<TState, TValue> ioT, Func<TValue, IoStateTry<TState, TResult>> f, Func<TValue, TResult, TSelect> selector) { return ioT.SelectMany(a => f(a).SelectMany(b => selector(a, b).ToIoStateTry<TState, TSelect>())); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DemoMVCApplication.Models { public class WrapperModel { public IEnumerable<Movie> Movies; public Movie movie; } }
using System; namespace ObjemStudny { class Program { static void Main(string[] args) { double r; double h; Console.WriteLine("Zadej poloměr studny:"); r = ReadLineToDouble(); Console.WriteLine("Zadej hloubku studny:"); h = ReadLineToDouble(); double vysledek = Math.PI * r * r * h * 1000; Console.WriteLine("Objem studny je: {0}", vysledek); } //Pomocná metoda pro získání doublu přes vstup od uživatele private static double ReadLineToDouble() { return Convert.ToDouble(Console.ReadLine()); } } }
using EddiEddnResponder.Sender; using JetBrains.Annotations; using System; using System.Collections.Generic; using Utilities; namespace EddiEddnResponder.Schemas { [UsedImplicitly] public class FSSDiscoveryScanSchema : ISchema { public List<string> edTypes => new List<string> { "FSSDiscoveryScan" }; public bool Handle(string edType, ref IDictionary<string, object> data, EDDNState eddnState) { try { if (!edTypes.Contains(edType)) { return false; } if (eddnState?.Location is null || eddnState.GameVersion is null) { return false; } if (!eddnState.Location.CheckLocationData(edType, data)) { return false; } // Remove personal data data.Remove("Progress"); // Apply data augments // Note: This event contains a `SystemName` property so we // do not need to enrich it with the conventional `StarSystem` property data = eddnState.Location.AugmentStarPos(data); data = eddnState.GameVersion.AugmentVersion(data); EDDNSender.SendToEDDN("https://eddn.edcd.io/schemas/fssdiscoveryscan/1", data, eddnState); return true; } catch (Exception e) { Logging.Error($"{GetType().Name} failed to handle journal data.", e); return false; } } } }
using Airelax.Domain.Houses.Defines; namespace Airelax.Application.Houses.Dtos.Request { public class UpdateHouseTypeInput { public HouseType HouseType { get; set; } } }
using Alabo.Runtime; namespace Alabo.Tenants.Extensions { public static class ConnectionStringExtension { /// <summary> /// Get master connection string /// </summary> /// <param name="connectionString"></param> /// <returns></returns> public static string GetConnectionStringForMaster(this string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { return string.Empty; } var database = RuntimeContext.GetTenantSqlDataBase(); connectionString = connectionString.Replace( "Initial Catalog=" + RuntimeContext.Current.WebsiteConfig.MsSqlDbConnection.Database, "Initial Catalog=" + database); return connectionString; } /// <summary> /// Get tenant connection string /// </summary> /// <param name="connectionString"></param> /// <param name="tenantName"></param> /// <returns></returns> public static string GetConnectionStringForTenant(this string connectionString, string tenantName) { if (string.IsNullOrWhiteSpace(connectionString) || string.IsNullOrWhiteSpace(tenantName)) { return string.Empty; } var database = RuntimeContext.GetTenantMongodbDataBase(); var databaseName = RuntimeContext.GetTenantMongodbDataBase(tenantName); return connectionString.Replace(database, databaseName); } } }
using ClientFramework.Request; using System; using System.Net; using System.Net.Sockets; using System.Text; namespace ClientFramework { class Program { static void Main(string[] args) { ClientManage clientManage = new ClientManage(); clientManage.OnInit(); LoginRequest loginRequest = new LoginRequest(); RegisterRequest registerRequest = new RegisterRequest(); while(true) { if (Console.ReadKey().KeyChar == 'l') { loginRequest.SendRequest(clientManage, "张三", "123"); } if (Console.ReadKey().KeyChar == 'r') { registerRequest.SendRequest(clientManage, "张三", "123"); } } } } }
 using Xamarin.Forms; namespace AsNum.XFControls.Templates { public partial class DefaultRadioButtonSelectedControlTemplate : ControlTemplate { public DefaultRadioButtonSelectedControlTemplate() { InitializeComponent(); } } }
namespace KartSystem.Common { public partial class SelectReportPrintForm : SelectDocumentPrintForm { public SelectReportPrintForm(long idDocType) : base(idDocType) { InitializeComponent(); IdDocType = idDocType; } public override void SaveSettings() { var s = new ParameterReportPrintForm { File1 = beFileName1.Text, File2 = beFileName2.Text, File3 = beFileName3.Text, File4 = beFileName4.Text, File5 = beFileName5.Text }; SaveParameter<ParameterReportPrintForm>(s); } public override void LoadSettings() { var s = (ParameterReportPrintForm) LoadParameter<ParameterReportPrintForm>(); if (s != null) { beFileName1.Text = s.File1; beFileName2.Text = s.File2; beFileName3.Text = s.File3; beFileName4.Text = s.File4; beFileName5.Text = s.File5; } } } }
#if NETSTANDARD2_0 using IHostApplicationLifetime = Microsoft.AspNetCore.Hosting.IApplicationLifetime; #else using Microsoft.Extensions.Hosting; #endif using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Sentry; using Sentry.AspNetCore; using Sentry.Extensibility; using Sentry.Extensions.Logging; using Sentry.Infrastructure; // ReSharper disable once CheckNamespace -- Discoverability namespace Microsoft.AspNetCore.Builder; /// <summary> /// Extension methods for <see cref="IApplicationBuilder"/> /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class ApplicationBuilderExtensions { /// <summary> /// Use Sentry integration /// </summary> /// <param name="app">The application.</param> public static IApplicationBuilder UseSentry(this IApplicationBuilder app) { // Container is built so resolve a logger and modify the SDK internal logger var options = app.ApplicationServices.GetService<IOptions<SentryAspNetCoreOptions>>(); if (options?.Value is { } o) { if (o.Debug && (o.DiagnosticLogger is null or ConsoleDiagnosticLogger || o.DiagnosticLogger.GetType().Name == "TestOutputDiagnosticLogger")) { var logger = app.ApplicationServices.GetRequiredService<ILogger<ISentryClient>>(); o.DiagnosticLogger = new MelDiagnosticLogger(logger, o.DiagnosticLevel); } var stackTraceFactory = app.ApplicationServices.GetService<ISentryStackTraceFactory>(); if (stackTraceFactory != null) { o.UseStackTraceFactory(stackTraceFactory); } } var lifetime = app.ApplicationServices.GetService<IHostApplicationLifetime>(); lifetime?.ApplicationStopped.Register(SentrySdk.Close); return app.UseMiddleware<SentryMiddleware>(); } }
using System.Threading.Tasks; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Fields; using FakeItEasy; using Newtonsoft.Json.Linq; using Xunit; namespace DFC.ServiceTaxonomy.UnitTests.GraphSync.GraphSyncers.Fields.DateTimeFieldGraphSyncerTests { public class DateTimeFieldGraphSyncerValidateSyncComponentTestsBase : FieldGraphSyncer_ValidateSyncComponentTestsBase { private const string ContentKey = "Value"; public DateTimeFieldGraphSyncerValidateSyncComponentTestsBase() { ContentFieldGraphSyncer = new DateTimeFieldGraphSyncer(); } //todo: move into base? [Theory] [InlineData(true)] [InlineData(false)] public async Task ValidateSyncComponentTests(bool dateTimeMatches) { A.CallTo(() => GraphValidationHelper.DateTimeContentPropertyMatchesNodeProperty( ContentKey, A<JObject>._, FieldNameTransformed, SourceNode)).Returns((dateTimeMatches, "")); (bool validated, _) = await CallValidateSyncComponent(); Assert.Equal(dateTimeMatches, validated); } } }
using System; using System.Collections.Generic; using System.Text; namespace RXCO.AzureDevOps.REST.Base { public abstract class BaseRestAPIInfo { } }
// <copyright file="FeatureRecord.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> namespace WaterTrans.GlyphLoader.OpenType { /// <summary> /// The relationship of scripts, language systems, features, and lookups for substitution and positioning tables. /// </summary> public class FeatureRecord { /// <summary> /// Initializes a new instance of the <see cref="FeatureRecord"/> class. /// </summary> /// <param name="scriptTag">The script identification tag.</param> /// <param name="languageSystemTag">The language system tag.</param> /// <param name="featureTag">The feature system tag.</param> /// <param name="featureIndex">The feature index.</param> internal FeatureRecord(string scriptTag, string languageSystemTag, string featureTag, int featureIndex) { ScriptTag = scriptTag; LanguageSystemTag = languageSystemTag; FeatureTag = featureTag; FeatureIndex = featureIndex; } /// <summary>Gets an identification.</summary> public string Id { get { return ScriptTag + "." + LanguageSystemTag + "." + FeatureTag; } } /// <summary>Gets the script identification tag.</summary> public string ScriptTag { get; } /// <summary>Gets the language system tag.</summary> public string LanguageSystemTag { get; } /// <summary>Gets the feature system tag.</summary> public string FeatureTag { get; } /// <summary>Gets the feature index.</summary> public int FeatureIndex { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Views.InputMethods; namespace CalCal { [Activity(Label = "Ile kalori potrzebujesz?")] public class CalcCalories : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.calcLayout); double activityRatio = 0; double sexRatio = 0; EditText heightText = FindViewById<EditText>(Resource.Id.heightText); EditText weightText = FindViewById<EditText>(Resource.Id.weightText); EditText ageText = FindViewById<EditText>(Resource.Id.ageText); RadioGroup sexRadioGroup = FindViewById<RadioGroup>(Resource.Id.sexRadioGroup); RadioButton womanRadio = FindViewById<RadioButton>(Resource.Id.womanButton); RadioButton manRadio = FindViewById<RadioButton>(Resource.Id.manButton); RadioGroup activityRadioGroup = FindViewById<RadioGroup>(Resource.Id.activityRadioGroup); RadioButton lowActivity = FindViewById<RadioButton>(Resource.Id.lowActivityRadio); RadioButton avarageActivity = FindViewById<RadioButton>(Resource.Id.avarageActivityRadio); RadioButton highActivity = FindViewById<RadioButton>(Resource.Id.highActivityRadio); RadioButton veryHighActivity = FindViewById<RadioButton>(Resource.Id.highestActivityRadio); Button countButton = FindViewById<Button>(Resource.Id.countButton); TextView ppmLabel = FindViewById<TextView>(Resource.Id.PPMLabel); TextView ppmText = FindViewById<TextView>(Resource.Id.PPMText); TextView calNeedsLabel = FindViewById<TextView>(Resource.Id.calNeedsLabel); TextView calNeedsText = FindViewById<TextView>(Resource.Id.calNeedsText); ppmLabel.Visibility = ViewStates.Invisible; ppmText.Visibility = ViewStates.Invisible; calNeedsLabel.Visibility = ViewStates.Invisible; calNeedsText.Visibility = ViewStates.Invisible; manRadio.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; womanRadio.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; lowActivity.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; avarageActivity.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; highActivity.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; veryHighActivity.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; sexRadioGroup.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; activityRadioGroup.Click += delegate { var inputManager = (InputMethodManager)GetSystemService(InputMethodService); inputManager.HideSoftInputFromWindow(ageText.WindowToken, HideSoftInputFlags.None); }; countButton.Click += delegate { try { if (womanRadio.Checked) sexRatio = -161; if (manRadio.Checked) sexRatio = 5; if (lowActivity.Checked) activityRatio = 1.4; if (avarageActivity.Checked) activityRatio = 1.6; if (highActivity.Checked) activityRatio = 1.75; if (veryHighActivity.Checked) activityRatio = 2.2; double ppm = 10 * double.Parse(weightText.Text) + 6.25 * double.Parse(heightText.Text) - 5 * double.Parse(ageText.Text) + sexRatio; double caloriesNeed = ppm * activityRatio; ppmLabel.Visibility = ViewStates.Visible; ppmText.Visibility = ViewStates.Visible; calNeedsLabel.Visibility = ViewStates.Visible; calNeedsText.Visibility = ViewStates.Visible; ppmText.Text = (ppm.ToString() + " kcal"); calNeedsText.Text = (caloriesNeed.ToString() + " kcal"); } catch { ppmText.Visibility = ViewStates.Visible; ppmText.Text = "Podaj poprawne wartości"; } }; } } }
using System; using System.Data; using System.Text.RegularExpressions; #if LINUX using Mono.Data.Sqlite; #else using System.Data.SQLite; #endif using System.Collections.Generic; namespace Server { public enum LayerType { Ground=0, Blocking=1, Object=2 } public struct Coord { public int X; public int Y; public Coord (int x, int y) { X=x; Y=y; } public static bool operator ==(Coord c, Coord c2){ return (c.X==c2.X && c.Y==c2.Y); } public static bool operator !=(Coord c, Coord c2){ return (c.X!=c2.X || c.Y!=c2.Y); } public static Coord operator +(Coord c, Coord c2){ return new Coord(c.X+c2.X, c.Y+c2.Y); } public static Coord operator -(Coord c, Coord c2){ return new Coord(c.X-c2.X, c.Y-c2.Y); } } public struct Equation { static Regex DiceParser = new Regex ("(?<sign>[+-])?((?<dice>(?<mult>[0-9]+)[dD](?<cat>[0-9]+))|(?<number>[0-9]+))", RegexOptions.Compiled); //TODO static Regex DiceParser = new Regex("(?<sign>[+-])?(?<mult>[0-9]+)(?<cat>[dD][0-9]+)?", RegexOptions.Compiled); //if cat.success -> dice; else -> static public string val; public string multiplier; string description; public Equation(string desc, string mult, string eq) { description=desc; val = eq; multiplier = mult; } public string Value () { int parsedMultiplier = Equation.Parse (multiplier); int total = 0; int curTotal = 0; string ret; if (parsedMultiplier == 1) return String.Format("{0}: {1} = {2}",description,val,Equation.Parse(val)); ret= String.Format("{0}:{1}({2})x({3})"+'\n',description,multiplier,parsedMultiplier,val); for (int i =0; i<parsedMultiplier; i++) { curTotal=Equation.Parse (val); total+=curTotal; ret += curTotal+"; "; } ret=ret.TrimEnd().TrimEnd(';')+'\n'; ret +="Total: " + total; return ret; } public static int Parse (string v) { MatchCollection matches = DiceParser.Matches (v); int sign; int sum=0; foreach (Match m in matches) { sign=1; if (m.Groups["sign"].Success) { if (m.Groups["sign"].Value=="-") sign=-1; } if (m.Groups["dice"].Success){ int mult=Int32.Parse(m.Groups["mult"].Value); int cat=Int32.Parse(m.Groups["cat"].Value); int DiceSum=0; for (int i=0; i<mult;i++) DiceSum+=Engine.Roll(cat); sum+=sign*DiceSum; } else { sum+=sign*Int32.Parse(m.Groups["number"].Value); } } return sum; } public string GetDescription () { return description; } } public struct Tile { int id; string description; public Tile (int i, string d) { id = i; description = d; } public string Get() { return id.ToString()+"-"+description+","; } } public static class Engine { public static int curTurn; public static int TotalChars=0; public static List<Character> playerIDInit= new List<Character>(); public static List<Character> Mobs=new List<Character>(); static List<Tile> Tiles = new List<Tile>(); public static string Objects; private const string ConnectionString = "URI=file:database.db"; private const int MAPID = 1; private static IDbConnection dbcon; private static IDataReader reader; private static IDbCommand dbcmd; private static int curMobID=2000; private static Random rnd=new Random(); public static int D10 { get { return rnd.Next (1, 10); } } public static int D6 { get { return rnd.Next (1, 6); } } public static int D12 { get { return rnd.Next (1, 12); } } public static int D20 { get { return rnd.Next (1, 20); } } public static int Roll (int i) { return rnd.Next(1,i); } public static void Initialize () { LoadDatabase(); } private static void LoadDatabase () { Console.WriteLine ("Started loading map from DB"); #if LINUX dbcon = (IDbConnection)new SqliteConnection (ConnectionString); #else dbcon = (IDbConnection)new SQLiteConnection (ConnectionString); #endif dbcon.Open (); Console.WriteLine("Loading Tiles"); GetTiles(); Console.WriteLine("Tiles loaded"); Console.WriteLine("Loading Objects"); GetObjects(); Console.WriteLine("Objects loaded"); dbcmd = dbcon.CreateCommand (); dbcmd.CommandText = "SELECT WIDTH,HEIGHT,SPAWNX,SPAWNY FROM MAP WHERE ID=" + MAPID; reader = dbcmd.ExecuteReader (); if (reader.Read ()) { Map.Initialize(reader.GetInt16 (0), reader.GetInt16 (1), new Coord(reader.GetInt32(2),reader.GetInt16(3))); } else { return; //die } Console.WriteLine ("Map loaded"); dbcmd.Dispose (); dbcmd.CommandText = "SELECT TYPE,DATA FROM LAYERS WHERE MAPID=" + MAPID; reader = dbcmd.ExecuteReader (); while (reader.Read ()) Map.ParseMapLayer((LayerType)reader.GetInt16 (0), Map.Width, Map.Height, reader.GetString (1)); Console.WriteLine ("Layers loaded"); Console.WriteLine("Loading Mobs"); GetAllMobs(); Console.WriteLine("Mobs loaded"); Console.WriteLine ("Finished loading"); } public static void Unload() { //TODO:Call this reader.Close(); reader = null; dbcon.Close(); dbcon = null; } public static Player Login (string name) { int id = 0; bool dm = false; List<Character> chars = new List<Character> (); dbcmd = dbcon.CreateCommand (); dbcmd.CommandText = string.Format ("SELECT ID,DM FROM PLAYER WHERE NAME='{0}'", name.ToUpper ()); reader = dbcmd.ExecuteReader (); if (reader.Read ()) { id = reader.GetInt32 (0); dm = reader.GetBoolean (1); } if (id == 0) return null; dbcmd = dbcon.CreateCommand (); dbcmd.CommandText = String.Format ("SELECT ID,NAME,SPRITE,VISIONRANGE,SIZE,WILL,REFLEX,FORTITUDE,CHA,WIS,INT,CON,DEX,STR,INITIATIVE FROM CHARACTERS WHERE PLAYER='{0}'", id); reader = dbcmd.ExecuteReader (); while (reader.Read ()) { chars.Add (new Character (reader.GetInt16 (0), reader.GetString (1), reader.GetInt16 (2), reader.GetInt16 (3), reader.GetInt16 (4), //up to size reader.GetInt16 (5), reader.GetInt16 (6), reader.GetInt16 (7), //will, reflex,fort reader.GetInt16 (8), reader.GetInt16 (9), reader.GetInt16 (10), reader.GetInt16 (11), reader.GetInt16 (12), reader.GetInt16 (13), reader.GetInt16 (14)) ); } foreach (Character c in chars) { dbcmd = dbcon.CreateCommand (); dbcmd.CommandText = String.Format ("SELECT MULT,VALUE,DESC FROM PRESETS WHERE CHAR='{0}'", c.ID); reader = dbcmd.ExecuteReader (); while (reader.Read ()) c.AddEquation(new Equation(reader.GetString(2),reader.GetString(0),reader.GetString(1))); } TotalChars+=chars.Count; return new Player(id,chars,name,dm); } private static void GetAllMobs () { string name; int sprite,visionrange,size,id; dbcmd = dbcon.CreateCommand(); dbcmd.CommandText = "SELECT ID,NAME,SPRITE,VISIONRANGE,SIZE,WILL,REFLEX,FORTITUDE,CHA,WIS,INT,CON,DEX,STR,INITIATIVE FROM MOBS"; reader = dbcmd.ExecuteReader (); while (reader.Read ()) { id = reader.GetInt16(0); name = reader.GetString(1); sprite = reader.GetInt32(2); visionrange = reader.GetInt32(3); size = reader.GetInt32(4); Mobs.Add (new Character(id,name,sprite,visionrange,size, reader.GetInt16(5),reader.GetInt16(6),reader.GetInt16(7), //will, reflex,fort reader.GetInt16(8),reader.GetInt16(9),reader.GetInt16(10),reader.GetInt16(11),reader.GetInt16(12),reader.GetInt16(13),reader.GetInt16(14))); } } private static void GetTiles () { string desc; int texture; dbcmd = dbcon.CreateCommand (); dbcmd.CommandText = "SELECT TEXTURE,DESCRIPTION FROM TILES"; reader = dbcmd.ExecuteReader (); while (reader.Read ()) { texture=reader.GetInt16(0); desc=reader.GetString(1); Tiles.Add(new Tile(texture,desc)); } } public static string SerializeTiles() { string ret ="TILE"; foreach(Tile t in Tiles) ret+=t.Get(); return ret.TrimEnd(','); } private static void GetObjects () { string desc; int texture; dbcmd = dbcon.CreateCommand (); dbcmd.CommandText = "SELECT TEXTURE,DESCRIPTION FROM OBJECTS"; reader = dbcmd.ExecuteReader (); Objects="OBJS"; while (reader.Read ()) { texture=reader.GetInt16(0); desc=reader.GetString(1); Objects+=texture+"-"+desc+","; } Objects=Objects.TrimEnd(','); } public static Character GetMob (int id) { foreach (Character mob in Mobs) if (mob.ID == id) { return new Character(mob,curMobID++); //unique char id } return null; } internal static void RollInitiative () { bool inserted; playerIDInit.Clear(); foreach (Player p in Network.Players) foreach (Character c in p.chars) { inserted=false; c.RollInitiative (); for (int i=0; i < playerIDInit.Count;i++) if (c.currentInitiative>playerIDInit[i].currentInitiative){ inserted=true; playerIDInit.Insert(i,c); break; } if (!inserted) playerIDInit.Add(c); } curTurn=0; } public static string InitiativeString () { string data="INIT"; for (int i=0; i<playerIDInit.Count; i++) data += playerIDInit [i].Name + " " + playerIDInit [i].currentInitiative + "(" + playerIDInit [i].initiative + "),"; return data; } public static void Delay (Character c) { Character aux; for (int i=0; i< playerIDInit.Count-1; i++) { // -1 because I won't switch anything if he is the last one if (playerIDInit[i].ID == c.ID){ aux = playerIDInit[i]; playerIDInit[i]=playerIDInit[i+1]; playerIDInit[i+1]=aux; return; } } } } }
namespace PatientWebApp.Auth { public static class UserRoles { public const string Admin = "Admin"; public const string Patient = "Patient"; public const string Doctor = "Doctor"; public const string Secretary = "Secretary"; public const string Manager = "Manager"; } }
using FeriaVirtual.Domain.SeedWork.Commands; namespace FeriaVirtual.Application.Users.Commands.ChangeStatus { public class ChangeUserStatusCommand : Command { public System.Guid UserId { get; protected set; } public int IsActive { get; protected set; } public ChangeUserStatusCommand(string userId, int isActive) { UserId = new System.Guid(userId); IsActive = isActive; } } }
using UnityEngine; using System.Collections; public class DoctorBehaviour : MonoBehaviour { public AudioSource [] audioSources; public bool audioOneTriggered = false; public bool audioTwoTriggered = false; public bool faceWaypoint = false; public Transform[] waypoints; public int currentWaypoint = 0; public DATACORE dataCore = null; public GameObject nurse = null; // Use this for initialization void Start () { if (dataCore == null) { dataCore = GameObject.FindGameObjectWithTag("GameLogic").GetComponent<DATACORE>(); } Debug.Log ("Number of AudioSources " + audioSources.Length ); } // Update is called once per frame void Update () { if (audioOneTriggered == true) { if(audioSources[0].isPlaying == true) { // Look at player this.transform.LookAt (dataCore.thePlayer.transform.position); currentWaypoint = 0; } else { nurse.SendMessage ("DoMovement"); //if(faceWaypoint == false) { // transform.LookAt(waypoints[currentWaypoint]); // faceWaypoint = true; //} // Move to nurse position if(currentWaypoint >= waypoints.Length) { audioOneTriggered = false; audioTwoTriggered = true; PlayAudioTwo(); //faceWaypoint = false; //currentWaypoint = 0; } else { if(faceWaypoint == false) { transform.LookAt(waypoints[currentWaypoint]); faceWaypoint = true; } float distToCurrentPosition = (waypoints[currentWaypoint].position - transform.position).magnitude; if(distToCurrentPosition < 0.5f) { ++currentWaypoint; faceWaypoint = false; Debug.Log ("Changing Way Point " + currentWaypoint); } if(currentWaypoint < waypoints.Length) { //this.transform.LookAt(waypoints[currentWaypoint].position); transform.position = Vector3.MoveTowards (transform.position, waypoints[currentWaypoint].position, 2.0f * Time.deltaTime); } } } } // When At nurse position, trigger audio two if (audioTwoTriggered == true) { if(audioSources[1].isPlaying == true) { this.transform.LookAt(new Vector3(nurse.transform.position.x, this.transform.position.y, nurse.transform.position.z)); } else { // When audio two is finished, allow player to move audioTwoTriggered = false; dataCore.thePlayer.SendMessage("ToggleMovement"); } } } void PlayAudioOne() { audioSources[0].Play (); audioOneTriggered = true; Destroy(GetComponent<InteractionBehaviourCS>()); //ItemScriptCS temp = this.gameObject.GetComponent<ItemScriptCS> (); //if (temp == null) Debug.Log ("NO ITEM SCRIP"); //Destroy(this.gameObject.GetComponent <ItemScriptCS>()); } void PlayAudioTwo() { audioSources[1].Play (); } }
using UnityEngine; public class SEManagerGame :MonoBehaviour { public AudioClip HomeButton1; public AudioClip Button1; public AudioClip CountDown; public AudioClip Go; public GameObject SEXmarkButton; static public int SEXmark ; AudioSource audioSource; // Start is called before the first frame update void Start() { audioSource = GetComponent<AudioSource>(); DontDestroyOnLoad(this.gameObject); } // Update is called once per frame void Update() { if (SEManagerHome.SEXmark == 1 || SEXmark ==1) { this.gameObject.SetActive(false); } if ((3.3f < GameDirector.starttime && GameDirector.starttime < 3.4f) || (2.3f < GameDirector.starttime && GameDirector.starttime < 2.4f) || (1.3f < GameDirector.starttime && GameDirector.starttime < 1.4f)) { audioSource.PlayOneShot(CountDown); } else if (0.2f < GameDirector.starttime && GameDirector.starttime < 0.4f) { audioSource.PlayOneShot(Go); } } public void HomeButtonPush1() { audioSource.PlayOneShot(HomeButton1); this.gameObject.SetActive(true); } public void ButtonPush1() { audioSource.PlayOneShot(Button1); } public void SEButtonPush() { this.gameObject.SetActive(false); SEXmarkButton.SetActive(true); SEXmark = 1; } public void SEXmarkButtonPush() { this.gameObject.SetActive(true); SEXmarkButton.SetActive(false); SEXmark = 0; SEManagerHome.SEXmark = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TDC_Union.ModelsPush { public class PLoginModel { public PLoginModel() { FName = "Login"; } public string FName { get; set; } public string Role { get; set; } public string Error { get; set; } } }
using System; namespace Nusstudios.Models { public class ArticleViewModel { public ArticleViewModel(string baseurl) { BaseURL = baseurl; BlogSelected = false; ReferenceSelected = true; } public ArticleViewModel(string title, string baseurl, bool hasAbout, bool hasDownload, bool gb) { Title = title; BaseURL = baseurl; BlogSelected = true; ReferenceSelected = false; HasAbout = hasAbout; HasDownload = hasDownload; GB = gb; } public string Title; public string BaseURL; public bool BlogSelected; public bool ReferenceSelected; public bool HasAbout; public bool HasDownload; public bool GB; } }
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Get current mute status. /// </summary> [LibVlcFunction("libvlc_audio_get_mute")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int IsMute(IntPtr mediaPlayerInstance); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography.X509Certificates; namespace ValidationExtensions.Tests.Main { public class BaseTest { protected const String certificateNameEC_ACC = @"..\..\support\ec-acc.cer"; protected const String certificateNameEC_IDCAT = @"..\..\support\ec-idcat.cer"; protected const String certificateNameFP_ROOT = @"..\..\support\FPROOT.cer"; protected const String certificateNameFP_INFRAESTRUCTURA = @"..\..\support\fp_infraestructura.cer"; protected const String certificateNameIMI = @"..\..\support\imiCA.cer"; protected const String certificateNameIZENPE_ROOT = @"..\..\support\izenpe_root.crt"; protected const String certificateNameIZENPE_INFRAESTRUCTURA = @"..\..\support\izenpe_ciudadanos_entidades.crt"; protected const String httpUrlCRL = "http://epscd.catcert.net/crl/ec-acc.crl"; protected const String httpsUrlCRL = "https://crl.firmaprofesional.com/firmaprofesional1.crl"; protected const String httpUrlCatcertOCSP = "http://ocsp.catcert.net"; protected const String httpUrlFPOCSP = "http://ocsp.firmaprofesional.com"; protected X509Certificate2 certificateTestEC_ACC; protected X509Certificate2 certificateTestEC_IDCAT; protected X509Certificate2 certificateTestFP_ROOT; protected X509Certificate2 certificateTestFP_INFRAESTRUCTURA; protected X509Certificate2 certificateTestIZENPE_ROOT; protected X509Certificate2 certificateTestIZENPE_INFRAESTRUCTURA; protected X509Certificate2 certificateTestIMI; protected String getCurrentAssemblyPath() { return System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".dll", ""); } } }
using MailKit.Net.Smtp; using SuiviCompresseur.Notification.Data.Context; using SuiviCompresseur.Notification.Domain.Interfaces; using SuiviCompresseur.Notification.Domain.Models; using SuiviCompresseur.Notification.Domain.Services; using MimeKit; using MimeKit.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace SuiviCompresseur.Notification.Data.Repositories { public class NotificationRepository : INotificationRepository { private readonly Notification_context _context; private readonly IEmailConfiguration _emailConfiguration; public NotificationRepository(Notification_context notification_Context, IEmailConfiguration emailConfiguration) { _context = notification_Context; _emailConfiguration = emailConfiguration; } public IEnumerable<EmailFrom> GetNotifications(string address) { var Notification = _context.EmailTos.Where(t => t.ToAddresses == address && t.Seen == false).Select(v => v.IdMail).ToList(); List<EmailFrom> Notification1 = new List<EmailFrom>(); foreach (var to in Notification) { Notification1.Add(_context.EmailFroms.Find(to)); } //////////////////////////////////////////////////////////////////////////////////////////////// return Notification1; } public string NotificationSeen(Guid Id) { var Notification = _context.EmailTos.Find(Id); if (Notification != null) { Notification.Seen = true; _context.SaveChanges(); return "Update Done"; } return "Notification not exist"; } public string Send(EmailMessage emailMessage) { //try //{ // _notification_Context.EmailFroms.Add(emailFrom); // _notification_Context.EmailTos.AddRange(emailTo); // _notification_Context.SaveChanges(); // return "Email send done"; //} //catch (Exception ex) //{ // return ex.Message; //} var message = new MimeMessage(); try { //message.From.Add(new MailboxAddress(emailMessage.FromAddresses.Address)); foreach (var addto in emailMessage.ToAddresses) { message.To.Add(new MailboxAddress(addto.Address)); } foreach (var addcc in emailMessage.CcAddresses) { message.Cc.Add(new MailboxAddress(addcc.Address)); } foreach (var addccc in emailMessage.CccAddresses) { message.Bcc.Add(new MailboxAddress(addccc.Address)); } //message.To.Add(new MailboxAddress("\"Rached Trabelsi/SIEGE/POULINA\"")); //message.To.AddRange(emailMessage1.ToAddresses.Select(x => new MailboxAddress(x.Address))); //message.To.AddRange(emailMessage1.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address))); //message.From.AddRange(emailMessage1.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address))); //message.From.Add(new MailboxAddress("\"Rached Trabelsi/SIEGE/POULINA\"")); //message.From.Add(new MailboxAddress("\"Rached Trabelsi/SIEGE/POULINA@POULINA\"")); message.Subject = emailMessage.Subject; //We will say we are sending HTML. But there are options for plaintext etc. /////////////////////////////////////////////////////////////////////////////// /// /* message.Body = new TextPart(TextFormat.Html) { Text = emailMessage1.Content }; */ ///////////////////////////////////////////////////////////////////////////html var bodyBuilder1 = new BodyBuilder(); ////////////////////////////////////////////////////////////////////////////var bodyBuilder = new BodyBuilder(); bodyBuilder1.HtmlBody = emailMessage.Content; ////////////////////////////////////////////////////////////////////////////var body = new TextPart("plain") ////////////////////////////////////////////////////////////////////////////{ //////////////////////////////////////////////////////////////////////////// Text = @"Hey" ////////////////////////////////////////////////////////////////////////////}; ////////////////////////////////////////////////////////////////////////////bodyBuilder.TextBody = "This is some plain text"; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// var builder = new BodyBuilder(); var image = builder.LinkedResources.Add(@"./poulinalogo.png"); image.ContentId = MimeUtils.GenerateMessageId(); // Set the html version of the message text builder.HtmlBody = string.Format(@"<br><br><br> <table> <thead> <tr> <td> Rached Trabelsi </td> </tr> </thead> <tbody> <tr> <td>E-Mail : {0}</td> </tr> <tr> <td>Service : Informatique Operationnelle</td> </tr> <tr> <td>Poste : 801249</td> </tr> <tr> <td>GSM : 58278855</td> </tr> </tbody> <tfoot> <center><img src=""cid:{1}""></center> </tfoot> </table>", message.From.ToString(), image.ContentId); var multipart = new Multipart("mixed"); multipart.Add(bodyBuilder1.ToMessageBody()); multipart.Add(builder.ToMessageBody()); var multipart1 = new Multipart("Attachements"); // create an image attachment for the file located at path /// foreach (var path in emailMessage.Files) { var attachment = new MimePart() { Content = new MimeContent(File.OpenRead(path)), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(path) }; multipart1.Add(attachment); } multipart.Add(multipart1); // now set the multipart/mixed as the message body message.Body = multipart; //Be careful that the SmtpClient class is the one from Mailkit not the framework! using (var emailClient = new SmtpClient()) { //The last parameter here is to use SSL (Which you should!) emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, false); //emailClient.Connect("192.168.1.4",25, false); emailClient.Send(message); emailClient.Disconnect(true); EmailFrom emailFrom = new EmailFrom(); emailFrom.FromAddresses = emailMessage.FromAddresses.Address; emailFrom.FromName = emailMessage.FromAddresses.Name; emailFrom.Subject = emailMessage.Subject; emailFrom.Content = emailMessage.Content; emailFrom.SendDate = DateTime.Now; emailFrom.MessageType = "info"; emailFrom.ExceptionMessage = "0"; _context.EmailFroms.Add(emailFrom); foreach (var toemail in emailMessage.ToAddresses) { EmailTo emailTo = new EmailTo(); emailTo.IdMail = emailFrom.IdMail; emailTo.Seen = false; emailTo.ToAddresses = toemail.Address; emailTo.ToName = toemail.Name; emailTo.ReceiveType = "A"; _context.EmailTos.Add(emailTo); } foreach (var toemail in emailMessage.CcAddresses) { EmailTo emailTo = new EmailTo(); emailTo.IdMail = emailFrom.IdMail; emailTo.Seen = false; emailTo.ToAddresses = toemail.Address; emailTo.ToName = toemail.Name; emailTo.ReceiveType = "Cc"; _context.EmailTos.Add(emailTo); } foreach (var toemail in emailMessage.CccAddresses) { EmailTo emailTo = new EmailTo(); emailTo.IdMail = emailFrom.IdMail; emailTo.Seen = false; emailTo.ToAddresses = toemail.Address; emailTo.ToName = toemail.Name; emailTo.ReceiveType = "Ccc"; _context.EmailTos.Add(emailTo); } _context.SaveChanges(); return "Mail success"; } } catch (Exception ex) { EmailFrom emailFrom = new EmailFrom(); emailFrom.FromAddresses = emailMessage.FromAddresses.Address; emailFrom.FromName = emailMessage.FromAddresses.Name; emailFrom.Subject = emailMessage.Subject; emailFrom.Content = emailMessage.Content; emailFrom.SendDate = DateTime.Now; emailFrom.MessageType = "info"; emailFrom.ExceptionMessage = ex.Message; _context.EmailFroms.Add(emailFrom); foreach (var toemail in emailMessage.ToAddresses) { EmailTo emailTo = new EmailTo(); emailTo.IdMail = emailFrom.IdMail; emailTo.Seen = false; emailTo.ToAddresses = toemail.Address; emailTo.ToName = toemail.Name; emailTo.ReceiveType = "A"; _context.EmailTos.Add(emailTo); } foreach (var toemail in emailMessage.CcAddresses) { EmailTo emailTo = new EmailTo(); emailTo.IdMail = emailFrom.IdMail; emailTo.Seen = false; emailTo.ToAddresses = toemail.Address; emailTo.ToName = toemail.Name; emailTo.ReceiveType = "Cc"; _context.EmailTos.Add(emailTo); } foreach (var toemail in emailMessage.CccAddresses) { EmailTo emailTo = new EmailTo(); emailTo.IdMail = emailFrom.IdMail; emailTo.Seen = false; emailTo.ToAddresses = toemail.Address; emailTo.ToName = toemail.Name; emailTo.ReceiveType = "Ccc"; _context.EmailTos.Add(emailTo); } _context.SaveChanges(); return ex.Message; //throw; } } } }
using jaytwo.Common.Collections; using jaytwo.Common.Appendix; using jaytwo.Common.System; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace jaytwo.Common.Http { public static class UrlHelper { public static string Combine(string baseUrl, string path) { if (string.IsNullOrEmpty(baseUrl)) { throw new ArgumentNullException("baseUrl"); } return baseUrl.TrimEnd('/') + "/" + (path ?? string.Empty).TrimStart('/'); } public static string Combine(string baseUrl, params string[] pathSegments) { if (string.IsNullOrEmpty(baseUrl)) { throw new ArgumentNullException("baseUrl"); } var result = baseUrl; if (pathSegments != null) { foreach (var pathSegment in pathSegments) { result = Combine(result, pathSegment); } } return result; } public static Uri Combine(Uri baseUri, string path) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (baseUri.IsAbsoluteUri) { return new Uri(Combine(baseUri.AbsoluteUri, path), UriKind.Absolute); } else { return new Uri(Combine(baseUri.ToString(), path), UriKind.Relative); } } public static Uri Combine(Uri baseUri, params string[] pathSegments) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (baseUri.IsAbsoluteUri) { return new Uri(Combine(baseUri.AbsoluteUri, pathSegments), UriKind.Absolute); } else { return new Uri(Combine(baseUri.ToString(), pathSegments), UriKind.Relative); } } public static Uri Combine(Uri baseUri, Uri pathUri) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (pathUri != null) { return Combine(baseUri, pathUri.ToString()); } else { return CopyUri(baseUri); } } public static Uri CopyUri(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return new Uri(uri.AbsoluteUri, UriKind.Absolute); } else { return new Uri(uri.ToString(), UriKind.Relative); } } public static string GetQueryStringParameterFromUri(Uri uri, string key) { if (uri == null) { throw new ArgumentNullException("uri"); } if (key == null) { throw new ArgumentNullException("key"); } if (uri.IsAbsoluteUri) { return GetQueryStringParameterFromPathOrUrl(uri.AbsoluteUri, key); } else { return GetQueryStringParameterFromPathOrUrl(uri.ToString(), key); } } public static string GetQueryStringParameterFromPathOrUrl(string pathOrUrl, string key) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } var result = GetQueryFromPathOrUrlAsNameValueCollection(pathOrUrl)[key]; return result; } public static Uri SetUriScheme(Uri uri, string newScheme) { if (uri == null) { throw new ArgumentNullException("uri"); } if (newScheme == null) { throw new ArgumentNullException("newScheme"); } if (string.IsNullOrEmpty(newScheme)) { throw new ArgumentException("newScheme cannot be empty"); } if (!uri.IsAbsoluteUri) { throw new InvalidOperationException("Uri must be absolute to set scheme."); } var builder = new UriBuilder(uri); builder.Scheme = newScheme; Uri result; if (uri.IsDefaultPort) { var resultUrl = builder.Uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped); result = new Uri(resultUrl, UriKind.Absolute); } else { result = builder.Uri; } return result; } public static string SetUrlScheme(string url, string newScheme) { if (url == null) { throw new ArgumentNullException("url"); } if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { throw new InvalidOperationException("Uri must be absolute to set scheme."); } var uri = new Uri(url); var result = SetUriScheme(uri, newScheme).AbsoluteUri; return result; } public static Uri SetUriSchemeHttp(Uri uri) { return SetUriScheme(uri, "http"); } public static string SetUrlSchemeHttp(string url) { return SetUrlScheme(url, "http"); } public static Uri SetUriSchemeHttps(Uri uri) { return SetUriScheme(uri, "https"); } public static string SetUrlSchemeHttps(string url) { return SetUrlScheme(url, "https"); } public static Uri SetUriHost(Uri uri, string newHost) { if (uri == null) { throw new ArgumentNullException("uri"); } if (newHost == null) { throw new ArgumentNullException("newHost"); } if (string.IsNullOrEmpty(newHost)) { throw new ArgumentException("newHost cannot be empty"); } if (!uri.IsAbsoluteUri) { throw new InvalidOperationException("Uri must be absolute to set host."); } var builder = new UriBuilder(uri); builder.Host = newHost; return builder.Uri; } public static Uri SetUriHost(Uri uri, string newHost, int? newPort) { var result = uri; result = SetUriHost(result, newHost); result = SetUriPort(result, newPort); return result; } public static string SetUrlHost(string url, string newHost) { if (url == null) { throw new ArgumentNullException("url"); } if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { throw new InvalidOperationException("Uri must be absolute to set host."); } var uri = new Uri(url); var result = SetUriHost(uri, newHost).AbsoluteUri; return result; } public static string SetUrlHost(string url, string newHost, int? newPort) { var result = url; result = SetUrlHost(result, newHost); result = SetUrlPort(result, newPort); return result; } public static Uri SetUriPort(Uri uri, int? newPort) { if (uri == null) { throw new ArgumentNullException("uri"); } if (!uri.IsAbsoluteUri) { throw new InvalidOperationException("Uri must be absolute to set port."); } Uri result; if (newPort.HasValue) { var builder = new UriBuilder(uri); builder.Port = newPort.Value; return builder.Uri; } else { var url = uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped); result = new Uri(url, UriKind.Absolute); } return result; } public static string SetUrlPort(string url, int? newPort) { if (url == null) { throw new ArgumentNullException("newPort"); } if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { throw new InvalidOperationException("Uri must be absolute to set port."); } var uri = new Uri(url); var result = SetUriPort(uri, newPort).AbsoluteUri; return result; } public static Uri SetUriPortHttp(Uri uri) { return SetUriPort(uri, 80); } public static string SetUrlPortHttp(string url) { return SetUrlPort(url, 80); } public static Uri SetUriPortHttps(Uri uri) { return SetUriPort(uri, 443); } public static string SetUrlPortHttps(string url) { return SetUrlPort(url, 443); } public static Uri SetUriPortDefault(Uri uri) { return SetUriPort(uri, null); } public static string SetUrlPortDefault(string url) { return SetUrlPort(url, null); } public static Uri SetUriQuery(Uri uri, NameValueCollection queryStringData) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return new Uri(SetUrlQuery(uri.AbsoluteUri, queryStringData), UriKind.Absolute); } else { return new Uri(SetUrlQuery(uri.ToString(), queryStringData), UriKind.Relative); } } public static string SetUrlQuery(string pathOrUrl, NameValueCollection queryStringData) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var baseUrl = GetPathOrUrlWithoutQuery(pathOrUrl); var queryStringResult = (queryStringData != null && queryStringData.AllKeys.Length > 0) ? "?" + CollectionUtility.ToPercentEncodedQueryString(queryStringData) : string.Empty; string result; if (Uri.IsWellFormedUriString(baseUrl, UriKind.Absolute)) { result = new Uri(baseUrl).AbsoluteUri + queryStringResult; } else { result = baseUrl + queryStringResult; } return result; } public static Uri AddUriQueryStringParameter<T>(Uri uri, string key, T value) { var valueString = string.Format(CultureInfo.InvariantCulture, "{0}", value); return AddUriQueryStringParameter(uri, key, valueString); } public static Uri AddUriQueryStringParameter(Uri uri, string key, object value) { return AddUriQueryStringParameter<object>(uri, key, value); } public static Uri AddUriQueryStringParameter(Uri uri, string key, string value) { if (uri == null) { throw new ArgumentNullException("uri"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (uri.IsAbsoluteUri) { return new Uri(AddUrlQueryStringParameter(uri.AbsoluteUri, key, value), UriKind.Absolute); } else { return new Uri(AddUrlQueryStringParameter(uri.ToString(), key, value), UriKind.Relative); } } public static string AddUrlQueryStringParameter<T>(string pathOrUrl, string key, T value) { var valueString = string.Format(CultureInfo.InvariantCulture, "{0}", value); return AddUrlQueryStringParameter(pathOrUrl, key, valueString); } public static string AddUrlQueryStringParameter(string pathOrUrl, string key, object value) { return AddUrlQueryStringParameter<object>(pathOrUrl, key, value); } public static string AddUrlQueryStringParameter(string pathOrUrl, string key, string value) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } var query = GetQueryFromPathOrUrlAsNameValueCollection(pathOrUrl); query.Add(key, value); var result = SetUrlQuery(pathOrUrl, query); return result; } public static string SetUrlQueryStringParameter<T>(string pathOrUrl, string key, T value) { var valueString = string.Format(CultureInfo.InvariantCulture, "{0}", value); return SetUrlQueryStringParameter(pathOrUrl, key, valueString); } public static string SetUrlQueryStringParameter(string pathOrUrl, string key, object value) { return SetUrlQueryStringParameter<object>(pathOrUrl, key, value); } public static string SetUrlQueryStringParameter(string pathOrUrl, string key, string value) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } var query = GetQueryFromPathOrUrlAsNameValueCollection(pathOrUrl); query.Set(key, value); var result = SetUrlQuery(pathOrUrl, query); return result; } public static string RemoveUrlQueryStringParameter(string pathOrUrl, string key) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } var query = GetQueryFromPathOrUrlAsNameValueCollection(pathOrUrl); query.Remove(key); var result = SetUrlQuery(pathOrUrl, query); return result; } public static Uri SetUriQueryStringParameter<T>(Uri uri, string key, T value) { var valueString = string.Format(CultureInfo.InvariantCulture, "{0}", value); return SetUriQueryStringParameter(uri, key, valueString); } public static Uri SetUriQueryStringParameter(Uri uri, string key, object value) { return SetUriQueryStringParameter<object>(uri, key, value); } public static Uri SetUriQueryStringParameter(Uri uri, string key, string value) { if (uri == null) { throw new ArgumentNullException("uri"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (uri.IsAbsoluteUri) { return new Uri(SetUrlQueryStringParameter(uri.AbsoluteUri, key, value), UriKind.Absolute); } else { return new Uri(SetUrlQueryStringParameter(uri.ToString(), key, value), UriKind.Relative); } } public static Uri RemoveUriQueryStringParameter(Uri uri, string key) { if (uri == null) { throw new ArgumentNullException("uri"); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (uri.IsAbsoluteUri) { return new Uri(RemoveUrlQueryStringParameter(uri.AbsoluteUri, key), UriKind.Absolute); } else { return new Uri(RemoveUrlQueryStringParameter(uri.ToString(), key), UriKind.Relative); } } public static Uri GetUriWithoutQuery(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return new Uri(GetPathOrUrlWithoutQuery(uri.AbsoluteUri), UriKind.Absolute); } else { return new Uri(GetPathOrUrlWithoutQuery(uri.ToString()), UriKind.Relative); } } public static string GetPathOrUrlWithoutQuery(string pathOrUrl) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var queryStringStartPosition = pathOrUrl.IndexOf('?'); var result = (queryStringStartPosition >= 0) ? pathOrUrl.Substring(0, queryStringStartPosition) : pathOrUrl; return result; } public static string GetQueryFromUri(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return GetQueryFromPathOrUrl(uri.AbsoluteUri); } else { return GetQueryFromPathOrUrl(uri.ToString()); } } public static string GetQueryFromPathOrUrl(string pathOrUrl) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var queryStringStartPosition = pathOrUrl.IndexOf('?'); var result = (queryStringStartPosition >= 0) ? pathOrUrl.Substring(queryStringStartPosition + 1) : string.Empty; return result; } public static string GetFileNameWithoutQuery(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return GetFileNameWithoutQuery(uri.AbsoluteUri); } else { return GetFileNameWithoutQuery(uri.ToString()); } } public static string GetFileNameWithoutQuery(string pathOrUrl) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var urlWithoutQuery = GetPathOrUrlWithoutQuery(pathOrUrl); return GetFileNameAndQuery(urlWithoutQuery); } public static string GetFileNameAndQuery(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return GetFileNameAndQuery(uri.AbsoluteUri); } else { return GetFileNameAndQuery(uri.ToString()); } } public static string GetFileNameAndQuery(string pathOrUrl) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var lastSlashPosition = pathOrUrl.LastIndexOf('/'); if (lastSlashPosition >= 0) { return pathOrUrl.Substring(lastSlashPosition + 1); } else { throw new ArgumentException("Unable to parse path or url directory from file name."); } } public static Uri GetUriWithoutFileNameAndQuery(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (uri.IsAbsoluteUri) { return new Uri(GetPathOrUrlWithoutFileNameAndQuery(uri.AbsoluteUri), UriKind.Absolute); } else { return new Uri(GetPathOrUrlWithoutFileNameAndQuery(uri.ToString()), UriKind.Relative); } } public static string GetPathOrUrlWithoutFileNameAndQuery(string pathOrUrl) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var lastSlashPosition = pathOrUrl.LastIndexOf('/'); if (lastSlashPosition >= 0) { return pathOrUrl.Substring(0, lastSlashPosition + 1); } else { throw new ArgumentException("Unable to parse path or url directory from file name."); } } public static NameValueCollection GetQueryFromPathOrUrlAsNameValueCollection(string pathOrUrl) { if (pathOrUrl == null) { throw new ArgumentNullException("pathOrUrl"); } var query = GetQueryFromPathOrUrl(pathOrUrl); return InternalScabHelpers.ParseQueryString(query); } public static NameValueCollection GetQueryFromUriAsNameValueCollection(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } var query = GetQueryFromUri(uri); return InternalScabHelpers.ParseQueryString(query); } private static readonly Regex percentEncoderRegex = new Regex(@"[^A-Za-z0-9_.~]", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static string PercentEncode(string value) { if (value != null) { return percentEncoderRegex.Replace(value, PercentEncoderMatchEvaluator); } else { return null; } } private static readonly Regex percentEncoderPathRegex = new Regex(@"[^A-Za-z0-9_.~/]", RegexOptions.Compiled | RegexOptions.CultureInvariant); public static string PercentEncodePath(string value) { if (value != null) { return percentEncoderPathRegex.Replace(value, PercentEncoderMatchEvaluator); } else { return null; } } private static string PercentEncoderMatchEvaluator(Match match) { byte[] bytes = Encoding.UTF8.GetBytes(match.Value); StringBuilder encoded = new StringBuilder(); foreach (byte b in bytes) { encoded.AppendFormat("%{0:X2}", b); } return encoded.ToString(); } } }
namespace BlazorShared.Models.Client { public class DeleteClientRequest : BaseRequest { public int Id { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; namespace com.zhifez.seagj { [ System.Serializable ] public class MachineLink { public TransmissionMachine tm; public SateliteDish sat; public MachineLink ( TransmissionMachine tm, SateliteDish sat ) { this.tm = tm; this.sat = sat; } } public class GameController : Base { public static GameController instance; public bool isHardMode; public Transform playerStartPos; public Transform endLookPos; public TransmissionMachine[] tmMachines; public Kiosk[] tmKiosks; public SateliteDish[] satDishes; public Kiosk[] satKiosks; private TransmissionMachine activeTmMachine; private SateliteDish activeSatDish; public List<ServiceStatus> serviceStatuses; private int _enabledTmMachineCount = 0; public int enabledTmMachineCount { get { return _enabledTmMachineCount; } set { _enabledTmMachineCount = value; for ( int a=0; a<tmMachines.Length; ++a ) { tmMachines[a].gameObject.SetActive ( a < _enabledTmMachineCount ); tmMachines[a].enabled = ( a < _enabledTmMachineCount ); tmKiosks[a].gameObject.SetActive ( a < _enabledTmMachineCount ); } } } private int _enabledSatDishCount; public int enabledSatDishCount { get { return _enabledSatDishCount; } set { _enabledSatDishCount = value; for ( int a=0; a<satDishes.Length; ++a ) { satDishes[a].enabled = ( a < _enabledSatDishCount ); satKiosks[a].gameObject.SetActive ( a < _enabledSatDishCount ); } } } //-------------------------------------------------- // state machine //-------------------------------------------------- public enum State { none, start, idle, manage_overall, manage_satelite, manage_tm, results } private State _currentState = State.idle; public State currentState { get { return _currentState; } set { if ( _currentState == value ) { return; } _currentState = value; // next state switch ( _currentState ) { case State.start: SCIENTIST.enabled = false; SCIENTIST.Respawn ( playerStartPos ); CAMERA.SetLookAtTarget ( endLookPos ); UI_GAME.SetLabelsAlpha ( 0f ); UI_START.enabled = true; UI_END.enabled = false; break; case State.idle: UI_GAME.SetLabelsAlpha ( 1.0f ); UI_END.enabled = false; break; case State.manage_overall: case State.manage_satelite: case State.manage_tm: case State.results: UI_GAME.SetLabelsAlpha ( 0.2f ); break; } } } private void State_start () { if ( Input.GetKeyDown ( KeyCode.Space ) ) { AudioController.Play ( "ui_btn_direction_section" ); UI_START.enabled = false; PLAYER_STATS.BeginTimer (); CAMERA.SetLookAtTarget ( null ); UI_GAME.SetLabelsAlpha ( 1.0f ); SCIENTIST.enabled = true; DATA_PACKAGE.enabled = true; currentState = State.idle; } } private void State_manage_overall () { if ( Input.GetKeyDown ( KeyCode.Escape ) ) { AudioController.Play ( "ui_btn_direction" ); StopManageOverall (); return; } if ( Input.GetKeyDown ( KeyCode.Q ) ) { AudioController.Play ( "ui_btn_direction_section" ); UI_MAIN.GoToPrevSection (); } if ( Input.GetKeyDown ( KeyCode.E ) ) { AudioController.Play ( "ui_btn_direction_section" ); UI_MAIN.GoToNextSection (); } } private void State_manage_satelite () { if ( Input.GetKeyDown ( KeyCode.Escape ) ) { AudioController.Play ( "ui_btn_direction" ); StopManageSatelite (); return; } float _offset = 0.1f; if ( INPUT_HOR < -_offset || INPUT_HOR > _offset || INPUT_VER < -_offset || INPUT_VER > _offset ) { if ( INPUT_HOR < -_offset || INPUT_HOR > _offset ) { activeSatDish.RotateDish ( INPUT_HOR, "Horizontal" ); } if ( INPUT_VER < -_offset || INPUT_VER > _offset ) { activeSatDish.RotateDish ( INPUT_VER, "Vertical" ); } } else { activeSatDish.RotateDish ( 0 ); } UI_SAT.UpdateValues ( activeSatDish.valueX, activeSatDish.valueY ); } private void State_manage_tm () { if ( Input.GetKeyDown ( KeyCode.Escape ) ) { AudioController.Play ( "ui_btn_direction" ); StopManageTM (); return; } if ( Input.GetKeyDown ( KeyCode.W ) || Input.GetKeyDown ( KeyCode.UpArrow ) ) { AudioController.Play ( "ui_btn_direction" ); activeTmMachine.SelectPrevLinkedSatDish (); } if ( Input.GetKeyDown ( KeyCode.S ) || Input.GetKeyDown ( KeyCode.DownArrow ) ) { AudioController.Play ( "ui_btn_direction" ); activeTmMachine.SelectNextLinkedSatDish (); } if ( Input.GetKeyDown ( KeyCode.A ) || Input.GetKeyDown ( KeyCode.LeftArrow ) ) { AudioController.Play ( "ui_btn_direction" ); activeTmMachine.DecrementSignalOffset (); } if ( Input.GetKeyDown ( KeyCode.D ) || Input.GetKeyDown ( KeyCode.RightArrow ) ) { AudioController.Play ( "ui_btn_direction" ); activeTmMachine.IncrementSignalOffset (); } UI_TM.UpdateValues ( activeTmMachine ); } private void RunState () { switch ( currentState ) { case State.start: State_start (); break; case State.manage_overall: State_manage_overall (); break; case State.manage_satelite: State_manage_satelite (); break; case State.manage_tm: State_manage_tm (); break; } } //-------------------------------------------------- // private //-------------------------------------------------- //-------------------------------------------------- // public //-------------------------------------------------- public bool isIdle { get { return currentState == State.idle; } } public void ManageOverall () { currentState = State.manage_overall; UI_MAIN.enabled = true; SCIENTIST.enabled = false; CAMERA.SetLookAtTarget ( transform ); } private void StopManageOverall () { currentState = State.idle; UI_MAIN.enabled = false; SCIENTIST.enabled = true; CAMERA.SetLookAtTarget ( null ); } public void ManageSatelite ( string sateliteId ) { currentState = State.manage_satelite; SCIENTIST.enabled = false; foreach ( SateliteDish satDish in satDishes ) { if ( satDish.name.Equals ( sateliteId ) ) { activeSatDish = satDish; break; } } UI_SAT.Setup ( activeSatDish ); CAMERA.SetLookAtTarget ( activeSatDish.transform, playerStartPos ); } private void StopManageSatelite () { currentState = State.idle; UI_SAT.enabled = false; SCIENTIST.enabled = true; activeSatDish.RotateDish ( 0 ); activeSatDish = null; CAMERA.SetLookAtTarget ( null ); } public void ManageTM ( string tmId ) { currentState = State.manage_tm; SCIENTIST.enabled = false; foreach ( TransmissionMachine tm in tmMachines ) { if ( tm.name.Equals ( tmId ) ) { activeTmMachine = tm; break; } } UI_TM.Setup ( activeTmMachine ); CAMERA.SetLookAtTarget ( activeTmMachine.transform ); } private void StopManageTM () { currentState = State.idle; UI_TM.enabled = false; SCIENTIST.enabled = true; activeTmMachine = null; CAMERA.SetLookAtTarget ( null ); } public int TotalEnabledAllServices () { List<DataPackage.Service> _services = new List<DataPackage.Service> (); foreach ( ServiceStatus ss in serviceStatuses ) { if ( !_services.Contains ( ss.service ) ) { _services.Add ( ss.service ); } } return _services.Count; } public bool HasEnabledAllServices () { List<DataPackage.Service> _services = new List<DataPackage.Service> (); foreach ( ServiceStatus ss in serviceStatuses ) { if ( !_services.Contains ( ss.service ) ) { _services.Add ( ss.service ); } } return ( _services.Count >= DATA_PACKAGE.serviceSignalPatterns.Length ); } public void AddServiceStatus ( ServiceStatus _status ) { foreach ( ServiceStatus ss in serviceStatuses ) { if ( ss.service == _status.service && ss.tmMachineId.Equals ( _status.tmMachineId ) ) { ss.isStable = _status.isStable; return; } } serviceStatuses.Add ( _status ); } public void RemoveServiceStatus ( ServiceStatus _status ) { for ( int a=0; a<serviceStatuses.Count; ++a ) { ServiceStatus ss = serviceStatuses[a]; if ( ss.service == _status.service && ss.tmMachineId.Equals ( _status.tmMachineId ) ) { serviceStatuses.RemoveAt ( a ); break; } } } public bool HasService ( DataPackage.Service _service ) { foreach ( ServiceStatus ss in serviceStatuses ) { if ( ss.service == _service ) { return true; } } return false; } public int GetSameServiceCount ( DataPackage.Service _service ) { int _total = 0; foreach ( ServiceStatus ss in serviceStatuses ) { if ( ss.service == _service ) { ++_total; } } return _total; } public float GetServiceMultiplier ( DataPackage.Service _service ) { float _multiplier = 0f; foreach ( ServiceStatus ss in serviceStatuses ) { if ( ss.service == _service ) { _multiplier += ss.isStable ? 1f : 0.5f; } } return _multiplier; } public void StartGame () { currentState = State.start; } public void EndGame () { currentState = State.results; SCIENTIST.Respawn ( playerStartPos ); SCIENTIST.enabled = false; DATA_PACKAGE.enabled = false; UI_MAIN.enabled = false; UI_TM.enabled = false; UI_SAT.enabled = false; UI_END.enabled = true; CAMERA.SetLookAtTarget ( endLookPos ); } public void RestartGame () { UI_END.enabled = false; foreach ( TransmissionMachine tm in tmMachines ) { tm.enabled = false; } enabledTmMachineCount = 1; foreach ( SateliteDish sd in satDishes ) { sd.enabled = false; } enabledSatDishCount = 1; tmMachines[0].LinkSateliteDish ( satDishes[0], 0f, 0f ); serviceStatuses.Clear (); DATA_PACKAGE.Reboot (); UI_MAIN.Reboot (); PLAYER_STATS.Init (); currentState = State.start; } //-------------------------------------------------- // protected //-------------------------------------------------- protected void Awake () { instance = this; } protected void Start () { for ( int a=0; a<tmMachines.Length; ++a ) { tmKiosks[a].linkId = tmMachines[a].name; } enabledTmMachineCount = 1; for ( int a=0; a<satDishes.Length; ++a ) { satKiosks[a].linkId = satDishes[a].name; } enabledSatDishCount = 1; serviceStatuses = new List<ServiceStatus> (); DOVirtual.DelayedCall ( 1f, () => { RestartGame (); } ); AudioController.PlayAmbienceSound ( "factory_ambience" ); } protected void Update () { RunState (); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp7 { class Program { static void Main(string[] args) { Console.WriteLine("Please enter a number."); string stringinput = Console.ReadLine(); int numberinput = Convert.ToInt32(stringinput); bool result = (numberinput % 2 == 0); if (result == true) Console.WriteLine("This is an even number."); else Console.WriteLine("This is an odd number."); Console.ReadKey(); } } }
using Azure; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Azure.Storage.Blobs.Specialized; using BDTest.Maps; using BDTest.NetCore.Razor.ReportMiddleware.Interfaces; using BDTest.NetCore.Razor.ReportMiddleware.Models; using Newtonsoft.Json; namespace BDTest.ReportGenerator.RazorServer; public class AzureStorageDataStore : IBDTestDataStore { private readonly BlobContainerClient _testRunSummariesContainer; private readonly BlobContainerClient _testDataContainer; private readonly JsonSerializer _jsonSerializer = JsonSerializer.Create(); public AzureStorageDataStore(AzureStorageConfig azureStorageConfig) { var connectionString = azureStorageConfig.ConnectionString; var blobClient = new BlobServiceClient(connectionString); _testRunSummariesContainer = blobClient.GetBlobContainerClient("test-runs-summaries"); _testRunSummariesContainer.CreateIfNotExists(); _testDataContainer = blobClient.GetBlobContainerClient("test-data"); _testDataContainer.CreateIfNotExists(); } public async Task<BDTestOutputModel> GetTestData(string id, CancellationToken cancellationToken) { try { var blobData = await _testDataContainer.GetBlockBlobClient(id).DownloadAsync(cancellationToken); return _jsonSerializer.Deserialize<BDTestOutputModel>(new JsonTextReader(new StreamReader(blobData.Value.Content))); } catch (RequestFailedException e) when(e.Status == 404) { return null; } } public Task DeleteTestData(string id) { return _testRunSummariesContainer.DeleteBlobIfExistsAsync(id); } public async Task<IEnumerable<TestRunSummary>> GetAllTestRunRecords() { var testRunSummaries = new List<TestRunSummary>(); var amountToTake = 50; var count = 0; await foreach (var blobItem in _testRunSummariesContainer.GetBlobsAsync()) { count++; var downloadAsync = await _testRunSummariesContainer.GetBlockBlobClient(blobItem.Name).DownloadAsync(); var testRunSummary = _jsonSerializer.Deserialize<TestRunSummary>(new JsonTextReader(new StreamReader(downloadAsync.Value.Content))); if (blobItem.Properties.CreatedOn < DateTimeOffset.UtcNow - TimeSpan.FromDays(30)) { await DeleteBlobItem(blobItem); } else { testRunSummaries.Add(testRunSummary); } if (count == amountToTake) { break; } } return testRunSummaries.ToArray(); } private async Task DeleteBlobItem(BlobItem blobItem) { await Task.WhenAll( DeleteTestData(blobItem.Name), DeleteTestRunRecord(blobItem.Name) ); } public Task StoreTestData(string id, BDTestOutputModel data) { return _testDataContainer.GetBlockBlobClient(id).UploadAsync(data.AsStream()); } public Task StoreTestRunRecord(TestRunSummary testRunSummary) { return _testRunSummariesContainer.GetBlockBlobClient(testRunSummary.RecordId).UploadAsync(testRunSummary.AsStream()); } public Task DeleteTestRunRecord(string id) { return _testDataContainer.DeleteBlobIfExistsAsync(id); } public Task InitializeAsync() { return GetAllTestRunRecords(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum ObjectiveType { None, Destroy, PositionChild, Isolate, Activate } [System.Serializable] public class Objective { public ObjectiveType type; public Interactable[] relatedObjects; public GameObject[] relatedGameObjects; bool setup; public bool[] activatedObjects; [Header("Position child parameters:")] public GameObject[] toPositionObjects; public bool strict; public ZoneBehaviour positionZone; List<GameObject> positionnedObjects; [HideInInspector] public bool validated; public void CheckValid() { switch (type) { case ObjectiveType.None: break; case ObjectiveType.Destroy: CheckDestroyed(); break; case ObjectiveType.PositionChild: CheckPositionned(); break; case ObjectiveType.Isolate: CheckIsolation(); break; case ObjectiveType.Activate: if (!setup) { setup = true; activatedObjects = new bool[relatedObjects.Length]; for (int i = 0; i < relatedObjects.Length; i++) { relatedObjects[i].ActionEvent += CheckActivate; } } break; } } void CheckDestroyed() { for (int i = 0; i < relatedObjects.Length; i++) { if (relatedObjects[i] != null/* && relatedObjects[i].enabled*/) { return; } } Debug.Log ("About to win"); Validate(); } void CheckPositionned() { if (ZoneBehaviour.instance != null) { if (ZoneBehaviour.instance.collidingObjects.Count >= toPositionObjects.Length) { Validate(); } } } void CheckIsolation() { //related game objects : 0 = SphereCollider / 1 = Bridge if(relatedGameObjects[0].GetComponent<LD4CollisionAI>().douglasIsolated && !relatedGameObjects[1].GetComponent<BridgeSwitcher>().opened) { Validate(); } } void CheckActivate(Interactable script) { for (int i = 0; i < relatedObjects.Length; i++) { if (script == relatedObjects[i]) { activatedObjects[i] = true; } } for (int i = 0; i < activatedObjects.Length; i++) { if (!activatedObjects[i]) { return; } else { Validate(); } } } void Validate() { validated = true; Debug.Log("Validate"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class StateDisableMode : State { public StateDisableMode(StateMachine owner) : base(owner) { this.owner = owner; } public override List<Object> myItems { get { return null; } } public override TextAsset[] mySaves { get{return null;} } public override void OnEnter() { Debug.Log("Enter DisableMode"); } public override void OnExit() { throw new System.NotImplementedException(); } public override void OnGUI() { throw new System.NotImplementedException(); } public override void OnUpdate() { throw new System.NotImplementedException(); } public override void OnPopUp(int windowType) { throw new System.NotImplementedException(); } public override void OnSave(string myString) { throw new System.NotImplementedException(); } public override void OnLoad(string myString) { throw new System.NotImplementedException(); } }
using UnityEngine; using System.Collections; using System; public class PlatformMove: MonoBehaviour { [SerializeField] private Transform[] waypoints; [SerializeField] private float speed; [SerializeField] private bool loop; [SerializeField] private int timesRepeat; [SerializeField] private bool moveWhenPlayer; public bool activate = false; private Vector2 originalPosition; private Rigidbody2D rb2d; private Vector3 nextPoint = Vector2.zero; private Vector3 moveVector = Vector2.zero; private int nextWaypointIndex = 0; private bool ballCollide = false; void Awake() { originalPosition = this.transform.position; if (waypoints.Length > 0) { transform.position = waypoints[0].position; CalculateNextWaypoint(); } } void LateUpdate() { if (moveWhenPlayer == true) { if (activate == true) Move(); } else Move(); } private void CalculateNextWaypoint() { nextWaypointIndex++; if (nextWaypointIndex == waypoints.Length) nextWaypointIndex = 0; nextPoint = waypoints[nextWaypointIndex].position; moveVector = nextPoint - transform.position; moveVector.Normalize(); } private void Move() { //PLATAFORMAS if (this.gameObject.layer==8) { if (moveWhenPlayer == true) { if (Vector3.Distance(transform.position, waypoints[0].position) < 0.5f && !ballCollide) { transform.position = waypoints[0].position; activate = false; } } transform.Translate(moveVector * speed * Time.deltaTime, Space.World); if (Vector3.Distance(transform.position, nextPoint) < 0.5f) { CalculateNextWaypoint(); } } //ENEMIGOS if (this.gameObject.layer == 14) { transform.Translate(moveVector * speed * Time.deltaTime, Space.World); if (Vector3.Distance(transform.position, nextPoint) < 0.5f) { CalculateNextWaypoint(); } } } public void ResetPosition() { this.transform.position = originalPosition; nextWaypointIndex = 0; nextPoint = Vector2.zero; moveVector = Vector2.zero; CalculateNextWaypoint(); this.activate = false; } private void OnCollisionEnter2D(Collision2D collision) { if(collision.gameObject.tag == "Ball") ballCollide = true; } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.tag == "Ball") ballCollide = false; } }
// Copyright (c) 2017 Gwaredd Mountain, https://opensource.org/licenses/MIT #if !UNIUM_DISABLE && ( DEVELOPMENT_BUILD || UNITY_EDITOR || UNIUM_ENABLE ) using System; using System.IO; using System.Collections.Generic; using System.Text; namespace gw.proto.http { //////////////////////////////////////////////////////////////////////////////// public class HttpResponse { Stream mStream = null; bool mHeadersWritten = false; public bool IsClosed { get; private set; } public Encoding Encoding = Encoding.UTF8; public int Code = 200; public string Reason = "OK"; public Dictionary<string,string> Headers = new Dictionary<string, string>(); //------------------------------------------------------------------------------ public HttpResponse( Stream stream ) { IsClosed = false; mStream = stream; } //------------------------------------------------------------------------------ public void Response( ResponseCode code, string reason = null ) { Code = (int) code; Reason = reason != null ? reason : HttpUtils.CodeToString( code ); } public void Close() { if( mHeadersWritten == false ) { WriteHeaders(); } if( IsClosed == false ) { mStream.Flush(); mStream.Close(); mStream.Dispose(); } IsClosed = true; } public void Abort() { mStream.Close(); mStream.Dispose(); IsClosed = true; } //------------------------------------------------------------------------------ public void Send( string str ) { Send( Encoding.GetBytes( str ) ); } public void Send( byte[] bytes ) { Headers[ "Connection" ] = "close"; WriteHeaders(); mStream.Write( bytes, 0, bytes.Length ); Close(); } public void SendAsync( byte[] bytes ) { Headers[ "Connection" ] = "close"; WriteHeaders(); mStream.BeginRead( bytes, 0, bytes.Length, OnSent, this ); } void OnSent( IAsyncResult res ) { mStream.EndWrite( res ); Close(); } //------------------------------------------------------------------------------ public void WriteHeaders() { if( mHeadersWritten || IsClosed ) { throw new HttpResponseException( ResponseCode.InternalServerError ); } mHeadersWritten = true; var str = new StringBuilder(); str.AppendFormat( "HTTP/1.1 {0} {1}\r\n", Code, Reason ); foreach( var item in Headers ) { str.AppendFormat( "{0}: {1}\r\n", item.Key, item.Value ); } str.Append( "\r\n" ); var bytes = Encoding.ASCII.GetBytes( str.ToString() ); mStream.Write( bytes, 0, bytes.Length ); } //------------------------------------------------------------------------------ public void Redirect( string url ) { Code = (int) ResponseCode.MovedPermanently; Reason = HttpUtils.CodeToString( ResponseCode.MovedPermanently ); Headers[ "Location" ] = url; Headers[ "Connection" ] = "close"; WriteHeaders(); Close(); } public void Reject( ResponseCode code ) { Code = (int) code; Reason = HttpUtils.CodeToString( code ); Headers[ "Connection" ] = "close"; WriteHeaders(); Close(); } } } #endif
using System; using System.Linq; using System.Windows.Forms; using System.Collections.Generic; using com.Sconit.SmartDevice.SmartDeviceRef; using System.Web.Services.Protocols; namespace com.Sconit.SmartDevice { public partial class UCPurchaseReturn : UCBase { //public event MainForm.ModuleSelectHandler ModuleSelectionEvent; private static UCPurchaseReturn usPurchaseReturn; private static object obj = new object(); private List<OrderMaster> orderMasters; private DateTime? effDate; private Boolean isOpPallet; public UCPurchaseReturn(User user) : base(user) { this.InitializeComponent(); base.btnOrder.Text = "退货"; isOpPallet = false; } public static UCPurchaseReturn GetUCPurchaseReturn(User user) { if (usPurchaseReturn == null) { lock (obj) { if (usPurchaseReturn == null) { usPurchaseReturn = new UCPurchaseReturn(user); } } } usPurchaseReturn.user = user; usPurchaseReturn.Reset(); return usPurchaseReturn; } protected override void ScanBarCode() { base.ScanBarCode(); if (base.op == CodeMaster.BarCodeType.ORD.ToString()) { if (orderMasters == null) { this.Reset(); orderMasters = new List<OrderMaster>(); } var orderMaster = base.smartDeviceService.GetOrder(base.barCode, true); //检查订单类型 if (orderMaster.Type != OrderType.Procurement && orderMaster.SubType != OrderSubType.Return) { throw new BusinessException("扫描的不是采购退货单。"); } if (!orderMaster.IsShipByOrder) { throw new BusinessException("不允许按订单退货。"); } //检查订单状态 if (orderMaster.Status != OrderStatus.Submit && orderMaster.Status != OrderStatus.InProcess) { throw new BusinessException("不是释放或执行中状态不能退货"); } this.MergeOrderMaster(orderMaster); } else if (base.op == CodeMaster.BarCodeType.HU.ToString()) { if (this.orderMasters == null || this.orderMasters.Count() == 0) { throw new BusinessException("请先扫描订单"); } Hu hu = smartDeviceService.GetHu(base.barCode); //if (!string.IsNullOrEmpty(hu.PalletCode)) //{ // throw new BusinessException("条码已与托盘绑定,请扫描托盘。"); //} this.MatchHu(hu); } else if (base.op == CodeMaster.BarCodeType.TP.ToString()) { if (this.orderMasters == null || this.orderMasters.Count() == 0) { throw new BusinessException("请先扫描订单"); } Hu[] huList = smartDeviceService.GetHuListByPallet(base.barCode); if (huList != null && huList.Count() > 0) { foreach (Hu hu in huList) { this.MatchHu(hu); } } isOpPallet = true; } else if (base.op == CodeMaster.BarCodeType.DATE.ToString()) { base.barCode = base.barCode.Substring(2, base.barCode.Length - 2); this.effDate = base.smartDeviceService.GetEffDate(base.barCode); this.lblMessage.Text = "生效时间:" + this.effDate.Value.ToString("yyyy-MM-dd HH:mm"); this.tbBarCode.Text = string.Empty; this.tbBarCode.Focus(); } else { throw new BusinessException("条码格式不合法"); } } protected override void gvListDataBind() { base.gvListDataBind(); List<OrderDetail> orderDetailList = new List<OrderDetail>(); if (this.orderMasters != null) { foreach (var om in this.orderMasters) { orderDetailList.AddRange(om.OrderDetails.Where(o => o.CurrentQty != 0)); } } base.dgList.DataSource = orderDetailList; base.ts.MappingName = orderDetailList.GetType().Name; } protected override void Reset() { this.orderMasters = new List<OrderMaster>(); base.Reset(); this.lblMessage.Text = "请扫描订单"; this.effDate = null; } protected override void DoSubmit() { try { if (this.orderMasters == null || this.orderMasters.Count == 0) { throw new BusinessException("请先扫描订单。"); } List<OrderDetail> orderDetailList = new List<OrderDetail>(); List<OrderDetailInput> orderDetailInputList = new List<OrderDetailInput>(); foreach (var om in orderMasters) { if (om.OrderDetails != null) { orderDetailList.AddRange(om.OrderDetails); } } if (orderDetailList.Any(od => od.CurrentQty > 0)) { DialogResult dr = MessageBox.Show("本次退货有未发完的明细,是否继续?", "未全部退货", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (dr == DialogResult.No) { return; } } foreach (var orderDetail in orderDetailList) { if (orderDetail.OrderDetailInputs != null) { orderDetailInputList.AddRange(orderDetail.OrderDetailInputs); } } if (orderDetailInputList.Count == 0) { throw new BusinessException("没有扫描条码"); } if (this.orderMasters.Count > 1) { if (this.orderMasters[0].OrderStrategy == FlowStrategy.KIT) { throw new BusinessException("KIT单不能合并退货。"); } if (this.orderMasters[0].OrderDetails.Count(o => o.CurrentQty != 0) > 0) { throw new BusinessException("必须满足KIT单退货的退货数。"); } } string ipNo = this.smartDeviceService.DoShipOrder(orderDetailInputList.ToArray(), this.effDate, this.user.Code,isOpPallet); this.Reset(); base.lblMessage.Text = string.Format("退货成功,送货单:{0}", ipNo); this.isMark = true; } catch (Exception ex) { this.isMark = true; this.tbBarCode.Text = string.Empty; this.tbBarCode.Focus(); Utility.ShowMessageBox(ex.Message); } } private void MatchHu(Hu hu) { base.CheckHu(hu); if (!Utility.HasPermission(user.Permissions, null, true, false, hu.Region, null)) { throw new BusinessException("没有此条码的权限"); } if (!base.isCancel) { #region 条码匹配 if (hu.Status != HuStatus.Location) { throw new BusinessException("条码不在库位中"); } var orderDetails = new List<OrderDetail>(); var orderMaster = this.orderMasters.First(); string huId = hu.HuId; //先按开始日期排序,在按订单序号排序 foreach (var om in orderMasters.OrderBy(o => o.StartTime)) { orderDetails.AddRange(om.OrderDetails.Where(o => o.OrderedQty > o.ShippedQty).OrderBy(o => o.Sequence)); } orderDetails = orderDetails.OrderByDescending(p => p.CurrentQty).ToList(); var matchedOrderDetailList = orderDetails.Where(o => o.Item == hu.Item); if (matchedOrderDetailList == null || matchedOrderDetailList.Count() == 0) { throw new BusinessException("没有找到和条码{0}的物料号{1}匹配的订单明细。", huId, hu.Item); } matchedOrderDetailList = matchedOrderDetailList.Where(o => o.Uom.Equals(hu.Uom, StringComparison.OrdinalIgnoreCase)); if (matchedOrderDetailList == null || matchedOrderDetailList.Count() == 0) { throw new BusinessException("没有找到和条码{0}的单位{1}匹配的订单明细。", huId, hu.Uom); } matchedOrderDetailList = matchedOrderDetailList.Where(o => o.LocationFrom.Equals(hu.Location, StringComparison.OrdinalIgnoreCase)); if (matchedOrderDetailList == null || matchedOrderDetailList.Count() == 0) { throw new BusinessException("没有找到和条码{0}的库位{1}匹配的订单明细。", huId, hu.Location); } if (orderMaster.IsShipFulfillUC) { matchedOrderDetailList = matchedOrderDetailList.Where(o => o.UnitCount == hu.UnitCount); if (matchedOrderDetailList == null || matchedOrderDetailList.Count() == 0) { throw new BusinessException("没有找到和条码{0}的包装数{1}匹配的订单明细。", huId, hu.UnitCount.ToString()); } } matchedOrderDetailList = matchedOrderDetailList.Where(o => o.QualityType == hu.QualityType); if (matchedOrderDetailList == null || matchedOrderDetailList.Count() == 0) { throw new BusinessException("没有找到和条码{0}的质量状态匹配的订单明细。", huId); } //matchedOrderDetailList = matchedOrderDetailList.Where(o => // (string.IsNullOrEmpty(o.Direction) && string.IsNullOrEmpty(hu.Direction)) || // (!string.IsNullOrEmpty(o.Direction) && o.Direction == hu.Direction)); //if (matchedOrderDetailList == null || matchedOrderDetailList.Count() == 0) //{ // throw new BusinessException("没有找到和条码{0}的方向匹配的订单明细。", huId); //} #region 先匹配未满足订单退货数的(未超发的) //OrderDetail matchedOrderDetail = MatchOrderDetail(hu, matchedOrderDetailList.Where(o => o.CurrentQty >= hu.Qty).ToList()); OrderDetail matchedOrderDetail = matchedOrderDetailList.Where(o => o.CurrentQty >= hu.Qty).FirstOrDefault(); if (matchedOrderDetail == null) { if (orderMaster.IsShipExceed) { matchedOrderDetail = matchedOrderDetailList.First(); } else { throw new BusinessException("不允许超发物料{0}。", hu.Item); } } #endregion //#region 再匹配允许超发的订单,未发满但是+本次退货超发了 //if (matchedOrderDetail == null) //{ // IList<string> orderNoList = orderMasters.Where(o => o.IsShipExceed).Select(o => o.OrderNo).ToList(); // matchedOrderDetail = MatchOrderDetail(hu, matchedOrderDetailList.Where(o => (o.CurrentQty > 0) // && (o.CurrentQty < hu.Qty) && orderNoList.Contains(o.OrderNo)).ToList()); // #region 再匹配允许超发的订单,已经满了或已经超发了 // if (matchedOrderDetail == null) // { // matchedOrderDetail = MatchOrderDetail(hu, matchedOrderDetailList.Where(o => (o.CurrentQty <= 0) && orderNoList.Contains(o.OrderNo)).ToList()); // } // #endregion //} #endregion #region 未找到匹配的订单,报错信息 //if (matchedOrderDetail == null) //{ // if (string.IsNullOrEmpty(hu.ManufactureParty)) // { // //条码未指定制造商 // if (matchedOrderDetailList.Where(o => string.IsNullOrEmpty(o.ManufactureParty)).Count() > 0) // { // //有未指定制造商的订货明细 // throw new BusinessException("和条码{0}匹配的订单明细的退货数已经全部满足。", huId, hu.Item); // } // else // { // //没有未指定制造商的订货明细 // throw new BusinessException("待退货订单明细指定了制造商,而条码{0}没有指定制造商", huId); // } // } // else // { // //条码指定了制造商 // if (matchedOrderDetailList.Where(o => o.ManufactureParty == hu.ManufactureParty).Count() > 0) // { // //有未指定制造商的订货明细 // throw new BusinessException("和条码{0}匹配的订单明细的退货数已经全部满足。", huId); // } // else // { // //没有未指定制造商的订货明细 // throw new BusinessException("待退货订单明细指定的制造商和条码{0}制造商{1}不匹配", huId, hu.ManufactureParty); // } // } //} #endregion OrderDetailInput orderDetailInput = new OrderDetailInput(); orderDetailInput.HuId = hu.HuId; orderDetailInput.ShipQty = hu.Qty; orderDetailInput.LotNo = hu.LotNo; orderDetailInput.Id = matchedOrderDetail.Id; List<OrderDetailInput> orderDetailInputs = new List<OrderDetailInput>(); if (matchedOrderDetail.OrderDetailInputs != null) { orderDetailInputs = matchedOrderDetail.OrderDetailInputs.ToList(); } orderDetailInputs.Add(orderDetailInput); matchedOrderDetail.OrderDetailInputs = orderDetailInputs.ToArray(); matchedOrderDetail.CurrentQty -= hu.Qty; matchedOrderDetail.Carton++; base.hus.Insert(0, hu); } else { #region 取消 this.CancelHu(hu); #endregion } this.gvListDataBind(); } private OrderDetail MatchOrderDetail(Hu hu, List<OrderDetail> orderDetailList) { if (orderDetailList != null && orderDetailList.Count > 0) { //先匹配退货明细的制造商 OrderDetail matchedOrderDetail = orderDetailList.Where(o => (o.ManufactureParty == null ? string.Empty : o.ManufactureParty.Trim()) == (hu.ManufactureParty == null ? string.Empty : hu.ManufactureParty.Trim())).FirstOrDefault(); //再匹配没有制造上的退货明细 if (matchedOrderDetail == null) { matchedOrderDetail = orderDetailList.Where(o => string.IsNullOrEmpty(o.ManufactureParty)).FirstOrDefault(); } if (matchedOrderDetail == null) { matchedOrderDetail = orderDetailList.FirstOrDefault(); } return matchedOrderDetail; } return null; } private void MergeOrderMaster(OrderMaster orderMaster) { if (orderMaster.OrderStrategy == FlowStrategy.KIT) { if (this.orderMasters != null && this.orderMasters.Count > 0) { throw new BusinessException("KIT单不能合并退货。"); } } if (this.orderMasters == null) { this.orderMasters = new List<OrderMaster>(); } if (orderMasters.Count(o => o.OrderNo == orderMaster.OrderNo) > 0) { //订单重复扫描检查 throw new BusinessException("重复扫描订单。"); } #region 订单类型 var orderType = orderMasters.Where(o => o.Type != orderMaster.Type); if (orderType.Count() > 0) { throw new BusinessException("订单类型不同不能合并退货。"); } #endregion #region 订单质量类型 var qualityType = orderMasters.Where(o => o.QualityType != orderMaster.QualityType); if (qualityType.Count() > 0) { throw new BusinessException("订单质量状态不同不能合并退货。"); } #endregion #region PartyFrom var partyFrom = orderMasters.Where(o => o.PartyFrom != orderMaster.PartyFrom); if (partyFrom.Count() > 0) { throw new BusinessException("来源组织不同不能合并退货。"); } #endregion #region PartyTo var partyTo = orderMasters.Where(o => o.PartyTo != orderMaster.PartyTo); if (partyTo.Count() > 0) { throw new BusinessException("目的组织不同不能合并退货。"); } #endregion #region ShipFrom var shipFrom = orderMasters.Where(o => o.ShipFrom != orderMaster.ShipFrom); if (shipFrom.Count() > 0) { throw new BusinessException("退货地址不同不能合并退货。"); } #endregion #region ShipTo var shipTo = orderMasters.Where(o => o.ShipTo != orderMaster.ShipTo); if (shipTo.Count() > 0) { throw new BusinessException("收货地址不同不能合并退货。"); } #endregion #region Dock var dock = orderMasters.Where(o => o.Dock != orderMaster.Dock); if (dock.Count() > 0) { throw new BusinessException("道口不同不能合并退货。"); } #endregion #region IsAutoReceive var isAutoReceive = orderMasters.Where(o => o.IsAutoReceive != orderMaster.IsAutoReceive); if (isAutoReceive.Count() > 0) { throw new BusinessException("自动收货选项不同不能合并退货。"); } #endregion #region IsShipScanHu var isShipScanHu = orderMasters.Where(o => o.IsShipScanHu != orderMaster.IsShipScanHu); if (isShipScanHu.Count() > 0) { throw new BusinessException("退货扫描条码选项不同不能合并退货。"); } #endregion #region IsRecScanHu var isRecScanHu = orderMasters.Where(o => o.IsReceiveScanHu != orderMaster.IsReceiveScanHu); if (isRecScanHu.Count() > 0) { throw new BusinessException("收货扫描条码选项不同不能合并退货。"); } #endregion #region IsRecExceed var isRecExceed = orderMasters.Where(o => o.IsReceiveExceed != orderMaster.IsReceiveExceed); if (isRecExceed.Count() > 0) { throw new BusinessException("允许超收选项不同不能合并退货。"); } #endregion #region IsRecFulfillUC var isRecFulfillUC = orderMasters.Where(o => o.IsReceiveFulfillUC != orderMaster.IsReceiveFulfillUC); if (isRecFulfillUC.Count() > 0) { throw new BusinessException("收货满足包装选项不同不能合并退货。"); } #endregion #region IsRecFifo var isRecFifo = orderMasters.Where(o => o.IsReceiveFifo != orderMaster.IsReceiveFifo); if (isRecFifo.Count() > 0) { throw new BusinessException("收货先进先出选项不同不能合并退货。"); } #endregion #region IsAsnAuotClose var isAsnAuotClose = orderMasters.Where(o => o.IsAsnAutoClose != orderMaster.IsAsnAutoClose); if (isAsnAuotClose.Count() > 0) { throw new BusinessException("送货单自动关闭选项不同不能合并退货。"); } #endregion #region IsAsnUniqueRec var isAsnUniqueRec = orderMasters.Where(o => o.IsAsnUniqueReceive != orderMaster.IsAsnUniqueReceive); if (isAsnUniqueRec.Count() > 0) { throw new BusinessException("送货单一次性收货选项不同不能合并退货。"); } #endregion #region IsRecCreateHu var createHuOption = from om in orderMasters where om.CreateHuOption == CreateHuOption.Receive select om.CreateHuOption; if (createHuOption != null && createHuOption.Count() > 0 && createHuOption.Count() != orderMasters.Count()) { throw new BusinessException("收货创建条码选项不同不能合并退货。"); } #endregion #region RecGapTo var recGapTo = orderMasters.Where(o => o.ReceiveGapTo != orderMaster.ReceiveGapTo); if (recGapTo.Count() > 0) { throw new BusinessException("收货差异调整选项不同不能合并退货。"); } #endregion foreach (var orderDetail in orderMaster.OrderDetails) { orderDetail.RemainShippedQty = orderDetail.OrderedQty > orderDetail.ShippedQty ? orderDetail.OrderedQty - orderDetail.ShippedQty : 0; orderDetail.CurrentQty = orderDetail.RemainShippedQty; } this.orderMasters.Add(orderMaster); this.gvListDataBind(); } protected override Hu DoCancel() { Hu firstHu = base.DoCancel(); this.CancelHu(firstHu); return firstHu; } private void CancelHu(Hu hu) { //if (this.orderMasters == null || this.orderMasters.Count() == 0) if (this.hus == null) { //this.ModuleSelectionEvent(CodeMaster.TerminalPermission.M_Switch); this.Reset(); return; } if (hu != null) { var orderDetailList = new List<OrderDetail>(); foreach (var om in this.orderMasters) { orderDetailList.AddRange(om.OrderDetails); } foreach (var orderDetail in orderDetailList) { if (orderDetail.OrderDetailInputs != null) { var q_pdi = orderDetail.OrderDetailInputs.Where(p => p.HuId == hu.HuId); if (q_pdi != null && q_pdi.Count() > 0) { var orderDetailInputList = orderDetail.OrderDetailInputs.ToList(); orderDetailInputList.Remove(q_pdi.First()); orderDetail.OrderDetailInputs = orderDetailInputList.ToArray(); orderDetail.CurrentQty += hu.Qty; orderDetail.Carton--; break; } } } base.hus = base.hus.Where(h => !h.HuId.Equals(hu.HuId, StringComparison.OrdinalIgnoreCase)).ToList(); this.gvHuListDataBind(); } } } }
// <copyright file="CharString.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System; using System.Collections.Generic; using System.Linq; using WaterTrans.GlyphLoader.Geometry; namespace WaterTrans.GlyphLoader.Internal.OpenType.CFF { /// <summary> /// The Type 2 Charstring Format. /// </summary> internal class CharString { private readonly IndexDataOfSubroutines _globalSubroutines; private readonly int _globalSubroutinesBias; private readonly IndexDataOfSubroutines _localSubroutines; private readonly int _localSubroutinesBias; private int _stemCount; private bool _haveWidth; /// <summary> /// Initializes a new instance of the <see cref="CharString"/> class. /// </summary> /// <param name="globalSubroutines">The Global Subrs INDEX.</param> /// <param name="localSubroutines">The Local Subrs INDEX.</param> internal CharString(IndexDataOfSubroutines globalSubroutines, IndexDataOfSubroutines localSubroutines) { _globalSubroutines = globalSubroutines; _localSubroutines = localSubroutines; _globalSubroutinesBias = CalcSubroutineBias(globalSubroutines.Count); _localSubroutinesBias = localSubroutines != null ? CalcSubroutineBias(localSubroutines.Count) : 0; } /// <summary>The list of expression.</summary> public List<CharStringExpression> Expressions { get; } = new List<CharStringExpression>(); /// <summary> /// Gets or sets the width. /// </summary> public int Width { get; set; } /// <summary>Gets a minimum x for coordinate data.</summary> public short XMin { get; private set; } = short.MaxValue; /// <summary>Gets a minimum y for coordinate data.</summary> public short YMin { get; private set; } = short.MaxValue; /// <summary>Gets a maximum x for coordinate data.</summary> public short XMax { get; private set; } = short.MinValue; /// <summary>Gets a maximum y for coordinate data.</summary> public short YMax { get; private set; } = short.MinValue; /// <summary> /// Parse Charstring. /// </summary> /// <param name="data">The byte array of The Type 2 Charstring.</param> /// <param name="operand">The stack of operand.</param> public void Parse(byte[] data, Stack<double> operand) { int index = 0; if (operand == null) { _stemCount = 0; _haveWidth = false; Expressions.Clear(); operand = new Stack<double>(); } while (index < data.Length) { int advance = 1; if (data[index] >= 32 && data[index] <= 246) { operand.Push(data[index] - 139); advance = 1; } else if (data[index] >= 247 && data[index] <= 250) { operand.Push(((data[index] - 247) * 256) + data[index + 1] + 108); advance = 2; } else if (data[index] >= 251 && data[index] <= 254) { operand.Push((-(data[index] - 251) * 256) - data[index + 1] - 108); advance = 2; } else if (data[index] == 255) { operand.Push((data[index + 1] << 24 | data[index + 2] << 16 | data[index + 3] << 8 | data[index + 4]) / 65536.0); advance = 5; } else if (data[index] == 28) { operand.Push((data[index + 1] << 24 | data[index + 2] << 16) >> 16); advance = 3; } else if (data[index] == 1 || data[index] == 3 || data[index] == 18 || data[index] == 23) { var stem = operand.Reverse().ToList(); if (operand.Count % 2 != 0) { Width = (int)stem[0]; stem.RemoveAt(0); _haveWidth = true; } Expressions.Add(new CharStringExpression(data[index], stem.ToArray())); operand.Clear(); _stemCount += stem.Count / 2; } else if (data[index] == 10) { if (operand.Count > 0) { var subrs = operand.Pop(); Parse(_localSubroutines.Objects[(int)subrs + _localSubroutinesBias], operand); } } else if (data[index] == 11) { return; } else if (data[index] == 12) { Expressions.Add(new CharStringExpression(data[index + 1] + 0x0c00, operand.Reverse().ToArray())); operand.Clear(); advance = 2; } else if (data[index] == 19 || data[index] == 20) { _stemCount += operand.Count / 2; Expressions.Add(new CharStringExpression(data[index], operand.Reverse().ToArray())); operand.Clear(); advance += (int)Math.Ceiling((double)_stemCount / 8); } else if (data[index] == 29) { if (operand.Count > 0) { var subrs = operand.Pop(); Parse(_globalSubroutines.Objects[(int)subrs + _globalSubroutinesBias], operand); } } else if (data[index] == 4 || data[index] == 22) { if (!_haveWidth && operand.Count > 1) { var removeWidth = operand.Reverse().ToList(); Width = (int)removeWidth[0]; removeWidth.RemoveAt(0); _haveWidth = true; Expressions.Add(new CharStringExpression(data[index], removeWidth.ToArray())); operand.Clear(); } else { Expressions.Add(new CharStringExpression(data[index], operand.Reverse().ToArray())); operand.Clear(); } } else if (data[index] == 14) { if (!_haveWidth && operand.Count > 0) { var removeWidth = operand.Reverse().ToList(); Width = (int)removeWidth[0]; removeWidth.RemoveAt(0); _haveWidth = true; Expressions.Add(new CharStringExpression(data[index], removeWidth.ToArray())); operand.Clear(); } else { Expressions.Add(new CharStringExpression(data[index], operand.Reverse().ToArray())); operand.Clear(); } } else if (data[index] == 21) { if (!_haveWidth && operand.Count > 2) { var removeWidth = operand.Reverse().ToList(); Width = (int)removeWidth[0]; removeWidth.RemoveAt(0); _haveWidth = true; Expressions.Add(new CharStringExpression(data[index], removeWidth.ToArray())); operand.Clear(); } else { Expressions.Add(new CharStringExpression(data[index], operand.Reverse().ToArray())); operand.Clear(); } } else if (data[index] >= 0 && data[index] <= 31) { Expressions.Add(new CharStringExpression(data[index], operand.Reverse().ToArray())); operand.Clear(); } index += advance; } } /// <summary> /// Calculate glyph metrics. /// </summary> public void CalcMetrics() { double x = 0; double y = 0; foreach (var expression in Expressions) { if (expression.OpCode == 0x0004) // vmoveto { y += expression.Operands[0]; SetXY(x, y); } else if (expression.OpCode == 0x0005) // rlineto { for (int i = 0; i < expression.Operands.Length; i += 2) { x += expression.Operands[i]; y += expression.Operands[i + 1]; SetXY(x, y); } } else if (expression.OpCode == 0x0006) // hlineto { for (int i = 0; i < expression.Operands.Length; i += 2) { x += expression.Operands[i]; SetXY(x, y); if (i + 1 >= expression.Operands.Length) { break; } y += expression.Operands[i + 1]; SetXY(x, y); } } else if (expression.OpCode == 0x0007) // vlineto { for (int i = 0; i < expression.Operands.Length; i += 2) { y += expression.Operands[i]; SetXY(x, y); if (i + 1 >= expression.Operands.Length) { break; } x += expression.Operands[i + 1]; SetXY(x, y); } } else if (expression.OpCode == 0x0008) // rrcurveto { for (int i = 0; i < expression.Operands.Length; i += 6) { double c1x = x + expression.Operands[i]; double c1y = y + expression.Operands[i + 1]; double c2x = c1x + expression.Operands[i + 2]; double c2y = c1y + expression.Operands[i + 3]; x = c2x + expression.Operands[i + 4]; y = c2y + expression.Operands[i + 5]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); } } else if (expression.OpCode == 0x0015) // rmoveto { x += expression.Operands[0]; y += expression.Operands[1]; SetXY(x, y); } else if (expression.OpCode == 0x0016) // hmoveto { x += expression.Operands[0]; SetXY(x, y); } else if (expression.OpCode == 0x0018) // rcurveline { for (int i = 0; i < expression.Operands.Length - 2; i += 6) { double c1x = x + expression.Operands[i]; double c1y = y + expression.Operands[i + 1]; double c2x = c1x + expression.Operands[i + 2]; double c2y = c1y + expression.Operands[i + 3]; x = c2x + expression.Operands[i + 4]; y = c2y + expression.Operands[i + 5]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); } x += expression.Operands[expression.Operands.Length - 2]; y += expression.Operands[expression.Operands.Length - 1]; SetXY(x, y); } else if (expression.OpCode == 0x0019) // rlinecurve { for (int i = 0; i < expression.Operands.Length - 6; i += 2) { x += expression.Operands[i]; y += expression.Operands[i + 1]; SetXY(x, y); } double c1x = x + expression.Operands[expression.Operands.Length - 6]; double c1y = y + expression.Operands[expression.Operands.Length - 5]; double c2x = c1x + expression.Operands[expression.Operands.Length - 4]; double c2y = c1y + expression.Operands[expression.Operands.Length - 3]; x = c2x + expression.Operands[expression.Operands.Length - 2]; y = c2y + expression.Operands[expression.Operands.Length - 1]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); } else if (expression.OpCode == 0x001a) // vvcurveto { int start = 0; if ((expression.Operands.Length % 2) != 0) { x += expression.Operands[0]; start = 1; } for (int i = start; i < expression.Operands.Length; i += 4) { double c1x = x; double c1y = y + expression.Operands[i]; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x; y = c2y + expression.Operands[i + 3]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); } } else if (expression.OpCode == 0x001b) // hhcurveto { int start = 0; if ((expression.Operands.Length % 2) != 0) { y += expression.Operands[0]; start = 1; } for (int i = start; i < expression.Operands.Length; i += 4) { double c1x = x + expression.Operands[i]; double c1y = y; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x + expression.Operands[i + 3]; y = c2y; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); } } else if (expression.OpCode == 0x001e) // vhcurveto { int i = 0; while (i < expression.Operands.Length) { double c1x = x; double c1y = y + expression.Operands[i]; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x + expression.Operands[i + 3]; y = c2y + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); i += 4; if (i + 1 >= expression.Operands.Length) { break; } c1x = x + expression.Operands[i]; c1y = y; c2x = c1x + expression.Operands[i + 1]; c2y = c1y + expression.Operands[i + 2]; x = c2x + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); y = c2y + expression.Operands[i + 3]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); i += 4; if (i + 1 >= expression.Operands.Length) { break; } } } else if (expression.OpCode == 0x001f) // hvcurveto { int i = 0; while (i < expression.Operands.Length) { double c1x = x + expression.Operands[i]; double c1y = y; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); y = c2y + expression.Operands[i + 3]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); i += 4; if (i + 1 >= expression.Operands.Length) { break; } c1x = x; c1y = y + expression.Operands[i]; c2x = c1x + expression.Operands[i + 1]; c2y = c1y + expression.Operands[i + 2]; x = c2x + expression.Operands[i + 3]; y = c2y + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(x, y); i += 4; if (i + 1 >= expression.Operands.Length) { break; } } } else if (expression.OpCode == 0x0c22) // hflex { double c1x = x + expression.Operands[0]; double c1y = y; double c2x = c1x + expression.Operands[1]; double c2y = c1y + expression.Operands[2]; double c3x = c2x + expression.Operands[3]; double c3y = c2y; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(c3x, c3y); double c4x = c3x + expression.Operands[4]; double c4y = c2y; double c5x = c4x + expression.Operands[5]; double c5y = y; x = c5x + expression.Operands[6]; SetXY(c4x, c4y); SetXY(c5x, c5y); SetXY(x, y); } else if (expression.OpCode == 0x0c23) // flex { double c1x = x + expression.Operands[0]; double c1y = y + expression.Operands[1]; double c2x = c1x + expression.Operands[2]; double c2y = c1y + expression.Operands[3]; double c3x = c2x + expression.Operands[4]; double c3y = c2y + expression.Operands[5]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(c3x, c3y); double c4x = c3x + expression.Operands[6]; double c4y = c3y + expression.Operands[7]; double c5x = c4x + expression.Operands[8]; double c5y = c4y + expression.Operands[9]; x = c5x + expression.Operands[10]; y = c5y + expression.Operands[11]; SetXY(c4x, c4y); SetXY(c5x, c5y); SetXY(x, y); } else if (expression.OpCode == 0x0c24) // hflex1 { double c1x = x + expression.Operands[0]; double c1y = y + expression.Operands[1]; double c2x = c1x + expression.Operands[2]; double c2y = c1y + expression.Operands[3]; double c3x = c2x + expression.Operands[4]; double c3y = c2y; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(c3x, c3y); double c4x = c3x + expression.Operands[5]; double c4y = c2y; double c5x = c4x + expression.Operands[6]; double c5y = c4y + expression.Operands[7]; x = c5x + expression.Operands[8]; SetXY(c4x, c4y); SetXY(c5x, c5y); SetXY(x, y); } else if (expression.OpCode == 0x0c25) // flex1 { double c1x = x + expression.Operands[0]; double c1y = y + expression.Operands[1]; double c2x = c1x + expression.Operands[2]; double c2y = c1y + expression.Operands[3]; double c3x = c2x + expression.Operands[4]; double c3y = c2y + expression.Operands[5]; SetXY(c1x, c1y); SetXY(c2x, c2y); SetXY(c3x, c3y); double c4x = c3x + expression.Operands[6]; double c4y = c3y + expression.Operands[7]; double c5x = c4x + expression.Operands[8]; double c5y = c4y + expression.Operands[9]; if (Math.Abs(c5x - x) > Math.Abs(c5y - y)) { x = c5x + expression.Operands[10]; } else { y = c5y + expression.Operands[10]; } SetXY(c4x, c4y); SetXY(c5x, c5y); SetXY(x, y); } } if (XMin == short.MaxValue) { XMin = 0; } if (YMin == short.MaxValue) { YMin = 0; } if (XMax == short.MinValue) { XMax = 0; } if (YMax == short.MinValue) { YMax = 0; } } /// <summary> /// Converts to glyph data to <see cref="PathGeometry"/>. /// </summary> /// <param name="scale">The scale.</param> /// <returns>Returns the <see cref="PathGeometry"/>.</returns> public PathGeometry ConvertToPathGeometry(double scale) { double x = 0; double y = 0; var result = new PathGeometry(); result.FillRule = FillRule.Nonzero; PathFigure figure = null; foreach (var expression in Expressions) { if (expression.OpCode == 0x0004) // vmoveto { y += expression.Operands[0]; figure = new PathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(x * scale, -y * scale); result.Figures.Add(figure); } else if (expression.OpCode == 0x0005) // rlineto { for (int i = 0; i < expression.Operands.Length; i += 2) { x += expression.Operands[i]; y += expression.Operands[i + 1]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); } } else if (expression.OpCode == 0x0006) // hlineto { for (int i = 0; i < expression.Operands.Length; i += 2) { x += expression.Operands[i]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); if (i + 1 >= expression.Operands.Length) { break; } y += expression.Operands[i + 1]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); } } else if (expression.OpCode == 0x0007) // vlineto { for (int i = 0; i < expression.Operands.Length; i += 2) { y += expression.Operands[i]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); if (i + 1 >= expression.Operands.Length) { break; } x += expression.Operands[i + 1]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); } } else if (expression.OpCode == 0x0008) // rrcurveto { for (int i = 0; i < expression.Operands.Length; i += 6) { double c1x = x + expression.Operands[i]; double c1y = y + expression.Operands[i + 1]; double c2x = c1x + expression.Operands[i + 2]; double c2y = c1y + expression.Operands[i + 3]; x = c2x + expression.Operands[i + 4]; y = c2y + expression.Operands[i + 5]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); } } else if (expression.OpCode == 0x0015) // rmoveto { x += expression.Operands[0]; y += expression.Operands[1]; figure = new PathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(x * scale, -y * scale); result.Figures.Add(figure); } else if (expression.OpCode == 0x0016) // hmoveto { x += expression.Operands[0]; figure = new PathFigure(); figure.IsClosed = true; figure.StartPoint = new Point(x * scale, -y * scale); result.Figures.Add(figure); } else if (expression.OpCode == 0x0018) // rcurveline { for (int i = 0; i < expression.Operands.Length - 2; i += 6) { double c1x = x + expression.Operands[i]; double c1y = y + expression.Operands[i + 1]; double c2x = c1x + expression.Operands[i + 2]; double c2y = c1y + expression.Operands[i + 3]; x = c2x + expression.Operands[i + 4]; y = c2y + expression.Operands[i + 5]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); } x += expression.Operands[expression.Operands.Length - 2]; y += expression.Operands[expression.Operands.Length - 1]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); } else if (expression.OpCode == 0x0019) // rlinecurve { for (int i = 0; i < expression.Operands.Length - 6; i += 2) { x += expression.Operands[i]; y += expression.Operands[i + 1]; figure.Segments.Add(new LineSegment(new Point(x * scale, -y * scale), true)); } double c1x = x + expression.Operands[expression.Operands.Length - 6]; double c1y = y + expression.Operands[expression.Operands.Length - 5]; double c2x = c1x + expression.Operands[expression.Operands.Length - 4]; double c2y = c1y + expression.Operands[expression.Operands.Length - 3]; x = c2x + expression.Operands[expression.Operands.Length - 2]; y = c2y + expression.Operands[expression.Operands.Length - 1]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); } else if (expression.OpCode == 0x001a) // vvcurveto { int start = 0; if ((expression.Operands.Length % 2) != 0) { x += expression.Operands[0]; start = 1; } for (int i = start; i < expression.Operands.Length; i += 4) { double c1x = x; double c1y = y + expression.Operands[i]; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x; y = c2y + expression.Operands[i + 3]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); } } else if (expression.OpCode == 0x001b) // hhcurveto { int start = 0; if ((expression.Operands.Length % 2) != 0) { y += expression.Operands[0]; start = 1; } for (int i = start; i < expression.Operands.Length; i += 4) { double c1x = x + expression.Operands[i]; double c1y = y; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x + expression.Operands[i + 3]; y = c2y; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); } } else if (expression.OpCode == 0x001e) // vhcurveto { int i = 0; while (i < expression.Operands.Length) { double c1x = x; double c1y = y + expression.Operands[i]; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x + expression.Operands[i + 3]; y = c2y + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); i += 4; if (i + 1 >= expression.Operands.Length) { break; } c1x = x + expression.Operands[i]; c1y = y; c2x = c1x + expression.Operands[i + 1]; c2y = c1y + expression.Operands[i + 2]; x = c2x + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); y = c2y + expression.Operands[i + 3]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); i += 4; if (i + 1 >= expression.Operands.Length) { break; } } } else if (expression.OpCode == 0x001f) // hvcurveto { int i = 0; while (i < expression.Operands.Length) { double c1x = x + expression.Operands[i]; double c1y = y; double c2x = c1x + expression.Operands[i + 1]; double c2y = c1y + expression.Operands[i + 2]; x = c2x + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); y = c2y + expression.Operands[i + 3]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); i += 4; if (i + 1 >= expression.Operands.Length) { break; } c1x = x; c1y = y + expression.Operands[i]; c2x = c1x + expression.Operands[i + 1]; c2y = c1y + expression.Operands[i + 2]; x = c2x + expression.Operands[i + 3]; y = c2y + (expression.Operands.Length == i + 5 ? expression.Operands[i + 4] : 0); figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(x * scale, -y * scale), true)); i += 4; if (i + 1 >= expression.Operands.Length) { break; } } } else if (expression.OpCode == 0x0c22) // hflex { double c1x = x + expression.Operands[0]; double c1y = y; double c2x = c1x + expression.Operands[1]; double c2y = c1y + expression.Operands[2]; double c3x = c2x + expression.Operands[3]; double c3y = c2y; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(c3x * scale, -c3y * scale), true)); double c4x = c3x + expression.Operands[4]; double c4y = c2y; double c5x = c4x + expression.Operands[5]; double c5y = y; x = c5x + expression.Operands[6]; figure.Segments.Add(new BezierSegment( new Point(c4x * scale, -c4y * scale), new Point(c5x * scale, -c5y * scale), new Point(x * scale, -y * scale), true)); } else if (expression.OpCode == 0x0c23) // flex { double c1x = x + expression.Operands[0]; double c1y = y + expression.Operands[1]; double c2x = c1x + expression.Operands[2]; double c2y = c1y + expression.Operands[3]; double c3x = c2x + expression.Operands[4]; double c3y = c2y + expression.Operands[5]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(c3x * scale, -c3y * scale), true)); double c4x = c3x + expression.Operands[6]; double c4y = c3y + expression.Operands[7]; double c5x = c4x + expression.Operands[8]; double c5y = c4y + expression.Operands[9]; x = c5x + expression.Operands[10]; y = c5y + expression.Operands[11]; figure.Segments.Add(new BezierSegment( new Point(c4x * scale, -c4y * scale), new Point(c5x * scale, -c5y * scale), new Point(x * scale, -y * scale), true)); } else if (expression.OpCode == 0x0c24) // hflex1 { double c1x = x + expression.Operands[0]; double c1y = y + expression.Operands[1]; double c2x = c1x + expression.Operands[2]; double c2y = c1y + expression.Operands[3]; double c3x = c2x + expression.Operands[4]; double c3y = c2y; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(c3x * scale, -c3y * scale), true)); double c4x = c3x + expression.Operands[5]; double c4y = c2y; double c5x = c4x + expression.Operands[6]; double c5y = c4y + expression.Operands[7]; x = c5x + expression.Operands[8]; figure.Segments.Add(new BezierSegment( new Point(c4x * scale, -c4y * scale), new Point(c5x * scale, -c5y * scale), new Point(x * scale, -y * scale), true)); } else if (expression.OpCode == 0x0c25) // flex1 { double c1x = x + expression.Operands[0]; double c1y = y + expression.Operands[1]; double c2x = c1x + expression.Operands[2]; double c2y = c1y + expression.Operands[3]; double c3x = c2x + expression.Operands[4]; double c3y = c2y + expression.Operands[5]; figure.Segments.Add(new BezierSegment( new Point(c1x * scale, -c1y * scale), new Point(c2x * scale, -c2y * scale), new Point(c3x * scale, -c3y * scale), true)); double c4x = c3x + expression.Operands[6]; double c4y = c3y + expression.Operands[7]; double c5x = c4x + expression.Operands[8]; double c5y = c4y + expression.Operands[9]; if (Math.Abs(c5x - x) > Math.Abs(c5y - y)) { x = c5x + expression.Operands[10]; } else { y = c5y + expression.Operands[10]; } figure.Segments.Add(new BezierSegment( new Point(c4x * scale, -c4y * scale), new Point(c5x * scale, -c5y * scale), new Point(x * scale, -y * scale), true)); } } return result; } private void SetXY(double x, double y) { if (x < XMin) { XMin = (short)x; } if (x > XMax) { XMax = (short)x; } if (y < YMin) { YMin = (short)y; } if (y > YMax) { YMax = (short)y; } } private int CalcSubroutineBias(int count) { int bias; if (count < 1240) { bias = 107; } else if (count < 33900) { bias = 1131; } else { bias = 32768; } return bias; } } }
using System; using System.Collections.Generic; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; namespace ApartmentApps.Api.BindingModels { public class MaintenanceCheckinBindingModel { public string StatusId { get; set; } public DateTime Date { get; set; } public string Comments { get; set; } public List<ImageReference> Photos { get; set; } public UserBindingModel Worker { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace _00.InversionTheFlowOfProgram { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Save_Click(object sender, RoutedEventArgs e) { var firstName = FirstName.Text; var lastName = LastName.Text; SaveToDB(firstName, lastName); } private void Clear_Click(object sender, RoutedEventArgs e) { FirstName.Text = ""; LastName.Text = ""; } private void SaveToDB(string firstName, string lastName) { Message.Text = $"{lastName} {firstName} 已经写入到数据库中了"; } } }
using System.Collections.Generic; using System.Linq; using Data.Infrastructure; using Model.Models; using System; using Model; using Data.Models; using ProjLib.ViewModels; namespace Service { public interface IRolesControllerActionService : IDisposable { RolesControllerAction Create(RolesControllerAction pt); void Delete(int id); void Delete(RolesControllerAction pt); RolesControllerAction Find(int ptId); void Update(RolesControllerAction pt); RolesControllerAction Add(RolesControllerAction pt); IEnumerable<RolesControllerAction> GetRolesControllerActionList(); RolesControllerAction Find(int MenuId, string RoleId); IEnumerable<RolesControllerActionViewModel> GetRolesControllerActionList(string RoleId); IEnumerable<RolesControllerActionViewModel> GetRolesControllerActionsForRoles(List<String> Roles); } public class RolesControllerActionService : IRolesControllerActionService { ApplicationDbContext db = new ApplicationDbContext(); private readonly IUnitOfWorkForService _unitOfWork; private readonly Repository<RolesControllerAction> _RolesControllerActionRepository; RepositoryQuery<RolesControllerAction> RolesControllerActionRepository; public RolesControllerActionService(IUnitOfWorkForService unitOfWork) { _unitOfWork = unitOfWork; _RolesControllerActionRepository = new Repository<RolesControllerAction>(db); RolesControllerActionRepository = new RepositoryQuery<RolesControllerAction>(_RolesControllerActionRepository); } public RolesControllerAction Find(int pt) { return _unitOfWork.Repository<RolesControllerAction>().Find(pt); } public RolesControllerAction Create(RolesControllerAction pt) { pt.ObjectState = ObjectState.Added; _unitOfWork.Repository<RolesControllerAction>().Insert(pt); return pt; } public void Delete(int id) { _unitOfWork.Repository<RolesControllerAction>().Delete(id); } public void Delete(RolesControllerAction pt) { _unitOfWork.Repository<RolesControllerAction>().Delete(pt); } public void Update(RolesControllerAction pt) { pt.ObjectState = ObjectState.Modified; _unitOfWork.Repository<RolesControllerAction>().Update(pt); } public IEnumerable<RolesControllerAction> GetRolesControllerActionList() { var pt = _unitOfWork.Repository<RolesControllerAction>().Query().Get(); return pt; } public RolesControllerAction Add(RolesControllerAction pt) { _unitOfWork.Repository<RolesControllerAction>().Insert(pt); return pt; } public RolesControllerAction Find(int ControllerActionId, string RoleId) { return _unitOfWork.Repository<RolesControllerAction>().Query().Get().Where(m=>m.RoleId==RoleId && m.ControllerActionId==ControllerActionId).FirstOrDefault(); } public IEnumerable<RolesControllerActionViewModel> GetRolesControllerActionList(string RoleId) { return (from p in db.RolesControllerAction where p.RoleId == RoleId select new RolesControllerActionViewModel { ControllerActionId = p.ControllerActionId, RoleId = p.RoleId, RolesControllerActionId = p.RolesControllerActionId, ControllerActionName=p.ControllerAction.ActionName, RoleName = p.Role.Name, }); } public RolesControllerAction GetControllerActionForRoleId(string RoleId,int ControllerActionId) { return (from p in db.RolesControllerAction where p.RoleId == RoleId && p.ControllerActionId==ControllerActionId select p).FirstOrDefault(); } public IEnumerable<RolesControllerActionViewModel> GetRolesControllerActionsForRoles(List<String> Roles) { var temp = (from p in db.Roles select p).ToList(); var RoleIds = string.Join(",", from p in temp where Roles.Contains(p.Name) select p.Id.ToString()); var Temp = (from p in db.RolesControllerAction where RoleIds.Contains(p.RoleId) select new RolesControllerActionViewModel { ControllerActionId=p.ControllerActionId, ControllerActionName=p.ControllerAction.ActionName, ControllerName=p.ControllerAction.Controller.ControllerName, RoleId=p.RoleId, RoleName=p.Role.Name, RolesControllerActionId=p.RolesControllerActionId }); return Temp; } public void Dispose() { } } }
using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { [System.Serializable] public sealed class PatrolHandler : MonoBehaviour { public struct PatrolInfo { private Vector2 m_destination; private Vector2 m_moveDirection; public PatrolInfo(Vector2 currentPosition, Vector2 destination) { m_destination = destination; m_moveDirection = (destination - currentPosition).normalized; } public Vector2 destination => m_destination; public Vector2 moveDirection => m_moveDirection; } public enum Iteration { Forward = 1, Backward = -1 } public bool isNearDestination; [BoxGroup("Significant Axis")] [SerializeField] private bool m_useX = true; [BoxGroup("Significant Axis")] [SerializeField] private bool m_useY; [SerializeField] [MinValue(0)][Tooltip("Max Distance to consider object is near")] private float m_nearDistanceTolerance =0.1f; [SerializeField] [MinValue(0)] [BoxGroup("Configuration")] private int m_startIndex; [SerializeField] [BoxGroup("Configuration")] private Iteration m_startIteration; [SerializeField] [BoxGroup("Configuration")] [ListDrawerSettings(CustomAddFunction = "AddToWaypoint")] private Vector2[] m_wayPoints; private int m_currentIndex; private Iteration m_iteration; public void Initialize() { m_currentIndex = m_startIndex; m_iteration = m_startIteration; } public PatrolInfo GetInfo(Vector2 position) { var destination = m_wayPoints[m_currentIndex]; bool nearX = m_useX ? IsNear(position.x, destination.x) : true; bool nearY = m_useY ? IsNear(position.y, destination.y) : true; if (nearX && nearY) { isNearDestination = true; NextPatrolPoint(); destination = m_wayPoints[m_currentIndex]; } else { isNearDestination = false; } return new PatrolInfo(position, destination); } private bool IsNear(float position, float destination) { var distance = Mathf.Abs(destination - position); return distance <= m_nearDistanceTolerance; } private void NextPatrolPoint() { if (m_currentIndex == m_wayPoints.Length - 1) { m_iteration = Iteration.Backward; } else if (m_currentIndex == 0) { m_iteration = Iteration.Forward; } m_currentIndex += (int)m_iteration; } #if UNITY_EDITOR [Space] [FoldoutGroup("ToolKit")] [SerializeField] private bool m_useCurrentPosition; [FoldoutGroup("ToolKit")] [SerializeField] [MinValue(0)] private int m_overridePatrolIndex; public bool useCurrentPosition => m_useCurrentPosition; public int overridePatrolIndex => m_overridePatrolIndex; public int iteration => (int)m_startIteration; public int startIndex => m_startIndex; public Vector2[] wayPoints => m_wayPoints; [FoldoutGroup("ToolKit")] [HideIf("m_useCurrentPosition")] [Button("Save To Current Index")] private void SaveToCurrentIndex() { m_wayPoints[m_overridePatrolIndex] = transform.position; } [FoldoutGroup("ToolKit")] [Button("Go To Starting Position")] private void GoToStartingPosition() { m_useCurrentPosition = false; transform.position = m_wayPoints[m_startIndex]; } private Vector2 AddToWaypoint() => transform.position; #endif private void OnValidate() { if (m_wayPoints != null) { m_startIndex = Mathf.Min(m_startIndex, m_wayPoints.Length - 1); #if UNITY_EDITOR m_overridePatrolIndex = Mathf.Min(m_overridePatrolIndex, m_wayPoints.Length - 1); #endif } } } }
using System; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.CUST { [Serializable] public partial class PubPrintOrder : EntityBase, IAuditable { public int Id { get; set; } public string ExcelTemplate { get; set; } public string Code { get; set; } public string Printer { get; set; } public string Client { get; set; } public Boolean IsPrinted { get; set; } public string PrintUrl { 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; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; using System.IO; using System; using UnityEngine.UI; using System.Linq; public class WebDataManager : MonoBehaviour { public ScrollRect view; //UI list public Button submitButton; //Submit button public InputField input; //Input field public Scrollbar scroll; //Scroll bar next to UI list private List<Title> programList; JsonData playerJson; void Start() { // Add Listeners for submit button is pressed submitButton.onClick.AddListener(delegate { handleInput(); }); //when the scrollbar value changes scroll.onValueChanged.AddListener(delegate { updateView(); }); input.onEndEdit.AddListener(delegate { handleInput(); }); programList = new List<Title>(); } // Starts routine to get data from API void handleInput() { if(input.text != "") { processQuery(input.text); input.text = ""; } } // Coroutine for data fetch void processQuery(string keyword) { StartCoroutine(getDataFromAPI(keyword)); } IEnumerator getDataFromAPI(string searchKeyword) { string url = "https://external.api.yle.fi/v1/programs/items.json?app_id=6e95a336&app_key=420f34d7cf92076ee50c905a07b4ee9d&limit=100&availability=ondemand&mediaobject=video&q=" + searchKeyword; WWW wwwObj = new WWW(url); yield return wwwObj; // check for errors if(wwwObj.error == null) { Debug.Log("WWW Ok!: " + wwwObj.text); ProcessJson(wwwObj.text); updateView(); } else { Debug.Log("WWW Error: " + wwwObj.error); } } void ProcessJson(string jsonString) { JsonReader reader = new JsonReader(jsonString); JsonData data = JsonMapper.ToObject(reader); ClearCache(); try { List<Title> duplicatesList = new List<Title>(); for (int i = 0; i < data["data"].Count; ++i) { //Make sure at least one title is found (either fi or sv) //Both titles are found if (data["data"][i]["title"].Keys.Contains("sv") && data["data"][i]["title"].Keys.Contains("fi")) { duplicatesList.Add(new Title(data["data"][i]["title"]["fi"].ToString(), data["data"][i]["title"]["sv"].ToString())); } //Only fi title is found else if (data["data"][i]["title"].Keys.Contains("fi")) { duplicatesList.Add(new Title(data["data"][i]["title"]["fi"].ToString(), "")); } //Only sv title is found else if (data["data"][i]["title"].Keys.Contains("sv")) { duplicatesList.Add(new Title("", data["data"][i]["title"]["sv"].ToString())); } else { Debug.Log("Error: Entity with no title"); } } //Get rid of duplicate titles programList = duplicatesList.Distinct().ToList(); } catch (Exception e) { Debug.Log("Exception caught: " + e.Message); } } //Pushes more entities into Scroll rect (UI list) void updateView() { //Used to handle unnecessary listener calls from scroll bar if (scroll.value != 0f) return; //Push 10 more entities into Scroll rect int countBefore = view.GetComponentInChildren<AppendProgramList>().GetShownCount(); for (int i = countBefore; i < programList.Count; ++i) { if (i == countBefore + 10) break; //Prefer finnish title but if missing, use swedish string title = (programList.ElementAt(i).fi == "" ? programList.ElementAt(i).sv : programList.ElementAt(i).fi); view.GetComponentInChildren<AppendProgramList>().AppendProgram(title); } //Update scroll value to a position where the list doesn't change when new entities are added int countAfter = view.GetComponentInChildren<AppendProgramList>().GetShownCount(); if (countAfter > 10) { scroll.value = 1 / (countAfter / 10); } } void ClearCache() { view.GetComponentInChildren<AppendProgramList>().ClearList(); programList.Clear(); } } //Class that holds the title data class Title : IEquatable<Title> { public Title(string fiName, string svName) { fi = fiName; sv = svName; } //Implemented IEquatable interface so that Distinct() can pick out duplicates away public override int GetHashCode() { int hashProductFi = fi.GetHashCode(); int hashProductSv = sv.GetHashCode(); return hashProductFi ^ hashProductSv; } //Implemented IEquatable interface so that Distinct() can pick out duplicates away public bool Equals(Title other) { if (other == null) return false; if (fi == other.fi && sv == other.sv) return true; else return false; } //Payload public string fi { get; set; } public string sv { get; set; } }
namespace Nailhang.Blazor.States { public class ModulesIndexState { public bool ShowOnlyWithDescription { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu] public class DialogData: ScriptableObject { [SerializeField] [TextArea(3, 10)] private string[] introduction; [SerializeField] private Answers[] answers; public int currentAnswer = 0; public int currentIntroduction = 0; public int rightAnswer; public string GetNextAnswer(int choice) { if (currentAnswer >= answers[choice].answers.Length) return null; currentAnswer++; return answers[choice].answers[currentAnswer -1]; } public string GetNextIntroduction() { if (currentIntroduction >= introduction.Length) return null; currentIntroduction++; return introduction[currentIntroduction - 1]; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerTools : MonoBehaviour { PlayerInputAction controls; public GameObject PlayerObject; public GameObject HandLocation; public GameObject PlayerCamera; public GameObject CameraBody; public Material IdleMaterial; public Material AvailableMaterial; public Material ActiveMaterial; public GameObject CurrentTarget; public List<GameObject> MagCollectables; private bool isHit, hasTarget; private string hitObjectTag; private bool pulling; void Awake() { controls = new PlayerInputAction(); controls.PlayerControls.ActivateMagArm.started += ctx => pulling = true; controls.PlayerControls.ActivateMagArm.canceled += ctx => pulling = false; controls.PlayerControls.Enable(); } // Start is called before the first frame update void Start() { MagCollectables = new System.Collections.Generic.List<GameObject>(); MagCollectables.AddRange(GameObject.FindGameObjectsWithTag("MagCollectable")); } // Update is called once per frame void Update() { IsLookingAt("MagCollectable"); if (CurrentTarget) { CurrentTarget.GetComponent<MeshRenderer>().material = AvailableMaterial; } else { if(hasTarget) { for (int i = 0; i < MagCollectables.Count; i++) { MagCollectables[i].GetComponent<MeshRenderer>().material = IdleMaterial; hasTarget = false; } } } if(pulling) { MagPull(CurrentTarget); } } void MagArm() { } void MagPull(GameObject target) { if (!CurrentTarget) return; if(Vector3.Distance(CurrentTarget.transform.position, HandLocation.transform.position) < 1.65f) { if(CurrentTarget.tag == "MagCollectable") { for(int i = 0; i < MagCollectables.Count; i++) { if(CurrentTarget == MagCollectables[i]) { Destroy(CurrentTarget); CurrentTarget = null; MagCollectables.RemoveAt(i); return; } } } } else { CurrentTarget.GetComponent<MeshRenderer>().material = ActiveMaterial; CurrentTarget.transform.position = Vector3.MoveTowards(CurrentTarget.transform.position, HandLocation.transform.position, 15.0f * Time.deltaTime); } } public bool IsLookingAt(string tag, float tolerance = 0.9f)//Must give interactable objects a tag that you can pass here. { if (tag == "MagCollectable") { for(int i = 0; i < MagCollectables.Count; i++) { Vector3 direction = (MagCollectables[i].transform.position - PlayerCamera.transform.position).normalized; float dot = Vector3.Dot(direction, PlayerCamera.transform.forward); if(dot > tolerance) { CurrentTarget = MagCollectables[i]; hasTarget = true; return true; } else { CurrentTarget = null; } } } return false; } void onEnable() { controls.PlayerControls.Enable(); } void onDisable() { controls.PlayerControls.Disable(); } }
using System; using System.Data.SqlClient; using System.Data; using System.Windows.Forms; namespace netflixuygulamasi { class Database { public static Database nesne; private string girisYapanKullaniciMail = ""; private string izlenecekFilm = ""; private int[] secim = new int[4]; public static Database DatabaseOlustur() //diğer classlarda kullanılması için fazladan nesne oluşturmaya gerek olmadığı için sigleton deseni kullanıldı { if (nesne == null) nesne = new Database(); return nesne; } private Database() { } public SqlConnection F_Baglanti() { var conStr = System.Configuration.ConfigurationManager.AppSettings["ConStr"]; SqlConnection baglan = new SqlConnection(conStr); // bu yolu debug klasöründeki config dosyasından değiştirebilisiniz baglan.Open(); return baglan; } public bool KullaniciKontrolEt(formGiris girisFormu) //kullanici girişi başarılıysa true döndürecek, değilse false { string mail = girisFormu.txtMail.Text; string sifre = girisFormu.txtSifre.Text; SqlCommand command = new SqlCommand(); command.Connection = F_Baglanti(); command.CommandText = "select * from Tbl_Kullanici where email='" + girisFormu.txtMail.Text + "'" + "and sifre='" + girisFormu.txtSifre.Text + "'"; girisYapanKullaniciMail = girisFormu.txtMail.Text; SqlDataReader dt = command.ExecuteReader(); if (dt.Read()) return true; else { return false; } } public void KullaniciEkle(KayitSayfasi kayitForm) //kullanıcı girişi başarısırızsa kullanici tablosuna kullanıcıyı kaydeder { SqlCommand komut = new SqlCommand( "insert into Tbl_Kullanici (kullaniciAd,email,sifre,dogumTarihi) values (@t1,@t2,@t3,@t4)", F_Baglanti()); komut.Parameters.AddWithValue("@t1", kayitForm.kTxtAd.Text); komut.Parameters.AddWithValue("@t2", kayitForm.kTxtEmail.Text); komut.Parameters.AddWithValue("@t3", kayitForm.kTxtSifre.Text); komut.Parameters.AddWithValue("@t4", kayitForm.kTxtDogumTarihi.Text); komut.ExecuteNonQuery(); F_Baglanti().Close(); } public void FilmListele(KayitSayfasi kayit, int seciliDeger, int sayac) //kullanıcı kayıt sayfasında checkboxlarda seçili olan verinin adını alır, inner joinler kullanılarak üç farklı tablodan gerekli veriler alınır { SqlCommand komut = new SqlCommand(@"SELECT top 2 Tbl_Program.programAd FROM Tbl_ProgramTur INNER JOIN Tbl_KullaniciProgram ON Tbl_ProgramTur.programId = Tbl_KullaniciProgram.kullaniciprogramId INNER JOIN Tbl_Program ON Tbl_ProgramTur.programId = Tbl_Program.programId WHERE(Tbl_ProgramTur.turId IN (@t1)) ORDER BY Tbl_KullaniciProgram.kullaniciPuan DESC", F_Baglanti()); komut.Parameters.AddWithValue("@t1", seciliDeger); DataTable data = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(komut); adapter.Fill(data); if (sayac == 1) kayit.dataGridView1.DataSource = data; else if (sayac == 2) kayit.dataGridView2.DataSource = data; else if (sayac == 3) kayit.dataGridView3.DataSource = data; } public void ProgramAraIsim(YonetimSayfasi yonetim) { SqlCommand komut = new SqlCommand( @"SELECT p.programAd FROM Tbl_Program AS p WHERE p.programAd='" + yonetim.txtAdAra.Text + "'", F_Baglanti()); DataTable data = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(komut); adapter.Fill(data); yonetim.dataGridView1.DataSource = data; } // Giriş yapıldıktan sonra isime göre arama yapar public void ComboboboxTuradlariSirala(YonetimSayfasi yonetim) { SqlCommand komut = new SqlCommand(@"SELECT turAd FROM Tbl_Tur ", F_Baglanti()); DataTable data = new DataTable(); SqlDataReader read = komut.ExecuteReader(); while (read.Read()) { yonetim.cmbTur.Items.Add(read["turAd"]); } yonetim.dataGridView1.DataSource = data; } //tür adlarına göre arama yapılabilmesi için comboboxa tür adlarını yazdırır public void ProgramAraTur(YonetimSayfasi yonetim) //burayı düzelt. kullanıcı program sayfasında olan türleri getiriyor bütün türleri getirmesi lazım { SqlCommand komut = new SqlCommand( @"SELECT DISTINCT Tbl_Program.programAd FROM Tbl_ProgramTur INNER JOIN Tbl_Program ON Tbl_ProgramTur.programId = Tbl_Program.programId WHERE(Tbl_ProgramTur.turId =(SELECT turId FROM Tbl_Tur WHERE turAd=(@p1)))", F_Baglanti()); komut.Parameters.AddWithValue("@p1", Convert.ToString(yonetim.cmbTur.SelectedItem)); DataTable data = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(komut); adapter.Fill(data); yonetim.dataGridView1.DataSource = data; } //comboboxtaki seçili veriyi kullanarak türe göre arama yapar public int BolumUzunluguGetir(YonetimSayfasi yonetim, DataGridViewCellEventArgs e) //bölümün uzunluğunu bulur { int uzunluk = 0; if (e.ColumnIndex == 0) { SqlCommand komut = new SqlCommand(@"SELECT uzunluk FROM Tbl_Program WHERE programAd =@p1", F_Baglanti()); if (yonetim.dataGridView1.CurrentRow != null) komut.Parameters.AddWithValue("@p1", yonetim.dataGridView1.CurrentRow.Cells["programAd"].Value.ToString()); if (yonetim.dataGridView1.CurrentRow != null) izlenecekFilm = yonetim.dataGridView1.CurrentRow.Cells["programAd"].Value.ToString(); DataTable data = new DataTable(); SqlDataReader read = komut.ExecuteReader(); while (read.Read()) { uzunluk = Convert.ToInt16(read["uzunluk"]); } } return uzunluk; } public int YarimKalmisFilmVarMi() //filmi izlemeye başlamadan önce daha önce izlemeye başlanan ve yarım kalmış film var mı diye kontrol eder { int kalinanYer = 0; SqlCommand command = new SqlCommand(); command.Connection = F_Baglanti(); command.CommandText = "SELECT kullaniciProgramId,kullaniciId,kalinanYer FROM Tbl_KullaniciProgram WHERE kullaniciprogramId=(SELECT programId FROM Tbl_Program WHERE programAd=@programadi) AND kullaniciId=(SELECT kullaniciId FROM Tbl_Kullanici WHERE email=(@kullanicimaili))"; command.Parameters.AddWithValue("@programadi", izlenecekFilm); command.Parameters.AddWithValue("@kullanicimaili", girisYapanKullaniciMail); SqlDataReader dt = command.ExecuteReader(); while (dt.Read()) kalinanYer = Convert.ToInt16(dt["kalinanYer"]); return kalinanYer; } public void IzlemeVerileriKaydet(int izlenenZaman, string tarih, int puan) //eğer daha önce seçili kullanıcıya ait izlenmiş film bulunmuyorsa kulalniciprogram tablosuna yeni kayıt ekler { SqlCommand komut = new SqlCommand( "INSERT INTO Tbl_KullaniciProgram(kullaniciprogramId,kullaniciId,kalinanYer,izlemeTarihi,kullaniciPuan)VALUES((SELECT programId FROM Tbl_Program WHERE programAd = (@programadi)), (SELECT kullaniciId FROM Tbl_Kullanici WHERE email = (@kullanicimaili)),@kalinanYer,@tarih,@puan)", F_Baglanti()); komut.Parameters.AddWithValue("@programadi", izlenecekFilm); komut.Parameters.AddWithValue("@kullanicimaili", girisYapanKullaniciMail); komut.Parameters.AddWithValue("@kalinanYer", izlenenZaman); komut.Parameters.AddWithValue("@tarih", tarih); komut.Parameters.AddWithValue("@puan", puan); komut.ExecuteNonQuery(); F_Baglanti().Close(); } public void IzlemeVerileriGuncelle(int izlenenZaman, string tarih, int puan) // kullaniciprogram tablosunda daha önceden kayıt var ise yeni kayıt oluşturmak yerine öncekinin üstüne yazılıyor { SqlCommand command = new SqlCommand(); command.Connection = F_Baglanti(); command.CommandText = "UPDATE Tbl_KullaniciProgram SET kalinanYer = @kalinanYer, izlemeTarihi =@tarih , kullaniciPuan = @puan WHERE kullaniciprogramId = (SELECT programId FROM Tbl_Program WHERE programAd = (@programadi)) and kullaniciId = (SELECT kullaniciId FROM Tbl_Kullanici WHERE email = (@kullanicimaili)) "; command.Parameters.AddWithValue("@programadi", izlenecekFilm); command.Parameters.AddWithValue("@kullanicimaili", girisYapanKullaniciMail); command.Parameters.AddWithValue("@kalinanYer", izlenenZaman); command.Parameters.AddWithValue("@tarih", tarih); command.Parameters.AddWithValue("@puan", puan); command.ExecuteNonQuery(); F_Baglanti().Close(); } public int DiziFilmBolumSayisiKontrolEt() // dizinin bölüm sayısını kontrol eder eğer film ise dönücek değer hep 1 olacak şekilde kabul edildi { int bolumSayisi = 1; SqlCommand komut = new SqlCommand("SELECT bolumSayisi FROM Tbl_Program WHERE programAd=(@programAdi)", F_Baglanti()); komut.Parameters.AddWithValue("@programAdi", izlenecekFilm); SqlDataReader dt = komut.ExecuteReader(); while (dt.Read()) bolumSayisi = Convert.ToInt16(dt["bolumSayisi"]); return bolumSayisi; } public bool DiziMi() //kayıt yapılırken dizi ise kullaniciprogram tablosuna bölüm uzunluğunu, film ise izlenen süreyi yazması için kontrol fonksiyonu { SqlCommand command = new SqlCommand(); command.Connection = F_Baglanti(); command.CommandText = "SELECT programTip FROM Tbl_Program WHERE programAd=(@p1)"; command.Parameters.AddWithValue("@p1", izlenecekFilm); SqlDataReader dt = command.ExecuteReader(); string bolumTur = ""; while (dt.Read()) bolumTur = dt["programTip"].ToString(); if (bolumTur == "Dizi") return true; else return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace ProjetGl.Models { public class Collaboration { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int ProjetId { get; set; } public virtual Projet Projet { get; set; } public string CollaborateurId { get; set; } public virtual ApplicationUser Collaborateur { get; set; } } }
using Microsoft.SharePoint; using BELCORP.GestorDocumental.BE.DDP; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.DA.Comun; using BELCORP.GestorDocumental.DA.Sharepoint; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Administration; using Microsoft.Office.Server.UserProfiles; namespace BELCORP.GestorDocumental.BL.DDP { public class CentroCostoBL { #region Singleton private static volatile CentroCostoBL _instance = null; private static object lockAccessObject = new Object(); public static CentroCostoBL Instance { get { if (_instance == null) { lock (lockAccessObject) { _instance = new CentroCostoBL(); } } return _instance; } } /// <summary> /// Contructor por defecto /// </summary> private CentroCostoBL() { } #endregion //public List<CentroCostoBE> ObtenerLista(string URL_Sitio) //{ // List<CentroCostoBE> lst = new List<CentroCostoBE>(); // CentroCostoBE oItem = null; // SPListItemCollection splic = SharePointHelper.ObtenerInformacionLista(URL_Sitio, Constantes.Listas.CentroCostos); // if (splic != null) // { // foreach (SPListItem splitem in splic) // { // oItem = new CentroCostoBE(); // oItem.Id = splitem.ID; // oItem.Nombre = splitem.Title; // lst.Add(oItem); // } // } // return lst; //} public CentroCostoBE LeerPropiedades(SPListItem spliCentroCosto) { CentroCostoBE oCentroCosto = null; if (spliCentroCosto != null) { oCentroCosto = new CentroCostoBE(); oCentroCosto.Id = spliCentroCosto.ID; oCentroCosto.Codigo = spliCentroCosto.Title; oCentroCosto.Descripcion = spliCentroCosto["Descripcion"].ToString(); } return oCentroCosto; } //public List<CentroCostoBE> ObtenerCentroCostoXTitulo(string URLSitio, string Nombre, int NumeroPagina, int FilasXPagina, ref int TotalFilas) //{ // List<CentroCostoBE> lstCentroCosto = null; // CentroCostoBE oCentroCosto = null; // #region SPQuery // string spQuery = "<Where>" + // "<Or>" + // "<Contains>" + // "<FieldRef Name='Title' />" + // "<Value Type='Text'>" + Nombre + "</Value>" + // "</Contains>" + // "<Contains>" + // "<FieldRef Name='Descripcion' />" + // "<Value Type='Text'>" + Nombre + "</Value>" + // "</Contains>" + // "</Or>" + // "</Where>"; // #endregion // SPListItemCollection splicCentroCosto; // if (!string.IsNullOrEmpty(Nombre)) // splicCentroCosto = SharePointHelper.ObtenerInformacionLista(URLSitio, Constantes.Listas.CentroCostos, spQuery); // else // splicCentroCosto = SharePointHelper.ObtenerInformacionLista(URLSitio, Constantes.Listas.CentroCostos); // if (splicCentroCosto != null) // { // foreach (SPListItem spliCentroCosto in splicCentroCosto) // { // oCentroCosto = LeerPropiedades(spliCentroCosto); // if (lstCentroCosto == null) lstCentroCosto = new List<CentroCostoBE>(); // if (oCentroCosto != null) // lstCentroCosto.Add(oCentroCosto); // } // } // lstCentroCosto = EnumerarLista(lstCentroCosto); // lstCentroCosto = PaginarLista(lstCentroCosto, NumeroPagina, FilasXPagina, ref TotalFilas); // return lstCentroCosto; //} public List<CentroCostoBE> ListarFiltrado(string URLSitio, string ValorFiltro, int NumeroPagina, int FilasXPagina, ref int TotalFilas, List<CentroCostoBE> CeCosAgregados) { List<CentroCostoBE> lstCentroCosto = null; CentroCostoBE oCentroCosto = null; SPListItemCollection splicCentroCosto = null; if (ValorFiltro.Trim() != string.Empty) { #region Si existe valor filtro string spQuery = "<Where>" + "<Or>" + "<Contains>" + "<FieldRef Name='Title' />" + "<Value Type='Text'>" + ValorFiltro + "</Value>" + "</Contains>" + "<Contains>" + "<FieldRef Name='Descripcion' />" + "<Value Type='Text'>" + ValorFiltro + "</Value>" + "</Contains>" + "</Or>" + "</Where>"; if (!string.IsNullOrEmpty(ValorFiltro)) splicCentroCosto = SharePointHelper.ObtenerInformacionLista(URLSitio, ListasGestorDocumental.CentrosCosto, spQuery); if (splicCentroCosto != null) { foreach (SPListItem spliCentroCosto in splicCentroCosto) { oCentroCosto = LeerPropiedades(spliCentroCosto); if (lstCentroCosto == null) lstCentroCosto = new List<CentroCostoBE>(); if (oCentroCosto != null) if (CeCosAgregados != null) { if (!CeCosAgregados.Exists(CeCoItem => CeCoItem.Codigo == oCentroCosto.Codigo)) { lstCentroCosto.Add(oCentroCosto); } } else lstCentroCosto.Add(oCentroCosto); } } #endregion } else { #region No existe valor filtro splicCentroCosto = SharePointHelper.ObtenerInformacionLista(URLSitio, ListasGestorDocumental.CentrosCosto); if (splicCentroCosto != null) { foreach (SPListItem spliCentroCosto in splicCentroCosto) { oCentroCosto = LeerPropiedades(spliCentroCosto); if (lstCentroCosto == null) lstCentroCosto = new List<CentroCostoBE>(); if (oCentroCosto != null) if (CeCosAgregados != null) { if (!CeCosAgregados.Exists(CeCoItem => CeCoItem.Codigo == oCentroCosto.Codigo)) { lstCentroCosto.Add(oCentroCosto); } } else lstCentroCosto.Add(oCentroCosto); } } #endregion } if (lstCentroCosto != null) { if (lstCentroCosto.Count > 0) { lstCentroCosto = lstCentroCosto.OrderBy(o => o.Descripcion).ToList(); lstCentroCosto = EnumerarLista(lstCentroCosto); lstCentroCosto = PaginarLista(lstCentroCosto, NumeroPagina, FilasXPagina, ref TotalFilas); } } return lstCentroCosto; } public List<CentroCostoBE> EnumerarLista(List<CentroCostoBE> lstCentroCosto) { if (lstCentroCosto != null) { int NumeroFila = 1; foreach (var oItem in lstCentroCosto) { oItem.NumeroFila = NumeroFila; NumeroFila++; } } return lstCentroCosto; } public List<CentroCostoBE> PaginarLista(List<CentroCostoBE> lstCentroCosto, int NumeroPagina, int FilasXPagina, ref int TotalFilas) { List<CentroCostoBE> lstPaginada = null; if (lstCentroCosto != null && lstCentroCosto.Count > 0) { TotalFilas = lstCentroCosto.Count(); int _NumeroPagina = NumeroPagina - 1; int _NumeroInicio = FilasXPagina * _NumeroPagina + 1; int _NumeroFin = _NumeroInicio + FilasXPagina - 1; lstPaginada = lstCentroCosto.FindAll(x => x.NumeroFila >= _NumeroInicio && x.NumeroFila <= _NumeroFin); } return lstPaginada; } //public List<CentroCostoBE> ListarFiltrado(int NumeroPagina, int FilasXPagina, string pDescripcion, ref int TotalFilas) //{ // return CentroCostoDL.Instance.ListarFiltrado(NumeroPagina, FilasXPagina, pDescripcion, ref TotalFilas); // //return Empleado_DL.Instance.ObtenerXRenovar(NumeroPagina, FilasXPagina, oEmpleado, ref TotalFilas); //} public String ObtenerCorreosNotificarPorCentroCosto(List<CentroCostoBE> oListaCentroCostos) { string CorreosNotificar = String.Empty; string CentroCostoPerfil = String.Empty; SPSecurity.RunWithElevatedPrivileges(delegate() { SPServiceContext oServiceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default); UserProfileManager profileManager = new UserProfileManager(oServiceContext, false); foreach (UserProfile profile in profileManager) { if (profile[Constantes.NOMBRE_CAMPO_PERFIL_CENTROCOSTO].Value != null) { CentroCostoPerfil = Convert.ToString(profile[Constantes.NOMBRE_CAMPO_PERFIL_CENTROCOSTO].Value); if (oListaCentroCostos.Exists(CC => CC.Codigo == CentroCostoPerfil.Split(Constantes.Caracteres.SeparadorCeCo)[0])==true) { if (CorreosNotificar==String.Empty) if (profile[Constantes.NOMBRE_CAMPO_PERFIL_CORREO]!=null) CorreosNotificar = Convert.ToString(profile[Constantes.NOMBRE_CAMPO_PERFIL_CORREO]); else CorreosNotificar = CorreosNotificar + ";" + Convert.ToString(profile[Constantes.NOMBRE_CAMPO_PERFIL_CORREO]); } } } }); return CorreosNotificar; } public int Actualizar(string pe_strUrlSitio, string Lista, CentroCostoBE CeCo) { int IDEncontrado = 0; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite objSPSite = new SPSite(pe_strUrlSitio)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { SPList listaDocVigente = objSPWeb.Lists[Lista]; SPQuery spQuery = new SPQuery(); spQuery.RowLimit = 1; spQuery.Query = "<Where>" + "<" + SharePointHelper.OperatorType.Equal + ">" + "<FieldRef Name='" + "Title" + "'/>" + "<Value Type='" + SharePointHelper.FieldTypeCAML.Text_ + "'>" + CeCo.Codigo + "</Value>" + "</" + SharePointHelper.OperatorType.Equal + ">" + "</Where>"; //Obtenemos la colección de items por Lista de documentos vigentes SPListItemCollection lt_DocumentosVigentes = listaDocVigente.GetItems(spQuery); //Validamos si la coleccion de elementos "lt_DocumentosVigentes" no está vacía if (lt_DocumentosVigentes.Count > 0) { IDEncontrado = lt_DocumentosVigentes[0].ID; } } } }); return IDEncontrado; } public int Registrar(string URLSitio, string Biblioteca, CentroCostoBE CeCo) { Dictionary<string, object> dicPropiedades = EstablecerPropiedades(CeCo); int idRegistro = SharePointHelper.AgregarRegistroLista(URLSitio, Biblioteca, dicPropiedades); return idRegistro; } private Dictionary<string, object> EstablecerPropiedades(CentroCostoBE CeCo) { Dictionary<string, object> dicPropiedades = new Dictionary<string, object>(); if (!string.IsNullOrEmpty(CeCo.Codigo)) dicPropiedades.Add("Title", CeCo.Codigo); if (!string.IsNullOrEmpty(CeCo.Descripcion)) dicPropiedades.Add("Descripcion", CeCo.Descripcion); return dicPropiedades; } public List<CentroCostoBE> ObtenerLista(string URLSitio, string ValorFiltro) { List<CentroCostoBE> lstCentroCosto = null; CentroCostoBE oCentroCosto = null; #region SPQuery string spQuery = "<Where>" + "<Or>" + "<Contains>" + "<FieldRef Name='Title' />" + "<Value Type='Text'>" + ValorFiltro + "</Value>" + "</Contains>" + "<Contains>" + "<FieldRef Name='Descripcion' />" + "<Value Type='Text'>" + ValorFiltro + "</Value>" + "</Contains>" + "</Or>" + "</Where>"; #endregion SPListItemCollection splicCentroCosto = null; if (!string.IsNullOrEmpty(ValorFiltro)) splicCentroCosto = SharePointHelper.ObtenerInformacionLista(URLSitio, ListasGestorDocumental.CentrosCosto, spQuery); else splicCentroCosto = SharePointHelper.ObtenerInformacionLista(URLSitio, ListasGestorDocumental.CentrosCosto); if (splicCentroCosto != null) { foreach (SPListItem spliCentroCosto in splicCentroCosto) { oCentroCosto = LeerPropiedades(spliCentroCosto); if (lstCentroCosto == null) lstCentroCosto = new List<CentroCostoBE>(); if (oCentroCosto != null) lstCentroCosto.Add(oCentroCosto); } } if (lstCentroCosto != null) { if (lstCentroCosto.Count > 0) { lstCentroCosto = lstCentroCosto.OrderBy(o => o.Descripcion).ToList(); } } return lstCentroCosto; } public List<CentroCostoBE> ObtenerLista(SPWeb obSPWeb, string ValorFiltro) { List<CentroCostoBE> lstCentroCosto = null; CentroCostoBE oCentroCosto = null; #region SPQuery string spQuery = "<Where>" + "<Or>" + "<Contains>" + "<FieldRef Name='Title' />" + "<Value Type='Text'>" + ValorFiltro + "</Value>" + "</Contains>" + "<Contains>" + "<FieldRef Name='Descripcion' />" + "<Value Type='Text'>" + ValorFiltro + "</Value>" + "</Contains>" + "</Or>" + "</Where>"; #endregion SPListItemCollection splicCentroCosto = null; if (!string.IsNullOrEmpty(ValorFiltro)) splicCentroCosto = SharePointHelper.ObtenerInformacionLista(obSPWeb, ListasGestorDocumental.CentrosCosto, spQuery); else splicCentroCosto = SharePointHelper.ObtenerInformacionLista(obSPWeb, ListasGestorDocumental.CentrosCosto); if (splicCentroCosto != null) { foreach (SPListItem spliCentroCosto in splicCentroCosto) { oCentroCosto = LeerPropiedades(spliCentroCosto); if (lstCentroCosto == null) lstCentroCosto = new List<CentroCostoBE>(); if (oCentroCosto != null) lstCentroCosto.Add(oCentroCosto); } } if (lstCentroCosto != null) { if (lstCentroCosto.Count > 0) { lstCentroCosto = lstCentroCosto.OrderBy(o => o.Descripcion).ToList(); } } return lstCentroCosto; } } }
using eTicaretProjesi.BL.Repository; using eTicaretProjesi.ENT.Model; using eTicaretProjesi.ENT.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using static eTicaretProjesi.ENT.ViewModel.KategorilerViewModel; namespace eTicaretProjesi.Controllers { [Authorize(Roles = "Admin")] public class IslemlerController : Controller { UrunlerRepo ur = new UrunlerRepo(); KategoriRepo kr = new KategoriRepo(); // GET: Islemler public ActionResult KategoriEkle() { return View(); } [HttpPost] public ActionResult KategoriEkle(KategoriViewModel model) { Kategoriler kat = new Kategoriler(); kat.KategoriAD = model.KategoriAd; kr.Ekle(kat); return RedirectToAction("KategoriListele"); } public ActionResult KategoriListele() { KategoriViewModel model = new KategoriViewModel(); model.KategoriList = kr.Listele(); return View(model); } public ActionResult KategoriGuncelle(int id) { KategoriViewModel model = new KategoriViewModel(); model.Kategoriler = kr.IDyeGoreBul(id); return View(model); } [HttpPost] public ActionResult KategoriGuncelle(KategoriViewModel model, int id) { Kategoriler kat = kr.IDyeGoreBul(id); kat.KategoriAD = model.Kategoriler.KategoriAD; kr.Guncelle(); return RedirectToAction("KategoriListele"); } public ActionResult KategoriSil(int id) { Kategoriler kat = kr.IDyeGoreBul(id); kr.Sil(kat); return RedirectToAction("KategoriListele"); } public ActionResult KategoriDetay(int id, KategoriViewModel model) { model.Kategoriler = kr.IDyeGoreBul(id); var AltKategoriler = new List<SelectListItem>(); akr.GenelListele().Where(z => z.KategoriID == id).ToList().ForEach(x => AltKategoriler.Add(new SelectListItem { Value = x.AltKategoriID.ToString(), Text = x.AltKategoriAD })); ViewBag.AltKDetay = AltKategoriler; return View(model); } //alt kategori işlemler AltKategoriRepo akr = new AltKategoriRepo(); public ActionResult AltKategoriEkle() { var KategoriForDropDown = new List<SelectListItem>(); kr.Listele().ForEach(x => KategoriForDropDown.Add(new SelectListItem { Text = x.KategoriAD, Value = x.KategoriID.ToString() })); ViewBag.KategoriDD = KategoriForDropDown; return View(); } [HttpPost] public ActionResult AltKategoriEkle(AltKategoriViewModel model) { KategoriAlt kat = new KategoriAlt(); kat.AltKategoriAD = model.AltKategoriAd; kat.KategoriID = model.Kategoriler.KategoriID; akr.Ekle(kat); return RedirectToAction("AltKategoriListele"); } public ActionResult AltKategoriListele() { KategoriViewModel model = new KategoriViewModel(); model.KategoriList = kr.Listele(); return View(model); } public ActionResult AltKategoriGuncelle(int id) { KategoriViewModel model = new KategoriViewModel(); model.Kategoriler = kr.IDyeGoreBul(id); return View(model); } [HttpPost] public ActionResult AltKategoriGuncelle(KategoriViewModel model, int id) { Kategoriler kat = kr.IDyeGoreBul(id); kat.KategoriAD = model.Kategoriler.KategoriAD; kr.Guncelle(); return RedirectToAction("KategoriListele"); } public ActionResult AltKategoriSil(int id) { Kategoriler kat = kr.IDyeGoreBul(id); kr.Sil(kat); return RedirectToAction("KategoriListele"); } public ActionResult AltKategoriDetay(int id, KategoriViewModel model) { model.Kategoriler = kr.IDyeGoreBul(id); return View(model); } public ActionResult UrunListele() { UrunlerViewModel model = new UrunlerViewModel(); model.UrunlerList = ur.Listele(); return View(model); //var model = ur.Listele(); //return View(model); } [HttpGet] public ActionResult UrunEkle() { return View(); } [HttpPost] public ActionResult UrunEkle(UrunlerViewModel model) { Urunler urun = new Urunler(); urun.UrunAD = model.UrunAD; urun.UrunFiyat = model.UrunFiyat; urun.UrunTanitim = model.UrunTanitim; urun.UrunAciklama = model.UrunAciklama; urun.GununUrunu = model.GununUrunu; return RedirectToAction("UrunListele"); } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Linq; using System.Net; using System.Threading.Tasks; namespace LighterApi { /// <summary> /// 自定义中间件 /// </summary> public class TokenValidateMiddleware { private readonly RequestDelegate _next; public TokenValidateMiddleware(RequestDelegate next) { _next = next; } /// <summary> /// /// </summary> /// <param name="httpContext"></param> /// <param name="env"></param> /// <returns></returns> public async Task Invoke(HttpContext httpContext, IWebHostEnvironment env) { //StringValues token = new StringValues(); //if (!httpContext.Request.Headers.TryGetValue("Authorization", out token)) // throw new ArgumentNullException(); //httpContext.Items["token"] = WebUtility.HtmlEncode(token.FirstOrDefault()); await _next(httpContext); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ricky.Infrastructure.Core; using Ricky.Infrastructure.Core.Generic; using VnStyle.Services.Business.Models; using VnStyle.Services.Data; using VnStyle.Services.Data.Domain; namespace VnStyle.Services.Business { public class VideoService : IVideoService { private readonly IBaseRepository<Movie> _movieRepository; public VideoService(IBaseRepository<Movie> movieRepository) { _movieRepository = movieRepository; } public List<VideoListingModel> GetRelatedVideo() { var movies = _movieRepository.Table.OrderByDescending(p => p.Id).Select(p => new VideoListingModel { Id = p.Id, Link = p.Link, Title = p.Title }).Take(5).ToList(); return movies; } public VideoListingModel GetVideoById(int id) { var movie = _movieRepository.Table.Where(p => p.Id == id).Select(p => new VideoListingModel { Id = p.Id , Link = p.Link , Title = p.Title }).FirstOrDefault(); return movie; } //public IList<VideoListingModel> GetVideoThumb() //{ // return _movieRepository.Table.OrderByDescending(p => p.Id).Select(p => new VideoListingModel { Id = p.Id, Link = p.Link , Title = p.Title}).ToList(); //} public IPagedList<VideoListingModel> GetVideoThumb(PagingRequest request) { if (request.PageIndex < 0) request.PageIndex = 0; if (request.PageSize < 1) request.PageSize = 10; var movie = _movieRepository.Table.OrderByDescending(p => p.Id).Select(p => new VideoListingModel { Id = p.Id, Link = p.Link, Title = p.Title }); var pageMovie = movie.Skip(request.PageIndex * request.PageSize).Take(request.PageSize).ToList(); var count = movie.Count(); return new PagedList<VideoListingModel>(pageMovie, request.PageIndex, request.PageSize, count); } } }
using UnityEngine; namespace UnityAtoms { /// <summary> /// Utility methods for IMGUI. /// </summary> public static class IMGUIUtils { /// <summary> /// Snip a `Rect` horizontally. /// </summary> /// <param name="rect">The rect.</param> /// <param name="range">The range.</param> /// <returns>A new `Rect` snipped horizontally.</returns> private static Rect SnipRectH(Rect rect, float range) { if (range == 0) return new Rect(rect); if (range > 0) { return new Rect(rect.x, rect.y, range, rect.height); } return new Rect(rect.x + rect.width + range, rect.y, -range, rect.height); } /// <summary> /// Snip a `Rect` horizontally. /// </summary> /// <param name="rect">The rect.</param> /// <param name="range">The range.</param> /// <param name="rest">Rest rect.</param> /// <param name="gutter">Gutter</param> /// <returns>A new `Rect` snipped horizontally.</returns> public static Rect SnipRectH(Rect rect, float range, out Rect rest, float gutter = 0f) { if (range == 0) rest = new Rect(); if (range > 0) { rest = new Rect(rect.x + range + gutter, rect.y, rect.width - range - gutter, rect.height); } else { rest = new Rect(rect.x, rect.y, rect.width + range + gutter, rect.height); } return SnipRectH(rect, range); } /// <summary> /// Snip a `Rect` vertically. /// </summary> /// <param name="rect">The rect.</param> /// <param name="range">The range.</param> /// <returns>A new `Rect` snipped vertically.</returns> private static Rect SnipRectV(Rect rect, float range) { if (range == 0) return new Rect(rect); if (range > 0) { return new Rect(rect.x, rect.y, rect.width, range); } return new Rect(rect.x, rect.y + rect.height + range, rect.width, -range); } /// <summary> /// Snip a `Rect` vertically. /// </summary> /// <param name="rect">The rect.</param> /// <param name="range">The range.</param> /// <param name="rest">Rest rect.</param> /// <param name="gutter">Gutter</param> /// <returns>A new `Rect` snipped vertically.</returns> public static Rect SnipRectV(Rect rect, float range, out Rect rest, float gutter = 0f) { if (range == 0) rest = new Rect(); if (range > 0) { rest = new Rect(rect.x, rect.y + range + gutter, rect.width, rect.height - range - gutter); } else { rest = new Rect(rect.x, rect.y, rect.width, rect.height + range + gutter); } return SnipRectV(rect, range); } } }
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OTAKURAO_wasm.Shared { public partial class Footer { public Footer() { } } }
using Microsoft.EntityFrameworkCore; namespace PostgresIssue855 { public class TestContext : DbContext { public DbSet<TestClass> MyClasses { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseNpgsql( "User ID=postgres;Password=password;Server=localhost;Port=5432;Database=test;Integrated Security=true;Pooling=true;"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text.RegularExpressions; using FontAwesome5.Extensions; namespace FontAwesome5.UWP.Example.ViewModels { public class MainViewModel : INotifyPropertyChanged { public MainViewModel() { AllIcons = Enum.GetValues(typeof(EFontAwesomeIcon)).Cast<EFontAwesomeIcon>() .OrderBy(i => i.GetStyle()).ThenBy(i => i.GetLabel()).ToList(); AllIcons.Remove(EFontAwesomeIcon.None); UpdateVisibleIcons(); FlipOrientations = Enum.GetValues(typeof(EFlipOrientation)).Cast<EFlipOrientation>().ToList(); SpinDuration = 5; PulseDuration = 5; FontSize = 30; Rotation = 0; } private EFontAwesomeIcon _selectedIcon; public EFontAwesomeIcon SelectedIcon { get => _selectedIcon; set { _selectedIcon = value; RaisePropertyChanged(nameof(SelectedIcon)); RaisePropertyChanged(nameof(FontText)); } } private bool _spinIsEnabled; public bool SpinIsEnabled { get => _spinIsEnabled; set { _spinIsEnabled = value; RaisePropertyChanged(nameof(SpinIsEnabled)); RaisePropertyChanged(nameof(FontText)); } } private double _spinDuration; public double SpinDuration { get => _spinDuration; set { _spinDuration = value; RaisePropertyChanged(nameof(SpinDuration)); RaisePropertyChanged(nameof(FontText)); } } private bool _pulseIsEnabled; public bool PulseIsEnabled { get => _pulseIsEnabled; set { _pulseIsEnabled = value; RaisePropertyChanged(nameof(PulseIsEnabled)); RaisePropertyChanged(nameof(FontText)); } } private double _pulseDuration; public double PulseDuration { get => _pulseDuration; set { _pulseDuration = value; RaisePropertyChanged(nameof(PulseDuration)); RaisePropertyChanged(nameof(FontText)); } } private EFlipOrientation _flipOrientation; public EFlipOrientation FlipOrientation { get => _flipOrientation; set { _flipOrientation = value; RaisePropertyChanged(nameof(FlipOrientation)); RaisePropertyChanged(nameof(FontText)); } } private double _fontSize; public double FontSize { get => _fontSize; set { _fontSize = value; RaisePropertyChanged(nameof(FontSize)); RaisePropertyChanged(nameof(FontText)); } } private double _rotation; public double Rotation { get => _rotation; set { _rotation = value; RaisePropertyChanged(nameof(Rotation)); RaisePropertyChanged(nameof(FontText)); } } public List<EFlipOrientation> FlipOrientations { get; set; } = new List<EFlipOrientation>(); public List<EFontAwesomeIcon> AllIcons { get; set; } = new List<EFontAwesomeIcon>(); public string FontText => $"<fa5:FontAwesome Icon=\"{SelectedIcon}\" Fontsize=\"{FontSize}\" Spin=\"{SpinIsEnabled}\" " + $"SpinDuration=\"{SpinDuration}\" Pulse=\"{PulseIsEnabled}\" PulseDuration=\"{PulseDuration}\" FlipOrientation=\"{FlipOrientation}\" >"; public void RaisePropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #region Visible Icon Filtering public List<EFontAwesomeIcon> VisibleIcons { get; private set; } private string _filterText; public string FilterText { get => _filterText; set { _filterText = value; UpdateVisibleIcons(); } } private void UpdateVisibleIcons() { var addAll = string.IsNullOrWhiteSpace(FilterText); //Confirm regex is valid if (!addAll) { try { _ = Regex.IsMatch(string.Empty, FilterText); } catch (Exception) { addAll = true; } } //Add all if no proper filter is applied VisibleIcons = addAll ? AllIcons : new List<EFontAwesomeIcon>(AllIcons.Where(icon => Regex.IsMatch( icon.GetInformation().Label , FilterText , RegexOptions.IgnoreCase ))); SelectedIcon = VisibleIcons.FirstOrDefault(); RaisePropertyChanged(nameof(VisibleIcons)); RaisePropertyChanged(nameof(SelectedIcon)); } #endregion } }
using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace VoxelSpace { using IO; public class MouseLook : IBinaryReadWritable { public float Sensitivity = 5; public Vector2 Look; Point _screenCenter; public MouseLook(Point screenCenter) { _screenCenter = screenCenter; } public void CenterMouse() { Mouse.SetPosition(_screenCenter.X, _screenCenter.Y); } public void ReadBinary(BinaryReader reader) { Look.ReadBinary(reader); } public void WriteBinary(BinaryWriter writer) { Look.WriteBinary(writer); } public Vector2 Update() { var lookDelta = Input.MouseUtil.GetRawPositionState(); Input.MouseUtil.SetRawPositionState(Vector2.Zero); lookDelta *= Time.DeltaTime * Sensitivity; Look += lookDelta; Look.Y = MathHelper.Clamp(Look.Y, -90, 90); CenterMouse(); return lookDelta; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using WebQLKhoaHoc; using WebQLKhoaHoc.Models; namespace WebQLKhoaHoc.Controllers { [CustomizeAuthorize(Roles = "1")] public class AdminNhaXuatBanController : Controller { private QLKhoaHocEntities db = new QLKhoaHocEntities(); // GET: AdminNhaXuatBan public async Task<ActionResult> Index() { return View(await db.NhaXuatBans.ToListAsync()); } // GET: AdminNhaXuatBan/Create public ActionResult Create() { return View(); } // POST: AdminNhaXuatBan/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "MaNXB,TenNXB,DiaChiNXB,DienThoaiNXB,DiaChiWeb")] NhaXuatBan nhaXuatBan) { if (ModelState.IsValid) { db.NhaXuatBans.Add(nhaXuatBan); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(nhaXuatBan); } // GET: AdminNhaXuatBan/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } NhaXuatBan nhaXuatBan = await db.NhaXuatBans.FindAsync(id); if (nhaXuatBan == null) { return HttpNotFound(); } return View(nhaXuatBan); } // POST: AdminNhaXuatBan/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "MaNXB,TenNXB,DiaChiNXB,DienThoaiNXB,DiaChiWeb")] NhaXuatBan nhaXuatBan) { if (ModelState.IsValid) { db.Entry(nhaXuatBan).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(nhaXuatBan); } // GET: AdminNhaXuatBan/Delete/5 public async Task<ActionResult> Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } NhaXuatBan nhaXuatBan = await db.NhaXuatBans.FindAsync(id); if (nhaXuatBan == null) { return HttpNotFound(); } return View(nhaXuatBan); } // POST: AdminNhaXuatBan/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(int id) { NhaXuatBan nhaXuatBan = await db.NhaXuatBans.FindAsync(id); db.NhaXuatBans.Remove(nhaXuatBan); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace MAS_Końcowy.Model { public class Waiter { [Key, ForeignKey("Employee")] public int Id { get; set; } private Employee _employee; public Employee Employee { get => _employee; set { if (value != _employee) { _employee = value; value.Waiter = this; } } } public ICollection<Order> Orders { get; set; } public Waiter() { } internal void RemoveOrder(Order order) { if (Orders.Contains(order)) { Orders.Remove(order); order.Waiter = null; } } internal void AddOrder(Order order) { if (!Orders.Contains(order)) { Orders.Add(order); order.Waiter = null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LAB2 { public class CriteriaSearch { private int id; private string criteria; public string Criteria { get { return criteria; } set { criteria = value; } } public int Id { get { return id; } set { id = value; } } public CriteriaSearch() { } public CriteriaSearch(int vid, string vcriteria) { this.Id = vid; this.Criteria = vcriteria; } public static List<CriteriaSearch> listCriteria; public static List<CriteriaSearch> CreateListCriteria() { listCriteria = new List<CriteriaSearch>(); CriteriaSearch criteria1 = new CriteriaSearch(0, "Code"); listCriteria.Add(criteria1); CriteriaSearch criteria2 = new CriteriaSearch(1, "Name"); listCriteria.Add(criteria2); CriteriaSearch criteria3 = new CriteriaSearch(2, "Price"); listCriteria.Add(criteria3); CriteriaSearch criteria4 = new CriteriaSearch(3, "Date"); listCriteria.Add(criteria4); CriteriaSearch criteria5 = new CriteriaSearch(4, "Category"); listCriteria.Add(criteria5); return listCriteria; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Window_Resurgence : MonoBehaviour { private GameObject _shop_Copy; public Image OK; void OnEnable() { MyKeys.Pause_Game = true; //根据钻石数判定按钮状态 if (MyKeys.Diamond_Value > MyKeys.ResurgenceCost) { OK.raycastTarget = true; OK.color = Color.white; } else { OK.raycastTarget = false; OK.color = Color.gray; } _shop_Copy = GameUIManager.ShowShop(); } public void OnDisable() { EffectManager.Instance.WindowEffect(false,_shop_Copy); } }
using ConsumeCrude.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Mvc; namespace ConsumeCrude.Controllers.mvc { public class SampleController : Controller { public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(stud_Details student) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:60188//api/"); //HTTP POST var postTask = client.PostAsJsonAsync("student", student); postTask.Wait(); var result = postTask.Result; if (result.IsSuccessStatusCode) { return RedirectToAction("Index"); } } ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator."); return View(student); } } }
using Microsoft.EntityFrameworkCore; using SnowDAL.DBModels; using SnowDAL.Repositories.Concrete; using SnowDAL.Repositories.Interfaces; using System.Linq; using System; using System.Collections.Generic; using System.Threading.Tasks; using SnowDAL.Searching; using SnowDAL.Extensions; using SnowDAL.Paging; using System.Data; using Npgsql; using Microsoft.EntityFrameworkCore.ChangeTracking; namespace SnowDAL.Concrete.Repositories { public class RouteRepository : EntityBaseRepository<RouteInfoEntity>, IRouteRepository { public RouteRepository(EFContext context) : base(context) { } public string GenerateGISLine(string line) { return "a"; } public async Task<RouteInfoEntity> GetSingleWithDependencies(int id) { return await this._context.Routes .Include(r => r.Geometry) .Include(r => r.User) .Include(r => r.Point) .FirstOrDefaultAsync(r => r.ID == id && r.Status == 1); } public bool IsValidLine(string line) { try { bool result = false; using (NpgsqlConnection conn = new NpgsqlConnection(_context.Database.GetDbConnection().ConnectionString)) { conn.Open(); NpgsqlCommand command = new NpgsqlCommand(RouteGeomEntityProcedures.ISVALIDROUTE_PROCEDURE, conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@line", line); NpgsqlDataReader dr = command.ExecuteReader(); while (dr.Read()) result = (bool)dr[0]; dr.Close(); conn.Close(); } return result; } catch (Exception ex) { return false; } } public async Task<IEnumerable<RouteGeomEntity>> GetGeometries(int[] ids) { return await this._context.RoutesGeom.Where(route => ids.Any(id => id == route.RouteInfo.ID && route.RouteInfo.Status == 1)).ToListAsync(); } public async Task<PagingResult<RouteInfoEntity>> Search(SearchQuery<RouteInfoEntity> searchQuery) { IQueryable<RouteInfoEntity> sequence = this._context.Routes; sequence = ManageFilters(searchQuery.FiltersDictionary, sequence); sequence = ManageIncludeProperties(searchQuery.IncludeProperties, sequence); sequence = ManageSortCriterias(searchQuery.SortCriterias, sequence); return await GetTheResult(searchQuery, sequence); } public async Task<PagingResult<RouteInfoEntity>> GetRoutesInRange(QueryPager pager, string point, int kilometers) { List<int> ids = new List<int>(pager.Take); long count = 0; using (NpgsqlConnection conn = new NpgsqlConnection(_context.Database.GetDbConnection().ConnectionString)) { conn.Open(); var getInRangeCountCommand = new NpgsqlCommand(RouteGeomEntityProcedures.GETINRANGECOUNT_PROCEDURE, conn); getInRangeCountCommand.CommandType = CommandType.StoredProcedure; getInRangeCountCommand.Parameters.AddWithValue(@"point", point); getInRangeCountCommand.Parameters.AddWithValue(@"dist", kilometers); NpgsqlDataReader countDataReader = getInRangeCountCommand.ExecuteReader(); while (countDataReader.Read()) count = (long)countDataReader[0]; countDataReader.Close(); var getInRangeCommand = new NpgsqlCommand(RouteGeomEntityProcedures.GETINRANGE_PROCEDURE, conn); getInRangeCommand.CommandType = CommandType.StoredProcedure; getInRangeCommand.Parameters.AddWithValue("@point", point); getInRangeCommand.Parameters.AddWithValue("@dist", kilometers); getInRangeCommand.Parameters.AddWithValue("@take", pager.Take); getInRangeCommand.Parameters.AddWithValue("@skip", pager.Skip); var rangeDataReader = getInRangeCommand.ExecuteReader(); while (rangeDataReader.Read()) ids.Add((int)rangeDataReader[0]); rangeDataReader.Close(); conn.Close(); } return new PagingResult<RouteInfoEntity>() { Count = (int)count, HasNext = (pager.Skip <= 0 && pager.Take <= 0) ? false : (pager.Skip + (pager.Take - 1) < count), Results = await _context.Routes.Where(r => ids.Any(id => id == r.ID)).ToListAsync() }; } public override void Delete(RouteInfoEntity entity) { entity.Geometry.Status = 0; EntityEntry geomEntity = _context.Entry(entity.Geometry); geomEntity.State = EntityState.Modified; entity.Point.Status = 0; EntityEntry pointEntity = _context.Entry(entity.Point); pointEntity.State = EntityState.Modified; base.Delete(entity); } } }
using Newtonsoft.Json; namespace GetXRAYTestExcecutionStatusFromJenkins.Entities { #region using #endregion public class BaseEntity { [JsonProperty("self")] public string Self { get; set; } } }
namespace DelftTools.Utils { public static class IEditableObjectExtensions { public static void BeginEdit(this IEditableObject obj, string actionName) { obj.BeginEdit(new DefaultEditAction(actionName)); } } }
using System; namespace PyramidPatterns { class Program { static void Main(string[] args) { Console.WriteLine("Pattern A"); int number = 6; for (int i = 1; i <=number; i++) { for (int j = 1; j <= i; j++) Console.Write(j + " "); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Pattern B"); for (int i = number; i > 0; i--) { for (int j = 1; j <= i; j++) Console.Write(j + " "); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Pattern C"); int repeat = number * 2; for (int i = 1; i <= number; i++) { for (int z = 0; z < repeat; z++)Console.Write(" "); for (int j = i; j >=1; j--) Console.Write(j + " "); Console.WriteLine(); repeat -= 2; } Console.WriteLine(); Console.WriteLine("Pattern D"); number = 6; repeat = 0; for (int i = number; i > 0; i--) { for (int z = 0; z < repeat; z++) Console.Write(" "); for (int j = 1; j <= i; j++) Console.Write(j + " "); Console.WriteLine(); repeat+=2; } } } }
using Hayaa.DataAccess; using Hayaa.UserAuth.Service.Core.Config; using System; using System.Collections.Generic; using System.Text; namespace Hayaa.UserAuth.Service.Core.DataAccess { class UserSessionDal : CommonDal { private static String con = ConfigHelper.Instance.GetConnection(DefineTable.DatabaseName); internal static UserSession Get(string sessionKey) { string sql = "select * from UserSession where SessionKey=@SessionKey and Status=1"; return Get<UserSession>(con, sql, new { SessionKey=sessionKey }); } internal static int Add(UserSession info) { string sql = "insert into UserSession(UserId,SessionKey,Status) value(@UserId,@SessionKey,@Status);select @@IDENTITY;"; return InsertWithReturnID<UserSession, int>(con, sql, info); } } }
using GucciBazaar.Models; using Microsoft.AspNet.Identity; using System; using System.Linq; using System.Web.Mvc; namespace GucciBazaar.Controllers { [Authorize(Roles = "User,Editor,Administrator")] public class ReviewController : Controller { private readonly ApplicationDbContext db = new ApplicationDbContext(); [HttpPost] [Route("Review/New")] public ActionResult New(Review review) { var product = db.Products.Where( m => m.Id == review.ProductId).ToList().FirstOrDefault(); var reviewRating = review.Rating; var numberOfRatings = product.Reviews.Count(); var sumOfRatings = product.Reviews.Sum(r => r.Rating); numberOfRatings++; sumOfRatings += reviewRating; product.Rating = sumOfRatings / numberOfRatings; try { if (ModelState.IsValid) { db.Reviews.Add(review); db.SaveChanges(); TempData["message"] = "A fost adaugat reviewul!"; return RedirectToAction($"Show/{product.Id}", "Product"); } else { return RedirectToAction($"Show/{product.Id}", "Product"); } } catch (Exception) { return RedirectToAction($"Show/{product.Id}", "Product"); } } [HttpDelete] [Route("Review/Delete/{Id}")] public ActionResult Delete(long Id) { var review = db.Reviews.Find(Id); var reviewRating = review.Rating; var productId = review.ProductId; Product product = db.Products.Where(m => m.Id == review.ProductId).ToList().FirstOrDefault(); var numberOfRatings = product.Reviews.Count(); var sumOfRatings = product.Reviews.Sum(r => r.Rating); numberOfRatings--; sumOfRatings -= reviewRating; product.Rating = sumOfRatings / numberOfRatings; try { if (ModelState.IsValid) { db.Reviews.Remove(review); db.SaveChanges(); TempData["message"] = "A fost adaugat reviewul!"; return RedirectToAction($"Show/{productId}", "Product"); } else { return RedirectToAction($"Show/{productId}", "Product"); } } catch (Exception) { return RedirectToAction($"Show/{productId}", "Product"); } } [HttpGet] [Route("Review/Edit/{Id}")] public ActionResult Edit(long Id) { Review review = db.Reviews.Find(Id); var productId = review.ProductId; Product product = db.Products.Find(productId); if (review.UserId == User.Identity.GetUserId() || User.IsInRole("Administrator")) { return View("~/Views/Product/EditReview.cshtml", review); } else { TempData["message"] = "Nu aveti dreptul sa faceti modificari asupra unui review care nu va apartine!"; return RedirectToAction("Index"); } } [HttpPut] [Route("Review/Edit/{Id}")] public ActionResult Edit(long Id, Review newReview) { var review = db.Reviews.Find(Id); var reviewRating = review.Rating; var productId = review.ProductId; Product product = db.Products.Where(m => m.Id == review.ProductId).ToList().FirstOrDefault(); try { if (ModelState.IsValid) { review.Rating = newReview.Rating; review.Title = newReview.Title; review.Description = newReview.Description; review.UpdateDate = DateTime.UtcNow; var numberOfRatings = product.Reviews.Count(); var sumOfRatings = product.Reviews.Sum(r => r.Rating); product.Rating = sumOfRatings / numberOfRatings; db.SaveChanges(); TempData["message"] = "A fost modificat reviewul!"; return RedirectToAction($"Show/{productId}", "Product"); } else { return RedirectToAction($"Show/{productId}", "Product"); } } catch (Exception) { return RedirectToAction($"Show/{productId}", "Product"); } } } }
using System.Collections.Generic; namespace DFC.ServiceTaxonomy.GraphVisualiser.Models.Owl { public partial class ClassAttribute { public string? Id { get; set; } public string? Iri { get; set; } public string? BaseIri { get; set; } public string? Label { get; set; } public string? Comment { get; set; } public List<string> Attributes { get; set; } = new List<string>(); public string? StaxBackgroundColour { get; set; } public List<string> StaxProperties { get; set; } = new List<string>(); } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using RiverPuzzle.Factories; using RiverPuzzle1.Models; using System; namespace RiverPuzzle1.JsonConverters { public class CharacterJsonConverter : JsonConverter { public override bool CanWrite => false; public override bool CanConvert(Type objectType) { return objectType == typeof(Character); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); var target = GetCharacter(objectType, jsonObject); serializer.Populate(jsonObject.CreateReader(), target); return target; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } private Character GetCharacter(Type objectType, JObject jsonObject) { string typeName = jsonObject.GetValue("name", StringComparison.OrdinalIgnoreCase).ToString(); return CharacterFactory.Build(typeName); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GridToggleScript : MonoBehaviour { // Update is called once per frame void Update () { if (Input.GetKeyDown("g")) { if (transform.position.z == 1) transform.Translate(new Vector3(0, 0, 2)); else transform.Translate(new Vector3(0, 0, -2)); } } }
using AutoFixture; using AutoFixture.Kernel; namespace Leprechaun.Tests.Test.SpecimenBuilders.StandardArchitectorValidator { public interface ITemplateMetadataSpec : ISpecimenBuilder { void Init(IFixture fixture); } }
using Tomelt.UI.Resources; namespace Tomelt.Widgets { public class ResourceManifest : IResourceManifestProvider { public void BuildManifests(ResourceManifestBuilder builder) { builder.Add().DefineStyle("WidgetsAdmin").SetUrl("tomelt-widgets-admin.css").SetDependencies("~/Themes/TheAdmin/Styles/Site.css"); } } }
using System; using com.Sconit.Entity; namespace com.Sconit.Entity.SI.BAT { [Serializable] public partial class JobParameter : EntityBase { #region O/R Mapping Properties public Int32 Id { get; set; } public string JobCode { get; set; } public string Key { get; set; } public string Value { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { JobParameter another = obj as JobParameter; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Sirenix.OdinInspector; [CreateAssetMenu(menuName = "Data/SFXSet")] public class SFXSet : SerializedScriptableObject { public Dictionary<string, List<AudioClip>> sources; public void Play(string id, AudioSource source) { // Debug.Log($"Playing: {id}"); List<AudioClip> clips = sources[id]; int index = Random.Range(0, clips.Count-1); source.Stop(); source.PlayOneShot(clips[index]); } }
using MyForum.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyForum.Services.Contracts { public interface ICommentsService { void CreateComment(string content, string threadId, string creatorId); void CreateCommentQuote(string content, string threadId, string creatorId, string quote); IQueryable<Comment> GetAllComments(); Task<Comment> GetCommentById(string commentId); Task Delete(string commentId); Task Edit(string commentId, string content, DateTime modifiedOn); } }
using UnityEngine; using System.Collections; using System.IO; using UnityEngine.UI; using System; /// <summary> /// /// </summary> public class EnvCheckInit : MonoBehaviour { public AssetUpdater _assetUpdater; //public Text statusText; //public Text descText; public Slider progressSlider; //public Image bottomImage; //public Text versionText; //public Text tip; //public GameObject enterButtonObj; //public GameObject loadingObj; string m_szCurrentVersion; void Awake() { //Once("event_lang_initialized", _start); //Once("LuaMangager_Started", GameStart); //On("Notice_Loaded", _noticeLoaded); //Once("MainPlayer_DataLoaded", _playerDataLoaded); //Once("ChannelManager_initialized", LocalVerCheck); //_assetUpdater = GetComponent<AssetUpdater>(); //progressSlider.gameObject.SetActive(false); //enterButtonObj.SetActive(false); //loadingObj.SetActive(true); //ClientConfig.Load(); //LangSetting.Initialize(); } /// <summary> /// 本地版本检查 /// </summary> public void LocalVerCheck(params object[] args) { //progressSlider.gameObject.SetActive(true); StartCoroutine(CheckVersion()); } /// <summary> /// 版本检查 /// </summary> /// <returns></returns> IEnumerator CheckVersion() { string path = Globals.wwwPersistenPath + "/version.txt"; WWW www = new WWW(path); yield return www; SampleDebuger.Log("version = " + www.text); if (string.IsNullOrEmpty(www.text) || (www.error != null)) { //没读取到,是第一次安装,拷贝资源 SampleDebuger.Log("First Time Launch!"); //读取应用程序版本号 www = new WWW(Globals.wwwStreamingPath + "/version.txt"); yield return www; m_szCurrentVersion = www.text.Trim(); //versionText.text = currentVersion; BeginCopy(); www.Dispose(); } else { //已安装过 SampleDebuger.Log(" installed"); string oldVersion = www.text.Trim(); //读取当前旧版本号 //读取应用程序版本号 www = new WWW(Globals.wwwStreamingPath + "/version.txt"); yield return www; m_szCurrentVersion = www.text.Trim(); //versionText.text = currentVersion; //版本号小于安装程序中包含的版本号,删除旧资源再拷贝当前资源 Version old_v = new Version(oldVersion); Version app_v = new Version(m_szCurrentVersion); if (old_v.IsLower(app_v)) { string abPath = Application.persistentDataPath + "/AssetBundles"; FileUtil.RemoveFolder(abPath); BeginCopy(); } else { VersionManager.Instance().proCurVersion = oldVersion; _assetUpdater.CheckVersionWithServer(); } } } /// <summary> /// 开始下载 /// </summary> public void StartDownload() { SampleDebuger.Log("start down load"); _assetUpdater.StartDownload(); } /// <summary> /// 更新下载进度 /// </summary> /// <param name="done"></param> /// <param name="total"></param> public void DownloadProcess(long done, long total) { SampleDebuger.Log("++ done: " + done + " total: " + total); progressSlider.value = done > 0 ? (float)done / (float)total : 0; //descText.text = LangSetting.GetWord("UI_DownLoadingRes_desc"); //statusText.text = Mathf.Floor(done / 1024).ToString() + "KB /" + Mathf.Floor(total / 1024).ToString() + "KB"; } /// <summary> /// 更新拷贝进度 /// </summary> /// <param name="done"></param> /// <param name="total"></param> /// <param name="content"></param> public void SetProcess(int done, int total, string content = null) { float percent = done > 0.0f ? (float)done / (float)total : 0.0f; progressSlider.value = percent; //statusText.text = ((int)(percent * 100)).ToString() + "%"; //if (!string.IsNullOrEmpty(content)) // descText.text = content; //"游戏初始化中,此过程不消耗流量! "; } ///<summary> ///开始拷贝, 完成更新应用程序的同步过程 ///即解压安装过程 /// </summary> private void BeginCopy() { StartCoroutine(BeginCopy(Globals.wwwStreamingPath)); } /// <summary> /// 将文件拷贝到路径中 /// </summary> /// <param name="streamPath"></param> /// <returns></returns> IEnumerator BeginCopy(string path) { yield return new WaitForSeconds(2.0f); WWW www = new WWW(path + "/streamPath.txt"); yield return www; string[] content = www.text.Split(new string[] { "\n" }, System.StringSplitOptions.RemoveEmptyEntries); www.Dispose(); int total = content.Length; int curIndex = 0; foreach (string item in content) { string it = item.Trim(); //window下会有\r,需要删除 int fileFlag = int.Parse(it.Split('|')[1]); it = it.Split('|')[0]; SampleDebuger.Log(path); it = it.Trim(); if (fileFlag == 1) { www = new WWW(path + it); yield return www; File.WriteAllBytes(Application.persistentDataPath + it, www.bytes); //更新进度 SetProcess(curIndex, total); www.Dispose(); } else if (fileFlag == 0) { SampleDebuger.Log("Create dir " + Application.persistentDataPath + it); Directory.CreateDirectory(Application.persistentDataPath + it); } else { SampleDebuger.LogError("既不是文件夹也不是文件 路径为" + Application.persistentDataPath + it); } ++curIndex; } SampleDebuger.Log(" writeversion"); // 同步版本 VersionManager.Instance().proCurVersion = m_szCurrentVersion; _assetUpdater.CheckVersionWithServer(); } public void GameInit() { //InvokeRepeating("_rollTips", 0, 2); StartCoroutine(_gameInit()); } IEnumerator _gameInit() { //LuaManager.Initialize(); yield return null; AssetBundleLoader.Instance().LoadLevelAsset(GameConstant.g_szChoseServerScene); } void GameStart(params object[] arg) { StartCoroutine(_gameStart()); } IEnumerator _gameStart() { //LuaManager.Instance.OpenLibs(); //setProcess(3, 20); //yield return 1; //LuaManager.Instance.Setup(); //setProcess(4, 20); //yield return 1; //LuaManager.Instance.Setup2(); //setProcess(11, 20); //yield return 1; //LuaManager.Instance.Setup3(); //setProcess(12, 20); //yield return 1; //LuaManager.Instance.Setup4(); //setProcess(13, 20); //yield return 1; //LuaManager.Instance.StartMain(); //setProcess(18, 20); //yield return 1; //LuaManager.Instance.StartLooper(); //setProcess(19, 20); //yield return 1; //string bankStr = LuaManager.Instance.CallFunction("GetWwiseBankNames")[0].ToString(); //Debug.Log("bankStr " + bankStr); //AudioCtrl.Init(bankStr); //setProcess(20, 20); yield return 1; AssetManager.Instance().PreloadAsset((done, total) => { SetProcess(done, total); if (done >= total) { //UGuiManager.Initialize(); //EventDispatcher.Instance.Emit("GetNotcie"); } }); } //void _rollTips() //{ // if (tipIndex >= tipArr.Length - 1) // { // tipIndex = 0; // } // descText.text = LangSetting.GetWord(tipArr[tipIndex]); // tipIndex++; //} void _noticeLoaded(params object[] arg) { //loadingObj.SetActive(false); LoginGame(); } public void LoginGame() { //ChannelManager.Instance.RequirePermission(8, (ret) => //{ // if (ret) // { // EventDispatcher.Instance.Emit("ResetLoginManager"); // } // else // { // enterButtonObj.SetActive(!ret); // } //}); } void _playerDataLoaded(params object[] args) { AssetBundleLoader.Instance().LoadLevelAsset("home", () => { AssetBundleManager.UnloadAssetBundle("assets/abres/scene/updater", true); }); } void OnDestroy() { //Off("Notice_Loaded", _noticeLoaded); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.Sconit.Web.Models.SearchModels.ORD { public class DistributionOrderSearchModel : SearchModelBase { public string OrderNo { get; set; } public string Flow { get; set; } public Int16? Type { get; set; } public DateTime? DateFrom { get; set; } public DateTime? DateTo { get; set; } public Int16? Priority { get; set; } public Int16? Status { get; set; } public string PartyFrom { get; set; } public string PartyFromName { get; set; } public string PartyTo { get; set; } public string PartyToName { get; set; } public string Shift { get; set; } public string ItemCode { get; set; } public string ItemDescription { get; set; } public string CreateUserName { get; set; } } }