text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.Net.Mail; using MySql.Data.MySqlClient; namespace gbwebapp { public partial class bd_rej_SemKonfOtwarte : System.Web.UI.Page { //MySqlConnection connection, pobierzMAXvalue; //string ConnectionString = gbwebapp.Properties.Settings.Default.ConnectionString; protected void Page_Load(object sender, EventArgs e) { } protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { Response.Redirect("http://www.ksap.gov.pl"); } protected void ks_przeslij_btn_Click(object sender, EventArgs e) { string a = "0*hd"; string nadawca = "powiadomienie@ksap365.onmicrosoft.com"; string m = "@ire3"; string o = "8rW"; string odbiorca = email_tbx.Text; string T = "lkdJG"; string s = "5#h"; string temat = "Potwierdzenie uczestnictwa w wydarzeniu w KSAP"; string z = "3hk"; string tekst_wiadomosci = "Potwierdzamy rejestrację na wydarzenie w KSAP." + "\n\n" + "Płeć: " + plec_ddl.SelectedValue.ToString() + "\n" + "Imię: " + imie_tbx.Text.ToString() + "\n" + "Drugie imię: " + drugieImie_tbx.Text.ToString() + "\n" + "Nazwisko: " + nazwisko_tbx.Text.ToString() + "\n" + "Aders e-mail: " + email_tbx.Text.ToString() + "\n\n" + "Zgoda na przetwarzanie danych osobowych: " + daneOsobowe_zgoda_ddl.SelectedValue.ToString(); string SMTPServer = "smtp.office365.com"; string dydelf = T + o + m + a + s + z; //string SMTPServer = "STARTTLS / smtp.office365.com"; int SMTPPort = 587; string uzytkownik = "powiadomienie@ksap365.onmicrosoft.com"; string haslo = dydelf; MailMessage wiadonmosc = new MailMessage(nadawca, odbiorca, temat, tekst_wiadomosci); //SmtpClient klientEmail = new SmtpClient(SMTPServer); SmtpClient klientEmail = new SmtpClient(SMTPServer, SMTPPort); NetworkCredential SMTP_dane_uzytkownika = new NetworkCredential(uzytkownik, haslo); try { klientEmail.UseDefaultCredentials = false; klientEmail.Credentials = SMTP_dane_uzytkownika; klientEmail.EnableSsl = true; klientEmail.Send(wiadonmosc); statusWiadomosci_lbl.ForeColor = System.Drawing.Color.Green; statusWiadomosci_lbl.Text = "Zgłoszenie wysłane"; statusWiadomosci_lbl.Visible = true; //// tu DB //pobierzMAXvalue = new MySqlConnection(ConnectionString); //MySqlCommand zapytanieMAXvalue = new MySqlCommand("SELECT MAX(id_zgloszenia) FROM web_test_skasowac.bd_rej_semkonfotwart", pobierzMAXvalue); //zapytanieMAXvalue.Connection.Open(); //string MAXval_ = zapytanieMAXvalue.ExecuteScalar().ToString(); //if (MAXval_ == "") // MAXval_ = "0"; //int MAXval = UInt16.Parse(MAXval_) + 1; //obliczenie wartości id_zgloszenia dla kolejnego INSERTa //connection = new MySqlConnection(ConnectionString); //MySqlCommand przeslij_btn_insert = new MySqlCommand(); //przeslij_btn_insert.CommandType = System.Data.CommandType.Text; //przeslij_btn_insert.CommandText = "INSERT INTO web_test_skasowac.bd_rej_semkonfotwart(id_zgloszenia,plec,imie,drugieImie,nazwisko,email,daneOsobowe_zgoda) VALUES (" + MAXval + "," + "'" + plec_ddl.SelectedValue.ToString() + "'" + "," + "'" + imie_tbx.Text + "'" + "," + "'" + drugieImie_tbx.Text + "'" + "," + "'" + nazwisko_tbx.Text + "'" + "," + "'" + email_tbx.Text + "'" + "," + "'" + daneOsobowe_zgoda_ddl.SelectedValue.ToString() + "'" + ")"; //przeslij_btn_insert.Connection = connection; //connection.Open(); //przeslij_btn_insert.ExecuteNonQuery(); //connection.Close(); } catch (Exception ex) { statusWiadomosci_lbl.ForeColor = System.Drawing.Color.Red; statusWiadomosci_lbl.Text = ex.ToString(); statusWiadomosci_lbl.Visible = true; } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VectorMath : MonoBehaviour { [SerializeField] GameObject ServerImageTarget; [SerializeField] GameObject PlayerImageTarget; public Camera mainCamera; public GameObject realPlayer, virtualPlayer, thirdRealPlayer, thirdVirtualPlayer; [SerializeField] bool vuforiaTargetDetected = false; string lastImageTracked = ""; [SerializeField]Text playerX, playerY, playerZ, virtualX, virtualY, virtualZ; // Use this for initialization void Start () { } // Update is called once per frame void Update () { scanImageTarget(); //move virtual player based on real player's movement updateVirtualPlayer(); updateText(); } private void updateText() { playerX.text = realPlayer.transform.localPosition.x.ToString(); playerY.text = realPlayer.transform.localPosition.y.ToString(); playerZ.text = realPlayer.transform.localPosition.z.ToString(); virtualX.text = virtualPlayer.transform.localPosition.x.ToString(); virtualY.text = virtualPlayer.transform.localPosition.y.ToString(); virtualZ.text = virtualPlayer.transform.localPosition.z.ToString(); } private void scanImageTarget() { if(vuforiaTargetDetected) { vuforiaTargetDetected = false; lastImageTracked = "actualImageTarget"; } } private void UpdatePlayerPositionAndRotation() { if(lastImageTracked != "") { RepositionThePlayer(); RotateThePlayer(); GetServerPlayer(); } } private void GetServerPlayer() { //TODO: Use RealPlayer coordinates (in server world space) and make it relative to player. RepositionServerObject(); RotateServerObjects(); } private void RotateServerObjects() { //Rotating the player //Code from Elias var targetFlatForward = -ServerImageTarget.transform.up; targetFlatForward.y = 0; targetFlatForward.Normalize(); var targQuat = Quaternion.LookRotation(targetFlatForward, Vector3.up); var cameraFlatForward = thirdRealPlayer.transform.forward; cameraFlatForward.y = 0; cameraFlatForward.Normalize(); var camQuat = Quaternion.LookRotation(cameraFlatForward, Vector3.up); var flatAngle = Quaternion.Inverse(targQuat) * camQuat; thirdVirtualPlayer.transform.localRotation = flatAngle; } private void RepositionServerObject() { //Code from Elias var m = Matrix4x4.TRS(ServerImageTarget.transform.position - thirdRealPlayer.transform.position, ServerImageTarget.transform.rotation, Vector3.one); m = m.inverse; //Positioning the player var pos = MatrixUtils.ExtractTranslationFromMatrix(ref m); thirdVirtualPlayer.SetActive(true); thirdVirtualPlayer.transform.position = pos + PlayerImageTarget.transform.position; } private void RepositionThePlayer() { //TODO: GetThe Player Image Target which was last recognized in imageTargetInPlayerWorld //Code from Elias var m = Matrix4x4.TRS(PlayerImageTarget.transform.position - realPlayer.transform.position, PlayerImageTarget.transform.rotation, Vector3.one); m = m.inverse; //Positioning the player var pos = MatrixUtils.ExtractTranslationFromMatrix(ref m); //Setting the virtual player as a child of Image Target (for server) virtualPlayer.transform.SetParent(ServerImageTarget.transform, false); //Assigning local position to virtual player with rewspect to Image Target virtualPlayer.transform.localPosition = pos; } private void RotateThePlayer() { //Rotating the player //Code from Elias var targetFlatForward = -PlayerImageTarget.transform.up; targetFlatForward.y = 0; targetFlatForward.Normalize(); var targQuat = Quaternion.LookRotation(targetFlatForward, Vector3.up); var cameraFlatForward = realPlayer.transform.forward; cameraFlatForward.y = 0; cameraFlatForward.Normalize(); var camQuat = Quaternion.LookRotation(cameraFlatForward, Vector3.up); var flatAngle = Quaternion.Inverse(targQuat) * camQuat; virtualPlayer.transform.localRotation = flatAngle; } private void updateVirtualPlayer() { UpdatePlayerPositionAndRotation(); } }
using System; using System.Collections.Generic; using System.Data; using System.Text; using MySql.Data.MySqlClient; using Models; namespace DAL { /// <summary> /// 家庭数据访问类 /// </summary> public class family : POJO<tb_family> { public family() { } #region 成员方法 /// <summary> /// 增加一条数据 /// </summary> public void Add(tb_family model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into tb_family("); strSql.Append("employeeid,name,relation,birth,tel,unit,status,situation,remark"); strSql.Append(")"); strSql.Append(" values ("); strSql.Append("'" + model.employeeid + "',"); strSql.Append("'" + model.name + "',"); strSql.Append("'" + model.relation + "',"); strSql.Append("'" + model.birth + "',"); strSql.Append("'" + model.tel + "',"); strSql.Append("'" + model.unit + "',"); strSql.Append("'" + model.status + "',"); strSql.Append("'" + model.situation + "',"); strSql.Append("'" + model.remark + "'"); strSql.Append(")"); DbHelperSQL.ExecuteSql(strSql.ToString()); } /// <summary> /// 更新一条数据 /// </summary> public void Update(tb_family model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update tb_family set "); strSql.Append("employeeid='" + model.employeeid + "',"); strSql.Append("name='" + model.name + "',"); strSql.Append("relation='" + model.relation + "',"); strSql.Append("birth='" + model.birth + "',"); strSql.Append("tel='" + model.tel + "',"); strSql.Append("unit='" + model.unit + "',"); strSql.Append("status='" + model.status + "',"); strSql.Append("situation='" + model.situation + "',"); strSql.Append("remark='" + model.remark + "'"); strSql.Append(" where id=" + model.id + ""); DbHelperSQL.ExecuteSql(strSql.ToString()); } /// <summary> /// 删除一条数据 /// </summary> public void Delete(string strwhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from tb_family "); 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_family "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere + ""); } strSql.Append(" order by id "); return DbHelperSQL.Query(strSql.ToString()); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BankAccount.BLL.Requests { class GetLogoutResponse { ResponseEnums.GetResponse Response { get; set; } } }
using strange.extensions.signal.impl; using syscrawl.Game.Views.Levels; using UnityEngine; using syscrawl.Game.Models.Levels; using syscrawl.Game.Views.Nodes; namespace syscrawl.Game { public class GameStartSignal : Signal { } public class GenerateLevelSignal : Signal { } public class LevelGeneratedSignal : Signal { } public class PlayerMovedSignal : Signal { } public class PlayerMoveToSignal : Signal<Node> { } public class PositionNodesSignal : Signal<LevelSceneMediator> { } public class CreateNodeSignal : Signal<Node, GameObject, Vector3, SceneNodeType> { } public class CreateNodeTypeSignal : Signal<NodeType, GameObject> { } public class CreateNodeConnectionSignal : Signal<CreateNodeConnection> { } public class NodeWrapperClickedSignal : Signal<NodeWrapperView> { } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Create : MonoBehaviour { public float sectionDistance = 0.2f; public Material[] materials; void Start () { Model.rowDistance = sectionDistance + 1.0f; Model.rowDistanceHalf = Model.rowDistance * 0.5f; Model.rowCount = materials.Length; ModelStart modelStart = GameObject.Find ("ModelStart").GetComponent<ModelStart> (); modelStart.objectStartSectionHole.transform.Translate(0.0f, -sectionDistance, 0.0f); modelStart.objectStartCapDown.transform.Translate(0.0f, 2 * sectionDistance, 0.0f); string sectionFirstName = modelStart.objectStartSection.name; modelStart.objectStartSection.name += "1"; for (int i = 1; i <= Model.rowCount; i++) { if (i == 1) { continue; } GameObject sect = (GameObject)Instantiate (modelStart.objectStartSection, new Vector3(0.0f, modelStart.objectStartSection.transform.position.y + (i - 1) * (1.0f + sectionDistance), 0.0f ), Quaternion.identity); sect.transform.RotateAround(new Vector3(0.0f, 0.0f, 0.0f), Vector3.up, -18); sect.name = sectionFirstName + i.ToString(); } modelStart.objectStartCapUp.transform.Translate(0.0f, Model.rowCount * Model.rowDistance, 0.0f); string ballFirstName = modelStart.objectStartBall.name; modelStart.objectStartBall.name += "1"; List<Material> materialsToBalls = new List<Material>(); for (int i = 0; i < Model.rowCount; i++) { materialsToBalls.AddRange (materials); } setMaterialToBall(modelStart.objectStartBall, ref materialsToBalls); Model.rowZeroY = modelStart.objectStartBall.transform.position.y; Model.rowHoleY = Model.rowZeroY - Model.rowDistance; Model.maxY = Model.rowZeroY + (Model.rowCount - 1) * Model.rowDistance; for (int j = 0; j < Model.rowCount; j++) { for (int i = 0; i < Model.rowCount; i++) { if (i == 0 && j == 0) { continue; } GameObject ball = (GameObject)Instantiate (modelStart.objectStartBall, new Vector3(0.0f, modelStart.objectStartBall.transform.position.y + i * (1.0f + sectionDistance), modelStart.objectStartBall.transform.position.z ), Quaternion.identity); ball.transform.RotateAround(Vector3.zero, Vector3.up, j * 360 / Model.rowCount); ball.name = ballFirstName + (j * Model.rowCount + i + 1).ToString(); setMaterialToBall(ball, ref materialsToBalls); } } Model.objects.AddRange (GameObject.FindGameObjectsWithTag ("Ball")); Model.objects.AddRange (GameObject.FindGameObjectsWithTag ("Section")); } void setMaterialToBall(GameObject ball, ref List<Material> materials) { int materialIndex = Random.Range(0, materials.Count - 1); ball.GetComponent<Ball>().ballMaterial = materials[materialIndex]; materials.RemoveAt(materialIndex); } }
/* Copyright (c) 2010, Direct Project All rights reserved. Authors: Umesh Madan umeshma@microsoft.com Sean Nolan seannol@microsoft.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of The Direct Project (directproject.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Health.Direct.Common.DnsResolver { /// <summary> /// Represents an SOA DNS RR /// </summary> /// <remarks> /// RFC 1035, /// <code> /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// / MNAME / /// / / /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// / RNAME / /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | SERIAL | /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | REFRESH | /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | RETRY | /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | EXPIRE | /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | MINIMUM | /// | | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// </code> /// /// where: /// /// MNAME The &lt;domain-name&gt; of the name server that was the /// original or primary source of data for this zone. /// /// RNAME A &lt;domain-name&gt; which specifies the mailbox of the /// person responsible for this zone. /// /// SERIAL The unsigned 32 bit version number of the original copy /// of the zone. Zone transfers preserve this value. This /// value wraps and should be compared using sequence space /// arithmetic. /// /// REFRESH A 32 bit time interval before the zone should be /// refreshed. /// /// RETRY A 32 bit time interval that should elapse before a /// failed refresh should be retried. /// /// EXPIRE A 32 bit time value that specifies the upper limit on /// the time interval that can elapse before the zone is no /// longer authoritative. /// /// MINIMUM The unsigned 32 bit minimum TTL field that should be /// exported with any RR from this zone. /// </remarks> public class SOARecord : DnsResourceRecord { string m_mname; string m_rname; internal SOARecord() { } /// <summary> /// Initializes an instance with the supplied values and default values for refresh, retry, expire and minimum. /// </summary> /// <param name="name">The domain name for which this is a record</param> /// <param name="domainName">The domain name of the name server that was the primary source for this zone</param> /// <param name="responsibleName">Email mailbox of the hostmaster</param> /// <param name="serialNumber">Version number of the original copy of the zone.</param> public SOARecord(string name, string domainName, string responsibleName, int serialNumber) : this(name, domainName, responsibleName, serialNumber, 0, 0, 0, 0) { } /// <summary> /// Initializes an instance with the supplied values. /// </summary> /// <param name="name">The domain name for which this is a record</param> /// <param name="domainName">The domain name of the name server that was the primary source for this zone</param> /// <param name="responsibleName">Email mailbox of the hostmaster</param> /// <param name="serialNumber">Version number of the original copy of the zone.</param> /// <param name="refresh">Number of seconds before the zone should be refreshed.</param> /// <param name="retry">Number of seconds before failed refresh should be retried.</param> /// <param name="expire">Number of seconds before records should be expired if not refreshed</param> /// <param name="minimum">Minimum TTL for this zone.</param> public SOARecord(string name, string domainName, string responsibleName, int serialNumber, int refresh, int retry, int expire, int minimum) : base(name, DnsStandard.RecordType.SOA) { this.DomainName = domainName; this.ResponsibleName = responsibleName; this.SerialNumber = serialNumber; this.Refresh = refresh; this.Retry = retry; this.Expire = expire; this.Minimum = minimum; } /// <summary> /// The domain name of the name server that was the primary source for this zone /// </summary> public string DomainName { get { return m_mname; } set { if (string.IsNullOrEmpty(value)) { throw new DnsProtocolException(DnsProtocolError.InvalidSOARecord); } m_mname = value; } } /// <summary> /// Gets and sets the mailbox of the responsible name for this SOA (MNAME) /// </summary> /// <value>A <see cref="string"/> representation of the email or mailbox name (generally hostmaster)</value> public string ResponsibleName { get { return m_rname; } set { if (value == null) { throw new DnsProtocolException(DnsProtocolError.InvalidSOARecord); } m_rname = value; } } /// <summary> /// Gets and sets the serial number for this SOA (SERIAL) /// </summary> public int SerialNumber { get; set; } /// <summary> /// Gets and sets the refresh interval /// </summary> /// <value>A 32-bit value representing number of seconds</value> public int Refresh { get; set; } /// <summary> /// Gets and sets the retry interval /// </summary> /// <value>A 32-bit value representing number of seconds</value> public int Retry { get; set; } /// <summary> /// Gets and sets the expiry interval /// </summary> /// <value>A 32-bit value representing number of seconds</value> public int Expire { get; set; } /// <summary> /// Gets and sets the minimum TTL /// </summary> /// <value>A 32-bit value representing number of seconds</value> public int Minimum { get; set; } /// <summary> /// Tests equality between this SOA record and the other <paramref name="record"/>. /// </summary> /// <param name="record">The other record.</param> /// <returns><c>true</c> if the RRs are equal, <c>false</c> otherwise.</returns> public override bool Equals(DnsResourceRecord record) { if (!base.Equals(record)) { return false; } SOARecord soaRecord = record as SOARecord; if (soaRecord == null) { return false; } return ( DnsStandard.Equals(m_mname, soaRecord.m_mname) && DnsStandard.Equals(m_rname, soaRecord.m_rname) && this.SerialNumber == soaRecord.SerialNumber && this.Refresh == soaRecord.Refresh && this.Retry == soaRecord.Retry && this.Expire == soaRecord.Expire && this.Minimum == soaRecord.Minimum ); } /// <summary> /// Writes this RR in DNS wire format to the <paramref name="buffer"/> /// </summary> /// <param name="buffer">The buffer to which DNS wire data are written</param> protected override void SerializeRecordData(DnsBuffer buffer) { buffer.AddDomainName(m_mname); buffer.AddDomainName(m_rname); buffer.AddInt(this.SerialNumber); buffer.AddInt(this.Refresh); buffer.AddInt(this.Retry); buffer.AddInt(this.Expire); buffer.AddInt(this.Minimum); } /// <summary> /// Reads data into this RR from the DNS wire format data in <paramref name="reader"/> /// </summary> /// <param name="reader">Reader in which wire format data for this RR is already buffered.</param> protected override void DeserializeRecordData(ref DnsBufferReader reader) { this.DomainName = reader.ReadDomainName(); this.ResponsibleName = reader.ReadDomainName(); this.SerialNumber = reader.ReadInt(); this.Refresh = reader.ReadInt(); this.Retry = reader.ReadInt(); this.Expire = reader.ReadInt(); this.Minimum = reader.ReadInt(); } } }
using System; namespace MeterReadings.Schema { public class MeterReading { public int AccountId { get; set; } public DateTime MeterReadingDateTime { get; set; } public string MeterReadValue { get; set; } public Guid Id { get; set; } public override string ToString() { return $"{nameof(AccountId)}: {AccountId}, {nameof(MeterReadingDateTime)}: {MeterReadingDateTime}, {nameof(MeterReadValue)}: {MeterReadValue}"; } } }
using GalaSoft.MvvmLight.Command; using Project_CelineGardier_2NMCT2.model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Project.view { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : UserControl { public Settings() { InitializeComponent(); } private void SearchList(object sender, TextChangedEventArgs e) { ObservableCollection<Stage> stageSearch = new ObservableCollection<Stage>(Stage.GetStages().Where(x => x.Name.IndexOf(search.Text, StringComparison.OrdinalIgnoreCase) >= 0)); StageList.ItemsSource = stageSearch; } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = EnableDisableControls(); } private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { try { string txt = ""; // edit tickettypes foreach (TicketType type in Tickets.Items) { if (!TicketType.Edit(type)) { // something went wrong txt += "\nError: editing tickettype #" + type.ticketID; } } // edit festival int id = Convert.ToInt32(name.Tag); var start = StartDate as DatePicker; var end = EndDate as DatePicker; if (!Festival.Edit(id, name.Text, location.Text, start.SelectedDate, end.SelectedDate)) { // something went wrong txt += "\nError: editing festival #" + id; } if (txt == "") { txt = "Festival has been edited successfully"; } MessageBox.Show(txt); } // Fail catch (Exception ex) { MessageBox.Show("1. Something went wrong:\n " + ex); } } public bool EnableDisableControls() { return true; } } }
namespace SchoolClasses { using System; public class Student : People { private int classNumber; public int ClassNumber { get { return this.classNumber; } set { this.classNumber = value; } } } }
using MovieLibrary2.Model; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MovieLibrary2.DataManagement { public static class MovieRepository { public static ObservableCollection<Movie> _movieList; public static ObservableCollection<Movie> MovieList { get { if (_movieList == null) { var movies = LoadMovies().OrderBy(mov => mov.Title); _movieList = new ObservableCollection<Movie>(movies); } return _movieList; } set { _movieList = value; } } public static Func<FileInfo, Movie> movieCreator = delegate (FileInfo info) { return new Movie(info); }; public static ICollection<Movie> LoadMovies() { var list = new List<Movie>(); var dataFileMovies = GetMoviesFromDataFile(Properties.Settings.Default.DataFilePath); if (dataFileMovies != null && dataFileMovies.Count > 0) list.AddRange(dataFileMovies); var directoryMovies = GetMoviesFromDirectory(Properties.Settings.Default.MoviesDirectoryPath); list.AddRange(directoryMovies.Where(m => !list.Contains(m))); return list; } public static ICollection<Movie> GetMoviesFromDirectory(string directory) { return DataLoader.LoadDataFromDir(directory, "*.mkv|*.avi|*.mp4", movieCreator); //var unique = from mov in loadedList // where !MovieList.Contains(mov) // select mov; //foreach (var mov in unique) //{ // MovieList.Add(mov); //} } public static ICollection<Movie> GetMoviesFromDataFile(string dataFile) { ICollection<Movie> movieCollection = new List<Movie>(); if (!File.Exists(dataFile)) return null; var deserializedMovieList = DataSerialization.DeserializeList<Movie>(dataFile); if (deserializedMovieList == null) return null; foreach (var mov in deserializedMovieList) { if (File.Exists(mov.FilePath) && !movieCollection.Contains(mov)) movieCollection.Add(mov); } return movieCollection; } public static void SaveMoviesToDataFile(string dataFile) { DataSerialization.SerializeList<Movie>(MovieList, dataFile); } } }
namespace AtmDb.Model { public enum MoneyTransactionType { Deposit, Withdraw } }
namespace CodeReuse.VirtualMachineExample { public class VirtualMachine : IResource { public int ResourceIdentifier { get; set ; } private SnapshotCreator<VirtualMachine> _snapshotCreator; public VirtualMachine(SnapshotCreator<VirtualMachine> snapshotCreator) { _snapshotCreator = snapshotCreator; } public void CreateSnapshotOfVolume() { _snapshotCreator.CreateSnapshot(this); } } }
using System; using System.Collections.Generic; using System.Linq; using Tookan.NET.Helpers; using Tookan.NET.Sanity; namespace Tookan.NET.Http { internal static class ApiInfoParser { public static ApiInfo ParseResponseHeaders(IDictionary<string, string> responseHeaders) { Ensure.ArgumentIsNotNull(responseHeaders, "responseHeaders"); var oauthScopes = new List<string>(); var acceptedOauthScopes = new List<string>(); string etag = null; if (responseHeaders.ContainsKey("X-Accepted-OAuth-Scopes")) { acceptedOauthScopes.AddRange(responseHeaders["X-Accepted-OAuth-Scopes"] .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim())); } if (responseHeaders.ContainsKey("X-OAuth-Scopes")) { oauthScopes.AddRange(responseHeaders["X-OAuth-Scopes"] .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim())); } if (responseHeaders.ContainsKey("ETag")) { etag = responseHeaders["ETag"]; } return new ApiInfo(oauthScopes, acceptedOauthScopes, etag, new RateLimit(responseHeaders)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Assets.Scripts.Interfaces { public interface IControlManager { ControlType CurrentControlType { get; set; } int CurrentScore { get; set; } void ResetPlayerPosition(); void Initialization(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace BPiaoBao.Client.UIExt.Model.Enumeration { /// <summary> /// Pos机状态 /// </summary> public enum PosStatus { [Description("所有")] All = -1, [Description("未分配")] Unassigned = 0, [Description("已分配")] Assigned = 1, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IVeraControl.Model; using UpnpModels.Model.UpnpService.Base; namespace UpnpModels.Model.UpnpService { public enum HomeAutomationGatewayAction { RunScene, } public enum HomeAutomationGatwayStateVariable { None } public class HomeAutomationGatewayService : UpnpServiceBase, IUpnpService { public string ServiceUrn => "urn:micasaverde-com:serviceId:HomeAutomationGateway1"; public string ServiceName { get; } = ServiceType.HomeAutomationGateway1.ToString(); public HomeAutomationGatewayService(IVeraController controller, IUpnpDevice device) { //StateVariables = new List<IUpnpStateVariable> //{ // new UpnpStateVariable(controller, this, device) // { // VariableName = HomeAutomationGatwayStateVariable.None.ToString(), // Type = typeof(int), // } //}; Actions = new List<IUpnpAction> { new UpnpAction(controller, this, device) { ActionName = HomeAutomationGatewayAction.RunScene.ToString(), ArgumentName = "SceneNum", Type = typeof(int), Value = null, Direction = Direction.In } }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MKMCrawler { public partial class MainWindow : Form { public MainWindow() { InitializeComponent(); } private void actualizarBaseDeDatosMenuSuperior_Click(object sender, EventArgs e) { RequestHelper requestHelper = new RequestHelper(); requestHelper.makeRequest("https://www.mkmapi.eu/ws/v1.1/expansion/1/"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EnergyPanelOperator : MonoBehaviour { private static EnergyPanelOperator mInstance; public static EnergyPanelOperator GetInstance() { return mInstance; } public int MaxEnergy; public int CurrentEnergy; public GameObject EnergySlot; void Awake() { mInstance = this; EnergySlot = Instantiate(EnergySlot); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { CurrentEnergy = DataBase.GetInstance().SaveGame.CurrentEnergy; MaxEnergy = DataBase.GetInstance().SaveGame.MaxEnergy; transform.Find("Info").GetComponent<Text>().text = "能量值:" + CurrentEnergy + "/" + MaxEnergy; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public enum TemplePieceType { UNDEFINED, LEFT_HORN, RIGHT_HORN, NOSE_RING }; public class TemplePieceInteract : EventActivator { [SerializeField] private UnityEvent onPickUp; [SerializeField] private TempleInteract temple; [SerializeField] private float destroyDelay = 0; [SerializeField] private TemplePieceType type; public TemplePieceType Type {get {return type;} } /// requests pickup of the collectable protected override void HoldInteract() { base.HoldInteract(); RequestPickUp(); } /// requests pickup of the collectable protected override void Interact() { base.Interact(); RequestPickUp(); } /// requests player to move towards this gameobject and execute OnPickUp at arrival private void RequestPickUp() { PlayerController.Instance.RequestMove(this.transform.position, this.OnPickUp); } /// destroys this object and decrements the counter private void OnPickUp() { onPickUp?.Invoke(); RelicsCollected.Instance.CollectPiece(Type); if (temple) temple.EnqueueTemplePiece(Type); Destroy(this.gameObject, destroyDelay); } }
namespace SuperSorter { public interface IAlgorithm { int[] Sort(int[] data); } }
using Mvc5IdentityExample.Domain.Entities; using Mvc5IdentityExample.Domain.Repositories; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace Mvc5IdentityExample.Data.EntityFramework.Repositories { internal class UserRepository : Repository<User>, IUserRepository { internal UserRepository(ApplicationDbContext context) : base(context) { } public User FindByUserName(string username) { return Set.FirstOrDefault(x => x.UserName == username); } public Task<User> FindByUserNameAsync(string username) { return Set.FirstOrDefaultAsync(x => x.UserName == username); } public Task<User> FindByUserNameAsync(System.Threading.CancellationToken cancellationToken, string username) { return Set.FirstOrDefaultAsync(x => x.UserName == username, cancellationToken); } public override void Remove(User entity) { var userEntry = Set.FirstOrDefault(t => t.UserId == entity.UserId); if (userEntry != null) { Set.Remove(userEntry); } } } }
using Microsoft.Maui.Controls; using System; namespace Contoso.XPlatform.Utils { public class MultiSelectItemTemplateSelector : DataTemplateSelector { private DataTemplate? _singleFieldTemplate; private DataTemplate? _doubleFieldTemplate; public DataTemplate SingleFieldTemplate { get => _singleFieldTemplate ?? throw new ArgumentException($"{nameof(_singleFieldTemplate)}: {{E7AEC16C-E94C-489A-9BF4-4D3DCE1226EC}}"); set => _singleFieldTemplate = value; } public DataTemplate DoubleFieldTemplate { get => _doubleFieldTemplate ?? throw new ArgumentException($"{nameof(_doubleFieldTemplate)}: {{F5F03AEA-E2D4-4B3E-9B3D-48A1DD9DB799}}"); set => _doubleFieldTemplate = value; } protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { return SingleFieldTemplate; } } }
using System; using System.Collections.Generic; namespace Array1 { class Program { static void Main(string[] args) { List<int> array = new List<int>(); int N = Convert.ToInt32(Console.ReadLine()); for (int i = 1; i <= N; i+=2) { array.Add(i); } for (int i = 0; i < array.Count; i++) { Console.WriteLine(array[i]); } } } }
// 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; using System; namespace NtApiDotNet.Net.Firewall { /// <summary> /// Class to represent an IKEEXT quick mode failure event. /// </summary> public sealed class FirewallNetEventIkeExtQmFailure : FirewallNetEvent { /// <summary> /// Windows error code for the failure /// </summary> public Win32Error FailureErrorCode { get; } /// <summary> /// Point of failure /// </summary> public IPsecFailurePoint FailurePoint { get; } /// <summary> /// IKE or Authip. /// </summary> public IkeExtKeyModuleType KeyingModuleType { get; } /// <summary> /// Main mode state /// </summary> public IkeExtQmSaState QmState { get; } /// <summary> /// Initiator or Responder /// </summary> public IkeExtSaRole SaRole { get; } /// <summary> /// Tunnel or transport mode. /// </summary> public IPsecTrafficType SaTrafficType { get; } /// <summary> /// Main mode filter ID /// </summary> public ulong QmFilterId { get; } /// <summary> /// Local subnet address and mask. /// </summary> public FirewallAddressAndMask LocalSubNet { get; } /// <summary> /// Remote subnet address and mask. /// </summary> public FirewallAddressAndMask RemoteSubNet { get; } private static FirewallAddressAndMask GetAddr(FWP_VALUE0 value) { var v = new FirewallValue(value, Guid.Empty); if (v.Value is FirewallAddressAndMask addr) return addr; return default; } internal FirewallNetEventIkeExtQmFailure(IFwNetEvent net_event) : base(net_event) { var ev = net_event.Value.ReadStruct<FWPM_NET_EVENT_IKEEXT_QM_FAILURE0>(); FailureErrorCode = ev.failureErrorCode; FailurePoint = ev.failurePoint; KeyingModuleType = ev.keyingModuleType; QmState = ev.qmState; SaRole = ev.saRole; QmFilterId = ev.qmFilterId; SaTrafficType = ev.saTrafficType; switch (SaTrafficType) { case IPsecTrafficType.Transport: case IPsecTrafficType.Tunnel: { LocalSubNet = GetAddr(ev.localSubNet); RemoteSubNet = GetAddr(ev.remoteSubNet); } break; } } } }
namespace FastFourierTransform { using System; using System.Diagnostics; using System.Linq; internal static class Program { private static void Main(string[] args) { Random r = new Random(0); int filter_size = 2048; double[] signal = Enumerable.Range(0, filter_size * 100).Select(t => r.NextDouble()).ToArray(); double[] filter = Enumerable.Range(0, filter_size).Select(_ => 1 / 2048.0).ToArray(); Stopwatch sw = Stopwatch.StartNew(); double[] fast_answer = new ConvolutionCalculator(signal, filter).Calculate(); Console.WriteLine(sw.Elapsed); sw = Stopwatch.StartNew(); double[] dump_answer = new double[signal.Length + filter.Length - 1]; for (int j = 0; j < dump_answer.Length; j++) { double temp = 0; for (int i = 0; i < filter.Length; i++) { int signalIndex = i + j - filter.Length + 1; int filterIndex = filter.Length - i - 1; double signal_value; if (signalIndex < 0) { signal_value = 0; } else if (signalIndex >= signal.Length) { signal_value = 0; } else { signal_value = signal[signalIndex]; } temp += signal_value * filter[filterIndex]; } dump_answer[j] = temp; } double squared_error = 0; for (int i = 0; i < signal.Length + filter.Length - 1; i++) { double error = fast_answer[i] - dump_answer[i]; squared_error += error * error; } Console.WriteLine(sw.Elapsed); Console.Write(squared_error); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ExpressionsSerialization { public class TransitionMap : ITransitionMap { private static Dictionary<ExpressionType, ExpressionType[]> states { get; } = new Dictionary<ExpressionType, ExpressionType[]>(); static TransitionMap() { Add( ExpressionType.Lambda, ExpressionType.Parameter, ExpressionType.AndAlso, ExpressionType.GreaterThanOrEqual ); Add( ExpressionType.MemberAccess, ExpressionType.MemberAccess, ExpressionType.Parameter ); Add( ExpressionType.GreaterThanOrEqual, ExpressionType.MemberAccess, ExpressionType.Parameter, ExpressionType.Constant ); } private static void Add(ExpressionType parentType, params ExpressionType[] childTypes) => states.Add(parentType, childTypes); public void EnsureValidTransition(ExpressionType parentType, ExpressionType childType) { if (!states[parentType].Contains(childType)) throw new InvalidOperationException( $"Expression type {childType} is not allowed in expression {parentType}" ); } } }
namespace ListagemNumerica.Servicos { internal interface IImpressaoServico { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class dog_run : MonoBehaviour { public GameObject dog; GameObject player; // Use this for initialization void Start () { player = GameObject.Find("player"); } // Update is called once per frame void Update () { if(dog.transform.position.x>player.transform.position.x) { Main._instance.Game_state = Main.state_game.gameover; scene_manager.Scene_isrun = false; Destroy(this); // Time.timeScale = 0; // scene_manager.Game_isrun = true; } else dog.transform.position+=new Vector3(0.02f,0,0); } }
// // - PropertyNodeDefinitionCollection.cs - // // Copyright 2012 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.Collections.Generic; using System.Diagnostics; using System.Linq; using Carbonfrost.Commons.Core; namespace Carbonfrost.Commons.PropertyTrees.Schema { public abstract class PropertyNodeDefinitionCollection<T> : ICollection<T>, IEnumerable<T> where T : PropertyNodeDefinition { private bool isReadOnly; private readonly Dictionary<QualifiedName, T> items = new Dictionary<QualifiedName, T>(Utility.OrdinalIgnoreCaseQualifiedName); protected bool IsReadOnly { get { return isReadOnly; } } internal PropertyNodeDefinitionCollection() {} protected void ThrowIfReadOnly() { if (IsReadOnly) throw Failure.ReadOnlyCollection(); } public bool ContainsValue(T value) { return items.ContainsValue(value); } internal void TryAdd(T item) { if (!items.ContainsKey(item.QualifiedName)) AddInternal(item); } internal virtual void AddInternal(T item) { lock (this.items) { this.items.Add(item.QualifiedName, item); } } internal void RemoveInternal(QualifiedName name) { lock (items) { items.Remove(name); } } public void Add(T item) { if (item == null) throw new ArgumentNullException("item"); ThrowIfReadOnly(); AddInternal(item); } public T this[string name, string ns] { get { if (name == null) throw new ArgumentNullException("name"); // $NON-NLS-1 if (name.Length == 0) throw Failure.EmptyString("name"); // $NON-NLS-1 ns = ns ?? string.Empty; return this[QualifiedName.Create(ns, name)]; } } public IEnumerable<T> GetByLocalName(string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw Failure.EmptyString("name"); return this.items.Values.Where(t => t.Name == name); } public IEnumerator<T> GetEnumerator() { return items.Values.GetEnumerator(); } public bool Contains(QualifiedName key) { return ContainsKey(key); } public bool Contains(string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw Failure.EmptyString("name"); return this.items.Keys.Any(t => string.Equals(t.LocalName, name, StringComparison.OrdinalIgnoreCase)); } public bool Contains(string name, string ns) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw Failure.EmptyString("name"); return Contains(QualifiedName.Create(ns ?? string.Empty, name)); } // IDictionary implementation public T this[QualifiedName name] { get { T result; if (this.items.TryGetValue(name, out result)) return result; return null; } set { ThrowIfReadOnly(); items[name] = value; } } public int Count { get { return items.Count; } } // bool IMakeReadOnly.IsReadOnly { // get { return isReadOnly; } } bool ICollection<T>.IsReadOnly { get { return isReadOnly; } } public bool ContainsKey(QualifiedName key) { return items.ContainsKey(key); } public bool Remove(QualifiedName key) { ThrowIfReadOnly(); return items.Remove(key); } public bool TryGetValue(QualifiedName key, out T value) { return items.TryGetValue(key, out value); } public void Clear() { ThrowIfReadOnly(); items.Clear(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public void MakeReadOnly() { this.isReadOnly = true; } public bool Contains(T item) { if (item == null) throw new ArgumentNullException("item"); return this.ContainsKey(item.QualifiedName); } public void CopyTo(T[] array, int arrayIndex) { items.Values.CopyTo(array, arrayIndex); } public bool Remove(T item) { if (item == null) throw new ArgumentNullException("item"); if (object.Equals(item, this[item.QualifiedName])) return Remove(item.QualifiedName); return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LeaveRequestApp.Models { public class Site { public static Site CurrentSite { get; set; } public string Url { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.Azure.SignalR.Tests { public class AddAzureSignalRFacts { private const string CustomValue = "customconnectionstring"; private const string DefaultValue = "defaultconnectionstring"; private const string SecondaryValue = "secondaryconnectionstring"; [Fact] public void AddAzureSignalRReadsDefaultConfigurationKeyForConnectionString() { var services = new ServiceCollection(); var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { {"Azure:SignalR:ConnectionString", DefaultValue} }) .Build(); var serviceProvider = services.AddSignalR() .AddAzureSignalR() .Services .AddSingleton<IConfiguration>(config) .BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<ServiceOptions>>().Value; Assert.Equal(DefaultValue, options.ConnectionString); Assert.Equal(5, options.ConnectionCount); Assert.Equal(TimeSpan.FromHours(1), options.AccessTokenLifetime); Assert.Null(options.ClaimsProvider); } [Fact] public void AddAzureUsesDefaultConnectionStringIfSpecifiedAndOptionsOverridden() { var services = new ServiceCollection(); var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { {"Azure:SignalR:ConnectionString", DefaultValue} }) .Build(); var serviceProvider = services.AddSignalR() .AddAzureSignalR(o => { o.ConnectionCount = 1; }) .Services .AddSingleton<IConfiguration>(config) .BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<ServiceOptions>>().Value; Assert.Equal(DefaultValue, options.ConnectionString); Assert.Equal(1, options.ConnectionCount); Assert.Equal(TimeSpan.FromHours(1), options.AccessTokenLifetime); Assert.Null(options.ClaimsProvider); } [Fact] public void AddAzureReadsConnectionStringFirst() { var services = new ServiceCollection(); var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { {"Azure:SignalR:ConnectionString", DefaultValue} }) .Build(); string capturedConnectionString = null; var serviceProvider = services.AddSignalR() .AddAzureSignalR(o => { capturedConnectionString = o.ConnectionString; }) .Services .AddSingleton<IConfiguration>(config) .BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<ServiceOptions>>().Value; Assert.Equal(DefaultValue, options.ConnectionString); Assert.Equal(DefaultValue, capturedConnectionString); } [Theory] [InlineData(CustomValue, null, null, CustomValue)] [InlineData(CustomValue, DefaultValue, SecondaryValue, CustomValue)] [InlineData(null, DefaultValue, SecondaryValue, DefaultValue)] [InlineData(null, null, SecondaryValue, SecondaryValue)] public void AddAzureSignalRLoadConnectionStringOrder(string customValue, string defaultValue, string secondaryValue, string expected) { var services = new ServiceCollection(); var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { {"Azure:SignalR:ConnectionString", defaultValue}, {"ConnectionStrings:Azure:SignalR:ConnectionString", secondaryValue} }) .Build(); var serviceProvider = services.AddSignalR() .AddAzureSignalR(o => { if (customValue != null) { o.ConnectionString = customValue; } }) .Services .AddSingleton<IConfiguration>(config) .BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<ServiceOptions>>().Value; Assert.Equal(expected, options.ConnectionString); } } }
using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(Image))] public class HealthBar : MonoBehaviour { private Image image; private void Start() { image = GetComponent<Image>(); } private void LateUpdate () { float scale = Mathf.Clamp(GameManager.Instance.PStats.health, 0, GameManager.Instance.PStats.maxHealth)/GameManager.Instance.PStats.maxHealth; image.fillAmount = scale; } }
using FixyNet.Clases; using FixyNet.Clases.Listas; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace FixyNet.Forms { public partial class frmGrafico : Form { public event EventHandler Cambio; public event EventHandler Cerrofrm; public frmGrafico() { InitializeComponent(); } private void frmGrafico_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; } private void frmGrafico_Paint(object sender, PaintEventArgs e) { InvocarCambio(); } public void InvocarCambio() { this.Cambio?.Invoke(this, EventArgs.Empty); } public void InvocarCerrar() { this.Cerrofrm?.Invoke(this, EventArgs.Empty); } private void frmGrafico_FormClosing(object sender, FormClosingEventArgs e) { } private void frmGrafico_FormClosed(object sender, FormClosedEventArgs e) { InvocarCerrar(); } private void progressGrafico_QueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e) { } private void progressGrafico_Leave(object sender, EventArgs e) { } } }
/* * Copyright (C) Timo Heinonen * * This file is part of my homework :) * * Created: Timo Heinonen */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace T5 { class Program { static void Main(string[] args) { Radio radio = new Radio(); int i = 1; //this is for the do while loop do { Console.WriteLine("Welcome to radio! What do you want to do?"); Console.WriteLine("1. Turn radio on/off"); Console.WriteLine("2. Adjust volume"); Console.WriteLine("3. Adjust frequency"); Console.WriteLine("4. Radio status"); Console.WriteLine("5. Abandon radio"); int valikko = int.Parse(Console.ReadLine()); switch (valikko) { case 1: { Console.Write("Set Radio on off (1 or 0): "); int valinta = int.Parse(Console.ReadLine()); if (valinta == 1) radio.IsOn = true; else radio.IsOn = false; Console.WriteLine("Radio is now " + radio.IsOn); break; } case 2: { Console.WriteLine("Adjust radio volume (0-9): "); radio.Volume = int.Parse(Console.ReadLine()); Console.WriteLine("Volume is now: " + radio.Volume); break; } case 3: { Console.WriteLine("Adjust radio frequency (2000 - 26000): "); radio.Frequency = int.Parse(Console.ReadLine()); Console.WriteLine("Frequency is now: " + radio.Frequency); break; } case 4: { Console.WriteLine(radio.ToString()); break; } case 5: { Console.WriteLine("Sad radio is sad :("); i = 0; break; } } } while (i == 1); } } }
using System.Collections.Generic; namespace Sorting_Algorithms { public class BubbleSort { public List<int> NumberOrdering(List<int> list) { var size = list.Count; for (var i = size - 1; i >= 1; i--) { for (var j = 0; j < i; j++) { if (list[j] <= list[j + 1]) continue; var aux = list[j]; list[j] = list[j + 1]; list[j + 1] = aux; } } return list; } } }
using System; using System.Drawing; using System.Collections; namespace CIS4800 { public class DrawImage { private int width; private int height; private Bitmap bmp; /* * public DrawImage() * Parameters: m - dimensions of generated image * Initializes DrawImage object * */ public DrawImage (int m) { this.width = m; this.height = m; this.bmp = new Bitmap (width, height); } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public Bitmap getBmp() { return this.bmp; } /* * public void DrawPixelAt() * Parameters: x - horizontal cooordinate on image * y - vertical coordinate on image * r - color of the pixel * Sets pixel to be drawn at coordinates (x, y) * */ public void DrawPixelAt(int x, int y, Color r) { this.bmp.SetPixel (x, y, r); } /* * public void SaveImage() * Parameters: none * Exports the generated bitmap to a .png file in root directory * */ public void SaveImage() { this.bmp.Save ("../../../output/image.png"); } } }
using ePay.ApplicationCore.Models; using System; using System.Linq; namespace ePay.Infrastructure.Data { public static class DbInitializer { public static void Initialize(ePayContext context) { context.Database.EnsureCreated(); //if (context.Persons.Any()) //{ // return; //} //var persons = new Person[] //{ // new Person{Id=1,FirstName="Carson",LastName="Alexander",Age=12}, // new Person{Id=2,FirstName="Carson",LastName="Alexander",Age=12}, // new Person{Id=3,FirstName="Carson",LastName="Alexander",Age=12}, //}; //foreach (var s in persons) //{ // context.Persons.Add(s); //} //context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ContosoUniversity.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] // specifies the PK is generated by the app not the DB [Display(Name = "Course Number")] public int CourseID { get; set; } // the reason the app generates the PK is because when the course is created the course // number will act as the PK, 1000, 2001, 3004, etc // [DatabaseGenerated(DatabaseGeneratedOption.Computed)] [StringLength(50, MinimumLength = 3)] // min length same as making required public string Title { get; set; } [Range(0, 5)] public int Credits { get; set; } // not required because the navigation property is set below // however, EF Core creates shadow properties for automatically created FKs // adding the DepartmentID FK here and not just leaving it to a navigation property // not only clarifies the relationship for migrations, but also EF Core does not need to // fetch the entire Department entity before populating the FK DepartmentID public int DepartmentID { get; set; } public Department Department { get; set; } public ICollection<Enrollment> Enrollments { get; set; } public ICollection<CourseAssignment> CourseAssignments { get; set; } } }
using System; using System.Collections.Generic; namespace Model { /** * This is a strategy for container objects. It does nothing. */ public class StrategyIdle : Strategy { private static StrategyIdle Instance = new StrategyIdle(); public static StrategyIdle GetInstance() { return Instance; } private StrategyIdle() {} public override void Behavior(AbstractActor self, List<AbstractActor> all) { } public override void ReactToEvent(AbstractActor self, MyEventArgs args) { } } }
using System; using System.Collections; using System.Threading; using System.IO; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using System.Collections.Generic; using System.Threading.Tasks; namespace CommonLib.Core.Utility { /// <summary> /// Logger ªººK­n´y­z¡C /// </summary> /// public class FileLoggerFactory : ILoggerFactory { public void AddProvider(ILoggerProvider provider) { } public ILogger CreateLogger(string categoryName) { return new FileLogger(); } public void Dispose() { } } }
using UnityEngine; namespace Explodables.CaveIn.Contracts { public abstract class Explodable : MonoBehaviour { public abstract void ReceiveDamage(int damage); public abstract void BlowUp(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MOSC { /// <summary> /// Логика взаимодействия для PageResources.xaml /// </summary> public partial class PageResources : Page { public PageResources() { InitializeComponent(); } public void ShowPath(System.Windows.Controls.TextBox tb) { OpenFileDialog OPF = new OpenFileDialog(); OPF.Filter = "|*.wav"; OPF.Multiselect = true; if (OPF.ShowDialog() == DialogResult.OK) { tb.Text = OPF.FileName; } } public void SavePathes() { GlobalSetting.pathMusicStartPair = tbPathStartSoundPair.Text; GlobalSetting.pathMusicForFiveMinutesStartPair = tbPathStartForFiveSoundPair.Text; GlobalSetting.pathMusicEndPair = tbPathEndSoundPair.Text; GlobalSetting.pathMusicForFiveMinutesEndPair = tbPathEndForFiveSoundPair.Text; bool status = GlobalSetting.SaveGlobalSettigsSound(); if (status) { statusSave.Foreground = Brushes.Green; statusSave.Visibility = Visibility.Visible; } } private void btnPathStartSoundPair_Click(object sender, RoutedEventArgs e) { ShowPath(tbPathStartSoundPair); } private void btnPathStartForFiveSoundPair_Click(object sender, RoutedEventArgs e) { ShowPath(tbPathStartForFiveSoundPair); } private void btnPathEndSoundPair_Click(object sender, RoutedEventArgs e) { ShowPath(tbPathEndSoundPair); } private void btnPathEndForFiveSoundPair_Click(object sender, RoutedEventArgs e) { ShowPath(tbPathEndForFiveSoundPair); } private void btnSave_Click(object sender, RoutedEventArgs e) { SavePathes(); } private void Page_Loaded(object sender, RoutedEventArgs e) { tbPathStartSoundPair.Text = GlobalSetting.pathMusicStartPair; tbPathStartForFiveSoundPair.Text = GlobalSetting.pathMusicForFiveMinutesStartPair; tbPathEndSoundPair.Text = GlobalSetting.pathMusicEndPair; tbPathEndForFiveSoundPair.Text = GlobalSetting.pathMusicForFiveMinutesEndPair; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Soko.Domain; using NHibernate; using Soko.Data; using NHibernate.Context; using Bilten.Dao; using Soko.Misc; namespace Soko.UI { public partial class BiracClana : Form { private int idClana = -1; private List<Clan> clanovi; public BiracClana(string naslov) { InitializeComponent(); this.Text = naslov; try { using (ISession session = NHibernateHelper.Instance.OpenSession()) using (session.BeginTransaction()) { CurrentSessionContext.Bind(session); clanovi = loadClanovi(); } } finally { CurrentSessionContext.Unbind(NHibernateHelper.Instance.SessionFactory); } setClanovi(clanovi); if (clanovi.Count > 0) SelectedClan = clanovi[0]; else SelectedClan = null; rbtClan.Checked = true; Font = Options.Instance.Font; } private List<Clan> loadClanovi() { List<Clan> result = new List<Clan>(DAOFactoryFactory.DAOFactory.GetClanDAO().FindAll()); Util.sortByPrezimeImeDatumRodjenja(result); return result; } private void setClanovi(List<Clan> clanovi) { cmbClan.Items.Clear(); foreach (Clan c in clanovi) { cmbClan.Items.Add(c.BrojPrezimeImeDatumRodjenja); } } private Clan SelectedClan { get { if (cmbClan.SelectedIndex >= 0) return clanovi[cmbClan.SelectedIndex]; else return null; } set { if (value == null || clanovi.IndexOf(value) == -1) cmbClan.SelectedIndex = -1; else cmbClan.SelectedIndex = clanovi.IndexOf(value); } } private void rbtCeoIzvestaj_CheckedChanged(object sender, System.EventArgs e) { if (rbtCeoIzvestaj.Checked) { cmbClan.Enabled = false; } } private void rbtClan_CheckedChanged(object sender, System.EventArgs e) { if (rbtClan.Checked) { cmbClan.Enabled = true; } } public bool CeoIzvestaj { get { return rbtCeoIzvestaj.Checked; } } public int IdClana { get { return idClana; } } private void btnOk_Click(object sender, System.EventArgs e) { if (SelectedClan != null) idClana = SelectedClan.Id; else idClana = -1; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlattformParent : MonoBehaviour { PlayerStateMachine player; Vector3 oldPos; private void Start() { oldPos = transform.position; } private void OnTriggerEnter(Collider other) { if (other.gameObject.tag.Equals("Player")) player = other.GetComponent<PlayerStateMachine>(); } private void OnTriggerExit(Collider other) { if (other.gameObject.tag.Equals("Player")) player = null; } private void LateUpdate() { var vel = transform.position - oldPos; if (player != null) player.transform.position += vel; oldPos = transform.position; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment5.Model { public class World { public Shape Shape { get; set; } } }
using System; using System.Collections.Generic; using ToDoApp.Db.Exceptions; using ToDoApp.Db.Interfaces; namespace ToDoApp.Db.Domain { public class User : IEntity { public Guid Id { get; private set; } public string Username { get; private set; } public string Email { get; private set; } public string Hash { get; private set; } public string Salt { get; private set; } public DateTime AddedAt { get; private set; } public virtual ICollection<ToDoList> TodoLists { get; private set; } public User(Guid id, string username, string email, string hash, string salt, DateTime addedAt) { SetId(id); SetUsername(username); SetEmail(email); SetPassword(hash, salt); SetAddedAt(addedAt); TodoLists = new List<ToDoList>(); } private void SetId(Guid id) { if(id == Guid.Empty) { throw new ToDOAppException(nameof(Id), "The id of user can not be empty!"); } Id = id; } private void SetUsername(string username) { if(string.IsNullOrEmpty(username)) // + regex { throw new ToDOAppException(nameof(username), "Username can not be empty!"); } Username = username; } public void SetPassword(string hash, string salt) { if(string.IsNullOrEmpty(hash) || string.IsNullOrEmpty(salt)) { throw new ToDOAppException("password", "There was problem with your password!"); } Hash = hash; Salt = salt; } private void SetEmail(string email) { if(string.IsNullOrEmpty(email)) { throw new ToDOAppException(nameof(email), "Email can not be null!"); } Email = email; } private void SetAddedAt(DateTime addedAt) { if(addedAt == DateTime.MinValue) { throw new ToDOAppException(nameof(addedAt), "There was problem with adding date!"); } AddedAt = addedAt; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; namespace Vasily { public class SqlModel { internal HashSet<string> IgnoreMembers; internal HashSet<string> RepeateMembers; public ConcurrentDictionary<string, string> ColumnToRealMap; public ConcurrentDictionary<string, string> RealToColumnMap; public ConcurrentDictionary<string, string> ALMap; public ModelStruction Struction; internal Type TypeHandler; public SqlModel(Type type) { TypeHandler = type; Struction = new ModelStruction(type); VasilyCache.StructionCache[type] = Struction; IgnoreMembers = new HashSet<string>(); RepeateMembers = new HashSet<string>(); ColumnToRealMap = new ConcurrentDictionary<string, string>(); RealToColumnMap = new ConcurrentDictionary<string, string>(); ALMap = new ConcurrentDictionary<string, string>(); } public string GetColumnName(string key) { if (RealToColumnMap.ContainsKey(key)) { return RealToColumnMap[key]; } return key; } public string GetRealName(string key) { if (ColumnToRealMap.ContainsKey(key)) { return ColumnToRealMap[key]; } return key; } public bool IsMaunally; public string Table; public string PrimaryKey; public string Insert; public string Update; public string Select; public string Delete; public string ConditionUpdate; public string ConditionDelete; public string ConditionSelect; public string SelectAll; public string CheckRepeate; public string GetPrimaryKey; } }
namespace E01_ReadTheTreeAndFind { using System; using System.Collections.Generic; using System.Linq; public class TreeUtils { public static void BuildTree(IList<Node<int>> myTree) { int N = int.Parse(Console.ReadLine()); for (int i = 0; i < N - 1; i++) { var tokens = Console.ReadLine().Split().Select(int.Parse).ToArray(); var parentValue = tokens[0]; var parentNode = myTree.FirstOrDefault(x => x.Value == parentValue); if (parentNode == null) { parentNode = new Node<int>(parentValue); myTree.Add(parentNode); } var childValue = tokens[1]; var childNode = myTree.FirstOrDefault(x => x.Value == childValue); if (childNode == null) { childNode = new Node<int>(childValue); myTree.Add(childNode); } parentNode.Children.Add(childNode); childNode.Parent = parentNode; } } public static Node<int> FindRoot(IList<Node<int>> myTree) { var nodes = myTree.Where(x => x.Parent == null); if (nodes.Count() != 1) { throw new ArgumentException("There are invalid number of roots in this tree!"); } var theRoot = nodes.First(); Console.WriteLine("The root is " + theRoot.ToString()); Console.WriteLine(); return theRoot; } public static void FindAllLeafs(IList<Node<int>> myTree) { Console.Write("All leafs are: "); Console.WriteLine(string.Join(", ", myTree .Where(x => x.Children.Count == 0) .Select(x => x.Value))); Console.WriteLine(); } public static void FindMiddleNodes(IList<Node<int>> myTree) { Console.Write("All middle nodes are: "); Console.WriteLine(string.Join(", ", myTree .Where(x => x.Children.Count > 0 && x.Parent != null) .Select(x => x.Value))); Console.WriteLine(); } public static void FindLongestPath(IList<Node<int>> myTree) { var leafs = myTree.Where(x => x.Children.Count == 0); var longestPaths = new List<int[]>(); foreach (var leaf in leafs) { var paths = new List<List<int>>(); var visited = new bool[myTree.Count]; visited[leaf.Value] = true; GetPathsFromNode(leaf, new List<int>() { leaf.Value }, visited, paths); if (longestPaths.Count > 0 && paths[0].Count > longestPaths[0].Length) { longestPaths.Clear(); } if (longestPaths.Count == 0 || paths[0].Count == longestPaths[0].Length) { foreach (var path in paths) { longestPaths.Add(path.ToArray()); } } } Console.WriteLine("All maximum paths have length of {0} and are: ", longestPaths[0].Length); Console.WriteLine(string.Join(Environment.NewLine, longestPaths.Select(x => string.Join(" -> ", x)))); Console.WriteLine(); } public static void FindPathsWithSum(int sum, IList<Node<int>> myTree) { var pathsWithSum = new List<int[]>(); foreach (var node in myTree) { var pathsFromThisNode = new List<List<int>>(); var visitedNodes = new bool[myTree.Count]; visitedNodes[node.Value] = true; GetPathsWithSumFromNode(node, sum, node.Value, new List<int>() { node.Value }, visitedNodes, pathsFromThisNode); pathsWithSum.AddRange(pathsFromThisNode.Select(x => x.ToArray())); } Console.WriteLine("All paths that have sum of {0} are: ", sum); Console.WriteLine(string.Join(Environment.NewLine, pathsWithSum.Select(x => string.Join(" -> ", x)))); Console.WriteLine(); } public static void FindSubTreesWithSum(int sum, IList<Node<int>> myTree) { var rootsOfSubtreesWithSum = new List<Node<int>>(); foreach (var node in myTree) { var subtreeSum = GetSumOfSubTreeWithRoot(node); if (subtreeSum == sum) { rootsOfSubtreesWithSum.Add(node); } } Console.WriteLine("All subtrees that have sum of {0} are: ", sum); foreach (var subRoot in rootsOfSubtreesWithSum) { PrintFromRoot(subRoot, 0); Console.WriteLine(new string('-', 40)); } Console.WriteLine(); } private static void PrintFromRoot(Node<int> root, int offset) { Console.Write(new string('-', offset) + root.Value); if (offset == 0) { Console.Write(" <- (root)"); } Console.WriteLine(); foreach (var child in root.Children) { PrintFromRoot(child, offset + 2); } } private static int GetSumOfSubTreeWithRoot(Node<int> node) { return GetSumFromNode(node); } private static int GetSumFromNode(Node<int> node) { if (node.Children.Count == 0) { return node.Value; } else { return node.Children.Select(GetSumFromNode).Sum() + node.Value; } } private static void GetPathsWithSumFromNode(Node<int> node, int sum, int sumSoFar, List<int> pathSoFar, bool[] visitedNodes, List<List<int>> pathsFromThisNode) { if (sumSoFar == sum) { pathsFromThisNode.Add(pathSoFar.ToList()); } if (sumSoFar > sum) { return; } foreach (var child in node.Children) { if (!visitedNodes[child.Value]) { visitedNodes[child.Value] = true; pathSoFar.Add(child.Value); GetPathsWithSumFromNode(child, sum, sumSoFar + child.Value, pathSoFar, visitedNodes, pathsFromThisNode); visitedNodes[child.Value] = false; pathSoFar.Remove(child.Value); } } if (node.Parent != null && !visitedNodes[node.Parent.Value]) { visitedNodes[node.Parent.Value] = true; pathSoFar.Add(node.Parent.Value); GetPathsWithSumFromNode(node.Parent, sum, sumSoFar + node.Parent.Value, pathSoFar, visitedNodes, pathsFromThisNode); visitedNodes[node.Parent.Value] = false; pathSoFar.Remove(node.Parent.Value); } } private static void GetPathsFromNode(Node<int> node, IList<int> pathSoFar, bool[] visited, IList<List<int>> maxPaths) { if (maxPaths.Count > 0 && pathSoFar.Count > maxPaths[0].Count) { maxPaths.Clear(); } if (maxPaths.Count == 0 || pathSoFar.Count == maxPaths[0].Count) { maxPaths.Add(pathSoFar.ToList()); } foreach (var child in node.Children) { if (!visited[child.Value]) { visited[child.Value] = true; pathSoFar.Add(child.Value); GetPathsFromNode(child, pathSoFar, visited, maxPaths); visited[child.Value] = false; pathSoFar.Remove(child.Value); } } if (node.Parent != null && !visited[node.Parent.Value]) { visited[node.Parent.Value] = true; pathSoFar.Add(node.Parent.Value); GetPathsFromNode(node.Parent, pathSoFar, visited, maxPaths); visited[node.Parent.Value] = false; pathSoFar.Remove(node.Parent.Value); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using SaleStore.Models; using SaleStore.Models.ViewModels; namespace SaleStore.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); } public DbSet<Product> Products { get; set; } public DbSet<Company> Companies { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<Campaign> Campaigns { get; set; } public DbSet<MailSetting> MailSettings { get; set; } public DbSet<Inbox> Inboxes { get; set; } public DbSet<SendMessage> SendMessages { get; set; } public DbSet<SaleStore.Models.Setting> Setting { get; set; } public DbSet<Role> ApplicationRoles { get; set; } public DbSet<SaleStore.Models.ApplicationUser> ApplicationUser { get; set; } public DbSet<Advertisement> Advertisements{ get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using SubSonic.Extensions; namespace Pes.Core { public partial class FileSystemFolder { public enum Paths { Pictures = 1, Videos = 2, Audios = 3 } } }
using UnityEngine; using System.Collections; /// <summary> /// Make persistant. /// </summary> public class makePersistant : MonoBehaviour { /// <summary> /// Copy of this object /// </summary> public static GameObject Instance; /// <summary> /// Makes the GameObject persistant through all scenes while also only allowing one single instance of the class /// </summary> void Awake () { if (Instance == null) { DontDestroyOnLoad(gameObject); Instance = this.gameObject; } else if (Instance != this) { Destroy (gameObject); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using LibrairieLabo2; using System.Data.Entity; using System.Linq; using System.Data.Entity.Infrastructure; namespace Labo2Test { [TestClass] public class UnitTest1 { [TestMethod] [ExpectedException(typeof(DbUpdateConcurrencyException))] public void DetecteLesEditionsConcurrentes() { var contextedeJohn = new CompanyContext(); var clientDeJohn = contextedeJohn.Customers.First(); var contextedeSarah = new CompanyContext(); var clientDeSarah = contextedeSarah.Customers.First(); clientDeJohn.AccountBalance += 1000; contextedeJohn.SaveChanges(); clientDeSarah.AccountBalance += 2000; contextedeSarah.SaveChanges(); } [TestMethod] public void InsertionFonctionnelle() { Database.SetInitializer(new DropCreateDatabaseAlways<CompanyContext>()); Customer quentin = new Customer(); quentin.City = "Moustier"; CompanyContext context = new CompanyContext(@"Data Source=vm-sql.iesn.be\stu3ig;Initial Catalog=DBIG3B3;User ID=IG3B3;Password=pwUserdb66"); context.Customers.Add(quentin); context.SaveChanges(); TestMethod2(); } public void TestMethod2() { CompanyContext context = new CompanyContext(@"Data Source=vm-sql.iesn.be\stu3ig;Initial Catalog=DBIG3B3;User ID=IG3B3;Password=pwUserdb66"); Assert.IsTrue(context.Customers.Count() >= 1); } } }
using System; using DevExpress.Mvvm.DataAnnotations; using DevExpress.Mvvm; namespace TestPort.ViewModels { [POCOViewModel] public class ViewModel1 { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; using Dapper; // @author: Fabio Cardoso namespace Haloween_Challenge { public partial class Form1 : Form { public Form1() { InitializeComponent(); staff.Enabled = false; films.Enabled = false; LogoutButton.Hide(); } private string connectionStringClient = "Server=127.0.0.1;Database=sakila;Uid=client;Pwd=$3cr3t3t"; private string connectionStringStaff = "Server=127.0.0.1;Database=sakila;Uid=staff;Pwd=$up3r$3cr3t"; private void FindButton_Click(object sender, EventArgs e) { // ToDO: BONUS points: Match whole word search. MySqlConnection con = new MySqlConnection(connectionStringClient); List<Films> films = new List<Films>(); String sql = $"SELECT film_id, title FROM sakila.film where title like '%{SearchTextBox.Text}%'"; films = con.Query<Films>(sql).ToList(); FilmsListBox.DataSource = films; FilmsListBox.DisplayMember = "title"; SearchBox.Text = string.Empty; // con.Close; } private void FilmsListBox_SelectedIndexChanged(object sender, EventArgs e) { } private void FilmsListBox_DoubleClick(object sender, EventArgs e) { Films selectedFilm = FilmsListBox.SelectedItem as Films; FilmDetails filmDetails = new FilmDetails(selectedFilm); DialogResult result = filmDetails.ShowDialog(this); filmDetails.Dispose(); } private void LoginButton_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(UserTextBox.Text)) { MessageBox.Show("Enter the user name!"); } else if (string.IsNullOrEmpty(PasswordTextBox.Text)) { MessageBox.Show("Enter the Password!"); } else if (UserTextBox.Text == ("guest") && PasswordTextBox.Text == ("£123")) { films.Enabled = true; LoginButton.Hide(); LogoutButton.Show(); UserTextBox.Enabled = false; PasswordTextBox.Enabled = false; } else if ((UserTextBox.Text == ("Mike")) || (UserTextBox.Text == ("Jon")) && PasswordTextBox.Text == ("£456")) { films.Enabled = true; staff.Enabled = true; LoginButton.Hide(); LogoutButton.Show(); UserTextBox.Enabled = false; PasswordTextBox.Enabled = false; pictureStaff.Hide(); } else { WrongText.Text = "Wrong credentials"; UserTextBox.Text = string.Empty; PasswordTextBox.Text = string.Empty; } } private void LogoutButton_Click(object sender, EventArgs e) { if (UserTextBox.Text == ("guest") && PasswordTextBox.Text == ("£123")) { films.Enabled = false; LogoutButton.Hide(); LoginButton.Show(); UserTextBox.Enabled = true; PasswordTextBox.Enabled = true; } else if ((UserTextBox.Text == ("Mike")) || (UserTextBox.Text == ("Jon")) && PasswordTextBox.Text == ("£456")) { films.Enabled = false; staff.Enabled = false; LogoutButton.Hide(); LoginButton.Show(); UserTextBox.Enabled = true; PasswordTextBox.Enabled = true; pictureStaff.Show(); } } private void ChangeButton_Click(object sender, EventArgs e) { MySqlConnection con = new MySqlConnection(connectionStringStaff); string sql = $"update staff set email = '{EmailTextBox.Text}' where staff_id = (select staff_id from staff where username = '{UserTextBox.Text}'"; var rowsAfected = con.Execute(sql); if (rowsAfected == 1) { MessageBox.Show("Email has ben Updated", "User MAnager", MessageBoxButtons.OK); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.Linq { using System.Collections; public static partial class FastLinq { public static IReadOnlyList<T> Skip<T>( this IReadOnlyList<T> source, int count) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return new SkipList<T>( source, count); } // TODO: Separate SkipList for Array/List would be faster at query time private sealed class SkipList<T> : IReadOnlyList<T>, ICanCopyTo<T> { private static T[] Empty = new T[]{}; private readonly IReadOnlyList<T> list; private readonly int skip; public void CopyTo(long sourceIndex, T[] dest, long count) { CanCopyHelper.CopyTo(this.list, sourceIndex + this.skip, dest, count); } public SkipList(IReadOnlyList<T> list, int skip) { if (skip >= list.Count) { this.list = Empty; this.skip = 0; return; } if (skip < 0) { // Analogous to what the BCL does skip = 0; } this.list = list; this.skip = skip; } public IEnumerator<T> GetEnumerator() { return GetEnumerable().GetEnumerator(); } private IEnumerable<T> GetEnumerable() { var listCount = this.list.Count; for (int i = skip; i < listCount; i++) { yield return this.list[i]; } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count => this.list.Count - this.skip; public T this[int index] { get => this.list[index + this.skip]; set => throw new NotSupportedException(); } } } }
using UnityEngine; public class WitcherVisualisation : MonoBehaviour { public RectTransform bar; public RectTransform point; public WitcherLogic logic; const float DEFAULT_BAR_WIDTH = 100; const float MIN_BAR_WIDTH = 10; public float CanvasWidth => 1000; public float MouseX { get { var pos01 = Mathf.Clamp01(Input.mousePosition.x / Screen.width); return pos01*CanvasWidth; } } public float BarX { get => bar.anchoredPosition.x + CanvasWidth / 2; set { var pos = bar.anchoredPosition; pos.x = value - CanvasWidth/2; bar.anchoredPosition = pos; } } public float BarWidth { get { return DEFAULT_BAR_WIDTH*bar.localScale.x; } set { var localScale = bar.localScale; localScale.x = Mathf.Clamp(value, MIN_BAR_WIDTH, DEFAULT_BAR_WIDTH) / DEFAULT_BAR_WIDTH; bar.localScale = localScale; } } public float PointX { get => point.anchoredPosition.x + CanvasWidth / 2; set => point.anchoredPosition = new Vector2(value - CanvasWidth/2, point.anchoredPosition.y); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ResetGameProgressButton : MonoBehaviour { public Sprite DoneIcon; public GameObject CentreTargetImage; public Transform LoadingBar; public Transform TextIndicator; private float TargetAmount = 100; private float CurrentAmount = 0; private float Speed = 50; private bool Clicked = false; // Start is called before the first frame update void Start() { Clicked = false; TextIndicator.GetComponent<Text>().text = ((int)CurrentAmount).ToString() + "%"; LoadingBar.GetComponent<Image>().fillAmount = (float)CurrentAmount / 100.0f; TextIndicator.gameObject.SetActive(false); } // Update is called once per frame void Update() { if (Clicked) { if (CurrentAmount<TargetAmount) { CurrentAmount += Speed * Time.deltaTime; TextIndicator.GetComponent<Text>().text = ((int)CurrentAmount).ToString() + "%"; LoadingBar.GetComponent<Image>().fillAmount = (float)CurrentAmount / 100.0f; } else { TextIndicator.gameObject.SetActive(false); LoadingBar.GetComponent<Image>().fillAmount = (float)CurrentAmount / 100.0f; CentreTargetImage.GetComponent<Image>().sprite = DoneIcon; Clicked = false; } } } public void OnClicked() { Clicked = true; TextIndicator.gameObject.SetActive(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CoreComponents.Threading { public abstract class CancelablePercentWorkItem : PercentWorkItem, IReset { bool myCancel; [ThreadSafe] public bool Cancel { [ThreadSafe] get { return Volatile.Read(ref myCancel); } [ThreadSafe] set { Volatile.Write(ref myCancel, value); } } public override void Reset() { base.Reset(); myCancel = false; } } }
using System; namespace OCP.Group.Backend { /** * @since 14.0.0 */ public interface IGroupDetailsBackend:IBackend { /** * @since 14.0.0 */ Pchp.Core.PhpArray getGroupDetails(string gid); } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.PlatformAbstractions; namespace Tiny.WebApp { public class Program { public static void Main(string[] args) { IConfigurationRoot Configuration = new ConfigurationBuilder() //.AddEnvironmentVariables() .AddCommandLine(args) .SetBasePath(PlatformServices.Default.Application.ApplicationBasePath) .AddJsonFile("hosting.json", false, false) .Build(); WebHost.CreateDefaultBuilder(args) //.UseEnvironment(Configuration["ASPNETCORE_ENVIRONMENT"]) .UseConfiguration(Configuration) .UseStartup<Startup>().Build().Run(); } } }
using AuditAppPcl.Entities; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace AuditAppPcl.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainPage : MasterDetailPage { public MainPage() { InitializeComponent(); masterPage.MenuListView.ItemSelected += OnItemSelected; } private void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = e.SelectedItem as MenuItems; if (item != null) { masterPage.MenuListView.SelectedItem = null; foreach (var menuitem in masterPage.MenuItemsList) { menuitem.IsSelected = false; } item.IsSelected = true; Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType)); IsPresented = false; } } } }
using System; namespace MyLibrary.Exceptions { public class InvalidPasswordException : Exception { } }
using System.Collections.Generic; namespace DAL { public class Role : BaseEntity { public string Name { get; set; } public virtual ICollection<UserRoles> UserRoles { get; set; } public virtual ICollection<RolePermissions> RolePermissions { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Model.DataEntity; using Model.Locale; using System.ComponentModel; using System.Linq.Expressions; namespace eIVOGo.Module.UI { public partial class SellerSelector : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { if (SelectAll) _Selector.Items.Add(new ListItem("全部", "")); var mgr = dsInv.CreateDataManager(); IQueryable<Organization> orgItems = Filter != null ? mgr.GetTable<Organization>().Where(Filter) : mgr.GetTable<Organization>(); _Selector.Items.AddRange(orgItems.Where( o => o.OrganizationCategory.Any( c => c.CategoryID == (int)Naming.CategoryID.COMP_E_INVOICE_B2C_SELLER || c.CategoryID == (int)Naming.CategoryID.COMP_VIRTUAL_CHANNEL)) .Select(o => new ListItem(String.Format("{0} {1}", o.ReceiptNo, o.CompanyName), o.CompanyID.ToString())).ToArray()); } } [Bindable(true)] public bool SelectAll { get; set; } [Bindable(true)] public Expression<Func<Organization, bool>> Filter { get;set; } public DropDownList Selector { get { return _Selector; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ThreeDB.Models; namespace ThreeDB.Controllers { public class DatasController : Controller { private readonly ThreeDBContext _context; public DatasController(ThreeDBContext context) { _context = context; } // GET: Datas public async Task<IActionResult> Index() { return View(await _context.Datas.ToListAsync()); } // GET: Datas/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var data = await _context.Datas .SingleOrDefaultAsync(m => m.Id == id); if (data == null) { return NotFound(); } return View(data); } // GET: Datas/Create public IActionResult Create() { return View(); } // POST: Datas/Create // 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> Create([Bind("Id,Name,Email")] Data data) { if (ModelState.IsValid) { _context.Add(data); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } return View(data); } // GET: Datas/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var data = await _context.Datas.SingleOrDefaultAsync(m => m.Id == id); if (data == null) { return NotFound(); } return View(data); } // POST: Datas/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("Id,Name,Email")] Data data) { if (id != data.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(data); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DataExists(data.Id)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } return View(data); } // GET: Datas/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var data = await _context.Datas .SingleOrDefaultAsync(m => m.Id == id); if (data == null) { return NotFound(); } return View(data); } // POST: Datas/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var data = await _context.Datas.SingleOrDefaultAsync(m => m.Id == id); _context.Datas.Remove(data); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } private bool DataExists(int id) { return _context.Datas.Any(e => e.Id == id); } } }
using Microsoft.EntityFrameworkCore; using SGL.ApplicationCore.Entity; using System; using System.Collections.Generic; using System.Text; namespace SGL.Infrastructure.Data { public class LanchoneteContext : DbContext { private object e; public LanchoneteContext(DbContextOptions<LanchoneteContext> options) : base(options) { } public DbSet <Pedido> Pedidos { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Pedido>().ToTable("Pedido"); #region Configuração de Pedido modelBuilder.Entity<Pedido>().Property(e => e.Nome) .HasColumnType("varchar(11)") .IsRequired(); modelBuilder.Entity<Pedido>().Property(e => e.Valor) .HasColumnType("varchar(200)") .IsRequired(); modelBuilder.Entity<Pedido>().Property(e => e.TipoLanche) .HasColumnType("varchar(200)") .IsRequired(); #endregion } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Plank : MonoBehaviour { public float waterOffset; public GameObject Water; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.position = new Vector2 (this.transform.position.x, (Water.transform.position.y + waterOffset)); } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Meziantou.Analyzer.Internals; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Meziantou.Analyzer.Rules; [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class MakeMethodStaticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_methodRule = new( RuleIdentifiers.MakeMethodStatic, title: "Make method static (deprecated, use CA1822 instead)", messageFormat: "Make method static (deprecated, use CA1822 instead)", RuleCategories.Design, DiagnosticSeverity.Info, isEnabledByDefault: true, description: "", helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.MakeMethodStatic)); private static readonly DiagnosticDescriptor s_propertyRule = new( RuleIdentifiers.MakePropertyStatic, title: "Make property static (deprecated, use CA1822 instead)", messageFormat: "Make property static (deprecated, use CA1822 instead)", RuleCategories.Design, DiagnosticSeverity.Info, isEnabledByDefault: true, description: "", helpLinkUri: RuleIdentifiers.GetHelpUri(RuleIdentifiers.MakePropertyStatic)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_methodRule, s_propertyRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); context.RegisterCompilationStartAction(ctx => { var analyzerContext = new AnalyzerContext(); ctx.RegisterSyntaxNodeAction(analyzerContext.AnalyzeMethod, SyntaxKind.MethodDeclaration); ctx.RegisterSyntaxNodeAction(analyzerContext.AnalyzeProperty, SyntaxKind.PropertyDeclaration); ctx.RegisterOperationAction(analyzerContext.AnalyzeDelegateCreation, OperationKind.DelegateCreation); ctx.RegisterCompilationEndAction(analyzerContext.CompilationEnd); }); } private sealed class AnalyzerContext { private readonly ConcurrentHashSet<ISymbol> _potentialSymbols = new(SymbolEqualityComparer.Default); private readonly ConcurrentHashSet<ISymbol> _cannotBeStaticSymbols = new(SymbolEqualityComparer.Default); public void CompilationEnd(CompilationAnalysisContext context) { foreach (var symbol in _potentialSymbols) { if (_cannotBeStaticSymbols.Contains(symbol)) continue; if (symbol is IMethodSymbol) { context.ReportDiagnostic(s_methodRule, symbol); } else if (symbol is IPropertySymbol) { context.ReportDiagnostic(s_propertyRule, symbol); } else { throw new InvalidOperationException("Symbol is not supported: " + symbol); } } } public void AnalyzeMethod(SyntaxNodeAnalysisContext context) { var node = (MethodDeclarationSyntax)context.Node; var methodSymbol = context.SemanticModel.GetDeclaredSymbol(node, context.CancellationToken); if (methodSymbol == null) return; if (context.Compilation == null) return; if (!IsPotentialStatic(methodSymbol) || methodSymbol.IsUnitTestMethod() || IsAspNetCoreMiddleware(context.Compilation, methodSymbol) || IsAspNetCoreStartup(context.Compilation, methodSymbol)) { return; } var body = (SyntaxNode?)node.Body ?? node.ExpressionBody; if (body == null) return; var operation = context.SemanticModel.GetOperation(body, context.CancellationToken); if (operation == null || HasInstanceUsages(operation)) return; _potentialSymbols.Add(methodSymbol); } public void AnalyzeProperty(SyntaxNodeAnalysisContext context) { var node = (PropertyDeclarationSyntax)context.Node; var propertySymbol = context.SemanticModel.GetDeclaredSymbol(node, context.CancellationToken); if (propertySymbol == null) return; if (!IsPotentialStatic(propertySymbol)) return; if (node.ExpressionBody != null) { var operation = context.SemanticModel.GetOperation(node.ExpressionBody, context.CancellationToken); if (operation == null || HasInstanceUsages(operation)) return; } if (node.AccessorList != null) { foreach (var accessor in node.AccessorList.Accessors) { var body = (SyntaxNode?)accessor.Body ?? accessor.ExpressionBody; if (body == null) return; var operation = context.SemanticModel.GetOperation(body, context.CancellationToken); if (operation == null || HasInstanceUsages(operation)) return; } } _potentialSymbols.Add(propertySymbol); } public void AnalyzeDelegateCreation(OperationAnalysisContext context) { var operation = (IDelegateCreationOperation)context.Operation; if (operation.Target is not IMethodReferenceOperation methodReference) return; // xaml cannot add event to static methods if (IsInXamlGeneratedFile(operation)) { _cannotBeStaticSymbols.Add(methodReference.Method); } } private static bool IsPotentialStatic(IMethodSymbol symbol) { return !symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride && !symbol.IsStatic && !symbol.IsInterfaceImplementation() && symbol.PartialDefinitionPart == null; } private static bool IsPotentialStatic(IPropertySymbol symbol) { return !symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride && !symbol.IsStatic && !symbol.IsInterfaceImplementation(); } private static bool HasInstanceUsages(IOperation operation) { if (operation == null) return false; var operations = new Queue<IOperation>(); operations.Enqueue(operation); while (operations.Count > 0) { var op = operations.Dequeue(); foreach (var child in op.GetChildOperations()) { operations.Enqueue(child); } switch (op) { case IInstanceReferenceOperation instanceReferenceOperation when instanceReferenceOperation.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance: return true; } } return false; } private static bool IsAspNetCoreMiddleware(Compilation compilation, IMethodSymbol methodSymbol) { if (string.Equals(methodSymbol.Name, "Invoke", StringComparison.Ordinal) || string.Equals(methodSymbol.Name, "InvokeAsync", StringComparison.Ordinal)) { var httpContextSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Http.HttpContext"); if (methodSymbol.Parameters.Length == 0 || !methodSymbol.Parameters[0].Type.IsEqualTo(httpContextSymbol)) return false; return true; } var imiddlewareSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Http.IMiddleware"); if (imiddlewareSymbol != null) { if (methodSymbol.ContainingType.Implements(imiddlewareSymbol)) { var invokeAsyncSymbol = imiddlewareSymbol.GetMembers("InvokeAsync").FirstOrDefault(); if (invokeAsyncSymbol != null) { var implementationMember = methodSymbol.ContainingType.FindImplementationForInterfaceMember(invokeAsyncSymbol); if (methodSymbol.IsEqualTo(implementationMember)) return true; } } } return false; } private static bool IsAspNetCoreStartup(Compilation compilation, IMethodSymbol methodSymbol) { // void ConfigureServices Microsoft.Extensions.DependencyInjection.IServiceCollection if (string.Equals(methodSymbol.Name, "ConfigureServices", StringComparison.Ordinal)) { var iserviceCollectionSymbol = compilation.GetBestTypeByMetadataName("Microsoft.Extensions.DependencyInjection.IServiceCollection"); if (methodSymbol.ReturnsVoid && methodSymbol.Parameters.Length == 1 && methodSymbol.Parameters[0].Type.IsEqualTo(iserviceCollectionSymbol)) return true; return false; } // void Configure Microsoft.AspNetCore.Builder.IApplicationBuilder if (string.Equals(methodSymbol.Name, "Configure", StringComparison.Ordinal)) { var iapplicationBuilder = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Builder.IApplicationBuilder"); if (methodSymbol.Parameters.Length > 0 && methodSymbol.Parameters[0].Type.IsEqualTo(iapplicationBuilder)) return true; return false; } return false; } private static bool IsInXamlGeneratedFile(IOperation operation) { return operation.Syntax.GetLocation().GetMappedLineSpan().Path?.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase) ?? false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace LearningCSharp { public class EmployeeTests { [Fact] public void CreatingAnEmployee() { var joe = new Employee("Joseph Schmidt", 520000); //joe.Name = "Joseph Schmidt"; //joe.Salary = 520000; Assert.Equal("Joseph Schmidt", joe.Name); Assert.Equal(520000, joe.Salary); Assert.Equal("unknown", joe.Email); var mary = new Employee("Mary Proto", 830000, "mary@aol.com"); Assert.Equal("mary@aol.com", mary.Email); } } public class Employee { //Having multiple methods with the same name is called overloading public Employee(string name, decimal salary):this(name, salary, "unknown") { } public Employee(string name, decimal salary, string email) { Name = name; Salary = salary; Email = email; } public string Name { get; private set; } public decimal Salary { get; private set; } public string Email { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json; namespace MyGame { class MyGame { /// <summary> /// The player. /// </summary> private Player player; /// <summary> /// Load Game /// </summary> /// <param name="stat"></param> public MyGame(GameStat stat = GameStat.NewGame) { if (stat == GameStat.NewGame) { // Initialization //File.Create("Player.json"); player = CreatePlayer(); // Player's Action Action(); // Save Player SaveGame(); } else if (stat == GameStat.Continue) { // Read Json file to read Player. player = Utils.ReadJson("Player.myprofile"); // Player's action Action(); // Save Player SaveGame(); } else throw new Exception("Unsuccessful in loading the game."); } /// <summary> /// Creates a new Player. /// </summary> /// <returns>new Player</returns> private Player CreatePlayer() { Console.Clear(); Console.Write("Please input your name: "); string name = Console.ReadLine(); return new Player(name); } /// <summary> /// Shows the menu. /// </summary> /// <returns>Player's choice</returns> private int ShowMenu() { Console.Clear(); Console.WriteLine("{0}({1}) : Level {2} | HP: {3} , Atk: {4} , Def: {5}", player.Name, player.UID, player.Level, player.HP, player.Attack, player.Defence); Console.WriteLine("Exp: {0} / {1}", player.Exp, Player.ExpNeeded(player.Level)); Console.WriteLine("Money: {0:C}", player.Money); Console.WriteLine("----------------Menu----------------"); Console.WriteLine("(1) Combat"); Console.WriteLine("(2) Shop"); Console.WriteLine("(8) Show Enemies"); Console.WriteLine("(9) Menu"); Console.WriteLine("(0) Save and Quit"); Console.Write("Choose to do: "); return Utils.UserInputToInt(9); } private void Action() { bool endGame = false; while (!endGame) { switch (ShowMenu()) { case 0: endGame = true; break; case 1: Combat(); break; case 2: Shop(); break; case 8: ShowEnemy(); break; case 9: break; default: Console.WriteLine("Invalid token, try type again..."); Console.ReadLine(); break; } } } /// <summary> /// Save game. /// </summary> private void SaveGame() { bool isWritten = Utils.WriteJson(player, "Player.myprofile"); if (!isWritten) { throw new Exception("Error saving game content."); } } // Todo private void Combat() { // Initialize combat Console.Clear(); Enemy enemy = Enemy.GetEnemy(player.Level); // Start Combat // Not Completed yet bool endCombat = false; while (!endCombat) { switch (ShowCombatUI(enemy)) { case 1: endCombat = PlayerAttack(enemy); break; case 9: continue; case 0: endCombat = player.CanEscape(); break; default: Console.WriteLine("Invalid token, try type again..."); Console.ReadLine(); continue; } if (!endCombat) { endCombat = EnemyAttack(enemy); } } //#if DEBUG // // Show Enemy (Debug use) // Console.WriteLine("{0} | HP: {1} , ID: {2} , LootExp: {3}", // enemy.Name, enemy.HP, enemy.ID, enemy.LootExp); // player.Exp += enemy.LootExp; // Console.ReadLine(); //#endif // Level up while (player.Level < Player.MAX_LEVEL) { if (player.Exp < Player.ExpNeeded(player.Level)) { break; } player.LevelUp(); } } private void Shop() { // Initialize Shop Console.Clear(); // Show shopping UI // Not finished yet bool endShopping = false; while (!endShopping) { switch (ShowShopUI()) { case 1: //endShopping = Buy(); break; case 9: continue; case 0: endShopping = true; break; default: Console.WriteLine("Invalid token, try type again..."); Console.ReadLine(); continue; } } } private int ShowCombatUI(Enemy enemy) { Console.Clear(); // Show status Console.Write("({0}){1} | ", enemy.ID, enemy.Name); if (enemy.currentHP <= 0.2f * enemy.HP) { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine("HP {0} / {1}", enemy.currentHP, enemy.HP); Console.ResetColor(); Console.WriteLine("----------------------------"); Console.Write("{0} | ", player.Name); if (player.currentHP <= 0.2f * player.HP) { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine("HP {0} / {1}", player.currentHP, player.HP); Console.ResetColor(); // Shows combat menu Console.WriteLine("------------Battle------------"); Console.WriteLine("(1) Attack"); Console.WriteLine("(0) Try escaping"); Console.Write("Choose one to do: "); return Utils.UserInputToInt(9); } /// <summary> /// Shows the list of enemies. /// </summary> private void ShowEnemy() { Console.Clear(); List<Enemy> enemies = Enemy.GetEnemyList(); Console.WriteLine("ID\t\tName\t\tHP\t\tAtk\tDef"); foreach (var enemy in enemies) { if (enemy.Name.ToCharArray().Length > 16) { string newName = enemy.Name.Substring(0, 15); Console.WriteLine("{0}\t\t{1}\t{2}\t\t{3}\t{4}", enemy.ID, newName, enemy.HP, enemy.Atk, enemy.Def); } else if (enemy.Name.ToCharArray().Length > 7) { Console.WriteLine("{0}\t\t{1}\t{2}\t\t{3}\t{4}", enemy.ID, enemy.Name, enemy.HP, enemy.Atk, enemy.Def); } else Console.WriteLine("{0}\t\t{1}\t\t{2}\t\t{3}\t{4}", enemy.ID, enemy.Name, enemy.HP, enemy.Atk, enemy.Def); } Console.ReadLine(); } /// <summary> /// Player's attack, if kills the enemy, return true. Otherwise, return false. /// </summary> /// <param name="enemy"></param> /// <returns></returns> private bool PlayerAttack(Enemy enemy) { int deal; if (enemy.Def >= player.Attack) { deal = 0; Console.WriteLine("{0}'s defence is too high, you can't deal any damage to it!!", enemy.Name); } else { deal = player.Attack - enemy.Def; Console.WriteLine("You dealt {0} damage to {1}.", deal, enemy.Name); } enemy.currentHP -= deal; Console.ReadLine(); if (enemy.currentHP <= 0) { Console.Clear(); player.Exp += enemy.LootExp; player.Money += enemy.LootMoney; Console.WriteLine("You win!!"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("You got {0} exp!", enemy.LootExp); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("You got {0:C}!", enemy.LootMoney); Console.ResetColor(); Console.ReadLine(); return true; } return false; } /// <summary> /// Enemy's attack, if kills the player, returns true. /// </summary> /// <param name="enemy"></param> /// <returns></returns> private bool EnemyAttack(Enemy enemy) { int deal; if (player.Defence >= enemy.Atk) deal = 0; else deal = enemy.Atk - player.Defence; player.currentHP -= deal; Console.WriteLine("You received {0} damage from {1}!", deal, enemy.Name); Console.ReadLine(); if (player.currentHP <= 0) { player.Die(); return true; } return false; } private int ShowShopUI() { Console.WriteLine("ShowShopUI() Method is called!"); Console.ReadLine(); return 0; } } enum GameStat { NewGame, Continue } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace DevAndersen.WpfChromelessWindow { public class ChromelessWindow : Window { protected ChromelessWindowViewModel viewModel; /// <summary> /// The height of the window's title bar. /// This is used to determine how much of the window's top can be used for dragging the window around, toggling resizable/maximized (double-clicking), as well as the right-click context menu. /// </summary> public double WindowTitleHeight { get; protected set; } public ChromelessWindow(double windowTitleHeight) : base() { WindowTitleHeight = windowTitleHeight; viewModel = new ChromelessWindowViewModel(this); DataContext = viewModel; Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("pack://application:,,,/DevAndersen.WpfChromelessWindow;component/ChromelessWindowStyle.xaml") }); Style = FindResource("ChromelessWindowStyle") as Style; } protected override void OnRenderSizeChanged(SizeChangedInfo e) { base.OnRenderSizeChanged(e); viewModel.WindowUpdate(); } protected override void OnLocationChanged(EventArgs e) { base.OnLocationChanged(e); viewModel.WindowUpdate(); } protected override void OnContentRendered(EventArgs e) { base.OnContentRendered(e); viewModel.WindowUpdate(); } protected override void OnDpiChanged(DpiScale oldDpi, DpiScale newDpi) { base.OnDpiChanged(oldDpi, newDpi); viewModel.WindowUpdate(); } } }
using System; using MySql.Data.MySqlClient; namespace PSW_lab4 { class UserDAO { public UserDAO() { } public UserDAO(string id, string name, string surname, string login, string password, string email) { this.Id = id; this.Name = name; this.Surname = surname; this.Login = login; this.Password = password; this.Email = email; } public UserDAO(string name, string surname, string login, string password, string email) { this.Name = name; this.Surname = surname; this.Login = login; this.Password = password; this.Email = email; } private string id; private string name; private string surname; private string login; private string password; private string email; public string Name { get => name; set => name = value; } public string Surname { get => surname; set => surname = value; } public string Login { get => login; set => login = value; } public string Password { get => password; set => password = value; } public string Email { get => email; set => email = value; } public string Id { get => id; set => id = value; } private static string server = "localhost"; private static string database = "psw_lab4"; private static string user = "admin"; private static string passwd = "admin"; private string connectionString = String.Format("server={0}; userid={1}; password={2}; database={3}", server, user, passwd, database); public void AddToDataBase() { string cmdText = String.Format( @"INSERT INTO psw_lab4.users (name,surname,login,password, email, permissions) VALUES ('{0}','{1}','{2}','{3}','{4}','USER');", Name, Surname, Login,Password, Email); using (MySqlConnection connection = new MySqlConnection(connectionString)) using (MySqlCommand command = new MySqlCommand(cmdText, connection)) { connection.Open(); command.ExecuteNonQuery(); connection.Clone(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WarlordController : PlayerController { // Public Attack Members public Transform attackPosition; public LayerMask whatIsEnemies; public float attackRange; public float damageWaitTime = 0.40f; // ----------- // Controllers // ----------- protected override void LeftClick() { // Check for nearby enemies Collider2D[] colliders = Physics2D.OverlapCircleAll(attackPosition.position, attackRange, whatIsEnemies); ArrayList enemies = new ArrayList(); for (int i = 0; i < colliders.Length; i++) { // If this enemy was already damaged, do nothing if (enemies.Contains(colliders[i].gameObject)) { continue; } // Slash the enemy StartCoroutine(OnDamagingEnemy(colliders[i].gameObject)); // Add to damaged enemies enemies.Add(colliders[i].gameObject); } } protected override void RightClick() { } // ------ // Events // ------ IEnumerator OnDamagingEnemy(GameObject enemy) { yield return new WaitForSeconds(damageWaitTime); if (enemy != null && enemy.GetComponent<EnemyController>() != null) { enemy.GetComponent<EnemyController>().GotSlashedBySword(); } } public override void OnGettingHit() { // If blocking, do not get hit if (!IsBlocking()) { base.OnGettingHit(); } } // ------ // Stats // ------ protected override void GotHit() { // If blocking, do not get hit if (!IsBlocking()) { base.GotHit(); } } public bool IsBlocking() { return animator.GetBool("IsRightClick"); } // --- // GUI // --- void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(attackPosition.position, attackRange); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BPiaoBao.DomesticTicket.Domain.Models.TravelPaper; using JoveZhao.Framework.DDD; namespace BPiaoBao.DomesticTicket.EFRepository { public class TravelGrantRecordRepository : BaseRepository<TravelGrantRecord>, ITravelGrantRecordRepository { public TravelGrantRecordRepository(IUnitOfWork uow, IUnitOfWorkRepository uowr) : base(uow, uowr) { } } }
// 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.Reflection; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace NtApiDotNet.Net.Firewall { /// <summary> /// Type of network event. /// </summary> [SDKName("FWPM_NET_EVENT_TYPE")] public enum FirewallNetEventType { [SDKName("FWPM_NET_EVENT_TYPE_IKEEXT_MM_FAILURE")] IkeExtMmFailure, [SDKName("FWPM_NET_EVENT_TYPE_IKEEXT_QM_FAILURE")] IkeExtQmFailure, [SDKName("FWPM_NET_EVENT_TYPE_IKEEXT_EM_FAILURE")] IkeExtEmFailure, [SDKName("FWPM_NET_EVENT_TYPE_CLASSIFY_DROP")] ClassifyDrop, [SDKName("FWPM_NET_EVENT_TYPE_IPSEC_KERNEL_DROP")] IPsecKernelDrop, [SDKName("FWPM_NET_EVENT_TYPE_IPSEC_DOSP_DROP")] IPsecDoSPDrop, [SDKName("FWPM_NET_EVENT_TYPE_CLASSIFY_ALLOW")] ClassifyAllow, [SDKName("FWPM_NET_EVENT_TYPE_CAPABILITY_DROP")] CapabilityDrop, [SDKName("FWPM_NET_EVENT_TYPE_CAPABILITY_ALLOW")] CapabilityAllow, [SDKName("FWPM_NET_EVENT_TYPE_CLASSIFY_DROP_MAC")] ClassifyDropMac, [SDKName("FWPM_NET_EVENT_TYPE_LPM_PACKET_ARRIVAL")] LpmPacketArrival } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
using ALM.ServicioAdminEmpresas.Datos; using ALM.ServicioAdminEmpresas.Entidades; using System; namespace ALM.ServicioAdminEmpresas.Negocio { public class NEmpresa { public string ValidarEmpresa(string dominio, int origen, short usuarios, short clientes, Int64 registros, string productKey, int fechaLlamada) { EValidarEmpresa eValidarEmpresa = null; try { eValidarEmpresa = new EValidarEmpresa() { Dominio = dominio, Origen = (Constante.Origen)origen, Usuarios = usuarios, Clientes = clientes, Registros = registros, ProductKey = productKey, FechaLlamada = int.Parse(DateTime.Now.ToString("yyyyMMdd")) }; if (DesEncriptarProductKey(ref eValidarEmpresa)) { new DEmpresa().ValidarEmpresa(ref eValidarEmpresa); if (eValidarEmpresa.CodIncidencia != "0") { eValidarEmpresa.Mensaje = GenerarMensaje(eValidarEmpresa.CodIncidencia); } } else { eValidarEmpresa.Mensaje = GenerarMensaje("Otro"); } EncriptarMensaje(ref eValidarEmpresa); return eValidarEmpresa.Mensaje; } finally { eValidarEmpresa = null; } } public void ValidarEmpresaSuperUsuario(ref EValidarEmpresa eValidarEmpresa) { if (DesEncriptarProductKey(ref eValidarEmpresa)) { new DEmpresa().ValidarEmpresaSuperUsuario(ref eValidarEmpresa); if (string.IsNullOrEmpty(eValidarEmpresa.CodIncidencia)) { eValidarEmpresa.Mensaje = GenerarMensaje("0"); } } else { eValidarEmpresa.Mensaje = GenerarMensaje("0"); } EncriptarMensaje(ref eValidarEmpresa); } public void ActualizarCodigoSuperAdministrador(ref EValidarEmpresa validar) { new DEmpresa().ActualizarCodigoSuperAdministrador(ref validar); } public bool LimpiarCodigoSuperAdministrador(ref EValidarEmpresa validar) { return new DEmpresa().LimpiarCodigoSuperAdministrador(ref validar); } private string GenerarMensaje(string codIncidencia) { return "@Dominio.com" + "|" + "ABC990101" + "|" + "0" + "-" + codIncidencia + "|" + "19010101"; } public void EncriptarMensaje(ref EValidarEmpresa eValidarEmpresa) { Utilerias.Utilerias utileria = null; try { utileria = new Utilerias.Utilerias(); utileria.Clave = ""; utileria.Clave = utileria.Descifrar(System.Configuration.ConfigurationManager.AppSettings["ALMCL01"]); eValidarEmpresa.Mensaje = utileria.Cifrar(eValidarEmpresa.Mensaje); } finally { utileria = null; } } public bool DesEncriptarProductKey(ref EValidarEmpresa eValidarEmpresa) { Utilerias.Utilerias utileria = null; string productKey = null; bool valido = false; try { if (!string.IsNullOrEmpty(eValidarEmpresa.ProductKey)) { utileria = new Utilerias.Utilerias(); utileria.Clave = ""; utileria.Clave = utileria.Descifrar(System.Configuration.ConfigurationManager.AppSettings["ALMCL01"]); utileria.ReemplazarMVC = true; productKey = utileria.Descifrar(eValidarEmpresa.ProductKey); if (!string.IsNullOrEmpty(productKey) && productKey.Contains("|") && productKey.Split('|').Length == 2) { eValidarEmpresa.ProductKey_Dominio = productKey.Split('|')[0]; eValidarEmpresa.ProductKey_RFC = productKey.Split('|')[1]; valido = eValidarEmpresa.ProductKey_Dominio == eValidarEmpresa.Dominio; } } return valido; } finally { utileria = null; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using TemporaryEmploymentCorp.DataAccess; using TemporaryEmploymentCorp.Models.Candidate; using TemporaryEmploymentCorp.Models.Editable; using TemporaryEmploymentCorp.Models.Session; namespace TemporaryEmploymentCorp.Models.Attendance { public class NewAttendanceModel : AttendanceEditModel { public NewAttendanceModel() : base(new DataAccess.EF.Attendance()) { InitializeRequiredFields(); } public ObservableCollection<CandidateSelection> ToCheckAttendance { get; } = new ObservableCollection<CandidateSelection>(); private IRepository _repository; public NewAttendanceModel(DataAccess.EF.Attendance model, IRepository repository, SessionModel selectedSession) : base(model) { _repository = repository; ToCheckAttendance.Clear(); var enrollments = _repository.Enrollment.GetRange(c => c.SessionCode == selectedSession.Model.SessionId); foreach (var enrollment in enrollments) { var candidates = _repository.Candidate.Get(c => c.CandidateId == enrollment.CandidateId); ToCheckAttendance.Add(new CandidateSelection(candidates)); //converts candidate into CandidateSelection for displaying in add attendance window } //removes candidates that are already marked present foreach (var item in selectedSession.PresentCandidatesList) { var toRemove = ToCheckAttendance.FirstOrDefault(c => c.Model.CandidateId == item.Model.CandidateId); ToCheckAttendance.Remove(toRemove); } } private void InitializeRequiredFields() { } } public class AttendanceEditModel : EditModelBase<DataAccess.EF.Attendance> { public AttendanceEditModel(DataAccess.EF.Attendance model) : base(model) { ModelCopy = CreateCopy(model); } private DataAccess.EF.Attendance CreateCopy(DataAccess.EF.Attendance model) { var copy = new DataAccess.EF.Attendance() { AttendanceId = model.AttendanceId, CandidateId = model.CandidateId, SessionId = model.SessionId, IsPresent = model.IsPresent }; return copy; } public int CandidateId { get { return _ModelCopy.CandidateId; } set { _ModelCopy.CandidateId = value; RaisePropertyChanged(nameof(CandidateId)); } } public string SessionId { get { return _ModelCopy.SessionId; } set { _ModelCopy.SessionId = value; RaisePropertyChanged(nameof(SessionId)); } } public bool? IsPresent { get { return _ModelCopy.IsPresent; } set { _ModelCopy.IsPresent = value; RaisePropertyChanged(nameof(IsPresent)); } } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace ATSBackend.Domain.Entities { public class Curriculo { public int IdCurriculo { get; set; } public string FormacaoAcademica { get; set; } [ForeignKey("IdCurriculo")] public virtual IEnumerable<Experiencia> Experiencias { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mirror; public class Unit : NetworkBehaviour { [SyncVar] public float movementSpeed = 2f; [SyncVar] public float timeToNextNode = .3f; [SyncVar] public float moveTimer = 0f; public SyncList<Node> path = new SyncList<Node>(); [SyncVar] public GameObject target; [SyncVar] public Grid gridObject; Node[,] grid; [SyncVar] Vector3 targetPos; [SyncVar] public Pathfinding pathfinder; float nodeDiameter; public void Init() { // pathfinder = pathGameObject.GetComponent<Pathfinding>(); // target = baseTarget; // Debug.Log(pathfinder); // //this.pathfinder = pathfinder; gridObject = pathfinder.gameObject.GetComponent<Grid>(); grid = gridObject.grid; // nodeDiameter = gridObject.nodeDiameter; path = pathfinder.FindPath(this.transform.position, target.transform.position); // Debug.Log(path); //path.Reverse(); } private void OnDrawGizmos() { if (grid != null) { foreach (Node n in grid) { Gizmos.color = (n.walkable) ? Color.white : Color.red; if (path != null) if (path.Contains(n)) Gizmos.color = Color.black; Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter - .1f)); } } } private void Update() { float dt = Time.deltaTime; if (moveTimer >= timeToNextNode && path.Count > 0) { Debug.Log(path[path.Count - 1].worldPosition); //MoveUnit(this.transform.position, path[path.Count - 1]); targetPos = path[path.Count - 1].worldPosition; path.RemoveAt(path.Count - 1); moveTimer = 0f; } else { if (this.transform.position != targetPos) { this.transform.position = Vector3.Lerp(this.transform.position, targetPos, movementSpeed * dt); } } moveTimer += dt; } void MoveUnit(Vector3 currentPos, Node targetPos) { this.transform.position = Vector3.Lerp(currentPos, targetPos.worldPosition, movementSpeed); } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace Tff.Panzer.Models.Geography { public class WeatherZone { public int WeatherZoneId { get; set; } public String WeatherZoneDescription { get; set; } public WeatherZoneEnum WeatherZoneEnum { get { switch (WeatherZoneId) { case 0: return WeatherZoneEnum.Desert; case 1: return WeatherZoneEnum.Mediterrian; case 2: return WeatherZoneEnum.WesternEurope; case 3: return WeatherZoneEnum.EasternEurope; default: return WeatherZoneEnum.WesternEurope; } } } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Primitives; using SkillsGardenApi.Controllers; using SkillsGardenApi.Models; using SkillsGardenApi.Repositories; using SkillsGardenApi.Services; using SkillsGardenApiTests.Factory; using SkillsGardenApiTests.Mock; using SkillsGardenDTO.Error; using System.Collections.Generic; using System.Net.Http; using Xunit; namespace SkillsGardenApiTests { public class LocationTests : UnitTest { private LocationRepository locationRepository; private LocationService locationService; private LocationController locationController; private IAzureService azureService; public LocationTests() { // create empty database this.locationRepository = new LocationRepository(CreateEmptyDatabase()); this.azureService = new AzureServiceMock(); this.locationService = new LocationService(this.locationRepository, this.azureService); // create location controller this.locationController = new LocationController(this.locationService); } ////////////////////////////////////////////// GET ALL ////////////////////////////////////////////// [Fact] public async void GetAllLocationsTest() { await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(1)); await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(2)); await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(3)); HttpRequest request = HttpRequestFactory.CreateGetRequest(); ObjectResult result = (ObjectResult)await this.locationController.LocationGetAll(request); List<Location> locations = (List<Location>)result.Value; // status code should be 200 OK Assert.Equal(200, result.StatusCode); // amount of found locations should be 3 Assert.Equal(3, locations.Count); } ////////////////////////////////////////////// GET SPECIFIC ID ////////////////////////////////////////////// [Fact] public async void GetSpecificLocationTest() { await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(10)); HttpRequest request = HttpRequestFactory.CreateGetRequest(); ObjectResult result = (ObjectResult)await this.locationController.LocationGet(request, 10); Location location = (Location)result.Value; // status code should be 200 OK Assert.Equal(200, result.StatusCode); // check if the right location was found Assert.Equal(10, location.Id); } //location not found [Fact] public async void GetSpecificLocationNotFoundTest() { await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(10)); HttpRequest request = HttpRequestFactory.CreateGetRequest(); ObjectResult result = (ObjectResult)await this.locationController.LocationGet(request, 5); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 404 not found Assert.Equal(404, result.StatusCode); Assert.Equal(ErrorCode.LOCATION_NOT_FOUND, errorResponse.ErrorCodeEnum); } ////////////////////////////////////////////// CREATE NEW LOCATION ////////////////////////////////////////////// [Fact] public async void CreateNewLocationAsAdminTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); // status code should be 200 OK Assert.Equal(200, result.StatusCode); } [Fact] public async void CreateNewLocationAsNonAdminTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult resultUser = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.userClaim); ObjectResult resultOrganiser = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.organiserClaim); ErrorResponse errorResponseUser = (ErrorResponse)resultUser.Value; ErrorResponse errorResponseOrganiser = (ErrorResponse)resultOrganiser.Value; // status code should be 403 FORBIDDEN Assert.Equal(403, resultUser.StatusCode); Assert.Equal(403, resultOrganiser.StatusCode); Assert.Equal(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS, errorResponseUser.ErrorCodeEnum); Assert.Equal(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS, errorResponseOrganiser.ErrorCodeEnum); } [Fact] public async void CreateNewLocationAsAdminNameTooLongTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam op de grote buitenheuvel naast het postkantoor"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errormessage = "Name can not be longer than 50 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("Name can not be longer than 50 characters", errorResponse.Message); } [Fact] public async void CreateNewLocationAsAdminNameTooShortTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "X"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errormessage = "City must be at least 2 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("Name must be at least 2 characters", errorResponse.Message); } [Fact] public async void CreateNewLocationAsAdminCityTooLongTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Wales"); formdata.Add("City", "Llanfair­pwllgwyngyll­gogery­chwyrn­drobwll­llan­tysilio­gogo­goch"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errorcode = "City can not be longer than 50 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("City can not be longer than 50 characters", errorResponse.Message); } [Fact] public async void CreateNewLocationAsAdminCityTooShortTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Wales"); formdata.Add("City", "X"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errorcode = "City must be at least 2 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("City must be at least 2 characters", errorResponse.Message); } [Fact] public async void CreateNewLocationAsAdminLatNoDoubleTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "één punt twee drie negen vier"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errorcode = "Lat must be a double" Assert.Equal(400, result.StatusCode); Assert.Equal("Lat must be a double", errorResponse.Message); } [Fact] public async void CreateNewLocationAsAdminLngNoDoubleTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "1.2134234"); formdata.Add("Lng", "één punt twee drie negen vier"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errorcode = "Lat must be a double" Assert.Equal(400, result.StatusCode); Assert.Equal("Lng must be a double", errorResponse.Message); } [Fact] public async void CreateNewLocationAsAdminEmptyNameTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "1.2134234"); formdata.Add("Lng", "3.2341234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_REQUEST_BODY Assert.Equal(400, result.StatusCode); Assert.Equal(ErrorCode.INVALID_REQUEST_BODY, errorResponse.ErrorCodeEnum); } [Fact] public async void CreateNewLocationAsAdminEmptyCityTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("Lat", "1.2134234"); formdata.Add("Lng", "2.1657865"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_REQUEST_BODY Assert.Equal(400, result.StatusCode); Assert.Equal(ErrorCode.INVALID_REQUEST_BODY, errorResponse.ErrorCodeEnum); } [Fact] public async void CreateNewLocationAsAdminEmptyLatTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("City", "Amsterdam"); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("Lng", "1.1234123"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_REQUEST_BODY Assert.Equal(400, result.StatusCode); Assert.Equal(ErrorCode.INVALID_REQUEST_BODY, errorResponse.ErrorCodeEnum); } [Fact] public async void CreateNewLocationAsAdminEmptyLngTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("City", "Amsterdam"); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("Lat", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_REQUEST_BODY Assert.Equal(400, result.StatusCode); Assert.Equal(ErrorCode.INVALID_REQUEST_BODY, errorResponse.ErrorCodeEnum); } [Fact] public async void CreateNewLocationAsAdminNoImageTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post, "empty"); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_REQUEST_BODY Assert.Equal(400, result.StatusCode); Assert.Equal(ErrorCode.INVALID_REQUEST_BODY, errorResponse.ErrorCodeEnum); } [Fact] public async void CreateNewLocationAsAdminUseGifAsImageTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post, "gif"); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 Assert.Equal(400, result.StatusCode); } [Fact] public async void CreateNewLocationAsAdminImageToBigTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam Centrum"); formdata.Add("Lat", "1.2345235"); formdata.Add("Lng", "1.2134234"); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post, "toBigImage"); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 Assert.Equal(400, result.StatusCode); } [Fact] public async void CreateNewLocationAsAdminEmptyFormdataTest() { Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); HttpRequest requestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Post, "empty"); ObjectResult result = (ObjectResult)await this.locationController.LocationCreate(requestmessage, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_REQUEST_BODY Assert.Equal(400, result.StatusCode); Assert.Equal(ErrorCode.INVALID_REQUEST_BODY, errorResponse.ErrorCodeEnum); } ////////////////////////////////////////////// UPDATE LOCATION ////////////////////////////////////////////// [Fact] public async void UpdateLocationAsAdminTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden IJmuiden"); formdata.Add("City", "IJmuiden Noord"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); Location resultLocation = (Location)result.Value; // status code should be 200 OK Assert.Equal(200, result.StatusCode); // the email should be updated Assert.Equal("Skillgarden IJmuiden", resultLocation.Name); } [Fact] public async void UpdateLocationAsNonAdminTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(10)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden IJmuiden"); formdata.Add("City", "IJmuiden Noord"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult resultUser = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.userClaim); ObjectResult resultOrganiser = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 10, this.organiserClaim); ErrorResponse errorMessageUser = (ErrorResponse)resultUser.Value; ErrorResponse errorMessageOrganiser = (ErrorResponse)resultOrganiser.Value; // status code should be 403 FORBIDDEN Assert.Equal(403, resultUser.StatusCode); Assert.Equal(403, resultOrganiser.StatusCode); Assert.Equal(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS, errorMessageUser.ErrorCodeEnum); Assert.Equal(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS, errorMessageOrganiser.ErrorCodeEnum); } [Fact] public async void UpdateLocationAsAdminNotFoundTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam op de grote buitenheuvel naast het postkantoor"); formdata.Add("City", "IJmuiden Noord"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 10, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 404 not found Assert.Equal(404, result.StatusCode); Assert.Equal(ErrorCode.LOCATION_NOT_FOUND, errorResponse.ErrorCodeEnum); } [Fact] public async void UpdateLocationAsAdminNameTooLongTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam op de grote buitenheuvel naast het postkantoor"); formdata.Add("City", "IJmuiden Noord"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errormessag = "Name can not be longer than 50 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("Name can not be longer than 50 characters", errorResponse.Message); } [Fact] public async void UpdateLocationAsAdminNameTooShortTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "X"); formdata.Add("City", "IJmuiden Noord"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errormessag = "Name must be at least 2 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("Name must be at least 2 characters", errorResponse.Message); } [Fact] public async void UpdateLocationAsAdminCityTooLongTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Wales"); formdata.Add("City", "Llanfair­pwllgwyngyll­gogery­chwyrn­drobwll­llan­tysilio­gogo­goch"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errorcode = "City can not be longer than 50 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("City can not be longer than 50 characters", errorResponse.Message); } [Fact] public async void UpdateLocationAsAdminCityTooShortTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Wales"); formdata.Add("City", "X"); formdata.Add("Lat", "1.3214"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 and errorcode = "City must be at least 2 characters" Assert.Equal(400, result.StatusCode); Assert.Equal("City must be at least 2 characters", errorResponse.Message); } [Fact] public async void UpdateLocationAsAdminLatNoDoubleTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "één punt twee drie negen vier"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_DOUBLEINPUT Assert.Equal(400, result.StatusCode); Assert.Equal("Lat must be a double", errorResponse.Message); } [Fact] public async void UpdateLocationAsAdminLngNoDoubleTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "1.2343"); formdata.Add("Lng", "één punt twee drie negen vier"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 INVALID_DOUBLEINPUT Assert.Equal(400, result.StatusCode); Assert.Equal("Lng must be a double", errorResponse.Message); } [Fact] public async void UpdateLocationAsAdminUseGifAsImageTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "1.2343"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put, "gif"); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 Assert.Equal(400, result.StatusCode); } [Fact] public async void UpdateLocationAsAdminImageToBigTest() { // create user await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(5)); // create updated user Dictionary<string, StringValues> formdata = new Dictionary<string, StringValues>(); formdata.Add("Name", "Skillgarden Amsterdam"); formdata.Add("City", "Amsterdam"); formdata.Add("Lat", "1.2343"); formdata.Add("Lng", "1.2343"); // create put request HttpRequest putrequestmessage = await HttpRequestFactory.CreateFormDataRequest(formdata, HttpMethod.Put, "toBigImage"); ObjectResult result = (ObjectResult)await this.locationController.LocationUpdate(putrequestmessage, 5, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 400 Assert.Equal(400, result.StatusCode); } ////////////////////////////////////////////// DELETE LOCATION ////////////////////////////////////////////// [Fact] public async void DeleteLocationAsAdminTest() { // create location await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(9000)); // create delete request HttpRequest deleteRequest = HttpRequestFactory.CreateDeleteRequest(); OkResult result = (OkResult)await this.locationController.LocationDelete(deleteRequest, 9000, this.adminClaim); // status code should be 200 OK Assert.Equal(200, result.StatusCode); // the account should be removed Assert.Empty(await this.locationRepository.ListAsync()); } [Fact] public async void DeleteLocationAsNonAdminTest() { // create location await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(9000)); // create delete request HttpRequest deleteRequest = HttpRequestFactory.CreateDeleteRequest(); ObjectResult resultUser = (ObjectResult)await this.locationController.LocationDelete(deleteRequest, 9000, this.userClaim); ObjectResult resultOrganiser = (ObjectResult)await this.locationController.LocationDelete(deleteRequest, 9000, this.organiserClaim); ErrorResponse errorMessageUser = (ErrorResponse)resultUser.Value; ErrorResponse errorMessageOrganiser = (ErrorResponse)resultOrganiser.Value; // status code should be 403 FORBIDDEN Assert.Equal(403, resultUser.StatusCode); Assert.Equal(403, resultOrganiser.StatusCode); Assert.Equal(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS, errorMessageUser.ErrorCodeEnum); Assert.Equal(ErrorCode.UNAUTHORIZED_ROLE_NO_PERMISSIONS, errorMessageOrganiser.ErrorCodeEnum); } [Fact] public async void DeleteLocationAsAdminNotFoundTest() { // create location await this.locationRepository.CreateAsync(LocationFactory.CreateLocation(9000)); // create delete request HttpRequest deleteRequest = HttpRequestFactory.CreateDeleteRequest(); ObjectResult result = (ObjectResult)await this.locationController.LocationDelete(deleteRequest, 1, this.adminClaim); ErrorResponse errorResponse = (ErrorResponse)result.Value; // status code should be 404 not found Assert.Equal(404, result.StatusCode); Assert.Equal(ErrorCode.LOCATION_NOT_FOUND, errorResponse.ErrorCodeEnum); } } }
using Accounting.DataAccess; using System; using System.Data; using System.Web; using System.Web.UI.WebControls; namespace AccSys.Web.DbControls { public class BusinessSubTypeDropDownList : DropDownList { private string _NullItemValue = null; public string NullItemValue { get { return _NullItemValue; } set { _NullItemValue = value; } } private string _NullItemText = string.Empty; public string NullItemText { get { return _NullItemText; } set { _NullItemText = value; } } public BusinessSubTypeDropDownList() : base() { //this.CssClass = "WindowsStyle"; this.AppendDataBoundItems = false; this.Load += new EventHandler(BusinessSubTypeDropDownList_Load); } public void Bind(int typeId=0) { string where = " 1 = 1"; if(typeId > 0) { where = string.Format(" BusinessTypeID={0} ", typeId); } DataTable dtdata = CommonDataSource.GetData(" BusinessSubTypeID, BusinessTypeID, Name ", "BusinessSubType", where, "Name", 100, 0); if (_NullItemValue != null) { DataRow dr = dtdata.NewRow(); dr["BusinessSubTypeID"] = _NullItemValue; dr["Name"] = _NullItemText; dtdata.Rows.InsertAt(dr, 0); } this.DataSource = dtdata; this.DataTextField = "Name"; this.DataValueField = "BusinessSubTypeID"; this.DataBind(false); } void BusinessSubTypeDropDownList_Load(object sender, EventArgs e) { try { //if (!this.Page.IsPostBack) //{ Bind(); //} } catch (Exception ex) { throw ex; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Release2.ViewModels { public class PerformanceCriterionViewModel { public int ReviewId { get; set; } public int? Score { get; set; } public int CompetencyId { get; set; } [Display(Name = "Competency Name")] public string CompetencyName { get; set; } [Display(Name = "Scores")] public int? TotalScore { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Threading.Tasks; using System.Data.SqlClient; namespace Secretaria { class BaseSelectBimestre { public string conexao() { return @"Data Source = PC-SERVIDOR,1433\sqlexpress ; Database = bdatafinal; User Id = sa; Password = yerdna"; } string strSelect = @" SELECT TOP 1000 [id_Bimestre] ,bimestre ,tbl_bimestre.[id_aluno] ,tbl_Alunos.nome ,tblAno.ano ,tbl_turno.turno ,tbl_professor.professor ,tbl_bimestre.[ano] ,[port] ,[mat] ,[hist] ,[geog] ,[ciencia] ,[arte] ,[religiao] ,[ingles] ,[fisica] ,[ap] ,[r] ,[faltas] FROM [BDAtaFinal].[dbo].[tbl_Bimestre] join tbl_Alunos on tbl_Bimestre.id_aluno = tbl_alunos.id_aluno join tbl_turma on tbl_Bimestre.id_turma = tbl_turma.id_turma join tbl_professor on tbl_turma.id_professor = tbl_professor.id_prof join tbl_turno on tbl_turma.id_turno = tbl_turno.id_turno join tblAno on tbl_turma.id_ano = tblAno.id_Ano "; string final = " order by tblAno.ano, turno, professor, nome "; public void select(DataTable tabela, string _select, string ano) { try{ SqlConnection con = new SqlConnection(conexao()); SqlDataAdapter adp = new SqlDataAdapter(_select + " where ano = "+ ano, con); adp.Fill(tabela); }catch { System.Windows.Forms. MessageBox.Show("Deu ruim"); } } public void select2(DataTable tabela, string _select) { try { SqlConnection con = new SqlConnection(conexao()); SqlDataAdapter adp = new SqlDataAdapter(_select, con); adp.Fill(tabela); } catch { System.Windows.Forms.MessageBox.Show("Deu ruim"); } } public void SelectSemFiltro(DataTable tabela, int ano) { try { SqlConnection con = new SqlConnection(conexao()); SqlDataAdapter adp = new SqlDataAdapter(string.Format(" {0} where tbl_bimestre.ano = {1} {2}",strSelect ,ano, final), con); adp.Fill(tabela); } catch { System.Windows.Forms.MessageBox.Show("Deu ruim"); } } public void SelectComFiltro(DataTable tabela, int bm, int ano) { try { SqlConnection con = new SqlConnection(conexao()); SqlCommand comando = new SqlCommand(); comando.Connection = con; comando.CommandText = strSelect + " where bimestre = " + bm +" and tbl_bimestre.ano = "+ ano + final; SqlDataAdapter adp = new SqlDataAdapter(comando); adp.Fill(tabela); } catch { System.Windows.Forms.MessageBox.Show("Deu ruim"); } } public void SelectComTurma(DataTable tabela, int Turma) { try { SqlConnection con = new SqlConnection(conexao()); SqlCommand comando = new SqlCommand(); comando.Connection = con; comando.CommandText = strSelect + " where tbl_Turma.id_Ano = " + Turma + final; SqlDataAdapter adp = new SqlDataAdapter(comando); adp.Fill(tabela); } catch { System.Windows.Forms.MessageBox.Show("Deu ruim"); } } public void SelectComturno(DataTable tabela, string Turno) { try { SqlConnection con = new SqlConnection(conexao()); SqlCommand comando = new SqlCommand(); comando.Connection = con; comando.CommandText = strSelect + " where tbl_turno.Turno ='" + Turno + "'" + final; SqlDataAdapter adp = new SqlDataAdapter(comando); adp.Fill(tabela); } catch { System.Windows.Forms.MessageBox.Show("Deu ruim"); } } public void SelectAnoETurno(DataTable tabela, int Turma,string Turno) { try { SqlConnection con = new SqlConnection(conexao()); SqlCommand comando = new SqlCommand(); comando.Connection = con; comando.CommandText = strSelect + " where tbl_Aluno.id_Turma = " + Turma + "and tbl_Turno.Turno = '" + Turno + "'" + final; SqlDataAdapter adp = new SqlDataAdapter(comando); adp.Fill(tabela); } catch { System.Windows.Forms.MessageBox.Show("Deu ruim"); } } public void SelectCompletoBimestre(DataTable tabela, int Bimestre, int id_turma ) { try { SqlConnection con = new SqlConnection(conexao()); SqlCommand comando = new SqlCommand(); comando.Connection = con; comando.CommandText = string.Format("{0} where bimestre ={1} and tbl_bimestre.id_turma = {2} {3}", strSelect, Bimestre, id_turma,final); SqlDataAdapter adp = new SqlDataAdapter(comando); adp.Fill(tabela); } catch(Exception erro) { System.Windows.Forms.MessageBox.Show("Deu ruim\n\t" + erro.ToString()); } } public void SelectPeloId(DataTable tabela, int id, int _ano) { try { SqlConnection con = new SqlConnection(conexao()); SqlCommand comando = new SqlCommand(); comando.Connection = con; comando.CommandText = string.Format("{0} where tbl_bimestre.id_Aluno = {1} and tbl_bimestre.ano = {2} {3}",strSelect, id,_ano,final); SqlDataAdapter adp = new SqlDataAdapter(comando); adp.Fill(tabela); } catch (Exception erro) { System.Windows.Forms.MessageBox.Show("Deu ruim\n\t" + erro.ToString()); } } public void FiltroPorNome(string nome, string ano, DataTable tabela) { if (nome != "") { SqlConnection con = new SqlConnection(conexao()); string str = strSelect + "where tbl_bimestre.ano = '" + ano + "' and nome like '%" + nome + "%' " + final; SqlCommand comando = new SqlCommand(str, con); SqlDataAdapter atp = new SqlDataAdapter(comando); atp.Fill(tabela); } else { SelectSemFiltro(tabela, int.Parse(ano)); } } public void FiltroPorNome(int bimestre ,string nome, string ano, DataTable tabela) { if (nome != "") { SqlConnection con = new SqlConnection(conexao()); string str = strSelect + "where tbl_bimestre.ano = '" + ano + "' and nome like '%" + nome + "%' and bimestre = "+ bimestre + final; SqlCommand comando = new SqlCommand(str, con); SqlDataAdapter atp = new SqlDataAdapter(comando); atp.Fill(tabela); } else { SelectSemFiltro(tabela, int.Parse(ano)); } } } }
using UnityEngine; using System.Collections; public class RocketDrill : MonoBehaviour { private bool _rocketDrillP1 = false; public GameObject _rocketPrefab; [SerializeField] private GameObject _portal; [SerializeField] private GameObject _bulletPrefab; public bool RocketDrillP1 { get { return _rocketDrillP1; } set { _rocketDrillP1 = value; } } private bool _rocketDrillP2 = false; public bool RocketDrillP2 { get { return _rocketDrillP2; } set { _rocketDrillP2 = value; } } private GameObject _planeP1; private GameObject _planeP2; private GameObject _PlayerP1; private GameObject _PlayerP2; // Use this for initialization void Start () { if (GameObject.FindObjectOfType<ConfirmScript>().Tutorial == false) { _planeP1 = GameObject.FindObjectOfType<Player1LevelScript>().gameObject; _planeP2 = GameObject.FindObjectOfType<Player2LevelScript>().gameObject; _PlayerP1 = GameObject.FindObjectOfType<Player1MoveScript>().gameObject; _PlayerP2 = GameObject.FindObjectOfType<Player2MoveScript>().gameObject; } else { _planeP1 = GameObject.FindObjectOfType<Player1LevelScript>().gameObject; _PlayerP1 = GameObject.FindObjectOfType<Player1MoveScript>().gameObject; } } // Update is called once per frame void Update () { if (_rocketDrillP1) { if (GameObject.FindObjectOfType<ConfirmScript>().Tutorial == false) { _rocketDrillP1 = false; //GameObject drill = GameObject.CreatePrimitive(PrimitiveType.Cylinder); GameObject drill = Instantiate(_rocketPrefab); Camera camera = GameObject.FindObjectOfType<Player2MoveScript>().GetComponentInChildren<Camera>(); Vector3 position; position = camera.transform.position + camera.transform.forward + new Vector3(0, 1, 2); drill.transform.position = position; drill.transform.parent = _planeP2.transform; // _portal.gameObject.transform.position = camera.transform.position + camera.transform.forward + new Vector3(0, 6f, 10); //_bulletPrefab.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + 3); //Instantiate(_bulletPrefab).GetComponent<Transform>(); Vector3 fireWallPos = _PlayerP2.transform.position; _portal = (GameObject)Instantiate(_portal, fireWallPos, Quaternion.identity); _portal.transform.localEulerAngles = new Vector3(90, 0, 0); //_portal.transform.localEulerAngles = new Vector3(0, 90, 0); _portal.GetComponent<ParticleSystem>().Play(); _portal.GetComponent<ParticleSystem>().loop = false; } else { } } if (_rocketDrillP2) { _rocketDrillP2 = false; //GameObject drill = GameObject.CreatePrimitive(PrimitiveType.Cylinder); GameObject drill = Instantiate(_rocketPrefab); Camera camera = GameObject.FindObjectOfType<Player1MoveScript>().GetComponentInChildren<Camera>(); Vector3 position; position = camera.transform.position + camera.transform.forward + new Vector3(0, -1, 2); drill.transform.position = position; drill.transform.parent = _planeP1.transform; //_portal.gameObject.transform.position = camera.transform.position + camera.transform.forward + new Vector3(0, -6f, 10); _portal.gameObject.transform.localRotation = new Quaternion(90, _portal.gameObject.transform.rotation.y, _portal.gameObject.transform.rotation.z, _portal.gameObject.transform.rotation.w); //_bulletPrefab.transform.position = new Vector3(this.transform.position.x, this.transform.position.y, this.transform.position.z + 3); //Instantiate(_bulletPrefab).GetComponent<Transform>(); Vector3 fireWallPos = _PlayerP1.transform.position; _portal = (GameObject)Instantiate(_portal, fireWallPos, Quaternion.identity); _portal.transform.localEulerAngles = new Vector3(270, 0, 0); _portal.GetComponent<ParticleSystem>().Play(); _portal.GetComponent<ParticleSystem>().loop = false; } } }
using System; using System.Collections.Generic; namespace UserStorageServices.UserStorage { public interface IUserStorageService { int Count { get; } void Add(User user); void Remove(Predicate<User> predicate); IEnumerable<User> Search(Predicate<User> predicate); } }
using System; namespace RO { [CustomLuaClass] public enum UILayer { Scene, BottomMost, Bottom, Lower, Normal, Upper, Top, TopMost, Screen, LayerCount } }
using System; using NopSolutions.NopCommerce.BusinessLogic.Products; using NopSolutions.NopCommerce.Web.MasterPages; namespace NopSolutions.NopCommerce.Web.Modules { public partial class ProductSize : BaseNopUserControl { protected void Page_Load(object sender, EventArgs e) { } protected string GetMaxHeight { get { decimal maxHeight = ProductManager.GetMaxHeight(((TwoColumn)Page.Master).CategoryID); int maxHeightInt = Convert.ToInt32(maxHeight); return maxHeightInt.ToString(); } } protected string GetMaxWidth { get { decimal maxWidth = ProductManager.GetMaxWidth(((TwoColumn)Page.Master).CategoryID); int maxWidthInt = Convert.ToInt32(maxWidth); return maxWidthInt.ToString(); } } } }
using System; using System.Collections.Generic; namespace NewWriteToWindow { class Program { public static string text; public static string textB; public static string TextA; public static List<int[]> StartText = new List<int[]>(); public static List<int> EndRowText = new List<int>(); public static List<int> countRow = new List<int>(); public static void WriteTextWithUseMouse(string text, int row, int lastPos) { int screenWidth = Console.WindowWidth; System.Console.SetCursorPosition(lastPos, row); Console.WriteLine(text); } static void Main(string[] args) { Console.SetWindowSize(100, 30); Console.SetBufferSize(100, 30); Start(3); Console.ReadKey(); } static void Start(int countWindows) { int[,] ConsoleArray = new int[100, 30]; int countPos = (int)(2 * countWindows); int[] windowPos = new int[countPos]; GenerateWindow(countWindows, ref ConsoleArray); CreateWriteBoxForEachWindow(countWindows, ConsoleArray, ref StartText, ref EndRowText, ref countRow); DrawWindow(ConsoleArray); //each second update drawtextinwindow //write text int maxTextLength = 0; for (int i = 0; i < EndRowText.Count; i++) { maxTextLength += ((EndRowText[i] + 1) * countRow[i]); } do { //text += Console.ReadKey().ToString(); if (!string.IsNullOrEmpty(text) && text.Length > maxTextLength) { char[] textChar = text.ToCharArray(); ConsoleKeyInfo ans = Console.ReadKey(true); if (ans.Key != ConsoleKey.LeftArrow && ans.Key != ConsoleKey.RightArrow) { text = string.Empty; textB += textChar[0]; for (int i = 1; i < textChar.Length; i++) { text += textChar[i]; } text += ans.KeyChar.ToString(); } else if (ans.Key == ConsoleKey.LeftArrow && textB.Length > 1) { char[] newTextChar = new char[textChar.Length]; text = string.Empty; for (int i = 0; i < textChar.Length - 1; i++) { newTextChar[i + 1] += textChar[i]; } TextA += textChar[textChar.Length - 1]; newTextChar[0] = textB[textB.Length - 1]; for (int i = 0; i < textChar.Length; i++) { text += newTextChar[i]; } char[] newTextB = textB.ToCharArray(); textB = string.Empty; for (int i = 0; i < newTextB.Length - 1; i++) { textB += newTextB[i]; } } else if (ans.Key == ConsoleKey.RightArrow && TextA.Length > 1) { char[] newTextChar = new char[textChar.Length]; text = string.Empty; for (int i = 1; i < textChar.Length; i++) { newTextChar[i - 1] += textChar[i]; } textB += textChar[0]; newTextChar[newTextChar.Length - 1] = TextA[TextA.Length - 1]; for (int i = 0; i < textChar.Length; i++) { text += newTextChar[i]; } char[] newTextA = TextA.ToCharArray(); TextA = string.Empty; for (int i = 0; i < newTextA.Length - 1; i++) { TextA += newTextA[i]; } } } else { ConsoleKeyInfo ans = Console.ReadKey(true); if (ans.Key != ConsoleKey.LeftArrow && ans.Key != ConsoleKey.RightArrow) { text += ans.KeyChar.ToString(); } } DrawTextInWindow(); } while (true); } static void GenerateWindow(int countWindows, ref int[,] ConsoleArray) { int currentWindow = 0; while (currentWindow < countWindows) { GenerateOneWindow(ref ConsoleArray, ref currentWindow); } } static void GenerateOneWindow(ref int[,] ConsoleArry, ref int currentWindow) { Random r = new Random(); int randomSizeX = r.Next(5, 15); int randomSizeY = r.Next(4, 5); int randomPosX = r.Next(randomSizeX / 2, 100 - (randomSizeX / 2)); int randomPosY = r.Next(randomSizeY / 2, 30 - (randomSizeY / 2)); bool isInCollision = false; for (int y = (randomPosY - randomSizeY / 2); y < (randomPosY + randomSizeY / 2); y++) { for (int x = (randomPosX - randomSizeX / 2); x < (randomPosX + randomSizeX / 2); x++) { if (ConsoleArry[x, y] > 0) { isInCollision = true; } if (isInCollision) { break; } } if (isInCollision) { break; } } if (!isInCollision) { for (int y = (randomPosY - randomSizeY / 2); y < (randomPosY + randomSizeY / 2); y++) { for (int x = (randomPosX - randomSizeX / 2); x < (randomPosX + randomSizeX / 2); x++) { if (y == (randomPosY - randomSizeY / 2) || y == (randomPosY + randomSizeY / 2) - 1 || x == (randomPosX - randomSizeX / 2) || x == (randomPosX + randomSizeX / 2) - 1) { ConsoleArry[x, y] = 99; } else { ConsoleArry[x, y] = currentWindow + 1; } } } currentWindow++; } } static void CreateWriteBoxForEachWindow(int countWindows, int[,] ConsoleArray, ref List<int[]> StartText, ref List<int> EndRowText, ref List<int> countRow) { for (int i = 0; i < countWindows; i++) { int[] startPos = new int[2]; bool isFirstPos = false; int countRowInt = 0; bool isCounted = false; int rowLength = 0; int maxRowLength = 0; for (int y = 0; y < 30; y++) { for (int x = 0; x < 100; x++) { if (isFirstPos == false && ConsoleArray[x, y] == i + 1) { startPos[0] = x; startPos[1] = y; StartText.Add(startPos); isFirstPos = true; } else if (ConsoleArray[x, y] == i + 1 && isCounted == false) { isCounted = true; countRowInt++; } else if (ConsoleArray[x, y] == i + 1) { rowLength++; } } if (rowLength > maxRowLength) { maxRowLength = rowLength; rowLength = 0; } else { rowLength = 0; } isCounted = false; } EndRowText.Add(maxRowLength); countRow.Add(countRowInt); } } static void DrawWindow(int[,] ConsoleArray) { for (int y = 0; y < 30; y++) { for (int x = 0; x < 100; x++) { if (ConsoleArray[x, y] == 99) { WriteTextWithUseMouse("#", y, x); } } } Console.SetCursorPosition(0, 0); } static void DrawTextInWindow() { if (!string.IsNullOrEmpty(text)) { int writeTo = 0; for (int i = 2; i > 0; i--) { if (text.Length > (countRow[i] * EndRowText[i])) { writeTo = i; break; } } char[] charText = text.ToCharArray(); int currentChar = 0; for (int i = 0; i < writeTo + 1; i++) { int lastPos = 0; int startPosX = StartText[i][0]; int startPosY = StartText[i][1]; for (int y = 0; y < countRow[i]; y++) { for (int x = 0; x < EndRowText[i] + 1; x++) { if (currentChar >= text.Length) { break; } WriteTextWithUseMouse(charText[currentChar].ToString(), y + startPosY, startPosX + lastPos); currentChar++; lastPos++; Console.SetCursorPosition(startPosX + lastPos, y + startPosY); } lastPos = 0; } } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; // 被攻击的卡牌 public class AttackedCard : MonoBehaviour, IDropHandler { public void OnDrop(PointerEventData eventData) { /*攻击*/ // 选择attacker卡牌(鼠标拖拽的卡牌) CardController attacker = eventData.pointerDrag.GetComponent<CardController>(); // 选择defender卡牌(本身) CardController defender = GetComponent<CardController>(); if (attacker == null || defender == null) { return; } if (attacker.model.canAttack) { // attacker和defender打一架 (GameManager被public成instancele,所以这里可以引用) GameManager.instance.CardsBattle(attacker, defender); } } }
using UnityEngine; using UnityEngine.InputSystem; public class PlayerMovement : MonoBehaviour { [SerializeField] private float forceMagnitude; [SerializeField] private float maxVelocity; [SerializeField] private float rotationSpeed; private Camera _mainCamera; private Rigidbody _rb; private Vector3 _movementDirection; private void Awake() { _rb = GetComponent<Rigidbody>(); } private void Start() { _mainCamera = Camera.main; } private void Update() { ProcessInput(); KeepPlayerOnScreen(); RotateToFaceVelocity(); } private void FixedUpdate() { if (_movementDirection == Vector3.zero) return; _rb.AddForce(_movementDirection * (forceMagnitude * Time.deltaTime), ForceMode.Force); _rb.velocity = Vector3.ClampMagnitude(_rb.velocity, maxVelocity); } private void ProcessInput() { if (Touchscreen.current.primaryTouch.press.isPressed) { var touchPosition = Touchscreen.current.primaryTouch.position.ReadValue(); var worldPosition = _mainCamera.ScreenToWorldPoint(touchPosition); _movementDirection = transform.position - worldPosition; _movementDirection.z = 0f; _movementDirection.Normalize(); } else { _movementDirection = Vector3.zero; } } private void KeepPlayerOnScreen() { var position = transform.position; var viewportPosition = _mainCamera.WorldToViewportPoint(position); if (viewportPosition.x > 1) position.x = -position.x + .1f; else if (viewportPosition.x < 0) position.x = -position.x - .1f; else if (viewportPosition.y > 1) position.y = -position.y + .1f; else if (viewportPosition.y < 0) position.y = -position.y - .1f; transform.position = position; } private void RotateToFaceVelocity() { if (_rb.velocity == Vector3.zero) return; var targetRotation = Quaternion.LookRotation(_rb.velocity, Vector3.back); transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime); } }
using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; namespace TypingGameKit { [CanEditMultipleObjects] [CustomEditor(typeof(TextCollection))] public class TextCollectionEditor : Editor { private TextCollection _texts; private string[] _randomSamples = new string[] { }; private int _sampleLength = 8; private char[] _initials = new char[] { }; private GUIStyle _labelStyle; private GUIStyle _boxStyle; private Vector2 _initialScroll; private void OnEnable() { _texts = (TextCollection)target; _labelStyle = EditorStyles.boldLabel; _boxStyle = EditorStyles.textArea; UpdateAnalysis(); } public override void OnInspectorGUI() { DrawDefaultInspector(); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Statistics", _labelStyle); EditorGUILayout.LabelField($"The collection contains {_texts.Texts.Length} texts."); EditorGUILayout.Separator(); DrawInitialStatistics(); EditorGUILayout.Separator(); DrawTextSamples(); serializedObject.ApplyModifiedProperties(); } private void DrawInitialToggle() { EditorGUI.BeginChangeCheck(); _texts.InitialsBreakdownByCase = EditorGUILayout.Toggle("case-sensitive", _texts.InitialsBreakdownByCase); if (EditorGUI.EndChangeCheck()) { UpdateAnalysis(); } } private void DrawInitialStatistics() { _initialScroll = EditorGUILayout.BeginScrollView(_initialScroll, _boxStyle); EditorGUILayout.LabelField($"Initial breakdown", _labelStyle); DrawInitialToggle(); EditorGUILayout.LabelField($"The text {_initials.Length} distinguishable initials."); EditorGUILayout.Separator(); DrawInitialBreakdown(); EditorGUILayout.EndScrollView(); } private void DrawInitialBreakdown() { EditorGUIUtility.labelWidth = 1; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField($"Initial"); EditorGUILayout.LabelField($"Count"); EditorGUILayout.LabelField($"Percent"); EditorGUILayout.EndHorizontal(); foreach (var c in _initials.OrderByDescending(c => _texts.TextsByInitial(c, _texts.InitialsBreakdownByCase).Count())) { int count = _texts.TextsByInitial(c, _texts.InitialsBreakdownByCase).Count(); float percent = 100 * count / (float)_texts.Texts.Length; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField($"{c}"); EditorGUILayout.LabelField($"{count}"); EditorGUILayout.LabelField($"({percent:#.##}%)"); EditorGUILayout.EndHorizontal(); } } private void DrawTextSamples() { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Random Samples", _labelStyle); if (GUILayout.Button("Generate")) { UpdateSample(); } EditorGUILayout.EndHorizontal(); foreach (string sample in _randomSamples) { EditorGUILayout.LabelField(sample, _boxStyle); } } private void UpdateAnalysis() { _texts.EvaluateTexts(); UpdateLeadingChars(); UpdateSample(); } private void UpdateLeadingChars() { _initials = _texts.Initials(_texts.InitialsBreakdownByCase).ToArray(); } private void UpdateSample() { var strings = new List<string>(); for (int i = 0; i < _sampleLength; i++) { strings.Add(_texts.PickRandomText()); } _randomSamples = strings.ToArray(); } } }
using UnityEngine; using System.Collections; using ProjectV.ItemSystem; public class Item { public string Name; public Sprite Icon; public int Value; public int Burden; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HackerrankSolutionConsole { class kangaroo : Challenge { private static string race(int x1, int v1, int x2, int v2) { //if (x2>x1 && v2>=v1) // return "NO"; if (v1 > v2 && ((x2 - x1) % (v1 - v2) == 0)) return "YES"; else return "NO"; } public override void Main(String[] args) { string[] tokens_x1 = Console.ReadLine().Split(' '); int x1 = Convert.ToInt32(tokens_x1[0]); int v1 = Convert.ToInt32(tokens_x1[1]); int x2 = Convert.ToInt32(tokens_x1[2]); int v2 = Convert.ToInt32(tokens_x1[3]); Console.WriteLine(race(x1, v1, x2, v2)); } public kangaroo() { Name = "Kangaroo"; Path = "kangaroo"; Difficulty = Difficulty.Easy; Domain = Domain.Algorithms; Subdomain = Subdomain.Implementation; } } }
using System; namespace SuppaCompiler.CodeAnalysis { public class Symbol { public Type Type { get; set; } public object Value { get; set; } } }
using Project_CelineGardier_2NMCT2.model; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Project.view { /// <summary> /// Interaction logic for PartTwo.xaml /// </summary> public partial class Bands : UserControl { public Bands() { InitializeComponent(); } private void SearchList(object sender, TextChangedEventArgs e) { ObservableCollection<Band> search = new ObservableCollection<Band>(Band.GetBands().Where(x => x.Name.IndexOf(txtSearch.Text, StringComparison.OrdinalIgnoreCase) >= 0)); bands.ItemsSource = search; } private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = EnableDisableControls(); } private void CommandBinding_ExecutedSave(object sender, ExecutedRoutedEventArgs e) { try { string txt = ""; string pic = ""; if (bands.SelectedItems.Count > 0) { // edit band Band b = (Band)bands.SelectedItem; if (!Band.Edit(b)) txt = "Couldn't edit band " + b.Name; txt = "Updated band"; // edit genre list ItemCollection items = GenreListS.Items; if(!Band.DeleteGenres(b.bandID)) txt = "Error with deleting bands genre"; if(items.Count > 0) { for (int i = 0; i < items.Count; i++) { Genre g = (Genre)items[i]; if (g.isChecked) { if (!Band.AddGenre(b.bandID, g.genreID)) { txt = "Couldn't edit band " + b.Name + " using bandgenre " + g.Name; } } } } } else { // add band if (!Band.Add(name.Text, description.Text, twitter.Text, facebook.Text, pic)) txt = "Couldn't add band"; else txt = "Added band"; } bands.ItemsSource = Band.GetBands(); MessageBox.Show(txt); } // Fail catch (Exception ex) { MessageBox.Show("1. Something went wrong:\n " + ex); } } private void CommandBinding_ExecutedNew(object sender, ExecutedRoutedEventArgs e) { bands.SelectedIndex = -1; } public bool EnableDisableControls() { return true; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using ExperianOfficeArrangement.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExperianOfficeArrangement.Factories; using Moq; using ExperianOfficeArrangement.Models; namespace ExperianOfficeArrangement.ViewModels.Tests { [TestClass] public class LoadMapViewModelTests { static LoadMapViewModelTests() { MockFactory = new Mock<IInteriorLayoutFactory>(); MockFactory.Setup(x => x.GetLayout()).Returns(new InteriorField[0, 0]); MockFactory.SetupGet(x => x.LayoutIdentifier).Returns("test"); } private static Mock<IInteriorLayoutFactory> MockFactory; [TestClass] public class LoadLayoutCommandTests { [TestMethod] public void ShouldSetIdentifier() { LoadMapViewModel vm = new LoadMapViewModel(MockFactory.Object); Assert.IsTrue(vm.LoadMapCommand.CanExecute(null)); vm.LoadMapCommand.Execute(null); Assert.AreEqual("test", vm.LayoutIdentifier); } } [TestClass] public class GetNextStateTests { [TestMethod] public void ShouldTransitionToChooseBrand() { LoadMapViewModel vm = new LoadMapViewModel(MockFactory.Object); Assert.IsFalse(vm.CanTransition); vm.LoadMapCommand.Execute(null); Assert.IsTrue(vm.CanTransition); Assert.IsTrue(vm.GetNextState() is ChooseBrandViewModel); } [TestMethod] public void ShouldReturnNullIfNoLayout() { LoadMapViewModel vm = new LoadMapViewModel(MockFactory.Object); Assert.IsFalse(vm.CanTransition); Assert.AreEqual(null, vm.GetNextState()); } } } }
using System.Collections.Generic; namespace Net { public class Node : Object { public string Name; public Node Parent; public List<Node> Children = new List<Node>(); public List<Component> Components = new List<Component>(); public Node() { } public Node( string name ) { Name = name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Numero13 { class Program { static void Main(string[] args) { Console.WriteLine("Ingrese algo:"); string ingreso1 = Console.ReadLine(); Console.WriteLine("Ingrese algo más:"); string ingreso2 = Console.ReadLine(); var length1 = ingreso1.Length; var length2 = ingreso2.Length; if (length1 == length2) { Console.WriteLine("Ambas cadenas tienen la misma longitud."); Console.ReadKey(); } else { Console.WriteLine("Las cadenas no tienen la misma longitud."); Console.ReadKey(); } } } }