text
stringlengths
13
6.01M
using MarsRoverProject.Contracts.Data; using System.Collections.Generic; namespace MarsRoverProject.Domain { public class MarsSurfaceInfo : IMarsSurfaceInfo { private List<Rover> rovers; private Location borders; public MarsSurfaceInfo(List<Rover> rovers, Location borders) { this.rovers = rovers; this.borders = borders; } public List<Rover> Rovers { get => rovers; set => rovers = value; } public Location Borders => borders; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebFormsConnectionString.MySessionUtility { public class MySession { private MySession() { //properties; } public static MySession Current { get { MySession mySession = (MySession)HttpContext.Current.Session["__MySession__"]; if (mySession == null) { mySession = new MySession(); HttpContext.Current.Session["__MySession__"] = mySession; } return mySession; } } //properties public string User_Id { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Models { /// <summary> /// A Module object represents a row in the modules view. /// Two attributes are mandatory: an id identifies a module in the modules view and is used in a ModuleEvent for identifying a module for adding, updating or /// deleting. /// The name is used to minimally render the module in the UI. /// Additional attributes can be added to the module.They will show up in the module View if they have a corresponding ColumnDescriptor. /// To avoid an unnecessary proliferation of additional attributes with similar semantics but different names /// we recommend to re-use attributes from the ‘recommended’ list below first, and only introduce new attributes if nothing appropriate could be found. /// </summary> public record Module { /// <summary> /// Unique identifier for the module. /// </summary> public NumberString Id { get; init; } /// <summary> /// A name of the module. /// </summary> public string Name { get; init; } = null!; /// <summary> /// optional but recommended attributes. /// always try to use these first before introducing additional attributes. /// /// Logical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module. /// </summary> [Optional] public string? Path { get; init; } /// <summary> /// True if the module is optimized. /// </summary> [Optional] public bool IsOptimized { get; init; } /// <summary> /// True if the module is considered 'user code' by a debugger that supports 'Just My Code'. /// </summary> [Optional] public bool IsUserCode { get; init; } /// <summary> /// Version of Module. /// </summary> [Optional] public string? Version { get; init; } /// <summary> /// User understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc. /// </summary> [Optional] public string? SymbolStatus { get; init; } /// <summary> /// Logical full path to the symbol file. The exact definition is implementation defined. /// </summary> [Optional] public string? SymbolFilePath { get; init; } /// <summary> /// Module created or modified. /// </summary> [Optional] public string? DateTimeStamp { get; init; } /// <summary> /// Address range covered by this module. /// </summary> [Optional] public string? AddressRange { get; init; } /// <summary> /// Allows additional data to be displayed /// </summary> [JsonExtensionData] public Dictionary<string, object> ExtensionData { get; init; } = new Dictionary<string, object>(); } }
using System; using System.Collections.Generic; using System.Text; namespace EuropAssistance.Portugal.DRSA.Missioning.Models { public class VehicleModel { public string plateNumber { get; set; } public string country { get; set; } public string vin { get; set; } public string registrationDate { get; set; } public string make { get; set; } public string model { get; set; } public string type { get; set; } public int weight { get; set; } public string colour { get; set; } } }
namespace PICSimulator.Model.Commands { static class PICComandHelper { public static PICCommand CreateCommand(string sct, uint scl, uint pos, uint cmd) { #region BYTE-ORIENTED if (BinaryFormatParser.TryParse(PICCommand_ADDWF.COMMANDCODE, cmd)) return new PICCommand_ADDWF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_ANDWF.COMMANDCODE, cmd)) return new PICCommand_ANDWF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_CLRF.COMMANDCODE, cmd)) return new PICCommand_CLRF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_CLRW.COMMANDCODE, cmd)) return new PICCommand_CLRW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_COMF.COMMANDCODE, cmd)) return new PICCommand_COMF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_DECF.COMMANDCODE, cmd)) return new PICCommand_DECF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_DECFSZ.COMMANDCODE, cmd)) return new PICCommand_DECFSZ(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_INCF.COMMANDCODE, cmd)) return new PICCommand_INCF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_INCFSZ.COMMANDCODE, cmd)) return new PICCommand_INCFSZ(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_IORWF.COMMANDCODE, cmd)) return new PICCommand_IORWF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_MOVF.COMMANDCODE, cmd)) return new PICCommand_MOVF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_MOVWF.COMMANDCODE, cmd)) return new PICCommand_MOVWF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_NOP.COMMANDCODE, cmd)) return new PICCommand_NOP(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_RLF.COMMANDCODE, cmd)) return new PICCommand_RLF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_RRF.COMMANDCODE, cmd)) return new PICCommand_RRF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_SUBWF.COMMANDCODE, cmd)) return new PICCommand_SUBWF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_SWAPF.COMMANDCODE, cmd)) return new PICCommand_SWAPF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_XORWF.COMMANDCODE, cmd)) return new PICCommand_XORWF(sct, scl, pos, cmd); #endregion #region BIT_ORIENTED else if (BinaryFormatParser.TryParse(PICCommand_BCF.COMMANDCODE, cmd)) return new PICCommand_BCF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_BSF.COMMANDCODE, cmd)) return new PICCommand_BSF(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_BTFSC.COMMANDCODE, cmd)) return new PICCommand_BTFSC(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_BTFSS.COMMANDCODE, cmd)) return new PICCommand_BTFSS(sct, scl, pos, cmd); #endregion #region LITERAL AND CONTROL else if (BinaryFormatParser.TryParse(PICCommand_ADDLW.COMMANDCODE, cmd)) return new PICCommand_ADDLW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_ANDLW.COMMANDCODE, cmd)) return new PICCommand_ANDLW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_CALL.COMMANDCODE, cmd)) return new PICCommand_CALL(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_CLRWDT.COMMANDCODE, cmd)) return new PICCommand_CLRWDT(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_GOTO.COMMANDCODE, cmd)) return new PICCommand_GOTO(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_IORLW.COMMANDCODE, cmd)) return new PICCommand_IORLW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_MOVLW.COMMANDCODE, cmd)) return new PICCommand_MOVLW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_RETFIE.COMMANDCODE, cmd)) return new PICCommand_RETFIE(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_RETLW.COMMANDCODE, cmd)) return new PICCommand_RETLW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_RETURN.COMMANDCODE, cmd)) return new PICCommand_RETURN(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_SLEEP.COMMANDCODE, cmd)) return new PICCommand_SLEEP(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_SUBLW.COMMANDCODE, cmd)) return new PICCommand_SUBLW(sct, scl, pos, cmd); else if (BinaryFormatParser.TryParse(PICCommand_XORLW.COMMANDCODE, cmd)) return new PICCommand_XORLW(sct, scl, pos, cmd); #endregion else return null; } } }
using System; using System.Collections.Generic; using System.Text; namespace PlayStoreOdev { class GameManager { public void GameAdd(Game game) { Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("Sisteme ***" + game.GameName + "*** oyunu eklendi\n"); } public void GameDelete(Game game) { Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("Sistemden ***" + game.GameName + "*** oyunu silindi\n"); } public void GameUpdate(Game game) { Console.WriteLine("----------------------------------------------------------"); Console.WriteLine("Sistemde ***" + game.GameName + "*** oyunu güncellendi\n"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Xml.Linq; using Xamarin.Forms; using Xamarin.Forms.Maps; namespace InfiniteMeals { public partial class AddressValidationPage : ContentPage { public AddressValidationPage() { InitializeComponent(); map.MapType = MapType.Street; Position point = new Position(37.334789, -121.888138); var mapSpan = new MapSpan(point, 5, 5); map.MoveToRegion(mapSpan); } // IF ANDROID DOESN'T LET YOU IN, THEN COMMENT EVERYTHING INSIDE THIS FUNCTION // EXCEPT THE LAST LINE. async void ValidateAddressClick(object sender, System.EventArgs e) { if (userAddress.Text != null) { userAddress.Text = userAddress.Text.Trim(); Application.Current.Properties["userAddress"] = userAddress.Text; } if (userCity.Text != null) { userCity.Text = userCity.Text.Trim(); Application.Current.Properties["userCity"] = userCity.Text; } if (userState.Text != null) { userState.Text = userState.Text.Trim(); Application.Current.Properties["userState"] = userState.Text; } if (userUnitNumber.Text != null) { if (userUnitNumber.Text.Length != 0) { userUnitNumber.Text = userUnitNumber.Text.Trim(); Application.Current.Properties["userAddressUnit"] = userUnitNumber.Text; } else { Application.Current.Properties["userAddressUnit"] = ""; } } if (userZipcode.Text != null) { userZipcode.Text = userZipcode.Text.Trim(); Application.Current.Properties["userZipCode"] = userZipcode.Text; } // Setting request for USPS API XDocument requestDoc = new XDocument( new XElement("AddressValidateRequest", new XAttribute("USERID", "400INFIN1745"), new XElement("Revision", "1"), new XElement("Address", new XAttribute("ID", "0"), new XElement("Address1", userAddress.Text), new XElement("Address2", userUnitNumber.Text), new XElement("City", userCity.Text), new XElement("State", userState.Text), new XElement("Zip5", userZipcode.Text), new XElement("Zip4", "") ) ) ); var url = "http://production.shippingapis.com/ShippingAPI.dll?API=Verify&XML=" + requestDoc; Console.WriteLine(url); var client = new WebClient(); var response = client.DownloadString(url); var xdoc = XDocument.Parse(response.ToString()); Console.WriteLine(xdoc); string latitude = "0"; string longtitude = "0"; foreach (XElement element in xdoc.Descendants("Address")) { if (GetXMLElement(element, "Error").Equals("")) { if (GetXMLElement(element, "DPVConfirmation").Equals("Y") && GetXMLElement(element, "Zip5").Equals(userZipcode.Text) && GetXMLElement(element, "City").Equals(userCity.Text.ToUpper())) // Best case { // Get longitude and latitide because we can make a deliver here. Move on to next page. // Console.WriteLine("The address you entered is valid and deliverable by USPS. We are going to get its latitude & longitude"); // GetAddressLatitudeLongitude(); Geocoder geoCoder = new Geocoder(); IEnumerable<Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync(userAddress.Text + "," + userCity.Text + "," + userState.Text); Position position = approximateLocations.FirstOrDefault(); latitude = $"{position.Latitude}"; longtitude = $"{position.Longitude}"; Application.Current.Properties["latitude"] = latitude; Application.Current.Properties["longitude"] = longtitude; map.MapType = MapType.Street; var mapSpan = new MapSpan(position, 0.001, 0.001); Pin address = new Pin(); address.Label = "Delivery Address"; address.Type = PinType.SearchResult; address.Position = position; map.MoveToRegion(mapSpan); map.Pins.Add(address); break; } else if (GetXMLElement(element, "DPVConfirmation").Equals("D")) { // await DisplayAlert("Alert!", "Address is missing information like 'Apartment number'.", "Ok"); // return; } else { // await DisplayAlert("Alert!", "Seems like your address is invalid.", "Ok"); // return; } } else { // USPS sents an error saying address not found in there records. In other words, this address is not valid because it does not exits. // Console.WriteLine("Seems like your address is invalid."); // await DisplayAlert("Alert!", "Error from USPS. The address you entered was not found.", "Ok"); // return; } } if (latitude == "0" || longtitude == "0") { await DisplayAlert("We couldn't find your address", "Please check for errors.", "Ok"); return; } await Application.Current.SavePropertiesAsync(); } bool IsValidEmail(string email) { try { var addr = new System.Net.Mail.MailAddress(email); return addr.Address == email; } catch { return false; } } public static string GetXMLElement(XElement element, string name) { var el = element.Element(name); if (el != null) { return el.Value; } return ""; } public static string GetXMLAttribute(XElement element, string name) { var el = element.Attribute(name); if (el != null) { return el.Value; } return ""; } void EnterEmailPasswordToSignUpClick(System.Object sender, System.EventArgs e) { // Console.WriteLine("You are about to transition to the SignUpPage"); Application.Current.MainPage = new signUpPage(); } void ProceedAsGuestClick(System.Object sender, System.EventArgs e) { // NEEDS AN ENTRY TO STORE PHONE NUMBER Application.Current.Properties["customer_uid"] = "100-000097"; Application.Current.Properties["userPhoneNumber"] = ""; Application.Current.MainPage = new NewUI.StartPage(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace quanlysinhvien.Models.DAO { public class DAODash : baseDAO { public int getCountSv() { return db_.SinhVien.Count(); } public int getCountCourses() { return db_.KhoaHoc.Count(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ProjectMFS { public partial class ParticipantView : System.Web.UI.Page { string WIN = ""; protected void Page_Load(object sender, EventArgs e) { WIN = Request.QueryString["WIN"]; if (((SiteMaster)this.Master).IsLoggedIn) { this.LoginPanel.Visible = false; if (!String.IsNullOrEmpty(WIN)) //Load Existing Participant { this.MainDataPanel.Visible = true; } } } protected void ViewYear_Click(object sender, EventArgs e) { //ViewYear logic; } protected void Delete_Click(object sender, EventArgs e) { //Delete logic; } protected void LoadYearFromBanner_Click(object sender, EventArgs e) { //LoadYearFromBanner logic; } protected void Update_Click(object sender, EventArgs e) { //Update logic; } protected void ViewSemester_Click(object sender, EventArgs e) { //ViewSemester logic; } protected void LoadSemesterFromBanner_Click(object sender, EventArgs e) { //LoadSemesterFromBanner logic; } protected void ClassesGridViewButton_Click(object source, GridViewCommandEventArgs e) { //LogicHere } protected void Activities_Click(object sender, EventArgs e) { Response.Redirect("/ParticipantActivityView.aspx?WIN=" + WIN); } } }
using System.Collections.Generic; using cn.bmob.io; namespace cn.bmob.response { /// <summary> /// 获取数据列表的回调类 /// </summary> /// <typeparam name="T">用户模型对象</typeparam> public class QueryCallbackData<T> : BmobObject, IBmobWritable { /// <summary> /// 返回结果列表 /// </summary> public List<T> results { get; set; } /// <summary> /// 请求数据总数,返回查询结果总数 /// </summary> public BmobInt count { get; set; } public override void readFields(BmobInput input) { this.count = input.getInt("count"); this.results = input.getList<T>("results"); } public override void write(BmobOutput output, bool all) { output.Put("count", this.count); output.Put("results", this.results); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OtherQuestions.cs { public class _008_SlideWindows { /* * Given a sequence of data (it may have duplicates), a fixed-sized moving window, move the window at each iteration from the start of the data sequence, such that (1) the oldest data element is removed from the window and a new data element is pushed into the window (2) find the median of the data inside the window at each moving. * http://www.mitbbs.com/article_t/JobHunting/32074175.html */ public void SlideWindowsMedian(int[] input) { } } }
using System; namespace Paralect.Schematra.Definitions { /// <summary> /// Can be schema, enum, namespace, using etc. /// </summary> public class TypeDefinition { /// <summary> /// Name of the schema /// </summary> protected string _name; /// <summary> /// Namespace /// </summary> protected string _namespace; /// <summary> /// Name of the schema /// </summary> public String Name { get { return _name; } set { _name = value; } } /// <summary> /// Namespace /// </summary> public string Namespace { get { return _namespace; } set { _namespace = value; } } } }
namespace Nancy.Markdown.Blog.Example { public class Bootstrapper : DefaultNancyBootstrapper { } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shop.BusinnesLogic.Models { public class ClientViewModel { public int Id { get; set; } [Required(ErrorMessage ="Should")] [MaxLength(20,ErrorMessage ="To long")] public string Name { get; set; } public int CategoryId { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace DBStore.Models { public class UserEmailOption { public List<string> ToEmails { get; set; } public string Subject { get; set; } public string Body { get; set; } public List<KeyValuePair<string, string>> PlaceHolders { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using PmSoft; using PmSoft.Events; namespace ManagementWebHost { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddPmSoftFrameWork(Configuration); services.AddControllersWithViews(); //获取web引用的所有Soft开头的程序集 AssemblyName[] assemblyNames = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(n => n.Name.StartsWith("PmSoft")).ToArray(); List<Assembly> assemblyList = assemblyNames.Select(n => Assembly.Load(n)).ToList(); //获取根目录下的指定名称开头的的程序集 IEnumerable<string> files = Directory.EnumerateFiles(AppContext.BaseDirectory, "ManagementWebHost.dll"); assemblyList.AddRange(files.Select(n => Assembly.Load(AssemblyName.GetAssemblyName(n)))); Assembly[] assemblies = assemblyList.ToArray(); //批量注入所有的EventMoudle services.AddSingletonByAssembly<IEventMoudle>(assemblies); //批量注入所有的EventHandler services.AddSingletonByAssembly(assemblies, "EventHandler"); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ServiceLocator.Instance = app.ApplicationServices; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //注册事件处理程序 IEnumerable<IEventMoudle> eventMoudles = app.ApplicationServices.GetServices<IEventMoudle>(); foreach (var eventMoudle in eventMoudles) { eventMoudle.RegisterEventHandler(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace WinSockSendRcv { class UdpEchoClient { static void Main(string[] args) { if ((args.Length < 2) || (args.Length > 3)) { throw new System.ArgumentException("Parameters: <Server> <Port> <Data>"); } //Server name or IP Address string server = args[0]; //Use port argument if entered,otherwise default to 22 int servPort = (args.Length == 3) ? Int32.Parse(args[1]) : 22; //Convert input string to an array of bytes byte[] sendPacket = Encoding.ASCII.GetBytes(args[2]); //Create a udp client instance UdpClient client = new UdpClient(); try { //Send the Echo String to the specified host and port client.Send(sendPacket, sendPacket.Length, server, servPort); Console.WriteLine("sent {0} bytes to the server ...", sendPacket.Length); IPEndPoint remoteIPEndpoint = new IPEndPoint(IPAddress.Any, 0); //attempt echo reply receive byte[] rcvPacket = client.Receive(ref remoteIPEndpoint); Console.WriteLine("Received {0} bytes from {1}: {2}", rcvPacket.Length, remoteIPEndpoint, Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length)); } catch (SocketException se) { Console.WriteLine(se.ErrorCode + ": " + se.Message); } //close the port client.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Forms; using TQVaultAE.Domain.Contracts.Providers; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.Domain.Entities; using TQVaultAE.Domain.Search; using TQVaultAE.GUI.Components; using TQVaultAE.GUI.Helpers; using TQVaultAE.Presentation; using TQVaultAE.Domain.Helpers; using System.Drawing; using Microsoft.Extensions.Logging; using TQVaultAE.GUI.Models.SearchDialogAdvanced; using TQVaultAE.GUI.Tooltip; using Newtonsoft.Json; using TQVaultAE.Domain.Results; using System.Text.RegularExpressions; using static TQVaultAE.GUI.Models.SearchDialogAdvanced.SearchQuery; using TQVaultAE.GUI.Models; using System.Reflection; using System.Xml.Linq; namespace TQVaultAE.GUI; /// <summary> /// Class for the Search Dialog box. /// </summary> public partial class SearchDialogAdvanced : VaultForm { private readonly SessionContext Ctx; private readonly ITranslationService TranslationService; private readonly List<Result> ItemDatabase = new List<Result>(); private readonly ILogger Log; private readonly Bitmap ButtonImageUp; private readonly Bitmap ButtonImageDown; private readonly (ScalingButton Button, FlowLayoutPanel Panel)[] _NavMap; private readonly List<BoxItem> _SelectedFilters = new List<BoxItem>(); public Result[] QueryResults { get; private set; } = new Result[] { }; private bool scalingCheckBoxReduceDuringSelection_LastChecked; /// <summary> /// Initializes a new instance of the SearchDialog class. /// </summary> public SearchDialogAdvanced( MainForm instance , SessionContext sessionContext , IItemProvider itemProvider , ITranslationService translationService , ILogger<SearchDialogAdvanced> log ) : base(instance.ServiceProvider) { this.Owner = instance; this.Ctx = sessionContext; this.TranslationService = translationService; this.Log = log; this.InitializeComponent(); this.MinimizeBox = false; this.NormalizeBox = false; this.MaximizeBox = true; #region Apply custom font this.ProcessAllControls(c => { if (c is IScalingControl) c.Font = FontService.GetFont(9F); }); this.applyButton.Font = FontService.GetFontLight(12F); this.cancelButton.Font = FontService.GetFontLight(12F); this.Font = FontService.GetFont(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)(0)); #endregion #region Load localized strings this.Text = Resources.SearchDialogCaption; this.applyButton.Text = TranslationService.TranslateXTag("tagMenuButton07"); this.cancelButton.Text = TranslationService.TranslateXTag("tagMenuButton06"); this.scalingLabelFiltersSelected.Tag = Resources.SearchFiltersSelected; this.scalingLabelFiltersSelected.Text = string.Empty; this.scalingLabelOperator.Text = $"{Resources.SearchOperator} :"; this.buttonExpandAll.Text = Resources.GlobalExpandAll; this.buttonCollapseAll.Text = Resources.GlobalCollapseAll; this.scalingLabelMaxVisibleElement.Text = $"{Resources.SearchVisibleElementsPerCategory} :"; this.scalingLabelSearchTerm.Text = $"{TranslationService.TranslateXTag("xtagLobbySearchSearch")} :"; this.scalingButtonReset.Text = TranslationService.TranslateXTag("tagSkillReset"); this.scalingLabelQueries.Text = $"{Resources.SearchQueries} :"; this.scalingButtonQuerySave.Text = Resources.GlobalSave; this.scalingButtonQueryDelete.Text = TranslationService.TranslateXTag("tagMenuButton03"); this.scalingCheckBoxReduceDuringSelection.Text = Resources.SearchReduceCategoriesDuringSelection; this.scalingComboBoxOperator.Items.Clear(); this.scalingComboBoxOperator.Items.AddRange(new[] { Resources.SearchOperatorAnd, Resources.SearchOperatorOr }); this.scalingButtonMenuAttribute.Text = this.scalingLabelItemAttributes.Text = TranslationService.TranslateXTag("tagCAttributes"); this.scalingButtonMenuBaseAttribute.Text = this.scalingLabelBaseAttributes.Text = Resources.GlobalBaseAttribute; this.scalingButtonMenuCharacters.Text = this.scalingLabelCharacters.Text = TranslationService.TranslateXTag("tagWindowName01"); this.scalingButtonMenuPrefixAttribute.Text = this.scalingLabelPrefixAttributes.Text = Resources.GlobalPrefix; this.scalingButtonMenuPrefixName.Text = this.scalingLabelPrefixName.Text = Resources.GlobalPrefixName; this.scalingButtonMenuQuality.Text = this.scalingLabelQuality.Text = Resources.ResultsQuality; this.scalingButtonMenuRarity.Text = this.scalingLabelRarity.Text = Resources.GlobalRarity; this.scalingButtonMenuStyle.Text = this.scalingLabelStyle.Text = Resources.GlobalStyle; this.scalingButtonMenuSuffixAttribute.Text = this.scalingLabelSuffixAttributes.Text = Resources.GlobalSuffix; this.scalingButtonMenuSuffixName.Text = this.scalingLabelSuffixName.Text = Resources.GlobalSuffixName; this.scalingButtonMenuType.Text = this.scalingLabelItemType.Text = Resources.GlobalType; this.scalingButtonMenuVaults.Text = this.scalingLabelInVaults.Text = Resources.GlobalVaults; this.scalingButtonMenuWithCharm.Text = this.scalingLabelWithCharm.Text = Resources.SearchHavingCharm; this.scalingButtonMenuWithRelic.Text = this.scalingLabelWithRelic.Text = Resources.SearchHavingRelic; this.scalingButtonMenuOrigin.Text = this.scalingLabelOrigin.Text = Resources.GlobalOrigin; this.scalingButtonMenuSetItems.Text = this.scalingLabelSetItems.Text = Resources.SearchSetItem; scalingCheckBoxMinReq.Text = $"{Resources.GlobalMin} {Resources.GlobalRequirements} :"; scalingCheckBoxMaxReq.Text = $"{Resources.GlobalMax} {Resources.GlobalRequirements} :"; scalingLabelMaxLvl.Text = scalingLabelMinLvl.Text = TranslationService.TranslateXTag("tagMenuImport05"); scalingLabelMaxStr.Text = scalingLabelMinStr.Text = TranslationService.TranslateXTag("Strength"); scalingLabelMaxDex.Text = scalingLabelMinDex.Text = TranslationService.TranslateXTag("Dexterity"); scalingLabelMaxInt.Text = scalingLabelMinInt.Text = TranslationService.TranslateXTag("Intelligence"); scalingCheckBoxHavingCharm.Text = Resources.SearchHavingCharm; scalingCheckBoxHavingRelic.Text = Resources.SearchHavingRelic; scalingCheckBoxHavingPrefix.Text = Resources.SearchHavingPrefix; scalingCheckBoxHavingSuffix.Text = Resources.SearchHavingSuffix; scalingCheckBoxIsSetItem.Text = Resources.SearchSetItem; #endregion this._SearchQueries = SearchQueries.Default(GamePathResolver); // Mapping between nav button & content component if (_NavMap is null) { _NavMap = new (ScalingButton Button, FlowLayoutPanel Panel)[] { (this.scalingButtonMenuAttribute, this.flowLayoutPanelItemAttributes), (this.scalingButtonMenuBaseAttribute, this.flowLayoutPanelBaseAttributes), (this.scalingButtonMenuCharacters, this.flowLayoutPanelCharacters), (this.scalingButtonMenuPrefixAttribute, this.flowLayoutPanelPrefixAttributes), (this.scalingButtonMenuPrefixName, this.flowLayoutPanelPrefixName), (this.scalingButtonMenuRarity, this.flowLayoutPanelRarity), (this.scalingButtonMenuStyle, this.flowLayoutPanelStyle), (this.scalingButtonMenuSuffixAttribute, this.flowLayoutPanelSuffixAttributes), (this.scalingButtonMenuSuffixName, this.flowLayoutPanelSuffixName), (this.scalingButtonMenuType, this.flowLayoutPanelItemType), (this.scalingButtonMenuVaults, this.flowLayoutPanelInVaults), (this.scalingButtonMenuWithCharm, this.flowLayoutPanelWithCharm), (this.scalingButtonMenuWithRelic, this.flowLayoutPanelWithRelic), (this.scalingButtonMenuQuality, this.flowLayoutPanelQuality), (this.scalingButtonMenuOrigin, this.flowLayoutPanelOrigin), (this.scalingButtonMenuSetItems, this.flowLayoutPanelSetItems), }; } // Keep reference of base Up & Down button image this.ButtonImageUp = this.scalingButtonMenuAttribute.UpBitmap; this.ButtonImageDown = this.scalingButtonMenuAttribute.DownBitmap; this.scalingComboBoxOperator.SelectedIndex = (int)SearchOperator.And; // Remove design time fake elements scalingComboBoxQueryList.Items.Clear(); CleanAllCheckBoxes(); // Set numerical to default this.ProcessAllControls(c => { if (c is NumericUpDown num && num != numericUpDownMaxElement) num.Value = 0; }); } private void CleanAllCheckBoxes() { this.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { lb.BeginUpdate(); lb.Items.Clear(); lb.EndUpdate(); } }); } private void SetSearchBoxVisibility(bool isVisible) => _NavMap.ToList().ForEach(m => m.Panel.Visible = isVisible); #region Apply & Cancel /// <summary> /// Handler for clicking the apply button on the form. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ApplyButtonClicked(object sender, EventArgs e) { if (!_SelectedFilters.Any()) { scalingLabelProgress.Text = $"{Resources.SearchTermRequired} - {string.Format(Resources.SearchItemCountIs, ItemDatabase.Count())}"; return; }; this.DialogResult = DialogResult.OK; this.Close(); } /// <summary> /// Handler for clicking the cancel button on the form. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void CancelButtonClicked(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } #endregion /// <summary> /// Handler for showing the search dialog. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void SearchDialogShown(object sender, EventArgs e) { Application.DoEvents();// Force control rendering (VaultForm stuff like custom borders etc...) // Init Data Base scalingLabelProgress.Text = Resources.SearchBuildingData; scalingLabelProgress.Visible = true; vaultProgressBar.Minimum = 0; vaultProgressBar.Maximum = ItemDatabase.Count(); vaultProgressBar.Visible = true; this.backgroundWorkerBuildDB.RunWorkerAsync(); } #region Load & Init private void SearchDialogAdvanced_Load(object sender, EventArgs e) => BuildItemDatabase(); /// <summary> /// Seek for all available items /// </summary> private void BuildItemDatabase() { foreach (KeyValuePair<string, Lazy<PlayerCollection>> kvp in Ctx.Vaults) { string vaultFile = kvp.Key; PlayerCollection vault = kvp.Value.Value; if (vault == null) continue; int vaultNumber = -1; foreach (SackCollection sack in vault) { vaultNumber++; if (sack == null) continue; foreach (var item in sack.Cast<Item>()) { var vaultName = GamePathResolver.GetVaultNameFromPath(vaultFile); ItemDatabase.Add(new Result( vaultFile , vaultName , vaultNumber , SackType.Vault , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } } foreach (KeyValuePair<string, Lazy<PlayerCollection>> kvp in Ctx.Players) { string playerFile = kvp.Key; PlayerCollection player = kvp.Value.Value; if (player == null) continue; string playerName = this.GamePathResolver.GetNameFromFile(playerFile); if (playerName == null) continue; int sackNumber = -1; foreach (SackCollection sack in player) { sackNumber++; if (sack == null) continue; foreach (var item in sack.Cast<Item>()) { this.ItemDatabase.Add(new Result( playerFile , playerName , sackNumber , SackType.Player , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } // Now search the Equipment panel var equipmentSack = player.EquipmentSack; if (equipmentSack == null) continue; foreach (var item in equipmentSack.Cast<Item>()) { ItemDatabase.Add(new Result( playerFile , playerName , 0 , SackType.Equipment , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } foreach (KeyValuePair<string, Lazy<Stash>> kvp in Ctx.Stashes) { string stashFile = kvp.Key; Stash stash = kvp.Value.Value; // Make sure we have a valid name and stash. if (stash == null) continue; string stashName = this.GamePathResolver.GetNameFromFile(stashFile); if (stashName == null) continue; SackCollection sack = stash.Sack; if (sack == null) continue; int sackNumber = 2; SackType sackType = SackType.Stash; if (stashName == Resources.GlobalTransferStash) { sackNumber = 1; sackType = SackType.TransferStash; } else if (stashName == Resources.GlobalRelicVaultStash) { sackNumber = 3; sackType = SackType.RelicVaultStash; } foreach (var item in sack.Cast<Item>()) { ItemDatabase.Add(new Result( stashFile , stashName , sackNumber , sackType , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } } /// <summary> /// Load item data & display progress /// </summary> private void InitItemDatabase() { // Must not change UI Controls. Just update backgroundWorker which handle this for you through his event pipeline. foreach (var item in ItemDatabase) { item.LazyLoad(); this.backgroundWorkerBuildDB.ReportProgress(1); } // Cleanup zombies ItemDatabase.RemoveAll(id => string.IsNullOrWhiteSpace(id.ItemName)); } #endregion #region backgroundWorkerBuildDB private void backgroundWorkerBuildDB_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) => InitItemDatabase(); private void backgroundWorkerBuildDB_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) => vaultProgressBar.Increment(1); private void backgroundWorkerBuildDB_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { SearchEngineReady(); LoadPersonnalQueries(); } #endregion private void SearchEngineReady() { scalingLabelProgress.Text = $"{Resources.SearchEngineReady} - {string.Format(Resources.SearchItemCountIs, ItemDatabase.Count())}"; PopulateCheckBoxes(); AdjustCheckBoxesWidth(); AdjustCheckBoxesHeight(); SetSearchBoxVisibility(true); SyncNaveButton(); // Start this.scalingTextBoxSearchTerm.Focus(); } private void AdjustCheckBoxesHeight() { flowLayoutPanelMain.ProcessAllControls(c => { // Adjust to current UI setting if (c is ScalingCheckedListBox lb) { var maxRow = (int)this.numericUpDownMaxElement.Value; int height = 0, currrow = 0; foreach (var line in lb.Items) { if (currrow == maxRow) break; height += lb.GetItemHeight(currrow); currrow++; } height += SystemInformation.HorizontalScrollBarHeight; lb.Height = height; } }); } private void AdjustCheckBoxesWidth() { flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.AdjustToMaxTextWidth((int)this.numericUpDownMaxElement.Value); }); } #region Populate private void PopulateCheckBoxes() { PopulateCharacters(); PopulateItemType(); PopulateRarity(); PopulateStyle(); PopulateQuality(); PopulateVaults(); PopulateWithCharm(); PopulateWithRelic(); PopulateOrigin(); PopulateSetItems(); PopulateItemAttributes(); PopulateBaseAttributes(); PopulatePrefixName(); PopulatePrefixAttributes(); PopulateSuffixName(); PopulateSuffixAttributes(); } private void PopulateSetItems() { var clb = scalingCheckedListBoxSetItems; var setitems = from id in ItemDatabase let itm = id.FriendlyNames.Item let set = id.FriendlyNames.ItemSet where set is not null let setName = set.Translations[set.setName].RemoveAllTQTags() orderby setName group id by setName into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, setitems); } private void PopulateOrigin() { var clb = scalingCheckedListBoxOrigin; var originList = new ItemOrigin[] { new ItemOrigin{ Value = GameDlc.TitanQuest, DisplayName = TranslationService.Translate(GameDlc.TitanQuest) }, new ItemOrigin{ Value = GameDlc.ImmortalThrone, DisplayName = TranslationService.Translate(GameDlc.ImmortalThrone) }, new ItemOrigin{ Value = GameDlc.Ragnarok, DisplayName = TranslationService.Translate(GameDlc.Ragnarok) }, new ItemOrigin{ Value = GameDlc.Atlantis, DisplayName = TranslationService.Translate(GameDlc.Atlantis) }, new ItemOrigin{ Value = GameDlc.EternalEmbers, DisplayName = TranslationService.Translate(GameDlc.EternalEmbers) }, }; var originItems = from id in ItemDatabase let itm = id.FriendlyNames.Item from org in originList where itm.GameDlc == org.Value orderby org.Value group id by org.DisplayName into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, originItems); } private void PopulateWithRelic() { var clb = scalingCheckedListBoxWithRelic; var WithRelic = from id in ItemDatabase let itm = id.FriendlyNames.Item where itm.HasRelicOrCharmSlot1 && !itm.IsRelic1Charm || itm.HasRelicOrCharmSlot2 && !itm.IsRelic2Charm from reldesc in new[] { id.FriendlyNames.RelicInfo1Description, id.FriendlyNames.RelicInfo2Description } where !string.IsNullOrWhiteSpace(reldesc) let attClean = reldesc.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, WithRelic); } private static void PopulateInit(ScalingCheckedListBox clb, IEnumerable<BoxItem> items) { var (_, tag) = clb.GetBoxTag(); tag.DataSource = items.ToArray(); clb.BeginUpdate(); clb.Items.AddRange(tag.DataSource); clb.EndUpdate(); } private void PopulateWithCharm() { var clb = scalingCheckedListBoxWithCharm; var WithCharm = from id in ItemDatabase let itm = id.FriendlyNames.Item where itm.HasRelicOrCharmSlot1 && itm.IsRelic1Charm || itm.HasRelicOrCharmSlot2 && itm.IsRelic2Charm from reldesc in new[] { id.FriendlyNames.RelicInfo1Description, id.FriendlyNames.RelicInfo2Description } where !string.IsNullOrWhiteSpace(reldesc) let attClean = reldesc.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, WithCharm); } private void PopulateVaults() { var clb = scalingCheckedListBoxVaults; var Vaults = from id in ItemDatabase.Where(i => i.SackType == SackType.Vault) let att = id.ContainerName orderby att group id by att into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Vaults); } private void PopulateQuality() { var clb = scalingCheckedListBoxQuality; var Quality = from id in ItemDatabase let att = id.FriendlyNames.BaseItemInfoQuality where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Quality); } private void PopulateSuffixName() { var clb = scalingCheckedListBoxSuffixName; var SuffixName = from id in ItemDatabase let att = id.FriendlyNames.SuffixInfoDescription where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, SuffixName); } private void PopulateSuffixAttributes() { var clb = scalingCheckedListBoxSuffixAttributes; var SuffixAttributes = from id in ItemDatabase from att in id.FriendlyNames.SuffixAttributes where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, SuffixAttributes); } private void PopulateStyle() { var clb = scalingCheckedListBoxStyle; var Style = from id in ItemDatabase let att = id.FriendlyNames.BaseItemInfoStyle where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Style); } private void PopulateRarity() { var equipmentOnly = new[] { ItemStyle.Broken , ItemStyle.Mundane , ItemStyle.Common , ItemStyle.Rare , ItemStyle.Epic , ItemStyle.Legendary }; var clb = scalingCheckedListBoxRarity; var Rarity = from id in ItemDatabase where equipmentOnly.Contains(id.ItemStyle) let att = id.FriendlyNames.BaseItemRarity where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Rarity); } private void PopulatePrefixName() { var clb = scalingCheckedListBoxPrefixName; var PrefixName = from id in ItemDatabase let att = id.FriendlyNames.PrefixInfoDescription where !string.IsNullOrWhiteSpace(att) let attClean = att.TQCleanup().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, PrefixName); } private void PopulatePrefixAttributes() { var clb = scalingCheckedListBoxPrefixAttributes; var PrefixAttributes = from id in ItemDatabase from att in id.FriendlyNames.PrefixAttributes where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, PrefixAttributes); } private void PopulateCharacters() { var clb = scalingCheckedListBoxCharacters; var Players = from id in ItemDatabase where id.SackType == SackType.Player || id.SackType == SackType.Equipment let att = id.ContainerName orderby att group id by att into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Players); } private void PopulateItemType() { var clb = scalingCheckedListBoxItemType; var ItemType = from id in ItemDatabase let att = id.FriendlyNames.BaseItemInfoClass ?? id.FriendlyNames.Item.ItemClass where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, ItemType); } private void PopulateItemAttributes() { var clb = scalingCheckedListBoxItemAttributes; var ItemAttributes = from id in ItemDatabase from att in id.FriendlyNames.AttributesAll where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, ItemAttributes); } private void PopulateBaseAttributes() { var clb = scalingCheckedListBoxBaseAttributes; var BaseAttributes = from id in ItemDatabase from att in id.FriendlyNames.BaseAttributes where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, BaseAttributes); } #endregion private void numericUpDownMaxElement_ValueChanged(object sender, EventArgs e) => AdjustCheckBoxesHeight(); private void scalingCheckedListBox_MouseMove(object sender, MouseEventArgs e) { var ctr = sender as Control; var (lstBox, tag) = ctr.GetBoxTag(); var focusedIdx = lstBox.IndexFromPoint(e.Location); if (tag.LastTooltipIndex != focusedIdx) { tag.LastTooltipIndex = focusedIdx; if (tag.LastTooltipIndex > -1) { var item = lstBox.Items[focusedIdx] as BoxItem; toolTip.SetToolTip(lstBox, string.Format(Resources.SearchMatchingItemsTT, item.MatchingResults.Count())); } } lstBox.Tag = tag; } private void buttonCollapseAll_Click(object sender, EventArgs e) { flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.Visible = false; }); } private void buttonExpandAll_Click(object sender, EventArgs e) { flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.Visible = true; }); } private void scalingButtonMenu_Click(object sender, EventArgs e) { // Toggle var (button, panel) = _NavMap.First(m => object.ReferenceEquals(m.Button, sender)); panel.Visible = !panel.Visible; SyncNaveButton(); } private void SyncNaveButton() { /// Push invisible categories at the end of <see cref="flowLayoutPanelMain"/> so nav buttons define categories order in flowpanel var trail = _NavMap.Where(map => !map.Panel.Visible).Select(map => map.Panel).ToList(); // Remove trail.ForEach(c => this.flowLayoutPanelMain.Controls.Remove(c)); // Then Put it back at the end this.flowLayoutPanelMain.Controls.AddRange(trail.ToArray()); SyncNavButtonImage(); } private void SyncNavButtonImage() { foreach (var map in _NavMap) { // Invert Up & Down each time you click to make it behave like a toggle if (map.Panel.Visible) { map.Button.UpBitmap = this.ButtonImageDown; map.Button.OverBitmap = this.ButtonImageUp; map.Button.Image = map.Button.DownBitmap; } else { map.Button.UpBitmap = this.ButtonImageUp; map.Button.OverBitmap = this.ButtonImageDown; map.Button.Image = map.Button.UpBitmap; } } } private void scalingCheckedListBox_SelectedValueChanged(object sender, EventArgs e) => Sync_SelectedFilters(); private void Sync_SelectedFilters() { _SelectedFilters.Clear(); // Add the SearchTerm on top var (_, searchTermBoxItem) = this.scalingTextBoxSearchTerm.GetBoxItem(false); // if i get something to filter with if (!string.IsNullOrWhiteSpace(searchTermBoxItem.DisplayValue)) _SelectedFilters.Add(searchTermBoxItem); // Crawl winform graf for selected BoxItem flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) _SelectedFilters.AddRange(lb.CheckedItems.Cast<BoxItem>()); }); this.Apply_SelectedFilters(); } private void scalingLabelCategory_MouseClick(object sender, MouseEventArgs e) { var label = sender as ScalingLabel; var flowpanel = label.Parent; if (e.Button == MouseButtons.Left) { // Individual Expand/Collapse flowpanel.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.Visible = !lb.Visible; }); } // Uncheck if (e.Button == MouseButtons.Right) { UncheckCategories(flowpanel); Sync_SelectedFilters(); } } private void UncheckCategories(Control flowpanel) { flowpanel.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { lb.BeginUpdate(); lb.CheckedIndices.Cast<int>().ToList().ForEach(idx => lb.SetItemChecked(idx, false)); lb.EndUpdate(); } }); } private void scalingLabelFiltersSelected_MouseEnter(object sender, EventArgs e) { var ctrl = sender as Control; SearchFiltersTooltip.ShowTooltip(this.ServiceProvider, ctrl, this._SelectedFilters, (SearchOperator)scalingComboBoxOperator.SelectedIndex); } private void scalingLabelFiltersSelected_MouseLeave(object sender, EventArgs e) => SearchFiltersTooltip.HideTooltip(); bool _Apply_SelectedFiltersDisabled = false; private SearchQueries _SearchQueries; private void Apply_SelectedFilters() { if (_Apply_SelectedFiltersDisabled) return; int MaxLvl = (int)numericUpDownMaxLvl.Value, MaxDex = (int)numericUpDownMaxDex.Value, MaxInt = (int)numericUpDownMaxInt.Value, MaxStr = (int)numericUpDownMaxStr.Value, MinLvl = (int)numericUpDownMinLvl.Value, MinDex = (int)numericUpDownMinDex.Value, MinInt = (int)numericUpDownMinInt.Value, MinStr = (int)numericUpDownMinStr.Value; bool MaxRequierement = scalingCheckBoxMaxReq.Checked, MinRequierement = scalingCheckBoxMinReq.Checked; this.scalingLabelFiltersSelected.Text = string.Format(this.scalingLabelFiltersSelected.Tag.ToString(), _SelectedFilters.Count()); var query = ItemDatabase.AsQueryable(); if (this.scalingComboBoxOperator.SelectedIndex == (int)SearchOperator.And) { // AND operator => item must exist in every filter foreach (var filter in _SelectedFilters) query = query.Intersect(filter.MatchingResults);// Reducing result at every step } else { // OR Operator => Accumulate & Distinct query = _SelectedFilters.AsQueryable().SelectMany(f => f.MatchingResults).Distinct(); } // Apply Quick Filters if (this.scalingCheckBoxHavingPrefix.Checked) query = query.Where(i => i.FriendlyNames.Item.HasPrefix); if (this.scalingCheckBoxHavingSuffix.Checked) query = query.Where(i => i.FriendlyNames.Item.HasSuffix); if (this.scalingCheckBoxHavingRelic.Checked) query = query.Where(i => i.FriendlyNames.Item.HasRelic); if (this.scalingCheckBoxHavingCharm.Checked) query = query.Where(i => i.FriendlyNames.Item.HasCharm); if (this.scalingCheckBoxIsSetItem.Checked) query = query.Where(i => i.FriendlyNames.ItemSet != null); // Apply Requirements if (MinRequierement) { if (MinLvl > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Lvl.HasValue // Item doesn't have requirement || x.FriendlyNames.RequirementInfo.Lvl >= MinLvl ); if (MinStr > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Str.HasValue || x.FriendlyNames.RequirementInfo.Str >= MinStr ); if (MinDex > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Dex.HasValue || x.FriendlyNames.RequirementInfo.Dex >= MinDex ); if (MinInt > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Int.HasValue || x.FriendlyNames.RequirementInfo.Int >= MinInt ); } if (MaxRequierement) { if (MaxLvl > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Lvl.HasValue // Item doesn't have requirement || x.FriendlyNames.RequirementInfo.Lvl <= MaxLvl ); if (MaxStr > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Str.HasValue || x.FriendlyNames.RequirementInfo.Str <= MaxStr ); if (MaxDex > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Dex.HasValue || x.FriendlyNames.RequirementInfo.Dex <= MaxDex ); if (MaxInt > 0) query = query.Where(x => !x.FriendlyNames.RequirementInfo.Int.HasValue || x.FriendlyNames.RequirementInfo.Int <= MaxInt ); } this.QueryResults = query.ToArray(); scalingLabelProgress.Text = $"{string.Format(Resources.SearchItemCountIs, QueryResults.Count())}"; ApplyCategoriesReducer(); } private void scalingComboBoxOperator_SelectionChangeCommitted(object sender, EventArgs e) { if (scalingCheckBoxReduceDuringSelection.Checked) ResetCheckBoxesToFirstLoad(); Apply_SelectedFilters(); } private void scalingCheckBoxReduceDuringSelection_CheckedChanged(object sender, EventArgs e) { scalingCheckBoxReduceDuringSelection_LastChecked = !scalingCheckBoxReduceDuringSelection.Checked; ApplyCategoriesReducer(); scalingCheckBoxReduceDuringSelection_LastChecked = scalingCheckBoxReduceDuringSelection.Checked; } private void ApplyCategoriesReducer() { // Category Reduced Display if (scalingCheckBoxReduceDuringSelection.Checked) { ReduceCheckBoxesToQueryResult(); return; } if ( ( // Category Full Display !scalingCheckBoxReduceDuringSelection.Checked /// But comes from <see cref="scalingCheckBoxReduceDuringSelection_CheckedChanged"/> meaning "from a Category Reduced Display" && scalingCheckBoxReduceDuringSelection.Checked != scalingCheckBoxReduceDuringSelection_LastChecked ) || this.FilterCategories.HasChanged ) { ResetCheckBoxesToFirstLoad();// Restore Full Display } } private class FilterCategoriesDetails { internal bool HasFilterCategory; internal bool IsRegex; internal string Search; internal Regex Regex; internal bool RegexIsValid; internal string SearchRaw; internal string SearchRawPrevious; internal bool HasChanged => SearchRaw != SearchRawPrevious; internal bool IsMatch(string attributeText) => (IsRegex && RegexIsValid) ? Regex.IsMatch(attributeText) : attributeText.ContainsIgnoreCase(Search); internal bool AvoidDisplayAttribute(string attributeText) => HasFilterCategory && !IsMatch(attributeText); } private readonly FilterCategoriesDetails FilterCategories = new FilterCategoriesDetails(); private void ResetCheckBoxesToFirstLoad() { // Reset to FirstLoad CleanAllCheckBoxes(); flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { var (_, tag) = lb.GetBoxTag(); lb.BeginUpdate(); bool isChecked; foreach (var item in tag.DataSource) { isChecked = _SelectedFilters.Contains(item); if (!isChecked // Do not hide already checked /// Should i filter out this check box based on <see cref="FilterCategories"/> ? && FilterCategories.AvoidDisplayAttribute(item.DisplayValue) ) continue; lb.Items.Add(item, isChecked); } lb.EndUpdate(); } }); } private void ReduceCheckBoxesToQueryResult() { if (this.QueryResults.Any()) { CleanAllCheckBoxes(); // Reset to QueryResult. flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { var (_, tag) = lb.GetBoxTag(); var DSvsQR = // Does boxitems match queryresult ? from boxitem in tag.DataSource from boxitemresult in boxitem.MatchingResults join QR in this.QueryResults on boxitemresult equals QR // distinct boxitems group boxitem by boxitem into grp select grp; lb.BeginUpdate(); bool isChecked; foreach (var item in DSvsQR) { isChecked = _SelectedFilters.Contains(item.Key); if (!isChecked // Do not hide already checked /// Should i filter out this check box based on <see cref="FilterCategories"/> ? && FilterCategories.AvoidDisplayAttribute(item.Key.DisplayValue) ) continue; lb.Items.Add(item.Key, isChecked); } lb.EndUpdate(); } }); } } private void scalingButtonReset_Click(object sender, EventArgs e) => ResetSelectedFilters(); private void ResetSelectedFilters() { this.scalingComboBoxQueryList.ResetText(); ResetQuickFilters(); ResetRequirements(); UncheckCategories(flowLayoutPanelMain); TextBoxSearchTerm_UpdateText_Notrigger(string.Empty); TextBoxSearchTerm_TextChanged_Logic(); } internal void ResetQuickFilters() { scalingCheckBoxIsSetItem.Checked = scalingCheckBoxHavingCharm.Checked = scalingCheckBoxHavingRelic.Checked = scalingCheckBoxHavingPrefix.Checked = scalingCheckBoxHavingSuffix.Checked = false; } internal void ResetRequirements() { scalingCheckBoxMaxReq.Checked = scalingCheckBoxMinReq.Checked = false; numericUpDownMaxDex.Value = numericUpDownMaxInt.Value = numericUpDownMaxLvl.Value = numericUpDownMaxStr.Value = numericUpDownMinDex.Value = numericUpDownMinInt.Value = numericUpDownMinLvl.Value = numericUpDownMinStr.Value = 0; } private void TextBoxSearchTerm_UpdateText_Notrigger(string newText) { this.scalingTextBoxSearchTerm.TextChanged -= scalingTextBoxSearchTerm_TextChanged; this.scalingTextBoxSearchTerm.Text = newText; this.scalingTextBoxSearchTerm.TextChanged += scalingTextBoxSearchTerm_TextChanged; } private void scalingTextBoxSearchTerm_TextChanged(object sender, EventArgs e) /// Wait for the end of typing by delaying the call to <see cref="scalingTextBoxSearchTerm_TextChanged_Idled"/> => this.typeAssistantSearchBox.TextChanged(); private void scalingTextBoxSearchTerm_TextChanged_Idled(object sender, EventArgs e) => TextBoxSearchTerm_TextChanged_Logic(); private void scalingTextBoxFilterCategories_TextChanged(object sender, EventArgs e) /// Wait for the end of typing by delaying the call to <see cref="typeAssistantFilterCategories_Idled"/> => typeAssistantFilterCategories.TextChanged(); private void typeAssistantFilterCategories_Idled(object sender, EventArgs e) { var f = FilterCategories; f.SearchRawPrevious = f.SearchRaw; f.SearchRaw = this.scalingTextBoxFilterCategories.Text; f.HasFilterCategory = !string.IsNullOrWhiteSpace(f.SearchRaw); if (f.HasFilterCategory) (f.IsRegex, f.Search, f.Regex, f.RegexIsValid) = StringHelper.IsTQVaultSearchRegEx(f.SearchRaw); /// Wrapped into an Invoke() because i'm currently in the thread of the /// <see cref="typeAssistantFilterCategories"> and i need <see cref="ApplyCategoriesReducer"/> to be executed from the main thread to avoid concurrent access exception this.Invoke(ApplyCategoriesReducer); } private void TextBoxSearchTerm_TextChanged_Logic() { MakeSearchTermBoxItem(); /// Wrapped into an Invoke() because i'm currently in the thread of the /// <see cref="typeAssistantSearchBox"> and i need <see cref="Sync_SelectedFilters"/> to be executed from the main thread to avoid concurrent access exception this.Invoke(Sync_SelectedFilters); } private BoxItem MakeSearchTermBoxItem(string searchTerm = null) { // Init a special BoxItem for the search term var txt = searchTerm is null ? scalingTextBoxSearchTerm.Text.Trim() : searchTerm.Trim(); var (_, searchTermBoxItem) = scalingTextBoxSearchTerm.GetBoxItem(true);// true : i need to make a new intance here to make the SearchQuery remember search term (must not share same object reference) searchTermBoxItem.Category = scalingLabelSearchTerm; searchTermBoxItem.DisplayValue = txt; if (string.IsNullOrWhiteSpace(txt)) searchTermBoxItem.MatchingResults = Enumerable.Empty<Result>(); else { // Item fulltext search var (isRegex, _, regex, regexIsValid) = StringHelper.IsTQVaultSearchRegEx(txt); searchTermBoxItem.MatchingResults = ( from id in ItemDatabase where isRegex && regexIsValid ? id.FriendlyNames.FulltextIsMatchRegex(regex) : id.FriendlyNames.FulltextIsMatchIndexOf(txt) select id ).ToArray(); } // When this method is used as a BoxItem factory, i don't want the textbox to keep the reference. if (searchTerm != null) scalingTextBoxSearchTerm.Tag = null; return searchTermBoxItem; } private void scalingLabelProgress_MouseEnter(object sender, EventArgs e) { var ctrl = sender as Control; FoundResultsTooltip.ShowTooltip(this.ServiceProvider, ctrl, this.QueryResults); } private void scalingLabelProgress_MouseLeave(object sender, EventArgs e) => FoundResultsTooltip.HideTooltip(); private void scalingLabelProgress_TextChanged(object sender, EventArgs e) { var ctrl = sender as Control; ScalingLabelProgressAdjustSizeAndPosition(ctrl); } private static void ScalingLabelProgressAdjustSizeAndPosition(Control ctrl) { // Adjust Control Size & position manualy because center align the control in it's container doesn't work with AutoSize = true ctrl.Size = TextRenderer.MeasureText(ctrl.Text, ctrl.Font); var loc = ctrl.Location; loc.X = (ctrl.Parent.Size.Width / 2) - (ctrl.Width / 2); ctrl.Location = loc; } private void scalingLabelProgressPanelAlignText_SizeChanged(object sender, EventArgs e) { // Prevent child text truncation during resize var ctrl = sender as Control; var label = ctrl.Controls.OfType<ScalingLabel>().First(); ScalingLabelProgressAdjustSizeAndPosition(label); } private void SavePersonnalQueries() { this._SearchQueries.Save(); } private void LoadPersonnalQueries() { if (!this._SearchQueries.Any()) return; // Try to retrieve actual instantiated BoxItems related to saved data. var matrix = ( from query in this._SearchQueries from boxi in query.CheckedItems select new { // Source query, query.QueryName, boxiSave = boxi, // Join boxi.DisplayValue, boxi.CategoryName, boxi.CheckedListName, found = new List<BoxItem>() // Late binding placeholder because anonymous types are immutable } ).ToList(); // Retrieve CheckBoxes flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { var (_, tag) = lb.GetBoxTag(); ( // Align Saved & Live BoxItems from ds in tag.DataSource join m in matrix on new { ds.CategoryName, ds.CheckedListName, ds.DisplayValue } equals new { m.CategoryName, m.CheckedListName, m.DisplayValue } select new { boxiLive = ds, matrix = m } ).ToList().ForEach(r => r.matrix.found.Add(r.boxiLive));// Bind } }); // Make Search terms ( from m in matrix where m.CategoryName == scalingLabelSearchTerm.Name // Unique to the search term select new { boxiLive = MakeSearchTermBoxItem(m.DisplayValue), matrix = m } ).ToList().ForEach(r => r.matrix.found.Add(r.boxiLive));// Bind // Renew list ( from m in matrix where m.found.Any() // Saved boxitems may not be retrieved if you have lost the items that carry the corresponding properties. group m by m.QueryName into grp // Should have only one query per group select grp ).ToList().ForEach(grp => { var originalQueryInstance = grp.First().query; //originalQueryInstance.QueryName = grp.Key; originalQueryInstance.CheckedItems = grp.SelectMany(i => i.found).ToArray(); }); SearchQueriesInit(); } private void scalingButtonQuerySave_Click(object sender, EventArgs e) { var input = scalingComboBoxQueryList.Text.Trim(); DialogResult? overrideIt = null; SearchQuery foundIt = null; #region Validation // You must have text if (string.IsNullOrWhiteSpace(input)) { MessageBox.Show( Resources.SearchQueryNameMustBeSet , Resources.GlobalInputWarning , MessageBoxButtons.OK , MessageBoxIcon.Error , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); return; } // You must have filters if (!HaveFilters()) { MessageBox.Show( Resources.SearchTermRequired , Resources.GlobalInputWarning , MessageBoxButtons.OK , MessageBoxIcon.Error , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); return; } // Name conflict foundIt = this._SearchQueries.FirstOrDefault(q => q.QueryName.Equals(input, StringComparison.OrdinalIgnoreCase)); if (foundIt != null) { overrideIt = MessageBox.Show( Resources.SearchQueryNameAlreadyExist , Resources.GlobalInputWarning , MessageBoxButtons.YesNo , MessageBoxIcon.Warning , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); if (overrideIt == DialogResult.No) return; } #endregion if (overrideIt == DialogResult.Yes) { UpdateQuery(input, foundIt); SavePersonnalQueries(); scalingComboBoxQueryList.Refresh(); return; } // Add scenario var newList = new IEnumerable<SearchQuery>[] { this._SearchQueries , new[] { UpdateQuery(input, new SearchQuery()) } } .SelectMany(s => s) .OrderBy(s => s.QueryName) .ToList(); this._SearchQueries.Clear(); this._SearchQueries.AddRange(newList); SearchQueriesInit(); SavePersonnalQueries(); SearchQuery UpdateQuery(string input, SearchQuery foundIt) { foundIt.QueryName = input; foundIt.CheckedItems = this._SelectedFilters.ToArray();// i need a clone here so ToArray() do the job // Visible elements / category foundIt.MaxElement = this.numericUpDownMaxElement.Value; // Reduce categories foundIt.Reduce = this.scalingCheckBoxReduceDuringSelection.Checked; // Logical operator foundIt.Logic = (SearchOperator)this.scalingComboBoxOperator.SelectedIndex; // Add Category filter foundIt.Filter = this.scalingTextBoxFilterCategories.Text; // Add Display elements foundIt.Visible = _NavMap.Select(m => new VisibilityItem(m.Button.Name, m.Panel.Visible)).ToList(); // Requierements foundIt.MinRequirement = scalingCheckBoxMinReq.Checked; foundIt.MaxRequirement = scalingCheckBoxMaxReq.Checked; foundIt.MaxLvl = (int)numericUpDownMaxLvl.Value; foundIt.MaxStr = (int)numericUpDownMaxStr.Value; foundIt.MaxDex = (int)numericUpDownMaxDex.Value; foundIt.MaxInt = (int)numericUpDownMaxInt.Value; foundIt.MinLvl = (int)numericUpDownMinLvl.Value; foundIt.MinStr = (int)numericUpDownMinStr.Value; foundIt.MinDex = (int)numericUpDownMinDex.Value; foundIt.MinInt = (int)numericUpDownMinInt.Value; foundIt.HavingPrefix = this.scalingCheckBoxHavingPrefix.Checked; foundIt.HavingSuffix = this.scalingCheckBoxHavingSuffix.Checked; foundIt.HavingRelic = this.scalingCheckBoxHavingRelic.Checked; foundIt.HavingCharm = this.scalingCheckBoxHavingCharm.Checked; foundIt.IsSetItem = this.scalingCheckBoxIsSetItem.Checked; return foundIt; } bool HaveFilters() { return this._SelectedFilters.Any() || (this.scalingCheckBoxMinReq.Checked && ( this.numericUpDownMinLvl.Value != 0 || this.numericUpDownMinStr.Value != 0 || this.numericUpDownMinDex.Value != 0 || this.numericUpDownMinInt.Value != 0 ) ) || (this.scalingCheckBoxMaxReq.Checked && ( this.numericUpDownMaxLvl.Value != 0 || this.numericUpDownMaxStr.Value != 0 || this.numericUpDownMaxDex.Value != 0 || this.numericUpDownMaxInt.Value != 0 ) ) || this.scalingCheckBoxHavingCharm.Checked || this.scalingCheckBoxHavingRelic.Checked || this.scalingCheckBoxHavingPrefix.Checked || this.scalingCheckBoxHavingSuffix.Checked || this.scalingCheckBoxIsSetItem.Checked ; } } private void SearchQueriesInit() { scalingComboBoxQueryList.BeginUpdate(); scalingComboBoxQueryList.Items.Clear(); scalingComboBoxQueryList.Items.AddRange(this._SearchQueries.ToArray()); scalingComboBoxQueryList.EndUpdate(); } private void scalingButtonQueryDelete_Click(object sender, EventArgs e) { var idx = scalingComboBoxQueryList.SelectedIndex; if (idx == -1) return; var item = scalingComboBoxQueryList.SelectedItem; var deleteIt = MessageBox.Show( string.Format(Resources.GlobalDeleteConfirm, item) , Resources.GlobalInputWarning , MessageBoxButtons.YesNo , MessageBoxIcon.Question , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); if (deleteIt == DialogResult.No) return; scalingComboBoxQueryList.Items.RemoveAt(idx); this._SearchQueries.RemoveAt(idx); SavePersonnalQueries(); } private void scalingComboBoxQueryList_SelectedIndexChanged(object sender, EventArgs e) { var idx = scalingComboBoxQueryList.SelectedIndex; Make_SelectedFilters(this._SearchQueries[idx]); } private void Make_SelectedFilters(SearchQuery searchQuery) { // Make _SelectedFilters from saved query _SelectedFilters.Clear(); _SelectedFilters.AddRange(searchQuery.CheckedItems); ResetCheckBoxesToFirstLoad(); // Restore SearchTerm ? var term = searchQuery.CheckedItems.FirstOrDefault(i => i.CheckedList is null); /// Avoid trigger of <see cref="scalingTextBoxSearchTerm_TextChanged"/> if (term is null) TextBoxSearchTerm_UpdateText_Notrigger(string.Empty); else { TextBoxSearchTerm_UpdateText_Notrigger(term.DisplayValue); this.scalingTextBoxSearchTerm.Tag = term; } MakeSearchTermBoxItem(); _Apply_SelectedFiltersDisabled = true;// Prevent filter before ui is fully init (// Find category visibility differences and apply from map in this._NavMap join vis in searchQuery.Visible on map.Button.Name equals vis.Name where map.Panel.Visible != vis.Visible select map ).ToList().ForEach(map => map.Button.PerformClick()); // Requirements this.numericUpDownMaxStr.Value = searchQuery.MaxStr; this.numericUpDownMaxDex.Value = searchQuery.MaxDex; this.numericUpDownMaxInt.Value = searchQuery.MaxInt; this.numericUpDownMinStr.Value = searchQuery.MinStr; this.numericUpDownMinDex.Value = searchQuery.MinDex; this.numericUpDownMinInt.Value = searchQuery.MinInt; this.numericUpDownMaxLvl.Value = searchQuery.MaxLvl; this.numericUpDownMinLvl.Value = searchQuery.MinLvl; this.scalingCheckBoxMinReq.Checked = searchQuery.MinRequirement; this.scalingCheckBoxMaxReq.Checked = searchQuery.MaxRequirement; // Quick Filters this.scalingCheckBoxHavingPrefix.Checked = searchQuery.HavingPrefix; this.scalingCheckBoxHavingSuffix.Checked = searchQuery.HavingSuffix; this.scalingCheckBoxHavingRelic.Checked = searchQuery.HavingRelic; this.scalingCheckBoxHavingCharm.Checked = searchQuery.HavingCharm; this.scalingCheckBoxIsSetItem.Checked = searchQuery.IsSetItem; // UI Behaviors this.numericUpDownMaxElement.Value = searchQuery.MaxElement; this.scalingComboBoxOperator.SelectedIndex = (int)searchQuery.Logic; this.scalingTextBoxFilterCategories.Text = searchQuery.Filter; this.scalingCheckBoxReduceDuringSelection.Checked = searchQuery.Reduce; _Apply_SelectedFiltersDisabled = false; this.Apply_SelectedFilters(); } private void scalingCheckBoxMinMaxReq_CheckedChanged(object sender, EventArgs e) { Apply_SelectedFilters(); } private void numericUpDownMinMax_ValueChanged(object sender, EventArgs e) { var num = sender as NumericUpDown; // Avoid absurd range if (num == numericUpDownMinLvl && numericUpDownMaxLvl.Value < num.Value) numericUpDownMaxLvl.Value = num.Value; else if (num == numericUpDownMaxLvl && numericUpDownMinLvl.Value > num.Value) numericUpDownMinLvl.Value = num.Value; else if (num == numericUpDownMinStr && numericUpDownMaxStr.Value < num.Value) numericUpDownMaxStr.Value = num.Value; else if (num == numericUpDownMaxStr && numericUpDownMinStr.Value > num.Value) numericUpDownMinStr.Value = num.Value; else if (num == numericUpDownMinDex && numericUpDownMaxDex.Value < num.Value) numericUpDownMaxDex.Value = num.Value; else if (num == numericUpDownMaxDex && numericUpDownMinDex.Value > num.Value) numericUpDownMinDex.Value = num.Value; else if (num == numericUpDownMinInt && numericUpDownMaxInt.Value < num.Value) numericUpDownMaxInt.Value = num.Value; else if (num == numericUpDownMaxInt && numericUpDownMinInt.Value > num.Value) numericUpDownMinInt.Value = num.Value; if (// No need to filter if corresponding checkbox is uncheck (num.Name.Contains("Min") && !this.scalingCheckBoxMinReq.Checked) || (num.Name.Contains("Max") && !this.scalingCheckBoxMaxReq.Checked) ) return; Apply_SelectedFilters(); } private void scalingCheckBoxQuickFilters_CheckedChanged(object sender, EventArgs e) { Apply_SelectedFilters(); } } public static class SearchDialogAdvancedExtension { public static (ScalingCheckedListBox, BoxTag) GetBoxTag(this Control obj) { var ctr = obj as ScalingCheckedListBox; if (ctr is null) return (null, null); var Tag = ctr.Tag as BoxTag ?? new BoxTag(); ctr.Tag = Tag; return (ctr, Tag); } public static (ScalingTextBox, BoxItem) GetBoxItem(this Control obj, bool newInstance) { var ctr = obj as ScalingTextBox; if (ctr is null) return (null, null); var Tag = newInstance ? new BoxItem() : ctr.Tag as BoxItem ?? new BoxItem(); ctr.Tag = Tag; return (ctr, Tag); } }
using Domain.Interfaces; using Repository; using System; namespace Domain.Fees { public class InvoiceFixedFee : IFee { public DateTimeOffset LastInvoiceFixedFeeDate; public Transaction Calculate(Transaction transaction, MerchantInformation merchantInformation) { if (!NeedToCalculate(transaction)) { return transaction; } transaction.InvoiceFixedFeeAmount += merchantInformation.InvoiceFixedFee; LastInvoiceFixedFeeDate = transaction.Date; return transaction; } private bool NeedToCalculate(Transaction transaction) { if (CheckIfDateIsNewerForMonthlyFee(transaction.Date) && transaction.TransactionPercentageFeeAmount > 0) { return true; } return false; } private bool CheckIfDateIsNewerForMonthlyFee(DateTimeOffset transactionDate) { if (LastInvoiceFixedFeeDate.Year == transactionDate.Year && LastInvoiceFixedFeeDate.Month < transactionDate.Month) { return true; } if (LastInvoiceFixedFeeDate.Year < transactionDate.Year) { return true; } return false; } } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.Doctrine.DBAL.Schema { public interface Schema { } }
using SFML.Graphics; using SFML.Window; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LD30 { class MouseMenu : GameObject { public bool Visible = true; public List<string> Options = new List<string>(); public Vector2f Position; public Vector2f OptionSize = new Vector2f(200f, 30f); public float OptionMargin = 4f; public int HoverIndex = -1; public MouseMenu(Game game) : base(game) { } public FloatRect GetRectForOption(int index) { var left = Position.X + OptionMargin; var top = Position.Y - (Options.Count * OptionSize.Y + Options.Count * OptionMargin) + (index * OptionSize.Y + index * OptionMargin); return new FloatRect(left, top, OptionSize.X, OptionSize.Y); } public override void Draw(SFML.Graphics.RenderTarget target) { var view = new View(target.GetView()); target.SetView(target.DefaultView); var bgRect = new RectangleShape(); bgRect.FillColor = new Color(150, 113, 57); bgRect.Size = new Vector2f(OptionSize.X + 2f * OptionMargin, Options.Count * OptionSize.Y + Options.Count * OptionMargin + OptionMargin); bgRect.Position = new Vector2f(Position.X, Position.Y - bgRect.Size.Y); target.Draw(bgRect); float nextX = bgRect.Position.X + OptionMargin; float nextY = bgRect.Position.Y + OptionMargin; for (int i = 0; i < Options.Count; i++) { var fgRect = new RectangleShape(); if (HoverIndex == i) { fgRect.FillColor = new Color(175, 132, 66); } else { fgRect.FillColor = new Color(201, 151, 76); } fgRect.Size = OptionSize; fgRect.Position = new Vector2f(nextX, nextY); target.Draw(fgRect); var text = new Text(Options[i], ResourceManager.GetResource<Font>("font"), 32u); text.DisplayedString = Options[i]; text.Position = new Vector2f(nextX + OptionMargin, nextY - OptionSize.Y / 3f); target.Draw(text); nextY += OptionSize.Y + OptionMargin; } target.SetView(view); } } }
using DynamicData; using MaterialDesignThemes.Wpf; using ReactiveUI; using ReactiveUI.Fody.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Windows; using System.Windows.Forms.VisualStyles; using TableTopCrucible.Core.Helper; using TableTopCrucible.Core.WPF.PageViewModels; using TableTopCrucible.Domain.Library.WPF.ViewModels; using TableTopCrucible.Domain.Library.WPF.Views; using TableTopCrucible.Domain.Models.ValueTypes.IDs; namespace TableTopCrucible.Domain.Library.WPF.PageViewModels { public class ItemEditorPageViewModel : PageViewModelBase { public ItemListViewModel ItemList { get; } public ItemEditorViewModel ItemEditor { get; } public IMultiItemEditor MultiItemEditor { get; } [Reactive] public object Editor { get; private set; } [Reactive] public bool IsSingle { get; private set; } public ItemListFilterViewModel Filter { get; } public ItemEditorPageViewModel( ItemListViewModel itemList, ItemEditorViewModel itemEditor, IMultiItemEditor multiItemEditor, ItemListFilterViewModel filter) : base("item Editor", PackIconKind.Edit) { this.ItemList = itemList; this.MultiItemEditor = multiItemEditor; Editor = this.ItemEditor = itemEditor; this.Filter = filter; multiItemEditor.BindSelection(itemList.Selection); this.disposables.Add(ItemList, ItemEditor, MultiItemEditor, Filter); filter.FilterChanges .TakeUntil(destroy) .Subscribe(itemList.FilterChanges.OnNext, ex => MessageBox.Show(ex.ToString(), $"{nameof(ItemEditorPageViewModel)}.ctor:subscribe") ); this.ItemList.Selection.Connect() .ToCollection() .Subscribe(x => { this.IsSingle = x.Count <= 1; if (x.Count == 1) itemEditor.SelectItem(x.FirstOrDefault().SourceItem.Id); else itemEditor.SelectItem(null); if (x.Count <= 1) this.Editor = ItemEditor; else this.Editor = MultiItemEditor; }); itemEditor.SetTagpool(Filter.Tagpool); multiItemEditor.SetTagpool(Filter.Tagpool); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Minigame28 { public class Car : MonoBehaviour { #region variables public Transform containerPath; private float _speed = 180; private UISprite _sprite; private bool _isMove = false; private List<Transform> listPath; private Transform _targetPoint; #endregion void Awake() { Reset(); } void Start() { MiniGameHelper.FindChildObjects<Transform>(containerPath, ref listPath); } void Update() { if (!MiniGame28_Manager.instance.isPlay || !_isMove) return; if (_targetPoint && _targetPoint.position != transform.position) { // Расчет поворота transform.right -= Vector3.Lerp(transform.right, _targetPoint.transform.localPosition - transform.localPosition, 0.3f * Time.deltaTime); // Расчет перемещения float speedThisFrame = _speed * Time.deltaTime; transform.localPosition += (_targetPoint.transform.localPosition - transform.localPosition).normalized * speedThisFrame; if (Vector3.Distance(transform.localPosition, _targetPoint.transform.localPosition) < speedThisFrame * 1.1f) GetNewTarget(); } else if (!GetNewTarget()) _isMove = false; } public void Move() { if (listPath.Count > 0) transform.position = listPath[0].position; if (listPath.Count > 1) _targetPoint = listPath[1]; if (_sprite != null) _sprite.alpha = 1f; _isMove = true; } public void Reset() { if (_sprite == null) _sprite = GetComponent<UISprite>(); if (_sprite != null) _sprite.alpha = 0f; _isMove = false; } private bool GetNewTarget() { if (_targetPoint != null) { int i = listPath.IndexOf(_targetPoint); if (i == listPath.Count - 1) { _targetPoint = null; MiniGame28_Manager.instance.Finish(); return false; } else if (i >= 0 && i < listPath.Count - 1) { _targetPoint = listPath[i + 1]; return true; } else { _targetPoint = null; return false; } } return false; } } }
// // - PropertyDefinition.cs - // // Copyright 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Reflection; using Carbonfrost.Commons.Core; namespace Carbonfrost.Commons.PropertyTrees.Schema { public abstract class PropertyDefinition : PropertyNodeDefinition { public abstract Type PropertyType { get; } public abstract bool IsReadOnly { get; } public abstract bool IsOptional { get; } public abstract object DefaultValue { get; } public abstract PropertyTreeDefinition DeclaringTreeDefinition { get; } public override string ToString() { return string.Format("{2}.{0}:{1}", Name, PropertyType, DeclaringTreeDefinition); } public virtual bool IsIndexer { get { return false; } } public virtual bool IsExtender { get { return false; } } public virtual bool IsParamArray { get { return false; } } public object GetValue(object component) { return GetValue(component, null); } public void SetValue(object component, object value) { SetValue(component, null, null, value); } public object GetValue(object component, QualifiedName name) { object result; if (TryGetValue(component, null, name, out result)) { return result; } throw new NotImplementedException(); } public void SetValue(object component, QualifiedName name, object value) { SetValue(component, null, name, value); } public abstract bool TryGetValue(object component, object ancestor, QualifiedName name, out object result); public abstract void SetValue(object component, object ancestor, QualifiedName name, object value); public virtual bool CanExtend(Type extendeeType) { return false; } internal virtual PropertyInfo GetUnderlyingDescriptor() { return null; } internal bool TryGetValue(object component, QualifiedName qualifiedName) { object dummy; return TryGetValue(component, null, qualifiedName, out dummy); } } }
using System; using System.Collections.Generic; using System.Data; using System.Text; using MySql.Data.MySqlClient; using Models; namespace DAL { public class learninfo : POJO<tb_learninfo> { public learninfo() { } #region 成员方法 public void Add(tb_learninfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into tb_learninfo("); strSql.Append("employeeid,degree,starttime,graduatetime,graduatesch,retence,profession,content"); strSql.Append(")"); strSql.Append(" values ("); strSql.Append("'" + model.employeeid + "',"); strSql.Append("'" + model.degree + "',"); strSql.Append("'" + model.starttime + "',"); strSql.Append("'" + model.graduatetime + "',"); strSql.Append("'" + model.graduatesch + "',"); strSql.Append("'" + model.retence + "',"); strSql.Append("'" + model.profession + "',"); strSql.Append("'" + model.content + "'"); strSql.Append(")"); DbHelperSQL.ExecuteSql(strSql.ToString()); } public void Update(tb_learninfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update tb_learninfo set "); strSql.Append("employeeid='" + model.employeeid + "',"); strSql.Append("degree='" + model.degree + "',"); strSql.Append("starttime='" + model.starttime + "',"); strSql.Append("graduatetime='" + model.graduatetime + "',"); strSql.Append("graduatesch='" + model.graduatesch + "',"); strSql.Append("retence='" + model.retence + "',"); strSql.Append("profession='" + model.profession + "',"); strSql.Append("content='" + model.content + "'"); strSql.Append(" where id=" + model.id + ""); DbHelperSQL.ExecuteSql(strSql.ToString()); } public void Delete(string strwhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from tb_learninfo "); strSql.Append(" where " + strwhere); DbHelperSQL.ExecuteSql(strSql.ToString()); } /// <summary> /// 获得数据列表 /// </summary> override public DataSet GetList(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select * from tb_learninfo "); if (strWhere.Trim() != "") { strSql.Append("where " + strWhere + ""); } strSql.Append(" order by id "); return DbHelperSQL.Query(strSql.ToString()); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class playerScoreScript : MonoBehaviour { private int score = 0; [SerializeField] TextMeshProUGUI gameScoreText,bestScoreText; void Start() { } void Update() { } void OnTriggerEnter2D(Collider2D collider){ if (collider.tag == "Coin"){ score++; gameScoreText.text = score.ToString(); collider.gameObject.SetActive(false); } if (collider.tag == "Rocket"){ transform.position = new Vector3(0,1000,0); collider.gameObject.SetActive(false); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UniInject; using UnityEngine; using UniRx; using System.IO; using UnityEngine.SceneManagement; // Disable warning about fields that are never assigned, their values are injected. #pragma warning disable CS0649 [ExecuteInEditMode] public class I18NManager : MonoBehaviour, INeedInjection { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void Init() { currentLanguageMessages?.Clear(); fallbackMessages?.Clear(); } public const string I18NFolder = "I18N"; public const string PropertiesFileExtension = ".properties"; public const string PropertiesFileName = "messages"; public static I18NManager Instance { get { return GameObjectUtils.FindComponentWithTag<I18NManager>("I18NManager"); } } public bool logInfo; public bool isOverwriteLanguage; public SystemLanguage overwriteLanguage; // Fields are static to be persisted across scenes private static Dictionary<string, string> currentLanguageMessages; private static Dictionary<string, string> fallbackMessages; private void Awake() { if (fallbackMessages.IsNullOrEmpty()) { UpdateCurrentLanguageAndTranslations(); } } #if UNITY_EDITOR private void Update() { if (Application.isPlaying) { return; } if (fallbackMessages.IsNullOrEmpty()) { UpdateCurrentLanguageAndTranslations(); } } #endif public List<string> GetKeys() { return fallbackMessages.Keys.ToList(); } public static string GetTranslation(string key, params string[] placeholderStrings) { if (placeholderStrings.Length % 2 != 0) { Debug.LogWarning($"Uneven number of placeholders for '{key}'. Format in array should be [key1, value1, key2, value2, ...]"); } // Create dictionary from placeholderStrings Dictionary<string, string> placeholders = new Dictionary<string, string>(); for (int i = 0; i < placeholderStrings.Length && i + 1 < placeholderStrings.Length; i += 2) { string placeholderKey = placeholderStrings[i]; string placeholderValue = placeholderStrings[i + 1]; placeholders[placeholderKey] = placeholderValue; } return GetTranslation(key, placeholders); } public static string GetTranslation(string key, Dictionary<string, string> placeholders) { string translation = GetTranslation(key); foreach (KeyValuePair<string, string> placeholder in placeholders) { string placeholderText = "{" + placeholder.Key + "}"; if (translation.Contains(placeholderText)) { translation = translation.Replace(placeholderText, placeholder.Value); } else { Debug.LogWarning($"Translation is missing placeholder {placeholderText}"); } } return translation; } public static string GetTranslation(string key) { if (currentLanguageMessages.TryGetValue(key, out string translation)) { return translation; } else { Debug.LogWarning($"Missing translation in language '{SettingsManager.Instance.Settings.GameSettings.language}' for key '{key}'"); if (fallbackMessages.TryGetValue(key, out string fallbackTranslation)) { return fallbackTranslation; } else { Debug.LogError($"No translation for key '{key}'"); return key; } } } public void UpdateCurrentLanguageAndTranslations() { currentLanguageMessages = new Dictionary<string, string>(); fallbackMessages = new Dictionary<string, string>(); SystemLanguage selectedLanguage = Application.isEditor && isOverwriteLanguage ? overwriteLanguage : SettingsManager.Instance.Settings.GameSettings.language; // Load the default properties file string fallbackPropertiesFilePath = GetPropertiesFilePath(PropertiesFileName); string fallbackPropertiesFileContent = File.ReadAllText(fallbackPropertiesFilePath); LoadPropertiesFromText(fallbackPropertiesFileContent, fallbackMessages); // Load the properties file of the current language string propertiesFileNameWithCountryCode = PropertiesFileName + GetCountryCodeSuffixForPropertiesFile(selectedLanguage); string propertiesFilePath = GetPropertiesFilePath(propertiesFileNameWithCountryCode); string propertiesFileContent = File.ReadAllText(propertiesFilePath); LoadPropertiesFromText(propertiesFileContent, currentLanguageMessages); if (logInfo) { Debug.Log("Loaded " + fallbackMessages.Count + " translations from " + fallbackPropertiesFilePath); Debug.Log("Loaded " + currentLanguageMessages.Count + " translations from " + propertiesFilePath); } UpdateAllTranslationsInScene(); } private static void UpdateAllTranslationsInScene() { LinkedList<ITranslator> translators = new LinkedList<ITranslator>(); Scene scene = SceneManager.GetActiveScene(); if (scene != null && scene.isLoaded) { GameObject[] rootObjects = scene.GetRootGameObjects(); foreach (GameObject rootObject in rootObjects) { UpdateTranslationsRecursively(rootObject, translators); } Debug.Log($"Updated ITranslator instances in scene: {translators.Count}"); } } private static void UpdateTranslationsRecursively(GameObject gameObject, LinkedList<ITranslator> translators) { MonoBehaviour[] scripts = gameObject.GetComponents<MonoBehaviour>(); foreach (MonoBehaviour script in scripts) { // The script can be null if it is a missing component. if (script == null) { continue; } if (script is ITranslator translator) { translators.AddLast(translator); translator.UpdateTranslation(); } } foreach (Transform child in gameObject.transform) { UpdateTranslationsRecursively(child.gameObject, translators); } } private static void LoadPropertiesFromText(string text, Dictionary<string, string> targetDictionary) { targetDictionary.Clear(); PropertiesFileParser.ParseText(text).ForEach(entry => targetDictionary.Add(entry.Key, entry.Value)); } private static string GetCountryCodeSuffixForPropertiesFile(SystemLanguage language) { if (language != SystemLanguage.English) { return "_" + LanguageHelper.Get2LetterIsoCodeFromSystemLanguage(language).ToLower(); } else { return ""; } } private static string GetPropertiesFilePath(string propertiesFileNameWithCountryCode) { string path = I18NFolder + "/" + propertiesFileNameWithCountryCode + PropertiesFileExtension; path = ApplicationUtils.GetStreamingAssetsPath(path); return path; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using XyzOfficeEmployeeTrackerr.Models; namespace XyzOfficeEmployeeTrackerr.Repository { public interface ISalaryRep { public List<SalaryDetail> GetDetails(); public SalaryDetail GetDetail(int id); public int AddDetail(SalaryDetail obj); public int UpdateDetail(int id, SalaryDetail obj); public int Delete(int id); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PersonTag : MonoBehaviour { public int storeID; }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; public class CharacterController : MonoBehaviourPunCallbacks { public float MovementSpeed = 4.5f; public float JumpForce = 10f; private Rigidbody2D _rigidbody; // Start is called before the first frame update void Start() { _rigidbody = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { if (photonView.IsMine) { float movement = Input.GetAxis("Horizontal"); transform.position += new Vector3(movement,0,0) * Time.deltaTime * MovementSpeed; if(Input.GetButtonDown("Jump") && Mathf.Abs(_rigidbody.velocity.y)<0.01f ) { _rigidbody.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse); } if (_rigidbody.velocity.y<=-2.0f) _rigidbody.gravityScale = 0.0f; else _rigidbody.gravityScale = 1.0f; } } }
using System; namespace Micro.Net.Exceptions { public class InitializationException : ApplicationException { public InitializationException(string message, int code) : base(message) { HResult = code; } public static InitializationException FeatureNotSupported(string featureName) => new InitializationException($"Failure to initialize feature: {featureName}. Please check platform compatibility.", 600); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class OverlayController : MonoBehaviour { public static OverlayController Instance; public UnityEvent onEndOverlay; public UnityEvent onStartOverlay; [SerializeField] private Animator overlayAnimator; private void Awake() { if(Instance == null) { Instance = this; } else { Destroy(this); } } /// Start obscuring the screen. public void StartOverlay() { onStartOverlay?.Invoke(); overlayAnimator.SetBool("Overlay", true); } /// Start removing the overlay. public void EndOverlay() { onEndOverlay?.Invoke(); overlayAnimator.SetBool("Overlay", false); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericsArrayCreator { public class ArrayCreator { public static T[] Create<T>(int length, T item) { var start = new T[length]; for(int i=0; i < length; i++) { start[i] = item; } return start; } } }
using FastSQL.Core; using FastSQL.Sync.Core.Models; using FastSQL.Sync.Core.Repositories; using FastSQL.Sync.Core.Workflows; using FastSQL.Sync.Workflow.Models; using FastSQL.Sync.Workflow.Steps; using Serilog; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using WorkflowCore.Interface; using WorkflowCore.Primitives; namespace FastSQL.Sync.Workflow.Workflows { [Description("Requeue Errors")] public class RequeueErrorsWorkflow : BaseWorkflow<GeneralMessage> { private ILogger _logger; private ILogger Logger => _logger ?? (_logger = ResolverFactory.Resolve<ILogger>("Workflow")); public override string Id => nameof(RequeueErrorsWorkflow); public override int Version => 1; public override bool IsGeneric => true; public RequeueErrorsWorkflow() { } public override void Build(IWorkflowBuilder<GeneralMessage> builder) { builder.StartWith(x => { }) .While(d => true) .Do(x => { x.StartWith<FilterRunningEntitiesStep>() .Input(s => s.WorkflowId, s => Id) .Output(d => d.Indexes, d => d.Indexes) .Output(d => d.Counter, d => 0) .If(s => s.Indexes == null || s.Indexes.Count() <= 0) .Do(i => i.StartWith<Delay>(d => TimeSpan.FromHours(1))) .If(s => s.Indexes != null && s.Indexes.Count() > 0) .Do(i => { i .StartWith(ii => { }) .While(w => w.Counter < w.Indexes.Count()) .Do(dd => dd.StartWith<RequeueErrorsStep>() .Input(u => u.IndexModel, g => g.Indexes[g.Counter]) .Output(s => s.Counter, u => u.Counter)) .Then<Delay>(d => TimeSpan.FromHours(1)); }); }); } } }
using Lfs.Persistense.Repositories; using System; using System.Data; using System.Data.SqlClient; namespace Lfs.Persistense.Infrastructure { public interface IUnitOfWork : IDisposable { IPersonRepository PersonRepository { get; } IQueryRepository QueryRepository { get; } void Commit(); } public class UnitOfWork : IUnitOfWork { private bool _disposed; private IDbConnection _connection; private IDbTransaction _transaction; private IPersonRepository _personRepository; private IQueryRepository _queryRepository; public IPersonRepository PersonRepository => _personRepository ?? (_personRepository = new PersonRepository(_transaction)); public IQueryRepository QueryRepository => _queryRepository ?? (_queryRepository = new QueryRepository(_transaction)); public UnitOfWork(IUnitOfWorkConfiguration configuration) { _connection = new SqlConnection(configuration.ConnectionString); _connection.Open(); _transaction = _connection.BeginTransaction(); } public void Commit() { if (_disposed) { throw new ObjectDisposedException(nameof(UnitOfWork)); } try { _transaction.Commit(); } catch { _transaction.Rollback(); throw; } finally { _transaction.Dispose(); _transaction = _connection.BeginTransaction(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if (_disposed) { return; } if (!disposing) { return; } _transaction?.Dispose(); _transaction = null; _connection?.Dispose(); _connection = null; _disposed = true; } ~UnitOfWork() { Dispose(false); } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; namespace Swiddler.Behaviors { public static class Button { private static readonly DependencyProperty ClickOpensContextMenuProperty = DependencyProperty.RegisterAttached("ClickOpensContextMenu", typeof(bool), typeof(Button), new PropertyMetadata(false, new PropertyChangedCallback(HandlePropertyChanged))); public static bool GetClickOpensContextMenu(DependencyObject obj) => (bool)obj.GetValue(ClickOpensContextMenuProperty); public static void SetClickOpensContextMenu(DependencyObject obj, bool value) => obj.SetValue(ClickOpensContextMenuProperty, value); private static void HandlePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { if (obj is ButtonBase btn) { btn.Click -= ExecuteClick; btn.Click += ExecuteClick; } } private static void ExecuteClick(object sender, RoutedEventArgs args) { if (sender is ButtonBase btn && GetClickOpensContextMenu(btn)) { if (btn.ContextMenu != null) { btn.ContextMenu.PlacementTarget = btn; btn.ContextMenu.Placement = ContextMenuService.GetPlacement(btn); btn.ContextMenu.IsOpen = true; } } } } }
using System; using System.Collections.Generic; using System.Data; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace JJApi.Controllers { [Authorize(Roles = "level1,level2")] public class CompanyProfileController : Controller { [HttpPost] [Route("/Companyprofile/getData")] public string getDataCompanyprofile([FromForm] IFormFile file, Dictionary<string, string> datos) { BL.queries.blCompany bCompany = new BL.queries.blCompany(Request.Headers["Authorization"].ToString()); string result = bCompany.getDataCompanyprofile(null, datos); return result; } [HttpPost] [Route("/Companyprofile/getDataSearch")] public string getDataCompanyFilter([FromForm] IFormFile file, Dictionary<string, string> datos) { BL.queries.blCompany bCompany = new BL.queries.blCompany(Request.Headers["Authorization"].ToString()); string result = bCompany.filtersearch( datos); return result; } [HttpPost] [Route("/Companyprofile/setData")] public string setDataCompanyprofile([FromForm] IFormFile file, Dictionary<string, string> collection) { BL.queries.blCompany bCompany = new BL.queries.blCompany(Request.Headers["Authorization"].ToString()); string result = bCompany.setDataCompanyprofile(null, collection); return result; } } }
using System; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Razor.Chunks; using Microsoft.AspNetCore.Razor.CodeGenerators; using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors; namespace Microsoft.AspNetCore.Mvc.RazorPages.Compilation { public class PageCodeGenerator : CSharpCodeGenerator { public PageCodeGenerator(CodeGeneratorContext context) : base(context) { } protected override CSharpCodeVisitor CreateCSharpCodeVisitor( CSharpCodeWriter writer, CodeGeneratorContext context) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } var csharpCodeVisitor = base.CreateCSharpCodeVisitor(writer, context); var attributeRenderer = new MvcTagHelperAttributeValueCodeRenderer(new GeneratedTagHelperAttributeContext() { CreateModelExpressionMethodName = "CreateModelExpression", ModelExpressionProviderPropertyName = "ModelExpressionProvider", ModelExpressionTypeName = "Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression", ViewDataPropertyName = "ViewData", }); csharpCodeVisitor.TagHelperRenderer.AttributeValueCodeRenderer = attributeRenderer; return csharpCodeVisitor; } protected override void BuildConstructor(CSharpCodeWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } base.BuildConstructor(writer); writer.WriteLineHiddenDirective(); var injectVisitor = new InjectChunkVisitor(writer, Context, "Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute"); injectVisitor.Accept(Context.ChunkTreeBuilder.Root.Children); var modelVisitor = new ModelChunkVisitor(writer, Context); modelVisitor.Accept(Context.ChunkTreeBuilder.Root.Children); if (modelVisitor.ModelType != null) { writer.WriteLine(); // public ModelType Model => ViewData?.Model ?? default(ModelType); writer.Write("public ").Write(modelVisitor.ModelType).Write(" Model => ViewData?.Model ?? default(").Write(modelVisitor.ModelType).Write(");"); writer.WriteLine(); var viewDataType = $"global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<{modelVisitor.ModelType}>"; writer.Write("public new ").Write(viewDataType).Write(" ViewData").WriteLine(); writer.Write("{").WriteLine(); writer.IncreaseIndent(4); writer.Write("get { return (").Write(viewDataType).Write(")base.ViewData; }").WriteLine(); writer.DecreaseIndent(4); writer.Write("}").WriteLine(); } writer.WriteLine(); writer.WriteLineHiddenDirective(); } private class ModelChunkVisitor : CodeVisitor<CSharpCodeWriter> { public ModelChunkVisitor(CSharpCodeWriter writer, CodeGeneratorContext context) : base(writer, context) { } public string ModelType { get; set; } public override void Accept(Chunk chunk) { if (chunk is ModelChunk) { Visit((ModelChunk)chunk); } else { base.Accept(chunk); } } private void Visit(ModelChunk chunk) { ModelType = chunk.ModelType; } } } }
using LAP_PowerMining.Core.Enums; using LAP_PowerMining.Core.Helpers; using LAP_PowerMining.Core.Repositories; using LAP_PowerMining.Models.ViewModels.Account; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LAP_PowerMining.Core.Services { public static class AccountService { static UserRepository context = new UserRepository(); public static bool LogOutUser() { LoginHelper.Logout(); return true; } public static bool LogInUser(VMLogin loginInfo) { bool result = context.CheckLogin(loginInfo); if (result == true) { LoginHelper.LoginUser(loginInfo); } loginInfo.Password = ""; return result; } public static int RegisterUser(VMRegister registerInfo) { if (registerInfo.Password != registerInfo.ConfirmPassword) { return (int)RegisterType.PasswordsDifferent; } int result = context.CreateUser(registerInfo); if (result == (int)RegisterType.Success) { LoginHelper.LoginUser(new VMLogin { Email = registerInfo.Email, Password = registerInfo.Password }); MailHelper.SendEmail(registerInfo.Email); } return result; } public static int UpdateUser(VMUserData userData, string userMail) { int result = -1; int tempResult = -1; // Gathers all data which are allowed to be changed VMUserData dataValidToChange = new VMUserData(); if (!string.IsNullOrEmpty(userData.FirstName)) { dataValidToChange.FirstName = userData.FirstName; } if (!string.IsNullOrEmpty(userData.LastName)) { dataValidToChange.LastName = userData.LastName; } if (!string.IsNullOrEmpty(userData.OldPassword) && !string.IsNullOrEmpty(userData.NewPassword) && !string.IsNullOrEmpty(userData.ConfirmNewPassword)) { VMLogin testOldPw = new VMLogin { Email = userMail, Password = userData.OldPassword }; if (userData.NewPassword == userData.ConfirmNewPassword) { if (context.CheckLogin(testOldPw)) { dataValidToChange.NewPassword = userData.NewPassword; } } } tempResult = context.UpdateUser(dataValidToChange, userMail); userData.ConfirmNewPassword = ""; userData.NewPassword = ""; userData.OldPassword = ""; return result; } public static VMUserData GetUserData(string email) { return context.GetUserData(email); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectEuler { public class TenThousandOnethPrime : ISolution { public void Run() { Result = Enumerable.Range(2, int.MaxValue - 1).TakeWhile(x => x < int.MaxValue).Where(x => MathHelper.IsPrime(x)).Skip(10000).First(); } public object Result { get; private set; } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game; using Triton.Game.Mono; [Attribute38("TwistingNetherSpell")] public class TwistingNetherSpell : SuperSpell { public TwistingNetherSpell(IntPtr address) : this(address, "TwistingNetherSpell") { } public TwistingNetherSpell(IntPtr address, string className) : base(address, className) { } public void Begin() { base.method_8("Begin", Array.Empty<object>()); } public bool CanFinish() { return base.method_11<bool>("CanFinish", Array.Empty<object>()); } public void CleanUp() { base.method_8("CleanUp", Array.Empty<object>()); } public void CleanUpVictim(Victim victim) { object[] objArray1 = new object[] { victim }; base.method_8("CleanUpVictim", objArray1); } public void Drain(Victim victim) { object[] objArray1 = new object[] { victim }; base.method_8("Drain", objArray1); } public void Float(Victim victim) { object[] objArray1 = new object[] { victim }; base.method_8("Float", objArray1); } public Card GetTargetCardFromPowerTask(int index, PowerTask task) { object[] objArray1 = new object[] { index, task }; return base.method_14<Card>("GetTargetCardFromPowerTask", objArray1); } public void Lift() { base.method_8("Lift", Array.Empty<object>()); } public void OnAction(SpellStateType prevStateType) { object[] objArray1 = new object[] { prevStateType }; base.method_8("OnAction", objArray1); } public void OnDrainFinished(Victim victim) { object[] objArray1 = new object[] { victim }; base.method_8("OnDrainFinished", objArray1); } public void OnFinishTimeFinished() { base.method_8("OnFinishTimeFinished", Array.Empty<object>()); } public void OnFloatFinished(Victim victim) { object[] objArray1 = new object[] { victim }; base.method_8("OnFloatFinished", objArray1); } public void OnLiftFinished(Victim victim) { object[] objArray1 = new object[] { victim }; base.method_8("OnLiftFinished", objArray1); } public void Setup() { base.method_8("Setup", Array.Empty<object>()); } public static Vector3 DEAD_SCALE { get { return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "TwistingNetherSpell", "DEAD_SCALE"); } } public TwistingNetherDrainInfo m_DrainInfo { get { return base.method_3<TwistingNetherDrainInfo>("m_DrainInfo"); } } public float m_FinishTime { get { return base.method_2<float>("m_FinishTime"); } } public TwistingNetherFloatInfo m_FloatInfo { get { return base.method_3<TwistingNetherFloatInfo>("m_FloatInfo"); } } public TwistingNetherLiftInfo m_LiftInfo { get { return base.method_3<TwistingNetherLiftInfo>("m_LiftInfo"); } } public TwistingNetherSqueezeInfo m_SqueezeInfo { get { return base.method_3<TwistingNetherSqueezeInfo>("m_SqueezeInfo"); } } public List<Victim> m_victims { get { Class267<Victim> class2 = base.method_3<Class267<Victim>>("m_victims"); if (class2 != null) { return class2.method_25(); } return null; } } [Attribute38("TwistingNetherSpell.Victim")] public class Victim : MonoClass { public Victim(IntPtr address) : this(address, "Victim") { } public Victim(IntPtr address, string className) : base(address, className) { } public Card m_card { get { return base.method_3<Card>("m_card"); } } public TwistingNetherSpell.VictimState m_state { get { return base.method_2<TwistingNetherSpell.VictimState>("m_state"); } } } public enum VictimState { NONE, LIFTING, FLOATING, DRAINING, DEAD } } }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet.Utilities.Memory; using NtApiDotNet.Win32.Rpc.Transport; using System; using System.Collections; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace NtApiDotNet.Net.Firewall { /// <summary> /// Firewall value. /// </summary> public struct FirewallValue : IComparable<FirewallValue>, IComparable, ICloneable { #region Public Properties /// <summary> /// Type of the value. /// </summary> public FirewallDataType Type { get; } /// <summary> /// The raw value. /// </summary> public object Value { get; } /// <summary> /// The context specific value, might be the same as the original. /// </summary> public object ContextValue { get; } #endregion #region Private Members private static object SpecializeValue(FirewallDataType type, object value, Guid condition_key) { if (condition_key == Guid.Empty) return value; if (FirewallConditionGuids.IsIpAddressCondition(condition_key)) { if (value is byte[] ba && (ba.Length == 4 || ba.Length == 16)) { return new IPAddress(ba); } else if (value is uint ui) { ba = BitConverter.GetBytes(ui); Array.Reverse(ba); return new IPAddress(ba); } else if (!(value is FirewallRange) && !(value is FirewallAddressAndMask)) { System.Diagnostics.Trace.Write($"Invalid IP Address type: {value.GetType().FullName}"); } } else if (FirewallConditionGuids.IsAppId(condition_key) || condition_key == FirewallConditionGuids.FWPM_CONDITION_PIPE || condition_key == FirewallConditionGuids.FWPM_CONDITION_RPC_SERVER_NAME) { if (value is byte[] ba && (ba.Length % 2 == 0)) { return Encoding.Unicode.GetString(ba).TrimEnd('\0'); } } else if (FirewallConditionGuids.IsGuid(condition_key)) { if (value is byte[] ba && ba.Length == 16) { return new Guid(ba); } } else if (condition_key == FirewallConditionGuids.FWPM_CONDITION_IP_PROTOCOL || condition_key == FirewallConditionGuids.FWPM_CONDITION_EMBEDDED_PROTOCOL) { if (value is byte b) { return (ProtocolType)b; } } else if (condition_key == FirewallConditionGuids.FWPM_CONDITION_FLAGS) { if (value is uint ui) { return (FirewallConditionFlags)ui; } } else if (type == FirewallDataType.Sid) { if (value is Sid sid) { return sid.Name; } } else if (type is FirewallDataType.SecurityDescriptor && value is SecurityDescriptor sd) { if (sd.DaclPresent && sd.Dacl.Count == 1 && sd.Dacl[0].Type == AceType.Allowed && sd.Dacl[0].Mask.IsAccessGranted(FirewallFilterAccessRights.Match)) { return sd.Dacl[0].Sid.Name; } return sd.ToSddl(); } else if (condition_key == FirewallConditionGuids.FWPM_CONDITION_DIRECTION) { if (value is uint ui) { return (FirewallDirectionType)ui; } } else if (condition_key == FirewallConditionGuids.FWPM_CONDITION_RPC_AUTH_TYPE) { if (value is byte b) { return (RpcAuthenticationType)b; } } else if (condition_key == FirewallConditionGuids.FWPM_CONDITION_RPC_AUTH_LEVEL) { if (value is byte b) { return (RpcAuthenticationType)b; } } else if (FirewallConditionGuids.IsMacAddressCondition(condition_key)) { if (value is byte[] ba && ba.Length == 6) { return string.Join(":", ba.Select(b => $"{b:X02}")); } } else if (FirewallConditionGuids.IsProfileId(condition_key)) { if (value is uint profile_id) { return (FirewallProfileId)profile_id; } } else if (FirewallConditionGuids.IsDataLink(condition_key)) { if (value is byte dl_type) { return (DataLinkAddressType)dl_type; } } else if (FirewallConditionGuids.IsNetworkLayer(condition_key)) { if (value is byte nl_type) { return (NetworkLayerAddressType)nl_type; } } else if (FirewallConditionGuids.IsTunnelType(condition_key)) { if (value is uint tunnel_type) { return (NetworkTunnelType)tunnel_type; } } else if (FirewallConditionGuids.IsInterfaceType(condition_key)) { if (value is uint if_type) { return (NetworkInterfaceType)if_type; } } return value; } private static byte[] ReadBytes(IntPtr ptr, int size) { if (size <= 0 || ptr == IntPtr.Zero) { return new byte[0]; } byte[] ret = new byte[size]; Marshal.Copy(ptr, ret, 0, ret.Length); return ret; } private static byte[] ReadBlob(IntPtr ptr) { var blob = ptr.ReadStruct<FWP_BYTE_BLOB>(); return ReadBytes(blob.data, blob.size); } private static object ToObject(FirewallDataType type, FWP_VALUE0_UNION value, Guid condition_key) { switch (type) { case FirewallDataType.SecurityDescriptor: return SecurityDescriptor.Parse(ReadBlob(value.sd), FirewallUtils.FirewallFilterType, false).GetResultOrDefault(); case FirewallDataType.TokenInformation: return new FirewallTokenInformation(value.tokenInformation.ReadStruct<FWP_TOKEN_INFORMATION>()); case FirewallDataType.TokenAccessInformation: return ReadBlob(value.tokenAccessInformation); case FirewallDataType.Sid: return Sid.Parse(value.sid, false).GetResultOrDefault(); case FirewallDataType.UInt8: return value.uint8; case FirewallDataType.UInt16: return value.uint16; case FirewallDataType.UInt32: return value.uint32; case FirewallDataType.Int8: return value.int8; case FirewallDataType.Int16: return value.int16; case FirewallDataType.Int32: return value.int32; case FirewallDataType.Range: return new FirewallRange(value.rangeValue.ReadStruct<FWP_RANGE0>(), condition_key); case FirewallDataType.ByteArray16: return ReadBytes(value.byteArray16, 16); case FirewallDataType.ByteArray6: return ReadBytes(value.byteArray6, 6); case FirewallDataType.UInt64: return (ulong)Marshal.ReadInt64(value.uint64); case FirewallDataType.Int64: return Marshal.ReadInt64(value.uint64); case FirewallDataType.ByteBlob: return ReadBlob(value.byteBlob); case FirewallDataType.V4AddrMask: return new FirewallAddressAndMask(value.v4AddrMask.ReadStruct<FWP_V4_ADDR_AND_MASK>()); case FirewallDataType.V6AddrMask: return new FirewallAddressAndMask(value.v6AddrMask.ReadStruct<FWP_V6_ADDR_AND_MASK>()); case FirewallDataType.UnicodeString: return Marshal.PtrToStringUni(value.unicodeString); case FirewallDataType.BitmapArray64: return new BitArray(value.bitmapArray64.ReadStruct<FWP_BITMAP_ARRAY64>().bitmapArray64); case FirewallDataType.Empty: return new FirewallEmpty(); default: return type.ToString(); } } #endregion #region Internal Members internal FirewallValue(FWP_VALUE0 value, Guid condition_key) { Type = value.type; Value = ToObject(value.type, value.value, condition_key); ContextValue = SpecializeValue(value.type, Value, condition_key); } internal FirewallValue(FirewallDataType type, object value, object context_value) { Type = type; Value = value; ContextValue = context_value; } internal FirewallValue(FirewallDataType type, object value) : this(type, value, value) { } internal FWP_VALUE0 ToStruct(DisposableList list) { FWP_VALUE0 ret = new FWP_VALUE0(); switch (Type) { case FirewallDataType.Empty: break; case FirewallDataType.Sid: ret.value.sid = list.AddSid((Sid)Value).DangerousGetHandle(); break; case FirewallDataType.UInt8: ret.value.uint8 = ((IConvertible)Value).ToByte(null); break; case FirewallDataType.UInt16: ret.value.uint16 = ((IConvertible)Value).ToUInt16(null); break; case FirewallDataType.UInt32: ret.value.uint32 = ((IConvertible)Value).ToUInt32(null); break; case FirewallDataType.Int8: ret.value.int8 = ((IConvertible)Value).ToSByte(null); break; case FirewallDataType.Int16: ret.value.int16 = ((IConvertible)Value).ToInt16(null); break; case FirewallDataType.Int32: ret.value.int32 = ((IConvertible)Value).ToInt32(null); break; case FirewallDataType.ByteArray16: ret.value.byteArray16 = list.AddResource(new SafeHGlobalBuffer((byte[])Value)).DangerousGetHandle(); break; case FirewallDataType.ByteArray6: ret.value.byteArray6 = list.AddResource(new SafeHGlobalBuffer((byte[])Value)).DangerousGetHandle(); break; case FirewallDataType.UInt64: ret.value.uint64 = list.AddResource(((IConvertible)Value).ToUInt64(null).ToBuffer()).DangerousGetHandle(); break; case FirewallDataType.Int64: ret.value.int64 = list.AddResource(((IConvertible)Value).ToInt64(null).ToBuffer()).DangerousGetHandle(); break; case FirewallDataType.TokenAccessInformation: case FirewallDataType.ByteBlob: case FirewallDataType.SecurityDescriptor: { if (!(Value is byte[] buffer)) { buffer = ((SecurityDescriptor)Value).ToByteArray(); } FWP_BYTE_BLOB blob = new FWP_BYTE_BLOB { size = buffer.Length, data = list.AddBytes(buffer).DangerousGetHandle() }; ret.value.byteBlob = list.AddStructureRef(blob).DangerousGetHandle(); break; } case FirewallDataType.V4AddrMask: ret.value.v4AddrMask = ((FirewallAddressAndMask)Value).ToBuffer(list).DangerousGetHandle(); break; case FirewallDataType.V6AddrMask: ret.value.v6AddrMask = ((FirewallAddressAndMask)Value).ToBuffer(list).DangerousGetHandle(); break; case FirewallDataType.UnicodeString: ret.value.unicodeString = list.AddNulTerminatedUnicodeString((string)Value).DangerousGetHandle(); break; case FirewallDataType.Range: ret.value.rangeValue = list.AddStructureRef(((FirewallRange)Value).ToStruct(list)).DangerousGetHandle(); break; case FirewallDataType.TokenInformation: ret.value.tokenInformation = list.AddStructureRef(((FirewallTokenInformation)Value).ToStruct(list)).DangerousGetHandle(); break; default: throw new ArgumentException($"Value type {Type} unsupported."); } ret.type = Type; return ret; } internal static FirewallValue FromBlob(byte[] value, object context_value) { return new FirewallValue(FirewallDataType.ByteBlob, value, context_value); } private static FirewallValue FromByteArray16(byte[] value, object context_value) { if (value.Length != 16) throw new ArgumentOutOfRangeException("Array must be 16 bytes in size.", nameof(value)); return new FirewallValue(FirewallDataType.ByteArray16, value, context_value); } private static FirewallValue FromUInt32(uint value, object context_value) { return new FirewallValue(FirewallDataType.UInt32, value, context_value); } #endregion #region Static Members /// <summary> /// Get a value which represents Empty. /// </summary> public static FirewallValue Empty => new FirewallValue(FirewallDataType.Empty, new FirewallEmpty()); /// <summary> /// Create a value from a security descriptor. /// </summary> /// <param name="security_descriptor">The security descriptor.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromSecurityDescriptor(SecurityDescriptor security_descriptor) { return new FirewallValue(FirewallDataType.SecurityDescriptor, security_descriptor); } /// <summary> /// Create a value from a SID. /// </summary> /// <param name="sid">The SID.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromSid(Sid sid) { return new FirewallValue(FirewallDataType.Sid, sid); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromUInt8(byte value) { return new FirewallValue(FirewallDataType.UInt8, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromUInt16(ushort value) { return new FirewallValue(FirewallDataType.UInt16, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromUInt32(uint value) { return new FirewallValue(FirewallDataType.UInt32, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromUInt64(ulong value) { return new FirewallValue(FirewallDataType.UInt64, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromUInt32Bool(bool value) { return FromUInt32(value ? 1U : 0U); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromInt8(sbyte value) { return new FirewallValue(FirewallDataType.Int8, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromInt16(short value) { return new FirewallValue(FirewallDataType.Int16, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromInt32(int value) { return new FirewallValue(FirewallDataType.Int32, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromInt64(ulong value) { return new FirewallValue(FirewallDataType.Int64, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromBlob(byte[] value) { return new FirewallValue(FirewallDataType.ByteBlob, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromBlobUnicodeString(string value) { return FromBlob(Encoding.Unicode.GetBytes(value + "\0"), value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromUnicodeString(string value) { return new FirewallValue(FirewallDataType.UnicodeString, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromByteArray16(byte[] value) { if (value.Length != 16) throw new ArgumentOutOfRangeException("Array must be 16 bytes in size.", nameof(value)); return new FirewallValue(FirewallDataType.ByteArray16, value); } /// <summary> /// Create a value. /// </summary> /// <param name="address">The IPv4 address.</param> /// <param name="mask">The IPv4 mask.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromV4AddrMask(IPAddress address, IPAddress mask) { if (address.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("Address must be InternetNetwork family.", nameof(address)); } if (mask.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("Mask must be InternetNetwork family.", nameof(mask)); } return new FirewallValue(FirewallDataType.V4AddrMask, new FirewallAddressAndMask(address, mask)); } /// <summary> /// Create a value. /// </summary> /// <param name="address">The IPv6 address.</param> /// <param name="prefix_length">The prefix length.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromV6AddrMask(IPAddress address, int prefix_length) { if (address.AddressFamily != AddressFamily.InterNetworkV6) { throw new ArgumentException("Address must be InterNetworkV6 family.", nameof(address)); } if (prefix_length < 0 || prefix_length > 128) { throw new ArgumentOutOfRangeException("Prefix length invalid.", nameof(prefix_length)); } return new FirewallValue(FirewallDataType.V6AddrMask, new FirewallAddressAndMask(address, prefix_length)); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromProtocolType(ProtocolType value) { return new FirewallValue(FirewallDataType.UInt8, (byte)value, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromConditionFlags(FirewallConditionFlags value) { return new FirewallValue(FirewallDataType.UInt32, (uint)value, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromIpAddress(IPAddress value) { if (value.AddressFamily == AddressFamily.InterNetworkV6) { return FromByteArray16(value.GetAddressBytes(), value); } else if (value.AddressFamily == AddressFamily.InterNetwork) { byte[] arr = value.GetAddressBytes(); Array.Reverse(arr); return FromUInt32(BitConverter.ToUInt32(arr, 0), value); } throw new ArgumentException("Must specify V4 or V6 IP address.", nameof(value)); } /// <summary> /// Create a range value. /// </summary> /// <param name="low">The low value.</param> /// <param name="high">The high value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromRange(FirewallValue low, FirewallValue high) { return new FirewallValue(FirewallDataType.Range, new FirewallRange(low, high)); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromTokenInformation(FirewallTokenInformation value) { return new FirewallValue(FirewallDataType.TokenInformation, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromTokenInformation(NtToken value) { return new FirewallValue(FirewallDataType.TokenInformation, new FirewallTokenInformation(value)); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromTokenAccessInformation(byte[] value) { return new FirewallValue(FirewallDataType.TokenAccessInformation, value); } /// <summary> /// Create a value. /// </summary> /// <param name="value">The value.</param> /// <returns>The firewall value.</returns> public static FirewallValue FromGuid(Guid value) { return new FirewallValue(FirewallDataType.ByteArray16, value.ToByteArray(), value); } #endregion #region Public Methods /// <summary> /// Overridden ToString method. /// </summary> /// <returns>The value as a string.</returns> public override string ToString() { return ContextValue?.ToString() ?? "(null)"; } #endregion #region Interface Implementations int IComparable<FirewallValue>.CompareTo(FirewallValue other) { if (Value is IComparable comp) { return comp.CompareTo(other.Value); } return 0; } int IComparable.CompareTo(object obj) { if (obj is FirewallValue other) { if (Value is IComparable comp) { return comp.CompareTo(other.Value); } } return 0; } object ICloneable.Clone() { return new FirewallValue(Type, Value.CloneValue(), ContextValue.CloneValue()); } #endregion } }
using MD.PersianDateTime.Core; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using OfficeOpenXml; using OfficeOpenXml.Table; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using VinarishMvc.Areas.Authentication.Data; using VinarishMvc.Data; using VinarishMvc.Models; namespace VinarishMvc.Controllers { [Authorize(Roles = RolesList.User.RoleName)] public class ReportsController : Controller { private readonly ApplicationDbContext _context; private readonly IHostingEnvironment _env; public ReportsController( IHostingEnvironment env, ApplicationDbContext context) { _env = env; _context = context; } // GET: Reports public async Task<IActionResult> Index() { Microsoft.EntityFrameworkCore.Query.IIncludableQueryable<Report, Wagon> applicationDbContext = _context.Reports.Include(r => r.DevicePlace).Include(r => r.DeviceStatus).Include(r => r.ParentReport).Include(r => r.Reporter).Include(r => r.Wagon); return View(await applicationDbContext.ToListAsync()); } // GET: Reports/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } Report report = await _context.Reports .Include(r => r.DevicePlace) .Include(r => r.DeviceStatus) .Include(r => r.ParentReport) .Include(r => r.Reporter) .Include(r => r.Wagon) .FirstOrDefaultAsync(m => m.ReportId == id); if (report == null) { return NotFound(); } return View(report); } public class CreateViewModel { [DisplayName(Expressions.Reporter)] public string Username { get; set; } [DisplayName(Expressions.DeviceTypes)] public Guid DeviceTypeId { get; set; } public Report Report { get; set; } = new Report(); public int ParentReportId { get; set; } [DisplayName(Expressions.Assistants)] public Dictionary<string, bool> Assistants { get; set; } } private void GenerateReportCode(ref CreateViewModel model) { Report report = model.Report; GenerateReportCode(ref report); model.Report = report; } private void GenerateReportCode(ref Report report) { report.Code = GenerateReportCode(report.DevicePlaceId, report.DeviceStatusId, report.ReporterId, report.WagonId, DateTime.Now); } private string GenerateReportCode(Guid DevicePlaceId, Guid DeviceStatusId, int ReporterId, Guid WagonId, DateTime date) { DevicePlace dp = _context.DevicePlaces.Find(DevicePlaceId); DeviceStatus ds = _context.DeviceStatus.Find(DeviceStatusId); Reporter rep = _context.Reporters.Find(ReporterId); Wagon w = _context.Wagons.Find(WagonId); return w.Number + dp.Code.ToUpper() + ds.Code.ToUpper() + rep.UserName.ToUpper() + date.ToString("yyMMdd"); } // GET: Reports/CreateTripReport/[WagonTripId] public async Task<IActionResult> CreateTripReport(Guid id) { WagonTrip wagonTrip = await _context.WagonTrips.Include(wt => wt.Wagon).Where(wt => wt.WagonTripId == id).FirstOrDefaultAsync(); Wagon wagon = wagonTrip.Wagon; CreateViewModel model = new CreateViewModel(); model.Report.WagonId = wagon.WagonId; model.Report.Wagon = wagon; model.Report.WagonTripId = wagonTrip.WagonTripId; model.Report.WagonTrip = wagonTrip; ViewData["DeviceTypeId"] = new SelectList(_context.DeviceTypes, "DeviceTypeId", "Name"); return View("Create", model); } // GET: Reports/CreateWagonReport/[WagonId] public IActionResult CreateWagonReport(Guid id) { Wagon wagon = _context.Wagons.Find(id); CreateViewModel model = new CreateViewModel(); model.Report.WagonId = wagon.WagonId; model.Report.Wagon = wagon; ViewData["DeviceTypeId"] = new SelectList(_context.DeviceTypes, "DeviceTypeId", "Name"); return View("Create", model); } // GET: Reports/CreateTripReport/DeviceTypeSelected public IActionResult DeviceTypeSelected(CreateViewModel model) { model.Report.Wagon = _context.Wagons.Find(model.Report.WagonId); ViewData["DeviceTypeId"] = new SelectList(_context.DeviceTypes, "DeviceTypeId", "Name", model.DeviceTypeId); ViewData["DevicePlaceId"] = new SelectList(_context.DevicePlaces.Where(dp => dp.DeviceTypeId == model.DeviceTypeId), "DevicePlaceId", "Description"); ViewData["DeviceStatusId"] = new SelectList(_context.DeviceStatus .Where(ds => ds.DeviceTypeId == model.DeviceTypeId && ds.DeviceStatusType == DeviceStatusType.Malfunction), "StatusId", "Text"); return View("Create", model); } // POST: Reports/CreateTripReport [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateReport(CreateViewModel model) { if (ModelState.IsValid) { model.Report.ReporterId = _context.Reporters.Where(r => r.UserName == model.Username).FirstOrDefault().ReporterId; GenerateReportCode(ref model); _context.Reports.Add(model.Report); await _context.SaveChangesAsync(); if (model.Report.WagonTripId != null) { WagonTrip wt = _context.WagonTrips.Find(model.Report.WagonTripId); return RedirectToAction("Details", "TrainTrips", new { id = model.Report.WagonTrip.TrainTripId }); } else { return RedirectToAction("Details", "Wagons", new { id = model.Report.Wagon.WagonId }); } } return RedirectToAction(nameof(CreateReport), model.Report.WagonId); } // GET: Reports/Edit/[ReportId] public IActionResult Edit(int id) { CreateViewModel model = new CreateViewModel { Report = _context.Reports .Include(r => r.DevicePlace) .Include(r => r.Wagon) .Where(r => r.ReportId == id) .FirstOrDefault(), ParentReportId = id }; ViewData["DeviceStatusId"] = new SelectList(_context.DeviceStatus .Where(ds => (ds.DeviceTypeId == model.Report.DevicePlace.DeviceTypeId && ds.DeviceStatusType == DeviceStatusType.Malfunction)), "StatusId", "Text"); return View("CreateChildReport", model); } // GET: Reports/CreateRepairingReport/[ReportId] public IActionResult CreateRepairingReport(int id) { if (!ReportExists(id)) return NotFound(); CreateViewModel model = new CreateViewModel { Report = _context.Reports .Include(r => r.DevicePlace) .Include(r => r.Wagon) .Where(r => r.ReportId == id) .FirstOrDefault(), ParentReportId = id, Assistants = new Dictionary<string, bool>() }; ViewData["SiteId"] = new SelectList(_context.Sites, "SiteId", "Name"); List<Reporter> assistants = _context.Reporters.OrderBy(r => r.UserName).ToList(); foreach (Reporter assitant in assistants) { model.Assistants.Add(assitant.UserName, false); } ViewData["DeviceStatusId"] = new SelectList(_context.DeviceStatus .Where(ds => (ds.DeviceTypeId == model.Report.DevicePlace.DeviceTypeId && ds.DeviceStatusType == DeviceStatusType.Repair)), "StatusId", "Text"); return View("CreateChildReport", model); } // GET: Reports/CreateUnrepairedReport/[ReportId] public IActionResult CreateUnrepairedReport(int id) { CreateViewModel model = new CreateViewModel { Report = _context.Reports .Include(r => r.DevicePlace) .Include(r => r.Wagon) .Where(r => r.ReportId == id) .FirstOrDefault(), ParentReportId = id }; ViewData["SiteId"] = new SelectList(_context.Sites, "SiteId", "Name"); ViewData["DeviceStatusId"] = new SelectList(_context.DeviceStatus .Where(ds => ds.DeviceStatusType == DeviceStatusType.Unrepairable), "StatusId", "Text"); return View("CreateChildReport", model); } // POST: Reports/CreateRepairingReport [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateChildReport(CreateViewModel model) { if (ModelState.IsValid) { Report NewReport = model.Report; NewReport.ReporterId = _context.Reporters.Where(r => r.UserName == model.Username).FirstOrDefault().ReporterId; NewReport.ParentReportId = model.ParentReportId; GenerateReportCode(ref NewReport); _context.Reports.Add(NewReport); await _context.SaveChangesAsync(); if (model.Assistants != null) { List<Assistant> assistants = new List<Assistant>(); foreach (var item in model.Assistants) { if (item.Value) { assistants.Add(new Assistant { ReportId = NewReport.ReportId, PersonId = _context.Reporters.Where(r => r.UserName == item.Key).FirstOrDefault().ReporterId }); } } _context.AddRange(assistants); await _context.SaveChangesAsync(); } if (NewReport.WagonTripId != null) { WagonTrip wt = _context.WagonTrips.Find(NewReport.WagonTripId); return RedirectToAction(nameof(Details), "TrainTrips", new { id = wt.TrainTripId }); } else { return RedirectToAction("Details", "Wagons", new { id = NewReport.WagonId }); } } return View("CreateChildReport", model); } //// GET: Reports/Edit/5 //[Authorize(Roles = RolesList.Admin.RoleName)] //public async Task<IActionResult> Edit(int? id) //{ // if (id == null) // { // return NotFound(); // } // Report report = await _context.Reports.FindAsync(id); // if (report == null) // { // return NotFound(); // } // ViewData["DevicePlaceId"] = new SelectList(_context.DevicePlaces, "DevicePlaceId", "Code", report.DevicePlaceId); // ViewData["DeviceStatusId"] = new SelectList(_context.DeviceStatus, "StatusId", "Code", report.DeviceStatusId); // ViewData["ParentReportId"] = new SelectList(_context.Reports, "ReportId", "Code", report.ParentReportId); // ViewData["ReporterId"] = new SelectList(_context.Reporters, "ReporterId", "UserName", report.ReporterId); // ViewData["WagonId"] = new SelectList(_context.Wagons, "WagonId", "Name", report.WagonId); // return View(report); //} //// POST: Reports/Edit/5 //// To protect from overposting attacks, please enable the specific properties you want to bind to, for //// more details see http://go.microsoft.com/fwlink/?LinkId=317598. //[HttpPost] //[ValidateAntiForgeryToken] //public async Task<IActionResult> Edit(int id, [Bind("ReportId,DateTimeCreated,DateTimeModified,ReporterId,Status,DeviceStatusId,ParentReportId,DevicePlaceId,WagonId")] Report report) //{ // if (id != report.ReportId) // { // return NotFound(); // } // if (ModelState.IsValid) // { // try // { // _context.Update(report); // await _context.SaveChangesAsync(); // } // catch (DbUpdateConcurrencyException) // { // if (!ReportExists(report.ReportId)) // { // return NotFound(); // } // else // { // throw; // } // } // return RedirectToAction(nameof(Index)); // } // ViewData["DevicePlaceId"] = new SelectList(_context.DevicePlaces, "DevicePlaceId", "Code", report.DevicePlaceId); // ViewData["DeviceStatusId"] = new SelectList(_context.DeviceStatus, "StatusId", "Code", report.DeviceStatusId); // ViewData["ParentReportId"] = new SelectList(_context.Reports, "ReportId", "Code", report.ParentReportId); // ViewData["ReporterId"] = new SelectList(_context.Reporters, "ReporterId", "UserName", report.ReporterId); // ViewData["WagonId"] = new SelectList(_context.Wagons, "WagonId", "Name", report.WagonId); // return View(report); //} // GET: Reports/Delete/5 [Authorize(Roles = RolesList.Admin.RoleName)] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } Report report = await _context.Reports .Include(r => r.DevicePlace) .Include(r => r.DeviceStatus) .Include(r => r.ParentReport) .Include(r => r.Reporter) .Include(r => r.Wagon) .FirstOrDefaultAsync(m => m.ReportId == id); if (report == null) { return NotFound(); } return View(report); } // POST: Reports/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { Report report = await _context.Reports.FindAsync(id); _context.Reports.Remove(report); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ReportExists(int id) { return _context.Reports.Any(e => e.ReportId == id); } // GET: Reports/Upload [Authorize(Roles = RolesList.Admin.RoleName)] public IActionResult Upload() { return View(); } private DateTime FromOldExcelDateTime(string InDate) { string persianDate = InDate; string[] userDateParts = persianDate.Split(new[] { "/" }, System.StringSplitOptions.None); int Year = int.Parse(userDateParts[2]); int Month = int.Parse(userDateParts[1]); int Day = int.Parse(userDateParts[0]); var persianDateTime = new PersianDateTime(Year, Month, Day); return persianDateTime.ToDateTime(); } private class ReportValues { [DisplayName(Expressions.DateTime)] public string Date { get; set; } [DisplayName(Expressions.Wagon)] public string WagonNum { get; set; } [DisplayName(Expressions.DevicePlaces)] public string DevicePlaceCode { get; set; } [DisplayName(Expressions.UserName)] public string UserName { get; set; } [DisplayName(Expressions.DeviceStatus)] public string DeviceStatusCode { get; set; } } // POST: Reports/Upload [HttpPost] //[ValidateAntiForgeryToken] //[RequestSizeLimit(5000000)] public async Task<IActionResult> Upload(IFormFile File) { IFormFile file = File; if (file == null || file.Length == 0) { return RedirectToAction(nameof(Index)); } List<Report> Reports = new List<Report>(); Dictionary<string, Report> ChildReports = new Dictionary<string, Report>(); List<int> LostReports = new List<int>(); using (MemoryStream memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream).ConfigureAwait(false); using (ExcelPackage package = new ExcelPackage(memoryStream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; // Tip: To access the first worksheet, try index 1, not 0 int totalRows = worksheet.Dimension.Rows; int[] ReportCells = { 0, 2, 3, 4, 6 };//بر اساس فایل گزارشهای شرکت ریل پرداز int[] RepairCells = { 5, 7, 11 };//بر اساس فایل گزارشهای شرکت ریل پرداز for (int i = 2; i < totalRows; i++) { string[] ReportCellValues = new string[ReportCells.Length]; bool SkipRow = false; for (int c = 0; c < ReportCells.Length; c++) { object CellValue = ((object[,])(worksheet.Cells.Value))[i, ReportCells[c]]; if (CellValue == null) { SkipRow = true; continue; } ReportCellValues[c] = CellValue.ToString(); } if (SkipRow) { LostReports.Add(i + 1); continue; } DateTime date; try { date = FromOldExcelDateTime(ReportCellValues[0]); } catch { LostReports.Add(i + 1); continue; } Wagon wagon = _context.Wagons.Where(w => w.Number == Convert.ToInt32(ReportCellValues[1])).FirstOrDefault(); DevicePlace devp = _context.DevicePlaces.Where(dp => dp.Code == ReportCellValues[2]).FirstOrDefault(); Reporter rep = _context.Reporters.Where(r => r.UserName == ReportCellValues[3]).FirstOrDefault(); DeviceStatus devS = _context.DeviceStatus.Where(ds => ds.Code == ReportCellValues[4]).FirstOrDefault(); string Code; try { Code = GenerateReportCode(devp.DevicePlaceId, devS.StatusId, rep.ReporterId, wagon.WagonId, date); } catch { LostReports.Add(i + 1); continue; } if (!_context.Reports.Any(r => r.Code == Code) && !Reports.Any(r => r.Code == Code)) { Reports.Add(new Report { DateTimeCreated = date, WagonId = wagon.WagonId, DevicePlaceId = devp.DevicePlaceId, DeviceStatusId = devS.StatusId, ReporterId = rep.ReporterId, Code = Code }); } //else // LostReports.Add(new ReportValues // { // Date = date, // WagonNum = ReportCellValues[1], // DevicePlaceCode = ReportCellValues[2], // UserName = ReportCellValues[3], // DeviceStatusCode = ReportCellValues[4] // }); string[] RepairCellValues = new string[RepairCells.Length]; bool NoChild = false; for (int c = 0; c < RepairCells.Length; c++) { object CellValue = ((object[,])(worksheet.Cells.Value))[i, RepairCells[c]]; if (CellValue == null || CellValue.ToString().Length < 2) { NoChild = true; break; } RepairCellValues[c] = CellValue.ToString(); } if (NoChild) { continue; } Reporter repairer = _context.Reporters.Where(r => r.UserName == RepairCellValues[0]).FirstOrDefault(); DeviceStatus dsRep = _context.DeviceStatus.Where(ds => ds.Code == RepairCellValues[1]).FirstOrDefault(); DateTime RepDate = FromOldExcelDateTime(RepairCellValues[2]); string RepCode; try { RepCode = GenerateReportCode(devp.DevicePlaceId, dsRep.StatusId, repairer.ReporterId, wagon.WagonId, RepDate); } catch { LostReports.Add(i + 1); continue; } ChildReports.Add(Code, new Report { DateTimeCreated = RepDate, WagonId = wagon.WagonId, DevicePlaceId = devp.DevicePlaceId, DeviceStatusId = dsRep.StatusId, ReporterId = repairer.ReporterId, Code = RepCode }); } } } _context.Reports.AddRange(Reports); await _context.SaveChangesAsync(); string fileName = _env.WebRootPath + @"\Excel\LostReports.xlsx"; FileInfo LostReportsFile = new FileInfo(fileName); if (LostReportsFile.Exists) { LostReportsFile.Delete(); } using (ExcelPackage ExcelPackage = new ExcelPackage(LostReportsFile)) { ExcelWorksheet worksheet = ExcelPackage.Workbook.Worksheets.Add(Expressions.LostReports); worksheet.Cells[1, 1].Value = "شماره ردیف"; int row = 2; foreach (int r in LostReports) { worksheet.Cells[row++, 1].Value = r.ToString(); } ExcelPackage.Save(); } List<Report> ChildReports2 = new List<Report>(); foreach (KeyValuePair<string, Report> item in ChildReports) { Report parentReport = _context.Reports.Where(r => r.Code == item.Key).FirstOrDefault(); if (parentReport == null) { continue;//ParentReportIsLost } item.Value.ParentReportId = parentReport.ReportId; if (!_context.Reports.Any(r => r.Code == item.Value.Code)) ChildReports2.Add(item.Value); else continue; _context.Reports.Update(parentReport); } _context.Reports.AddRange(ChildReports2); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } public FileResult DownloadLostReports(string filename) { return PhysicalFile(filename, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Expressions.LostReports + ".xlsx"); } public IActionResult Download() { string fileName = _env.WebRootPath + @"\Excel\Reports.xlsx"; FileInfo file = new FileInfo(fileName); if (file.Exists) file.Delete(); using (ExcelPackage ExcelPackage = new ExcelPackage(file)) { ExcelWorksheet worksheet = ExcelPackage.Workbook.Worksheets.Add(Expressions.Reports); worksheet.View.RightToLeft = true; List<Report> reports = _context.Reports.ToList(); int row = 1; int col = 1; worksheet.Cells[row, col++].Value = Expressions.DateTime; worksheet.Cells[row, col++].Value = Expressions.Wagon; worksheet.Cells[row, col++].Value = Expressions.Code + Expressions.DevicePlaces; worksheet.Cells[row, col++].Value = Expressions.DevicePlaces; worksheet.Cells[row, col++].Value = Expressions.Reporter; worksheet.Cells[row, col++].Value = Expressions.DeviceStatus; worksheet.Cells[row, col++].Value = Expressions.Status; worksheet.Cells[row, col++].Value = Expressions.Site; foreach (Report r in reports) { if (r.ParentReport != null) continue; col = 1; row++; worksheet.Cells[row, col++].Value = r.DateTimeCreated.ToString("yy/MM/dd"); worksheet.Cells[row, col++].Value = r.Wagon.Name; worksheet.Cells[row, col++].Value = r.DevicePlace.Code; worksheet.Cells[row, col++].Value = r.DevicePlace.Description; worksheet.Cells[row, col++].Value = r.Reporter.UserName; worksheet.Cells[row, col++].Value = r.DeviceStatus.Code; worksheet.Cells[row, col++].Value = r.DeviceStatus.Text; col++; if (r.Site != null) worksheet.Cells[row, col].Value = r.Site.Name; foreach (Report cr in r.AppendixReports) { worksheet.Cells[row, col++].Value = cr.DateTimeCreated.ToString("yy/MM/dd"); worksheet.Cells[1, col].Value = Expressions.DateTime; worksheet.Cells[row, col++].Value = cr.Reporter.UserName; worksheet.Cells[1, col].Value = Expressions.Reporter; worksheet.Cells[row, col++].Value = cr.DeviceStatus.Code; worksheet.Cells[1, col].Value = Expressions.Code + Expressions.Status; worksheet.Cells[row, col++].Value = cr.DeviceStatus.Text; worksheet.Cells[1, col].Value = Expressions.DeviceStatus; } } //worksheet.Cells["A1"].LoadFromCollection(reports, true, TableStyles.Medium25); var range = worksheet.Cells[worksheet.Dimension.Address]; var table = worksheet.Tables.Add(range, "Reports"); table.TableStyle = TableStyles.Medium25; worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns(); ExcelPackage.Save(); } return PhysicalFile(fileName, " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Expressions.Reports + ".xlsx"); } } }
using UnityEngine; using System.Collections; using NewtonVR; public class AntiPhobicPistol : MonoBehaviour { public Material laserMaterial; public Color onColor; public Color offColor; public Transform FirePoint; public NVRHand Hand; private Transform laser; // Use this for initialization void Start () { GameObject laserObj = GameObject.CreatePrimitive(PrimitiveType.Cylinder); laserObj.transform.SetParent(this.transform); laserObj.transform.rotation = Quaternion.AngleAxis(90, transform.right); laserObj.GetComponent<MeshRenderer>().material = laserMaterial; laserObj.GetComponent<MeshRenderer>().material.color = offColor; Destroy(laserObj.GetComponent<Collider>()); laser = laserObj.transform; } // Update is called once per frame void Update() { float distance = 1000; Ray ray = new Ray(FirePoint.position, transform.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit, distance)) { distance = Vector3.Distance(hit.point, FirePoint.position); } laser.localScale = new Vector3(0.01f, distance / 2f, 0.01f); laser.position = FirePoint.position + transform.forward * distance / 2f; if (Hand.Inputs[NVRButtons.Trigger].IsPressed) { if (Physics.Raycast(FirePoint.position, transform.forward, out hit, distance)) { if (hit.collider.CompareTag("PhobicObject")) { Destroy(hit.transform.gameObject); } } Hand.TriggerHapticPulse(500); } if (Hand.Inputs[NVRButtons.Trigger].PressDown == true) { laser.GetComponent<MeshRenderer>().material.color = onColor; } if (Hand.Inputs[NVRButtons.Trigger].PressUp == true) { laser.GetComponent<MeshRenderer>().material.color = offColor; } } }
using System.Collections.Generic; namespace XorLog.Core { public class Page { public long OffsetStart { get; private set;} public long OffsetStop { get; private set; } public long TotalSize { get; private set; } public long RequestedOffset{ get; private set; } public IList<string> Lines { get; private set; } public Page(long offsetStart, long offsetStop, long totalSize, IList<string> lines, long requestedOffset) { OffsetStart = offsetStart; OffsetStop = offsetStop; TotalSize = totalSize; Lines = lines; RequestedOffset = requestedOffset; } public override string ToString() { string ret = string.Format("Page: Start:{0}, Stop:{1}, Size:{2}, NbLines:{3}, RequestedOffset:{4}", OffsetStart, OffsetStop, TotalSize, Lines.Count, RequestedOffset); // if (Lines.Count > 0) commented because dumps private data in log // { // ret += Environment.NewLine + "First Line: " + Lines.First(); // ret += Environment.NewLine + "Last Line: " + Lines.Last(); // } return ret; } } }
using Entities.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entities.ViewModels { public class PilotepdcaViewModel { public List<PDCA> pdcas { get; set; } public Zone zone { get; set; } public Pilote pilote { get; set; } public bool certificationasked { get; set; } } }
using System.Collections; using UnityEngine; public class LoadLevel : MonoBehaviour { #region Fields [SerializeField] private string levelName; [SerializeField] private FadeInFadeOutCanvas fadeInFadeOut; [SerializeField] private GameObject canvas; #endregion #region Behaviour Methods public void Load() { StartCoroutine(this.DifferedLoad()); } private IEnumerator DifferedLoad() { this.canvas.SetActive(true); this.fadeInFadeOut.FadeOut(); yield return new WaitForSeconds(5.0f); Application.LoadLevel(this.levelName); } #endregion }
namespace Zzz.Dic.MaxLengths { public class DataDictionaryMaxLength { public const int Name = 64; public const int Description = 256; public const int Label = 64; public const int Value = 64; } }
using System.Reflection; namespace Redback { public abstract class BaseFilter { public abstract bool IsMatch(MemberInfo memberInfo); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HttpCookieCollection cookies = Response.Cookies; if(cookies.Count > 0) { if(Session["USERTYPE"] != null) { string usertype = Session["USERTYPE"].ToString(); if (usertype.Equals("ADMIN")) { Response.Redirect("Admin/AdminHome.aspx"); } else if (usertype.Equals("Customer") || usertype.Equals("Vendor") || usertype.Equals("Both")) { Response.Redirect("Users/UserHome.aspx"); } } else { Session["USERTYPE"] = cookies["USERTYPE"].Value; Session["USERID"] = cookies["USERID"].Value; string usertype = Session["USERTYPE"].ToString(); if (usertype.Equals("ADMIN")) { Response.Redirect("Admin/AdminHome.aspx"); } else if (usertype.Equals("Customer") || usertype.Equals("Vendor") || usertype.Equals("Both")) { Response.Redirect("Users/UserHome.aspx"); } } } else { if (Session["USERTYPE"] != null) { string usertype = Session["USERTYPE"].ToString(); if (usertype.Equals("ADMIN")) { Response.Redirect("Admin/AdminHome.aspx"); } else if (usertype.Equals("Customer") || usertype.Equals("Vendor") || usertype.Equals("Both")) { Response.Redirect("Users/UserHome.aspx"); } } } BindRptrCatogery(); } protected void BindRptrCatogery() { DataTable dt = BussinessLogic.getCategories(); rptrCatogery.DataSource = dt; rptrCatogery.DataBind(); } }
using System; using System.Collections; namespace Tasks { public class UQueue { ////////////////////////////////////////////////// // Q operations ////////////////////////////////////////////////// public void Enqueue(object el) { lst.Add(el); } public object Dequeue() { var res = Peek(); lst.RemoveAt(0); return res; } public void Clear() { lst.Clear(); } public object Peek() { if (lst.Count == 0) { throw new InvalidOperationException(); } return lst[0]; } ////////////////////////////////////////////////// // Data members ////////////////////////////////////////////////// private ArrayList lst = new ArrayList(); public int Count { get { return lst.Count; } } ////////////////////////////////////////////////// // Misc ////////////////////////////////////////////////// public override string ToString() { return "Front [" + string.Join(" ,", lst.ToArray()) + "] Rear"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ERP_Palmeiras_LA.Models; using ERP_Palmeiras_LA.Models.Facade; using ERP_Palmeiras_LA.Core; namespace ERP_Palmeiras_LA.Controllers { public class EquipamentosClinicaController : BaseController { private LogisticaAbastecimento facade = LogisticaAbastecimento.GetInstance(); public ActionResult Index() { IEnumerable<EquipamentoClinica> equipamentos = facade.BuscarEquipamentosClinica(); if (equipamentos == null) equipamentos = new List<EquipamentoClinica>(); ViewBag.equipamentos = equipamentos; return View(); } public ActionResult Quebrados() { IEnumerable<EquipamentoClinica> equipamentos = facade.BuscarEquipamentosClinica(StatusEquipamento.QUEBRADO); if (equipamentos == null) equipamentos = new List<EquipamentoClinica>(); ViewBag.equipamentos = equipamentos; return View("Index"); } public ActionResult Funcionando() { IEnumerable<EquipamentoClinica> equipamentos = facade.BuscarEquipamentosClinica(StatusEquipamento.FUNCIONANDO); if (equipamentos == null) equipamentos = new List<EquipamentoClinica>(); ViewBag.equipamentos = equipamentos; return View("Index"); } public ActionResult RegistrarDefeito(int id) { EquipamentoClinica eq = facade.BuscarEquipamentoClinica(id); if (eq.Status == StatusEquipamento.FUNCIONANDO) { eq.Status = StatusEquipamento.QUEBRADO; facade.AlterarEquipamentoClinica(eq); // TODO: Criar Pendencia de Manutencao!! } return RedirectToAction("Quebrados"); } public ActionResult Excluir(int id) { facade.ExcluirEquipamentoClinica(id); return RedirectToAction("Index"); } } }
using FileDataService.Adapter; using System.Linq; namespace FileDataService.Service { public class FileService : IFileService { private readonly IFileDataTarget fileDataTarget; private readonly FileDetailsClient _fileDetailsClient; public FileService(FileDetailsClient fileDetailsClient) { fileDataTarget = new DefaultFileDataAdapter(); _fileDetailsClient = fileDetailsClient; } public string GetFileMetaData(string requiredFunctionality, string filePath) { string fileMetaData = null; if (!string.IsNullOrEmpty(requiredFunctionality) && !string.IsNullOrEmpty(filePath)) { // Get global functionality list string[] fileSizes = GetFileSizeInput(); string[] fileVersions = GetFileVersionInput(); // check file version or size if (fileVersions.Any(requiredFunctionality.Equals)) { fileMetaData = _fileDetailsClient.Version(filePath); } else if (fileSizes.Any(requiredFunctionality.Equals)) { fileMetaData = _fileDetailsClient.Size(filePath).ToString(); } } return fileMetaData; } private string[] GetFileSizeInput() => fileDataTarget.GetFileSizeInput(); private string[] GetFileVersionInput() => fileDataTarget.GetFileVersionInput(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PowerString.Data { public class EntityData<T> where T:class { public PowerStringEntities CreateContext() { PowerStringEntities context = new PowerStringEntities(); context.Database.Log = PrintSQL; context.Configuration.ProxyCreationEnabled = false; return context; } private static void PrintSQL(string sql) { Console.WriteLine(sql); } public List<T> Select() { using (var context = CreateContext()) { return context.Set<T>().ToList(); } } public int Count() { using(var context = CreateContext()) { return context.Set<T>().Count(); } } } }
/* * Copyright 2014 Technische Universitšt Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using KaVE.Commons.Utils; namespace KaVE.VS.FeedbackGenerator.Interactivity { public class Confirmation : Notification { public bool Confirmed { get; set; } protected bool Equals(Confirmation other) { return base.Equals(other) && Confirmed.Equals(other.Confirmed); } public override bool Equals(object obj) { return this.Equals(obj, Equals); } public override int GetHashCode() { unchecked { return (base.GetHashCode()*397) ^ Confirmed.GetHashCode(); } } public override string ToString() { return string.Format("[{0}, Confirmed: {1}]", base.ToString(), Confirmed); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerMovement : MonoBehaviour { public float speed; public float jumpforce; public float jumpRaycastDistance; public bool OnGround; public GameObject objectToRotate; private bool rotating; private Rigidbody rb; float elapsedTime; float shift; private void Start() { rb = GetComponent<Rigidbody>(); elapsedTime = 0; shift = 0; } private void Update() { Jump(); } private void FixedUpdate() { Move(); elapsedTime += Time.deltaTime; if(elapsedTime >= 15 && shift == 0) { GravShiftLeft(); elapsedTime = 0; shift = 1; } if (elapsedTime >= 15 && shift == 1) { GravShiftUp(); elapsedTime = 0; shift = 2; } if (elapsedTime >= 15 && shift == 2) { GravShiftRight(); elapsedTime = 0; shift = 3; } if (elapsedTime >= 15 && shift == 3) { GravShiftDown(); elapsedTime = 0; shift = 0; } } private void Move() { float hAxis = Input.GetAxisRaw("Horizontal"); float vAxis = Input.GetAxisRaw("Vertical"); Vector3 movement = new Vector3(hAxis, 0, vAxis) * speed * Time.fixedDeltaTime; Vector3 newPosition = rb.position + rb.transform.TransformDirection(movement); rb.MovePosition(newPosition); } private void Jump() { if (Input.GetKeyDown(KeyCode.Space) && OnGround == true && shift == 0) { rb.velocity = new Vector3(0f, 15f, 0f); OnGround = false; } if (Input.GetKeyDown(KeyCode.Space) && OnGround == true && shift == 1) { rb.velocity = new Vector3(-15f, 0f, 0f); OnGround = false; } if (Input.GetKeyDown(KeyCode.Space) && OnGround == true && shift == 2) { rb.velocity = new Vector3(0f, -15f, 0f); OnGround = false; } if (Input.GetKeyDown(KeyCode.Space) && OnGround == true && shift == 3) { rb.velocity = new Vector3(15f, 0f, 0f); OnGround = false; } } void OnCollisionEnter(Collision other) { OnGround = true; } private void GravShiftUp() { GetComponent<ConstantForce>().force = new Vector3(0, 9.81f, 0); StartRotation(); } private void GravShiftDown() { GetComponent<ConstantForce>().force = new Vector3(0, -9.81f, 0); StartRotation(); } private void GravShiftLeft() { GetComponent<ConstantForce>().force = new Vector3(9.81f, 0, 0); StartRotation(); } private void GravShiftRight() { GetComponent<ConstantForce>().force = new Vector3(-9.81f, 0, 0); StartRotation(); } private IEnumerator Rotate(Vector3 angles, float duration) { rotating = true; Quaternion startRotation = objectToRotate.transform.rotation; Quaternion endRotation = Quaternion.Euler(angles) * startRotation; for (float t = 0; t < duration; t += Time.deltaTime) { objectToRotate.transform.rotation = Quaternion.Lerp(startRotation, endRotation, t / duration); yield return null; } objectToRotate.transform.rotation = endRotation; rotating = false; } public void StartRotation() { if (!rotating) StartCoroutine(Rotate(new Vector3(0, 0, 90), 1)); } }
using System; namespace Ex13 { class Program { static void Main(string[] args) { Console.WriteLine("Output"); Console.WriteLine("fizzbuzz"); for(int i=1;i<=50;i++) { if (i%3==0) { Console.WriteLine("fizz"); } if(i%5==0) { Console.WriteLine("buzz"); } if(i%5==0 & i%3==0) { Console.WriteLine("fizzbuzz"); } if(!(i%3==0) & !(i % 5 == 0)) { Console.WriteLine(i); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace online_knjizara.EntityModels { public class KorisnickiNalozi { [Key] public int KorisnickiNalog_ID { get; set; } public string KorisnickoIme { get; set; } public string Lozinka { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Content_Manegement.Test.Exceptions { public class EmailNotFoundException:Exception { public string Messages = " Email Not Found "; public EmailNotFoundException(string message) { Messages = message; } } }
using System; using System.Linq; class Program { static void Main() { var inputList = Console.ReadLine().Split().ToList(); var nums = Console.ReadLine().Split().Select(int.Parse).ToList(); Console.WriteLine(inputList.Take(nums[0]).Skip(nums[1]).Where(x => x == nums[2].ToString()).Any() ? "YES!" : "NO!"); } }
using System; using UnityEngine; namespace RO.Config { public static class NavMeshArea { public const int MASK_ALL = -1; public static readonly int NOT_WALKABLE = NavMesh.GetAreaFromName("Not Walkable"); public static int CalcMask(params int[] areas) { int num = 0; for (int i = 0; i < areas.Length; i++) { int num2 = areas[i]; num |= 1 << num2; } return num; } } }
using System; using UnityEngine; public class GameManager : MonoBehaviour{ [SerializeField] private int _scoreToWin; [SerializeField] private int _currScore; [SerializeField] public bool _gamePaused; public static GameManager _instance; private void Awake(){ _instance = this; } private void Start(){ Time.timeScale = 1.0f; } private void Update(){ InputListener(); } private void InputListener(){ if(Input.GetButtonDown("Cancel")) TogglePauseGame(); } public void TogglePauseGame(){ _gamePaused = !_gamePaused; Time.timeScale = _gamePaused ? 0.0f : 1.0f; Cursor.lockState = _gamePaused ? CursorLockMode.None : CursorLockMode.Locked; GameUIController._instance.TogglePauseMenu(_gamePaused); } public void AddScore(int score){ _currScore += score; GameUIController._instance.UpdateScoreText(_currScore); if (_currScore >= _scoreToWin) HandleWin(); } private void HandleWin(){ GameUIController._instance.SetEndGameScreen(true, _currScore); HandleEnd(); } public void HandleLoss(){ GameUIController._instance.SetEndGameScreen(false, _currScore); HandleEnd(); } public void HandleEnd(){ Time.timeScale = 0.0f; _gamePaused = true; Cursor.lockState = CursorLockMode.None; } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ namespace NopSolutions.NopCommerce.DataAccess.Directory { /// <summary> /// Acts as a base class for deriving custom country provider /// </summary> [DBProviderSectionName("nopDataProviders/CountryProvider")] public abstract partial class DBCountryProvider : BaseDBProvider { #region Methods /// <summary> /// Deletes a country /// </summary> /// <param name="CountryID">Country identifier</param> public abstract void DeleteCountry(int CountryID); /// <summary> /// Gets all countries /// </summary> /// <returns>Country collection</returns> public abstract DBCountryCollection GetAllCountries(bool showHidden); /// <summary> /// Gets all countries that allow registration /// </summary> /// <returns>Country collection</returns> public abstract DBCountryCollection GetAllCountriesForRegistration(bool showHidden); /// <summary> /// Gets all countries that allow billing /// </summary> /// <returns>Country collection</returns> public abstract DBCountryCollection GetAllCountriesForBilling(bool showHidden); /// <summary> /// Gets all countries that allow shipping /// </summary> /// <returns>Country collection</returns> public abstract DBCountryCollection GetAllCountriesForShipping(bool showHidden); /// <summary> /// Gets a country /// </summary> /// <param name="CountryID">Country identifier</param> /// <returns>Country</returns> public abstract DBCountry GetCountryByID(int CountryID); /// <summary> /// Gets a country by two letter ISO code /// </summary> /// <param name="TwoLetterISOCode">Country two letter ISO code</param> /// <returns>Country</returns> public abstract DBCountry GetCountryByTwoLetterISOCode(string TwoLetterISOCode); /// <summary> /// Gets a country by three letter ISO code /// </summary> /// <param name="ThreeLetterISOCode">Country three letter ISO code</param> /// <returns>Country</returns> public abstract DBCountry GetCountryByThreeLetterISOCode(string ThreeLetterISOCode); /// <summary> /// Inserts a country /// </summary> /// <param name="Name">The name</param> /// <param name="AllowsRegistration">A value indicating whether registration is allowed to this country</param> /// <param name="AllowsBilling">A value indicating whether billing is allowed to this country</param> /// <param name="AllowsShipping">A value indicating whether shipping is allowed to this country</param> /// <param name="TwoLetterISOCode">The two letter ISO code</param> /// <param name="ThreeLetterISOCode">The three letter ISO code</param> /// <param name="NumericISOCode">The numeric ISO code</param> /// <param name="Published">A value indicating whether the entity is published</param> /// <param name="DisplayOrder">The display order</param> /// <returns>Country</returns> public abstract DBCountry InsertCountry(string Name, bool AllowsRegistration, bool AllowsBilling, bool AllowsShipping, string TwoLetterISOCode, string ThreeLetterISOCode, int NumericISOCode, bool Published, int DisplayOrder); /// <summary> /// Updates the country /// </summary> /// <param name="CountryID">The country identifier</param> /// <param name="Name">The name</param> /// <param name="AllowsRegistration">A value indicating whether registration is allowed to this country</param> /// <param name="AllowsBilling">A value indicating whether billing is allowed to this country</param> /// <param name="AllowsShipping">A value indicating whether shipping is allowed to this country</param> /// <param name="TwoLetterISOCode">The two letter ISO code</param> /// <param name="ThreeLetterISOCode">The three letter ISO code</param> /// <param name="NumericISOCode">The numeric ISO code</param> /// <param name="Published">A value indicating whether the entity is published</param> /// <param name="DisplayOrder">The display order</param> /// <returns>Country</returns> public abstract DBCountry UpdateCountry(int CountryID, string Name, bool AllowsRegistration, bool AllowsBilling, bool AllowsShipping, string TwoLetterISOCode, string ThreeLetterISOCode, int NumericISOCode, bool Published, int DisplayOrder); #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextRefresher : MonoBehaviour { [SerializeField] private GameManager gameManager; [SerializeField] private Text scoreText; [SerializeField] private Text movesText; [SerializeField] private Text previousResultText; [SerializeField] private Text bestRecordText; public void RefreshScore() { scoreText.text = "Score: " + gameManager.Score.ToString(); } public void RefreshMoves() { movesText.text = "Moves: " + gameManager.Moves.ToString(); } public void RefreshPlayerStats() { previousResultText.text = "Previous Score: \n" + gameManager.Score.ToString(); bestRecordText.text = "Best Record: \n" + PlayerPrefs.GetInt("Best Record").ToString(); } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using CatalogBooks.Properties; namespace CatalogBooks { public partial class FormMain : Form { /// <summary> /// Объект для работы с базой данных /// </summary> private readonly BaseContext _db; /// <summary> /// Показывает, активировалась ли форма /// </summary> private bool _activeForm; /// <summary> /// Объекты для храниния исходных данных таблиц /// </summary> private List<ListViewItem> _listBook, _listAuthor; /// <summary> /// Конструктор класса /// </summary> public FormMain() { InitializeComponent(); _db = new BaseContext(); } /// <summary> /// Заполнение списка книг /// </summary> private void FillListViewBooks() { _listBook = new List<ListViewItem>(); listViewBooks.Items.Clear(); foreach (Book item in _db.Books) { ListViewItem listItem = new ListViewItem(item.BookId.ToString()); string authors = ""; var authorCollection = _db.Books.Where(book => book.BookId == item.BookId).SelectMany(book => book.Authors); foreach (Author author in authorCollection) authors += String.Format("{0}. {1}; ", author.FirstName[0], author.LastName); string name = item.Name; if (name.Length > 50) name = name.Substring(0, 50) + "..."; listItem.SubItems.AddRange(new[] { name, item.Year.ToString(), authors }); _listBook.Add(listItem); } listViewBooks.Items.AddRange(_listBook.ToArray()); listViewBooks.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listViewBooks.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.HeaderSize); } /// <summary> /// Заполнение списка авторов /// </summary> private void FillListViewAuthors() { _listAuthor = new List<ListViewItem>(); listViewAuthors.Items.Clear(); foreach (Author item in _db.Authors) { ListViewItem listItem = new ListViewItem(item.AuthorID.ToString()); int bookCount = _db.Authors.Where(author => author.AuthorID == item.AuthorID).SelectMany(author => author.Books).Count(); listItem.SubItems.AddRange(new [] { item.LastName, item.FirstName, bookCount.ToString() }); _listAuthor.Add(listItem); } listViewAuthors.Items.AddRange(_listAuthor.ToArray()); listViewAuthors.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent); listViewAuthors.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize); } private void ScanFiles(object sender, EventArgs e) { if (!(sender is ToolStripMenuItem) && Settings.Default.AutoScan) new FormBooksDetected().ShowDialog(); if (sender is ToolStripMenuItem) new FormBooksDetected().ShowDialog(); FillListViewBooks(); FillListViewAuthors(); } private void настройкиToolStripMenuItem_Click(object sender, EventArgs e) { new FormSettings().ShowDialog(); } private void выходToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void showFormDBMenuItem_Click(object sender, EventArgs e) { new FormDataBase((sender as ToolStripMenuItem).Text).ShowDialog(); FillListViewBooks(); FillListViewAuthors(); } private void listViewBooks_DoubleClick(object sender, EventArgs e) { if (listViewBooks.SelectedItems.Count > 0) { string path = _db.Books.Find(int.Parse(listViewBooks.SelectedItems[0].SubItems[0].Text)).Path; if (File.Exists(path)) Process.Start(path); else MessageBox.Show(String.Format("Файл по указанному пути не найден: {0}.", path), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void listViewAuthors_MouseDoubleClick(object sender, MouseEventArgs e) { if (listViewAuthors.SelectedItems.Count > 0 && _activeForm) { FormAuthorBooks formAuthorBooks = new FormAuthorBooks(int.Parse(listViewAuthors.SelectedItems[0].SubItems[0].Text)); int x = listViewBooks.PointToScreen(Point.Empty).X + e.X; int y = listViewBooks.PointToScreen(Point.Empty).Y + e.Y; formAuthorBooks.DesktopLocation = new Point(x, y); _activeForm = false; formAuthorBooks.Show(); } } private void listViewAuthors_MouseClick(object sender, MouseEventArgs e) { _activeForm = true; } private void toolStripTextBoxFilter_TextChanged(object sender, EventArgs e) { listViewBooks.Items.Clear(); listViewAuthors.Items.Clear(); if (toolStripTextBoxFilter.Text != "") { string search = toolStripTextBoxFilter.Text.ToLower(); listViewBooks.Items.AddRange(_listBook.Where(x => x.SubItems[1].ToString().ToLower().Contains(search)).ToArray()); listViewAuthors.Items.AddRange(_listAuthor.Where(x => x.SubItems[1].ToString().ToLower().Contains(search) || x.SubItems[2].ToString().ToLower().Contains(search)).ToArray()); } else { listViewBooks.Items.AddRange(_listBook.ToArray()); listViewAuthors.Items.AddRange(_listAuthor.ToArray()); } } } }
using Contoso.XPlatform.ViewModels.DetailForm; using Contoso.XPlatform.ViewModels.EditForm; using Contoso.XPlatform.ViewModels.ListPage; using Contoso.XPlatform.ViewModels.ReadOnlys; using Contoso.XPlatform.ViewModels.SearchPage; using Contoso.XPlatform.ViewModels.TextPage; using Contoso.XPlatform.ViewModels.Validatables; using Contoso.XPlatform.Views; using Contoso.XPlatform.Views.Factories; using System; namespace Microsoft.Extensions.DependencyInjection { internal static class ViewServices { internal static IServiceCollection AddViews(this IServiceCollection services) { return services .AddTransient<ExtendedSplashView>() .AddTransient<MainPageView>() .AddTransient<Func<IValidatable, ChildFormArrayPageCS>> ( provider => validatable => new ChildFormArrayPageCS ( validatable ) ) .AddTransient<Func<IValidatable, ChildFormPageCS>> ( provider => validatable => new ChildFormPageCS ( validatable ) ) .AddTransient<Func<DetailFormViewModelBase, DetailFormViewCS>> ( provider => viewModel => new DetailFormViewCS ( viewModel ) ) .AddTransient<Func<EditFormViewModelBase, EditFormViewCS>> ( provider => viewModel => new EditFormViewCS ( viewModel ) ) .AddTransient<Func<ListPageViewModelBase, ListPageViewCS>> ( provider => viewModel => new ListPageViewCS ( viewModel ) ) .AddTransient<Func<IValidatable, MultiSelectPageCS>> ( provider => validatable => new MultiSelectPageCS ( validatable ) ) .AddTransient<Func<IReadOnly, ReadOnlyChildFormArrayPageCS>> ( provider => readOnly => new ReadOnlyChildFormArrayPageCS ( readOnly ) ) .AddTransient<Func<IReadOnly, ReadOnlyChildFormPageCS>> ( provider => readOnly => new ReadOnlyChildFormPageCS ( readOnly ) ) .AddTransient<Func<IReadOnly, ReadOnlyMultiSelectPageCS>> ( provider => readOnly => new ReadOnlyMultiSelectPageCS ( readOnly ) ) .AddTransient<Func<SearchPageViewModelBase, SearchPageViewCS>> ( provider => viewModel => new SearchPageViewCS ( viewModel ) ) .AddTransient<Func<TextPageViewModel, TextPageViewCS>> ( provider => viewModel => new TextPageViewCS ( viewModel ) ) .AddViewFactories(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace DataUploads.DataModels { public class EmpInterest { #region Member variables string _compcode, _Empno, _EmpName, _uptodate, _YearCode; decimal _OWNINTT, _VOLINTT, _COMPINTT; bool _tDeleteRecords = false; public bool TDeleteRecords { get { return _tDeleteRecords; } set { _tDeleteRecords = value; } } private SqlCommand cmd; private SqlConnection lConnect; private connection cn; private SqlDataReader reader; private SqlDataAdapter adp; public string YearCode { get { return _YearCode; } set { _YearCode = value; } } public string Uptodate { get { return _uptodate; } set { _uptodate = value; } } public decimal COMPINTT { get { return _COMPINTT; } set { _COMPINTT = value; } } public decimal VOLINTT { get { return _VOLINTT; } set { _VOLINTT = value; } } public decimal OWNINTT { get { return _OWNINTT; } set { _OWNINTT = value; } } public string EmpName { get { return _EmpName; } set { _EmpName = value; } } public string Empno { get { return _Empno; } set { _Empno = value; } } public string Compcode { get { return _compcode; } set { _compcode = value; } } #endregion public EmpInterest() { cn = new connection(); lConnect = cn.OpenConnetion(); cmd = new SqlCommand("", lConnect); cmd.CommandType = CommandType.StoredProcedure; } public bool InsertEmpInterest() { try { DataTable dtSlab = new DataTable(); cmd = new SqlCommand("", lConnect); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "InsertEmpInterest"; cmd.Parameters.AddWithValue("@compcode", this.Compcode); cmd.Parameters.AddWithValue("@Empno", this.Empno); cmd.Parameters.AddWithValue("@EmpName", this.EmpName); cmd.Parameters.AddWithValue("@OWNINTT", this.OWNINTT); cmd.Parameters.AddWithValue("@VOLINTT", this.VOLINTT); cmd.Parameters.AddWithValue("@COMPINTT", this.COMPINTT); cmd.Parameters.AddWithValue("@uptodate", Convert.ToDateTime(this.Uptodate)); cmd.Parameters.AddWithValue("@YearCode", this.YearCode); cmd.Parameters.AddWithValue("@tDeleteRecords", this._tDeleteRecords); cmd.CommandTimeout = 1000000000; int iResult = cmd.ExecuteNonQuery(); if (iResult != -1) return true; return false; } catch (Exception ex) { return false; } finally { cn.CloseConnection(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ghost { private int blood=1000; private float activityRange = 50f; private Vector3 defoultPosition=Vector3.zero; private float fightRange = 10f; private float moveSpeed = 2f; private bool isFightStatus = false; public float ActivityRange { get { return activityRange; } set { activityRange = value; } } public Vector3 DefoultPosition { get { return defoultPosition; } set { defoultPosition = value; } } public float FightRange { get { return fightRange; } set { fightRange = value; } } public int Blood { get { return blood; } set { blood = value; } } public float MoveSpeed { get { return moveSpeed; } set { moveSpeed = value; } } public bool IsFightStatus { get { return isFightStatus; } set { isFightStatus = value; } } public Ghost(int b,float ar,Vector3 dp,float fr,float ms,bool ifs) { blood = b; activityRange = ar; defoultPosition = dp; fightRange = fr; moveSpeed = ms; isFightStatus = ifs; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; ///<summary> /// Script Manager: Denver /// Description: Handles the functionality of the bomb. /// Date Modified: 8/11/2018 ///</summary> [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(SphereCollider))] public class BombActor : MonoBehaviour { [Header("Bomb")] [Tooltip("How much damage will be dealt to all active enemies.")] [SerializeField] private int m_nBombDamage; [Tooltip("How much score will be awarded for each bullet destroyed.")] [SerializeField] private int m_nBulletScore; [Tooltip("Maximum bomb range.")] [SerializeField] private float m_fMaximumRange; [Tooltip("Time bomb lasts.")] [SerializeField] private float m_fDuration; [Tooltip("Starting distance.")] [SerializeField] [Range(1f, float.MaxValue)] private float m_fStartRange; [Header("Camera Shake")] [Tooltip("Magnitude of shake.")] [SerializeField] private float m_fShakeMagnitude; [Tooltip("Roughness of shake.")] [SerializeField] private float m_fShakeRoughness; [Tooltip("Fade in time of shake.")] [SerializeField] private float m_fShakeFadeIn; [Tooltip("Fade out time of shake.")] [SerializeField] private float m_fShakeFadeOut; [Header("Slow Down Time")] [Tooltip("By how much do you want to slow down time.")] [SerializeField] [Range(0.0001f, 1)] private float m_fTimeMagnitude; [Tooltip("How long the effect will take place in seconds.")] [SerializeField] private float m_fTimeDuration; [HideInInspector] public bool m_bIsExploding; private float m_fCurrentTime; private float m_fChangeInValue; private float m_fCurrentRange; private float m_fOldRange; private CameraActor m_camera; private MeshRenderer m_renderer; private SphereCollider m_collider; void Start() { // get components m_renderer = GetComponent<MeshRenderer>(); m_collider = GetComponent<SphereCollider>(); // initialise components m_renderer.enabled = false; m_collider.enabled = false; // initialise easing function variables m_fCurrentTime = 0f; m_fChangeInValue = 0f; m_fCurrentRange = m_fStartRange; m_fOldRange = 0f; // calculate scaled slow down time duration m_fTimeDuration *= m_fTimeMagnitude; } void FixedUpdate() { // if bomb should blow up if (m_bIsExploding) { // enable renderer and collider m_renderer.enabled = true; m_collider.enabled = true; // calculate change in value m_fChangeInValue = m_fCurrentRange - m_fOldRange; m_fCurrentTime += Time.deltaTime; // calcualte current range using easing function m_fCurrentRange = EaseOutExpo(m_fCurrentTime, m_fStartRange, m_fChangeInValue, m_fDuration); // Clamp range m_fCurrentRange = Mathf.Clamp(m_fCurrentRange, m_fStartRange, m_fMaximumRange); // display range visually using bomb effect transform.localScale = new Vector3(m_fCurrentRange, transform.localScale.y, m_fCurrentRange); } } float EaseOutExpo(float t, float b, float c, float d) { // calculate new range using easing function return c * (-Mathf.Pow(2, -10 * t / d) + 1) + b; } public void StartBomb() { m_bIsExploding = true; // invoke stop bomb Invoke("StopBomb", m_fDuration); // shake camera CameraActor cameraActor = GameObject.FindObjectOfType<CameraActor>(); cameraActor.ShakeCamera(m_fShakeMagnitude, m_fShakeRoughness, m_fShakeFadeIn, m_fShakeFadeOut); // slow down time StartCoroutine(SlowDownTime()); } void StopBomb() { // set blow up to false m_bIsExploding = false; // disable components m_renderer.enabled = false; m_collider.enabled = false; // reset easing function variables m_fCurrentTime = 0f; m_fChangeInValue = 0f; m_fCurrentRange = m_fStartRange; m_fOldRange = 0f; // reset bomb effect transform.localScale = new Vector3(1, transform.localScale.y, 1); Destroy(gameObject, 1f); } IEnumerator SlowDownTime() { // set time scale Time.timeScale = m_fTimeMagnitude; // scale fixedDeltaTime Time.fixedDeltaTime = 0.02f * Time.timeScale; yield return new WaitForSeconds(m_fTimeDuration); // reset Time.timeScale = 1f; Time.fixedDeltaTime = 0.02f; } void OnTriggerEnter(Collider other) { // check that other is an EnemyBullet if (other.tag == "EnemyBullet" && other.gameObject.GetComponent<EnemySpellProjectile>().m_eBulletType != eBulletType.BEAM) { ScoreManager.Instance.DropScorePickup(m_nBulletScore, other.gameObject.transform); Destroy(other.gameObject); } } void OnTriggerStay(Collider other) { // check that other is an Enemy if (other.tag == "Enemy") { other.gameObject.GetComponent<EnemyActor>().TakeDamage(m_nBombDamage); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pitstop { public class LinesMaskBehaviour : MonoBehaviour { [SerializeField] CrystalAltarRecuperation crystalAltar = default; [SerializeField] float propSpeed = 1; [SerializeField] float maxSize = 2.15f; [SerializeField] float minSize = 0.25f; float t; float currentSize; bool switchDone = false; private void Start() { t = maxSize; currentSize = maxSize; StartCoroutine(BeamTowardsCrystalAltar()); } private void Update() { transform.localScale = new Vector3(currentSize, currentSize, currentSize); if (crystalAltar.triggerOnceCheck && !switchDone) { Reset(minSize); StopCoroutine(BeamTowardsCrystalAltar()); StartCoroutine(BeamTowardsExitDoor()); switchDone = true; } } private void Reset(float floatForReset) { transform.localScale = Vector3.one * floatForReset; t = 0; currentSize = floatForReset; } IEnumerator BeamTowardsCrystalAltar() { t = 0; while (t < propSpeed) { t += Time.deltaTime; currentSize = Mathf.Lerp((maxSize+currentSize*2)/3, minSize, t / propSpeed); yield return null; } Reset(maxSize); if (!switchDone) { StartCoroutine(BeamTowardsCrystalAltar()); } } IEnumerator BeamTowardsExitDoor() { t = 0; while (t < propSpeed) { t += Time.deltaTime; currentSize = Mathf.Lerp(minSize, maxSize, t / propSpeed); yield return null; } Reset(minSize); StartCoroutine(BeamTowardsExitDoor()); } } }
using System; using System.Data; using System.Collections.Generic; using Maticsoft.Common; using PDTech.OA.Model; namespace PDTech.OA.BLL { /// <summary> /// 岗位职责 /// </summary> public partial class DUTY_RESPONSIBILITY { private readonly PDTech.OA.DAL.DUTY_RESPONSIBILITY dal = new PDTech.OA.DAL.DUTY_RESPONSIBILITY(); public DUTY_RESPONSIBILITY() { } #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(decimal DUTY_RESPONSIBILITY_ID) { return dal.Exists(DUTY_RESPONSIBILITY_ID); } /// <summary> /// 增加一条数据 /// </summary> public bool Add(PDTech.OA.Model.DUTY_RESPONSIBILITY model) { return dal.Add(model); } /// <summary> /// 更新一条数据 /// </summary> public bool Update(PDTech.OA.Model.DUTY_RESPONSIBILITY model) { return dal.Update(model); } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(decimal DUTY_RESPONSIBILITY_ID) { return dal.Delete(DUTY_RESPONSIBILITY_ID); } /// <summary> /// 删除一条数据 /// </summary> public bool DeleteList(string DUTY_RESPONSIBILITY_IDlist) { return dal.DeleteList(DUTY_RESPONSIBILITY_IDlist); } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.DUTY_RESPONSIBILITY GetModel(decimal DUTY_RESPONSIBILITY_ID) { return dal.GetModel(DUTY_RESPONSIBILITY_ID); } /// <summary> /// 得到一个对象实体,从缓存中 /// </summary> public PDTech.OA.Model.DUTY_RESPONSIBILITY GetModelByCache(decimal DUTY_RESPONSIBILITY_ID) { string CacheKey = "DUTY_RESPONSIBILITYModel-" + DUTY_RESPONSIBILITY_ID; object objModel = Maticsoft.Common.DataCache.GetCache(CacheKey); if (objModel == null) { try { objModel = dal.GetModel(DUTY_RESPONSIBILITY_ID); if (objModel != null) { int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache"); Maticsoft.Common.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero); } } catch { } } return (PDTech.OA.Model.DUTY_RESPONSIBILITY)objModel; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { return dal.GetList(strWhere); } /// <summary> /// 获得数据列表 /// </summary> public List<PDTech.OA.Model.DUTY_RESPONSIBILITY> GetModelList(string strWhere) { DataSet ds = dal.GetList(strWhere); return DataTableToList(ds.Tables[0]); } /// <summary> /// 获得数据列表 /// </summary> public List<PDTech.OA.Model.DUTY_RESPONSIBILITY> DataTableToList(DataTable dt) { List<PDTech.OA.Model.DUTY_RESPONSIBILITY> modelList = new List<PDTech.OA.Model.DUTY_RESPONSIBILITY>(); int rowsCount = dt.Rows.Count; if (rowsCount > 0) { PDTech.OA.Model.DUTY_RESPONSIBILITY model; for (int n = 0; n < rowsCount; n++) { model = dal.DataRowToModel(dt.Rows[n]); if (model != null) { modelList.Add(model); } } } return modelList; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetAllList() { return GetList(""); } /// <summary> /// 分页获取数据列表 /// </summary> public int GetRecordCount(string strWhere) { return dal.GetRecordCount(strWhere); } #endregion BasicMethod #region ExtensionMethod /// <summary> /// 查询岗位职责(当前用户) /// </summary> /// <param name="uId">用户ID</param> /// <returns>返回岗位职责</returns> public string GetResponsibility(string uId) { return dal.GetResponsibility(uId); } /// <summary> /// 查询岗位职责(所有) /// </summary> /// <param name="strWhere">查询条件</param> /// <param name="currentPage">当前页面</param> /// <param name="pageSize">每页条数</param> /// <param name="totalNum">总条数</param> /// <returns>返回所有岗位职责</returns> public IList<Model.RESPONSIBILITY> GetAllResponsibility(string strWhere, string currentPage, string pageSize, out int totalNum) { return dal.GetAllResponsibility(strWhere, currentPage, pageSize, out totalNum); } /// <summary> /// 查询部门单位 /// </summary> /// <returns>部门单位</returns> public DataTable GetDepartment() { return dal.GetDepartment(); } /// <summary> /// 查询部门列表 /// </summary> /// <returns>返回部门列表</returns> public IList<Model.DEPARTMENT_NAME> GetDepartmentName() { return dal.GetDepartmentName(); } /// <summary> /// 查询岗位人员(正常使用状态) /// </summary> /// <returns>岗位人员</returns> public DataTable GetPerson() { return dal.GetPerson(); } /// <summary> /// 查询岗位人员(正常使用状态) /// </summary> /// <param name="strName">姓名</param> /// <returns>岗位人员</returns> public DataTable GetPerson(string strName) { return dal.GetPerson(strName); } #endregion ExtensionMethod } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using PESWeb.Friends.Interface; using PESWeb.Friends.Presenter; namespace PESWeb.Friends { public partial class ConfirmFriendshipRequest : System.Web.UI.Page, IConfirmFriendshipRequest { private ConfirmFriendshipRequestPresenter _presenter; protected void Page_Load(object sender, EventArgs e) { _presenter = new ConfirmFriendshipRequestPresenter(); _presenter.Init(this); } protected void lbLogin_Click(object sender, EventArgs e) { _presenter.LoginClick(); } protected void lbCreateAccount_Click(object sender, EventArgs e) { _presenter.RegisterClick(); } public void LoadDisplay(string FriendInvitationKey, Int32 AccountID, string AccountFirstName, string AccountLastName, string SiteName) { lblFullName.Text = AccountFirstName + " " + AccountLastName; lblSiteName1.Text = SiteName; lblSiteName2.Text = SiteName; imgProfileAvatar.ImageUrl = "~/images/ProfileAvatar/ProfileImage.aspx?AccountID=" + AccountID.ToString(); } public void ShowMessage(string Message) { lblMessage.Text = Message; } public void ShowConfirmPanel(bool value) { pnlConfirm.Visible = value; pnlError.Visible = !value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class ProceduralGenerationAlgorithm { public static HashSet<Vector2Int> SimpleRandomWalk(Vector2Int startPos, int walkLength) { HashSet<Vector2Int> path = new HashSet<Vector2Int>(); path.Add(startPos); var previousPos = startPos; for (int i = 0; i < walkLength; i++) { var newPos = previousPos + Direction2D.getCardinalDirection(); path.Add(newPos); previousPos = newPos; } return path; } public static List<Vector2Int> RandomWalkCorridor(Vector2Int startPos, int corridorLength) { List<Vector2Int> corridor = new List<Vector2Int>(); var direction = Direction2D.getCardinalDirection(); var currentPos = startPos; for (int i = 0; i < corridorLength; i++) { currentPos += direction; corridor.Add(currentPos); } return corridor; } public static List<BoundsInt> BinaeySpacePartitioning(BoundsInt spaceToSplit, int minWidth, int minHeight) { Queue<BoundsInt> roomQueue = new Queue<BoundsInt>(); List<BoundsInt> roomList = new List<BoundsInt>(); roomQueue.Enqueue(spaceToSplit); while (roomQueue.Count > 0) { var room = roomQueue.Dequeue(); if(room.size.y >= minHeight && room.size.x >= minWidth) { if (UnityEngine.Random.value > 0.5f) { if(room.size.y >= minHeight * 2) { SplitHorizontally(minHeight, roomQueue, room); }else if(room.size.x >= minWidth * 2) { SplitVertically(minWidth, roomQueue, room); }else if(room.size.x >= minWidth && room.size.y > minHeight) { roomList.Add(room); } } else { if (room.size.x >= minWidth * 2) { SplitVertically(minWidth, roomQueue, room); } else if (room.size.y >= minHeight * 2) { SplitHorizontally(minHeight, roomQueue, room); } else if (room.size.x >= minWidth && room.size.y > minHeight) { roomList.Add(room); } } } } return roomList; } private static void SplitVertically(int minWidth, Queue<BoundsInt> roomQueue, BoundsInt room) { var xSplit = Random.Range(1, room.size.x); BoundsInt room1 = new BoundsInt(room.min, new Vector3Int(xSplit, room.size.y, room.size.y)); BoundsInt room2 = new BoundsInt(new Vector3Int(room.min.x + xSplit, room.min.y, room.min.z), new Vector3Int(room.size.x - xSplit, room.size.y, room.size.z)); roomQueue.Enqueue(room1); roomQueue.Enqueue(room2); } private static void SplitHorizontally(int minHeight, Queue<BoundsInt> roomQueue, BoundsInt room) { var ySplit = Random.Range(1, room.size.y); BoundsInt room1 = new BoundsInt(room.min, new Vector3Int(room.size.x, ySplit, room.size.z)); BoundsInt room2 = new BoundsInt(new Vector3Int(room.min.x, room.min.y + ySplit, room.min.z), new Vector3Int(room.size.x, room.size.y - ySplit, room.size.z)); roomQueue.Enqueue(room1); roomQueue.Enqueue(room2); } } public static class Direction2D { public static List<Vector2Int> CardinalDirectionsList = new List<Vector2Int> { new Vector2Int(0,1), //Up new Vector2Int(1,0), // RIGHT new Vector2Int(0,-1), //DOWN new Vector2Int(-1,0) //LEFT }; public static List<Vector2Int> DiagonalDirectionsList = new List<Vector2Int> { new Vector2Int(1,1), //UP-RIGHT new Vector2Int(1,-1), // RIGHT-DOWN new Vector2Int(-1,-1), //DOWN-LEFT new Vector2Int(-1,1) //LEFT-UP }; public static List<Vector2Int> eightDirectionList = new List<Vector2Int> { new Vector2Int(0,1), //Up new Vector2Int(1,1), //UP-RIGHT new Vector2Int(1,0), // RIGHT new Vector2Int(1,-1), // RIGHT-DOWN new Vector2Int(0,-1), //DOWN new Vector2Int(-1,-1), //DOWN-LEFT new Vector2Int(-1,0), //LEFT new Vector2Int(-1,1) //LEFT-UP }; public static Vector2Int getCardinalDirection() { return CardinalDirectionsList[Random.Range(0, CardinalDirectionsList.Count)]; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CapaAccesoServicios { public class ServiciosReserva { ProxyReserva.ServicioReservaClient objServicioReserva = new ProxyReserva.ServicioReservaClient(); public Boolean InsertarReserva(ProxyReserva.ReservaBE objReserva) { return objServicioReserva.InsertarReserva(objReserva); } public Boolean ActualizarReserva(ProxyReserva.ReservaBE objReserva) { return objServicioReserva.ActualizarReserva(objReserva); } public List<ProxyReserva.ReservaBE> DevuelveReservasCliente(byte IdCliente) { return objServicioReserva.DevuelveReservasCliente(IdCliente); } public ProxyReserva.ReservaBE DevuelveReservaIdAuxiliar(short idAux) { return objServicioReserva.DevuelveReservaIdAuxiliar(idAux); } } }
using Contoso.Forms.Configuration; using Contoso.Forms.Configuration.Bindings; using Contoso.Forms.Configuration.DataForm; using Contoso.XPlatform.Constants; using System; using System.Collections.Generic; using System.Linq; using Xamarin.Forms; namespace Contoso.XPlatform.Utils { internal static class LayoutHelpers { public static T AddBinding<T>(this T bindable, BindableProperty targetProperty, BindingBase binding) where T : BindableObject { bindable.SetBinding ( targetProperty, binding ); return bindable; } public static T SetAutomationPropertiesName<T>(this T bindable, string propertyName) where T : BindableObject { AutomationProperties.SetName(bindable, propertyName); return bindable; } public static T AssignDynamicResource<T>(this T bindable, BindableProperty property, string key) where T : Element { bindable.SetDynamicResource ( property, key ); return bindable; } public static T SetGridColumn<T>(this T bindable, int column) where T : BindableObject { Grid.SetColumn(bindable, column); return bindable; } public static T SetGridColumnSpan<T>(this T bindable, int columnSpan) where T : BindableObject { Grid.SetColumnSpan(bindable, columnSpan); return bindable; } public static T SetGridRow<T>(this T bindable, int row) where T : BindableObject { Grid.SetRow(bindable, row); return bindable; } public static T SetGridRowSpan<T>(this T bindable, int rowSpan) where T : BindableObject { Grid.SetRowSpan(bindable, rowSpan); return bindable; } public static T SetDataTemplateSelector<T>(this T bindable, DataTemplateSelector dataTemplateSelector) where T : BindableObject { BindableLayout.SetItemTemplateSelector(bindable, dataTemplateSelector); return bindable; } public static T SetAbsoluteLayoutBounds<T>(this T bindable, Rect rectangle) where T : BindableObject { AbsoluteLayout.SetLayoutBounds(bindable, rectangle); return bindable; } public static T SetAbsoluteLayoutFlags<T>(this T bindable, AbsoluteLayoutFlags absoluteLayoutFlags) where T : BindableObject { AbsoluteLayout.SetLayoutFlags(bindable, absoluteLayoutFlags); return bindable; } public static Style GetStaticStyleResource(string styleName) { if (Application.Current == null) throw new ArgumentException($"{nameof(Application.Current)}: {{E118848A-872E-48DA-A6D4-A1E5A0D57070}}"); if (Application.Current.Resources.TryGetValue(styleName, out object resource) && resource is Style style) return style; throw new ArgumentException($"{styleName}: DF65BD5C-E8A5-409C-A736-F6DF1B29D5E7"); } internal static DataTemplate GetCollectionViewItemTemplate(string templateName, Dictionary<string, ItemBindingDescriptor> bindings) { return templateName switch { TemplateNames.HeaderTextDetailTemplate => new DataTemplate ( () => new Grid { Style = GetStaticStyleResource(StyleKeys.HeaderTextDetailListItemStyle), Children = { new StackLayout { Style = GetStaticStyleResource(StyleKeys.HeaderTextDetailItemLayout), Children = { CollectionCellIViewHelpers.GetCollectionViewItemTemplateItem ( bindings[BindingNames.Header].TemplateName, bindings[BindingNames.Header].Property, FontAttributes.Bold ), CollectionCellIViewHelpers.GetCollectionViewItemTemplateItem ( bindings[BindingNames.Text].TemplateName, bindings[BindingNames.Text].Property, FontAttributes.None ), CollectionCellIViewHelpers.GetCollectionViewItemTemplateItem ( bindings[BindingNames.Detail].TemplateName, bindings[BindingNames.Detail].Property, FontAttributes.Italic ) } } } } ), TemplateNames.TextDetailTemplate => new DataTemplate ( () => new Grid { Style = GetStaticStyleResource(StyleKeys.TextDetailListItemStyle), Children = { new StackLayout { Style = GetStaticStyleResource(StyleKeys.TextDetailItemLayout), Children = { CollectionCellIViewHelpers.GetCollectionViewItemTemplateItem ( bindings[BindingNames.Text].TemplateName, bindings[BindingNames.Text].Property, FontAttributes.Bold ), CollectionCellIViewHelpers.GetCollectionViewItemTemplateItem ( bindings[BindingNames.Detail].TemplateName, bindings[BindingNames.Detail].Property, FontAttributes.Italic ) } } } } ), _ => throw new ArgumentException ( $"{nameof(templateName)}: 83C55FEE-9A93-45D3-A972-2335BA0F16AE" ), }; } private struct TemplateNames { public const string TextDetailTemplate = "TextDetailTemplate"; public const string HeaderTextDetailTemplate = "HeaderTextDetailTemplate"; } private struct BindingNames { public const string Header = "Header"; public const string Text = "Text"; public const string Detail = "Detail"; } internal static void AddToolBarItems(IList<ToolbarItem> toolbarItems, ICollection<CommandButtonDescriptor> buttons) { foreach (var button in buttons) toolbarItems.Add(BuildToolbarItem(button)); } static ToolbarItem BuildToolbarItem(CommandButtonDescriptor button) => new ToolbarItem { AutomationId = button.ShortString, //Text = button.LongString, IconImageSource = new FontImageSource { FontFamily = EditFormViewHelpers.GetFontAwesomeFontFamily(), Glyph = FontAwesomeIcons.Solid[button.ButtonIcon], Size = 20 }, Order = ToolbarItemOrder.Primary, Priority = 0, CommandParameter = button } .AddBinding(MenuItem.CommandProperty, new Binding(button.Command)) .SetAutomationPropertiesName(button.ShortString); /// <summary> /// For inline child forms the key includes a period which does not work for binding dictionaries. /// i.e. new Binding(@"[Property.ChildProperty].Value") does not work. /// We're using new Binding(@"[Property_ChildProperty].Value") instead /// </summary> /// <param name="key"></param> /// <returns></returns> internal static string ToBindingDictionaryKey(this string key) => key.Replace(".", "_"); /// <summary> /// If every form field has a FormGroupBoxSettingsDescriptor parent then we don't need to create a /// default group box. Otherwise we create a default group box using IFormGroupSettings.Title as the /// group header. /// </summary> /// <param name="descriptors"></param> /// <returns></returns> internal static bool ShouldCreateDefaultControlGroupBox(this List<FormItemSettingsDescriptor> descriptors) { return descriptors.Aggregate(false, DoAggregate); static bool DoAggregate(bool shouldAdd, FormItemSettingsDescriptor next) { if (shouldAdd) return shouldAdd; if (next is FormGroupSettingsDescriptor inlineFormGroupSettingsDescriptor && inlineFormGroupSettingsDescriptor.FormGroupTemplate.TemplateName == FromGroupTemplateNames.InlineFormGroupTemplate) { if (inlineFormGroupSettingsDescriptor.FieldSettings.Aggregate(false, DoAggregate)) return true; } else if ((next is FormGroupBoxSettingsDescriptor) == false) { return true; } return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using XPowerAPI.Models; using XPowerAPI.Repository.Collections; using XPowerAPI.Logging; using MySql.Data.MySqlClient; using Microsoft.AspNetCore.Mvc; using XPowerAPI.Models.Params; using System.Data.Common; namespace XPowerAPI.Repository { public class SessionKeyRepository : IRepository<SessionKey, SessionKeyParams>, IDisposable { bool isDisposed = false; MySqlConnection con; ILogger logger; public SessionKeyRepository( [FromServices]MySqlConnection con, [FromServices]ILogger logger) { this.logger = logger; this.con = con; } ~SessionKeyRepository() { Dispose(false); } public int Count() { throw new NotImplementedException(); } public Task<int> CountAsync() { throw new NotImplementedException(); } public void Delete(object id) { throw new NotImplementedException(); } public void Delete(SessionKeyParams entity) { throw new NotImplementedException(); } public void Delete(params SessionKeyParams[] entities) { throw new NotImplementedException(); } public void Delete(IEnumerable<SessionKeyParams> entities) { throw new NotImplementedException(); } public Task DeleteAsync(object id) { throw new NotImplementedException(); } public Task DeleteAsync(SessionKeyParams entity) { throw new NotImplementedException(); } public Task DeleteAsync(params SessionKeyParams[] entities) { throw new NotImplementedException(); } public Task DeleteAsync(IEnumerable<SessionKeyParams> entities) { throw new NotImplementedException(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (isDisposed) return; if (disposing) { con.Dispose(); logger.Dispose(); } } public bool Exists(object key) { throw new NotImplementedException(); } public Task<bool> ExistsAsync(object key) { throw new NotImplementedException(); } public SessionKey Find(params object[] keyValues) { if (keyValues[0] == null) throw new ArgumentNullException(nameof(keyValues)); string val = keyValues[0].ToString(); if (string.IsNullOrEmpty(val)) throw new ArgumentNullException(nameof(keyValues)); SessionKey key = null; MySqlCommand cmd = new MySqlCommand(); //check whether the value is an email if (val.Contains('@', StringComparison.OrdinalIgnoreCase)) { cmd = new MySqlCommand("GetFullSessionKeyByEmail", con) { CommandType = System.Data.CommandType.StoredProcedure }; cmd.Parameters.Add("email", MySqlDbType.VarChar); cmd.Parameters["email"].Value = val; cmd.Parameters["email"].Direction = System.Data.ParameterDirection.Input; } //or a uuid else if (val.Length == 36) { cmd = new MySqlCommand("GetFullSessionKeyById", con) { CommandType = System.Data.CommandType.StoredProcedure }; cmd.Parameters.Add("keyid", MySqlDbType.VarChar); cmd.Parameters["keyid"].Value = val; cmd.Parameters["keyid"].Direction = System.Data.ParameterDirection.Input; } try { con.Open(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { key = new SessionKey( reader.GetString( reader.GetOrdinal("SessionKeyId")), reader.GetString( reader.GetOrdinal("ApiKeyId")), reader.GetDateTime( reader.GetOrdinal("ExpirationDate"))); } } catch (Exception) { throw; } finally { con.Close(); cmd.Dispose(); } return key; } public async Task<SessionKey> FindAsync(params object[] keyValues) { if (keyValues[0] == null) throw new ArgumentNullException(nameof(keyValues)); string val = keyValues[0].ToString(); if (string.IsNullOrEmpty(val)) throw new ArgumentNullException(nameof(keyValues)); SessionKey key = null; MySqlCommand cmd = new MySqlCommand(); //check whether the value is an email if (val.Contains('@', StringComparison.OrdinalIgnoreCase)) { cmd = new MySqlCommand("GetFullSessionKeyByEmail", con) { CommandType = System.Data.CommandType.StoredProcedure }; cmd.Parameters.Add("email", MySqlDbType.VarChar); cmd.Parameters["email"].Value = val; cmd.Parameters["email"].Direction = System.Data.ParameterDirection.Input; } //or a uuid else if (val.Length == 36) { cmd = new MySqlCommand("GetFullSessionKeyById", con) { CommandType = System.Data.CommandType.StoredProcedure }; cmd.Parameters.Add("keyid", MySqlDbType.VarChar); cmd.Parameters["keyid"].Value = val; cmd.Parameters["keyid"].Direction = System.Data.ParameterDirection.Input; } try { con.Open(); DbDataReader reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); while (reader.Read()) { key = new SessionKey( reader.GetString( reader.GetOrdinal("SessionKeyId")), reader.GetString( reader.GetOrdinal("ApiKeyId")), reader.GetDateTime( reader.GetOrdinal("ExpirationDate"))); } } catch (Exception) { throw; } finally { await con.CloseAsync().ConfigureAwait(false); cmd.Dispose(); } return key; } public async Task<SessionKey> FindAsync(object[] keyValues, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await FindAsync(keyValues).ConfigureAwait(false); } public IEnumerable<SessionKey> FromSql(string sql, params object[] parameters) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql)); if (parameters == null || parameters.Length == 0) throw new ArgumentNullException(nameof(parameters)); MySqlCommand cmd = new MySqlCommand(sql, con) { CommandType = (System.Data.CommandType)parameters[0] }; for (int i = 1; i < parameters.Length; i++) { cmd.Parameters.Add((MySqlParameter)parameters[i]); } List<SessionKey> keys = null; try { keys = new List<SessionKey>(); con.Open(); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { keys.Add( new SessionKey( reader.GetString(reader.GetOrdinal("SessionKeyId")), reader.GetDateTime(reader.GetOrdinal("ExpirationDate")) )); } } catch (Exception) { throw; } finally { con.Close(); cmd.Dispose(); } return keys; } public async Task<IEnumerable<SessionKey>> FromSqlAsync(string sql, params object[] parameters) { if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql)); if (parameters == null || parameters.Length == 0) throw new ArgumentNullException(nameof(parameters)); MySqlCommand cmd = new MySqlCommand(sql, con) { CommandType = (System.Data.CommandType)parameters[0] }; for (int i = 1; i < parameters.Length; i++) { cmd.Parameters.Add((MySqlParameter)parameters[i]); } List<SessionKey> keys = null; try { keys = new List<SessionKey>(); con.Open(); DbDataReader reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); while (reader.Read()) { keys.Add( new SessionKey( reader.GetString(reader.GetOrdinal("SessionKeyId")), reader.GetDateTime(reader.GetOrdinal("ExpirationDate")) )); } } catch (Exception) { throw; } finally { await con.CloseAsync().ConfigureAwait(false); cmd.Dispose(); } return keys; } public IEnumerable<SessionKey> GetAll() { throw new NotImplementedException(); } public Task<IEnumerable<SessionKey>> GetAllAsync() { throw new NotImplementedException(); } public IPagedList<SessionKey> GetPagedList(object[] keyValues, int pageNumber = 0, int pageSize = 20) { throw new NotImplementedException(); } public Task<IPagedList<SessionKey>> GetPagedListAsync(object[] keyValues, int pageNumber = 0, int pageSize = 20, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } //fix out params public SessionKey Insert(SessionKeyParams entity) { //check that the email is non null if (entity == null || entity.Email.Length == 0) throw new ArgumentNullException(nameof(entity)); //create command MySqlCommand cmd = new MySqlCommand("CreateSessionKey", con) { CommandType = System.Data.CommandType.StoredProcedure }; //add parameters cmd.Parameters.Add("email", MySqlDbType.VarChar); cmd.Parameters.Add("sessionkey", MySqlDbType.VarChar); cmd.Parameters.Add("expirationdate", MySqlDbType.DateTime); cmd.Parameters["email"].Value = entity.Email; cmd.Parameters["email"].Direction = System.Data.ParameterDirection.Input; cmd.Parameters["sessionkey"].Direction = System.Data.ParameterDirection.Output; cmd.Parameters["expirationdate"].Direction = System.Data.ParameterDirection.Output; //create temporary object SessionKey ses = null; try { //create key con.Open(); int res = cmd.ExecuteNonQuery(); if (res != 0) { //fill object if any rows were affected ses = new SessionKey( (string)cmd.Parameters["sessionkey"].Value, (DateTime)cmd.Parameters["expirationdate"].Value); } } catch (Exception) { throw; } finally { con.Close(); cmd.Dispose(); } return ses; } //fix out params public void Insert(params SessionKeyParams[] entities) { //check that the email is non null if (entities == null || entities.Length == 0) throw new ArgumentNullException(nameof(entities)); //create command MySqlCommand cmd = new MySqlCommand("CreateSessionKey", con) { CommandType = System.Data.CommandType.StoredProcedure }; //add parameters cmd.Parameters.Add("email", MySqlDbType.VarChar); cmd.Parameters.Add("sessionkey", MySqlDbType.VarChar); cmd.Parameters.Add("expirationdate", MySqlDbType.DateTime); cmd.Parameters["sessionkey"].Direction = System.Data.ParameterDirection.Output; cmd.Parameters["expirationdate"].Direction = System.Data.ParameterDirection.Output; try { //open connection con.Open(); for (int i = 0; i < entities.Length; i++) { //check each entity email if (entities[i].Email.Length == 0) throw new ArgumentNullException(nameof(entities)); //change parameters cmd.Parameters["email"].Value = entities[i].Email; cmd.Parameters["email"].Direction = System.Data.ParameterDirection.Input; //execute query cmd.ExecuteNonQuery(); } } catch (Exception) { throw; } finally { con.Close(); cmd.Dispose(); } } //fix out params public void Insert(IEnumerable<SessionKeyParams> entities) { Insert(entities); } public async Task<SessionKey> InsertAsync(SessionKeyParams entity) { //check that the email is non null if (entity == null || entity.Email.Length == 0) throw new ArgumentNullException(nameof(entity)); //create command MySqlCommand cmd = new MySqlCommand("CreateSessionKey", con) { CommandType = System.Data.CommandType.StoredProcedure }; //add parameters cmd.Parameters.Add("email", MySqlDbType.VarChar); cmd.Parameters.Add("sessionkey", MySqlDbType.VarChar); cmd.Parameters.Add("expirationdate", MySqlDbType.DateTime); cmd.Parameters["email"].Value = entity.Email; cmd.Parameters["email"].Direction = System.Data.ParameterDirection.Input; cmd.Parameters["sessionkey"].Direction = System.Data.ParameterDirection.Output; cmd.Parameters["expirationdate"].Direction = System.Data.ParameterDirection.Output; //create temporary object SessionKey ses = null; try { //create key using (CancellationTokenSource tkn = new CancellationTokenSource(5000)) { //open connection await con.OpenAsync(tkn.Token).ConfigureAwait(true); //if unable to connect to the db, cancel the request if (tkn.IsCancellationRequested) return null; } DbDataReader reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); while (reader.Read()) { ses = new SessionKey( reader.GetString( reader.GetOrdinal("SessionKeyId")), reader.GetDateTime( reader.GetOrdinal("ExpirationDate"))); } //await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); /*if (cmd.Parameters["sessionkey"] != null) throw new ArgumentNullException(cmd.Parameters["sessionkey"].ToString()); if (cmd.Parameters["expirationdate"] != null) throw new ArgumentNullException(cmd.Parameters["expirationdate"].ToString()); if (cmd.Parameters["sessionkey"] != null) { //fill object if any rows were affected ses = new SessionKey( (string)cmd.Parameters["sessionkey"].Value, (DateTime)cmd.Parameters["expirationdate"].Value); }*/ } catch (Exception) { throw; } finally { await con.CloseAsync().ConfigureAwait(false); cmd.Dispose(); } return ses; } //fix out params public async Task InsertAsync(params SessionKeyParams[] entities) { //check that the email is non null if (entities == null || entities.Length == 0) throw new ArgumentNullException(nameof(entities)); //create command MySqlCommand cmd = new MySqlCommand("CreateSessionKey", con) { CommandType = System.Data.CommandType.StoredProcedure }; //add parameters cmd.Parameters.Add("email", MySqlDbType.VarChar); cmd.Parameters.Add("sessionkey", MySqlDbType.VarChar); cmd.Parameters.Add("expirationdate", MySqlDbType.DateTime); cmd.Parameters["sessionkey"].Direction = System.Data.ParameterDirection.Output; cmd.Parameters["expirationdate"].Direction = System.Data.ParameterDirection.Output; try { using (CancellationTokenSource tkn = new CancellationTokenSource(5000)) { //open connection await con.OpenAsync(tkn.Token).ConfigureAwait(true); //if unable to connect to the db, cancel the request if (tkn.IsCancellationRequested) return; } for (int i = 0; i < entities.Length; i++) { //check each entity email if (entities[i].Email.Length == 0) throw new ArgumentNullException(nameof(entities)); //change parameters cmd.Parameters["email"].Value = entities[i].Email; cmd.Parameters["email"].Direction = System.Data.ParameterDirection.Input; //execute query await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); } } catch (Exception) { throw; } finally { await con.CloseAsync().ConfigureAwait(false); cmd.Dispose(); } } //fix out params public async Task InsertAsync(IEnumerable<SessionKeyParams> entities, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); await InsertAsync(entities).ConfigureAwait(false); } public SessionKey Update(SessionKeyParams entity) { throw new NotImplementedException(); } public void Update(params SessionKeyParams[] entities) { throw new NotImplementedException(); } public void Update(IEnumerable<SessionKeyParams> entities) { throw new NotImplementedException(); } public Task<SessionKey> UpdateAsync(SessionKeyParams entity) { throw new NotImplementedException(); } public Task UpdateAsync(params SessionKeyParams[] entities) { throw new NotImplementedException(); } public Task UpdateAsync(IEnumerable<SessionKeyParams> entities) { throw new NotImplementedException(); } } }
using System; using System.Linq; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ninject; using Webcorp.lib.onedcut; using GAF; using GAF.Extensions; using System.Diagnostics; using ReactiveUI; using System.Threading.Tasks; using Webcorp.Model; using Webcorp.Model.Quotation; namespace Webcorp.oned.tests { /// <summary> /// Description résumée pour UnitTest3 /// </summary> [TestClass] public class UnitTest3 { public UnitTest3() { // // TODO: ajoutez ici la logique du constructeur // } private TestContext testContextInstance; /// <summary> ///Obtient ou définit le contexte de test qui fournit ///des informations sur la série de tests active, ainsi que ses fonctionnalités. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Attributs de tests supplémentaires // // Vous pouvez utiliser les attributs supplémentaires suivants lorsque vous écrivez vos tests : // // Utilisez ClassInitialize pour exécuter du code avant d'exécuter le premier test de la classe // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Utilisez ClassCleanup pour exécuter du code une fois que tous les tests d'une classe ont été exécutés // [ClassCleanup()] // public static void MyClassCleanup() { } // // Utilisez TestInitialize pour exécuter du code avant d'exécuter chaque test // [TestInitialize()] // public void MyTestInitialize() { } // // Utilisez TestCleanup pour exécuter du code après que chaque test a été exécuté // [TestCleanup()] // public void MyTestCleanup() { } // #endregion [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { } [TestMethod] public void TestCuttingPopulation() { var kernel = new StandardKernel(new OneDCutModule()); kernel.Bind<IPopulation>().To<InitialBeamPopulationWithNoError>().InSingletonScope(); kernel.Bind(typeof(IEntityProvider<,>)).To(typeof(EntityProvider<,>)).InSingletonScope(); kernel.Bind(typeof(IEntityProviderInitializable<Article, string>)).To(typeof(BeamInitializer)); var population = kernel.Get<IPopulation>(); Assert.IsTrue(population.CuttingStock.Count() == 126); Assert.IsTrue(population.CuttingStock.Length == 4125); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Must have same length")] public void TestCuttingPopulationError() { var kernel = new StandardKernel(new OneDCutModule()); kernel.Bind<IPopulation>().To<InitialBeamPopulationWithError>().InSingletonScope(); var population = kernel.Get<IPopulation>(); } [TestMethod] public void TestCuttingBeamWithNinject() { var kernel = new StandardKernel(new OneDCutModule()); kernel.Bind<IPopulation>().To<InitialBeamPopulation>().InSingletonScope(); kernel.Bind(typeof(IEntityProvider<,>)).To(typeof(EntityProvider<,>)).InSingletonScope(); kernel.Bind(typeof(IEntityProviderInitializable<Article, string>)).To(typeof(BeamInitializer)); ISolver solver = kernel.Get<ISolver>(); Assert.IsNotNull(solver); solver.Beams = kernel.Get<IPopulation>().Beams; solver.Stocks = kernel.Get<IPopulation>().CuttingStock; solver.Beam = kernel.Get<IPopulation>().Beam; solver.OnSolved += Solver_OnSolved; solver.Solve(); } [TestMethod] public async Task TestCuttingBeamWithNinjectAsync() { var kernel = new StandardKernel(new OneDCutModule()); kernel.Bind<IPopulation>().To<InitialBeamPopulation>().InSingletonScope(); kernel.Bind(typeof(IEntityProvider<,>)).To(typeof(EntityProvider<,>)).InSingletonScope(); kernel.Bind(typeof(IEntityProviderInitializable<Article, string>)).To(typeof(BeamInitializer)); ISolver solver = kernel.Get<ISolver>(); Assert.IsNotNull(solver); solver.Beams = kernel.Get<IPopulation>().Beams; solver.Stocks = kernel.Get<IPopulation>().CuttingStock; solver.Beam = kernel.Get<IPopulation>().Beam; solver.OnSolved += Solver_OnSolved; await solver.SolveAsync(); } [TestMethod] public void TestCuttingBeamWithNinjectWithBigData() { var kernel = new StandardKernel(new OneDCutModule()); kernel.Bind<IPopulation>().To<InitialBeamBigPopulation>().InSingletonScope(); kernel.Bind(typeof(IEntityProvider<,>)).To(typeof(EntityProvider<,>)).InSingletonScope(); kernel.Bind(typeof(IEntityProviderInitializable<Article, string>)).To(typeof(BeamInitializer)); ISolver solver = kernel.Get<ISolver>(); Assert.IsNotNull(solver); solver.Beams = kernel.Get<IPopulation>().Beams; solver.Stocks = kernel.Get<IPopulation>().CuttingStock; solver.Beam = kernel.Get<IPopulation>().Beam; solver.OnSolved += Solver_OnSolved; solver.Solve(); } [TestMethod] public void TestCuttingBeamRealCase() { var kernel = new StandardKernel(new OneDCutModule()); kernel.Bind<IPopulation>().To<InitialBeamRealPopulation>().InSingletonScope(); kernel.Bind(typeof(IEntityProvider<,>)).To(typeof(EntityProvider<,>)).InSingletonScope(); kernel.Bind(typeof(IEntityProviderInitializable<Article, string>)).To(typeof(BeamInitializer)); ISolver solver = kernel.Get<ISolver>(); Assert.IsNotNull(solver); solver.Beams = kernel.Get<IPopulation>().Beams; solver.Stocks = kernel.Get<IPopulation>().CuttingStock; solver.Beam = kernel.Get<IPopulation>().Beam; solver.OnSolved += Solver_OnSolved; solver.Solve(); } private void Solver_OnSolved(object sender, SolverEventArgs e) { var solver = sender as Solver; Debug.WriteLine("Best solution"); Debug.WriteLine("----------------------------"); Debug.WriteLine("Total To Cut:" + e.TotalToCut); Debug.WriteLine("Total Cut:" + e.TotalCut); Debug.WriteLine("Total Stock:" + e.TotalStock); Debug.WriteLine("Total Cutting Mass:" + e.TotalCuttingMass.ToString("#.00 [kg]")); Debug.WriteLine("Total Cutting Cost:" + e.TotalCuttingCost.ToString("#.00 [euro]")); Debug.WriteLine("Total Waste Length:" + e.TotalWaste); Debug.WriteLine("Total Waste Cost:" + e.TotalWasteCost.ToString("#.00 [euro]")); Debug.WriteLine(string.Format("Percentage Waste {0:P2} ", e.WastePercentage)); Debug.WriteLine("Uncut Stock:" + e.TotalUncut); if (!e.IsStockSuffisant) { Debug.WriteLine("No stock to cut all need"); Debug.WriteLine(e.RestToCut + " rest tot cut"); } DebugCutPlan(e.CutPlan); } private void DebugCutPlan(List<lib.onedcut.CutPlan> cutplan) { Debug.WriteLine("**** Cutting plan ****"); foreach (var cut in cutplan.Where(c=>c.CutLength>0).OrderBy(i => i.StockIndex)) { Debug.WriteLine(cut); } } } public class InitialBeamPopulation : IPopulation, IInitializable { Stocks stocks; Beams beams = new Beams(); public InitialBeamPopulation() { } public ReactiveList<BeamToCut> Beams => beams; public Stocks CuttingStock => stocks; [Inject] public IKernel Kernel { get; set; } Article _beam; public Article Beam => _beam; public void Initialize() { var mpp = Kernel.Get<IEntityProvider<Article, string>>(); _beam = mpp.Find("IPE 220"); _beam.MassCurrency = unite.MassCurrency.Parse("600 euro/tonne"); for (int i = 0; i < 10; i++) { beams.Add(new BeamToCut(3, 5, _beam)); beams.Add(new BeamToCut(5, 1, _beam)); beams.Add(new BeamToCut(5, 2, _beam)); } int[] cuttingStock = new int[] { 20, 5, 105, 150, 30 }; stocks = new Stocks(cuttingStock); } } public class InitialBeamPopulationWithError : IPopulation, IInitializable { public InitialBeamPopulationWithError() { } public Article Beam => null; public ReactiveList<BeamToCut> Beams => null; public Stocks CuttingStock => null; public void Initialize() { int[] cuttingStockCount = new int[] { 1, 1, 1, 1 }; int[] cuttingStockLength = new int[] { 20, 5, 105, 150, 30 }; var stocks = new Stocks(cuttingStockCount, cuttingStockLength); } } public class InitialBeamPopulationWithNoError : IPopulation, IInitializable { public InitialBeamPopulationWithNoError() { } public Article Beam => null; public ReactiveList<BeamToCut> Beams => null; public Stocks CuttingStock { get; private set; } public void Initialize() { int[] cuttingStockCount = new int[] { 10, 8, 7, 1, 100 }; int[] cuttingStockLength = new int[] { 20, 5, 105, 150, 30 }; CuttingStock = new Stocks(cuttingStockLength, cuttingStockCount); } } public class InitialBeamBigPopulation : IPopulation, IInitializable { Stocks stocks; Beams beams = new Beams(); public InitialBeamBigPopulation() { } public ReactiveList<BeamToCut> Beams => beams; public Stocks CuttingStock => stocks; [Inject] public IKernel Kernel { get; set; } Article _beam; public Article Beam => _beam; public void Initialize() { var mpp = Kernel.Get<IEntityProvider<Article, string>>(); _beam = mpp.Find("IPE 80"); _beam.MassCurrency = unite.MassCurrency.Parse("600 euro/tonne"); for (int i = 0; i < 1000; i++) { beams.Add(new BeamToCut(3, 5, _beam)); beams.Add(new BeamToCut(5, 1, _beam)); beams.Add(new BeamToCut(5, 2, _beam)); beams.Add(new BeamToCut(20, 15, _beam)); beams.Add(new BeamToCut(15, 10, _beam)); beams.Add(new BeamToCut(50, 20, _beam)); } int[] cuttingStockCount = new int[] { 100, 200, 80, 1000, 100 }; int[] cuttingStockLength = new int[] { 200, 50, 1050, 1500, 300 }; stocks = new Stocks(cuttingStockLength, cuttingStockCount); } } public class InitialBeamRealPopulation : IPopulation, IInitializable { Stocks stocks; Beams beams = new Beams(); public InitialBeamRealPopulation() { } public ReactiveList<BeamToCut> Beams => beams; public Stocks CuttingStock => stocks; [Inject] public IKernel Kernel { get; set; } Article _beam; public Article Beam => _beam; public void Initialize() { var mpp = Kernel.Get<IEntityProvider<Article, string>>(); _beam = mpp.Find("IPE 80"); _beam.MassCurrency = unite.MassCurrency.Parse("600 euro/tonne"); beams.Add(new BeamToCut(5,4024, _beam)); // beams.Add(new BeamToCut(4,1896, _beam)); //beams.Add(new BeamToCut(2, 4456, _beam)); stocks = new Stocks(6000,100); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using DevExpress.XtraReports.UI; using System.Linq; using DevExpress.Xpo; using prjQLNK.QLNK; namespace prjQLNK { public partial class BcNhanKhau : DevExpress.XtraReports.UI.XtraReport { public string NguoiLap_ = "...................................................................", DiaChi_ = "........................................"; public DateTime NgayLap_ = DateTime.Today; public DateTime NgayTu, NgayDen; public BcNhanKhau(string NguoiLap, DateTime NgayLap, string DiaChi) { InitializeComponent(); if (NguoiLap != "") NguoiLap_ = NguoiLap; if (DiaChi != "") DiaChi_ = DiaChi; NgayLap_ = NgayLap; xrLabel38.Text = DiaChi_ + ", ngày " + NgayLap_.Day + " tháng " + NgayLap_.Month + " năm " + NgayLap_.Year; xrNguoilap.Text = NguoiLap_; } private void BcHoKhau_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e) { var nhankhau_ = (from hk in new XPQuery<HOKHAU>(Session.DefaultSession) join nk in new XPQuery<NHANKHAU>(Session.DefaultSession) on hk.SOHOKHAU equals nk.SOHOKHAU select new { MAKHAISINH = nk.MAKHAISINH, HOTENKHAISINH = nk.HOTENKHAISINH, TENGOIKHAC = nk.TENGOIKHAC, NGAYSINH = nk.NGAYSINH, GIOITINH = nk.GIOITINH == 0 ? "Nam" : nk.GIOITINH == 1 ? "Nữ" : "", DANTOC = nk.DANTOC, TONGIAO = nk.TONGIAO, QUOCTICH = nk.QUOCTICH, SOCMND = nk.SOCMND, NGAYCAP = nk.NGAYCAP.ToString("dd/MM/yyyy"), NOICAP = nk.NOICAP, TRINHDO = nk.TRINHDO, TDCHUYENMON = nk.TDCHUYENMON, NGHENGHIEP = nk.NGHENGHIEP, NOILAMVIEC = nk.NOILAMVIEC, QUANHE = nk.QUANHE, BIETTIENGDANTOC = nk.BIETTIENGDANTOC, TDNGOAINGU = nk.TDNGOAINGU, SOHOKHAU = nk.SOHOKHAU, NOISINH = nk.DC1 + ", xã " + nk.IDXA1 + ", huyện " + nk.IDHUYEN1 + ", tỉnh " + nk.IDTINH1, NGUYENQUAN = nk.DC2 + ", xã " + nk.IDXA2 + ", huyện " + nk.IDHUYEN2 + ", tỉnh " + nk.IDTINH2, NOITHUONGTRU = nk.DC3 + ", xã " + nk.IDXA3 + ", huyện " + nk.IDHUYEN3 + ", tỉnh " + nk.IDTINH3, CHOOHIENHAN = nk.DC4 + ", xã " + nk.IDXA4 + ", huyện " + nk.IDHUYEN4 + ", tỉnh " + nk.IDTINH4, }).ToList(); this.DataSource = nhankhau_.ToList(); } } }
using org.in2bits.MyXls; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary { public class MyXlsHelper { private static HorizontalAlignments horizontalAlignment = HorizontalAlignments.Centered; private static VerticalAlignments verticalAlignment = VerticalAlignments.Centered; private static string fontName = "宋体"; private static ushort titleFontHeight = 14 * 20; private static ushort thFontHeight = 12 * 20; private static ushort tdFontHeight = 12 * 20; private static int minWidth = 20; private static int maxWidth = 40; public delegate void FillExcelTh(Worksheet sheet, XF thXF, ref int row, object others = null); public static void Export(DataTable dt, string title, FillExcelTh FillTh = null, object others = null) { XlsDocument xls = new XlsDocument(); #region 样式 XF titleXF = xls.NewXF(); titleXF.HorizontalAlignment = horizontalAlignment; titleXF.VerticalAlignment = verticalAlignment; titleXF.Font.FontName = fontName; titleXF.Font.Bold = true; titleXF.Font.Height = titleFontHeight; XF thXF = xls.NewXF(); thXF.HorizontalAlignment = horizontalAlignment; thXF.VerticalAlignment = verticalAlignment; thXF.Font.FontName = fontName; thXF.Font.Bold = true; thXF.Font.Height = thFontHeight; XF tdXF = xls.NewXF(); tdXF.HorizontalAlignment = horizontalAlignment; tdXF.VerticalAlignment = verticalAlignment; tdXF.Font.FontName = fontName; tdXF.Font.Bold = false; tdXF.Font.Height = tdFontHeight; #endregion #region 初始化sheet int colCount = dt.Columns.Count; Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1"); ColumnInfo colInfo = new ColumnInfo(xls, sheet); colInfo.ColumnIndexStart = 0; colInfo.ColumnIndexEnd = (ushort)(colCount - 1); int width = 255 / colCount; if (width < minWidth) width = minWidth; if (width > maxWidth) width = maxWidth; colInfo.Width = (ushort)(width * 256); sheet.AddColumnInfo(colInfo); #endregion #region title int row = 1; int col = 1; sheet.Cells.Add(row, col, title, titleXF); sheet.Cells.Merge(row, row, 1, colCount); #endregion #region th row++; if (FillTh == null) { col = 1; foreach (DataColumn item in dt.Columns) { sheet.Cells.Add(row, col++, item.ColumnName, thXF); } } else { FillTh(sheet, thXF, ref row, others); } #endregion #region td foreach (DataRow rowItem in dt.Rows) { row++; col = 1; foreach (DataColumn colItem in dt.Columns) { sheet.Cells.Add(row, col++, rowItem[colItem], tdXF); } } #endregion xls.FileName = title; xls.Save(@"E:\", true); } public static void FillExcelThSample(Worksheet sheet, XF thXF, ref int row, object others = null) { int col = 1; sheet.Cells.Add(row, 1, ((DateTime)others).ToString("时间:yyyy年MM月dd日"), thXF); sheet.Cells.Merge(row, row++, 1, 16); sheet.Cells.Add(row, 1, "城市名称", thXF); sheet.Cells.Merge(row, row + 2, 1, 1); sheet.Cells.Add(row, 2, "监测点位名称", thXF); sheet.Cells.Merge(row, row + 2, 2, 2); sheet.Cells.Add(row, 3, "污染物浓度及空气质量分指数(IAQI)", thXF); sheet.Cells.Merge(row, row++, 3, 16); col = 3; sheet.Cells.Add(row, col, "二氧化硫(SO2)24小时平均", thXF); sheet.Cells.Merge(row, row, col++, col++); sheet.Cells.Add(row, col, "二氧化氮(NO2)24小时平均", thXF); sheet.Cells.Merge(row, row, col++, col++); sheet.Cells.Add(row, col, "颗粒物(粒径小于等于10μm)24小时平均", thXF); sheet.Cells.Merge(row, row, col++, col++); sheet.Cells.Add(row, col, "一氧化碳(CO)24小时平均", thXF); sheet.Cells.Merge(row, row, col++, col++); sheet.Cells.Add(row, col, "臭氧(O3)最大1小时平均", thXF); sheet.Cells.Merge(row, row, col++, col++); sheet.Cells.Add(row, col, "臭氧(O3)最大8小时滑动平均", thXF); sheet.Cells.Merge(row, row, col++, col++); sheet.Cells.Add(row, col, "颗粒物(粒径小于等于2.5μm)24小时平均", thXF); sheet.Cells.Merge(row, row++, col++, col++); col = 3; sheet.Cells.Add(row, col++, "浓度/(μg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); sheet.Cells.Add(row, col++, "浓度/(μg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); sheet.Cells.Add(row, col++, "浓度/(μg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); sheet.Cells.Add(row, col++, "浓度/(mg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); sheet.Cells.Add(row, col++, "浓度/(μg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); sheet.Cells.Add(row, col++, "浓度/(μg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); sheet.Cells.Add(row, col++, "浓度/(μg/m³)", thXF); sheet.Cells.Add(row, col++, "分指数", thXF); } } }
using ProConstructionsManagment.Desktop.Models.Base; namespace ProConstructionsManagment.Desktop.Models { public class Position : BaseModel { public string Name { get; set; } public string JobDescription { get; set; } } }
using UnityEngine; using System.Collections; public class AutoRot : MonoBehaviour { public float rotX = 0; public float rotY = 0; public float rotZ = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.Rotate(rotX, rotY, rotZ); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Vuokranseuranta { public partial class ApartLayout : Form { SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Projects\program-for-tracking-rental\Vuokranseuranta\vuose_db.mdf;Integrated Security=True;Connect Timeout=30"); int cid; public ApartLayout() { InitializeComponent(); con.Open(); SqlCommand command; SqlDataReader dataReader; String sql = ""; sql = "Select name from Condominium"; command = new SqlCommand(sql, con); dataReader = command.ExecuteReader(); while (dataReader.Read()) { comboBox1.Items.Add(dataReader.GetValue(0).ToString()); //cid = Convert.ToInt16(dataReader.GetValue(1)); } dataReader.Close(); command.Dispose(); con.Close(); } private void button1_Click(object sender, EventArgs e) { string message = "Haluatko varmasti lisätä huoneiston?"; string caption = "Error Detected in Input"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; result = MessageBox.Show(message, caption, buttons); if (result == System.Windows.Forms.DialogResult.Yes) { con.Open(); SqlCommand command; String sql = ""; int aid = 0; SqlDataReader dataReader; sql = "SELECT COUNT(aid) FROM Apartment"; command = new SqlCommand(sql, con); dataReader = command.ExecuteReader(); while (dataReader.Read()) { aid = Convert.ToInt32(dataReader.GetValue(0)) + 1; } dataReader.Close(); command.Dispose(); con.Close(); con.Open(); sql = "INSERT INTO Apartment (Aid,apartNro,Cid) VALUES (@a1,@a2,@a3)"; command = new SqlCommand(sql, con); command.Parameters.Add("a1", aid); command.Parameters.Add("a2", textBox1.Text); command.Parameters.Add("a3", cid); command.ExecuteNonQuery(); con.Close(); // Closes the parent form. this.Close(); } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { con.Open(); SqlCommand command; SqlDataReader dataReader; String sql = ""; string test = comboBox1.Text; sql = "Select cid from Condominium WHERE name = @a1"; command = new SqlCommand(sql, con); command.Parameters.Add("a1", test); dataReader = command.ExecuteReader(); while (dataReader.Read()) { cid = Convert.ToInt16(dataReader.GetValue(0)); } dataReader.Close(); command.Dispose(); con.Close(); } private void button2_Click(object sender, EventArgs e) { this.Close(); } } }
using System.Threading.Tasks; using FORUM.BLL.DTO; using FORUM.BLL.Infrastructure; using FORUM.BLL.Services; using FORUM.DAL.Interfaces; using Moq; using NUnit.Framework; namespace FORUM.BLL.UnitTests { [TestFixture] public class UserServiceTests { [Test] public async Task CreateUser_EmailNull_ShouldReturnFalseInOperationDetails() { //Arrange var mock = new Mock<IUnitOfWork>(); UserService userService = new UserService(mock.Object); UserDTO userDto = new UserDTO() { Email = null, Id = "id", Password = "123Qwerty", UserName = "User", Role = "User"}; var expectedOpDet = new OperationDetails(false, "", ""); //Act var actualOpDet = await userService.Create(userDto); //Assert Assert.AreEqual(expectedOpDet.Succeeded, actualOpDet.Succeeded, "True OperationDetails.Succeded result occurred"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Day15 { internal static void part1() { FileInfo input = new FileInfo(Program.dir + "day15.txt"); var stream = input.OpenText(); List<Disk> disks = new List<Disk>(); while (!stream.EndOfStream) { string line = stream.ReadLine(); var s = line.Split(); Disk d = new Disk(int.Parse(s[1][1].ToString()), int.Parse(s[3]), int.Parse(s[11].TrimEnd('.'))); disks.Add(d); } //part2 disks.Add(new Disk(disks.Count + 1, 11, 0)); bool running = true; int time = 0; while (running) { foreach(Disk d in disks) { int t = time; if (d.isGoodPosition(t)) { t++; if(d.disk == disks.Count) { running = false; Console.WriteLine(time); } } else { break; } } time++; } } private static bool testDisks(List<Disk> disks) { var tmp = disks; return testDisks(tmp); } } class Disk { public int disk; public int positions; public int currentPostion; public Disk(int disk, int positions, int currentPosition) { this.disk = disk; this.positions = positions; this.currentPostion = currentPosition; } internal bool isGoodPosition(int time) { return (currentPostion + disk + time) % positions == 0; } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using lianda.Component; namespace lianda.LD90 { /// <summary> /// LD901010 的摘要说明。 /// </summary> public class LD901010 : BasePage { protected System.Web.UI.WebControls.Button be_upd; protected System.Web.UI.WebControls.Button bt_del; protected System.Web.UI.WebControls.TextBox XM; protected System.Web.UI.WebControls.TextBox DH; protected System.Web.UI.WebControls.TextBox ZZ; protected System.Web.UI.WebControls.TextBox BZ; protected System.Web.UI.WebControls.DropDownList ZT; protected System.Web.UI.WebControls.Button BT_RE; protected System.Web.UI.WebControls.Button BT_NEW; protected System.Web.UI.WebControls.TextBox XH; protected System.Web.UI.WebControls.TextBox back; private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 if(!this.IsPostBack) { AttributesAdd(); // 在此处放置用户代码以初始化页面 if (Request.Params["XH"]!=null) { //this.XM.Enabled=false; bt_ask(Request.Params["XH"].ToString().Trim()); this.XH.Text=Request.Params["XH"].ToString().Trim(); } else { this.XM.Enabled=true; } } } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.BT_NEW.Click += new System.EventHandler(this.BT_NEW_Click); this.be_upd.Click += new System.EventHandler(this.be_upd_Click); this.bt_del.Click += new System.EventHandler(this.bt_del_Click); this.BT_RE.Click += new System.EventHandler(this.BT_RE_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion #region 查询 /// <summary> /// /// </summary> /// <param name="bm">安装编码查询</param> private void bt_ask(string bm) { string strSQL; // SQL语句 // 查询数据 strSQL = "select * from J_JSY where XH = @XH ;"; SqlParameter[] prams = { new SqlParameter("@XH",SqlDbType.Decimal) }; prams[0].Value= bm; SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,prams);// //赋值 if(dr.HasRows) { dr.Read(); //编码 姓名 电话 住址 备注 状态 //this.BH.Text=dr["BH"].ToString();//编码 back.Text=dr["XM"].ToString(); this.XM.Text=dr["XM"].ToString();//姓名 this.DH.Text=dr["DH"].ToString();//电话 this.ZZ.Text=dr["ZZ"].ToString(); this.BZ.Text=dr["BZ"].ToString(); this.XH.Text=dr["XH"].ToString(); int n=ZT.Items.IndexOf(this.ZT.Items.FindByValue(dr["ZT"].ToString())); if (n>0) this.ZT.Items[n].Selected =true; } dr.Close(); } #endregion #region 页面控件增加脚本验证 /// <summary> /// 页面控件增加脚本验证 /// </summary> private void AttributesAdd() { this.be_upd.Attributes.Add("onclick","javascript:return confirm('确定增加吗?')"); // 保存 this.bt_del.Attributes.Add("onclick","javascript:return confirm('确定删除吗?')"); // 删除 } #endregion #region 保存 /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void be_upd_Click(object sender, System.EventArgs e) { if( this.XM.Text.Trim()==""||this.XM.Text.Trim().Length<1 ) { this.msgbox("驾驶员姓名不能为空!"); return; } //话 住址 备注 状态 string strSQL; // SQL语句 if (back.Text.Trim()!=null&&back.Text.Length>0&&back.Text!="") { strSQL = "update J_JSY set DH='@DH' ,ZZ='@ZZ',BZ='@BZ',ZT='@ZT' ,XM='@XM' where XH=@XH"; //修改语句 strSQL=strSQL.Replace("@DH",this.DH.Text.Trim()); strSQL=strSQL.Replace("@ZZ",this.ZZ.Text.Trim()); strSQL=strSQL.Replace("@BZ",this.BZ.Text.Trim()); strSQL=strSQL.Replace("@ZT",this.ZT.SelectedValue); strSQL=strSQL.Replace("@XM",this.XM.Text.Trim()); strSQL=strSQL.Replace("@XH",this.XH.Text.Trim()); } else { strSQL = "INSERT INTO J_JSY (XM,DH,ZZ,BZ,ZT) VALUES('@XM','@DH','@ZZ','@BZ','@ZT') ;"; //新增语句 //代码是否存在 string chekDM="SELECT COUNT(*) FROM J_JSY WHERE XM ='@XM'"; chekDM=chekDM.Replace("@XM",this.XM.Text.Trim()); int count=int.Parse(SqlHelper.ExecuteScalar(SqlHelper.CONN_STRING,CommandType.Text,chekDM,null).ToString()) ; if(count>0) //该用户代码已经存在 { this.msgbox("该驾驶员姓名已经存在!请区分!"); return; } strSQL=strSQL.Replace("@DH",this.DH.Text.Trim()); strSQL=strSQL.Replace("@ZZ",this.ZZ.Text.Trim()); strSQL=strSQL.Replace("@BZ",this.BZ.Text.Trim()); strSQL=strSQL.Replace("@ZT",this.ZT.SelectedValue); strSQL=strSQL.Replace("@XM",this.XM.Text.Trim()); //strSQL=strSQL.Replace(@XH,this.XH.Text.Trim()); } //执行语句 出错处理 try { int count = SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.Text,strSQL,null);// //序号 string chekDM="SELECT XH FROM J_JSY WHERE XM ='@XM'"; chekDM=chekDM.Replace("@XM",this.XM.Text.Trim()); count=int.Parse(SqlHelper.ExecuteScalar(SqlHelper.CONN_STRING,CommandType.Text,chekDM,null).ToString()) ; this.XH.Text=count.ToString(); } catch(Exception ex) { this.msgbox(ex.Message+"保存失败!!,检查数据 "); } bt_ask(this.XH.Text.Trim()); this.msgbox("保存成功!"); } #endregion #region 删除 /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void bt_del_Click(object sender, System.EventArgs e) { if( this.XM.Text.Trim()==""||this.XM.Text.Trim().Length<1 ) { this.msgbox("驾驶员姓名不能为空!"); return; } string strSQL; // 删除语句 strSQL = "UPDATE J_JSY SET SC='Y',ZT='00',SCR=@SCR,SCSJ=GETDATE() where XM=@XM"; SqlParameter[] prams = { new SqlParameter("@XM",SqlDbType.VarChar,10), new SqlParameter("@SCR",SqlDbType.VarChar,10) }; prams[0].Value=this.XM.Text.Trim(); prams[1].Value=this.Session["UserName"].ToString(); //执行语句 出错处理 try { int count = SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.Text,strSQL,prams);// } catch(Exception ex) { this.msgbox(ex.Message+"删除失败!!,检查数据 "); return; } this.msgbox("删除成功!"); this.Response.Redirect("LD9010.aspx"); } #endregion private void BT_RE_Click(object sender, System.EventArgs e) { this.Response.Redirect("LD9010.aspx"); } private void BT_NEW_Click(object sender, System.EventArgs e) { this.back.Text=""; this.XM.Text=""; this.ZZ.Text=""; this.BZ.Text=""; this.DH.Text=""; this.XM.Enabled=true; this.XH.Text=""; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using Proyecto_Web.Patrones.FactoryMethod; namespace Proyecto_Web.Controladores { public class ORGANOLEPTICACONTROLADOR { protected ORGANOLEPTICO Mol_Organoleptico = new ORGANOLEPTICO(); public ORGANOLEPTICACONTROLADOR() { Mol_Organoleptico = new ORGANOLEPTICO(); } public DataTable Guardar_Prueba_Organolepticas(ORGANOLEPTICO obj) { return obj.Registrar_Prueba_Organolepticas(obj); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmsChapter1 { public class _1_1_21_FindGCD { /* * GCD -- Euclid's method */ public int FindGCDEuclid(int p, int q, ref string tracker) { if (tracker != null) { tracker += string.Format("p = {0}, q = {1}", p.ToString(), q.ToString()); } if (q == 0) return p; int r = p % q; return FindGCDEuclid(q, r, ref tracker); } } }
using MrHai.Core; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MrHai.Application { [Export(typeof(IMrHaiApplication))] internal class MrHaiApplication : MrHaiService, IMrHaiApplication { } }
namespace ConcurrentLinkedList { public interface IConcurrentLinkedList<T> { Node<T> First { get; } /// <summary> /// Attempts to add the specified value to the <see cref="ConcurrentLinkedList{T}"/>. /// </summary> bool TryAdd(T value); /// <summary> /// Attempts to remove the specified value from the <see cref="ConcurrentLinkedList{T}"/>. /// </summary> bool Remove(T value, out T result); /// <summary> /// Determines whether the <see cref="ConcurrentLinkedList{T}"/> contains the specified key. /// </summary> bool Contains(T value); } }
using System; using System.Linq; using System.Reflection; using UserStorageServices.Notification; using UserStorageServices.Repositories; using UserStorageServices.UserStorage; namespace UserStorageApp { internal class SlaveDomainAction : MarshalByRefObject { public IUserStorageService SlaveService { get; private set; } public INotificationReceiver Receiver { get; private set; } public void Run() { Assembly assembly = Assembly.Load("UserStorageServices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f46a87b3d9a80705"); var slaveServiceType = assembly.ExportedTypes .Where(t => t.GetCustomAttribute<MyApplicationServiceAttribute>() != null) .First(t => t.GetCustomAttribute<MyApplicationServiceAttribute>().ServiceMode == "UserStorageSlave"); var slave = (UserStorageServiceSlave)Activator.CreateInstance( slaveServiceType, new UserMemoryRepository()); Receiver = slave.Receiver; SlaveService = new UserStorageServiceLog(slave); } } }
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; /// <summary> /// This file defines the Soldier class. It is the strong physical, weak 'magic' class. /// </summary> public class Soldier : ICharacterClass { #region Class Data Members private static int hitPoints = 25; private static int techPoints = 10; private static int baseDmg = 6; private static int hpMultiplier = 4; private static int tpMultiplier = 2; private static int baseDmgMultiplier = 4; private static int baseDefense = 10; #endregion #region Class Methods public Soldier() { } #endregion #region Class Properties public int HP { get { return hitPoints; } } public int TP { get { return techPoints; } } public int BaseDMG { get { return baseDmg; } } public int HPMultiplier { get { return hpMultiplier; } } public int TPMultiplier { get { return tpMultiplier; } } public int BaseDMGMultiplier { get { return baseDmgMultiplier; } } public int BaseDefense { get { return baseDefense; } } #endregion }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using WaitingListBot.Data; namespace WaitingListBot.Api { [Route("[controller]")] [ApiController] public class GuildController : ControllerBase { readonly WaitingListDataContext dataContext; public GuildController() { dataContext = new WaitingListDataContext(); } [HttpGet] [Route("List")] public IEnumerable<ulong> List() { return dataContext.GuildData.AsQueryable().Select(x => x.GuildId); } [HttpGet] [Route("{guildId}/List")] public IEnumerable<UserInGuild>? ListPlayers(ulong guildId) { var guildData = dataContext.GetGuild(guildId); List<UserInGuild>? sortedList = guildData?.GetSortedList(); // We dont want to leak this foreach (var item in sortedList!) { item.UserId = 0; item.Guild = null!; } return sortedList; } [HttpGet] [Route("{guildId}/Info")] public GuildInformation? GetGuildInformation(ulong guildId) { var guildData = dataContext.GetGuild(guildId); if (guildData == null) { return null; } return new GuildInformation { Name = guildData.Name, Description = guildData.Description, IconUrl = guildData.IconUrl }; } } }
using HAGVeT.Helper; using System.Collections.Generic; using System.IO; using System.Windows; using Newtonsoft.Json; namespace HAGVeT { /// <summary> /// Interaktionslogik für MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainPage mPage; public MainWindow() { InitializeComponent(); mainpageframe.Content = mPage = new MainPage(); } private void close_click(object sender, RoutedEventArgs e) { Application.Current.Shutdown(); } private void import_click(object sender, RoutedEventArgs e) { } private void openfolder_click(object sender, RoutedEventArgs e) { var path = mPage.chooseDirectory(); mPage.openDirectory(path); } private void new_click(object sender, RoutedEventArgs e) { mPage.createDirectory(); } } }
using UnityEngine; using System.Collections; using System; public class Capture_AreaManager : MonoBehaviour, IGame { // Transform de les posicions on es poden crear areas de captura [SerializeField] private Transform captureAreaParent; private Transform previousArea; public void OnGameSetup() { } public void OnGameStart() { } public void OnRoundSetup() { if (PhotonNetwork.isMasterClient) InstantiateNewRandomCapture(); } public void OnRoundStart() { } public void OnRoundEnd() { if (PhotonNetwork.isMasterClient) RemoveOldArea(); } public void OnGameEnd() { } void RemoveOldArea() { Capture_AreaController currentArea = Component.FindObjectOfType<Capture_AreaController>(); if (currentArea != null) { previousArea = currentArea.transform; PhotonNetwork.Destroy(currentArea.gameObject); } else { Debug.LogError("No area was found when trying to remove old area"); } } void InstantiateNewRandomCapture() { Transform newTransform = getDiferentRandomAreaPosition(previousArea); PhotonNetwork.InstantiateSceneObject("GameMode/Area", newTransform.position, newTransform.rotation, 0, new object[0]); } Transform getDiferentRandomAreaPosition(Transform previousArea) { Transform newCapturePosition; do { newCapturePosition = GetRandomCapturePosition(); } while (previousArea != null && newCapturePosition.position == previousArea.position); return newCapturePosition; } Transform GetRandomCapturePosition() { return captureAreaParent.GetChild(UnityEngine.Random.Range(0, captureAreaParent.childCount)); } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { [Serializable] public class OrderNote { public Guid OrderNoteId; public Guid OrderId; public DateTime NoteDate; public Boolean Internal; public String Note; public String CreatedBy; public Byte? NoteTypeId; } }
namespace _02.ValidateURL { using System; using System.Net; public class Startup { public static void Main() { var url = Console.ReadLine(); var decodeUrl = WebUtility.UrlDecode(url); var parseUrl = new Uri(decodeUrl); if (string.IsNullOrEmpty(parseUrl.Host) && string.IsNullOrEmpty(parseUrl.Host) && string.IsNullOrEmpty(parseUrl.LocalPath)) { Console.WriteLine("Invalid URL"); return; } Console.WriteLine(parseUrl.Scheme); Console.WriteLine(parseUrl.Host); if (parseUrl.Scheme == "http") { Console.WriteLine($"Port: 80"); } else { Console.WriteLine($"Port: 447"); } if (parseUrl.LocalPath.Length > 1) { Console.WriteLine($"Path: {parseUrl.LocalPath}"); } else { Console.WriteLine($"Path: /"); } Console.WriteLine(parseUrl.Query); Console.WriteLine(parseUrl.Fragment); } } }
using ConsoleApplication1.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.Diagnostics.Contracts; namespace ConsoleApplication1.Microsoft.glassdoor { public class ProblemSet1 { public static string ReverseWordsInString(string src) { //we want this >> reverse words >> ew tnaw siht >> reverse >> this want we StringBuilder sb = new StringBuilder(); string[] words = src.Split(' '); foreach (var item in words) { sb.Append(item.Reverse()); } string res = sb.ToString().Reverse().ToString(); return res; } public static string ReverseString(string src) { //window >> wodniw int s = 0; int e = src.Length - 1; char[] chars = src.ToCharArray(); while (s < e) { char tmp = chars[s]; chars[s] = chars[e]; chars[e] = tmp; s++; e--; } return new string(chars); } public static int ParseFromString(string number) { //453 char[] chars = number.ToCharArray(); int res = 0; int zero = (int)'0'; for (int i = 0; i < chars.Length; i++) { if (!char.IsDigit(chars[i])) { throw new FormatException(); } checked { res += ((int)chars[i] - zero) * (int)Math.Pow(10.0, chars.Length - 1 - i); } } return res; } public static string IntToString(int num) { StringBuilder sb = new StringBuilder(); int tracker = 0; int tmp = num; while (tmp > 0) { sb.Append(tmp % 10); tracker++; if (tracker == 3) { tracker = 0; if (tmp / 10 > 0) sb.Append(','); } tmp = tmp / 10; } return new string(sb.ToString().Reverse().ToArray()); } public static int FindFibonacciNumber(int n) { if (n == 1) return 1; if (n == 0) return 1; return FindFibonacciNumber(n - 1) + FindFibonacciNumber(n - 2); } public static List<int> FindFibonacciNumbers(int n) { List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(1); for (int i = 2; i < n; i++) { numbers.Add(numbers[i - 1] + numbers[i - 2]); } return numbers; } public static bool IsIntPalindrom1(int num) { int t = num; int rev = 0; while (t > 0) { rev = rev * 10 + t % 10; t = t / 10; } return rev == num; } public static bool IsIntPalindrom(int num) { return IsIntPalindromRecursive(num, new List<int>(), 0); } public static bool IsIntPalindromRecursive(int num, List<int> numbers, int ind) { if (num == 0) return true; //123321 /* 1 2 3 3 2 1 */ int item = num % 10; int nextind = ind + 1; numbers.Add(item); bool res = IsIntPalindromRecursive(num / 10, numbers, nextind); return res && (item == numbers[numbers.Count - 1 - ind]); } public static SinglyLinkedListNode Reverse(SinglyLinkedListNode head) { SinglyLinkedListNode prev, curr, next; prev = null; curr = head; while (curr != null) { next = curr.Next; curr.Next = prev; prev = curr; curr = next; } return prev; } public static SinglyLinkedListNode ReverseLinkedList(SinglyLinkedListNode head) { SinglyLinkedListNode tmp = head; SinglyLinkedListNode curr, prev; prev = null; while (tmp != null) { curr = new SinglyLinkedListNode() { Value = tmp.Value, Next = prev }; prev = curr; tmp = tmp.Next; } return prev; } public static SinglyLinkedListNode ReverseLinkedList1(SinglyLinkedListNode head) { SinglyLinkedListNode tmp = head; SinglyLinkedListNode curr, prev, next; prev = null; while (tmp != null) { curr = tmp; next = curr.Next; curr.Next = prev; prev = curr; tmp = next; } return prev; } public static LinkedListNodeWithRundomRef CloneLinkedList(LinkedListNodeWithRundomRef head) { Dictionary<LinkedListNodeWithRundomRef, LinkedListNodeWithRundomRef> tbl = new Dictionary<LinkedListNodeWithRundomRef, LinkedListNodeWithRundomRef>(); LinkedListNodeWithRundomRef tmp = head; while (tmp != null) { LinkedListNodeWithRundomRef t = new LinkedListNodeWithRundomRef() { Value = tmp.Value }; tbl.Add(tmp, t); tmp = tmp.Next; } tmp = head; while (tmp != null) { tbl[tmp].Next = tbl[tmp.Next]; tbl[tmp].Rundom = tbl[tmp.Rundom]; } return tbl[head]; } public static string ShortenStringByCharCount(string str) { Dictionary<char, int> cnts = new Dictionary<char, int>(); foreach (var item in str) { if (cnts.ContainsKey(item)) { cnts[item] = ++cnts[item]; } else { cnts.Add(item, 1); } } StringBuilder sb = new StringBuilder(); foreach (var item in cnts.Keys) { sb.Append(cnts[item]).Append(item); } return sb.ToString(); } public static BstNodeWithParent LowestCommonAncestor(BstNodeWithParent a, BstNodeWithParent b) { if (a == b) return a; BstNodeWithParent root = a; while (root.Parent != null) { root = root.Parent; } BstNodeWithParent left, right; if (a.Value < b.Value) { left = a; right = b; } else { left = b; right = a; } BstNodeWithParent curr = root; while (curr.Value > right.Value || curr.Value < left.Value) { if (curr.Value > right.Value) { curr = curr.Left; } else curr = curr.Right; } return curr; } public static BtNodeWithParent LowestCommonAncestor(BtNodeWithParent a, BtNodeWithParent b) { if (a == b) return a; int aheight = 0, bheight = 0; BtNodeWithParent root = a; while (root.parent != null) { aheight++; root = root.parent; } root = b; while (root.parent != null) { bheight++; root = root.parent; } BtNodeWithParent acurr = a; while (aheight > bheight) { aheight--; acurr = acurr.parent; } BtNodeWithParent bcurr = b; while (bheight > aheight) { bheight--; bcurr = bcurr.parent; } while (bcurr != acurr) { acurr = acurr.parent; bcurr = bcurr.parent; } return acurr; } public static BtNode LowestCommonAncestor(BtNode root, BtNode a, BtNode b) { if (root == null || root == a || root == b) return root; bool islefta = Covers(root.left, a); bool isleftb = Covers(root.left, b); if (islefta && isleftb) return LowestCommonAncestor(root.left, a, b); else if (!islefta && !isleftb) return LowestCommonAncestor(root.right, a, b); else return root; } public static bool Covers(BtNode root, BtNode p) { if (root == null) return false; if (root == p) return true; return Covers(root.left, p) || Covers(root.right, p); } public static BtNode LCA(BtNode root, BtNode p, BtNode q) { if (root == null || root == p || root == q) return root; bool lp = Covers1(root.left, p); bool lq = Covers1(root.left, q); if (lp != lq) return root; else if (lp) { return LCA(root.left, p, q); } else { return LCA(root.right, p, q); } } public static bool Covers1(BtNode root, BtNode n) { if (root == null) return false; if (root == n) return true; return Covers1(root.left, n) || Covers1(root.right, n); } /* Returns p, if root's subtree includes p (and not q). Returns q, if root's subtree includes q (and not p). Returns null, if neither p nor q are in root's subtree. Else, returns the common ancestor of p and q. */ public static BtNode LowestCommonAncestorOptimized(BtNode root, BtNode a, BtNode b) { if (root == null) return root; if (root == a && root == b) return root; BtNode l = LowestCommonAncestorOptimized(root.left, a, b); if (l != null && l != a && l != b) return l;//this is common anc(not null,a,b) BtNode r = LowestCommonAncestorOptimized(root.right, a, b); if (r != null && r != a && r != b) return r;//this is common anc(not null,a,b) //when l and r == null or a or b if (l != null && r != null) // l==a r==b or l==b r==a { // p and q found in diff subtrees return root; //root is commonanc } else if (root == a || root == b) //one of subtrees contains a or b { return root;//if root is a or b then it is commonanc } else { return l == null ? r : l;//return a or b } } public static CommonAncResult LowestCommonAncestorOptimized1(BtNode root, BtNode a, BtNode b) { if (root == null) return new CommonAncResult() { node = root, isancestor = false }; if (root == a && root == b) return new CommonAncResult() { node = root, isancestor = true }; CommonAncResult l = LowestCommonAncestorOptimized1(root.left, a, b); if (l.isancestor) return l;//this is common anc(not null,a,b) CommonAncResult r = LowestCommonAncestorOptimized1(root.right, a, b); if (r.isancestor) return r;//this is common anc(not null,a,b) //when l and r == null or a or b if (l.node != null && r.node != null) // l==a r==b or l==b r==a { // p and q found in diff subtrees return new CommonAncResult() { node = root, isancestor = true }; //root is commonanc } else if (root == a || root == b) //one of subtrees contains a or b { return new CommonAncResult() { node = root, isancestor = (l.node != null || r.node != null) };//if root is a or b then it is commonanc } else { return new CommonAncResult() { node = l.node == null ? r.node : l.node, isancestor = false }; //return a or b } } public class CommonAncResult { public BtNode node; public bool isancestor; } public static int SetBitsCount(int num) { int cnt = 0; while (num != 0) { num = (num - 1) & num; cnt++; } return cnt; } public static int SetBitsCount1(int num) { int cnt = 0; while (num != 0) { if ((num & 1) == 1) cnt++; num >>= 1; } return cnt; } public static BtNode RandomNode(BtNode root) { Random rnd = new Random(); BtNode randomnode = root; int index = 0; Queue<BtNode> q = new Queue<BtNode>(); q.Enqueue(root.left); q.Enqueue(root.right); while (q.Count > 0) { BtNode tmp = q.Dequeue(); index++; if (rnd.Next(0, index + 1) == 0) { randomnode = tmp; } q.Enqueue(tmp.left); q.Enqueue(tmp.right); } return randomnode; } public static void RandomNode(BtNode root, RandomNodeWrapper w, Random rnd) { if (root == null) return; if (w.node == null) w.node = root; else if (rnd.Next(0, w.index + 1) == 0) { w.node = root; w.index += 1; } RandomNode(root.left, w, rnd); RandomNode(root.right, w, rnd); } public class RandomNodeWrapper { public BtNode node; public int index; } public static bool ChackBracketsValidity(char[] brackets) { Stack<char> st = new Stack<char>(); foreach (var item in brackets) { if (IsOpeningBracket(item)) st.Push(item); else if (IsClosingBracket(item)) { if (st.Count == 0) return false; char tmp = st.Pop(); if (tmp != MatchingBracket(item)) return false; } else return false; } if (st.Count == 0) return true; return false; } public static bool IsOpeningBracket(char ch) { switch (ch) { case '{': return true; case '(': return true; case '[': return true; default: break; } return false; } public static bool IsClosingBracket(char ch) { switch (ch) { case '}': return true; case ')': return true; case ']': return true; default: break; } return false; } public static char MatchingBracket(char ch) { switch (ch) { case '}': return '{'; case ')': return '('; case ']': return '['; default: break; } throw new ArgumentException(); } public static int CompareOrdinalIgnoreCaseHelper(String strA, String strB) { int length = Math.Min(strA.Length, strB.Length); char[] ca = strA.ToCharArray(); char[] cb = strB.ToCharArray(); unsafe { fixed (char* ap = &ca[0]) fixed (char* bp = &cb[0]) { char* a = ap; char* b = bp; while (length != 0) { int charA = *a; int charB = *b; Contract.Assert((charA | charB) <= 0x7F, "strings have to be ASCII"); // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; //Return the (case-insensitive) difference between them. if (charA != charB) return charA - charB; // Next char a++; b++; length--; } } } return strA.Length - strB.Length; //c = (Char)(c & ~0x20); toupper } public static SinglyLinkedListNode Merge(SinglyLinkedListNode a, SinglyLinkedListNode b) { SinglyLinkedListNode nd = new SinglyLinkedListNode(); SinglyLinkedListNode ndtail = nd; SinglyLinkedListNode acurr = a; SinglyLinkedListNode bcurr = b; while (acurr != null && bcurr != null) { if (acurr.Value <= bcurr.Value) { ndtail.Next = acurr; acurr = acurr.Next; ndtail.Next.Next = null; } else { ndtail.Next = bcurr; bcurr = bcurr.Next; ndtail.Next.Next = null; } ndtail = ndtail.Next; } if (acurr == null) { ndtail.Next = bcurr; } if (bcurr == null) { ndtail.Next = acurr; } return nd.Next; } public static SinglyLinkedListNode DeleteOddValuedNodes(ref SinglyLinkedListNode head) { SinglyLinkedListNode newhead = null; SinglyLinkedListNode curr = head; SinglyLinkedListNode prev = null; while (curr != null && newhead == null) { if (curr.Value % 2 == 0) { newhead = curr; } curr = curr.Next; } prev = newhead; while (curr != null) { if (curr.Value % 2 == 0) { prev.Next = curr; prev = prev.Next; } curr = curr.Next; } head = newhead; return newhead; } public static SinglyLinkedListNode SeggregateEvenOddValuedNodes(ref SinglyLinkedListNode head) { SinglyLinkedListNode odds = null, oddshead = null; SinglyLinkedListNode evens = null, evenshead = null; SinglyLinkedListNode curr = head; while (curr != null) { if (curr.Value % 2 != 0) { if (oddshead == null) { oddshead = curr; odds = curr; } else { odds.Next = curr; odds = odds.Next; } } else { if (evenshead == null) { evenshead = curr; evens = curr; } else { evens.Next = curr; evens = evens.Next; } } curr = curr.Next; } evens.Next = oddshead; head = evenshead; return head; } //a has space for b public static int[] MergeInPlace(int[] a, int[] b, int acnt) { //acnt + b.Length <= a.Length int n = acnt + b.Length - 1; int ai = acnt - 1; int bi = b.Length - 1; while (ai >= 0 && bi >= 0) { if (a[ai] >= b[bi]) { a[n] = a[ai]; ai--; } else { a[n] = b[bi]; bi--; } n--; } if (ai >= 0) for (int i = ai; i >= 0; i--) { a[n] = a[ai]; n--; } if (bi >= 0) for (int i = bi; i >= 0; i--) { a[n] = a[bi]; n--; } return a; } public static DoublyLinkedListNode DeleteAlternateNodes(DoublyLinkedListNode head) { DoublyLinkedListNode curr = head; while (curr != null) { curr.Next = curr.Next.Next; if (curr.Next.Next != null) curr.Next.Next.Prev = curr; curr = curr.Next; } return head; } public static SinglyLinkedListNode DeleteAlternateNodes(SinglyLinkedListNode head) { SinglyLinkedListNode curr = head; while (curr != null) { curr.Next = curr.Next.Next; curr = curr.Next; } return head; } public static bool IsValidRansom(string ransom, string source) { Dictionary<string, int> sourcewords = new Dictionary<string, int>(); foreach (var item in source.Split(' ')) { if (sourcewords.ContainsKey(item)) { sourcewords[item] = ++sourcewords[item]; } else { sourcewords.Add(item, 1); } } foreach (var item in ransom.Split(' ')) { if (!sourcewords.ContainsKey(item)) return false; else if (sourcewords[item] <= 0) return false; sourcewords[item] = --sourcewords[item]; } return true; } public static int LargestCoherentOnes(int[,] arr) { bool[,] visited = new bool[arr.GetLength(0), arr.GetLength(1)]; int maxgroup = 0; for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { if (arr[i, j] == 1 && !visited[i, j]) { int cur = CountCoherentOnes(arr, i, j, visited); maxgroup = Math.Max(maxgroup, cur); } } } return maxgroup; } public static int CountCoherentOnes(int[,] arr, int i, int j, bool[,] visited) { int cnt = 1; visited[i, j] = true; if (i - 1 >= 0 && arr[i - 1, j] == 1 && !visited[i - 1, j]) { cnt += CountCoherentOnes(arr, i - 1, j, visited); } if (i + 1 <= arr.GetLength(0) - 1 && arr[i + 1, j] == 1 && !visited[i + 1, j]) { cnt += CountCoherentOnes(arr, i + 1, j, visited); } if (j - 1 >= 0 && arr[i, j - 1] == 1 && !visited[i, j - 1]) { cnt += CountCoherentOnes(arr, i, j - 1, visited); } if (j + 1 <= arr.GetLength(1) - 1 && arr[i, j + 1] == 1 && !visited[i, j + 1]) { cnt += CountCoherentOnes(arr, i, j + 1, visited); } return cnt; } public static int PathNumbersInGrid(int[,] arr) { int n = arr.GetLength(0); int m = arr.GetLength(1); int cnt = 0; cnt = PathToCell(arr, n - 1, m - 1); return cnt; } public static int PathToCell(int[,] arr, int i, int j) { if (arr[i, j] == 0) { return 0; } if (i == 0 && j == 0) return 1; int cnt = 0; if (i - 1 >= 0 && arr[i - 1, j] == 1) { cnt += PathToCell(arr, i - 1, j); } if (j - 1 >= 0 && arr[i, j - 1] == 1) { cnt += PathToCell(arr, i, j - 1); } return cnt; } //move by spiral public static Tuple<int, int> FindSetCellInGrid(int[,] arr) { int n = arr.GetLength(0) - 1; int m = arr.GetLength(1) - 1; int istart = arr.GetLength(0) / 2; int jstart = arr.GetLength(1) / 2; int move = 1; while (true) { if (istart == 0 && jstart == 0) break; int curmove = move; for (int i = 1; i <= curmove; i++)//right { if (jstart + 1 <= m) { jstart++; if (arr[istart, jstart] == 1) return new Tuple<int, int>(istart, jstart); } } for (int i = 1; i <= curmove; i++)//down { if (istart + 1 <= n) { istart++; if (arr[istart, jstart] == 1) return new Tuple<int, int>(istart, jstart); } } for (int i = 1; i <= curmove + 1; i++)//left { if (jstart - 1 >= 0) { jstart--; if (arr[istart, jstart] == 1) return new Tuple<int, int>(istart, jstart); } } for (int i = 1; i <= curmove + 1; i++)//up { if (istart - 1 >= 0) { istart--; if (arr[istart, jstart] == 1) return new Tuple<int, int>(istart, jstart); } } move += 2; } return new Tuple<int, int>(-1, -1); } public struct CellMove : IEqualityComparer<CellMove> { public int FromI { get; set; } public int FromJ { get; set; } public int ToI { get; set; } public int ToJ { get; set; } public bool Equals(CellMove x, CellMove y) { if (x.FromI == y.FromI && x.FromJ == y.FromJ && x.ToI == y.ToI && x.ToJ == y.ToJ) return true; return false; } public int GetHashCode(CellMove obj) { return obj.FromI.GetHashCode() + obj.FromJ.GetHashCode() + obj.ToI.GetHashCode() + obj.ToJ.GetHashCode(); } } public class Exit { public int Count { get; set; } } public static int FindExitInMaze(int[,] arr, int starti, int startj) { int n = arr.GetLength(0) - 1; int m = arr.GetLength(1) - 1; //HashSet<CellMove> visited = new HashSet<CellMove>(new CellMove()); bool[,] visited = new bool[n + 1, m + 1]; ////visited[starti, startj] = true; Exit exit = new Exit() { Count = 0 }; FindExitInMazeHelper(arr, starti, startj, n, m, visited, 0, exit); return exit.Count; } public static void FindExitInMazeHelper(int[,] arr, int starti, int startj, int n, int m, bool[,] visited, int cnt, Exit exit) { if (exit.Count > 0 && cnt > exit.Count) { Console.WriteLine(cnt); return; } if (arr[starti, startj] == 2) { if (exit.Count == 0) exit.Count = cnt; else if (cnt < exit.Count) exit.Count = cnt; Console.WriteLine(cnt); return; } else visited[starti, startj] = true; if (starti + 1 <= n && arr[starti + 1, startj] != 0 && !visited[starti + 1, startj]) { //if (visited.Add(new CellMove() { FromI = starti, FromJ = startj, ToI = starti + 1, ToJ = startj })) //{ // visited.Add(new CellMove() { FromI = starti + 1, FromJ = startj, ToI = starti, ToJ = startj }); FindExitInMazeHelper(arr, starti + 1, startj, n, m, visited, cnt + 1, exit); //} } if (starti - 1 >= 0 && arr[starti - 1, startj] != 0 && !visited[starti - 1, startj]) { //if (visited.Add(new CellMove() { FromI = starti, FromJ = startj, ToI = starti - 1, ToJ = startj })) //{ // visited.Add(new CellMove() { FromI = starti - 1, FromJ = startj, ToI = starti, ToJ = startj }); FindExitInMazeHelper(arr, starti - 1, startj, n, m, visited, cnt + 1, exit); //} } if (startj + 1 <= m && arr[starti, startj + 1] != 0 && !visited[starti, startj + 1]) { //if (visited.Add(new CellMove() { FromI = starti, FromJ = startj, ToI = starti, ToJ = startj + 1 })) //{ // visited.Add(new CellMove() { FromI = starti + 1, FromJ = startj + 1, ToI = starti, ToJ = startj }); FindExitInMazeHelper(arr, starti, startj + 1, n, m, visited, cnt + 1, exit); //} } if (startj - 1 >= 0 && arr[starti, startj - 1] != 0 && !visited[starti, startj - 1]) { //if (visited.Add(new CellMove() { FromI = starti, FromJ = startj, ToI = starti, ToJ = startj - 1 })) //{ // visited.Add(new CellMove() { FromI = starti + 1, FromJ = startj - 1, ToI = starti, ToJ = startj }); FindExitInMazeHelper(arr, starti, startj - 1, n, m, visited, cnt + 1, exit); //} } return; } public static BstNodeWithLevel LinkBstNodesByLevel(BstNodeWithLevel root) { Queue<BstNodeWithLevel> q = new Queue<BstNodeWithLevel>(); Queue<BstNodeWithLevel> lq = new Queue<BstNodeWithLevel>(); q.Enqueue(root); while (q.Count > 0) { BstNodeWithLevel tmp = q.Dequeue(); if (q.Count > 0) tmp.Level = q.Peek(); if (tmp.Left != null) lq.Enqueue(tmp.Left); if (tmp.Right != null) lq.Enqueue(tmp.Right); if (q.Count == 0) { while (lq.Count > 0) { q.Enqueue(lq.Dequeue()); } } } return root; } public static void FindColladingHotKeys(List<string> resource) { //module > (hotkay > [commands...]) Dictionary<string, Dictionary<string, List<string>>> col = new Dictionary<string, Dictionary<string, List<string>>>(); } } public class QueueBasedOnStack_HeavyEnqueue { Stack<int> main = new Stack<int>(); Stack<int> helper = new Stack<int>(); public void Enqueue(int num) { while (main.Count > 0) { helper.Push(main.Pop()); } main.Push(num); while (helper.Count > 0) { main.Push(helper.Pop()); } } public int Dequeue() { return main.Pop(); } } public class QueueBasedOnStack_HeavyDequeu { Stack<int> main = new Stack<int>(); Stack<int> helper = new Stack<int>(); public void Enqueue(int num) { main.Push(num); } public int Dequeue() { if (helper.Count > 0) return helper.Pop(); while (main.Count > 0) { helper.Push(main.Pop()); } return helper.Pop(); } } public class HybridStackQueue { LinkedList<int> list = new LinkedList<int>(); public void Enqueue(int num) { list.AddFirst(new LinkedListNode<int>(num)); } public int Dequeue() { var tmp = list.Last; list.RemoveLast(); return tmp.Value; } public void Push(int num) { list.AddFirst(new LinkedListNode<int>(num)); } public int Pop() { var tmp = list.First; list.RemoveFirst(); return tmp.Value; } } public class C { public static void M() { /*whatever*/ } } public class D : C { public new static void M() { /*whatever*/ } } public class E<T> where T : C { public static void N() { //T.M(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Tem.Action; public class CCSequenceAction : SSAction, ISSActionCallback { public List<SSAction> sequence; public int repeat = -1; public int start = 0; public static CCSequenceAction GetSSAction(List<SSAction> _sequence,int _start = 0,int _repeat = 1) { CCSequenceAction actions = ScriptableObject.CreateInstance<CCSequenceAction>(); actions.sequence = _sequence; actions.start = _start; actions.repeat = _repeat; return actions; } public override void Start() { foreach (SSAction ac in sequence) { ac.gameObject = this.gameObject; ac.transform = this.transform; ac.callback = this; ac.Start(); } } public override void Update() { if (sequence.Count == 0) return; if (start < sequence.Count) sequence[start].Update(); } public void SSEventAction(SSAction source, SSActionEventType events = SSActionEventType.COMPLETED, int intParam = 0, string strParam = null, Object objParam = null) //通过对callback函数的调用执行下个动作 { source.destory = false; this.start++; if (this.start >= this.sequence.Count) { this.start = 0; if (this.repeat > 0) this.repeat--; if (this.repeat == 0) { this.destory = true; this.callback.SSEventAction(this); } } } private void OnDestroy() { this.destory = true; } }
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. // VisualNovelToolkit /_/_/_/_/_/_/_/_/_/. // Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/. //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. using UnityEngine; using System.Collections; using System.Collections.Generic; using ViNoToolkit; /// <summary> /// TextBox UI Component. /// </summary> [ System.Serializable] [ AddComponentMenu( "ViNo/UI/TextBox" ) ] public class ViNoTextBox : MonoBehaviour{ public ViNoTextEventListener textEventListener; public GameObject backGround; public bool ClearMessageAtAwake; public Blink blink; // Text Animation. public bool useTextAfterEffect; public AnimationNode textDisplayEffect; // For example , attach a AnimationNode with Fade in Effect. public AnimationNode textAfterEffect; // For example , attach a AnimationNode with Fade out Effect. [ Range( 10 , 200 ) ] public int m_TextSpeed = 100; public bool wrapText; public int wrapEvery = 22; // default value. [ HideInInspector ]public bool playAtStart; [ HideInInspector ][ SerializeField ] private string m_Text; [ HideInInspector ][ SerializeField ] private float m_TimeElapsed = 0f; [ HideInInspector ][ SerializeField ] public float m_WaitTime = 0.1f; private Vector3 m_InitialPos; private int m_StartIndex = 0; private int m_CurrLength = 0; private bool m_ReachedEnd; private bool m_Update; private ColorPanel m_Panel; //******************* Properties ****************************. public int startIndex{ set{ m_StartIndex = value; } get{ return m_StartIndex; } } /// <summary> /// The text of All. /// </summary> /// <value> /// The text. /// </value> public string text{ get{ return m_Text; } set{ m_Text = value; } } /// <summary> /// Gets or sets the text speed Percentage 100% is Normal Speed. /// </summary> /// <value> /// The text speed. /// </value> public int textSpeed{ get{ return (int)( 1f / m_WaitTime ); } set{ m_WaitTime = 1f/(float)value; } } /// <summary> /// The Text to be Shown in a TextView. /// </summary> /// <value> /// The text shown. /// </value> public string textShown{ get{ if( m_CurrLength < m_Text.Length ){ if( m_CurrLength == 1 ){ if( m_Text[ 0 ].Equals( '[' ) ){ StripTag(); } } if( m_CurrLength - 1 >= 0 ){ if( m_Text[ m_CurrLength - 1 ].Equals( '[' ) ){ StripTag(); } } return m_Text.Substring( m_StartIndex , m_CurrLength ); } else{ if( m_Update ){ if( textEventListener != null) { textEventListener.OnDisplayedText( ); } } m_Update = false; m_ReachedEnd = true; return m_Text; } } } public bool reachedEnd{ get{ return m_ReachedEnd; } } public int currentTextLength{ get{ return m_CurrLength; } } public ColorPanel panel{ get { return m_Panel; } } //***********************************************. // param hash is attributes. public void ChangeProperty( Hashtable param ){ textEventListener.OnPropertyChange( param ); } public void ResetFont(){ textEventListener.ResetFont(); } void Awake(){ if( ClearMessageAtAwake ){ ClearMessage(); } m_Panel = GetComponent<ColorPanel>(); } void Start(){ textSpeed = m_TextSpeed; } // Update is called once per frame void Update(){ if( ! m_Update ){ return; } if( ! reachedEnd ){ if( Process( Time.deltaTime * ViNoConfig.prefsTextSpeed ) ){ m_CurrLength++; if( textEventListener != null) { textEventListener.OnUpdateText( textShown ); } } } } public void NextMessage(){ if( blink != null ){ blink.DontShow(); } if( ! ViNo.isLockNextMessage ){ if( useTextAfterEffect ){ if( ! reachedEnd ){ ViNo.NextMessage(); } else{ DoTextAfterEffect(); } } else{ ViNo.NextMessage(); } } } public void ActivateBackground( bool t ){ if( backGround != null ){ backGround.SetActive( t ); } } /// <summary> /// Sets the text. /// </summary> /// <param name='text'> /// Text. /// </param> public void SetText( string text ){ if( textEventListener != null) { textEventListener.OnTextSet( text ); } } /// <summary> /// Initialize the specified message. /// </summary> /// <param name='message'> /// Message. /// </param> public void Initialize( string message ){ text = message; if( blink != null ){ blink.DontShow(); } // Init. m_Update = true; m_TimeElapsed = 0f; startIndex = 0; m_CurrLength = 0; m_ReachedEnd = false; } /// <summary> /// Append the specified message. /// </summary> /// <param name='message'> /// Message. /// </param> public void Append( string message ){ if( blink != null ){ blink.DontShow(); } if( wrapText ){ System.Text.StringBuilder sb = new System.Text.StringBuilder(); int counter = 0; for(int i=0;i<message.Length;i++){ sb.Append( message[ i ] ); counter++; if( counter > wrapEvery ){ counter = 0; sb.Append( System.Environment.NewLine ); } } text += sb.ToString(); } else{ text += message; } if( ! m_Update ){ if( textEventListener != null) { textEventListener.OnStartMessage(); } } m_Update = true; m_TimeElapsed = 0f; m_ReachedEnd = false; if( textEventListener != null) { textEventListener.OnAppend( message ); } } /// <summary> /// Process the specified dt. /// </summary> /// <param name='dt'> /// If set to <c>true</c> dt. /// </param> public bool Process( float dt ){ m_TimeElapsed += dt; if( m_TimeElapsed > m_WaitTime ){ textSpeed = m_TextSpeed; m_TimeElapsed = 0f; return true; } else{ return false; } } /// <summary> /// Clears the message. /// </summary> public void ClearMessage(){ Initialize( "" ); m_Update = false; if( textEventListener != null) { textEventListener.OnUpdateText( "" ); } } public void CommitChanges(){ if( textEventListener != null) { textEventListener.CommitChanges(); } } /// <summary> /// Display the text quick. /// </summary> public void DispTextQuick(){ m_CurrLength = m_Text.Length; string text = textShown; // Get Text and Reached end soon. if( textEventListener != null) { textEventListener.OnUpdateText( text ); } } public void DoTextDisplayEffect(){ if( textDisplayEffect != null ){ textDisplayEffect.Preview(); } } public void DoTextAfterEffect(){ StartCoroutine( "TextAfterEffectAndNextMessage" ); } IEnumerator TextAfterEffectAndNextMessage( ){ ViNo.LockNextMessage(); if( textAfterEffect != null ){ textAfterEffect.Preview(); } // Wait Until the Text After Effect is Finished. if( textAfterEffect != null ){ yield return new WaitForSeconds( textAfterEffect.duration/1000f ); } else{ yield return new WaitForSeconds( 0.001f ); } ViNo.UnlockNextMessage(); ViNo.NextMessage(); } //*********** Getter *****************. public string GetBeginColorTag( Color col ){ return textEventListener.GetBeginColorTag( col ); } public string GetEndColorTag(){ return textEventListener.GetEndColorTag(); } public bool IsUpdate(){ return m_Update; } private void StripTag(){ while( ! m_Text[ m_CurrLength - 1 ].Equals( ']') ){ m_CurrLength++; } m_CurrLength++; } }
using UnityEngine; public class Waterfall : MonoBehaviour { [SerializeField][Range(0.0f, 1.0f )] private float fVolume = 1.0f; AudioSource pAudioSource = null; // Use this for initialization void Start () { pAudioSource = AudioManager.Play( "Waterfall", true ); if ( pAudioSource != null ) pAudioSource.volume = fVolume; } private void OnDestroy() { if ( pAudioSource != null ) pAudioSource.Stop(); } }