text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InfHallwayGenerator : MonoBehaviour { [SerializeField] List<GameObject> _currentHallwaySections; [SerializeField] private Transform _playerTransform; [SerializeField] GameObject _hallwayPrefab; [SerializeField] GameObject _goalHallwayPrefab; private EncounterHandler _encounterHandler; public int InitHallwayPieces = 2; public int CurHallWayPieces = 0; public int MaxHallwayPieces = 5; public int NumOfMaxEncounters = 10; public int _encounterCount = 0; private void Awake() { DontDestroyOnLoad(this); } // Use this for initialization void Start () { _encounterHandler = this.GetComponent<EncounterHandler>(); _playerTransform = Root.Instance._playerChar.transform; _currentHallwaySections = new List<GameObject>(); InitHallway(); } // Update is called once per frame void Update () { } void InitHallway() { if(_playerTransform != null) { // AddHallwayPiece(new Vector3(_playerTransform.position.x, 0, _playerTransform.position.z), true); float zPos = 0; for(int i = 0; i < InitHallwayPieces; i++) { AddHallwayPiece(new Vector3(_playerTransform.position.x, 0, zPos), true); zPos += 11.5f; } } } void AddHallwayPiece(Vector3 offset, bool first = false) { CurHallWayPieces++; GameObject temp = Instantiate(_hallwayPrefab, offset, new Quaternion(0, 180, 0, 0)); _currentHallwaySections.Add(temp); if (_encounterCount >= NumOfMaxEncounters) { CreateHallwayPiece(temp, 3); } else { CreateHallwayPiece(temp, Random.Range(0, 3)); } } private void CreateHallwayPiece(GameObject temp, int encounterType) { if (encounterType != 0) ++_encounterCount; StraightHallway instance = temp.GetComponent<StraightHallway>(); instance.HallwayOutOfRange += RemoveHallwayPiece; instance.EncounterType = (EncounterType)encounterType; Debug.Log(instance.EncounterType); instance.EncounterBegin += _encounterHandler.StartEncounter; } private void CreateGoalPiece(Vector3 offset) { CurHallWayPieces++; var hallway = Instantiate(_goalHallwayPrefab, offset, new Quaternion(0, 180, 0, 0)); _currentHallwaySections.Add(hallway); // Root.GetComponentFromRoot<EncounterHandler>().StartGoalEncounter(); } void RemoveHallwayPiece(GameObject item) { //Debug.Log("removing " + item.name); _currentHallwaySections.Remove(item); CurHallWayPieces--; if (CurHallWayPieces < MaxHallwayPieces) { AddHallwayPiece(new Vector3(_currentHallwaySections[_currentHallwaySections.Count - 1].transform.position.x, 0, (_currentHallwaySections[_currentHallwaySections.Count - 1].transform.position.z + 11.5f))); } } }
using System; using System.Linq; using NUnit.Framework; using OpenQA.Selenium; using Framework.Core.Common; using Tests.Data.Van.Input; using Tests.Pages.Van.Main.Common; using System.Collections.Generic; namespace Tests.Pages.Van.Main { public class ContactDetailsPage : VanBasePage { #region Page Element Declarations public IWebElement ContactHistoryButton { get { return _driver.FindElement(By.XPath("//input[contains(@id, 'ContactHistory')]")); } } public IWebElement ContactHistoryInputTypeName { get { return _driver.FindElement(By.XPath("//span[contains(@id, 'ContactHistoryInputTypeName')]")); } } public IWebElement ContactHistoryContactTypeName { get { return _driver.FindElement(By.XPath("//span[contains(@id, 'ContactHistoryContactTypeName')]")); } } public IWebElement ContactHistoryCanvasserName { get { return _driver.FindElement(By.XPath("//span[contains(@id, 'ContactHistoryCanvasserName')]")); } } public IWebElement PhonesButton { get { return _driver.FindElement(By.XPath("//input[contains(@id,'Phones') and contains(@id,'ExpandButton')]")); } } public By PageHeaderTextLocator = By.Id("ctl00_ContentPlaceHolderVANPage_HeaderText"); public IWebElement PageHeaderText { get { return _driver.FindElement(PageHeaderTextLocator); } } // this membership locator is only good for this particular VANID //TODO - make this work for all public By MembershipPageSectionLocatorVANID_EIDCE3DBQ = By.Id("ctl00_ContentPlaceHolderVANPage_ctl09_innerContentPanel_Groups_EIDCE3DBQ_Content"); public IWebElement MembershipPageSection { get { return _driver.FindElement(MembershipPageSectionLocatorVANID_EIDCE3DBQ); } } #endregion public ContactDetailsPage(Driver driver) : base(driver) { } #region Methods /// <summary> /// Asserts if the passed ContactsPhones appear correctly on the page and are correctly marked as preferred /// </summary> /// <param name="contactsPhonesList"></param> public void AssertContactsPhonesAreCorrect(List<ContactsPhone> contactsPhonesList) { ValidateContactsPhoneListDataIsCorrect(contactsPhonesList); _driver.Click(PhonesButton); WaitForSpinner(); foreach (var phone in contactsPhonesList) { // There should not be whitespace at the end of the phone number in the html... var phoneNumberLocator = By.XPath(String.Format("//span[text()='{0} ']", phone.PhoneNumber)); var phoneNumberElement = _driver.FindElement(phoneNumberLocator); Assert.That(_driver.IsElementPresent(phoneNumberElement), Is.True, "Phone number: {0} is not present when it should be", phone.PhoneNumber); if (!phone.Preferred) continue; var preferredElement = phoneNumberElement.FindElement(By.XPath("following-sibling::span[text()='*']")); Assert.That(_driver.IsElementPresent(preferredElement), Is.True, "Phone number: {0} is not marked as preferred when it should be", phone.PhoneNumber); } } /// <summary> /// Checks the passed list of ContactsPhones to see if there are more than one ContactsPhones that are marked as preferred. /// If there is more than one, the test will be failed /// </summary> /// <param name="contactsPhonesList"></param> /// <returns>True if there is 1 or less than 1 ContactsPhones marked as preferred. False otherwise</returns> public bool ValidateContactsPhoneListDataIsCorrect(List<ContactsPhone> contactsPhonesList) { var preferredCount = contactsPhonesList.Count(contactsPhone => contactsPhone.Preferred); if (preferredCount == 1) return true; if (preferredCount < 1) { Console.WriteLine("No PhoneNumbers in the ContactsPhone list have been set to preferred. Preferred Contacts Phone Number validation will not be performed."); return true; } if (preferredCount > 1) Assert.Fail("More than one Contacts Phone Number has been set to preferred.\n Please make sure that the test data is configured properly. Failing test."); // Assert.Fail will fail the test, but this is necessary for compiling return false; } /// <summary> /// goes to https:// CD pages ONLY - make new method for other ones later /// </summary> /// <param name="url"></param> public void GoToHTTPSContactsDetailsPageDirectly(string url) { _driver.GoToPage("https://" + _driver.GetUrl().Split('/')[2] + "/" + url); _driver.WaitForElementToDisplayBy(PageHeaderTextLocator); } /// <summary> /// goes to https:// CD pages ONLY - ONLY for clients using the AFL membership PS - make new method for other ones later /// </summary> /// <param name="url"></param> public void GoToHTTPSContactsDetailsPageDirectlyAFLMembership(string url) { GoToHTTPSContactsDetailsPageDirectly(url); _driver.WaitForElementToDisplayBy(MembershipPageSectionLocatorVANID_EIDCE3DBQ); } #endregion } }
namespace Google { using System; using System.Collections.Generic; using System.Linq; public class GoogleProgram { public static void Main() { var persons = new List<Person>(); var input = Console.ReadLine(); while (input != "End") { var line = input.Split(); var personName = line[0]; if (!persons.Any(x => x.Name == personName)) { var person = new Person(personName); persons.Add(person); } var currentPerson = persons.First(x => x.Name == personName); switch (line[1]) { case "company": var salaryToDigit = double.Parse(line.Last()); var salaryToString = $"{salaryToDigit:f2}"; line[4] = salaryToString; currentPerson.Company = line.Skip(2).ToList(); break; case "car": currentPerson.Car = line.Skip(2).ToList(); break; case "parents": var currentParent = new Parent(line[2], line[3]); currentPerson.Parents.Add(currentParent); break; case "children": var currentChildren = new Children(line[2], line[3]); currentPerson.Children.Add(currentChildren); break; case "pokemon": var currentPokemon = new Pokemon(line[2], line[3]); currentPerson.Pokemons.Add(currentPokemon); break; } input = Console.ReadLine(); } var nameForSearch = Console.ReadLine(); var item = persons.First(x => x.Name == nameForSearch); Console.WriteLine(item.Name); Console.WriteLine("Company:"); if (item.Company.Count > 0) { Console.WriteLine(string.Join(" ", item.Company)); } Console.WriteLine("Car:"); if (item.Car.Count > 0) { Console.WriteLine(string.Join(" ", item.Car)); } Console.WriteLine("Pokemon:"); foreach (var pokemon in item.Pokemons) { Console.WriteLine($"{pokemon.PokemonName} {pokemon.PokemonType}"); } Console.WriteLine("Parents:"); foreach (var parent in item.Parents) { Console.WriteLine($"{parent.ParentName} {parent.ParentBirthDay}"); } Console.WriteLine("Children: "); foreach (var children in item.Children) { Console.WriteLine($"{children.ChildrenName} {children.ChildrenBirthDay}"); } } } }
using System.Reflection; using Autofac; using Autofac.Integration.Mvc; using TAiMStore.Model.Factory; using TAiMStore.Model.Repository; using TAiMStore.Model.UnitOfWork; using TAiMStore.Model.Interfaces; using System.Web.ModelBinding; namespace TAiMStore.Configs { public class AutofacConfiguration { public static AutofacDependencyResolver GetAutofacDependencyResolver() { const string repository = "Repository"; var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); builder.RegisterType<Factory>().As<IFactory>().InstancePerHttpRequest(); builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(ProductRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(UserRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(RoleRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(ContactsRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(CategoryRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(OrderRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(OrderProductRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes(typeof(PaymentRepository).Assembly) .Where(t => t.Name.EndsWith(repository)) .AsImplementedInterfaces() .InstancePerHttpRequest(); return new AutofacDependencyResolver(builder.Build()); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace University.UI.Areas.Admin.Models { public class FAQViewModel { public decimal Id { get; set; } // [StringLength(100, ErrorMessage = "Do not enter more than 100 characters")] public string Question { get; set; } // [StringLength(150, ErrorMessage = "Do not enter more than 150 characters")] public string Answer { get; set; } public Nullable<bool> IsDeleted { get; set; } public Nullable<System.DateTime> CreatedDate { get; set; } public Nullable<Decimal> CreatedBy { get; set; } public Nullable<System.DateTime> DeletedDate { get; set; } public Nullable<Decimal> DeletedBy { get; set; } public Nullable<System.DateTime> UpdatedDate { get; set; } public Nullable<Decimal> UpdatedBy { get; set; } public Nullable<int> AssocitedCustID { get; set; } public virtual ICollection<FAQDocViewModel> FAQDoc { get; set; } } }
using System.Windows.Forms; using System; using Stock_Exchange_Analyzer.DataRepresentation; using System.ComponentModel; using Stock_Exchange_Analyzer.Exceptions; using Stock_Exchange_Analyzer.Data_Storage; namespace Stock_Exchange_Analyzer { public partial class Search_Stock_Prices : Form { BackgroundWorker downloader; Portfolio thisPortfolio; public Portfolio ThisPortfolio { get { return thisPortfolio; } set { thisPortfolio = value; } } public Search_Stock_Prices(ref Portfolio pt) { InitializeComponent(); this.Icon = Properties.Resources.Stocks; thisPortfolio = pt; dateTimePicker1.Value = DateTime.Now.AddMonths(-1); dateTimePicker2.Value = DateTime.Now; dateTimePicker2.MaxDate = dateTimePicker2.Value; } private void bSearch_Click(object sender, EventArgs e) { errorProvider1.Clear(); if (dateTimePicker1.Value > dateTimePicker2.Value) { errorProvider1.SetError(dateTimePicker1, "The initial date cannot be set to a value after the final date."); errorProvider1.SetError(dateTimePicker2, "The initial date cannot be set to a value after the final date."); return; } downloader = new BackgroundWorker(); downloader.DoWork += PerformQuery; downloader.RunWorkerCompleted += QueryFinished; DownloaderArguments da = new DownloaderArguments(); da.Company = tbCompanyName.Text; da.EndDate = dateTimePicker2.Value; da.StartDate = dateTimePicker1.Value; downloader.RunWorkerAsync(da); bSearch.Text = "Retrieving data..."; bSearch.Enabled = false; } private void QueryFinished(object sender, RunWorkerCompletedEventArgs e) { DownloaderResult dr = e.Result as DownloaderResult; if(dr.Error != null) { if (dr.ControlCausedError != null) errorProvider1.SetError(dr.ControlCausedError, dr.Error); else MessageBox.Show(dr.Error, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); bSearch.Text = "Search"; bSearch.Enabled = true; } else { Search_Results sr = new Search_Results(dr.Result, ref thisPortfolio); sr.ShowDialog(); thisPortfolio = sr.ThisPortfolio; this.Close(); } } private void PerformQuery(object sender, DoWorkEventArgs e) { DownloaderResult dr = new DownloaderResult(); DownloaderArguments da = e.Argument as DownloaderArguments; try { dr.Result = new QueryResult(DataRetriever.RetrieveData(da.DataProvider, da.StartDate, da.EndDate, da.Company), da.Company); } catch(CompanyNotFoundException) { dr.ControlCausedError = tbCompanyName; dr.Error = "Company not found in records."; } catch(ConnectionErrorException) { dr.Error = "Network error, cannot contact data source."; } catch(DataProviderNotValidException) { dr.Error = "Data provider doesn't exist."; } e.Result = dr; } } class DownloaderResult { public QueryResult Result = null; public string Error = null; public Control ControlCausedError = null; } class DownloaderArguments { public DataProviders DataProvider = DataProviders.YahooFinance; public DateTime StartDate, EndDate; public string Company = null; } }
namespace Swan.Ldap { using System.IO; /// <summary> /// Represents an Ldap Modify Request. /// <pre> /// ModifyRequest ::= [APPLICATION 6] SEQUENCE { /// object LdapDN, /// modification SEQUENCE OF SEQUENCE { /// operation ENUMERATED { /// add (0), /// delete (1), /// replace (2) }, /// modification AttributeTypeAndValues } } /// </pre> /// </summary> /// <seealso cref="Asn1Sequence" /> /// <seealso cref="IRfcRequest" /> internal sealed class RfcModifyRequest : Asn1Sequence, IRfcRequest { public RfcModifyRequest(string obj, Asn1SequenceOf modification) : base(2) { Add(obj); Add(modification); } public Asn1SequenceOf Modifications => (Asn1SequenceOf)Get(1); public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.ModifyRequest); public string GetRequestDN() => ((Asn1OctetString)Get(0)).StringValue(); } internal class RfcModifyResponse : RfcLdapResult { public RfcModifyResponse(Stream stream, int len) : base(stream, len) { } public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.ModifyResponse); } }
namespace Apache.Shiro.Session.Management { public interface IValidatingSessionManager : ISessionManager { void Validate(object sessionId); void ValidateAll(); } }
using WebApplication1.EfStuff.Model.Energy; namespace WebApplication1.EfStuff.Repositoryies.Energy.Intrefaces { public interface IPersonalAccountRepository : IBaseRepository<PersonalAccount> { public PersonalAccount GetByCitizenId(long id); public PersonalAccount GetByNumber(string accountNumber); public PersonalAccount SaveBalance(PersonalAccount account); } }
using System.Collections.Generic; namespace Restaurants.Domain { public class Menu { public int Id { get; set; } public string ImagePath { get; set; } public string Name { get; set; } public string Description { get; set; } public double Price { get; set; } public virtual Restaurant Restaurant { get; set; } public virtual List<OrderItem> Items { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace ProjectManagement.Entity { public class Employee { public int EmployeeId { get; set; } public string Name { get; set; } public string Surname { get; set; } public List<Sample> Samples { get; set; } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace Kuromori { /// <summary> /// Simple splash page with an image, logo and button /// </summary> public partial class SplashPage : ContentPage { public SplashPage() { InitializeComponent(); InitializeComponent(); Splash.Source = new Uri("http://haydenszymanski.me/splash-image.png"); Splash.Aspect = Aspect.Fill; Logo.Source = new Uri("http://haydenszymanski.me/logo.png"); } /// <summary> /// Push a new page onto navigation stack /// </summary> void OnButtonClick(object sender, EventArgs e) { Navigation.PushAsync(new UserSelectPage()); } protected override bool OnBackButtonPressed() { return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using AudioText.Models; namespace AudioText.DAL { public class AudioTextInitializer : System.Data.Entity.DropCreateDatabaseAlways<AudioTextContext> { protected override void Seed(AudioTextContext context) { var posts = new List<NewsLetterPost>() { new NewsLetterPost() {Post="<H3>hello, this is a test</h3><p>some text</p>", DatePosted = DateTime.Now, Subject = "Post one"}, new NewsLetterPost() {Post="<h1>THIS IS ANOTHER POST</h1><p>some text</p><p>some more text</p><h2>some more stuff</h2>", DatePosted = DateTime.Now, Subject = "Post two"}}; var categories = new List<Category> { new Category{name="scifi"}, new Category{name="studyguides"} }; var authors = new List<Author> { new Author { Name = "Ray Bradbury" }, new Author { Name = "Orson Scott Cardd" }, new Author {Name="Stephen King" } }; var filters = new List<Filter> { new Filter {Name = "Scary" }, new Filter {Name = "Study" }, new Filter {Name = "Time-Travel"}, new Filter {Name = "Suspense" }, }; var inventoryItems = new List<InventoryItem> { new InventoryItem{dateAdded=DateTime.Now, Authors=new List<Author> { authors[0]}, image="placeholder.png",itemName="something wicked this way comes",price=(decimal)20.5F,quantity=10,seller="AudioTextTapes", Filters=new List<Filter> { filters[0]}, Category=categories[0]}, new InventoryItem{dateAdded=DateTime.Now.AddDays(-1), Authors=new List<Author> { authors[0]}, image="placeholder.png",itemName="The Martian", price=(decimal)15F, quantity=0, seller="AudioTextTapes",Filters=new List<Filter> { filters[1]},Category=categories[0]}, new InventoryItem{dateAdded=DateTime.Now.AddDays(-2), Authors=new List<Author> { authors[1]}, image="placeholder.png", itemName="Ender's Game", price=(decimal)20f, quantity=10, seller="AudioTextTapes",Filters=new List<Filter> { filters[2]},Category=categories[0]}, new InventoryItem{dateAdded=DateTime.Now.AddDays(-3), Authors=new List<Author> { authors[1]}, image="placeholder.png", itemName="Dune", price=(decimal)50f, quantity=20, seller="AudioTextTapes",Filters=new List<Filter> { filters[3]},Category=categories[0] }, new InventoryItem{dateAdded=DateTime.Now.AddDays(-4), Authors=new List<Author> { authors[0]}, image="placeholder.png", itemName="StarWars", price=(decimal)100f, quantity=20, seller="AudioTextTapes",Filters=new List<Filter> { filters[0], filters[1]},Category=categories[0]}, new InventoryItem{dateAdded=DateTime.Now.AddDays(-5), Authors=new List<Author> { authors[2]}, image="placeholder.png", itemName="Babylon 5", price=(decimal)20f, quantity=0, seller="AudioTextTapes",Filters=new List<Filter> { filters[0], filters[2]},Category=categories[0]}, new InventoryItem{dateAdded=DateTime.Now.AddDays(-6), Authors=new List<Author> { authors[1]}, image="placeholder.png", itemName="Study Guide 1", price=(decimal) 20f, quantity=1, seller="AudioTextTapes",Filters=new List<Filter> { filters[0], filters[3]},Category=categories[1] }, new InventoryItem{dateAdded=DateTime.Now.AddDays(-7), Authors=new List<Author> { authors[1]}, image="placeholder.png", itemName="Study Guide 2", price=(decimal) 20f, quantity=3, seller="AudioTextTapes",Filters=new List<Filter> { filters[0], filters[1], filters[2], filters[3]},Category=categories[1]}, new InventoryItem{dateAdded=DateTime.Now.AddDays(-8), Authors=new List<Author> { authors[0]}, image="placeholder.png", itemName="Study Guide 3", price=(decimal)20f, quantity=10, seller="AudioTextTapes",Filters=new List<Filter> { filters[1], filters[3]},Category=categories[1] }, new InventoryItem{dateAdded=DateTime.Now.AddDays(-9), Authors=new List<Author> { authors[0], authors[1]}, image="placeholder.png", itemName="Study Guide 4", price=(decimal)20f, quantity=1, seller="AudioTextTapes", Filters=new List<Filter> { filters[1], filters[2]},Category=categories[1] }, new InventoryItem{dateAdded=DateTime.Now.AddDays(-10), Authors=new List<Author> { authors[0], authors[1]}, image="placeholder.png", itemName="Study Guide 5", price=(decimal)20f, quantity=0, seller="AudioTextTapes",Filters=new List<Filter> { filters[2], filters[3]},Category=categories[1] }, new InventoryItem{dateAdded=DateTime.Now.AddDays(-11), Authors=new List<Author> { authors[0], authors[1]}, image="placeholder.png", itemName="Study Guide 6", price=(decimal)20f, quantity=1, seller="AudioTextTapes",Filters=new List<Filter> { filters[3], filters[2]},Category=categories[1] } }; var announcements = new List<Announcement> { new Announcement{content="This is our first announcement!",date=DateTime.Now.AddDays(-5),title="First Announcement", image="slider1.jpg"}, new Announcement{content="This is our second announcement!",date=DateTime.Now, title="Second Announcement", image="slider2.jpg"}, new Announcement{content="This is our third announcement!",date=DateTime.Now.AddDays(1), title="Third Announcement", image="slider3.jpg"} }; var emails = new List<AccountInformation> { new AccountInformation{Email="stuart.millner@gmail.com"}, new AccountInformation{Email="ejkaster@gmail.com"}, new AccountInformation{Email="arjanmillner@yahoo.com"} }; var testOrders = new List<Order>(){ new Order() { Address = "409 Regency Court", City = "Friendswood", State = "Texas", FirstName = "Stuart", LastName = "Millner", OrderDate = DateTime.Now, Zip = "77546" }, new Order() { Address = "5400 Memorial Drive", City = "Houston", State = "Texas", FirstName = "John", LastName = "Bonham", OrderDate = DateTime.Now, Zip = "77007" }, new Order() { Address = "333 Dawn Hill", City = "Friendswood", State = "Texas", FirstName = "Stuart", LastName = "Millner", OrderDate = DateTime.Now, Zip = "77007" }, new Order() { Address = "4301 Houston Avenue", City = "Houston", State = "Texas", FirstName = "Frank", LastName = "Abagnale", OrderDate = DateTime.Now, Zip = "77007" }, new Order() { Address = "333 Cray Street", City = "Houston", State = "Texas", FirstName = "Beth", LastName = "Kaster", OrderDate = DateTime.Now, Zip = "77007" }, new Order() { Address = "1100 Heights Blvd", City = "League City", State = "Texas", FirstName = "Stuart", LastName = "Millner", OrderDate = DateTime.Now, Zip = "77546", ShippedDate = DateTime.Now} }; var orderDetails = new List<OrderDetail>(){ new OrderDetail() { InventoryItem=inventoryItems[0],Order=testOrders[0], Quantity=1}, new OrderDetail() { InventoryItem = inventoryItems[0], Order = testOrders[0], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[1], Order = testOrders[0], Quantity = 2 }, new OrderDetail() { InventoryItem = inventoryItems[2], Order = testOrders[0], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[4], Order = testOrders[0], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[5], Order = testOrders[0], Quantity = 3 }, new OrderDetail() { InventoryItem=inventoryItems[0],Order=testOrders[1], Quantity=1}, new OrderDetail() { InventoryItem = inventoryItems[0], Order = testOrders[1], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[1], Order = testOrders[1], Quantity = 2 }, new OrderDetail() { InventoryItem = inventoryItems[3], Order = testOrders[1], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[4], Order = testOrders[1], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[5], Order = testOrders[1], Quantity = 3 }, new OrderDetail() { InventoryItem=inventoryItems[0],Order=testOrders[2], Quantity=1}, new OrderDetail() { InventoryItem = inventoryItems[2], Order = testOrders[2], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[1], Order = testOrders[2], Quantity = 2 }, new OrderDetail() { InventoryItem = inventoryItems[2], Order = testOrders[2], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[4], Order = testOrders[2], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[5], Order = testOrders[3], Quantity = 3 }, new OrderDetail() { InventoryItem=inventoryItems[4],Order=testOrders[3], Quantity=1}, new OrderDetail() { InventoryItem = inventoryItems[0], Order = testOrders[3], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[1], Order = testOrders[3], Quantity = 2 }, new OrderDetail() { InventoryItem = inventoryItems[2], Order = testOrders[3], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[1], Order = testOrders[4], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[5], Order = testOrders[4], Quantity = 3 }, new OrderDetail() { InventoryItem=inventoryItems[2],Order=testOrders[4], Quantity=1}, new OrderDetail() { InventoryItem = inventoryItems[0], Order = testOrders[4], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[1], Order = testOrders[5], Quantity = 2 }, new OrderDetail() { InventoryItem = inventoryItems[2], Order = testOrders[5], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[3], Order = testOrders[5], Quantity = 1 }, new OrderDetail() { InventoryItem = inventoryItems[5], Order = testOrders[5], Quantity = 3 } }; context.Authors.AddRange(authors); context.Filters.AddRange(filters); context.categories.AddRange(categories); context.Announcements.AddRange(announcements); context.inventory.AddRange(inventoryItems); context.accounts.AddRange(emails); context.orderdetails.AddRange(orderDetails); context.orders.AddRange(testOrders); context.NewsLetters.AddRange(posts); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class AgregarUsuario : System.Web.UI.Page { webservicio.Webservice2Client conec = new webservicio.Webservice2Client(); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string a = nickname.Text; string b = nombre.Text; string c = correo.Text; string d = fechanac.Text; string f = contra.Text; conec.CrearUsuario(a, b, c, d, f); } protected void Button2_Click(object sender, EventArgs e) { // response,redirect("login.aspx"); } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace Bankapp { class Account { //Constructor private string _accountNumber; private double _balance; private List<Transaction> _transactions; public Account(string accountNumber) { _accountNumber = accountNumber; _transactions = new List<Transaction>(); } public Account (string accountNumber , double balance, List<Transaction> transactions) { _accountNumber = accountNumber; Balance = balance; _transactions = transactions; } public double Balance { get => _balance; set => _balance = value; } public string AccountNumber { get => _accountNumber; set => _accountNumber = value; } public bool Addtransaction(Transaction transaction) { bool res = false; _transactions.Add(transaction); double balanceBeforeTransaction = Balance; if (_transactions.Last().Equals(transaction)) { Balance += transaction.Sum; } if (Balance - transaction.Sum == balanceBeforeTransaction) { res = true; } return res; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DamageCalculatorFinal { class WeaponDamage { public int Damage { get; protected set; } // The Damage property's get accessor needs to be marked protected. That way the subclasses have access to update it, but no other class can set it. It's still protected from other classes accidentally setting it, so the subclasses will still be well-encapsulated. private int roll; public int Roll { get { return roll; } set { roll = value; CalculateDamage(); // The properties still call the CalculateDamage()-method, which keeps the Damage property updated. Even though the Properties are defined in the superclass, when they're inherited by a subclass they call the CalculateDamage()-method defined in that subclass. } } private bool magic; public bool Magic { get { return magic; } set { magic = value; CalculateDamage(); // The properties still call the CalculateDamage()-method, which keeps the Damage property updated. Even though the Properties are defined in the superclass, when they're inherited by a subclass they call the CalculateDamage()-method defined in that subclass. } } private bool flaming; public bool Flaming { get { return flaming; } set { flaming = value; CalculateDamage(); // The properties still call the CalculateDamage()-method, which keeps the Damage property updated. Even though the Properties are defined in the superclass, when they're inherited by a subclass they call the CalculateDamage()-method defined in that subclass. } } protected virtual void CalculateDamage() { Console.WriteLine("This text will never get printed"); // This method is empty because the sub-classes overrides this method, so it will never be called. } public WeaponDamage(int startingRoll) { roll = startingRoll; CalculateDamage(); } } }
using System; using System.Collections.Generic; using System.Linq; using IDI.Digiccy.Common.Enums; using IDI.Digiccy.Models.Base; using IDI.Digiccy.Models.Transaction; namespace IDI.Digiccy.Domain.Transaction { /// <summary> /// 撮合器 /// </summary> public sealed class Matchmaker { public TradeResult Do() { TradeOrder order; if (TradeQueue.Instance.TryDequeue(out order)) { var result = MakeMacth(order); //如果交易未完成,则重新加入待交易队列 if (order.Remain() > 0) TradeQueue.Instance.Add(order); return result; } else { TradeLogger.Instance.Update(); } return TradeResult.None(); } private TradeResult MakeMacth(TradeOrder order) { switch (order.Type) { case TranType.Bid: var asks = TradeQueue.Instance.GetMatchOrders(order).Select(e => e as AskOrder).ToList(); return MakeMatch(order as BidOrder, asks); case TranType.Ask: var bids = TradeQueue.Instance.GetMatchOrders(order).Select(e => e as BidOrder).ToList(); return MakeMatch(order as AskOrder, bids); default: return TradeResult.Fail(); } } private TradeResult MakeMatch(BidOrder bid, List<AskOrder> asks) { asks = asks.OrderBy(e => e.Price).ThenBy(e => e.Date).ToList(); var items = new List<TradeLog>(); foreach (var ask in asks) { if (bid.Remain() == 0) break; var item = MakeMatch(bid, ask); items.Add(item); } return items.Count > 0 ? TradeResult.Success(items) : TradeResult.None(); } private TradeResult MakeMatch(AskOrder ask, List<BidOrder> bids) { bids = bids.OrderByDescending(e => e.Price).ThenBy(e => e.Date).ToList(); var items = new List<TradeLog>(); foreach (var bid in bids) { if (ask.Remain() == 0) break; var item = MakeMatch(bid, ask); items.Add(item); } return items.Count > 0 ? TradeResult.Success(items) : TradeResult.None(); } private TradeLog MakeMatch(BidOrder bid, AskOrder ask) { decimal price = bid.Date < ask.Date ? bid.Price : ask.Price; decimal volume = bid.Remain() <= ask.Remain() ? bid.Remain() : ask.Remain(); var taker = bid.Date < ask.Date ? TradeParty.Seller : TradeParty.Buyer; bid.Volume += volume; ask.Volume += volume; if (ask.Remain() == 0) TradeQueue.Instance.Remove(ask); if (bid.Remain() == 0) TradeQueue.Instance.Remove(bid); var log = new TradeLog { Ask = ask, Bid = bid, Price = price, Volume = volume, Taker = taker, Time = DateTime.Now }; TradeLogger.Instance.Update(log); return log; } } }
using System; using Zesty.Core.Entities; namespace Zesty.Core.Api.System.Admin.User { public class Get : ApiHandlerBase { public override ApiHandlerOutput Process(ApiInputHandler input) { string userId = Get(input, "id"); Entities.User user = Business.User.Get(userId); if (user == null) { ThrowNotFound(userId); } return GetOutput(new GetResponse() { User = user }); } } public class GetResponse { public Entities.User User { get; set; } } }
using System; using OPyke.ZopaTest.LoanProcessor.Interfaces; using StructureMap; namespace OPyke.ZopaTest.ConsoleApp { public class Program { static void Main(string[] args) { // Use StructureMap to map the the interfaces to the concrete classes var iocRegistry = new IocRegistry(); var container = new Container(iocRegistry); var loanProcessor = container.GetInstance<ILoanProcessor>(); // Set exceptions to show on debug builds #if(DEBUG == false) try { #endif var loanResponse = loanProcessor.ProcessLoanRequest(args); Console.Write(loanResponse.ToString()); #if(DEBUG == false) } catch (Exception e) { Console.WriteLine(e.Message); } # endif Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace AsteroidsGame { public class PowerUp { public bool isActive = false; public Matrix transformationMatrix; public Vector3 position; public float rotationX; public float rotationZ; public static Model bombModel; public static Matrix[] bombTransforms; public PowerUp() { } public void Initialize(Vector3 pos) { position = pos; rotationX = 0; rotationZ = 0; isActive = true; } public void Update(GameTime gameTime, Vector3 shipPosition) { rotationX += 0.15f; rotationZ += 0.01f; transformationMatrix = Matrix.CreateRotationX(rotationX) * Matrix.CreateRotationZ(rotationZ) * Matrix.CreateTranslation(position); if ((position - shipPosition).Length() > 2200) position -= (position - shipPosition) / 100; BoundingSphere bombSphere = new BoundingSphere(position, bombModel.Meshes[0].BoundingSphere.Radius); for (int i = 0; i < GamePlay.playerList.Length; i++) if (GamePlay.playerList[i].ship.isActive) { BoundingSphere shipSphere = new BoundingSphere(GamePlay.playerList[i].ship.Position, GamePlay.playerList[i].shipModel.Meshes[0].BoundingSphere.Radius * 0.8f); if (shipSphere.Intersects(bombSphere)) { MainClass.soundBank.PlayCue("powerUp"); isActive = false; GamePlay.playerList[i].bomb.isAvailable = true; return; //exit the loop } } } public void Draw(Vector3 color) { ((BasicEffect)PowerUp.bombModel.Meshes[0].Effects[0]).DiffuseColor = color; ((BasicEffect)PowerUp.bombModel.Meshes[1].Effects[0]).DiffuseColor = color; GamePlay.DrawModel(bombModel, transformationMatrix, bombTransforms); } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace KeepTeamAutotests.Pages { public class UsersPage : CommonPage { [FindsBy(How = How.ClassName, Using = "b-header-button-text")] private IWebElement addUserButton; public UsersPage(PageManager pageManager) : base(pageManager) { pagename = "users"; } public void clickAddUser() { addUserButton.Click(); } } }
/*********************************************************************** * Module: Patient.cs * Author: Sladjana Savkovic * Purpose: Definition of the Class Patient ***********************************************************************/ using System; namespace Model.Users { public class Patient : User { public DateTime DateOfRegistration { get; set; } public bool IsGuest { get; set; } public Patient() { IsGuest = false; } public Patient(string jmbg,string name,string surname,DateTime dateOfBirth,GenderType gender,City city,string homeAddress,string phone,string email,string username, string password,DateTime dateOfRegistration,bool isGuest) { this.Jmbg = jmbg; this.Name = name; this.Surname = surname; this.DateOfBirth = dateOfBirth; this.Gender = gender; if (city != null) { this.City = new City(city); } else { this.City = new City(); } this.HomeAddress = homeAddress; this.Phone = phone; this.Email = email; this.Username = username; this.Password = password; this.DateOfRegistration = dateOfRegistration; this.IsGuest = isGuest; } public Patient(Patient patient) { this.Jmbg = patient.Jmbg; this.Name = patient.Name; this.Surname = patient.Surname; this.DateOfBirth = patient.DateOfBirth; this.Gender = patient.Gender; if (patient.City != null) { this.City = new City(patient.City); } else { this.City = new City(); } this.HomeAddress = patient.HomeAddress; this.Phone = patient.Phone; this.Email = patient.Email; this.Username = patient.Username; this.Password = patient.Password; this.DateOfRegistration = patient.DateOfRegistration; this.IsGuest = patient.IsGuest; } } }
using UnityEngine; public class SwitchMoveCorridor2 : MonoBehaviour { // Switch control. [HideInInspector] public bool isTriggered { get; set; } = false; // Attached corridor. [SerializeField] private GameObject corridor; // Attached player. [SerializeField] private GameObject player; // Attached twin switch. [SerializeField] private GameObject switch1; // Attached objects' components. private Transform corridorTr; private Transform playerTr; private CharacterController charCtrl; private SwitchMoveCorridor1 switch1Ref; private void Awake() { // Init components. corridorTr = corridor.transform; playerTr = player.transform; charCtrl = player.GetComponent<CharacterController>(); switch1Ref = switch1.GetComponent<SwitchMoveCorridor1>(); } private void OnTriggerEnter(Collider other) { // If the player has triggered the switch. if (other.name == "player" && isTriggered == false) { // Disable second-time triggering of current switch. isTriggered = true; // Enable the twin switch. switch1.gameObject.SetActive(true); switch1Ref.isTriggered = false; // Move the GameObject to the desired location. MoveCorridor(); // Disable the current switch. this.gameObject.SetActive(false); } } // Move the GameObject to the desired location. private void MoveCorridor() { // Set the corridor's attributes, and the player's attribute accordingly. charCtrl.enabled = false; corridorTr.localPosition = new Vector3(78.086f, 204.56f, -50.707f); corridorTr.eulerAngles = new Vector3(0.0f, -90.0f, 0.0f); charCtrl.enabled = true; playerTr.SetParent(null); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TemplateFramework { /// <summary> </summary> public class FileSettingText { public string Name { get; set; } public string SaveTo { get; set; } public SaveType SaveType { get; set; } public List<InjectSettingText> InjectSettings { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Restaurant.Repositories; using Restaurant.Models; using Microsoft.AspNetCore.Authorization; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace Restaurant.Controllers { public class RestaurantController : Controller { private IRestaurantRepository restrepo; public RestaurantController(IRestaurantRepository repo) { restrepo = repo; } // GET: /<controller>/ [Route("TastyThaiFood")] public ViewResult Menu1() { return View(restrepo.GetAllMenu1().ToList()); } [Route("TastyThaiFood/Edit")] [Authorize(Roles = "Administrator")] public ViewResult Edit(int Menu1ID) { ViewBag.Menu1ID = Menu1ID; return View(restrepo.GetAllMenu1().FirstOrDefault(m => m.Menu1ID == Menu1ID)); } [Route("TastyThaiFood/Index")] [Authorize(Roles = "Administrator")] public ViewResult Index() => View(restrepo.GetAllMenu1()); [HttpPost] [Authorize(Roles = "Administrator")] public IActionResult Edit(Menu1 menu1) { if (ModelState.IsValid) { restrepo.Update(menu1); TempData["message"] = $"{menu1.Menu1ID} has been saved"; return RedirectToAction("Index"); } else { return View(menu1); } } [HttpPost] [Authorize(Roles = "Administrator")] public IActionResult Delete(int menu1ID) { Menu1 deletedfood = restrepo.DeleteMessage(menu1ID); if (deletedfood != null) { TempData["message"] = $"{deletedfood.Menu1ID} was deleted"; } return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.Text; namespace MyObserver { public class Subscriber : ISubscriber { private string _name; public Subscriber(string name) { _name = name; } public virtual void Update(IPostOffice postOffice) { Console.WriteLine($"{postOffice.GetLetter().ToString()}"); } } }
// ----------------------------------------------------------------------- // <copyright company="Fireasy" // email="faib920@126.com" // qq="55570729"> // (c) Copyright Fireasy. All rights reserved. // </copyright> // ----------------------------------------------------------------------- using System.Linq.Expressions; namespace Fireasy.Data.Entity.Linq { /// <summary> /// <see cref="IDataSegment"/> 查找器。 /// </summary> internal class SegmentFinder : Common.Linq.Expressions.ExpressionVisitor { private IDataSegment dataSegment; /// <summary> /// <see cref="IDataSegment"/> 查找器。 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static IDataSegment Find(Expression expression) { var replaer = new SegmentFinder(); replaer.Visit(expression); return replaer.dataSegment; } protected override Expression VisitConstant(ConstantExpression constExp) { if (constExp.Value is IDataSegment) { dataSegment = constExp.Value as IDataSegment; } return constExp; } } }
public class Solution { public int CountPrimes(int n) { int res = 0; var hs = new HashSet<int>(); for (int i=2; i<n; i++) { if (!hs.Contains(i)) { res++; for (int j=2; j<=n/i; j++) { int tmp = i*j; if (!hs.Contains(tmp)) hs.Add(tmp); } } } return res; } }
using AndreMotos.Dominio.EstoqueRoot; using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AndreMotos.Application.Validacao { public class ProdutoValidation : AbstractValidator<Produto> { public ProdutoValidation() { RuleFor(a => a.NomeProduto) .NotEmpty().WithMessage("O compo {PropertyName} é obrigatório.") .Length(2, 150).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres."); RuleFor(a => a.Descricao) .NotEmpty().WithMessage("O compo {PropertyName} é obrigatório.") .Length(2, 150).WithMessage("O campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres."); } } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Title : MonoBehaviour { private int selectedStageNum; public AudioClip BGM; public AudioClip btnSE; public Image fade; public Image cutScene; public Text cutText; public Button fastBtn; public GameObject optPanel; public GameObject creditPanel; public GameObject pausePanel; public GameObject cutPanel; public GameObject collectPanel; public GameObject goalPanel; public Text goalText; public GameObject pingImg; public GameObject pingImg2; public Text stageText; public Image[] scoreStar = new Image[3]; public Sprite noStar; public Sprite yesStar; public Button[] On_Off = new Button[3]; public Sprite[] On_Off_Sprite = new Sprite[2]; public Sprite[] cutScene_Sprite = new Sprite[2]; // Use this for initialization void Start () { //AudioSource.PlayClipAtPoint(BGM,transform.position); //GetComponent<AudioSource>().loop = true; Debug.Log (PlayerPrefs.GetInt ("clearedStage")); fade = GameObject.Find("Fade").GetComponent<Image>(); fade.color = new Color(0,0,0,255); StartCoroutine ("fadein"); if(SceneManager.GetActiveScene().name == "Title") StartCoroutine (startCutScene ()); } void checkEndGame() { if (Input.GetKeyDown(KeyCode.Escape)) { //Quit game Application.Quit(); } } //cutscene IEnumerator startCutScene(){ yield return new WaitForSeconds (3.0f); cutScene.CrossFadeColor (new Color (0, 0, 0,0), 0.5f, true, true); yield return new WaitForSeconds (0.5f); cutScene.sprite = cutScene_Sprite [0]; cutText.text = "빨강머리 용사는 슬라임을 잡아 강해지기 위해 \r슬라임 마을을 습격한다! \r"; cutText.GetComponent<RectTransform> ().localPosition = new Vector2 (-165, -68); cutScene.CrossFadeColor (new Color (255, 255, 255), 1.0f, false, true); yield return new WaitForSeconds (3.0f); cutScene.CrossFadeColor (new Color (0, 0, 0,0), 0.5f, true, true); yield return new WaitForSeconds (0.5f); cutScene.sprite = cutScene_Sprite [1]; cutText.text = "라이벌인 빨간머리 용사가 더 이상 강해지지못하게 \n슬라임들을 구해라! "; cutText.GetComponent<RectTransform> ().localPosition = new Vector2 (230 , -120); cutScene.CrossFadeColor (new Color (255, 255, 255), 0.5f, false, true); yield return new WaitForSeconds (3.0f); cutScene.CrossFadeColor (new Color (0, 0, 0,0), 0.5f, true, true); yield return new WaitForSeconds (0.7f); cutPanel.SetActive (false); } //fade in/out IEnumerator fadein(){ fade.CrossFadeAlpha(0.0f, 1, true); yield return new WaitForSeconds (1.0f); fade.canvasRenderer.SetAlpha(0.0f); fade.gameObject.SetActive(false); } IEnumerator fadeOut() { fade.gameObject.SetActive(true); fade.CrossFadeAlpha(255, 1.0f, false); yield return new WaitForSeconds(1.0f); } // Update is called once per frame void Update () { if (PlayerPrefs.GetInt ("isNotFirst") == 1 && SceneManager.GetActiveScene().name == "Title") { if (Input.GetMouseButtonDown (0)) { StopCoroutine (startCutScene ()); cutPanel.SetActive (false); } } checkEndGame(); debugging (); } public void allClearBtnDown(){ PlayerPrefs.SetInt("clearedStage",8); GameObject.Find("Main Camera").GetComponent<StageSelete>().showStage(); } void debugging() { if (Input.GetKeyDown(KeyCode.Delete)) { PlayerPrefs.DeleteAll(); Debug.Log ("deleteAll"); PlayerPrefs.SetInt("clearedStage",-1); } }//title btn public void titleCloseBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); creditPanel.SetActive (false); optPanel.SetActive (false); collectPanel.SetActive(false); goalPanel.SetActive(false); } public void optBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); optPanel.SetActive (true); } public void collBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); collectPanel.SetActive(true); } public void titleOnOffBtnDown(int n){ if (On_Off [n].image.sprite.name == "option_off") On_Off [n].image.sprite = On_Off_Sprite [0]; else On_Off [n].image.sprite = On_Off_Sprite [1]; } public void creditBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); creditPanel.SetActive (true); optPanel.SetActive (false); } //in stage Btn public void fastBtnDown() { AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); if(Time.timeScale < 2) Time.timeScale = 2; else Time.timeScale = 1; } public void pausBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); pausePanel.SetActive (true); Time.timeScale = 0; } public void ContinueBtn(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); pausePanel.SetActive (false); Time.timeScale = 1; } //menu btn public void nextBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex+1); } public void menuBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); SceneManager.LoadScene (2); } public void replayBtnDown(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex); } public void SelectStage(int n){ goalText.text = userData.stage[n].getGoalString(); pingImg.SetActive(false); stageText.text = "Stage "+ (n+1); selectedStageNum = n; int score = PlayerPrefs.GetInt("Stage" + n + "Score"); Debug.Log(score); if (score < 3) { scoreStar[0].sprite = noStar; scoreStar[1].sprite = noStar; scoreStar[2].sprite = noStar; } else if (score < 10) { scoreStar[1].sprite = noStar; scoreStar[2].sprite = noStar; } else if (score >= 10 && score < 20) scoreStar[2].sprite = noStar; else{ scoreStar[0].sprite = yesStar; scoreStar[1].sprite = yesStar; scoreStar[2].sprite = yesStar; } goalPanel.SetActive(true); if(PlayerPrefs.GetInt ("isNotFirst") == 0){ pingImg2.SetActive(true); } } public void StageStart(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); userData.curStageNum = selectedStageNum; SceneManager.LoadScene (selectedStageNum+3); } public void SelectChapter(){ AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); SceneManager.LoadScene (2,LoadSceneMode.Single); } public void GameStart(){ //StartCoroutine(fadeOut()); AudioSource.PlayClipAtPoint(btnSE,Camera.main.transform.position); SceneManager.LoadScene (2,LoadSceneMode.Single); } }
using System; using System.Collections.Generic; using System.Linq; using OPyke.ZopaTest.LoanProcessor.Interfaces; using OPyke.ZopaTest.LoanProcessor.Model; namespace OPyke.ZopaTest.LoanProcessor.Implementation { public class InterestCalculator : IInterestCalculator { private readonly IFinancierInterestCalculator _financierInterestCalculator; public InterestCalculator(IFinancierInterestCalculator financierInterestCalculator) { if (financierInterestCalculator == null) { throw new ArgumentNullException(nameof(financierInterestCalculator)); } _financierInterestCalculator = financierInterestCalculator; } public LoanResponse Calculate(LoanRequest loanRequest, IEnumerable<Financier> financiers, int numberOfRepayments) { if (loanRequest == null) throw new ArgumentNullException(nameof(loanRequest), "loanRequest parameter must be specified"); if (financiers == null) throw new ArgumentNullException(nameof(financiers), "financiers parameter must be specified"); var financierList = financiers as IList<Financier> ?? financiers.ToList(); if (!financierList.Any()) throw new ArgumentException("financiers list is empty"); decimal totalInterestAmount = 0; foreach (var financier in financierList) { var totalAmount = financier.Amount; // TODO: Remove multiplication var interestRate = financier.Lender.Rate * 100; var financierInterest = _financierInterestCalculator.CalculateFinancierInterest(numberOfRepayments, totalAmount, interestRate); totalInterestAmount += financierInterest; } var totalRepayment = decimal.Round((loanRequest.LoanAmount + totalInterestAmount),2); var monthlyRepayment = decimal.Round(totalRepayment / numberOfRepayments,2); var overallInterestRate = decimal.Round(totalInterestAmount / loanRequest.LoanAmount * 100 , 1); var returnValue = new LoanResponse(loanRequest.LoanAmount, overallInterestRate, monthlyRepayment, totalRepayment); return returnValue; } } }
namespace Pobs.Comms { public interface IEmailSenderConfig { string SmtpUsername { get; } string SmtpPassword { get; } string SmtpHost { get; } int SmtpPort { get; } } }
using Microsoft.AspNetCore.SignalR.Client; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DIPS.Samsnakk.Client.Interfaces { public interface ISignalRService { public Task Connect(); public HubConnection GetConnection(); public Task GetUsers(); public Task GetGroups(); public Task<string> Login(string username); public Task SendMessage(string receiver, string message); public Task SendMessage(string groupName, string message, string sender); public Task<List<string>> GetMessages(string username); public Task<List<string>> GetGroupMessages(string groupName); public Task JoinGroup(string groupName); public Task AddGroup(string groupName); public Task UpdateNotifications(List<string> notifications); public Task<List<string>> GetNotifications(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication1.Models; namespace MvcApplication1.Controllers { public class AccountController : Controller { // // GET: /Account/ public ActionResult Index() { return View(); } public ActionResult Logout() { return RedirectToAction("Index", "Home"); } [HttpPost] public ActionResult Index(User user) { MVCTestEntities _entity = new MVCTestEntities(); var _result = _entity.Users.Where(x => x.Email == user.Email && x.Pws == user.Pws).ToList(); if (_result.Count > 0) { Session["UserID"] = _result[0].UserID; if(user.Email =="admin@myshop.com") return RedirectToAction("Index", "Admin"); else return RedirectToAction("Index", "Shopping"); } else { Session["UserID"] = null; return View(); } } public ActionResult RegisterUser() { return View(); } [HttpPost] public ActionResult RegisterUser( User user) { if (ModelState.IsValid) { MVCTestEntities _entity = new MVCTestEntities(); _entity.Users.Add(user); _entity.SaveChanges(); return View("Index"); } else { return View(); } } } }
namespace Vlc.DotNet.Core { public interface IAudioManagement { IAudioOutputsManagement Outputs { get; } bool IsMute { get; set; } void ToggleMute(); int Volume { get; set; } ITracksManagement Tracks { get; } int Channel { get; set; } long Delay { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using SimpleJSON; using UnityEngine; namespace Daz3D { public class MaterialMap { public MaterialMap(string path) { Path = path; } public void AddMaterial(Material material) { if (material && !Map.ContainsKey(material.name)) Map.Add(material.name, material); } public string Path { get; set; } public Dictionary<string, Material> Map = new Dictionary<string, Material>(); } #region Material Properties public struct DTUMaterialProperty { public string Name; public DTUValue Value; public string Texture; public bool TextureExists() { return !string.IsNullOrEmpty(Texture); } /// <summary> /// True if this property was found in the DTU /// </summary> public bool Exists; public Color Color => Value.AsColor; public float ColorStrength => Utilities.GetStrengthFromColor(Color); public float Float => (float) Value.AsDouble; public bool Boolean => Value.AsDouble > 0.5; public static DTUMaterialProperty FromJSON(JSONNode prop) { var dtuMatProp = new DTUMaterialProperty(); //since this property was found, mark it dtuMatProp.Exists = true; dtuMatProp.Name = prop["Name"].Value; dtuMatProp.Texture = prop["Texture"].Value; var v = DTUValue.FromJSON(prop); dtuMatProp.Value = v; return dtuMatProp; } } /// <summary> /// These are analagous to the shaders in Daz3D, if your shader is not in this list /// the material will fail or be skipped /// </summary> public enum DTUMaterialType { Unknown, IrayUber, PBRSP, DazStudioDefault, OmUberSurface, OOTHairblendingHair, BlendedDualLobeHair, //used in some dforce hairs PBRSkin } /// <summary> /// Used with the Daz Studio Default shader /// </summary> public enum DTULightingModel { Unknown = -1, Plastic = 0, Metallic = 1, Skin = 2, GlossyPlastic = 3, Matte = 4, GlossyMetallic = 5, } /// <summary> /// Used when the shader type is Iray Uber, this defines the flow and changes which properties are read /// </summary> public enum DTUBaseMixing { Unknown = -1, PBRMetalRoughness = 0, PBRSpecularGlossiness = 1, Weighted = 2, } #endregion [Serializable] public struct DTUMaterial { public float Version; public string AssetName; public string MaterialName; public string MaterialType; public string Value; public List<DTUMaterialProperty> Properties; private Dictionary<string, DTUMaterialProperty> _map; public static DTUMaterial FromJSON(JSONNode matValue) { var dtuMat = new DTUMaterial(); dtuMat.Version = matValue["Version"].AsFloat; dtuMat.AssetName = matValue["AssetName"].Value; dtuMat.MaterialName = matValue["MaterialName"].Value; dtuMat.MaterialType = matValue["MaterialType"].Value; dtuMat.Value = matValue["Value"].Value; dtuMat.Properties = new List<DTUMaterialProperty>(); var properties = matValue["Properties"]; foreach (var propKVP in properties) { var dtuMatProp = DTUMaterialProperty.FromJSON(propKVP.Value); dtuMat.Properties.Add(dtuMatProp); } return dtuMat; } public Dictionary<string, DTUMaterialProperty> Map { get { if (_map == null || _map.Count == 0) { _map = new Dictionary<string, DTUMaterialProperty>(); if (Properties != null) { foreach (var prop in Properties) { _map[prop.Name] = prop; } } } return _map; } } public DTUMaterialProperty Get(string key) { if (Map.ContainsKey(key)) { return Map[key]; } return new DTUMaterialProperty(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace shp读取 { struct PointD { double x, y; public PointD(double x0, double y0) { this.x = x0; this.y = y0; } public double X { get { return this.x; } } public double Y { get { return this.y; } } } class PointFeature { static ShapeTypes shapeType = ShapeTypes.Point; static int shapeTypeID = 1; public double x; public double y; public PointFeature(double x0, double y0) { this.x = x0; this.y = y0; } public Point GetBMPPoint(BBOX boundarybox, int width, int height) { double x = width * (this.x - boundarybox.xmin) / (boundarybox.xmax - boundarybox.xmin); double y = height * (this.y - boundarybox.ymin) / (boundarybox.ymax - boundarybox.ymin); Point bmpPoint = new Point((int)x, height - (int)y); return bmpPoint; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Easy.Domain.Base; namespace Supplier.Model { public class Delivery : EntityBase<int> { public Delivery() { } public int ID { set; get; } public string Name { set; get; } protected override BrokenRuleMessage GetBrokenRuleMessages() { return null; } public override bool Validate() { return true; } } }
using System.IO; using SqlServerRunnerNet.Controls.DirectoryTreeView.Data; namespace SqlServerRunnerNet.Controls.DirectoryTreeView.ViewModel { public class FolderViewModel : DirectoryTreeViewItemViewModel { private readonly Folder _folder; private readonly string _displayPath; public FolderViewModel(Folder folder, DirectoryTreeViewItemViewModel parentFolderViewModel) : base(parentFolderViewModel, true) { _folder = folder; var dir = new DirectoryInfo(_folder.FolderPath); _displayPath = dir.Name; } public override string FullPath { get { return _folder.FolderPath; } } public override string DisplayPath { get { return _displayPath; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace ztm_otwartedane { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class EstimatedArrives : ContentPage { List<BusEstimatedTime> GetEstimatedArrives(int id) { string url = "http://87.98.237.99:88/delays?stopId=" + id; var response = ApiRequests.GET(url); return BusEstimatedTimeParser.FromJson(response).allArrives; } public EstimatedArrives (int id, string name) { this.Title = name; InitializeComponent (); estimatedArrives.ItemsSource = GetEstimatedArrives(id); } private void EstimatedArrives_ItemSelected(object sender, SelectedItemChangedEventArgs e) { if (estimatedArrives.SelectedItem == null) return; estimatedArrives.SelectedItem = null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FightingScript : MonoBehaviour { public CharacterController controller; public float moveSpeed; public float gravityScale; public float jumpForce; Vector3 moveDirection; public GameObject snowball; public GameObject stick; public GameObject earthPiece; public ParticleSystem sleepStorm; public ParticleSystem speedBurst; GameObject snowballClone; GameObject stickClone; GameObject earthPieceClone; ParticleSystem sleepStormClone; ParticleSystem speedBurstClone; bool spinStick; float timeBetweenSnowballs; Transform cameraRep; bool movingWithShield = false, setUpShield = true; float setupShieldTime; float setupShieldDone; bool sleepFieldOn = false; // Start is called before the first frame update void Start() { timeBetweenSnowballs = Time.time; setupShieldTime = 4.5f; setupShieldDone = Time.time + setupShieldTime; spinStick = true; } // Update is called once per frame void Update() { if (Input.GetKey(KeyCode.C) && (Time.time - timeBetweenSnowballs) >= 0.10f) { timeBetweenSnowballs = Time.time; snowballClone = Instantiate(snowball, transform.position, Camera.main.transform.rotation); } if (Input.GetKeyDown(KeyCode.T)) { if (spinStick) { spinStick = false; stickClone = Instantiate(stick, new Vector3(transform.position.x + 2, transform.position.y, transform.position.z), Quaternion.Euler(0, 0, 103.45f)); stickClone.GetComponent<Orbit>().target = transform; } } if (Input.GetKeyUp(KeyCode.T)) { Destroy(stickClone); spinStick = true; } if (Input.GetKeyDown(KeyCode.E)) { cameraRep = Camera.main.transform; earthPieceClone = Instantiate(earthPiece, transform.position + cameraRep.forward * 2.5f, Quaternion.Euler(0f, cameraRep.transform.eulerAngles.y, 0f)); earthPieceClone.transform.position = new Vector3(earthPieceClone.transform.position.x, 0.235f - 2.7f, earthPieceClone.transform.position.z); //Debug.Log("sp: " + earthPieceClone.transform.position); } if (Input.GetKeyDown(KeyCode.M)) { speedBurstClone = Instantiate(speedBurst, transform.position, Quaternion.Euler(-90, 0, 0)); speedBurstClone.GetComponent<SleepBurst>().player = transform.gameObject; speedBurstClone.Play(); } if (Input.GetKeyDown(KeyCode.Z)) { sleepStormClone = Instantiate(sleepStorm, transform.position, Quaternion.Euler(-90, 0, 0)); sleepStormClone.GetComponent<PinkStorm>().player = transform.gameObject; sleepStormClone.Play(); sleepFieldOn = true; } if (sleepFieldOn) { if (Time.time > setupShieldDone && sleepStormClone != null && setUpShield) { sleepStormClone.GetComponent<SphereCollider>().enabled = true; //Debug.Log("enabled setup collider"); setUpShield = false; } if (movingWithShield) { if (Input.GetAxis("Horizontal") == 0 && Input.GetAxis("Vertical") == 0) { movingWithShield = false; sleepStormClone.GetComponent<PinkStorm>().colliderTime = Time.time + sleepStormClone.GetComponent<PinkStorm>().waitTime; //Debug.Log("time set"); } } if (Input.GetAxis("Horizontal") != 0 || Input.GetAxis("Vertical") != 0) { setUpShield = false; //if (!movingWithShield) Debug.Log("movement detected"); sleepStormClone.GetComponent<PinkStorm>().colliderTime = 0; sleepStormClone.GetComponent<SphereCollider>().enabled = false; movingWithShield = true; } } moveDirection = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, 0f, Input.GetAxis("Vertical") * moveSpeed); controller.Move(moveDirection * Time.deltaTime); } /* cameraRep = Camera.main.transform; cameraRep.transform.eulerAngles = new Vector3(-2.5f, cameraRep.transform.eulerAngles.y, cameraRep.transform.eulerAngles.z); earthPieceClone = Instantiate(earthPiece, transform.position + cameraRep.forward * 2.5f, Quaternion.Euler(0f, cameraRep.transform.eulerAngles.y, 0f)); earthPieceClone.transform.position = new Vector3(earthPieceClone.transform.position.x, 0.235f - 2.7f, earthPieceClone.transform.position.z); Debug.Log("sp: " + earthPieceClone.transform.position); /* for (int i = -2; i < 3; i++) { earthPieceClone = Instantiate(earthPiece, new Vector3(transform.position.x + i * 2, transform.position.y - 3, transform.position.z + 2), transform.rotation); earthPieceClone.GetComponent<EarthPieceMovement>().player = transform.gameObject; } */ }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConfirmPanel : MonoBehaviour { // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void Init(string szContnet, System.Action<object> pfConfirmFunc, object pParam1, System.Action<object> pfCancleFunc, object pParam2) { m_pfConfirmFunc = pfConfirmFunc; m_pParam1 = pParam1; m_pfCancleFunc = pfCancleFunc; m_pParam2 = pParam2; m_textContent.text = szContnet; if (m_pfConfirmFunc != null) { m_buttonConfirm.onClick.AddListener(delegate () { m_pfConfirmFunc(m_pParam1); Destroy(gameObject); }); } if (m_pfCancleFunc != null) { m_buttonCancle.onClick.AddListener(delegate () { m_pfCancleFunc(m_pParam2); Destroy(gameObject); }); } } public void Init(string szContnet, string szConfirm, string szCancle, System.Action<object> pfConfirmFunc, object pParam1, System.Action<object> pfCancleFunc, object pParam2) { m_pfConfirmFunc = pfConfirmFunc; m_pParam1 = pParam1; m_pfCancleFunc = pfCancleFunc; m_pParam2 = pParam2; m_textContent.text = szContnet; m_textConfirm.text = szConfirm; m_textCancle.text = szCancle; if (m_pfConfirmFunc != null) { m_buttonConfirm.onClick.AddListener(delegate () { m_pfConfirmFunc(m_pParam1); Destroy(gameObject); }); } if (m_pfCancleFunc != null) { m_buttonCancle.onClick.AddListener(delegate () { m_pfCancleFunc(m_pParam2); Destroy(gameObject); }); } } [SerializeField] UnityEngine.UI.Button m_buttonConfirm = null; [SerializeField] UnityEngine.UI.Text m_textConfirm = null; [SerializeField] UnityEngine.UI.Button m_buttonCancle = null; [SerializeField] UnityEngine.UI.Text m_textCancle = null; [SerializeField] UnityEngine.UI.Text m_textContent = null; [SerializeField] System.Action<object> m_pfConfirmFunc; [SerializeField] object m_pParam1; [SerializeField] System.Action<object> m_pfCancleFunc; [SerializeField] object m_pParam2; }
using jaytwo.Common.Http; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Text; using System.Text.RegularExpressions; namespace jaytwo.Common.System { public static class StringUtility { private static readonly Regex normalizeWhitespaceRegex = new Regex(@"[\s]{2,}", RegexOptions.Compiled); public static string NormalizeWhiteSpace(string value) { if (!string.IsNullOrEmpty(value)) { return normalizeWhitespaceRegex.Replace(value, " ").Trim(); } else { return value; } } public static string RemoveDiacritics(string value) { if (!string.IsNullOrEmpty(value)) { StringBuilder result = new StringBuilder(); foreach (var charFormD in value.Normalize(NormalizationForm.FormD).ToCharArray()) { UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory(charFormD); if (category != UnicodeCategory.NonSpacingMark) { result.Append(charFormD); } } return result.ToString().Normalize(NormalizationForm.FormC); } else { return value; } } } }
 /************************************************************************/ /* Project Name : RuiJieHacker */ /* Author: luoweifeng1989 */ /* Date: 2011-4-23 */ /* All Rights Reserved. */ /************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.NetworkInformation; using System.Windows.Forms; using System.Runtime.InteropServices; using System.ServiceProcess; using System.Management; using ROOT.CIMV2.Win32; namespace RuiJieHacker { class NetWorkHelper { /************************************************************************/ /* 导入依赖的Win Socket相关的DLL文件 */ /************************************************************************/ [DllImport("ws2_32.dll")] private static extern int inet_addr(string cp); [DllImport("IPHLPAPI.dll")] private static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 pMacAddr, ref Int32 PhyAddrLen); /************************************************************************/ /* */ /************************************************************************/ public static void restartEthernet() { SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2"); ManagementObjectSearcher search = new ManagementObjectSearcher(query); foreach (ManagementObject result in search.Get()) { NetworkAdapter adapter = new NetworkAdapter(result); // Here, we're selecting the LAN adapters. if (adapter.AdapterType.Equals("Ethernet 802.3")) { adapter.Disable(); adapter.Enable(); } } } /************************************************************************/ /* 根据远程主机的 IP 地址取得主机的 MAC Address(IP必须是局域网网段) */ /************************************************************************/ public static string GetMacAddress(string hostip) { string Mac = ""; try { Int32 ldest = inet_addr(hostip); Int64 macinfo = new Int64(); Int32 len = 6; SendARP(ldest, 0, ref macinfo, ref len); string temmac = Convert.ToString(macinfo, 16).PadLeft(12, '0'); Mac = temmac.Substring(0, 2).ToUpper(); for (int i = 2; i < temmac.Length; i = i + 2) { Mac = temmac.Substring(i, 2).ToUpper() + Mac; } } catch (Exception Mye) { MessageBox.Show(Mye.Message); } return Mac; } } }
namespace IdentifyMe.MVVM.Abstractions { /// <summary> /// Interface that lets us check whether a given viewmodel is part of a PopupPage /// </summary> public interface IPopupViewModel { } }
using ScriptableObjectFramework.Events.UnityEvents; using UnityEngine; namespace ScriptableObjectFramework.Events { public class BoolEventEmitter : BaseEventEmitter<bool, BoolUnityEvent> { } }
namespace AbstractFactory { public class ExecuteAbstractFactory { public static Carro MonstarCarro(string tipoCarro) { CarroFactory carroFactory = null; switch (tipoCarro) { case "luxo": carroFactory = new CarroLuxo(); break; case "popular": carroFactory = new CarroPopular(); break; } var carro = new Carro { Som = carroFactory.MontarSom(), Roda = carroFactory.MontarRoda() }; return carro; } } }
using UnityEngine; using System.Collections; using uDoil; public class LocomotionSMB : StateMachineBehaviour { public float m_Damping = 0.15f; // private readonly int m_HashHorizontalPara = Animator.StringToHash ("Horizontal"); // private readonly int m_HashVerticalPara = Animator.StringToHash ("Vertical"); override public void OnStateUpdate (Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { float horizontal = 0.GetAxis("L_HORIZONTAL"); float vertical = 0.GetAxis("L_VERTICAL"); // Vector2 input = new Vector2 (horizontal, vertical).normalized; // animator.SetFloat ("Horizontal", input.x, m_Damping, Time.deltaTime); // animator.SetFloat ("Vertical", input.y, m_Damping, Time.deltaTime); animator.SetFloat ("Horizontal", horizontal, m_Damping, Time.deltaTime); animator.SetFloat ("Vertical", vertical, m_Damping, Time.deltaTime); } }
namespace ostranauts_modding { public class LifeEvent { public double fShipCashReward { get; set; } public double fStartATCRange { get; set; } public string strInteraction { get; set; } public string strName { get; set; } public string strShipRewards { get; set; } public string strStartATC { get; set; } } }
using Angular7Mvc5.Controllers.Core; using Angular7Mvc5.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Angular7Mvc5.Controllers.Api { public class OrderProductsController : ApiController { private List<OrderProducts> OrderProducts { get; set; } public OrderProductsController() { //reload all the data first in ordr to keep all data updated. SystemController.Instance.LoadData(); //assign data OrderProducts = SystemController.Instance.OrderProducts; } // GET: api/OrderProducts public IEnumerable<OrderProducts> Get() { return OrderProducts; } // GET: api/OrderProducts/5 public OrderProducts Get(int id) { return OrderProducts.FirstOrDefault(i => i.OrderId == id); } } }
using UnityEngine; using System.Collections; public class MoveCamera : MonoBehaviour{ public Transform TheCamera; public float MoveSpeed = 1 , RotSpeed = 10; public bool PressLeftMBToRot = true; public bool HideCursor = false; public bool CanUpAndDown = true; public float UpDownSpeed = 1; public bool CanRot = true; public Vector3 CameraRot; void Start() { if (HideCursor) { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } CameraRot = TheCamera.eulerAngles; DeltaRotSpeed = RotSpeed*100; } float TheX,TheY; float DeltaRotSpeed; LightObj TheLO; void Update () { //Move if (Input.GetKey(KeyCode.W)||Input.GetKey(KeyCode.UpArrow)) { transform.position+=new Vector3(TheCamera.forward.x,0,TheCamera.forward.z).normalized*Time.deltaTime*MoveSpeed; } else if (Input.GetKey(KeyCode.S)||Input.GetKey(KeyCode.DownArrow)) { transform.position-=new Vector3(TheCamera.forward.x,0,TheCamera.forward.z).normalized*Time.deltaTime*MoveSpeed; } if (Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.LeftArrow)) { transform.position-=new Vector3(TheCamera.right.x,0,TheCamera.right.z).normalized*Time.deltaTime*MoveSpeed; } else if (Input.GetKey(KeyCode.D)||Input.GetKey(KeyCode.RightArrow)) { transform.position+=new Vector3(TheCamera.right.x,0,TheCamera.right.z).normalized*Time.deltaTime*MoveSpeed; } //Camera Rote if (CanRot) { if (PressLeftMBToRot) { if (Input.GetMouseButton(0)) { while (CameraRot.x > 90) { CameraRot -= new Vector3(180, 0, 0); } while (CameraRot.x < -90) { CameraRot += new Vector3(180, 0, 0); } while (CameraRot.y > 180) { CameraRot -= new Vector3(0, 360, 0); } while (CameraRot.y < -180) { CameraRot += new Vector3(0, 360, 0); } TheX = CameraRot.x - Input.GetAxis("Mouse Y") * DeltaRotSpeed * Time.deltaTime; if (TheX < -89) TheX = -89; if (TheX > 89) TheX = 89; TheY = CameraRot.y - Input.GetAxis("Mouse X") * DeltaRotSpeed * -0.6f * Time.deltaTime; CameraRot = new Vector3(TheX, TheY, 0); TheCamera.eulerAngles = CameraRot; } } else { while (CameraRot.x > 90) { CameraRot -= new Vector3(180, 0, 0); } while (CameraRot.x < -90) { CameraRot += new Vector3(180, 0, 0); } while (CameraRot.y > 180) { CameraRot -= new Vector3(0, 360, 0); } while (CameraRot.y < -180) { CameraRot += new Vector3(0, 360, 0); } TheX = CameraRot.x - Input.GetAxis("Mouse Y") * DeltaRotSpeed * Time.deltaTime; if (TheX < -89) TheX = -89; if (TheX > 89) TheX = 89; TheY = CameraRot.y - Input.GetAxis("Mouse X") * DeltaRotSpeed * -0.6f * Time.deltaTime; CameraRot = new Vector3(TheX, TheY, 0); TheCamera.eulerAngles = CameraRot; } } //Cursor Visible if(Input.GetKeyUp(KeyCode.Escape)) { HideCursor = !HideCursor; Cursor.visible = !HideCursor; if (HideCursor) { Cursor.lockState = CursorLockMode.Locked; } else { Cursor.lockState = CursorLockMode.None; } } //Move Up and Down if(CanUpAndDown) { if(Input.GetKey(KeyCode.Space)) { TheCamera.position+=Vector3.up * 0.1f * UpDownSpeed* Time.deltaTime; } else if(Input.GetKey(KeyCode.LeftShift)) { TheCamera.position-=Vector3.up * 0.1f * UpDownSpeed* Time.deltaTime; } } if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { TheLO = hit.transform.GetComponent<LightObj>(); if (TheLO) { TheLO.OnClick(); } } } } public void SetCanRot() { CanRot = true; } public void SetCanNotRot() { CanRot = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NetApi; namespace TraderApiTest { class Program { static void Main(string[] args) { Callback pcallback = new Callback("114.113.231.66:56001", "trade1", "123", "37000205_02", 1, 2); if (pcallback.init()) { pcallback.join(); } System.Console.WriteLine("Main process exit unexpectedly"); } } }
using System; using UnityEngine; namespace Project.Game.UI { public enum Swipe { left, rigth, up, down, none }; public class UIControls : MonoBehaviour { public bool swipeLeft, swipeRight, swipeUp, swipeDown, forceCancel = false; public Swipe swipe = Swipe.none; private Vector2 origin; private Vector2 current; private Vector2 delta; private float angle; private float minDistance = 10f; private float time; public string debug = ""; //public Controls mainControls; public GameObject defaulPanel; public event Action<Swipe> UIUpdate; private void Update() { if (Input.touchCount > 0) { debug = Input.touches[0].phase.ToString(); if (Input.touches[0].phase == TouchPhase.Began) { Reset(); time = Time.time; origin = Input.touches[0].position; current = Input.touches[0].position; } else if (Input.touches[0].phase == TouchPhase.Canceled ) { forceCancel = true; Debug.Log("Called by canceled or stationary"); } else if (Input.touches[0].phase == TouchPhase.Ended) { if (forceCancel) return; Vector2 v = current - origin; if (v.magnitude < minDistance || Time.time - time > 1f) return; float x = v.x; float y = v.y; if (Mathf.Abs(x) > Mathf.Abs(y)) { if (x < 0 && UIUpdate != null) UIUpdate(Swipe.rigth); else if (UIUpdate != null) UIUpdate(Swipe.left); } else { if (y < 0 && UIUpdate != null) UIUpdate(Swipe.down); else if (UIUpdate != null) UIUpdate(Swipe.up); } } else { if (forceCancel) return; if (current == origin) { current = Input.touches[0].position; angle = Vector2.SignedAngle(current - origin, Vector2.zero); return; } delta = Input.touches[0].position - current; float deltaAngle = Vector2.SignedAngle(delta, Vector2.zero); if (Mathf.Abs(deltaAngle) > Mathf.Abs(angle) * 1.25f) // este valor deberia ser el cambio minimo para salir de algun limite { forceCancel = true; Debug.Log("Called by angle"); return; } current = Input.touches[0].position; } } } private void Reset() { origin = current = delta = Vector2.zero; angle = 0; swipeLeft = swipeRight = swipeUp = swipeDown = forceCancel = false; } public void ResetUI() { foreach (Transform panel in GetComponentInChildren<Transform>()) panel.gameObject.SetActive(false); defaulPanel.SetActive(true); } private void OnEnable() { // mainControls.enabled = false; } private void OnDisable() { //mainControls.enabled = true; ResetUI(); gameObject.SetActive(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using KartObjects; using KartObjects.Entities; using KartObjects.Entities.Documents; using System.Threading; using System.Data; namespace KartExchangeEngine { public class ExchangeJobShtrihM : FileExchangeJob { public ExchangeJobShtrihM(AbstractFlagMonitor flagMonitor) : base(flagMonitor) { PointsOfSale = Loader.DbLoad<PointOfSale>(""); POSDevices = Loader.DbLoad<POSDevice>(""); PayTypes = Loader.DbLoad<PayType>(""); Cashiers = Loader.DbLoad<Cashier>(""); } public override string FriendlyName { get { return "Обмен с кассовым модулем Штрих-М"; } } List<PointOfSale> PointsOfSale; List<POSDevice> POSDevices; List<PayType> PayTypes; List<Cashier> Cashiers; int PosNum; int ShiftNumber; ZReport CurrReport; long IdPosDevice; int SleepInterval = 5000; //Пауза перед выгрузкой public override void DoExport(List<string> DataList) { if ((FlagMonitor as TimeFileMonitor).IsPosExchange) DoImportPOSSale(); else DoExportPOSSale(); } /// <summary> /// Импорт реализации /// </summary> /// <param name="DataList"></param> private void DoExportPOSSale() { WriteLog("Начало работы импорта реализации "); DirectoryInfo di = new DirectoryInfo(FlagMonitor.DirName); FileInfo[] fi = di.GetFiles("*.rep"); if ((fi.Length > 0) && (Loader.DataContext.CheckConnection())) { for (int i = 0; i < fi.Length; i++) { PosNum = Int32.Parse(fi[i].Name.Substring(3, fi[i].Name.Length - fi[i].Name.IndexOf('.') - 3)); ShiftNumber = 0; using (StreamReader sw = new StreamReader(fi[i].FullName, Encoding.GetEncoding(1251))) { sw.ReadLine(); sw.ReadLine(); sw.ReadLine(); while (!sw.EndOfStream) { string[] starr = sw.ReadLine().Split(';'); if (starr[7] != "") if (Int64.Parse(starr[3]) == 61) { ShiftNumber = Int32.Parse(starr[7]); break; } } } if (ShiftNumber == 0) { WriteLog("Не найден номер отчета"); return; } using (StreamReader sw = new StreamReader(fi[i].FullName, Encoding.GetEncoding(1251))) { sw.ReadLine(); sw.ReadLine(); sw.ReadLine(); //ShiftNumber = Int32.Parse(sw.ReadLine()); PayType pt = PayTypes.FirstOrDefault(q => q.PayTypeInfo == PayTypeInfo.Cash); IdPosDevice = (from p in POSDevices from s in PointsOfSale where s.Id == p.IdPointOfSale && s.Number == PosNum && p.POSDeviceType == POSDeviceType.Printer select p.Id).First(); CurrReport = new ZReport(IdPosDevice, ShiftNumber); int counter = 0; while (!sw.EndOfStream) { parseReportString(sw.ReadLine().Split(';')); counter++; if (counter % 100 == 0) WriteLog("Обработано " + counter + " строк"); } } WriteLog("Файл " + fi[i].Name + " обработан"); File.Delete(fi[i].FullName); } } WriteLog("Конец работы импорта реализации "); } List<Receipt> _Receipt; List<ZReport> _ZReport; List<ReceiptSpecRecord> _CurrRecord; /// <summary> /// Экспорт реализации /// </summary> private void DoImportPOSSale() { WriteLog("Начало работы экспорта реализации "); //DirectoryInfo di = new DirectoryInfo(FlagMonitor.DirName); _ZReport = Loader.DbLoad<ZReport>("STATUS = 0 OR STATUS = 1"); if (_ZReport != null) { for (int i = 0; i < _ZReport.Count; i++) //Цикл Z отчета { ZReportPayment _ZReportPayment = Loader.DbLoadSingle<ZReportPayment>("IDZREPORT = " + _ZReport[i].Id); Int64 ZRIdPosDevice = _ZReport[i].IdPosDevice; Int64 IDPD = (Loader.DbLoadSingle<POSDevice>("ID = " + ZRIdPosDevice)).IdPointOfSale; Int64 KKM = (Loader.DbLoadSingle<PointOfSale>("ID = " + IDPD)).Number; Int64 ZRShiftNumber = _ZReport[i].ShiftNumber; //DateTime RDateReceipt = _Receipt[i].DateReceipt; _Receipt = Loader.DbLoad<Receipt>("IDPOSDEVICE = " + Convert.ToString(ZRIdPosDevice) + " and SHIFTNUMBER = " + Convert.ToString(ZRShiftNumber)); if (_Receipt != null) { int t = 1; //Счетчки позиций в файле StreamWriter fs = null; DirectoryInfo di = new DirectoryInfo(FlagMonitor.DirName); FileInfo[] fi = di.GetFiles("reports" + KKM + ".txt"); if (fi.Length != 0) { StreamReader sr = new StreamReader(fi[0].FullName, Encoding.GetEncoding(1251)); if (sr.ReadLine() == "#") { string[] w = null; while (!sr.EndOfStream) { w = sr.ReadLine().Split(';'); } if (sr.EndOfStream) { sr.Close(); t = Convert.ToInt32(w[0]) + 1; fs = new StreamWriter(FlagMonitor.DirName + @"\reports" + KKM + ".txt", true); } } //if (sr.ReadLine() == "@") else { sr.Close(); fs = new StreamWriter(FlagMonitor.DirName + @"\reports" + KKM + ".txt"); fs.WriteLine("#"); fs.WriteLine(KKM); //Номер кассы fs.WriteLine(ZRShiftNumber); //Номер смены } } else { fs = new StreamWriter(FlagMonitor.DirName + @"\reports" + KKM + ".txt"); fs.WriteLine("#"); fs.WriteLine(KKM); //Номер кассы fs.WriteLine(ZRShiftNumber); //Номер смены } //fs.WriteLine("Id;IdCashier;BuyerSum;CustomerCardCode;DateReceipt;DirectOperation;IdCashier;KpkNum;Number;ReceiptStatus;TotalDiscount;TotalSum"); int s = 0; string st = ""; //foreach (var item in _Receipt) //Цикл чеков в Z отчета for (int e = 0; e < _Receipt.Count; e++) { _CurrRecord = Loader.DbLoad<ReceiptSpecRecord>("", 0, _Receipt[e].Id); if (_CurrRecord == null) { continue; } else { _Receipt[e].ReceiptSpecRecords = _CurrRecord; string fl = "", tt = "11"; if (_Receipt[e].DirectOperation == 1) { fl = ""; tt = "11"; } else if (_Receipt[e].DirectOperation == -1) { fl = "-"; tt = "13"; } for (int r = 0; r < _CurrRecord.Count; r++) //Цикл позиций в чеке { if (!_CurrRecord[r].IsDeleted) { string _GoodCode = Loader.DbLoadSingle<GoodCode>("ID = " + _CurrRecord[r].IdGood).Code; if (_GoodCode != null) { st = ""; st += string.Format("{0:D6}", (t)) + ";"; //Счетчик st += String.Format("{0}.{1}.{2};", _Receipt[e].DateReceipt.Day, _Receipt[e].DateReceipt.Month, _Receipt[e].DateReceipt.Year); //Дата транзакции st += String.Format("{0}:{1}:{2};", string.Format("{0:D2}", _Receipt[e].DateReceipt.Hour), string.Format("{0:D2}", _Receipt[e].DateReceipt.Minute), string.Format("{0:D2}", _Receipt[e].DateReceipt.Second)); //Дата транзакции st += tt + ";"; //Тип транзакции st += KKM + ";"; //Номер ККМ st += _Receipt[e].Number + ";"; //Номер чека st += _Receipt[e].IdCashier + ";"; //Код кассира st += _GoodCode + ";"; //Код st += "1;"; //Секция st += String.Format("{0:#.00};", _CurrRecord[r].Price).Replace(",", "."); //Цена st += String.Format("{0}{1};", fl, _CurrRecord[r].Quantity); //Количество st += String.Format("{0}{1:#.00};", fl, (_CurrRecord[r].Price * Convert.ToDecimal(_CurrRecord[r].Quantity))).Replace(",", "."); //Цена * Количество fs.WriteLine(st); t++; } else { WriteLog("Позиция номер " + r + " не записана, пустое поле Code. Строка: " + t); } } } //Оплата st = ""; st += string.Format("{0:D6}", (t)) + ";"; //Счетчик st += String.Format("{0}.{1}.{2};", _Receipt[e].DateReceipt.Day, _Receipt[e].DateReceipt.Month, _Receipt[e].DateReceipt.Year); //Дата транзакции st += String.Format("{0}:{1}:{2};", string.Format("{0:D2}", _Receipt[e].DateReceipt.Hour), string.Format("{0:D2}", _Receipt[e].DateReceipt.Minute), string.Format("{0:D2}", _Receipt[e].DateReceipt.Second)); //Дата транзакции st += "40;"; //Тип транзакции st += KKM + ";"; //Номер ККМ st += _Receipt[e].Number + ";"; //Номер чека st += _Receipt[e].IdCashier + ";"; //Код кассира st += "0;"; //Код платежн. карты st += ";"; //- st += String.Format("{0:0.00};", (_Receipt[e].BuyerSum - _Receipt[e].TotalSum)).Replace(",", "."); //Сумма сдачи st += "2;"; //Номер вида оплаты st += String.Format("{0:#.00}", _Receipt[e].TotalSum).Replace(",", "."); //Сумма оплаты fs.WriteLine(st); t++; //Закрытие чека st = ""; st += string.Format("{0:D6}", (t)) + ";"; //Счетчик st += String.Format("{0}.{1}.{2};", _Receipt[e].DateReceipt.Day, _Receipt[e].DateReceipt.Month, _Receipt[e].DateReceipt.Year); //Дата транзакции st += String.Format("{0}:{1}:{2};", string.Format("{0:D2}", _Receipt[e].DateReceipt.Hour), string.Format("{0:D2}", _Receipt[e].DateReceipt.Minute), string.Format("{0:D2}", _Receipt[e].DateReceipt.Second)); //Дата транзакции st += "55;"; //Тип транзакции st += KKM + ";"; //Номер ККМ st += _Receipt[e].Number + ";"; //Номер чека st += _Receipt[e].IdCashier + ";"; //Код кассира st += "0;"; //Штрих-код чека st += ";"; //- st += ";"; //- st += ";"; //- st += String.Format("{0:#.00}", _Receipt[e].TotalSum).Replace(",", "."); //Сумма чека fs.WriteLine(st); s = e; t++; } } //Z отчет st = ""; st += string.Format("{0:D6}", (t)) + ";"; //Счетчик st += String.Format("{0}.{1}.{2};", _Receipt[s].DateReceipt.Day, _Receipt[s].DateReceipt.Month, _Receipt[s].DateReceipt.Year); //Дата транзакции st += String.Format("{0}:{1}:{2};", string.Format("{0:D2}", _Receipt[s].DateReceipt.Hour), string.Format("{0:D2}", _Receipt[s].DateReceipt.Minute), string.Format("{0:D2}", _Receipt[s].DateReceipt.Second)); //Дата транзакции st += "61;"; //Тип транзакции st += KKM + ";"; //Номер ККМ st += _Receipt[s].Number + ";"; //Номер чека st += _Receipt[s].IdCashier + ";"; //Код кассира int ZNumber = Loader.DbLoadSingle<ZReport>("ID = " + _ZReportPayment.IdZReport).ShiftNumber; st += ZNumber + ";"; //Номер отчета st += "0;"; //Логический номер ФРа st += String.Format("{0:#.00};", _ZReportPayment.TotalResult).Replace(",", "."); //Наличность в кассе st += ";"; //- st += String.Format("{0:#.00}", _ZReportPayment.TotalResult).Replace(",", "."); //Сумма выручки fs.WriteLine(st); fs.Flush(); fs.Close(); } //_ZReport[i].Status = 2; //Saver.SaveToDb<ZReport>(_ZReport[i]); string queryZReport = "update zreport set status = 2 where ID = " + _ZReport[i].Id; Saver.DataContext.ExecuteScalar(queryZReport); } } WriteLog("Конец работы экспорта реализации "); } Receipt CurrReceipt; ReceiptSpecRecord CurrRecord; private void parseReportString(string[] starr) { DateTime DateTran = Convert.ToDateTime(starr[1]); string[] TimeArr = starr[2].Split(':'); DateTran = DateTran.AddHours(Int32.Parse(TimeArr[0])).AddMinutes(Int32.Parse(TimeArr[1])).AddSeconds(Int32.Parse(TimeArr[2])); int tranType = Int32.Parse(starr[3]); int kkmNum = Int32.Parse(starr[4]); int receiptNum = Int32.Parse(starr[5]); int cashierCode = Int32.Parse(starr[6]); if (tranType == 11) { if (CurrReceipt == null) { CurrReceipt = new Receipt(IdPosDevice, ShiftNumber, receiptNum); CurrReceipt.DateReceipt = DateTran; CurrReceipt.DirectOperation = 1; } long GoodCode = Int64.Parse(starr[7]); Good g = Loader.DbLoadSingle<GoodCode>("articul=" + GoodCode); if (g == null) { WriteLog("Нет товара с кодом: " + GoodCode); return; } Assortment asrt= Loader.DbLoadSingle<Assortment>("IdGood=" + g.Id); if (asrt == null) { WriteLog("Нет ассортиментной позиции или штрихкода у товара с кодом: " + GoodCode); return; } CurrRecord = new ReceiptSpecRecord() { IdGood=asrt.IdGood, IdReceipt = CurrReceipt.Id, IsDeleted = false, NumPos = CurrReceipt.ReceiptSpecRecords.Count + 1, Quantity = Double.Parse(starr[10].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), Price = Decimal.Parse(starr[9].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), IdAssortment=asrt.Id, PromoActionEnabled=true }; CurrReceipt.ReceiptSpecRecords.Add(CurrRecord); } //Удаляем позицию if (tranType == 12) { long GoodCode = Int64.Parse(starr[7]); Good g = Loader.DbLoadSingle<GoodCode>("articul=" + GoodCode); CurrRecord = CurrReceipt.ReceiptSpecRecords.FirstOrDefault(q=>q.IdGood==g.Id); if (CurrRecord == null) { WriteLog("Нет позиций товара в чеке, возврат"); return; } if (CurrRecord.Quantity + Double.Parse(starr[10].Replace(",", decimalSeparator).Replace(".", decimalSeparator)) == 0) CurrRecord.IsDeleted = true; // CurrReceipt.ReceiptSpecRecords.Remove(CurrRecord); } if (tranType == 13) { if (CurrReceipt == null) { CurrReceipt = new Receipt(IdPosDevice, ShiftNumber, receiptNum); CurrReceipt.DateReceipt = DateTran; CurrReceipt.DirectOperation = -1; } long GoodCode = Int64.Parse(starr[7]); Good g = Loader.DbLoadSingle<GoodCode>("articul=" + GoodCode); if (g == null) { WriteLog("Нет товара с кодом: " + GoodCode); return; } Assortment asrt = Loader.DbLoadSingle<Assortment>("IdGood=" + g.Id); if (asrt == null) { WriteLog("Нет ассортиментной позиции или штрихкода у товара с кодом: " + GoodCode); return; } CurrRecord = new ReceiptSpecRecord() { IdGood = asrt.IdGood, IdReceipt = CurrReceipt.Id, IsDeleted = false, NumPos = CurrReceipt.ReceiptSpecRecords.Count + 1, Quantity = -1 * Double.Parse(starr[10].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), Price = Decimal.Parse(starr[9].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), IdAssortment = asrt.Id, PromoActionEnabled = true }; CurrReceipt.ReceiptSpecRecords.Add(CurrRecord); } if (tranType == 17) { if (CurrReceipt.GetRecords().Count == 0 || CurrReceipt.ReceiptSpecRecords.Count == 0) { WriteLog("Нет позиций товара в чеке, скидка"); return; } CurrReceipt.ApplySumDiscount(Decimal.Parse(starr[11].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), DiscountType.ReceiptSumDiscount); } if (tranType == 24) { if (CurrReceipt.ReceiptSpecRecords.Count == 0) { WriteLog("Нет позиций товара в чеке"); return; } CurrReceipt.ReceiptSpecRecords[CurrReceipt.ReceiptSpecRecords.Count-1].Barcode = starr[7]; Barcode b = Loader.DbLoadSingle<Barcode>("barcode='"+starr[7]+"'"); if (b == null) { WriteLog("Нет штрихкода: " + starr[7] + " в базе"); return; } CurrReceipt.ReceiptSpecRecords[CurrReceipt.ReceiptSpecRecords.Count-1].IdAssortment = b.IdAssortment; } if (tranType == 40) { if (starr[10] == "1.000") { PayType pt = PayTypes.FirstOrDefault(q=>q.PayTypeInfo== PayTypeInfo.Cash); Payment p = new Payment() { IdPayType = pt.Id, IdReceipt = CurrReceipt.Id, PaymentSum = Math.Abs(Decimal.Parse(starr[11].Replace(",", decimalSeparator).Replace(".", decimalSeparator)) - Decimal.Parse(starr[9].Replace(",", decimalSeparator).Replace(".", decimalSeparator))), PayType = pt }; CurrReceipt.Payment.Add(p); CurrReceipt.BuyerSum = Decimal.Parse(starr[9].Replace(",", decimalSeparator).Replace(".", decimalSeparator)); } if (starr[10] == "2.000") { PayType pt = PayTypes.FirstOrDefault(q => q.PayTypeInfo == PayTypeInfo.Cashless); Payment p = new Payment() { IdPayType = pt.Id, IdReceipt = CurrReceipt.Id, PaymentSum = Decimal.Parse(starr[11].Replace(",", decimalSeparator).Replace(".", decimalSeparator)), PayType = pt }; CurrReceipt.Payment.Add(p); } } if (tranType == 55) { //Чек Cashier cashier = Cashiers.FirstOrDefault(q => q.Code == cashierCode.ToString()); if (cashier != null) { CurrReceipt.Cashier = cashier; CurrReceipt.IdCashier = cashier.Id; } else CurrReceipt.IdCashier = Cashiers[0].Id; Saver.SaveToDb<Receipt>(CurrReceipt); //Спецификация if ((CurrReceipt as Receipt).ReceiptSpecRecords != null) foreach (ReceiptSpecRecord rsr in (CurrReceipt as Receipt).ReceiptSpecRecords) { Saver.SaveToDb<ReceiptSpecRecord>(rsr); //Скидки спецификации if (rsr.Discounts.Count > 0) foreach (ReceiptDiscount d in rsr.Discounts) { Saver.SaveToDb<ReceiptDiscount>(d); } } //Оплаты if (CurrReceipt.Payment != null) foreach (Payment p in CurrReceipt.Payment) { Saver.SaveToDb<Payment>(p); //Сохраняем оплаты картами foreach (CardPayment cp in p.CardPayments) { Saver.SaveToDb<CardPayment>(cp); } } CurrReceipt.ReceiptState = ReceiptState.Printed; CurrReport.AddReceipt(CurrReceipt); CurrReceipt = null; } if (tranType == 61) { CurrReport.ShiftTime = DateTran; Saver.SaveToDb<ZReport>(CurrReport); foreach (ZReportPayment zp in CurrReport.ZReportPayments) { //Накопительные счетчики zp.TotalReturn = Math.Abs(zp.TotalReturn); Saver.SaveToDb<ZReportPayment>(zp); } ShiftNumber += 1; CurrReport = new ZReport(IdPosDevice, ShiftNumber); } } protected string ClearJobFileName { get { return FlagMonitor.DirName + @"\clearjob.tsk"; } } private string[] GetPosToClearList() { string str = ""; if (File.Exists(ClearJobFileName)) { StreamReader reader = new StreamReader(ClearJobFileName); str = reader.ReadLine(); reader.Close(); } if (str==null) return new string[]{"0"}; else { if (str.Contains(',')) return str.Split(','); else return new string[] { str }; } } private void ExcludeClearPosList(string[] starr,int PosNumber) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < starr.Length; i++) { if (PosNumber.ToString() != starr[i]) sb.Append(starr[i] + ","); } if (sb.ToString() == ",") File.Delete(ClearJobFileName); else using (StreamWriter w = new StreamWriter(ClearJobFileName)) { w.WriteLine(sb.ToString().Remove(sb.Length - 1, 1)); w.Flush(); w.Close(); } } protected override void DoImport(List<string> DataList) { WriteLog("Пауза " + Convert.ToString(SleepInterval / 1000) + " секунд."); Thread.Sleep(SleepInterval); //DoImport(DataList); if ((FlagMonitor as TimeFileMonitor).IsPosExchange) DoRefFileExport(); else DoRefFileImport(); } /// <summary> /// Экспорт справочной информации /// </summary> /// <param name="DataList"></param> private void DoRefFileImport() { WriteLog("Начало выгрузки файла обмена "); if (Loader.DataContext.CheckConnection()) { List<PointOfSale> posList = Loader.DbLoad<PointOfSale>("permitreceivedata=1"); string[] PosToClear = GetPosToClearList(); foreach (var pos in posList) { bool IsOnline = true; if (PosToClear.FirstOrDefault(q => q == pos.Number.ToString()) != null) { string FileName = String.Format(@"{0}\pos{1}.spr", FlagMonitor.DirName, pos.Number); using (StreamWriter sw = new StreamWriter(FileName, false, Encoding.GetEncoding(1251))) { sw.WriteLine("##@@&&"); sw.WriteLine("#"); sw.WriteLine("$$$CLR"); sw.Flush(); sw.Close(); } //Создаем пустой файл using (FileStream fs = File.Create(FlagMonitor.DirName + @"\pos" + pos.Number + ".flg")) { fs.Close(); } System.Threading.Thread.Sleep(1000); int counter = 0; while ((File.Exists(FileName)) && (counter < 10)) { WriteLog("Ожидание обработки файла" + FileName); System.Threading.Thread.Sleep(1000); counter++; } IsOnline = counter < 10; if (IsOnline) ExcludeClearPosList(PosToClear, pos.Number); else File.Delete(FileName); } if (IsOnline) { string FileName1 = FlagMonitor.DirName + @"\pos" + pos.Number + ".spr"; using (StreamWriter sw = new StreamWriter(FileName1, false, Encoding.GetEncoding(1251))) { sw.WriteLine("##@@&&"); sw.WriteLine("#"); sw.WriteLine("$$$CLR"); List<ExportGoodShtrihM> goods = Loader.DbLoad<ExportGoodShtrihM>("", 0, pos.Id) ?? new List<ExportGoodShtrihM>(); int counter = 0; foreach (var item in goods) { sw.WriteLine(getGoodLine(item)); List<ExportBarcode> Barcodes = Loader.DbLoadFullQuery<ExportBarcode>("", 0, item.Id) ?? new List<ExportBarcode>(); foreach (var bc in Barcodes) { bc.IdGood = item.Id; sw.WriteLine(getBCLine(bc)); } counter++; if (counter % 100 == 0) WriteLog(String.Format("Обработано {0} из {1} товаров. Касса", counter, goods.Count)); } sw.Flush(); sw.Close(); } //Создаем пустой файл using (FileStream fs = File.Create(FlagMonitor.DirName + @"\pos" + pos.Number + ".flg")) { fs.Close(); } WriteLog("Выгружен файл " + FileName1); } else WriteLog("Касса оффлайн " + pos.Number); } } WriteLog("Конец выгрузки файла обмена "); } /// <summary> /// Импорт справочной информации /// </summary> private void DoRefFileExport() { WriteLog("Начало работы импорта справочной информации "); DirectoryInfo di = new DirectoryInfo(FlagMonitor.DirName); FileInfo[] fi = di.GetFiles("*.txt"); if ((fi.Length > 0) && (Loader.DataContext.CheckConnection())) { for (int i = 0; i < fi.Length; i++) { string PN = (fi[i].Name.Substring(0, fi[i].Name.Length - 4)); ShiftNumber = 0; using (StreamReader sw = new StreamReader(fi[i].FullName, Encoding.GetEncoding(1251))) { sw.ReadLine(); //Пропускаем строчку с ##@@&& sw.ReadLine(); //Пропускаем строчку с # //sw.ReadLine(); //Пропускаем строчку с $$$CLR int counter = 0; string gc = ""; while (!sw.EndOfStream) { string[] st = sw.ReadLine().Split(';'); if (Convert.ToString((st[0])[0]) != "#") //Группы товаров { string gg = ""; gc = st[0]; if (st[15] != "0") { gg = st[15]; } else { gg = "32150"; //Специальная группа товаров для 8ки } ImportGoodGroupCSV IGG = new ImportGoodGroupCSV() { Name = st[2], ParentCode = gg, Code = "43801" //Алкогольная группа 8ки }; Saver.SaveToDb<ImportGoodGroupCSV>(IGG); if (st[16] == "1") { decimal n = 0; if (st[4] != "") n = Convert.ToDecimal(st[4].Replace(".", ",")); else WriteLog("У товара " + st[2] + " нет цены"); ImportGoodCSV IG = new ImportGoodCSV() //Товары { Name = st[2], GroupCode = "9", //Код алкогольной группы 8ки Code = gc //Price = n }; Saver.SaveToDb<ImportGoodCSV>(IG); ImportPriceListCSV IPL = new ImportPriceListCSV() //Прайс дисты { PriceName = PN, //Наименование прайслиста Price = n, GoodCode = gc }; Saver.SaveToDb<ImportPriceListCSV>(IPL); if (st[1] != "") { ImportBarcodeCSV IB = new ImportBarcodeCSV() //Штрихкоды { Barcode = st[1], GoodCode = gc }; Saver.SaveToDb<ImportBarcodeCSV>(IB); } } } else { ImportBarcodeCSV IB = new ImportBarcodeCSV() //Штрихкоды { Barcode = st[1], GoodCode = gc }; Saver.SaveToDb<ImportBarcodeCSV>(IB); } counter++; if (counter % 100 == 0) WriteLog("Обработано " + counter + " строк"); } } WriteLog("Файл " + fi[i].Name + " обработан"); File.Delete(fi[i].FullName); } } WriteLog("Конец работы импорта справочной информации "); } private string getBCLine(ExportBarcode bc) { StringBuilder sb = new StringBuilder(); sb.Append("# "); sb.Append(bc.Articul+";"); sb.Append(bc.Barcode + ";"); sb.Append(bc.Name + ";"); sb.Append(bc.Name + ";"); sb.Append(bc.Price.ToString().Replace(",",".") + ";"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append("1;"); return sb.ToString(); } private string getGoodLine(ExportGoodShtrihM good) { StringBuilder sb = new StringBuilder(); sb.Append(good.Articul+ ";"); sb.Append(";"); sb.Append(good.Name+ ";"); sb.Append(";"); sb.Append(good.Price.ToString().Replace(",", ".") + ";"); sb.Append(";"); sb.Append(";"); if (good.IsWeight) sb.Append("1;"); else sb.Append("0;"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append(";"); sb.Append(good.GoodGroupCode + ";"); sb.Append(good.IsGood + ";"); return sb.ToString(); } } }
using NeuroLinker.Helpers; using NeuroLinker.Interfaces.Factories; using NeuroLinker.Interfaces.Helpers; using NeuroLinker.Interfaces.Workers; using NeuroLinker.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using NeuroLinker.ResponseWrappers; using VaraniumSharp.Attributes; namespace NeuroLinker.Workers { /// <summary> /// Push user updates to MAL /// </summary> [AutomaticContainerRegistration(typeof(IDataPushWorker))] public class DataPushWorker : IDataPushWorker { #region Constructor /// <summary> /// DI Constructor /// </summary> /// <param name="httpClientFactory">HttpClientFactory instance</param> /// <param name="listRetrievalWorker">List retrieval worker instance</param> /// <param name="xmlHelper">XML Helper instance</param> public DataPushWorker(IHttpClientFactory httpClientFactory, IListRetrievalWorker listRetrievalWorker, IXmlHelper xmlHelper) { _httpClientFactory = httpClientFactory; _listRetrievalWorker = listRetrievalWorker; _xmlHelper = xmlHelper; } #endregion #region Public Methods /// <summary> /// Push user details to MAL. /// This method automatically figures out if the anime should be added to the user's list or if it should simply be updated /// </summary> /// <param name="details">Update details</param> /// <param name="username">Username for authentication</param> /// <param name="password">Password for authentication</param> /// <returns>True - Update succeeded, otherwise false</returns> public async Task<DataPushResponseWrapper> PushAnimeDetailsToMal(AnimeUpdate details, string username, string password) { var userlist = await _listRetrievalWorker.RetrieveUserListAsync(username); var item = userlist.Anime.FirstOrDefault(t => t.SeriesId == details.AnimeId); return item == null ? await UpdateAnimeDetails(details, username, password) : await UpdateAnimeDetails(details, username, password, true); } #endregion #region Private Methods /// <summary> /// Push update/add details to MAL /// </summary> /// <param name="details">Update details</param> /// <param name="username">Username for authentication</param> /// <param name="password">Password for authentication</param> /// <param name="isupdate">Indicate if this is an update or an add</param> /// <returns>True - Update succeeded, otherwise false</returns> private async Task<DataPushResponseWrapper> UpdateAnimeDetails(AnimeUpdate details, string username, string password, bool isupdate = false) { try { var url = isupdate ? MalRouteBuilder.UpdateAnime(details.AnimeId) : MalRouteBuilder.AddAnime(details.AnimeId); var client = _httpClientFactory.GetHttpClient(username, password); var result = await client.PostAsync(url, new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("data", _xmlHelper.SerializeData(details)) })); return new DataPushResponseWrapper(result.StatusCode, result.IsSuccessStatusCode); } catch (Exception exception) { return new DataPushResponseWrapper(exception); } } #endregion #region Variables private readonly IHttpClientFactory _httpClientFactory; private readonly IListRetrievalWorker _listRetrievalWorker; private readonly IXmlHelper _xmlHelper; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.ComponentModel; namespace SurfaceApplicationMaurice.Utility { public class gradientManager { public gradientManager() { } public void setgradient(Panel elm) { LinearGradientBrush myBrush = new LinearGradientBrush(); Point startpoint = new Point(); int angle = CommunConfig.getInstance().Angle; startpoint.X = System.Math.Cos(((double)angle / 180) * System.Math.PI)/2 + 0.5; startpoint.Y = System.Math.Sin(((double)angle / 180) * System.Math.PI)/2 + 0.5; angle -= 180; Point endpoint = new Point(); endpoint.X = System.Math.Cos(((double)angle / 180) * System.Math.PI)/2 +0.5; endpoint.Y = System.Math.Sin(((double)angle / 180) * System.Math.PI)/2 +0.5; myBrush.StartPoint = startpoint; myBrush.EndPoint = endpoint; System.Windows.Media.Color c = new Color(); System.Drawing.Color drawingColor = CommunConfig.getInstance().StartColor; c = System.Windows.Media.Color.FromRgb(drawingColor.R, drawingColor.G, drawingColor.B); myBrush.GradientStops.Add(new GradientStop(c, 1)); drawingColor = CommunConfig.getInstance().EndColor; c = System.Windows.Media.Color.FromRgb(drawingColor.R, drawingColor.G, drawingColor.B); myBrush.GradientStops.Add(new GradientStop(c, 0)); elm.Background = myBrush; } } }
namespace CheckIt { using System; public class MatchException : Exception { public MatchException(string message, params object[] parameters) : base(string.Format(message, parameters)) { } } }
using System; namespace Simple.Expressions { public class Variable<T> : IExpression<T> { private readonly string name; public Variable(string name) { this.name = name; } public T Value { get { throw new InvalidOperationException("Variables need to be reduced to get their value"); } } public bool IsReducible { get { return true; } } public string Name { get { return name; } } public IExpression<T> Reduce(IEnvironment environment) { return environment.GetValue<T>(Name); } public override string ToString() { return Name; } } }
using System; namespace ValRefType { public struct Coordinate { public int X; public int Y; public Coordinate(int x, int y) { X = x; Y = y; } public void DisplayCoordinate() { Console.WriteLine("Coordinate value: X = {0}, Y = {1}", X, Y); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.Globalization; using System.IO; using IRAP.Global; namespace IRAP.PLC.Collection { public partial class frmSystemParams : Form { public frmSystemParams() { InitializeComponent(); } private void btnSwitch_Click(object sender, EventArgs e) { Controls.Clear(); if (btnSwitch.Text == "英") { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } if (btnSwitch.Text == "中") { Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-CN"); } InitializeComponent(); frmSystemParams_Load(null, null); } private void frmSystemParams_Load(object sender, EventArgs e) { if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") { cboDeviceType.Properties.Items.Clear(); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 0, Name = "BF-0016/BF-0824", }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 1, Name = "BF-0017", }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 2, Name = "BF-0825", }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 3, Name = "BF-Leak" }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 4, Name = "BF-Tighten" }); } else { cboDeviceType.Properties.Items.Clear(); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 0, Name = "电镀设备-纽堡", }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 1, Name = "脱氢炉设备-纽堡", }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 2, Name = "脱氢炉设备-耐美特", }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 3, Name = "测漏设备-阿普顿" }); cboDeviceType.Properties.Items.Add(new DeviceType() { ID = 4, Name = "拧紧设备-阿普顿" }); } edtBrokeURI.Text = SystemParams.Instance.ActiveMQ_URI; edtQueueName.Text = SystemParams.Instance.ActiveMQ_QueueName; edtUpgradeURL.Text = SystemParams.Instance.UpgradeURL; chkWriteLog.Checked = SystemParams.Instance.WriteLog; edtT133Code.Text = SystemParams.Instance.DeviceCode; edtDBFileName.Text = SystemParams.Instance.DataFileName; edtDeltaTimeSpan.Text = SystemParams.Instance.DeltaTimeSpan.ToString(); cboDeviceType.SelectedIndex = SystemParams.Instance.DeviceType; edtLastCheckPoint.Value = SystemParams.Instance.BeginDT; edtT216Code.Text = SystemParams.Instance.T216Code; edtExCode.Text = SystemParams.Instance.ExCode; edtFilter.Text = SystemParams.Instance.Filter; } private void edtBrokeURI_Validated(object sender, EventArgs e) { SystemParams.Instance.ActiveMQ_URI = edtBrokeURI.Text; } private void edtQueueName_Validated(object sender, EventArgs e) { SystemParams.Instance.ActiveMQ_QueueName = edtQueueName.Text; } private void edtUpgradeURL_Validated(object sender, EventArgs e) { SystemParams.Instance.UpgradeURL = edtUpgradeURL.Text; } private void chkWriteLog_CheckedChanged(object sender, EventArgs e) { WriteLog.Instance.IsWriteLog = chkWriteLog.Checked; SystemParams.Instance.WriteLog = chkWriteLog.Checked; } private void edtT133Code_Validated(object sender, EventArgs e) { SystemParams.Instance.DeviceCode = edtT133Code.Text; } private void edtDBFileName_Validated(object sender, EventArgs e) { SystemParams.Instance.DataFileName = edtDBFileName.Text; } private void edtDBFileName_Validating(object sender, CancelEventArgs e) { if (edtDBFileName.Text != "") { if (File.Exists(edtDBFileName.Text)) e.Cancel = false; else e.Cancel = true; } } private void btnSelectFile_Click(object sender, EventArgs e) { if (edtDBFileName.Text != "") openFileDialog.InitialDirectory = Path.GetFullPath(edtDBFileName.Text); if (openFileDialog.ShowDialog() == DialogResult.OK) { edtDBFileName.Text = openFileDialog.FileName; SystemParams.Instance.DataFileName = openFileDialog.FileName; } } private void edtDeltaTimeSpan_Validated(object sender, EventArgs e) { SystemParams.Instance.DeltaTimeSpan = int.Parse(edtDeltaTimeSpan.Text); } private void cboDeviceType_SelectedIndexChanged(object sender, EventArgs e) { SystemParams.Instance.DeviceType = ((DeviceType)cboDeviceType.SelectedItem).ID; } private void edtLastCheckPoint_ValueChanged(object sender, EventArgs e) { SystemParams.Instance.BeginDT = edtLastCheckPoint.Value; } private void edtExCode_Validated(object sender, EventArgs e) { SystemParams.Instance.ExCode = edtExCode.Text; } private void edtFilter_Validated(object sender, EventArgs e) { SystemParams.Instance.Filter = edtFilter.Text; } } public class DeviceType { public string Name { get; set; } public int ID { get; set; } public override string ToString() { return Name; } } }
using System; using System.Threading; using System.Threading.Tasks; namespace Yaringa.ViewModels { /// <summary> /// This class provides message settings for all the action code when executed in ViewModel's command. /// See <see cref="ViewModel"/> for how to use this class. /// This class is renamed from class MessageSettings. /// Search MessageSettings.cs if you want to read the whole class history. /// </summary> public class InvokingSettings { public string BusyMessage { get; set; } = "Loading..."; public ConfirmationMessageSettings Confirmation { get; set; } public ErrorMessageSettings Error { get; set; } public InfoMessageSettings Info { get; set; } //Providing post-processing (i.e. page navigation) after an action is invoked successfully. public Func<Task> Callback { get; set; } } /// <summary> /// This class provides the settings for a confirmation message box before an action is going to be executed. /// </summary> public class ConfirmationMessageSettings { public string Message { get; set; } public string Title { get; set; } public string OkButtonLabel { get; set; } = "OK"; public string CancelButtonLabel { get; set; } = "Cancel"; public CancellationToken? CancellationToken { get; set; } = null; } /// <summary> /// This class provides the settings for an error message box after an action fails. /// </summary> public class ErrorMessageSettings { public string Message { get; set; } public string Title { get; set; } = "Error"; public string ButtonLabel { get; set; } = "OK"; public CancellationToken? CancellationToken { get; set; } = null; } /// <summary> /// This class provides the settings for an information message box after an action succeeds. /// </summary> public class InfoMessageSettings { public string Message { get; set; } public string Title { get; set; } = ""; public string ButtonLabel { get; set; } = "OK"; public CancellationToken? CancellationToken { get; set; } = null; } }
//imports using System; using System.Collections.Generic; namespace LuckyUnicorn01 { class Program { //global variables //private static List<string> animals = new List<string> {"horse","donkey","zebra","unicorn" }; private static float money; //methods private static int MoneyCheck(int low, int high) { bool valid = false; while (!valid) { string error = $"Whoops! Please choose a whole number between {low} and {high}"; try { Console.WriteLine($"\nPlease enter the amount of money you want to spend between {low}$ and {high}$:" + "\nWe do not accept decimal values."); int response = Convert.ToInt32(Console.ReadLine()); if (low <= response && response <= high) { return response; } else { Console.WriteLine(error); } } catch (Exception) { Console.WriteLine(error); } } return -1; } private static string CheckYesNo() { while (true) { Console.WriteLine("Have you played before? y/n"); char userinput = Convert.ToChar(Console.ReadLine().ToLower()[0]); if (userinput == 'y') { return "y"; } else if (userinput == 'n') { return "n"; } else { Console.WriteLine("----ERROR PLEASE ENTER Y/N----"); } } //return ""; } static void GetRandomAnimal() { Random rd = new Random(); int randNum = rd.Next(0, 100); if (randNum >= 90) { money += 4; Console.WriteLine("unicorn"); } else if (randNum >= 60) { money -= (float)0.5; Console.WriteLine("zebra"); } else if (randNum >= 30) { money -= (float)0.5; Console.WriteLine("horse"); } else { money -= 1; Console.WriteLine("donkey"); } } private static void StartGame() { int cost = MoneyCheck(1, 10); money += cost; Console.WriteLine("You will be spending " + cost + "$, so you shall recieve " + cost + " random animals\n"); for (int i = 0; i < cost; i++) { GetRandomAnimal(); } Console.WriteLine("\nYour balance is "+money+"$"); } //main process static void Main(string[] args) { Console.WriteLine("Welcome to Lucky Unicorn!!\n\n"); if (CheckYesNo().Equals("y")) { StartGame(); } else { Console.WriteLine("\nIn this game, you will enter the amount of money you want to play----\n" + "Based on the amount you have entered, there will be a random animal generated----\n" + "A unicorn, donkey or horse can be generated--to be continued"); StartGame(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using KPIDemo.Service; using KPIDemo.DataAccess; using KPIDemo.DTO; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace KPIDemo.Controllers { public class StudentController : Controller { private IStudentService studentService; public StudentController(IStudentService studentService) { this.studentService = studentService; } public IActionResult Index() { var students = studentService.List(); return View(students); } public IActionResult Edit(Guid id) { if (id != null && id != Guid.Empty) { var student = studentService.Get(id); return View(student); } else { return View(); } } [HttpPost] public IActionResult Edit(StudentDto model) { if (ModelState.IsValid) { if (model.Id != Guid.Empty && model.Id != null) { this.studentService.Update(model); } else { this.studentService.Insert(model); } } return View(model); } } }
using Microsoft.AspNetCore.Builder; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Btf.Web.Api.Authorization { public static class AuthorizationMiddlewareEntensions { public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<AuthorizationMiddleware>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace St.Eg.Day3.M2.Ex2.AsyncAwait.After { class Program { static void Main(string[] args) { var program = new Program(); //program.exercise1(); program.exercise2(); Console.ReadLine(); } async public void exercise1() { Console.WriteLine("in exercise1"); await thisMethodWillBeRunAsync(); Console.WriteLine("after calling async method"); } async public Task thisMethodWillBeRunAsync() { Console.WriteLine("async method running"); Task.Delay(5000).Wait(); Console.WriteLine("async method ending"); } public void exercise2() { Console.WriteLine("in exercise2"); var task = Task.Factory.StartNew( () => { Console.WriteLine("in task"); Task.Factory.StartNew(() => thisMethodWillBeRunAsync()).Wait(); Console.WriteLine("after calling async method"); }); task.ContinueWith(a => Console.WriteLine("After running the task")); task.Wait(); Console.WriteLine("Leaving exercise2"); } } }
using Common; using IBLLService; using MODEL; using MODEL.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BLLService { public partial class MemberManager : IMemberManager { public EasyUIGrid GetAllSuppliers(MODEL.ViewModel.DataTableRequest request) { int total = 0; return new EasyUIGrid() { rows = GetAllSuppliers(request, ref total), total = total }; } public IEnumerable<Member> GetAllSuppliers(DataTableRequest request, ref int Count) { var predicate = PredicateBuilder.True<Member>(); DateTime time = TypeParser.ToDateTime("1975-1-1"); predicate = predicate.And(p => p.isdelete == 0); var data = base.LoadPagedList(request.PageNumber, request.PageSize, ref Count, predicate, request.Model, p => p.isdelete == 0, request.SortOrder, request.SortName); //var list = ViewModelProduct.ToListViewModel(data); return data; } public int ApprovedMoreSupplier(List<int> ids) { return 1; } } }
using System; using Uintra.Infrastructure.TypeProviders; namespace Uintra.Features.Notification { public class NotifierTypeProvider : EnumTypeProviderBase, INotifierTypeProvider { public NotifierTypeProvider(params Type[] enums) : base(enums) { } } }
using IModels.Commons; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Models.Commons { public class Person : IPerson { public string Telephone { get; set; } public string CPF { get; set; } public string Name { get; set; } public string Surname { get; set; } public int Old { get; set; } public int Id { get; set; } } }
using System; using System.Threading.Tasks; using Grpc.Net.Client; using Grpc.Server; namespace Grpc.Client { class Program { static async Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); var channel = GrpcChannel.ForAddress("http://localhost:5007"); var client = new Greeter.GreeterClient(channel); var response = await client.SayHelloAsync(new HelloRequest { Name = "from net core console app" }); Console.WriteLine(response.Message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DistCWebSite.Core.Entities; using DistCWebSite.Core.Interfaces; namespace DistCWebSite.Infrastructure { public class SFEHospitalRespository : ISFEHospitalRespository { public int Add(M_SFEHospital hos) { var ctx = new DistCSiteContext(); ctx.M_SFEHospital.Add(hos); return ctx.SaveChanges(); } public int Delete(M_SFEHospital hos) { var ctx = new DistCSiteContext(); ctx.Entry(hos).State = System.Data.Entity.EntityState.Deleted; return ctx.SaveChanges(); } public M_SFEHospital GetbySFEDistCode(string hosCode) { var ctx = new DistCSiteContext(); return ctx.M_SFEHospital.Where(x => x.Active == true && x.SFEHosCode == hosCode).FirstOrDefault(); } public M_SFEHospital GetbySFEDistName(string hosName) { var ctx = new DistCSiteContext(); return ctx.M_SFEHospital.Where(x => x.Active == true && x.SFEHosName == hosName).FirstOrDefault(); } public List<M_SFEHospital> GetList() { var ctx = new DistCSiteContext(); return ctx.M_SFEHospital.Where(x => x.Active == true).ToList(); } public int Update(M_SFEHospital hos) { var ctx = new DistCSiteContext(); ctx.Entry(hos).State = System.Data.Entity.EntityState.Modified; return ctx.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.ContentItemVersions; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts; using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Helpers; using DFC.ServiceTaxonomy.GraphSync.Interfaces; using DFC.ServiceTaxonomy.GraphSync.Services; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OrchardCore.ContentManagement; namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Contexts { //todo: should IDeleteGraphSyncer implement IGraphDeleteItemSyncContext?? public class GraphDeleteContext : GraphSyncContext, IGraphDeleteItemSyncContext { public new IGraphDeleteContext? ParentContext { get; } public new IEnumerable<IGraphDeleteContext> ChildContexts => _childContexts.Cast<IGraphDeleteContext>(); public IDeleteGraphSyncer DeleteGraphSyncer { get; } public IDeleteNodeCommand DeleteNodeCommand { get; } public SyncOperation SyncOperation { get; } public IEnumerable<KeyValuePair<string, object>>? DeleteIncomingRelationshipsProperties { get; } public GraphDeleteContext(ContentItem contentItem, IDeleteNodeCommand deleteNodeCommand, IDeleteGraphSyncer deleteGraphSyncer, SyncOperation syncOperation, ISyncNameProvider syncNameProvider, IContentManager contentManager, IContentItemVersion contentItemVersion, IEnumerable<KeyValuePair<string, object>>? deleteIncomingRelationshipsProperties, IGraphDeleteContext? parentGraphDeleteContext, IServiceProvider serviceProvider) : base( contentItem, syncNameProvider, contentManager, contentItemVersion, parentGraphDeleteContext, serviceProvider.GetRequiredService<ILogger<GraphDeleteContext>>()) { DeleteGraphSyncer = deleteGraphSyncer; DeleteNodeCommand = deleteNodeCommand; SyncOperation = syncOperation; DeleteIncomingRelationshipsProperties = deleteIncomingRelationshipsProperties; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using GSVM.Components.Mem; using GSVM.Components.Processors.CPU_1; using GSVM.Constructs; using GSVM.Constructs.DataTypes; using GSVM.Components.Clocks; using GSVM.Components.Controllers; namespace GSVM.Components.Processors { public partial class CPU1 : CPU { Stack<IDataType> stack; public IDataType[] Stack { get { return stack.ToArray(); } } Dictionary<Opcodes, Delegate> opcodes; Registers<Register> registers; Opcode opcode; Delegate operation; Integral<ushort> operandA, operandB; public string Name { get { return "GSVM CPU1"; } } public double Speed { get; private set; } bool speedTesting = false; int cycleCount = 0; DateTime startTime; bool debug; public override bool Debug { get { return debug; } set { debug = value; if (debug) { Northbridge.Clock.Stop(); } else if (!Northbridge.Clock.Enabled) { Northbridge.Clock.Start(); } } } bool cycleException = false; public CPU1() { stack = new Stack<IDataType>(); opcodes = new Dictionary<Opcodes, Delegate>(); registers = new Registers<Register>(); registers.Append<uint16_t>(Register.PC); // Program counter registers.Append<uint16_t>(Register.MAR); // Memory address register registers.Append<uint16_t>(Register.MLR); // Memory length register registers.Append<uint64_t>(Register.MDR); // Memory data register (64-bits) registers.Subdivide(Register.MDR, Register.MDR32); // 32-bit MDR register registers.Subdivide(Register.MDR32, Register.MDR16); // 16-bit MDR register registers.Subdivide(Register.MDR16, Register.MDR8); // 8-bit MDR register registers.Append<Opcode>(Register.CIR); // Current instruction register registers.Append<uint16_t>(Register.IDT); // Interrupt Descriptor Table address registers.Append<uint64_t>(Register.FLAGS); // Flags register registers.Append<uint32_t>(Register.SVM); // Shared Video Memory address registers.Append<uint32_t>(Register.EAX); registers.Subdivide(Register.EAX, Register.AX); registers.Subdivide(Register.AX, Register.AL, Register.AH); registers.Append<uint32_t>(Register.EBX); registers.Subdivide(Register.EBX, Register.BX); registers.Subdivide(Register.BX, Register.BL, Register.BH); registers.Append<uint32_t>(Register.ECX); registers.Subdivide(Register.ECX, Register.CX); registers.Subdivide(Register.CX, Register.CL, Register.CH); registers.Append<uint32_t>(Register.EDX); registers.Subdivide(Register.EDX, Register.DX); registers.Subdivide(Register.DX, Register.DL, Register.DH); registers.Append<uint16_t>(Register.ABP); registers.Append<uint16_t>(Register.AEI); registers.Append<uint16_t>(Register.AEL); registers.Append<uint16_t>(Register.AEP); registers.BuildMemory(); SetupOpCodes(); registers.Write<uint64_t>(Register.FLAGS, new uint64_t((ulong)CPUFlags.Empty)); } void SetupOpCodes() { opcodes.Add(Opcodes.nop, new Action(NoOp)); opcodes.Add(Opcodes.movr, new Action<Register_t, Register_t>(MoveR)); opcodes.Add(Opcodes.movl, new Action<Register_t, uint16_t>(MoveL)); opcodes.Add(Opcodes.readr, new Action<Register_t, Register_t>(Read)); opcodes.Add(Opcodes.readl, new Action<Register_t, uint16_t>(Read)); opcodes.Add(Opcodes.writerr, new Action<Register_t, Register_t>(Write)); opcodes.Add(Opcodes.writelr, new Action<uint16_t, Register_t>(Write)); opcodes.Add(Opcodes.writell, new Action<uint16_t, uint16_t>(Write)); opcodes.Add(Opcodes.writerl, new Action<Register_t, uint16_t>(Write)); opcodes.Add(Opcodes.pushr, new Action<Register_t>(PushRegister)); opcodes.Add(Opcodes.pushl, new Action<uint16_t>(PushLiteral)); opcodes.Add(Opcodes.pusha, new Action(PushAll)); opcodes.Add(Opcodes.pop, new Action<Register_t>(Pop)); opcodes.Add(Opcodes.popa, new Action(PopAll)); opcodes.Add(Opcodes.addr, new Action<Register_t, Register_t>(Add)); opcodes.Add(Opcodes.addl, new Action<Register_t, uint16_t>(Add)); opcodes.Add(Opcodes.subr, new Action<Register_t, Register_t>(Subtract)); opcodes.Add(Opcodes.subl, new Action<Register_t, uint16_t>(Subtract)); opcodes.Add(Opcodes.multr, new Action<Register_t, Register_t>(Multiply)); opcodes.Add(Opcodes.multl, new Action<Register_t, uint16_t>(Multiply)); opcodes.Add(Opcodes.divr, new Action<Register_t, Register_t>(Divide)); opcodes.Add(Opcodes.divl, new Action<Register_t, uint16_t>(Divide)); opcodes.Add(Opcodes.modr, new Action<Register_t, Register_t>(Mod)); opcodes.Add(Opcodes.modl, new Action<Register_t, uint16_t>(Mod)); opcodes.Add(Opcodes.andr, new Action<Register_t, Register_t>(And)); opcodes.Add(Opcodes.andl, new Action<Register_t, uint16_t>(And)); opcodes.Add(Opcodes.orr, new Action<Register_t, Register_t>(Or)); opcodes.Add(Opcodes.orl, new Action<Register_t, uint16_t>(Or)); opcodes.Add(Opcodes.xorr, new Action<Register_t, Register_t>(Xor)); opcodes.Add(Opcodes.xorl, new Action<Register_t, uint16_t>(Xor)); opcodes.Add(Opcodes.not, new Action<Register_t>(Not)); opcodes.Add(Opcodes.neg, new Action<Register_t>(Neg)); opcodes.Add(Opcodes.cmpr, new Action<Register_t, Register_t>(Compare)); opcodes.Add(Opcodes.cmpl, new Action<Register_t, uint16_t>(Compare)); opcodes.Add(Opcodes.lsr, new Action<Register_t, Register_t>(LeftShift)); opcodes.Add(Opcodes.lsl, new Action<Register_t, uint16_t>(LeftShift)); opcodes.Add(Opcodes.rsr, new Action<Register_t, Register_t>(RightShift)); opcodes.Add(Opcodes.rsl, new Action<Register_t, uint16_t>(RightShift)); opcodes.Add(Opcodes.hlt, new Action(Halt)); opcodes.Add(Opcodes._out, new Action(_out)); opcodes.Add(Opcodes._in, new Action(_in)); opcodes.Add(Opcodes.intr, new Action<Register_t>(intr)); opcodes.Add(Opcodes.intl, new Action<uint16_t>(intl)); opcodes.Add(Opcodes.jmpr, new Action<Register_t>(JumpR)); opcodes.Add(Opcodes.jmpl, new Action<uint16_t>(JumpL)); opcodes.Add(Opcodes.je, new Action<uint16_t>(JumpEqual)); opcodes.Add(Opcodes.jne, new Action<uint16_t>(JumpNotEqual)); opcodes.Add(Opcodes.jg, new Action<uint16_t>(JumpGreater)); opcodes.Add(Opcodes.jge, new Action<uint16_t>(JumpGreaterEqual)); opcodes.Add(Opcodes.jl, new Action<uint16_t>(JumpLess)); opcodes.Add(Opcodes.jle, new Action<uint16_t>(JumpLessEqual)); opcodes.Add(Opcodes.callr, new Action<Register_t>(CallR)); opcodes.Add(Opcodes.calll, new Action<uint16_t>(CallL)); opcodes.Add(Opcodes.ret, new Action(Ret)); opcodes.Add(Opcodes.derefr, new Action<Register_t, Register_t>(Deref)); opcodes.Add(Opcodes.derefl, new Action<Register_t, uint16_t>(Deref)); opcodes.Add(Opcodes.brk, new Action(Brk)); opcodes.Add(Opcodes.cpuid, new Action(CPUID)); opcodes.Add(Opcodes.sall, new Action<uint16_t, uint16_t>(sall)); opcodes.Add(Opcodes.salr, new Action<uint16_t, Register_t>(salr)); opcodes.Add(Opcodes.sarl, new Action<Register_t, uint16_t>(sarl)); opcodes.Add(Opcodes.sarr, new Action<Register_t, Register_t>(sarr)); opcodes.Add(Opcodes.inca, new Action(inca)); opcodes.Add(Opcodes.deca, new Action(deca)); opcodes.Add(Opcodes.sail, new Action<uint16_t>(sail)); opcodes.Add(Opcodes.sair, new Action<Register_t>(sair)); } public override byte[] GetRegisters() { return registers.Dump(); } protected override void Fetch() { cycleException = false; if (speedTesting) cycleCount++; if (!HasFlag(CPUFlags.WaitForInterrupt)) { uint svm = registers.Read<uint32_t>(Register.SVM).Value; if (Northbridge.videoMemoryAddress != svm) Northbridge.videoMemoryAddress = svm; MoveR(Register.MAR, Register.PC); MoveL(Register.MLR, 8); ReadMemory(); MoveR(Register.CIR, Register.MDR); Add(Register.PC, Register.MLR); Parent.RaiseUpdateDebugger(); } } protected override void Decode() { if (!cycleException) { opcode = registers.Read<Opcode>(Register.CIR); try { operation = opcodes[opcode.Code]; } catch (KeyNotFoundException) { cycleException = true; // TODO: Interrupt with an invalid opcode } if (opcode.Flags.HasFlag(OpcodeFlags.Register1)) operandA = new Register_t(opcode.OperandA); if (opcode.Flags.HasFlag(OpcodeFlags.Register2)) operandB = new Register_t(opcode.OperandB); if (opcode.Flags.HasFlag(OpcodeFlags.Literal1)) operandA = opcode.OperandA; if (opcode.Flags.HasFlag(OpcodeFlags.Literal2)) operandB = opcode.OperandB; } } protected override void Execute() { if (!cycleException) { int arguments = operation.Method.GetParameters().Length; // TODO: Wrap in try-catch try { switch (arguments) { case 0: operation.DynamicInvoke(); break; case 1: operation.DynamicInvoke(operandA); break; case 2: operation.DynamicInvoke(operandA, operandB); break; } } catch (Exception ex) { Northbridge.WriteDisplay(0, Encoding.ASCII.GetBytes(ex.Message)); } Parent.RaiseUpdateDebugger(); if ((speedTesting) && (cycleCount == 5)) { TimeSpan time = DateTime.Now - startTime; Speed = 5.0f / time.TotalSeconds; speedTesting = false; } } } public override void Start() { Enabled = true; Northbridge.Clock.Start(); speedTesting = true; startTime = DateTime.Now; } public override void Stop() { Enabled = false; } void NoOp() { // DO NOTHING } void Halt() { SetFlag(CPUFlags.WaitForInterrupt); } public override void Interrupt(int channel) { Interrupt((ushort)channel); } void Interrupt(ushort interrupt) { // Get the interrupt address MoveR(Register.MAR, Register.IDT); Add(Register.MAR, new uint16_t((ushort)(interrupt * 2))); MoveL(Register.MLR, 4); ReadMemory(); //// call that address as a function ushort address = registers.Read<uint16_t>(Register.MDR16); CallR(Register.MDR16); } void CPUID() { uint32_t eax = registers.Read<uint32_t>(Register.EAX); uint32_t ebx, ecx, edx; byte[] str = new byte[4]; switch (eax.Value) { case 0: List<byte> name = new List<byte>(Encoding.ASCII.GetBytes(Name)); while (name.Count < 12) { name.Add(32); } while (name.Count > 12) { name.RemoveAt(name.Count - 1); } byte[] bName = name.ToArray(); Array.Copy(bName, str, 4); ebx = new uint32_t(str); Array.Copy(bName, 4, str, 0, 4); ecx = new uint32_t(str); Array.Copy(bName, 8, str, 0, 4); edx = new uint32_t(str); registers.Write(Register.EBX, ebx); registers.Write(Register.ECX, ecx); registers.Write(Register.EDX, edx); break; case 1: List<byte> speed = new List<byte>(Encoding.ASCII.GetBytes(string.Format("{0:F2} Hz\0", Speed))); while (speed.Count < 12) { speed.Add(32); } while (speed.Count > 12) { speed.RemoveAt(speed.Count - 1); } byte[] bSpeed = speed.ToArray(); Array.Copy(bSpeed, str, 4); ebx = new uint32_t(str); Array.Copy(bSpeed, 4, str, 0, 4); ecx = new uint32_t(str); Array.Copy(bSpeed, 8, str, 0, 4); edx = new uint32_t(str); registers.Write(Register.EBX, ebx); registers.Write(Register.ECX, ecx); registers.Write(Register.EDX, edx); break; } } void SetFlag(CPUFlags flag) { CPUFlags state = (CPUFlags)registers.Read<uint64_t>(Register.FLAGS).Value; state = state | flag; registers.Write<uint64_t>(Register.FLAGS, (ulong)state); } void UnsetFlag(CPUFlags flag) { CPUFlags state = (CPUFlags)registers.Read<uint64_t>(Register.FLAGS).Value; state = state & ~flag; registers.Write<uint64_t>(Register.FLAGS, (ulong)state); } bool HasFlag(CPUFlags flag) { CPUFlags state = (CPUFlags)registers.Read<uint64_t>(Register.FLAGS).Value; return (state & flag) == flag; } protected void ReadMemory() { if (Parent == null) throw new Exception("Not connected to VM. Parent is null."); if (Northbridge == null) throw new Exception("Not connected to northbridge."); uint16_t address = registers.Read<uint16_t>(Register.MAR); uint16_t length = registers.Read<uint16_t>(Register.MLR); try { byte[] value = Northbridge.ReadMemory(address.Value, length.Value); registers.Write(Register.MDR, value); } catch (IndexOutOfRangeException) { SetFlag(CPUFlags.MemoryError); } } protected void WriteMemory() { if (Parent == null) throw new Exception("Not connected to VM. Parent is null."); if (Northbridge == null) throw new Exception("Not connected to northbridge."); uint16_t address = registers.Read<uint16_t>(Register.MAR); uint16_t length = registers.Read<uint16_t>(Register.MLR); byte[] value = new byte[0]; switch (length.Value) { case 8: value = registers.Read(Register.MDR); break; case 4: value = registers.Read(Register.MDR32); break; case 2: value = registers.Read(Register.MDR16); break; case 1: value = registers.Read(Register.MDR8); break; } try { Northbridge.WriteMemory(address, value, (uint)value.Length); } catch (MemoryAccessException) { // Raise interrupt SetFlag(CPUFlags.MemoryError); } } } }
using LeaveApplication.Dal.Models; using System; using System.Collections.Generic; using System.Text; namespace LeaveApplication.Dal.Repositories { public interface IUser { void SetDate(DateTime _DateTime); void Add(User _User); // List<User> GetUsers { get; } //User GetUser(int Id); //void Remove(int Id); } }
using System; using System.IO; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Uberware.Study { public class frmMain : System.Windows.Forms.Form { #region API Imports [DllImport("winmm.dll", EntryPoint="PlaySound", SetLastError=true, CallingConvention=CallingConvention.Winapi)] static extern bool sndPlaySound( string pszSound, IntPtr hMod, SoundFlags sf ); [Flags] public enum SoundFlags : int { SND_SYNC = 0x0000, /* play synchronously (default) */ SND_ASYNC = 0x0001, /* play asynchronously */ SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */ SND_MEMORY = 0x0004, /* pszSound points to a memory file */ SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */ SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */ SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */ SND_ALIAS = 0x00010000, /* name is a registry alias */ SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */ SND_FileName = 0x00020000, /* name is file name */ SND_RESOURCE = 0x00040004 /* name is resource name or atom */ } #endregion #region Class Variables private static MatchingSettings m_Settings = null; // !!!!! private MatchingSheet m_Sheet = null; private bool m_MultiTerm = false; private string [] m_MultiTermList = null; private string [] m_MultiTermListAquired = null; private ArrayList m_MultiTermListRemains = new ArrayList(); private int m_MultiTermNum = 0; private Font m_BoldFont = null; private Font m_RegularFont = null; private bool m_AutoBeginStudy = false; private bool m_Studying = false; private bool m_Improving = false; private int [] m_TermList = null; private int m_TermNum = 0; private int m_TermIndex = 0; private int m_Correct = 0; private ArrayList m_ImproveList = null; #region Controls private System.Windows.Forms.TextBox txtTitle; private System.Windows.Forms.GroupBox grpLine01; private System.Windows.Forms.GroupBox grpLine02; private System.Windows.Forms.Label lblDefinition; private System.Windows.Forms.TextBox txtRemaining; private System.Windows.Forms.Label lblRemaining; private System.Windows.Forms.GroupBox grpLine03; private System.Windows.Forms.TextBox txtTotal; private System.Windows.Forms.Button btnMenu; private System.Windows.Forms.GroupBox grpLine04; private System.Windows.Forms.Panel panTerms; private System.Windows.Forms.Panel panImprove; private System.Windows.Forms.Label lblTotal; private System.Windows.Forms.Label lblTermList; private System.Windows.Forms.Splitter splTerms; private System.Windows.Forms.Panel panTermList; private System.Windows.Forms.Label lblImprove; private System.Windows.Forms.Label lblCorrect; private System.Windows.Forms.Label lblWrong; private System.Windows.Forms.TextBox txtCorrect; private System.Windows.Forms.TextBox txtWrong; private System.Windows.Forms.ListBox lstTermList; private System.Windows.Forms.ListBox lstImprove; private System.Windows.Forms.ContextMenu menuMain; private System.Windows.Forms.MenuItem menuMainOpen; private System.Windows.Forms.MenuItem menuMainClose; private System.Windows.Forms.MenuItem menuMainLine01; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.Button btnExit; private System.Windows.Forms.Button btnStudy; private System.Windows.Forms.Button btnSelect; private System.Windows.Forms.Timer tmrResetColors; private System.Windows.Forms.MenuItem menuMainEdit; private System.Windows.Forms.MenuItem menuMainNew; private System.Windows.Forms.RichTextBox txtDefinition; private System.Windows.Forms.Panel panDefinition; private System.Windows.Forms.MenuItem menuMainLine02; private System.Windows.Forms.Button btnEditor; private System.Windows.Forms.MenuItem menuMainExit; private System.Windows.Forms.MenuItem menuMainLine03; private System.Windows.Forms.MenuItem menuMainAbout; private System.Windows.Forms.MenuItem menuMainPreferences; private System.Windows.Forms.Label lblMessage; private System.Windows.Forms.TextBox txtMultiTerms; private System.Windows.Forms.TextBox txtMultiTermCount; private System.Windows.Forms.Label lblMultiTermCount; private System.Windows.Forms.TextBox txtMultiTermPos; private System.Windows.Forms.Panel panMultiTerm; private System.Windows.Forms.Label lblMultiTerms; private System.Windows.Forms.Timer tmrResetMessage; private System.Windows.Forms.MenuItem menuMainSoundEffects; private System.Windows.Forms.Timer tmrResetMultiTerm; private System.ComponentModel.IContainer components; #endregion #endregion #region Class Construction public frmMain() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMain)); this.txtTitle = new System.Windows.Forms.TextBox(); this.grpLine01 = new System.Windows.Forms.GroupBox(); this.lblDefinition = new System.Windows.Forms.Label(); this.grpLine02 = new System.Windows.Forms.GroupBox(); this.txtRemaining = new System.Windows.Forms.TextBox(); this.lblRemaining = new System.Windows.Forms.Label(); this.grpLine03 = new System.Windows.Forms.GroupBox(); this.lblTotal = new System.Windows.Forms.Label(); this.txtTotal = new System.Windows.Forms.TextBox(); this.btnStudy = new System.Windows.Forms.Button(); this.btnMenu = new System.Windows.Forms.Button(); this.grpLine04 = new System.Windows.Forms.GroupBox(); this.lblTermList = new System.Windows.Forms.Label(); this.panTerms = new System.Windows.Forms.Panel(); this.panTermList = new System.Windows.Forms.Panel(); this.btnSelect = new System.Windows.Forms.Button(); this.lstTermList = new System.Windows.Forms.ListBox(); this.splTerms = new System.Windows.Forms.Splitter(); this.panImprove = new System.Windows.Forms.Panel(); this.lblImprove = new System.Windows.Forms.Label(); this.lstImprove = new System.Windows.Forms.ListBox(); this.lblCorrect = new System.Windows.Forms.Label(); this.lblWrong = new System.Windows.Forms.Label(); this.txtCorrect = new System.Windows.Forms.TextBox(); this.txtWrong = new System.Windows.Forms.TextBox(); this.menuMain = new System.Windows.Forms.ContextMenu(); this.menuMainNew = new System.Windows.Forms.MenuItem(); this.menuMainOpen = new System.Windows.Forms.MenuItem(); this.menuMainClose = new System.Windows.Forms.MenuItem(); this.menuMainLine01 = new System.Windows.Forms.MenuItem(); this.menuMainEdit = new System.Windows.Forms.MenuItem(); this.menuMainLine02 = new System.Windows.Forms.MenuItem(); this.menuMainSoundEffects = new System.Windows.Forms.MenuItem(); this.menuMainPreferences = new System.Windows.Forms.MenuItem(); this.menuMainAbout = new System.Windows.Forms.MenuItem(); this.menuMainLine03 = new System.Windows.Forms.MenuItem(); this.menuMainExit = new System.Windows.Forms.MenuItem(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.btnExit = new System.Windows.Forms.Button(); this.tmrResetColors = new System.Windows.Forms.Timer(this.components); this.txtDefinition = new System.Windows.Forms.RichTextBox(); this.panDefinition = new System.Windows.Forms.Panel(); this.lblMessage = new System.Windows.Forms.Label(); this.btnEditor = new System.Windows.Forms.Button(); this.txtMultiTerms = new System.Windows.Forms.TextBox(); this.txtMultiTermCount = new System.Windows.Forms.TextBox(); this.lblMultiTermCount = new System.Windows.Forms.Label(); this.txtMultiTermPos = new System.Windows.Forms.TextBox(); this.lblMultiTerms = new System.Windows.Forms.Label(); this.panMultiTerm = new System.Windows.Forms.Panel(); this.tmrResetMessage = new System.Windows.Forms.Timer(this.components); this.tmrResetMultiTerm = new System.Windows.Forms.Timer(this.components); this.panTerms.SuspendLayout(); this.panTermList.SuspendLayout(); this.panImprove.SuspendLayout(); this.panDefinition.SuspendLayout(); this.panMultiTerm.SuspendLayout(); this.SuspendLayout(); // // txtTitle // this.txtTitle.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.txtTitle.BackColor = System.Drawing.SystemColors.Control; this.txtTitle.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.txtTitle.ForeColor = System.Drawing.SystemColors.GrayText; this.txtTitle.Location = new System.Drawing.Point(8, 8); this.txtTitle.Name = "txtTitle"; this.txtTitle.ReadOnly = true; this.txtTitle.Size = new System.Drawing.Size(356, 26); this.txtTitle.TabIndex = 0; this.txtTitle.Text = "( nothing loaded )"; this.txtTitle.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // grpLine01 // this.grpLine01.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.grpLine01.Location = new System.Drawing.Point(0, 36); this.grpLine01.Name = "grpLine01"; this.grpLine01.Size = new System.Drawing.Size(376, 3); this.grpLine01.TabIndex = 1; this.grpLine01.TabStop = false; // // lblDefinition // this.lblDefinition.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblDefinition.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblDefinition.Location = new System.Drawing.Point(8, 48); this.lblDefinition.Name = "lblDefinition"; this.lblDefinition.Size = new System.Drawing.Size(356, 16); this.lblDefinition.TabIndex = 2; this.lblDefinition.Text = "Definition:"; // // grpLine02 // this.grpLine02.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.grpLine02.Location = new System.Drawing.Point(0, 168); this.grpLine02.Name = "grpLine02"; this.grpLine02.Size = new System.Drawing.Size(376, 3); this.grpLine02.TabIndex = 5; this.grpLine02.TabStop = false; // // txtRemaining // this.txtRemaining.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.txtRemaining.BackColor = System.Drawing.SystemColors.Control; this.txtRemaining.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtRemaining.Location = new System.Drawing.Point(332, 180); this.txtRemaining.Name = "txtRemaining"; this.txtRemaining.ReadOnly = true; this.txtRemaining.Size = new System.Drawing.Size(32, 20); this.txtRemaining.TabIndex = 11; this.txtRemaining.Text = ""; this.txtRemaining.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // lblRemaining // this.lblRemaining.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.lblRemaining.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblRemaining.Location = new System.Drawing.Point(204, 184); this.lblRemaining.Name = "lblRemaining"; this.lblRemaining.Size = new System.Drawing.Size(124, 16); this.lblRemaining.TabIndex = 10; this.lblRemaining.Text = "Remaining:"; // // grpLine03 // this.grpLine03.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.grpLine03.Location = new System.Drawing.Point(0, 232); this.grpLine03.Name = "grpLine03"; this.grpLine03.Size = new System.Drawing.Size(376, 3); this.grpLine03.TabIndex = 14; this.grpLine03.TabStop = false; // // lblTotal // this.lblTotal.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.lblTotal.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblTotal.Location = new System.Drawing.Point(204, 208); this.lblTotal.Name = "lblTotal"; this.lblTotal.Size = new System.Drawing.Size(124, 16); this.lblTotal.TabIndex = 12; this.lblTotal.Text = "Total:"; // // txtTotal // this.txtTotal.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.txtTotal.BackColor = System.Drawing.SystemColors.Control; this.txtTotal.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtTotal.Location = new System.Drawing.Point(332, 204); this.txtTotal.Name = "txtTotal"; this.txtTotal.ReadOnly = true; this.txtTotal.Size = new System.Drawing.Size(32, 20); this.txtTotal.TabIndex = 13; this.txtTotal.Text = ""; this.txtTotal.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // btnStudy // this.btnStudy.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.btnStudy.Location = new System.Drawing.Point(104, 456); this.btnStudy.Name = "btnStudy"; this.btnStudy.Size = new System.Drawing.Size(88, 36); this.btnStudy.TabIndex = 18; this.btnStudy.Text = "&Begin"; this.btnStudy.Click += new System.EventHandler(this.btnStudy_Click); // // btnMenu // this.btnMenu.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left); this.btnMenu.Location = new System.Drawing.Point(8, 456); this.btnMenu.Name = "btnMenu"; this.btnMenu.Size = new System.Drawing.Size(88, 36); this.btnMenu.TabIndex = 17; this.btnMenu.Text = "&Menu"; this.btnMenu.Click += new System.EventHandler(this.btnMenu_Click); this.btnMenu.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnMenu_MouseDown); // // grpLine04 // this.grpLine04.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.grpLine04.Location = new System.Drawing.Point(0, 444); this.grpLine04.Name = "grpLine04"; this.grpLine04.Size = new System.Drawing.Size(376, 3); this.grpLine04.TabIndex = 16; this.grpLine04.TabStop = false; // // lblTermList // this.lblTermList.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblTermList.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblTermList.Name = "lblTermList"; this.lblTermList.Size = new System.Drawing.Size(188, 16); this.lblTermList.TabIndex = 0; this.lblTermList.Text = "Term Selection:"; // // panTerms // this.panTerms.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.panTerms.Controls.AddRange(new System.Windows.Forms.Control[] { this.panTermList, this.splTerms, this.panImprove}); this.panTerms.Location = new System.Drawing.Point(8, 244); this.panTerms.Name = "panTerms"; this.panTerms.Size = new System.Drawing.Size(356, 192); this.panTerms.TabIndex = 15; // // panTermList // this.panTermList.Controls.AddRange(new System.Windows.Forms.Control[] { this.btnSelect, this.lblTermList, this.lstTermList}); this.panTermList.Dock = System.Windows.Forms.DockStyle.Fill; this.panTermList.Name = "panTermList"; this.panTermList.Size = new System.Drawing.Size(188, 192); this.panTermList.TabIndex = 0; // // btnSelect // this.btnSelect.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.btnSelect.Enabled = false; this.btnSelect.Location = new System.Drawing.Point(0, 164); this.btnSelect.Name = "btnSelect"; this.btnSelect.Size = new System.Drawing.Size(188, 28); this.btnSelect.TabIndex = 2; this.btnSelect.Text = "&Select"; this.btnSelect.Click += new System.EventHandler(this.btnSelect_Click); // // lstTermList // this.lstTermList.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lstTermList.BackColor = System.Drawing.SystemColors.Control; this.lstTermList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstTermList.IntegralHeight = false; this.lstTermList.Location = new System.Drawing.Point(0, 16); this.lstTermList.Name = "lstTermList"; this.lstTermList.Size = new System.Drawing.Size(188, 146); this.lstTermList.Sorted = true; this.lstTermList.TabIndex = 1; this.lstTermList.DoubleClick += new System.EventHandler(this.lstTermList_DoubleClick); this.lstTermList.Leave += new System.EventHandler(this.lstTermList_Leave); this.lstTermList.Enter += new System.EventHandler(this.lstTermList_Enter); // // splTerms // this.splTerms.Dock = System.Windows.Forms.DockStyle.Right; this.splTerms.Location = new System.Drawing.Point(188, 0); this.splTerms.Name = "splTerms"; this.splTerms.Size = new System.Drawing.Size(8, 192); this.splTerms.TabIndex = 1; this.splTerms.TabStop = false; // // panImprove // this.panImprove.Controls.AddRange(new System.Windows.Forms.Control[] { this.lblImprove, this.lstImprove}); this.panImprove.Dock = System.Windows.Forms.DockStyle.Right; this.panImprove.Location = new System.Drawing.Point(196, 0); this.panImprove.Name = "panImprove"; this.panImprove.Size = new System.Drawing.Size(160, 192); this.panImprove.TabIndex = 2; // // lblImprove // this.lblImprove.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lblImprove.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblImprove.Name = "lblImprove"; this.lblImprove.Size = new System.Drawing.Size(160, 16); this.lblImprove.TabIndex = 0; this.lblImprove.Text = "Terms to work on:"; // // lstImprove // this.lstImprove.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.lstImprove.BackColor = System.Drawing.SystemColors.Control; this.lstImprove.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstImprove.IntegralHeight = false; this.lstImprove.Location = new System.Drawing.Point(0, 16); this.lstImprove.Name = "lstImprove"; this.lstImprove.Size = new System.Drawing.Size(160, 176); this.lstImprove.TabIndex = 1; this.lstImprove.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lstImprove_MouseDown); this.lstImprove.MouseMove += new System.Windows.Forms.MouseEventHandler(this.lstImprove_MouseMove); this.lstImprove.SelectedIndexChanged += new System.EventHandler(this.lstImprove_SelectedIndexChanged); // // lblCorrect // this.lblCorrect.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblCorrect.Location = new System.Drawing.Point(8, 184); this.lblCorrect.Name = "lblCorrect"; this.lblCorrect.Size = new System.Drawing.Size(124, 16); this.lblCorrect.TabIndex = 6; this.lblCorrect.Text = "Correct:"; // // lblWrong // this.lblWrong.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblWrong.Location = new System.Drawing.Point(8, 208); this.lblWrong.Name = "lblWrong"; this.lblWrong.Size = new System.Drawing.Size(124, 16); this.lblWrong.TabIndex = 8; this.lblWrong.Text = "Wrong:"; // // txtCorrect // this.txtCorrect.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtCorrect.Location = new System.Drawing.Point(136, 180); this.txtCorrect.Name = "txtCorrect"; this.txtCorrect.ReadOnly = true; this.txtCorrect.Size = new System.Drawing.Size(32, 20); this.txtCorrect.TabIndex = 7; this.txtCorrect.Text = ""; this.txtCorrect.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // txtWrong // this.txtWrong.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtWrong.Location = new System.Drawing.Point(136, 204); this.txtWrong.Name = "txtWrong"; this.txtWrong.ReadOnly = true; this.txtWrong.Size = new System.Drawing.Size(32, 20); this.txtWrong.TabIndex = 9; this.txtWrong.Text = ""; this.txtWrong.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // menuMain // this.menuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuMainNew, this.menuMainOpen, this.menuMainClose, this.menuMainLine01, this.menuMainEdit, this.menuMainLine02, this.menuMainSoundEffects, this.menuMainPreferences, this.menuMainAbout, this.menuMainLine03, this.menuMainExit}); // // menuMainNew // this.menuMainNew.Index = 0; this.menuMainNew.Text = "&New..."; this.menuMainNew.Click += new System.EventHandler(this.menuMainNew_Click); // // menuMainOpen // this.menuMainOpen.Index = 1; this.menuMainOpen.Text = "&Open..."; this.menuMainOpen.Click += new System.EventHandler(this.menuMainOpen_Click); // // menuMainClose // this.menuMainClose.Enabled = false; this.menuMainClose.Index = 2; this.menuMainClose.Text = "&Close"; this.menuMainClose.Click += new System.EventHandler(this.menuMainClose_Click); // // menuMainLine01 // this.menuMainLine01.Index = 3; this.menuMainLine01.Text = "-"; // // menuMainEdit // this.menuMainEdit.Enabled = false; this.menuMainEdit.Index = 4; this.menuMainEdit.Text = "&Edit sheet..."; this.menuMainEdit.Click += new System.EventHandler(this.menuMainEdit_Click); // // menuMainLine02 // this.menuMainLine02.Index = 5; this.menuMainLine02.Text = "-"; // // menuMainSoundEffects // this.menuMainSoundEffects.Index = 6; this.menuMainSoundEffects.Text = "&Sound Effects"; this.menuMainSoundEffects.Click += new System.EventHandler(this.menuMainSoundEffects_Click); // // menuMainPreferences // this.menuMainPreferences.Index = 7; this.menuMainPreferences.Text = "&Preferences..."; this.menuMainPreferences.Visible = false; this.menuMainPreferences.Click += new System.EventHandler(this.menuMainPreferences_Click); // // menuMainAbout // this.menuMainAbout.Index = 8; this.menuMainAbout.Text = "Ab&out..."; this.menuMainAbout.Click += new System.EventHandler(this.menuMainAbout_Click); // // menuMainLine03 // this.menuMainLine03.Index = 9; this.menuMainLine03.Text = "-"; // // menuMainExit // this.menuMainExit.Index = 10; this.menuMainExit.Text = "E&xit"; this.menuMainExit.Click += new System.EventHandler(this.menuMainExit_Click); // // openFileDialog // this.openFileDialog.DefaultExt = "sheet"; this.openFileDialog.Filter = "Study Sheet Files (*.sheet)|*.sheet|All Files (*.*)|*.*"; this.openFileDialog.Title = "Open Study Sheet"; // // btnExit // this.btnExit.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnExit.Location = new System.Drawing.Point(292, 460); this.btnExit.Name = "btnExit"; this.btnExit.Size = new System.Drawing.Size(72, 32); this.btnExit.TabIndex = 20; this.btnExit.Text = "E&xit"; this.btnExit.Click += new System.EventHandler(this.btnExit_Click); // // tmrResetColors // this.tmrResetColors.Interval = 500; this.tmrResetColors.Tick += new System.EventHandler(this.tmrResetColors_Tick); // // txtDefinition // this.txtDefinition.BackColor = System.Drawing.SystemColors.Control; this.txtDefinition.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtDefinition.Dock = System.Windows.Forms.DockStyle.Fill; this.txtDefinition.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.txtDefinition.Name = "txtDefinition"; this.txtDefinition.ReadOnly = true; this.txtDefinition.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical; this.txtDefinition.Size = new System.Drawing.Size(354, 70); this.txtDefinition.TabIndex = 0; this.txtDefinition.Text = ""; this.txtDefinition.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.txtDefinition_ContentsResized); this.txtDefinition.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.txtDefinition_LinkClicked); // // panDefinition // this.panDefinition.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.panDefinition.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panDefinition.Controls.AddRange(new System.Windows.Forms.Control[] { this.lblMessage, this.txtDefinition}); this.panDefinition.Location = new System.Drawing.Point(8, 64); this.panDefinition.Name = "panDefinition"; this.panDefinition.Size = new System.Drawing.Size(356, 72); this.panDefinition.TabIndex = 3; // // lblMessage // this.lblMessage.Dock = System.Windows.Forms.DockStyle.Fill; this.lblMessage.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblMessage.Name = "lblMessage"; this.lblMessage.Size = new System.Drawing.Size(354, 70); this.lblMessage.TabIndex = 1; this.lblMessage.Text = ":: Message ::"; this.lblMessage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.lblMessage.Visible = false; // // btnEditor // this.btnEditor.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right); this.btnEditor.Location = new System.Drawing.Point(212, 460); this.btnEditor.Name = "btnEditor"; this.btnEditor.Size = new System.Drawing.Size(72, 32); this.btnEditor.TabIndex = 19; this.btnEditor.Text = "&Editor..."; this.btnEditor.Click += new System.EventHandler(this.btnEditor_Click); // // txtMultiTerms // this.txtMultiTerms.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.txtMultiTerms.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtMultiTerms.Location = new System.Drawing.Point(60, 0); this.txtMultiTerms.Name = "txtMultiTerms"; this.txtMultiTerms.ReadOnly = true; this.txtMultiTerms.Size = new System.Drawing.Size(226, 20); this.txtMultiTerms.TabIndex = 1; this.txtMultiTerms.Text = ""; // // txtMultiTermCount // this.txtMultiTermCount.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.txtMultiTermCount.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtMultiTermCount.Location = new System.Drawing.Point(332, 0); this.txtMultiTermCount.Name = "txtMultiTermCount"; this.txtMultiTermCount.ReadOnly = true; this.txtMultiTermCount.Size = new System.Drawing.Size(24, 20); this.txtMultiTermCount.TabIndex = 4; this.txtMultiTermCount.Text = ""; this.txtMultiTermCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // lblMultiTermCount // this.lblMultiTermCount.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.lblMultiTermCount.Location = new System.Drawing.Point(318, 4); this.lblMultiTermCount.Name = "lblMultiTermCount"; this.lblMultiTermCount.Size = new System.Drawing.Size(14, 12); this.lblMultiTermCount.TabIndex = 3; this.lblMultiTermCount.Text = "of"; // // txtMultiTermPos // this.txtMultiTermPos.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right); this.txtMultiTermPos.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtMultiTermPos.Location = new System.Drawing.Point(294, 0); this.txtMultiTermPos.Name = "txtMultiTermPos"; this.txtMultiTermPos.ReadOnly = true; this.txtMultiTermPos.Size = new System.Drawing.Size(24, 20); this.txtMultiTermPos.TabIndex = 2; this.txtMultiTermPos.Text = ""; this.txtMultiTermPos.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // lblMultiTerms // this.lblMultiTerms.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblMultiTerms.Location = new System.Drawing.Point(0, 4); this.lblMultiTerms.Name = "lblMultiTerms"; this.lblMultiTerms.Size = new System.Drawing.Size(56, 16); this.lblMultiTerms.TabIndex = 0; this.lblMultiTerms.Text = "Multiple:"; // // panMultiTerm // this.panMultiTerm.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.panMultiTerm.Controls.AddRange(new System.Windows.Forms.Control[] { this.txtMultiTermPos, this.lblMultiTermCount, this.lblMultiTerms, this.txtMultiTermCount, this.txtMultiTerms}); this.panMultiTerm.Location = new System.Drawing.Point(8, 140); this.panMultiTerm.Name = "panMultiTerm"; this.panMultiTerm.Size = new System.Drawing.Size(356, 20); this.panMultiTerm.TabIndex = 4; this.panMultiTerm.VisibleChanged += new System.EventHandler(this.panMultiTerm_VisibleChanged); // // tmrResetMessage // this.tmrResetMessage.Interval = 3000; this.tmrResetMessage.Tick += new System.EventHandler(this.tmrResetMessage_Tick); // // tmrResetMultiTerm // this.tmrResetMultiTerm.Interval = 500; this.tmrResetMultiTerm.Tick += new System.EventHandler(this.tmrResetMultiTerm_Tick); // // frmMain // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(372, 497); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.panMultiTerm, this.btnEditor, this.panDefinition, this.panTerms, this.btnMenu, this.btnStudy, this.txtRemaining, this.lblRemaining, this.lblDefinition, this.grpLine01, this.txtTitle, this.grpLine02, this.grpLine03, this.lblTotal, this.txtTotal, this.grpLine04, this.lblCorrect, this.lblWrong, this.txtCorrect, this.txtWrong, this.btnExit}); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(368, 468); this.Name = "frmMain"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Study Guide"; this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing); this.Load += new System.EventHandler(this.frmMain_Load); this.Activated += new System.EventHandler(this.frmMain_Activated); this.panTerms.ResumeLayout(false); this.panTermList.ResumeLayout(false); this.panImprove.ResumeLayout(false); this.panDefinition.ResumeLayout(false); this.panMultiTerm.ResumeLayout(false); this.ResumeLayout(false); } #endregion #endregion #region Entry Point of Application /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main (string [] args) { frmMain form = new frmMain(); // !!!!! Load settings //m_Settings = (MatchingSettings)MatchingSettings.FromUserSettings(); m_Settings = new MatchingSettings(); // Get default preferences // Parse command line foreach (string arg in args) { if (arg.Length == 0) continue; if (arg[0] == '-') { // Get options switch (arg) { case "-b": form.m_AutoBeginStudy = true; break; } } else { // Load sheet form.DoOpen(arg); break; } } // Run app Application.Run(form); } #endregion private void frmMain_Load(object sender, System.EventArgs e) { m_BoldFont = txtDefinition.Font; m_RegularFont = new Font(txtDefinition.Font, FontStyle.Regular); panMultiTerm.Visible = false; } private void frmMain_Activated(object sender, System.EventArgs e) { if (m_Studying) { if (m_Improving) lstImprove.Focus(); else lstTermList.Focus(); } else { if (m_Sheet != null) btnStudy.Focus(); else btnMenu.Focus(); if (m_AutoBeginStudy) { m_AutoBeginStudy = false; DoStudy(); } } } private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (!DoClose()) e.Cancel = true; } private void menuMainNew_Click(object sender, System.EventArgs e) { DoNew(); } private void menuMainOpen_Click(object sender, System.EventArgs e) { DoOpen(); } private void menuMainEdit_Click(object sender, System.EventArgs e) { DoEdit(); } private void menuMainClose_Click(object sender, System.EventArgs e) { DoClose(); } // !!!!! private void menuMainSoundEffects_Click(object sender, System.EventArgs e) { menuMainSoundEffects.Checked = !menuMainSoundEffects.Checked; } private void menuMainPreferences_Click(object sender, System.EventArgs e) { DoPreferences(); } private void menuMainAbout_Click(object sender, System.EventArgs e) { DoAbout(); } private void menuMainExit_Click(object sender, System.EventArgs e) { this.Close(); } private void btnMenu_Click(object sender, System.EventArgs e) { menuMain.Show(btnMenu.Parent, new Point(btnMenu.Left, btnMenu.Bottom)); } private void btnMenu_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { menuMain.Show(btnMenu.Parent, new Point(btnMenu.Left, btnMenu.Bottom)); } private void btnStudy_Click(object sender, System.EventArgs e) { DoStudy(); } private void btnEditor_Click(object sender, System.EventArgs e) { DoShowEditor(); } private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); } private void btnSelect_Click(object sender, System.EventArgs e) { DoSelectTerm(); } private void lstTermList_DoubleClick(object sender, System.EventArgs e) { DoSelectTerm(); } private void tmrResetColors_Tick(object sender, System.EventArgs e) { DoResetColors(); } private void tmrResetMultiTerm_Tick(object sender, System.EventArgs e) { DoResetMultiple(); } private void tmrResetMessage_Tick(object sender, System.EventArgs e) { DoResetMessage(); } private void lstImprove_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) lstImprove_SelectedIndexChanged(sender, new EventArgs()); } private void lstImprove_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) lstImprove_SelectedIndexChanged(sender, new EventArgs()); } private void lstImprove_SelectedIndexChanged(object sender, System.EventArgs e) { DoShowImproveItem(); } private void lstTermList_Enter(object sender, System.EventArgs e) { if (btnSelect.Enabled) this.AcceptButton = btnSelect; } private void lstTermList_Leave(object sender, System.EventArgs e) { this.AcceptButton = null; } bool b = false; private void txtDefinition_ContentsResized(object sender, System.Windows.Forms.ContentsResizedEventArgs e) { if (!this.Visible) return; if (this.WindowState == FormWindowState.Minimized) return; if (b) return; if ((e.NewRectangle.Height > txtDefinition.ClientSize.Height) && (txtDefinition.Font.Bold)) { b = true; txtDefinition.Font = m_RegularFont; string s = txtDefinition.Rtf; txtDefinition.Clear(); txtDefinition.Rtf = s; b = false; } } private void panMultiTerm_VisibleChanged(object sender, System.EventArgs e) { panDefinition.Height = (( panMultiTerm.Visible )?( (panMultiTerm.Top - 4) ):( panMultiTerm.Top + panMultiTerm.Height )) - panDefinition.Top; } private void txtDefinition_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e) { try // Call the Process.Start method to open the default browser with a URL: { System.Diagnostics.Process.Start(e.LinkText); } catch (Win32Exception) {} catch // Failsafe { MessageBox.Show(this, "Could not start browser process.", "Study Guide", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool DoNew () { return DoShowEditor("-n"); } private bool DoOpen () { if (openFileDialog.ShowDialog(this) == DialogResult.Cancel) return false; return DoOpen(openFileDialog.FileName); } private bool DoOpen (string FileName) { try { return DoOpen(MatchingSheet.FromFile(FileName)); } catch (IOException e) { MessageBox.Show(this, e.Message, "File Load Error"); } return false; } private bool DoOpen (MatchingSheet sheet) { return DoOpen(sheet, false); } private bool DoOpen (MatchingSheet sheet, bool testSheet) { if (!DoClose()) return false; if (sheet == null) return false; m_Sheet = sheet; txtTitle.Text = m_Sheet.Title; txtTitle.ForeColor = Color.FromKnownColor(KnownColor.InfoText); txtTitle.BackColor = Color.FromKnownColor(KnownColor.Info); menuMainClose.Enabled = (!testSheet); menuMainEdit.Enabled = (!testSheet); return true; } private bool DoEdit () { if (m_Sheet == null) return false; return DoShowEditor(m_Sheet.FileName); } private bool DoClose () { if (m_Sheet == null) return true; if (m_Studying) if (!DoStudy(true)) return false; m_Sheet = null; txtTitle.Text = "( nothing loaded )"; txtTitle.ForeColor = Color.FromKnownColor(KnownColor.GrayText); txtTitle.BackColor = Color.FromKnownColor(KnownColor.Control); menuMainClose.Enabled = false; menuMainEdit.Enabled = false; txtRemaining.Text = ""; txtTotal.Text = ""; txtCorrect.Text = ""; txtWrong.Text = ""; DoResetColors(); return true; } private bool DoPreferences () { // !!!!! //MatchingSettings settings = (new frmSettings()).ShowDialog(this, m_Settings); //if (settings != null) m_Settings = settings; MessageBox.Show(":: Preferences ::"); return true; } private bool DoAbout () { frmAbout form = new frmAbout(); form.ShowDialog(this); return true; } private bool DoShowEditor () { return DoShowEditor(""); } private bool DoShowEditor (string arg) { return DoShowEditor( new string [] { arg }); } private bool DoShowEditor (string [] args) { string cmdline = ""; // Build command line foreach (string arg in args) { if (cmdline != "") cmdline += " "; cmdline += (( arg.IndexOf(' ') == -1 )?( arg ):( '"' + arg + '"' )); } try { System.Diagnostics.Process.Start(Path.Combine(Application.StartupPath, "Study Guide Editor"), cmdline); } catch (Win32Exception e) { // Failsafe MessageBox.Show(this, "Could not run editor:\n\n" + e.Message, "Study Guide", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void DoShowDefinition (string definition) { // !!!!! Mini-HTML //if (definition.Substring(0, 1) == ((char)27).ToString()) //{ // if (!MatchingSheet.TextEquals(txtDefinition.Rtf, definition.Substring(1))) // { // txtDefinition.Clear(); // txtDefinition.Font = m_BoldFont; // txtDefinition.Rtf = definition.Substring(1); // } //} //else //{ // if (txtDefinition.Text != definition) // { // txtDefinition.Clear(); // txtDefinition.Font = m_BoldFont; // txtDefinition.Text = definition; // } //} if (txtDefinition.Text != definition) { txtDefinition.Clear(); txtDefinition.Font = m_BoldFont; txtDefinition.Text = definition; } } private bool DoNextTerm () { return DoNextTerm (false); } private bool DoNextTerm (bool noRefresh) { // Update 'remaining' count txtRemaining.Text = (m_Sheet.TermCount - m_TermNum).ToString(); // Check for end of study m_TermNum++; if (m_TermNum > m_TermList.Length) { m_MultiTerm = false; DoStudy(noRefresh); // End of study return true; } // Update term and definition m_TermIndex = m_TermList[(m_TermNum-1)]; DoShowDefinition(m_Sheet.Definitions[m_TermIndex]); bool b = m_MultiTerm == false; string [] aMultiTermList = MatchingSheet.SplitTerms(m_Sheet.Terms[m_TermIndex]); m_MultiTerm = (aMultiTermList.Length > 1); if (m_MultiTerm) DoResetMultiple(); m_MultiTermNum = 0; m_MultiTermList = aMultiTermList; m_MultiTermListAquired = new string [m_MultiTermList.Length]; m_MultiTermListRemains.Clear(); m_MultiTermListRemains.AddRange(m_MultiTermList); if (b) DoResetMultiple(); lstTermList.SelectedIndex = 0; lstTermList.SelectedIndex = -1; lstTermList.Focus(); return true; } private bool DoSelectTerm () { bool bCorrect; if (lstTermList.SelectedIndex == -1) return false; if (tmrResetColors.Enabled) tmrResetColors_Tick(tmrResetColors, new EventArgs()); string item = (string)lstTermList.SelectedItem; // Multi-term selection if (m_MultiTerm) { m_MultiTermNum++; txtMultiTermPos.Text = m_MultiTermNum.ToString(); // Check for wrong if (!m_MultiTermListRemains.Contains(item)) return DoSelectTerm(false); // Remove term from list of remaining terms m_MultiTermListRemains.Remove(item); // Get 'aquired' list txtMultiTerms.Text = ""; for (int i = 0; i < m_MultiTermListAquired.Length; i++) { if (m_MultiTermListAquired[i] == null) { if (item != m_MultiTermList[i]) continue; m_MultiTermListAquired[i] = item; } if (txtMultiTerms.Text != "") txtMultiTerms.Text += ", "; txtMultiTerms.Text += m_MultiTermListAquired[i]; } // Check for correct (completely answered) if (m_MultiTermNum >= m_MultiTermList.Length) { // Signal multi-term to user DoSelectTerm(true); SignalSelectMultiTerm(true); return true; } lstTermList.SelectedIndex = 0; lstTermList.SelectedIndex = -1; lstTermList.Focus(); // Signal to user SignalSelectTerm(true, true, false); SignalSelectMultiTerm(false); return true; } bCorrect = false; for (int i = 0; i < m_Sheet.TermCount; i++) if ((string.Compare(item, m_Sheet.Terms[i], true) == 0) && (i == m_TermIndex)) { bCorrect = true; break; } return DoSelectTerm(bCorrect); } private bool DoSelectTerm (bool bCorrect) { if (bCorrect) { // Correct m_Correct++; txtCorrect.Text = m_Correct.ToString(); } else { // Wrong txtWrong.Text = (m_TermNum - m_Correct).ToString(); m_ImproveList.Add(m_TermIndex); // Hide current multi-term if wrong m_MultiTerm = false; if (panMultiTerm.Visible == true) panMultiTerm.Visible = false; } // Remember 'completed' bool bCompleted = (m_TermNum < m_TermList.Length); // First do next item DoNextTerm(); // Signal to user SignalSelectTerm(bCorrect, bCompleted); return true; } private void SignalSelectTerm (bool bCorrect) { SignalSelectTerm(bCorrect, true, true); } private void SignalSelectTerm (bool bCorrect, bool bPlaySound) { SignalSelectTerm(bCorrect, bPlaySound, true); } private void SignalSelectTerm (bool bCorrect, bool bPlaySound, bool bShowColors) { // Force refresh DoResetColors(); // Signal correct/wrong answer to user if (bCorrect) { // Show colors if (bShowColors) { lblCorrect.ForeColor = Color.SeaGreen; txtCorrect.BackColor = Color.PaleGreen; } this.Refresh(); tmrResetColors.Enabled = true; // Play sound if (bPlaySound) PlaySound(MatchingSounds.Correct); } else { // Show colors if (bShowColors) { lblWrong.ForeColor = Color.Firebrick; txtWrong.BackColor = Color.Salmon; } this.Refresh(); tmrResetColors.Enabled = true; // Play sound if (bPlaySound) PlaySound(MatchingSounds.Wrong); } } // To be called immediately after SignalSelectTerm private void SignalSelectMultiTerm (bool bComplete) { // Force reset DoResetMultiple(tmrResetMultiTerm.Enabled); // Show colors lblMultiTerms.ForeColor = Color.SeaGreen; if (bComplete) { txtMultiTerms.BackColor = Color.PaleGreen; txtMultiTermCount.BackColor = Color.PaleGreen; } txtMultiTermPos.BackColor = Color.PaleGreen; tmrResetColors.Interval = (( bComplete )?( 800 ):( 500 )); tmrResetMultiTerm.Enabled = false; tmrResetMultiTerm.Interval = (( bComplete )?( 800 ):( 500 )); tmrResetMultiTerm.Enabled = true; } private bool DoStudy () { return DoStudy(false); } private bool DoStudy (bool forceStop) { return DoStudy(forceStop, false); } private bool DoStudy (bool forceStop, bool noRefresh) { if (!m_Studying) { if (m_Sheet == null) if (!DoOpen()) return false; if (m_Sheet.TermCount == 0) { MessageBox.Show(this, "Could not begin; the Study Sheet is empty.", "Study Guide", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } m_Studying = true; btnStudy.Text = "&Stop"; Color bgc = Color.FromKnownColor(KnownColor.Window); txtDefinition.BackColor = bgc; txtRemaining.BackColor = bgc; txtTotal.BackColor = bgc; lstTermList.BackColor = bgc; btnSelect.Enabled = true; DoResetMessage(); DoResetColors(); lstTermList.Items.Clear(); lstTermList.BeginUpdate(); for (int i = 0; i < m_Sheet.TermCount; i++) { foreach (string item in MatchingSheet.SplitTerms(m_Sheet.Terms[i])) { bool b = true; for (int n = 0; n < lstTermList.Items.Count; n++) { if (string.Compare((string)lstTermList.Items[n], item, true) == 0) { b = false; break; } } if (b) lstTermList.Items.Add(item); } } try { lstTermList.EndUpdate(); } catch (NullReferenceException) {} txtTotal.Text = m_Sheet.TermCount.ToString(); txtRemaining.Text = txtTotal.Text; txtCorrect.Text = "0"; txtWrong.Text = "0"; m_MultiTermList = null; m_MultiTermListRemains.Clear(); txtMultiTerms.BackColor = bgc; txtMultiTermPos.BackColor = bgc; txtMultiTermCount.BackColor = bgc; m_Correct = 0; m_TermNum = 0; m_ImproveList = new ArrayList(m_Sheet.TermCount); m_MultiTerm = false; RandomizeTerms(); // Play begin sound PlaySound(MatchingSounds.Begin); if (!noRefresh) this.Refresh(); return DoNextTerm(); } else if (m_Improving) { m_Improving = false; m_Studying = false; lstImprove.BackColor = Color.FromKnownColor(KnownColor.Control); lstImprove.Items.Clear(); Color bgc = Color.FromKnownColor(KnownColor.Control); txtRemaining.BackColor = bgc; txtTotal.BackColor = bgc; DoResetColors(); btnStudy.Text = "&Begin"; txtDefinition.Text = ""; txtDefinition.BackColor = bgc; m_ImproveList = null; m_MultiTermList = null; m_MultiTermListRemains.Clear(); if (!noRefresh) this.Refresh(); return true; } else { Color bgc = Color.FromKnownColor(KnownColor.Control); lstTermList.BackColor = bgc; txtDefinition.Text = ""; btnSelect.Enabled = false; lstTermList.Items.Clear(); // Check for improvement if ((m_ImproveList.Count > 0) && (forceStop == false)) { m_Improving = true; lstImprove.BackColor = Color.FromKnownColor(KnownColor.Window); lstImprove.Items.Clear(); if (m_ImproveList.Count > 0) { lstImprove.BeginUpdate(); for (int i = 0; i < m_ImproveList.Count; i++) lstImprove.Items.Add(m_Sheet.Terms[(int)m_ImproveList[i]]); lstImprove.EndUpdate(); } btnStudy.Text = "&Done"; lstImprove.Focus(); } else { m_Studying = false; txtRemaining.BackColor = bgc; txtTotal.BackColor = bgc; DoResetColors(); btnStudy.Text = "&Begin"; txtDefinition.BackColor = bgc; m_MultiTermList = null; m_MultiTermListRemains.Clear(); m_ImproveList = null; } // Signal to user if (m_TermNum > m_Sheet.TermCount) { if (m_Correct == m_Sheet.TermCount) { // Perfect PlaySound(MatchingSounds.Perfect); lblMessage.Text = "Perfect!!"; lblMessage.BackColor = Color.LightSkyBlue; lblMessage.ForeColor = Color.LightYellow; } else { PlaySound(MatchingSounds.Complete); int p = ((int)(100 * ((double)m_Correct / (double)m_Sheet.TermCount))); if (p >= 90) { lblMessage.Text = "Excellent!"; lblMessage.BackColor = Color.LightSteelBlue; lblMessage.ForeColor = Color.Honeydew; } else if (p >= 80) { lblMessage.Text = "Great work!"; lblMessage.BackColor = Color.LightSteelBlue; lblMessage.ForeColor = Color.Honeydew; } else if (p >= 75) { lblMessage.Text = "Good job!"; lblMessage.BackColor = Color.LightSteelBlue; lblMessage.ForeColor = Color.Honeydew; } else if (p >= 70) { lblMessage.Text = "Not bad!"; lblMessage.BackColor = Color.Thistle; lblMessage.ForeColor = Color.GhostWhite; } else if (p >= 60) { lblMessage.Text = "Keep working!"; lblMessage.BackColor = Color.Thistle; lblMessage.ForeColor = Color.GhostWhite; } else if (p >= 50) { lblMessage.Text = "Keep it up!"; lblMessage.BackColor = Color.Thistle; lblMessage.ForeColor = Color.GhostWhite; } else if (p >= 25) { lblMessage.Text = "Needs some work!"; lblMessage.BackColor = Color.RosyBrown; lblMessage.ForeColor = Color.LightPink; } else { lblMessage.BackColor = Color.RosyBrown; lblMessage.ForeColor = Color.LightPink; switch ((new Random(unchecked((int)DateTime.Now.Ticks))).Next(5)) { case 1: lblMessage.Text = "Keep practicing!"; break; case 2: lblMessage.Text = "Don't give up!"; break; case 3: lblMessage.Text = "Uh oh! Keep trying!"; break; case 4: lblMessage.Text = "You'll get it!"; break; default: lblMessage.Text = "Don't get discouraged!"; break; } } } lblMessage.Visible = true; txtDefinition.Visible = false; } else { m_MultiTerm = false; panMultiTerm.Visible = false; DoResetColors(); } // Enable timer tmrResetMessage.Enabled = true; // Refresh form if (!noRefresh) this.Refresh(); return true; } } private void DoResetColors () { Color bgc = Color.FromKnownColor(KnownColor.ControlText); lblCorrect.ForeColor = bgc; lblWrong.ForeColor = bgc; bgc = Color.FromKnownColor(KnownColor.Control); txtCorrect.BackColor = (( m_Studying )?( Color.FromKnownColor(KnownColor.Window) ):( bgc )); txtWrong.BackColor = (( m_Studying )?( Color.FromKnownColor(KnownColor.Window) ):( bgc )); tmrResetColors.Interval = 500; tmrResetColors.Enabled = false; } private void DoResetMultiple () { DoResetMultiple(true); } private void DoResetMultiple (bool ResetAll) { if (ResetAll) panMultiTerm.Visible = m_MultiTerm; Color bgc = Color.FromKnownColor(KnownColor.Window); txtMultiTerms.BackColor = bgc; txtMultiTermPos.BackColor = bgc; txtMultiTermCount.BackColor = bgc; lblMultiTerms.ForeColor = Color.FromKnownColor(KnownColor.ControlText); if (ResetAll) { if (m_MultiTermNum == 0) txtMultiTerms.Text = ""; txtMultiTermPos.Text = m_MultiTermNum.ToString(); if (m_MultiTermList != null) txtMultiTermCount.Text = m_MultiTermList.Length.ToString(); else txtMultiTermCount.Text = ""; } tmrResetMultiTerm.Enabled = false; } private void DoResetMessage () { txtDefinition.Visible = true; lblMessage.Visible = false; tmrResetMessage.Enabled = false; } private bool DoShowImproveItem () { if (lstImprove.SelectedIndex == -1) return false; if (m_ImproveList == null) return false; lblMessage.Visible = false; txtDefinition.Visible = true; DoShowDefinition(m_Sheet.Definitions[(int)m_ImproveList[lstImprove.SelectedIndex]]); return true; } private void PlaySound (MatchingSounds sound) { string FileName; // Failsafe if (!m_Settings.PlaySounds) return; // !!!!! if (!menuMainSoundEffects.Checked) return; // Get FileName FileName = ""; switch (sound) { case MatchingSounds.Begin: FileName = m_Settings.Sounds[0]; break; case MatchingSounds.Correct: FileName = m_Settings.Sounds[1]; break; case MatchingSounds.Wrong: FileName = m_Settings.Sounds[2]; break; case MatchingSounds.Complete: FileName = m_Settings.Sounds[3]; break; case MatchingSounds.Perfect: FileName = m_Settings.Sounds[4]; break; default: return; } // Play sound sndPlaySound(FileName, IntPtr.Zero, (SoundFlags.SND_FileName | SoundFlags.SND_ASYNC | SoundFlags.SND_NOWAIT)); } private void RandomizeTerms () { int val = 0; bool b; m_TermList = new int [m_Sheet.TermCount]; Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < m_Sheet.TermCount; i++) m_TermList[i] = -1; b = false; for (int i = 0; i < m_Sheet.TermCount; i++) { if (!b) val = rnd.Next(m_Sheet.TermCount); // Check to see if value was already used b = false; for (int i2 = 0; i2 < m_Sheet.TermCount; i2++) { if (m_TermList[i2] == val) { // Value was already used; increase to next value val = ((val + 1) % m_Sheet.TermCount); b = true; break; } } // Repeat current term with new value if (b) { i--; continue; } // Term is unique; use it m_TermList[i] = val; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using UberApp.Models; namespace UberApp.Controllers { public class tblCustomersController : ApiController { private MyAppDataEntities db = new MyAppDataEntities(); // GET: api/tblCustomers public IQueryable<tblCustomer> GettblCustomers() { return db.tblCustomers; } // GET: api/tblCustomers/5 public IHttpActionResult GettblCustomer(string Email, string Password) { var cust = db.tblCustomers.Where(tblCustomer => tblCustomer.Email.Equals(Email) && tblCustomer.Password.Equals(Password)).FirstOrDefault(); if (cust.Email == null && cust.Password == null) { return (null); } else { return Ok(cust); } } // PUT: api/tblCustomers/5 [ResponseType(typeof(void))] public IHttpActionResult PuttblCustomer(int id, tblCustomer tblCustomer) { Console.WriteLine("Hello"); tblCustomer oldDetails = tblCustomer; if (!ModelState.IsValid) { return BadRequest("Not valid data"); } using (db) { var cust = db.tblCustomers.Where(g => g.CustId.Equals(id)).FirstOrDefault(); if (cust != null) { cust.Firstname = tblCustomer.Firstname; cust.Lastname = tblCustomer.Lastname; cust.CustomerAddress= tblCustomer.CustomerAddress; cust.Email = tblCustomer.Email; cust.Password = tblCustomer.Password; var res = db.SaveChanges(); } else { return NotFound(); } } return Ok(); } // POST: api/tblCustomers [ResponseType(typeof(tblCustomer))] public IHttpActionResult PosttblCustomer(tblCustomer tblCustomer) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.tblCustomers.Add(tblCustomer); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = tblCustomer.CustId }, tblCustomer); } // DELETE: api/tblCustomers/5 [ResponseType(typeof(tblCustomer))] public IHttpActionResult DeletetblCustomer(int id) { tblCustomer tblCustomer = db.tblCustomers.Find(id); if (tblCustomer == null) { return NotFound(); } db.tblCustomers.Remove(tblCustomer); db.SaveChanges(); return Ok(tblCustomer); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool tblCustomerExists(int id) { return db.tblCustomers.Count(e => e.CustId == id) > 0; } } }
using System; using System.Collections.Generic; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace LunchTime.Collections{ public class UserProfile: Collection{ public string UserName {get; set;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace IRAP.BL.OPCGateway.Interfaces { internal interface IWebAPIAction { string DoAction(); } }
using System; namespace Core.Concrete.Exceptions { public class ObjectNotFoundedException : Exception { public ObjectNotFoundedException() : base() { } public ObjectNotFoundedException(string message) : base(message) { } public ObjectNotFoundedException(string message, Exception innerException) : base(message, innerException) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnManager : MonoBehaviour { //array that holds planet gameobjects [SerializeField] private GameObject[] _planets; //array that holds scenery ships [SerializeField] private GameObject[] _sceneryShips; [SerializeField] private GameObject[] _asteroids; [SerializeField] private GameObject _berserker; [SerializeField] private GameObject _berserkerLeft; [SerializeField] private GameObject _littleShooter; [SerializeField] private GameObject _bomber; [SerializeField] private GameObject _boss1; //bool holding value if player is killed [SerializeField] private bool _isPlayerDead = false; [SerializeField] private int _enemiesDestroyed = 0; [SerializeField] public bool _bossSpawned = false; int planetIndex; int sceneryShipIndex; int asteroidIndex; // Use this for initialization void Start () { StartCoroutine("SpawnBackgroundPlanets"); StartCoroutine("SpawnBackgroundShips"); StartCoroutine("SpawnAsteroids"); StartCoroutine("SpawnBerserkerWave"); StartCoroutine("SpawnShooterWave"); StartCoroutine("SpawnBomberWave"); } // Update is called once per frame void Update () { if(_enemiesDestroyed >= 20 && _bossSpawned == false) { _bossSpawned = true; Debug.Log("Boss active."); Instantiate(_boss1, new Vector3(0, 14, 0), Quaternion.identity); } } IEnumerator SpawnBackgroundPlanets() { while (!_isPlayerDead && _enemiesDestroyed < 20) { planetIndex = Random.Range(0, _planets.Length); Instantiate(_planets[planetIndex], new Vector3(Random.Range(-9.5f, 9.5f), 15, 0), Quaternion.identity); yield return new WaitForSeconds(Random.Range(10.0f, 13.0f)); } } IEnumerator SpawnBackgroundShips() { while (!_isPlayerDead && _enemiesDestroyed < 20) { sceneryShipIndex = Random.Range(0, _sceneryShips.Length); Instantiate(_sceneryShips[sceneryShipIndex], new Vector3(Random.Range(-9.5f, 9.5f), 15, 0), Quaternion.identity); yield return new WaitForSeconds(Random.Range(3.0f, 7.0f)); } } IEnumerator SpawnAsteroids() { while (!_isPlayerDead && _enemiesDestroyed < 20) { asteroidIndex = Random.Range(0, _asteroids.Length); Instantiate(_asteroids[asteroidIndex], new Vector3(Random.Range(-9.5f, 9.5f), 15, 0), Quaternion.identity); yield return new WaitForSeconds(Random.Range(3.0f, 7.0f)); } } IEnumerator SpawnBerserkerWave() { while (!_isPlayerDead && _enemiesDestroyed < 20) { InstantiateBerserkerWave(); yield return new WaitForSeconds(Random.Range(14.0f, 17.0f)); } } IEnumerator SpawnShooterWave() { while (!_isPlayerDead && _enemiesDestroyed < 20) { yield return new WaitForSeconds(Random.Range(13.0f, 17.0f)); InstantiateShooterWave(); } } IEnumerator SpawnBomberWave() { while (!_isPlayerDead && _enemiesDestroyed < 20) { Instantiate(_bomber, new Vector3(-10.66f, -.68f, 0), Quaternion.identity); yield return new WaitForSeconds(20); } } private void InstantiateBerserkerWave() { int offset = 0; for (int i = 0; i <= 2; i++) { Instantiate(_berserker, new Vector3(2 + offset, 13, 0), Quaternion.identity); Instantiate(_berserkerLeft, new Vector3(-2 - offset, 13, 0), Quaternion.identity); offset += 2; } } private void InstantiateShooterWave() { int offset = 0; for (int i = 0; i < 2; i++) { Instantiate(_littleShooter, new Vector3(2 + offset, 13, 0), Quaternion.identity); Instantiate(_littleShooter, new Vector3(-2 - offset, 13, 0), Quaternion.identity); offset += 2; } } public void UpdateDestroyedEnemies() { _enemiesDestroyed++; } }
namespace Storyblok.Sdk { public enum StoryblokCache { NoCache, EveryHour } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; using System.Diagnostics; using System.Configuration; using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common; namespace TY.SPIMS.Client { public class ClientHelper { public static bool IsEdit = false; public static string StatusLabelText = "Total Records: {0} | Execution Time: {1} ms."; #region Message Box public static DialogResult ShowConfirmMessage(string message) { return KryptonMessageBox.Show(message, "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); } public static void ShowErrorMessage(string message) { KryptonMessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } public static void ShowRequiredMessage(string requiredFields) { KryptonMessageBox.Show(string.Format("Required fields: {0}", requiredFields), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } public static void ShowSuccessMessage(string message) { KryptonMessageBox.Show(message, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } public static void ShowDuplicateMessage(string message) { KryptonMessageBox.Show(string.Format("{0} already exists.", message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } #endregion #region Exception Handler public static void LogException(Exception ex) { string sourceName = "T.Y. Enterprises - Sales and Inventory System"; if (!EventLog.SourceExists(sourceName)) EventLog.CreateEventSource(sourceName, "Application"); EventLog.WriteEntry(sourceName, ex.Message.ToString(), EventLogEntryType.Error); } #endregion #region DB Backup public static void BackupDB() { SaveFileDialog d = new SaveFileDialog(); d.Filter = "Database backup file (*.bak)|*.bak"; if (d.ShowDialog() == DialogResult.OK) { try { Backup sqlBackup = new Backup(); sqlBackup.Action = BackupActionType.Database; sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString(); sqlBackup.BackupSetName = "Archive"; string dbName = "TYEnterprises"; sqlBackup.Database = dbName; BackupDeviceItem deviceItem = new BackupDeviceItem(d.FileName, DeviceType.File); string ServerIP = ConfigurationManager.AppSettings["ServerIP"] != null ? ConfigurationManager.AppSettings["ServerIP"] : "127.0.0.1"; ServerConnection connection = new ServerConnection(ServerIP, "TYLogin", "ty12345"); Server sqlServer = new Server(connection); Database db = sqlServer.Databases[dbName]; sqlBackup.Initialize = true; sqlBackup.Checksum = true; sqlBackup.ContinueAfterError = true; sqlBackup.Devices.Add(deviceItem); sqlBackup.Incremental = false; sqlBackup.ExpirationDate = DateTime.Now.AddDays(30); sqlBackup.LogTruncation = BackupTruncateLogType.Truncate; sqlBackup.FormatMedia = false; sqlBackup.SqlBackup(sqlServer); ShowSuccessMessage("Backup successful."); } catch (Exception ex) { throw ex; } } } #endregion #region Helper public static long PerformFetch(Action a) { Stopwatch s = new Stopwatch(); s.Start(); a(); s.Stop(); return s.ElapsedMilliseconds; } public static string GetSaleType(int type) { string saleType = string.Empty; switch (type) { case 0: saleType = "Cash Invoice"; break; case 1: saleType = "Cash/Petty/SOR"; break; case 2: saleType = "Cash/Charge Invoice"; break; case 3: saleType = "Sales Order Slip"; break; case 4: saleType = "Charge Invoice"; break; case 5: saleType = "No Invoice"; break; } return saleType; } #endregion } }
using MobileCollector.model; using ServerCollector; using ServerCollector.store; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ServerCollector { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { //var value = new Google.Apis.Datastore.v1.Data.Value() { // TimestampValue=DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture) //}; //var ser = Newtonsoft.Json.JsonConvert.SerializeObject(value); AppInstance.Instance.InitialiseAppResources(null,null); //we have loaded the app this.menuServerSync.Click += MenuServerSync_Click; //this.menuServerSyncOldData.Click += MenuServerSync_Click; this.menuConfigure.Click += MenuConfigure_Click; this.menuAllData.Click += MenuAllData_Click; this.menuSmmaries.Click += MenuSmmaries_Click; this.menuRefreshLocal.Click += menuRefreshLocal_Click; } void setProgressValue(int value) { pbarProgress.Value = value; } private void menuRefreshLocal_Click(object sender, RoutedEventArgs e) { AppInstance.Instance.CloudDbInstance.RefreshLocalEntities(setProgressValue); } private void MenuSmmaries_Click(object sender, RoutedEventArgs e) { var addRecordsFromTablet = false; if (addRecordsFromTablet) { //we have records that couldn't be synced from the tablet var toSave = new List<CloudEntity>(); var txt = File.ReadAllText("Assets\\unsyncd.txt"); var outEntities = txt.DecompressFromBase64String(); var now = DateTime.Now.AddDays(-8); var asBinary = now.ToBinary(); var processors = new Dictionary<string, List<CloudEntity>>(); foreach (var outEntity in outEntities) { var ppdataset = DbSaveableEntity.fromJson<GeneralEntityDataset>(new KindItem(outEntity.DataBlob)); var saveable = new DbSaveableEntity(ppdataset) { kindName = new KindName(ppdataset.FormName) }; if (!processors.ContainsKey(ppdataset.FormName)) { processors[ppdataset.FormName] = new List<CloudEntity>(); } var cloudEntity = new CloudEntity() { Id = saveable.Id.Value, EntityId = saveable.EntityId.Value, EditDay = now.toYMDInt(), EditDate = asBinary, DataBlob = saveable .getJson() .Encrypt() .Value, FormName = ppdataset.FormName, KindMetaData = saveable.Entity.KindMetaData ?? string.Empty }; processors[ppdataset.FormName].Add(cloudEntity); } foreach (var item in processors) { new KindDataProcessor() .addToProcessingQueue(item.Key, item.Value); } //we save them to local AppInstance.Instance.CloudDbInstance.RefreshLocalEntities(setProgressValue); } MessageBox.Show("Menu item clicked "); } private void MenuAllData_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Menu item clicked "); } private void MenuConfigure_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Menu item clicked "); } private async void MenuServerSync_Click(object sender, RoutedEventArgs e) { //we test the connection var isConnected = await CloudDb.checkConnection(); if(!isConnected) { MessageBox.Show("No internet connection detected"); return; } var dialog = MessageBox.Show("Do you want to start data download from the server", "Please confirm action", MessageBoxButton.OKCancel); if (dialog != MessageBoxResult.OK) return; //we get list of files to download var syncOldData = this.menuServerSyncOldData == sender; var res = await AppInstance.Instance.CloudDbInstance .EnsureServerSync(setProgressValue, syncOldData); //for each file, we download AppInstance.Instance.CloudDbInstance.RefreshLocalEntities(setProgressValue); //we decrypt //we deidentify //and save to the main datastore MessageBox.Show("Menu item clicked "); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08.NumbersMatrix { class MainProg { static void Main() { int[,] matrix1 = new int[,] { {1, 2, -3}, {2, 1, 3}, {3, 1, 2} }; int[,] matrix2 = new int[,] { {4, 5, 6}, {-1, 0, 7}, {3, 2, 1} }; Matrix<int> m1 = new Matrix<int>(matrix1); Matrix<int> m2 = new Matrix<int>(matrix2); Console.WriteLine(m1 + m2); Console.WriteLine(m1 - m2); Console.WriteLine(m1 * m2); Console.WriteLine(m1.Transpose()); Console.WriteLine(m1 * 5); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Foundry.SourceControl { public interface ISourceFile : ISourceObject { string Extension { get; } byte[] Content { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EasyDev.Configuration; using System.Xml; using System.Collections; using System.IO; using System.Threading; using System.Reflection; namespace EasyDev.Resources { public class XmlResourceManager : ResourceManagerBase { private XmlDocument languageNodes = null; public XmlResourceManager() { } #region ResourceManagerBase Members public override string GetString(string key) { return this.GetValueByKey(key); } public override void Initialize(ResourceItemConfig item) { string cultureName = item.Culture; if (string.IsNullOrEmpty(cultureName)) { cultureName = Thread.CurrentThread.CurrentCulture.Name; } string path = string.Format(@"{0}.{1}_{2}.xml", item.Assembly, item.BaseName, cultureName); Stream resouceStream = Assembly.Load(item.Assembly).GetManifestResourceStream(path); StreamReader reader = null; try { if (resouceStream != null && resouceStream.CanRead) { resouceStream.Seek(0, SeekOrigin.Begin); reader = new StreamReader(resouceStream); this.languageNodes = new XmlDocument(); this.languageNodes.LoadXml(reader.ReadToEnd()); } else { throw new GlobalizeException("_cannot_find_language_resource"); } } catch (GlobalizeException e) { throw e; } } #endregion /// <summary> /// 在国际化语言信息中查找对应的值 /// </summary> /// <param name="key"></param> /// <returns></returns> private string GetValueByKey(string key) { string value = string.Empty; try { XmlNodeList items = this.languageNodes.SelectNodes("./Resources/ResourceItem"); XmlNode item = null; XmlNode node = null; IEnumerator itr_items = items.GetEnumerator(); while (itr_items.MoveNext()) { node = ((XmlNode)itr_items.Current); item = node.SelectSingleNode("Key"); if (item != null && item.InnerText.Equals(key)) { break; } } if (node != null && node.HasChildNodes) { value = node.SelectSingleNode("Value").InnerText; } else { throw new GlobalizeException("_can_not_find_the_right_language_item"); } } catch (GlobalizeException e) { throw e; } return value; } } }
namespace RRExpress.Express { public static class Const { public static readonly string SettingCatlog = "自由快递"; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace TestApplication.Models { public class Date { [Required(ErrorMessage ="Name este necesar")] public string Nume { get; set; } [Required(ErrorMessage ="Prenumele este necesar")] public string Prenume { get; set; } [Required(ErrorMessage ="Este necesar")] [DataType(DataType.EmailAddress)] [EmailAddress] public string Email { get; set; } } public class Zbor { [Required] public string Locatie { get; set; } List<Puncte> ListaPuncte { get; set; } public Zbor() { ListaPuncte = new List<Puncte>(); } } public class Puncte { public string Latitudine { get; set; } public string Longitudine { get; set; } } public class Aggregate { public Date DateSolicitant { get; set; } public List<Zbor> ListaZbor { get; set; } public Aggregate() { ListaZbor = new List<Zbor>(); } } }
namespace Funding.Data.Models { using Funding.Common.Constants; using System; using System.ComponentModel.DataAnnotations; public class Message { public int Id { get; set; } [Required] [StringLength(MessageConst.MaxLength, MinimumLength = MessageConst.MinLength)] public string Title { get; set; } [Required] [StringLength(MessageConst.MaxLength, MinimumLength = MessageConst.MinLength)] public string Content { get; set; } [Required] public DateTime SentDate { get; set; } public string SenderId { get; set; } public User Sender { get; set; } public string ReceiverId { get; set; } public User Receiver { get; set; } [Required] public bool isRead { get; set; } } }
using Blazored.LocalStorage; using Microsoft.AspNetCore.Components.Authorization; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using System.Text.Json; using System.Net.Http.Headers; namespace AnyTest.ClientAuthentication { /// <summary> /// \~english A service class for authenticating with JWT tokens /// \~ukrainian Сервісний клас для аутентифікації JWT токенів /// </summary> public class AuthService : IAuthService { private readonly HttpClient _httpClient; private readonly AuthenticationStateProvider _authenticationStateProvider; private readonly ILocalStorageService _localStorage; /// <summary> /// \~english A list of valid roles /// \~ukrainian Перелік дійснийх ролей /// </summary> public static readonly List<string> Roles = new List<string> { "Administrator", "Tutor", "Student" }; /// <summary> /// \~english Initalizes a new instance of <c>AuthService</c> class /// \~ukrainian Ініціалізує новий екземпляр класу <c>AuthService</c> /// </summary> /// <param name="httpClient"> /// \~english An instance of <c>HttpClient</c> class. Depencency /// \~ukrainian Езкемплярр класу <c>HttpClient</c>. Залежність /// </param> /// <param name="authenticationStateProvider"> /// \~english An instance of <c>AuthenticationStateProvider</c> class. Depencency /// \~ukrainian Езкемплярр класу <c>AuthenticationStateProvider</c>. Залежність /// </param> /// <param name="localStorage"> /// \~english A class, implementing an <c>ILocalStorageService</c> interface. Dependency. /// \~ukrainian Клас. який наслідує інтерфейсу <c>ILocalStorageSerivce</c>. Залежність. /// </param> public AuthService(HttpClient httpClient,AuthenticationStateProvider authenticationStateProvider, ILocalStorageService localStorage) { _httpClient = httpClient; _authenticationStateProvider = authenticationStateProvider; _localStorage = localStorage; } ///<inheritdoc /> public async Task<LoginResult> Login(LoginModel creds) { var loginAsJson = JsonSerializer.Serialize(creds); var response = await _httpClient.PostAsync("Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json")); var loginResult = JsonSerializer.Deserialize<LoginResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if(response.IsSuccessStatusCode) { await _localStorage.SetItemAsync("authToken", loginResult.Token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token); (_authenticationStateProvider as ApiAuthenticaionStateProvider).MarkUserAsAuthenticated(loginResult.Token); } return loginResult; } ///<inheritdoc /> public async Task Logout() { await _localStorage.RemoveItemAsync("authToken"); (_authenticationStateProvider as ApiAuthenticaionStateProvider).MarkUserAsLoggedOut(); _httpClient.DefaultRequestHeaders.Authorization = null; } ///<inheritdoc /> public async Task<RegisterResult> Register(RegisterModel registerModel) { var result = await _httpClient.PostJsonAsync<RegisterResult>("api/accounts", registerModel); return result; } /// <inheritdoc /> public async Task<bool> GetToken() { var savedToken = await _localStorage.GetItemAsync<string>("authToken"); if (string.IsNullOrWhiteSpace(savedToken)) { return false; } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", savedToken); return true; } } }
using FamilyAccounting.DAL.Connection; using FamilyAccounting.DAL.Entities; using FamilyAccounting.DAL.Interfaces; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; namespace FamilyAccounting.DAL.Repositories { public class TransactionRepository : ITransactionRepository { private readonly string connectionString; public TransactionRepository(DbConfig dbConfig) { connectionString = dbConfig.ConnectionString; } public async Task<Transaction> MakeExpenseAsync(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_MakeExpense"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet", transaction.SourceWalletId); command.Parameters.AddWithValue("@_amount", transaction.Amount); command.Parameters.AddWithValue("@_id_category", transaction.CategoryId); command.Parameters.AddWithValue("@_description", transaction.Description); SqlParameter output = new SqlParameter { ParameterName = "@_success", SqlDbType = SqlDbType.Int }; output.Direction = ParameterDirection.Output; command.Parameters.Add(output); await command.ExecuteNonQueryAsync(); int successStatus = (int)command.Parameters["@_success"].Value; } return transaction; } public async Task<Transaction> MakeIncomeAsync(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_MakeIncome"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet", transaction.TargetWalletId); command.Parameters.AddWithValue("@_amount", transaction.Amount); command.Parameters.AddWithValue("@_id_category", transaction.CategoryId); command.Parameters.AddWithValue("@_description", transaction.Description); await command.ExecuteNonQueryAsync(); } return transaction; } public async Task<Transaction> MakeTransferAsync(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_MakeTransfer"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet_source", transaction.SourceWalletId); command.Parameters.AddWithValue("@_id_wallet_target", transaction.TargetWalletId); command.Parameters.AddWithValue("@_amount", transaction.Amount); command.Parameters.AddWithValue("@_description", transaction.Description); SqlParameter output = new SqlParameter { ParameterName = "@_success", SqlDbType = SqlDbType.Int }; output.Direction = ParameterDirection.Output; command.Parameters.Add(output); await command.ExecuteNonQueryAsync(); int successStatus = (int)command.Parameters["@_success"].Value; } return transaction; } public async Task<Transaction> UpdateAsync(int id, Transaction transaction) { using (SqlConnection con = new SqlConnection(connectionString)) { string sqlExpression = $"EXEC PR_Actions_Update {id}, '{transaction.CategoryId}', '{transaction.Description}'"; SqlCommand command = new SqlCommand(sqlExpression, con); if (con.State != ConnectionState.Open) { con.Open(); } await command.ExecuteNonQueryAsync(); } return transaction; } public async Task<Transaction> GetAsync(int walletId, int transactionId) { var transaction = new Transaction(); using (var conn = new SqlConnection(connectionString)) { var cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = $"EXEC PR_ActionsWallets_Read {walletId}, {transactionId}"; if (conn.State != ConnectionState.Open) { conn.Open(); } using (var dr = await cmd.ExecuteReaderAsync()) { while (dr.Read()) { int sourceId = dr.IsDBNull("id_wallet_source") ? 0 : dr.GetInt32("id_wallet_source"); string sourceDescription = dr.IsDBNull("wallet_src_desc") ? "" : dr.GetString("wallet_src_desc"); int targetId = dr.IsDBNull("id_wallet_target") ? 0 : dr.GetInt32("id_wallet_target"); string targetDescription = dr.IsDBNull("wallet_trg_desc") ? "" : dr.GetString("wallet_trg_desc"); int categoryId = dr.IsDBNull("id_category") ? 0 : dr.GetInt32("id_category"); string categoryDescription = dr.IsDBNull("category_desc") ? "" : dr.GetString("category_desc"); transaction = new Transaction { Id = dr.GetInt32("id"), SourceWallet = sourceDescription, SourceWalletId = sourceId, TargetWallet = targetDescription, TargetWalletId = targetId, Category = categoryDescription, CategoryId = categoryId, Amount = dr.GetDecimal("amount"), TimeStamp = dr.GetDateTime("timestamp"), State = dr.GetBoolean("success"), Description = dr.GetString("description"), TransactionType = (TransactionType)dr.GetInt32("type"), BalanceBefore = dr.GetDecimal("balance_prev"), BalanceAfter = dr.GetDecimal("balance") }; } } } return transaction; } public async Task<Transaction> SetInitialBalanceAsync(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_SetInitialBalance"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet", transaction.SourceWalletId); command.Parameters.AddWithValue("@_initial_balance", transaction.Amount); await command.ExecuteNonQueryAsync(); } return transaction; } public async Task<IEnumerable<Category>> GetExpenseCategoriesAsync() { string sqlProcedure = "PR_Categories_Read_Expenses"; List<Category> table = new List<Category>(); using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(sqlProcedure, con) { CommandType = CommandType.StoredProcedure }; SqlDataReader reader = await cmd.ExecuteReaderAsync(); if (reader.HasRows) { while (reader.Read()) { Category category = new Category { Id = reader.GetInt32("id"), Description = reader.GetString("description"), Amount = 0, Type = true }; table.Add(category); } } reader.Close(); } return table; } public async Task<IEnumerable<Category>> GetIncomeCategoriesAsync() { string sqlProcedure = "PR_Categories_Read_Incomes"; List<Category> table = new List<Category>(); using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(sqlProcedure, con) { CommandType = CommandType.StoredProcedure }; SqlDataReader reader = await cmd.ExecuteReaderAsync(); if (reader.HasRows) { while (reader.Read()) { Category category = new Category { Id = reader.GetInt32("id"), Description = reader.GetString("description"), Amount = reader.GetDecimal("total") }; table.Add(category); } } reader.Close(); } return table; } public Transaction MakeExpense(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_MakeExpense"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet", transaction.SourceWalletId); command.Parameters.AddWithValue("@_amount", transaction.Amount); command.Parameters.AddWithValue("@_id_category", transaction.CategoryId); command.Parameters.AddWithValue("@_description", transaction.Description); SqlParameter output = new SqlParameter { ParameterName = "@_success", SqlDbType = SqlDbType.Int }; output.Direction = ParameterDirection.Output; command.Parameters.Add(output); command.ExecuteNonQuery(); int successStatus = (int)command.Parameters["@_success"].Value; } return transaction; } public Transaction MakeIncome(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_MakeIncome"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet", transaction.TargetWalletId); command.Parameters.AddWithValue("@_amount", transaction.Amount); command.Parameters.AddWithValue("@_id_category", transaction.CategoryId); command.Parameters.AddWithValue("@_description", transaction.Description); command.ExecuteNonQuery(); } return transaction; } public Transaction MakeTransfer(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_MakeTransfer"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet_source", transaction.SourceWalletId); command.Parameters.AddWithValue("@_id_wallet_target", transaction.TargetWalletId); command.Parameters.AddWithValue("@_amount", transaction.Amount); command.Parameters.AddWithValue("@_description", transaction.Description); SqlParameter output = new SqlParameter { ParameterName = "@_success", SqlDbType = SqlDbType.Int }; output.Direction = ParameterDirection.Output; command.Parameters.Add(output); command.ExecuteNonQuery(); int successStatus = (int)command.Parameters["@_success"].Value; } return transaction; } public Transaction Update(int id, Transaction transaction) { using (SqlConnection con = new SqlConnection(connectionString)) { string sqlExpression = $"EXEC PR_Actions_Update {id}, '{transaction.CategoryId}', '{transaction.Description}'"; SqlCommand command = new SqlCommand(sqlExpression, con); if (con.State != ConnectionState.Open) { con.Open(); } command.ExecuteNonQuery(); } return transaction; } public Transaction Get(int walletId, int transactionId) { var transaction = new Transaction(); using (var conn = new SqlConnection(connectionString)) { var cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = $"EXEC PR_ActionsWallets_Read {walletId}, {transactionId}"; if (conn.State != ConnectionState.Open) { conn.Open(); } using (var dr = cmd.ExecuteReader()) { while (dr.Read()) { int sourceId = dr.IsDBNull("id_wallet_source") ? 0 : dr.GetInt32("id_wallet_source"); string sourceDescription = dr.IsDBNull("wallet_src_desc") ? "" : dr.GetString("wallet_src_desc"); int targetId = dr.IsDBNull("id_wallet_target") ? 0 : dr.GetInt32("id_wallet_target"); string targetDescription = dr.IsDBNull("wallet_trg_desc") ? "" : dr.GetString("wallet_trg_desc"); int categoryId = dr.IsDBNull("id_category") ? 0 : dr.GetInt32("id_category"); string categoryDescription = dr.IsDBNull("category_desc") ? "" : dr.GetString("category_desc"); transaction = new Transaction { Id = dr.GetInt32("id"), SourceWallet = sourceDescription, SourceWalletId = sourceId, TargetWallet = targetDescription, TargetWalletId = targetId, Category = categoryDescription, CategoryId = categoryId, Amount = dr.GetDecimal("amount"), TimeStamp = dr.GetDateTime("timestamp"), State = dr.GetBoolean("success"), Description = dr.GetString("description"), TransactionType = (TransactionType)dr.GetInt32("type"), BalanceBefore = dr.GetDecimal("balance_prev"), BalanceAfter = dr.GetDecimal("balance") }; } } } return transaction; } public Transaction SetInitialBalance(Transaction transaction) { string sqlExpression = "PR_Wallets_Update_SetInitialBalance"; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand command = new SqlCommand(sqlExpression, con) { CommandType = CommandType.StoredProcedure }; command.Parameters.AddWithValue("@_id_wallet", transaction.SourceWalletId); command.Parameters.AddWithValue("@_initial_balance", transaction.Amount); command.ExecuteNonQuery(); } return transaction; } public IEnumerable<Category> GetExpenseCategories() { string sqlProcedure = "PR_Categories_Read_Expenses"; List<Category> table = new List<Category>(); using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(sqlProcedure, con) { CommandType = CommandType.StoredProcedure }; SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Category category = new Category { Id = reader.GetInt32("id"), Description = reader.GetString("description"), Amount = 0, Type = true }; table.Add(category); } } reader.Close(); } return table; } public IEnumerable<Category> GetIncomeCategories() { string sqlProcedure = "PR_Categories_Read_Incomes"; List<Category> table = new List<Category>(); using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); SqlCommand cmd = new SqlCommand(sqlProcedure, con) { CommandType = CommandType.StoredProcedure }; SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Category category = new Category { Id = reader.GetInt32("id"), Description = reader.GetString("description"), Amount = reader.GetDecimal("total") }; table.Add(category); } } reader.Close(); } return table; } } }
using System.Collections; using System.Web.UI; using System.Web.UI.WebControls; namespace DevExpress.Web.Demos { public static class GSP { public static IEnumerable GetData() { using (AccessDataSource dataSource = new AccessDataSource("~/App_Data/gsp.mdb", "SELECT Year, Region, GSP FROM GSP")) return dataSource.Select(new DataSourceSelectArguments()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using OpenQA.Selenium; namespace WebAutomationFramework.Pages { class HoldLuggagePage { private IWebDriver Driver { get; set; } public HoldLuggagePage(IWebDriver driver) { Driver = driver; } public void AddHoldLuggageClick() { //Wait.WaitForElement(Driver, By.CssSelector("input[ng-class*='HasReachedMaximumBaggageAllowance']")); //var addHoldLuggageClick = Driver.FindElement(By.CssSelector("input[ng-class*='HasReachedMaximumBaggageAllowance']")); Wait.WaitForElement(Driver, By.CssSelector("input[ng-click*='bagOption.Bag']:last-child")); Console.WriteLine("On Hold Luggage Page"); var addHoldLuggageClick = Driver.FindElement(By.CssSelector("input[ng-click*='bagOption.Bag']:last-child")); addHoldLuggageClick.Click(); } public void HoldLuggageSkipButtonClick() { //Wait.WaitForElement(Driver, By.ClassName("class[*=skip-link]")); var holdLuggageSkipButtonClick = Driver.FindElement(By.ClassName("class[*=skip-link]")); holdLuggageSkipButtonClick.Click(); } public void HoldLuggageInfoButtonClick() { //Wait.WaitForElement(Driver, By.CssSelector("a[ng-click*='DoInfoIconClick']")); //var holdLuggageInfoButtonClick = Driver.FindElement(By.CssSelector("a[ng-click*='DoInfoIconClick']")); Wait.WaitForElement(Driver, By.ClassName("info-icon")); var holdLuggageInfoButtonClick = Driver.FindElement(By.ClassName("info-icon")); holdLuggageInfoButtonClick.Click(); } public void HoldLuggageInfoCloseDraw() { Wait.WaitForElement(Driver, By.Id("close-drawer-link")); var holdLuggageInfoCloseDraw = Driver.FindElement(By.Id("close-drawer-link")); holdLuggageInfoCloseDraw.Click(); } public void ContinueButtonClick() { Wait.WaitForElement(Driver, By.CssSelector("button[ng-if*='ShowContinueButton']")); var continueButtonClick = Driver.FindElement(By.CssSelector("button[ng-if*='ShowContinueButton']")); continueButtonClick.Click(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Video; public class Intro : MonoBehaviour { public Animator animatorScene; private int SceneIndex; private bool videoEnded = false; private void Start() { GameObject video = GameObject.FindGameObjectWithTag("VideoObject"); if (video != null) video.GetComponent<VideoPlayer>().loopPointReached += CheckOver; } void Update() { if (Input.GetKey(KeyCode.KeypadEnter) || Input.GetKey("enter") || Input.GetKey(KeyCode.Space) || videoEnded) { FadeLevel(SceneManager.GetActiveScene().buildIndex + 1); } if (Fade.faded) { Fade.faded = false; SceneManager.LoadScene(SceneIndex); } } public void FadeLevel(int SceneToTransition) { SceneIndex = SceneToTransition; animatorScene.SetTrigger("FadeOut"); } void CheckOver(VideoPlayer vp) { videoEnded = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TiendasServicios.Api.CarritoCompra.Aplicacion { public class CarritoDetalleDto { public Guid? LibrooId { get; set; } public string TituloLibro { get; set; } public string AutorLibro { get; set; } public DateTime? FechaPublicacion { get; set; } } }
using System.Collections.Generic; using NHibernate; namespace Profiling2.Domain.Contracts.Queries.Stats { public interface IPersonStatisticsQuery { IList<object[]> GetCreatedProfilesCountByMonth(); IList<object[]> GetLiveCreatedProfilesCount(ISession session); /// <summary> /// Get count of persons grouped by organization short name and profile status name. Organization /// comes from most recent career. WARNING: doesn't include person profiles which have NO careers. /// </summary> /// <returns></returns> IList<object[]> GetProfileStatusCountsByOrganization(); /// <summary> /// Get count of persons with no career grouped by profile status name. Combined with person status counts /// by organization, this gives a full picture of persons by status and organization. /// </summary> /// <returns></returns> IList<object[]> GetProfileStatusCountsNoOrganization(); } }
using System; using MessagePack; using MessagePack.Resolvers; namespace HiLoSocket.CommandFormatter.Implements { internal sealed class MessagePackCommandFormatter<TCommandModel> : ICommandFormatter<TCommandModel> where TCommandModel : class { /// <inheritdoc /> /// <summary> /// Deserializes the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> /// <returns> /// TCommandModel. /// </returns> /// <exception cref="T:System.ArgumentNullException">bytes - 輸入參數沒東西可以反序列化喔。</exception> /// <exception cref="T:System.ArgumentException">資料長度不能為零阿。 - bytes</exception> public TCommandModel Deserialize( byte[ ] bytes ) { CheckIfCanBeDeserialized( bytes ); return MessagePackSerializer.Deserialize<TCommandModel>( bytes, ContractlessStandardResolver.Instance ); } /// <inheritdoc /> /// <summary> /// Serializes the specified command model. /// </summary> /// <param name="commandModel">The command model.</param> /// <returns> /// Byte Array. /// </returns> /// <exception cref="T:System.ArgumentNullException">commandModel - 輸入參數沒東西可以序列化喔。</exception> public byte[ ] Serialize( TCommandModel commandModel ) { CheckIfCanBeSerialized( commandModel ); var mPackObject = MessagePackSerializer.Serialize( commandModel, ContractlessStandardResolver.Instance ); return mPackObject; } private static void CheckIfCanBeDeserialized( byte[ ] bytes ) { if ( bytes == null ) throw new ArgumentNullException( nameof( bytes ), $"輸入參數沒東西可以反序列化喔,類別名稱 : {nameof( MessagePackCommandFormatter<TCommandModel> )}。" ); if ( bytes.Length == 0 ) throw new ArgumentException( $"資料長度不能為零阿,類別名稱 : {nameof( MessagePackCommandFormatter<TCommandModel> )}。", nameof( bytes ) ); } private static void CheckIfCanBeSerialized( TCommandModel commandModel ) { if ( commandModel == null ) throw new ArgumentNullException( nameof( commandModel ), $"輸入參數沒東西可以序列化喔,類別名稱 : {nameof( MessagePackCommandFormatter<TCommandModel> )}。" ); } } }
namespace ChallengeTechAndSolve.DataAccess { using ChallengeTechAndSolve.DataAccess.Contracts; using ChallengeTechAndSolve.DataAccess.Contracts.Entities; using ChallengeTechAndSolve.DataAccess.EntityConfig; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; public class ChallengeTechAndSolveDBContext : DbContext, IChallengeTechAndSolveDBContext { public DbSet<TraceabilityEntity> TraceabilityEntities { get; set; } public ChallengeTechAndSolveDBContext(DbContextOptions options) : base(options) { } public ChallengeTechAndSolveDBContext() { } protected override void OnModelCreating(ModelBuilder modelBuilder) { TraceabilityEntityConfig.SetEntityBuilder(modelBuilder.Entity<TraceabilityEntity>()); base.OnModelCreating(modelBuilder); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1 { /// <summary> /// PayServerInfo 的摘要说明 /// </summary> public class RequestPayTradeNo : IHttpHandler { public class CRequestPayTradeNo { public int code = 0; public string msg = ""; public string TradeNo = ""; } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; CRequestPayTradeNo newPayServerInfoCellMgr = new CRequestPayTradeNo(); newPayServerInfoCellMgr.TradeNo = DateTime.Now.Ticks.ToString(); context.Response.Write(LitJson.JsonMapper.ToJson(newPayServerInfoCellMgr)); } public bool IsReusable { get { return false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParticleChild : MonoBehaviour { public float time; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void PlayParticle() { if(time != 0) { Invoke("StopParticle", time); } } public void StopParticle() { transform.SetParent(ParticleManager.Instance.unusedParticleObj.transform); gameObject.SetActive(false); } }
using System; using System.Xml; using System.Reflection; using System.Windows.Forms; namespace IRAP.Client.Actions { public class UDFActions { public static void DoActions(string actionParams, ExtendEventHandler extendAction) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(actionParams); foreach (XmlNode node in xmlDoc.SelectNodes("ROOT/Action")) { string factoryName = node.Attributes["Action"].Value.ToString(); if (factoryName != "") { IUDFActionFactory factory = (IUDFActionFactory)Assembly.Load("IRAP.Client.Actions").CreateInstance( string.Format( "IRAP.Client.Actions.{0}Factory", factoryName)); if (factory != null) { IUDFAction action = factory.CreateAction(node, extendAction); try { action.DoAction(); } catch (Exception error) { throw error; } } } } } public static void DoActions( XmlNode xmlNode, ExtendEventHandler extendAction) { foreach (XmlNode node in xmlNode.SelectNodes("ROOT/Action")) { string factoryName = node.Attributes["Action"].Value.ToString(); if (factoryName != "") { IUDFActionFactory factory = (IUDFActionFactory)Assembly.Load("IRAP.Client.Actions").CreateInstance( string.Format( "IRAP.Client.Actions.{0}Factory", factoryName)); if (factory != null) { IUDFAction action = factory.CreateAction(node, extendAction); try { action.DoAction(); } catch (Exception error) { throw error; } } } } } } }