text
stringlengths
13
6.01M
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.Threading.Tasks; using System.Web.Http; using System.Web.Http.ModelBinding; using System.Web.Http.OData; using System.Web.Http.OData.Routing; using AngularTablesDataManager.DataLayer; namespace AngularTablesDataManager.Controller { public class ZipsController : ODataController { private Context db = new Context(); // GET: odata/Zips [EnableQuery] public IQueryable<Zip> GetZips() { return db.Zips; } // GET: odata/Zips(5) [EnableQuery] public SingleResult<Zip> GetZip([FromODataUri] Guid key) { return SingleResult.Create(db.Zips.Where(zip => zip.Id == key)); } // PUT: odata/Zips(5) public async Task<IHttpActionResult> Put([FromODataUri] Guid key, Delta<Zip> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Zip zip = await db.Zips.FindAsync(key); if (zip == null) { return NotFound(); } patch.Put(zip); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ZipExists(key)) { return NotFound(); } else { throw; } } return Updated(zip); } // POST: odata/Zips public async Task<IHttpActionResult> Post(Zip zip) { if (!ModelState.IsValid) { return BadRequest(ModelState); } zip.Id = Guid.NewGuid(); db.Zips.Add(zip); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (ZipExists(zip.Id)) { return Conflict(); } else { throw; } } return Created(zip); } // PATCH: odata/Zips(5) [AcceptVerbs("PATCH", "MERGE")] public async Task<IHttpActionResult> Patch([FromODataUri] Guid key, Delta<Zip> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Zip zip = await db.Zips.FindAsync(key); if (zip == null) { return NotFound(); } patch.Patch(zip); try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ZipExists(key)) { return NotFound(); } else { throw; } } return Updated(zip); } // DELETE: odata/Zips(5) public async Task<IHttpActionResult> Delete([FromODataUri] Guid key) { Zip zip = await db.Zips.FindAsync(key); if (zip == null) { return NotFound(); } db.Zips.Remove(zip); await db.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool ZipExists(Guid key) { return db.Zips.Count(e => e.Id == key) > 0; } } }
using BenefitDeduction.EmployeesSalary; using System.Collections.Generic; namespace BenefitDeduction.EmployeeBenefitDeduction.Employees.Calculators { public interface ICalculateDeductionDetailRespository { IBenefitDeductionDetail CalculateDeductionDetail(ISalary salary, List<IBenefitDeductionItem> benefitDeductionItems); } }
namespace LikDemo.Models { public class Creditor { public RelationshipIdentification Data { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Voluntariat.Services { public interface ITaskScheduler { void RunBackgoundTasks(); } public class TaskScheduler : ITaskScheduler { private readonly IVolunteerService _volunteerService; private readonly TimeSpan NoonTime = new TimeSpan(12, 0, 0); private readonly List<IScheduledTask> tasks = new List<IScheduledTask>(); private readonly List<DayOfWeek> workDays; public TaskScheduler(IVolunteerService volunteerService) { _volunteerService = volunteerService; workDays = new List<DayOfWeek> { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }; } public void RunBackgoundTasks() { DailyTask(); } private void DailyTask() { var dailyTask = AddTask(workDays, async () => { _volunteerService.DeleteUnaffiliatedVolunteers(); _volunteerService.NotifyUnaffiliatedVolunteers(); }, NoonTime); dailyTask.Start(); } private IScheduledTask AddTask(List<DayOfWeek> workDays, Action action, TimeSpan runTime) { if (workDays.Any()) { var taskConfig = new ScheduledTaskConfiguration { DaysOfWeek = workDays, RunTime = runTime }; var newTask = new ScheduledTask { Configuration = taskConfig, Action = action }; tasks.Add(newTask); return newTask; } return null; } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Collections.ObjectModel; using System.Windows.Data; using System.Globalization; using GeoSearch.CSWQueryServiceReference; using System.Collections.Generic; namespace GeoSearch { public class Converters { public static string getQoSBarImagePathString(double quality) { string path = "/GeoSearch;component/images/QoS/0bars.png"; if (quality >= 0 && quality < 6) { int next = (int)quality; path = "/GeoSearch;component/images/QoS/" + next + "bars.png"; } return path; } } public class OpenLayersButtonVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Visible; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if ((!type.ToLower().Equals(ConstantCollection.ServiceType_WFS)) && (!type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_AnalysisAndVisualization)) && (!type.Equals(ConstantCollection.ServiceType_WMS))) v = Visibility.Collapsed; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class BingMapsButtonVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Visible; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if ((!type.ToLower().Equals(ConstantCollection.ServiceType_WFS)) && (!type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_AnalysisAndVisualization)) && (!type.Equals(ConstantCollection.ServiceType_WMS))) v = Visibility.Collapsed; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class OtherVisualizationViewerButtonVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Visible; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if ((!type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_AnalysisAndVisualization)) && (!type.Equals(ConstantCollection.ServiceType_WMS))) v = Visibility.Collapsed; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SWPViewerButtonVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Visible; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if ((!type.Equals(ConstantCollection.ServiceType_WFS)) && (!type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_AnalysisAndVisualization)) && (!type.Equals(ConstantCollection.ServiceType_WMS))) v = Visibility.Collapsed; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class GetDataButtonVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if ((type.Equals(ConstantCollection.resourceTypeValue_GOS_Datasets_DownloadableData))) v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class ResourceTypeIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string source = "/GeoSearch;component/images/resourceTypes/dataset1.png"; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; //services if (type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_AnalysisAndVisualization) || type.Equals(ConstantCollection.resourceTypeValue_CSR_DataServices_AnalysisAndVisualization) || type.Equals(ConstantCollection.resourceTypeValue_GOS_DataServices_AnalysisAndVisualization)) source = "/GeoSearch;component/images/resourceTypes/network_Service.png"; else if (type.Equals(ConstantCollection.ServiceType_WMS)) source = "/GeoSearch;component/images/resourceTypes/WMS.png"; else if (type.Equals(ConstantCollection.ServiceType_WFS)) source = "/GeoSearch;component/images/resourceTypes/WFS.png"; else if (type.Equals(ConstantCollection.ServiceType_WCS)) source = "/GeoSearch;component/images/resourceTypes/WCS.png"; else if (type.Equals(ConstantCollection.ServiceType_WPS)) source = "/GeoSearch;component/images/resourceTypes/network_Service.png"; else if (type.Equals(ConstantCollection.ServiceType_CSW)) source = "/GeoSearch;component/images/resourceTypes/network_Service.png"; else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_AlertsRSSAndInformationFeeds) || type.Equals(ConstantCollection.resourceTypeValue_CSR_DataServices_AlertsRSSAndInformationFeeds) || type.Equals(ConstantCollection.resourceTypeValue_GOS_DataServices_AlertsRSSAndInformationFeeds)) source = "/GeoSearch;component/images/resourceTypes/RSS.png"; else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_DataServices_CatalogRegistryOrMetadataCollection) || type.Equals(ConstantCollection.resourceTypeValue_CSR_DataServices_CatalogRegistryOrMetadataCollection) || type.Equals(ConstantCollection.resourceTypeValue_GOS_DataServices_CatalogRegistryOrMetadataCollection)) source = "/GeoSearch;component/images/resourceTypes/CatalogServer.png"; //datasets else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_Datasets) || type.Equals(ConstantCollection.resourceTypeValue_CLH_Datasets_nonGeographic) || type.Equals(ConstantCollection.resourceTypeValue_CSR_Datasets) || type.Equals(ConstantCollection.resourceTypeValue_GOS_Datasets_OfflineData)) source = "/GeoSearch;component/images/resourceTypes/dataset1.png"; else if (type.Equals(ConstantCollection.resourceTypeValue_GOS_Datasets_LiveData)) source = "/GeoSearch;component/images/resourceTypes/globe.png"; else if (type.Equals(ConstantCollection.resourceTypeValue_GOS_Datasets_DownloadableData)) source = "/GeoSearch;component/images/resourceTypes/downloadableData.png"; else if (type.Equals(ConstantCollection.resourceTypeValue_GOS_Datasets_StaticMapImage)) source = "/GeoSearch;component/images/resourceTypes/dataset.png"; else if (type.Equals(ConstantCollection.resourceTypeValue_GOS_Datasets_MapFiles)) source = "/GeoSearch;component/images/resourceTypes/map.png"; //Initiatives else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_Initiatives) || type.Equals(ConstantCollection.resourceTypeValue_CSR_Initiatives) || type.Equals(ConstantCollection.resourceTypeValue_GOS_Initiatives)) source = "/GeoSearch;component/images/resourceTypes/Initiatives.png"; //MonitoringAndObservationSystems else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_MonitoringAndObservationSystems) || type.Equals(ConstantCollection.resourceTypeValue_GOS_MonitoringAndObservationSystems) || type.Equals(ConstantCollection.resourceTypeValue_CSR_MonitoringAndObservationSystems)) source = "/GeoSearch;component/images/resourceTypes/exec.png"; //ComputationalModel else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_ComputationalModel) || type.Equals(ConstantCollection.resourceTypeValue_GOS_ComputationalModel) || type.Equals(ConstantCollection.resourceTypeValue_CSR_ComputationalModel)) source = "/GeoSearch;component/images/resourceTypes/models.png"; //WebsitesAndDocuments else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_WebsitesAndDocuments) || type.Equals(ConstantCollection.resourceTypeValue_GOS_WebsitesAndDocuments) || type.Equals(ConstantCollection.resourceTypeValue_CSR_WebsitesAndDocuments)) source = "/GeoSearch;component/images/resourceTypes/WebsitesAndDocuments.png"; //SoftwareAndApplications else if (type.Equals(ConstantCollection.resourceTypeValue_CLH_SoftwareAndApplications) || type.Equals(ConstantCollection.resourceTypeValue_GOS_SoftwareAndApplications) || type.Equals(ConstantCollection.resourceTypeValue_CSR_SoftwareAndApplications)) source = "/GeoSearch;component/images/resourceTypes/applications.png"; else if (type.ToLower().Equals("directories")) source = "/GeoSearch;component/images/resourceTypes/Folder.png"; else if (type.ToLower().Equals("pdf")) source = "/GeoSearch;component/images/resourceTypes/pdf.png"; else if (type.ToLower().Equals("photo")) source = "/GeoSearch;component/images/resourceTypes/photo.png"; else if (type.ToLower().Equals("layer")) source = "/GeoSearch;component/images/resourceTypes/layer.png"; else if (type.ToLower().Equals("photo")) source = "/GeoSearch;component/images/resourceTypes/photo.png"; } return source; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class GeneralResourceTypeIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string source = null; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if (type.Equals(ConstantCollection.resourceType_PickID_AllServices)) source = "/GeoSearch;component/images/resourceTypes/network_Service.png"; else if (type.Equals(ConstantCollection.resourceType_DataServices_AnalysisAndVisualization)) source = "/GeoSearch;component/images/resourceTypes/network_Service.png"; else if (type.Equals(ConstantCollection.ServiceType_WMS)) source = "/GeoSearch;component/images/resourceTypes/WMS.png"; else if (type.Equals(ConstantCollection.ServiceType_WCS)) source = "/GeoSearch;component/images/resourceTypes/WCS.png"; else if (type.Equals(ConstantCollection.ServiceType_WFS)) source = "/GeoSearch;component/images/resourceTypes/WFS.png"; else if (type.Equals(ConstantCollection.ServiceType_WPS)) source = "/GeoSearch;component/images/resourceTypes/network_Service.png"; else if (type.Equals(ConstantCollection.resourceType_DataServices_AlertsRSSAndInformationFeeds)) source = "/GeoSearch;component/images/resourceTypes/RSS.png"; else if (type.Equals(ConstantCollection.resourceType_DataServices_CatalogRegistryOrMetadataCollection)) source = "/GeoSearch;component/images/resourceTypes/CatalogServer.png"; else if (type.Equals(ConstantCollection.resourceType_Datasets)) source = "/GeoSearch;component/images/resourceTypes/globe.png"; else if (type.Equals(ConstantCollection.resourceType_MonitoringAndObservationSystems)) source = "/GeoSearch;component/images/resourceTypes/exec.png"; else if (type.Equals(ConstantCollection.resourceType_ComputationalModel)) source = "/GeoSearch;component/images/resourceTypes/models.png"; else if (type.Equals(ConstantCollection.resourceType_Initiatives)) source = "/GeoSearch;component/images/resourceTypes/Initiatives.png"; else if (type.Equals(ConstantCollection.resourceType_WebsitesAndDocuments)) source = "/GeoSearch;component/images/resourceTypes/WebsitesAndDocuments.png"; else if (type.Equals(ConstantCollection.resourceType_SoftwareAndApplications)) source = "/GeoSearch;component/images/resourceTypes/applications.png"; } return source; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class RelevanceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double relevance = (double)value; string result = relevance * 100 + "%"; return result; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class QoSIconTypeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string source = "/GeoSearch;component/images/QoS/5bars.png"; if (value != null && value.GetType() == typeof(double)) { double quality = (double)value; source = Converters.getQoSBarImagePathString(quality); } return source; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class QoSIconVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; if (value != null && value.GetType() == typeof(double)) { double quality = (double)value; if (quality >= 0) v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class ProviderIconVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; string provider = value as string; provider = provider.ToLower(); if (provider != null && !provider.Trim().Equals("")) { if (provider.Contains("usgs") || provider.Contains("u.s. geological survey")) v = Visibility.Visible; else if (provider.Contains("nasa") || provider.Contains("national aeronautics and space administration")) v = Visibility.Visible; else if (provider.Contains("jpl") || provider.Contains("jet propulsion laboratory")) v = Visibility.Visible; else if (provider.ToUpper().Contains("GCMD") || provider.ToLower().Contains("global change master directory")) v = Visibility.Visible; else if (provider.Contains("university of montana")) v = Visibility.Visible; else if (provider.Contains("noaa") || provider.Contains("national oceanic and atmospheric administration")) v = Visibility.Visible; else if (provider.Contains("esri") || provider.Contains("economic and social research institute")) v = Visibility.Visible; //else // v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class ProviderIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string source = "/GeoSearch;component/images/Organizer/NASA.png"; string provider = value as string; string OrganizerName = "NASA"; provider = provider.ToLower(); if (provider.Contains("usgs") || provider.Contains("u.s. geological survey")) OrganizerName = "USGS"; else if (provider.Contains("nasa") || provider.Contains("national aeronautics and space administration")) OrganizerName = "NASA"; else if (provider.Contains("jpl") || provider.Contains("jet propulsion laboratory")) OrganizerName = "NASA"; else if (provider.ToUpper().Contains("GCMD") || provider.ToLower().Contains("global change master directory")) OrganizerName = "NASA"; else if (provider.Contains("university of montana")) OrganizerName = "MU"; else if (provider.Contains("noaa") || provider.Contains("national oceanic and atmospheric administration")) OrganizerName = "NOAA"; else if (provider.Contains("esri") || provider.Contains("economic and social research institute")) OrganizerName = "ESRI"; source = "/GeoSearch;component/images/Organizer/" + OrganizerName + ".png"; return source; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class KeywordsShowingConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string source = ""; //ObservableCollection<string> DescriptiveKeywords = value as ObservableCollection<string>; StringList DescriptiveKeywords = value as StringList; if (DescriptiveKeywords != null && DescriptiveKeywords.Count > 0) { foreach (string keyword in DescriptiveKeywords) { { source += (keyword + "; "); } } } else source = "none"; return source; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class GetDataButtonTextContentConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string text = "Get Data"; string accessURL = value as string; int index0 = accessURL.LastIndexOf("/"); if (index0 > 0) { string header = accessURL.Substring(0, index0); if (header.ToLower().Equals("http:/") || header.ToLower().Equals("ftp:/")) return text; accessURL = accessURL.Substring(index0 + 1); int index = accessURL.LastIndexOf("."); if (index > 0) { string extention = accessURL.Substring(index + 1).ToLower(); if (extention.IndexOf("?") < 0) { if ((!extention.Equals("html")) && (!extention.Equals("htm")) && (!extention.Equals("asp")) && (!extention.Equals("aspx")) && (!extention.Equals("jsp")) && (!extention.Equals("php"))) text = "Download Data"; } } } return text; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class GESSDataCOREIconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //Visibility v = Visibility.Visible; bool provider = (bool)value; if (provider == true) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } //------------------------------------For Pivot Viewer--------------------------------- public class ProviderNameConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string generalProvider = "Others"; string provider = value as string; provider = provider.ToLower(); if (provider != null && !provider.Trim().Equals("")) { if (provider.Contains("usgs") || provider.Contains("u.s. geological survey")) generalProvider = "USGS"; else if (provider.Contains("nasa") || provider.Contains("national aeronautics and space administration")) generalProvider = "NASA"; else if (provider.Contains("jpl") || provider.Contains("jet propulsion laboratory")) generalProvider = "NASA"; else if (provider.ToUpper().Contains("GCMD") || provider.ToLower().Contains("global change master directory")) generalProvider = "NASA"; else if (provider.Contains("university")) generalProvider = "Universities"; else if (provider.Contains("noaa") || provider.Contains("national oceanic and atmospheric administration")) generalProvider = "NOAA"; else if (provider.Contains("esri") || provider.Contains("economic and social research institute")) generalProvider = "ESRI"; else if (provider.Contains("unknown")) generalProvider = "Unknown"; else generalProvider = "Others"; } return generalProvider; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class GeoExtensionConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string extension = "Global"; BBox bbox = value as BBox; if (bbox != null) extension = "Global"; else extension = "Local"; return extension; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class ServerLocationDescriptionConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string locationDescription = null; if (value != null && !((string)value).Trim().Equals("")) { string[] location = ((string)value).Split(','); locationDescription = "Unknown"; try { double lon = double.Parse(location[0]); double lat = double.Parse(location[1]); if (lon >= 0 && lat >= 0) locationDescription = "North_East"; else if (lon >= 0 && lat <= 0) locationDescription = "South_East"; else if (lon <= 0 && lat <= 0) locationDescription = "South_West"; else if (lon <= 0 && lat >= 0) locationDescription = "North_West"; } catch (Exception e) { e.ToString(); } } return locationDescription; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class DescriptiveKeywordsStringListToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string keywords = "Keywords: "; //ObservableCollection<String> DescriptiveKeywords = value as ObservableCollection<String>; StringList DescriptiveKeywords = value as StringList; if (DescriptiveKeywords != null && DescriptiveKeywords.Count > 0) { foreach (string keyword in DescriptiveKeywords) { { keywords += (keyword + "; "); } } } else keywords = keywords+"none"; return keywords; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class DescriptiveKeywordsVisibilityOnInformationCardConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<String> DescriptiveKeywords = value as ObservableCollection<String>; StringList DescriptiveKeywords = value as StringList; if (DescriptiveKeywords != null && DescriptiveKeywords.Count>0) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class AbstractStringOnInformationCardConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string a = "Abstract: "; string abstractValue = value as string; a += abstractValue; return a; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class AbstractStringVisibilityOnInformationCardConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; string abstractValue = value as string; if (abstractValue != null && !abstractValue.Trim().Equals("") && !abstractValue.Trim().Equals("unknown")) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Health_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count> 0 && SBAs.Contains(SBAVocabularyTree.SBA_Health)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Disasters_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Disasters)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Energy_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Energy)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Climate_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Climate)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Water_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Water)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Weather_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Weather)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Ecosystems_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Ecosystems)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Agriculture_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Agriculture)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBA_Biodiversity_IconVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Visibility v = Visibility.Collapsed; //ObservableCollection<string> SBAs = (ObservableCollection<string>)value; StringList SBAs = value as StringList; if (SBAs != null && SBAs.Count > 0 && SBAs.Contains(SBAVocabularyTree.SBA_Biodiversity)) { v = Visibility.Visible; } return v; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } public class SBAVocabularyIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string source = null; if (value != null && value.GetType() == typeof(string)) { string type = (string)value; if (type.Equals(SBAVocabularyTree.SBA_Disasters)) source = "/GeoSearch;component/images/SBA/icon_disaster_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Health)) source = "/GeoSearch;component/images/SBA/icon_health_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Energy)) source = "/GeoSearch;component/images/SBA/icon_energy_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Climate)) source = "/GeoSearch;component/images/SBA/icon_climate_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Water)) source = "/GeoSearch;component/images/SBA/icon_water_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Weather)) source = "/GeoSearch;component/images/SBA/icon_weather_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Ecosystems)) source = "/GeoSearch;component/images/SBA/icon_ecosystem_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Agriculture)) source = "/GeoSearch;component/images/SBA/icon_agriculture_off.png"; else if (type.Equals(SBAVocabularyTree.SBA_Biodiversity)) source = "/GeoSearch;component/images/SBA/icon_biodiver_off.png"; else source = "/GeoSearch;component/images/SBA/subtype.png"; } return source; } // Not used. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
using System; using System.Collections.Generic; namespace Admin.ViewModels { public class ServicePageModel { public int Id {get;set;} public string Name {get;set;} public string Address {get;set;} public string Phone {get;set;} public int OrdersCount {get;set;} public int OrdersSucceedCount {get;set;} public int ReviewsCount {get;set;} public float AvarageMark {get;set;} public string About {get;set;} public IEnumerable<ReviewModel> Reviews {get;set;} } }
using System; using System.Text; using System.IO; using System.Text.RegularExpressions; namespace lab_1 { class Program { static void Main(string[] args) { string input = File.ReadAllText("../../input.txt"); string reg = File.ReadAllText("../../regex.txt"); Regex regex = new Regex(reg); var output = new StringBuilder(EscapeCsvValue("Номер") + ";" + EscapeCsvValue("Группа1") +";"+ EscapeCsvValue("Группа2") + ";"+ EscapeCsvValue("Группа3") +";"+ EscapeCsvValue("Группа4")); output.AppendLine(); int id = 1; foreach (Match m in regex.Matches(input)) { output.Append(EscapeCsvValue($"Строка {id++}") + ";"); output.AppendLine($"{EscapeCsvValue(m.Groups[1].Value.Replace("\t", "\\t"))};" + $"{EscapeCsvValue(m.Groups[2].Value.Replace("\t", "\\t"))};" + $"{EscapeCsvValue(m.Groups[3].Value.Replace("\t", "\\t"))};" + $"{EscapeCsvValue(m.Groups[4].Value.Replace("\t", "\\t"))}"); } Console.WriteLine(output); File.WriteAllText("../../output.csv", output.ToString(), Encoding.Default); } static string EscapeCsvValue(string s) => "\"" + s.Replace("\"", "\"\"") + "\""; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Common.Servicei.ViewModels.Users; using Controllers; using Demo.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using SAAS.Api.Router; using SAAS.FrameWork.Module.Api.Data; namespace SAAS.Api.Controllers.V1 { /// <summary> /// EXCEL操作 /// </summary> [ApiVersion("1.0")] [CustomRoute(ApiVersions.v1, "excel")] public class ExcelController : BaseApiController { private readonly IHostingEnvironment _environment; private readonly IDemoService _demoservice; public ExcelController(IHostingEnvironment environment) { _environment = environment; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenerateRewards : MonoBehaviour { private int planeCount; public GameObject Rewards; private GameObject grandChild; private System.Random random = new System.Random(); private bool hasCalled = false; // Start is called before the first frame update void Update() { if(!hasCalled) { grandChild = this.gameObject.transform.GetChild(0).GetChild(0).gameObject; //get the child of the child gameObject of the attached object RandomDrop(); hasCalled = true; } } private void RandomDrop() { foreach(Transform planeTransform in grandChild.transform) //iterate through each plane in the grand child { int randomNum = random.Next(0,3); //generate random integer if(randomNum == 2) //2 over 3 chance of having a Pickup Rewards on the plane { Instantiate(Rewards, planeTransform.position + Vector3.up * 0.02f, Rewards.transform.rotation); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Cdiscount.Alm.Sonar.Api.Wrapper.Core.Measures.Component.Response { public class ComponentMeasureResponse { /// <summary> /// Component /// </summary> [JsonProperty(PropertyName = "component")] public SonarComponentMeasures SonarComponentMeasures { get; set; } } }
using System.Runtime.InteropServices; using System.Windows.Forms; namespace DemoScanner.Settings { public static class asdf { public static int asdf2 = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SecurityPlusUI.Model; using SecurityPlusUI.View; namespace SecurityPlusUI.Services { public class NotificationService { public static void DisplayMessage(string message) { Console.WriteLine(message); } public static void DisplayMessage(string format, params object[] options) { Console.WriteLine(format, options); } public static void DisplayException(Exception exception) { Console.WriteLine("\t Error: {0}", exception.Message); } public static void DisplayWindows(IContext context) { var notificationWindow = new NotificationWindow(context); notificationWindow.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using RimLiqourProject.Models; using NewRimLiqourProject.Models; namespace NewRimLiqourProject.Controllers { [Authorize(Roles = "Admin")] public class ProductController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: /Product/ public ActionResult Index() { return View(db.Products.ToList()); } // GET: /Product/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Products products = db.Products.Find(id); if (products == null) { return HttpNotFound(); } return View(products); } // GET: /Product/Create public ActionResult Create() { return View(); } // POST: /Product/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Products products, HttpPostedFileBase upload) { if (ModelState.IsValid) { if (upload != null) { var fileLength = upload.ContentLength; byte[] ImageBytes = new byte[upload.ContentLength]; upload.InputStream.Read(ImageBytes, 0, fileLength); products.Image = ImageBytes; } db.Products.Add(products); db.SaveChanges(); return RedirectToAction("Index"); } return View(products); } // GET: /Product/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Products products = db.Products.Find(id); if (products == null) { return HttpNotFound(); } return View(products); } // POST: /Product/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Products products) { if (ModelState.IsValid) { db.Entry(products).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(products); } // GET: /Product/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Products products = db.Products.Find(id); if (products == null) { return HttpNotFound(); } return View(products); } // POST: /Product/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Products products = db.Products.Find(id); db.Products.Remove(products); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerController : MonoBehaviour { public float speed; public float hight; bool facingR; public KeyCode spacebar; public KeyCode one; public KeyCode two; public KeyCode L; public KeyCode R; public Transform checker; public float cheackerRadius; public Transform throwfrom; public GameObject Sword; public LayerMask Ground; private bool grounded; private Animator anim; private bool MyFunctionCalled = false; // Start is called before the first frame update void Start() { facingR = true; anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { if (Input.GetKey(spacebar) && grounded) { FindObjectOfType<AudioManager>().Play("jump"); jump(); } if (Input.GetKey(L)) { GetComponent<Rigidbody2D>().velocity = new Vector2(-speed, GetComponent<Rigidbody2D>().velocity.y); if (facingR) { turn(); facingR = false; } } if (Input.GetKey(R)) { GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y); if (!facingR) { turn(); facingR = true; } } if (Input.GetMouseButtonDown(0)) { FindObjectOfType<AudioManager>().Play("attack"); attack(); } if (Input.GetMouseButtonDown(1)) { if (FindObjectOfType<PlayerStatus>().Mana > 0) { FindObjectOfType<PlayerStatus>().Mana -= 1; Instantiate(Sword, throwfrom.position, throwfrom.rotation); anim.SetTrigger("throw"); } } if (Input.GetKey(one)) { if (MyFunctionCalled == false) { MyFunctionCalled = true; if (FindObjectOfType<PlayerStatus>().healthPotion > 0) { FindObjectOfType<AudioManager>().Play("potion"); FindObjectOfType<PlayerStatus>().healthPotion -= 1; FindObjectOfType<PlayerStatus>().health += 3; if (FindObjectOfType<PlayerStatus>().health > 6) { FindObjectOfType<PlayerStatus>().health = 6; FindObjectOfType<PlayerStatus>().lives += 1; } } Invoke("potion", 0.5f); } } if (Input.GetKey(two)) { if (MyFunctionCalled == false) { MyFunctionCalled = true; if (FindObjectOfType<PlayerStatus>().ManaPotion > 0) { FindObjectOfType<AudioManager>().Play("potion"); FindObjectOfType<PlayerStatus>().ManaPotion = FindObjectOfType<PlayerStatus>().ManaPotion - 1; FindObjectOfType<PlayerStatus>().Mana += 3; if (FindObjectOfType<PlayerStatus>().Mana > 6) { FindObjectOfType<PlayerStatus>().Mana = 6; } } Invoke("potion", 0.5f); } } anim.SetFloat("speed", Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x)); } void FixedUpdate() { grounded = Physics2D.OverlapCircle(checker.position, cheackerRadius, Ground); anim.SetBool("grounded", grounded); } void attack() { anim.SetTrigger("attack"); } void turn() { transform.localScale = new Vector3(-(transform.localScale.x), transform.localScale.y, transform.localScale.z); } void jump() { GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, hight); } void potion() { MyFunctionCalled = false; } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Project371; using Project371.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assig_2.GameClasses { class Battery : Entity { private Vector3 rotationAxis; private SphereCollider sphereCollider; public readonly float PowerValue = 50; public Battery() : base("Battery") { Model model = Game1.Instance.Content.Load<Model>("Models\\Battery"); ModelRenderer renderer = new ModelRenderer(model); renderer.material.texture = Game1.Instance.Content.Load<Texture2D>("Textures\\BatteryTex"); transform.scale = new Microsoft.Xna.Framework.Vector3(0.05f, 0.05f,0.05f); rotationAxis = new Vector3(0, 1, 0); sphereCollider = new SphereCollider(); sphereCollider.transform.scale = new Microsoft.Xna.Framework.Vector3(0.8f, 0.8f, 0.8f); // sphereCollider.EnableRender = true; AddComponent(new AudibleComponent3D("batterySound", volume: 0.25f, loop: true)); AddComponent(new AudibleComponent3D("batteryPickUp", manual: true)); AddComponent(renderer); AddComponent(sphereCollider); } override public void Update() { base.Update(); transform.RotateBy(25 * Timer.Delta, rotationAxis); } public SphereCollider GetSphereCollider() { return sphereCollider; } } }
using Newtonsoft.Json; using System; namespace Alabo.Schedules { public class BackJobParameter { /// <summary> /// 当前用户Id /// </summary> [JsonIgnore] public long UserId { get; set; } /// <summary> /// 模块Id /// </summary> [JsonIgnore] public Guid ModuleId { get; set; } /// <summary> /// 服务名称 /// </summary> public string ServiceName { get; set; } /// <summary> /// 方法 /// </summary> public string Method { get; set; } /// <summary> /// 参数 /// </summary> public object Parameter { get; set; } /// <summary> /// 是否检查上一个任务是否执行 /// </summary> [JsonIgnore] public bool CheckLastOne { get; set; } = false; } }
using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using WorkScheduleManagement.Data.Entities.Requests; using WorkScheduleManagement.Persistence; namespace WorkScheduleManagement.Application.CQRS.Commands { public static class UpdateRequestStatus { public record Command(Request Request) : IRequest<bool>; public class Handler : IRequestHandler<Command, bool> { private readonly AppDbContext _context; public Handler(AppDbContext context) { _context = context; } public async Task<bool> Handle(Command request, CancellationToken cancellationToken) { var originRequest = await _context.Requests.Include(r => r.RequestStatus).FirstOrDefaultAsync(r => request.Request.Id == r.Id); originRequest.RequestStatus = await _context.RequestStatuses.FirstOrDefaultAsync(s => s.Id == request.Request.RequestStatus.Id); await _context.SaveChangesAsync(); return true; } } } }
using System; using System.Collections.Generic; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Order; using BenchmarkDotNet.Running; using EnsureThat; namespace Benchmarks { class Program { static void Main(string[] args) { BenchmarkRunner.Run<Ensures>(); } } public static class BaseLines { public static void NullableIntHasValue(int? value) { if (!value.HasValue) throw new ArgumentNullException(nameof(value)); } public static void StringIsNotNull(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); } public static void StringIsNotNullOrWhiteSpace(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Some message 1.", nameof(value)); } public static void StringIsEqualTo(string value, string expected) { if (!string.Equals(value, expected, StringComparison.Ordinal)) throw new ArgumentException("Some message 2.", nameof(value)); } public static void StringsHasItems(List<string> strings) { if (strings.Count == 0) throw new ArgumentException("Some message 3.", nameof(strings)); } public static void IntIs(int value, int expected) { if (value != expected) throw new ArgumentOutOfRangeException(nameof(value), value, "Some message 4."); } public static void IntIsGt(int value, int limit) { if (value <= limit) throw new ArgumentOutOfRangeException(nameof(value), value, "Some message 5."); } public static void IntsHasItems(List<int> ints) { if (ints.Count == 0) throw new ArgumentException("Some message 6.", nameof(ints)); } public static void ThingIsNotNullViaThat<T>(T thing) where T : class { if (thing == null) throw new ArgumentNullException(nameof(thing)); } public static void ThingsHasItems<T>(List<T> things) where T : class { if (things.Count == 0) throw new ArgumentException("Some message 7.", nameof(things)); } } [Orderer(SummaryOrderPolicy.FastestToSlowest)] [RankColumn] [MemoryDiagnoser] [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] [CategoriesColumn] //[CategoryFilter("Things.HasItems")] public class Ensures { private const string ParamName = "test"; private static readonly int? NullableInt = 1; private readonly List<string> _strings = new List<string> { "test1", "TEST2", "Test3" }; private readonly List<int> _ints = new List<int> { 1, 2, 3 }; private readonly List<MyThing> _things = new List<MyThing> { new MyThing { MyInt = 1, MyString = "A" }, new MyThing { MyInt = 2, MyString = "B" }, new MyThing { MyInt = 3, MyString = "C" } }; [Benchmark(Baseline = true)] [BenchmarkCategory("String.IsNotNullOrWhiteSpace")] public void StringIsNotNullOrWhiteSpace() => BaseLines.StringIsNotNullOrWhiteSpace("foo"); [Benchmark] [BenchmarkCategory("String.IsNotNullOrWhiteSpace")] public void StringIsNotNullOrWhiteSpaceViaThat() => Ensure.That("foo", "test").IsNotNullOrWhiteSpace(); [Benchmark] [BenchmarkCategory("String.IsNotNullOrWhiteSpace")] public void StringIsNotNullOrWhiteSpaceViaEnforcer() => Ensure.String.IsNotNullOrWhiteSpace("foo", ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("String.IsEqualTo")] public void StringIsEqualTo() => BaseLines.StringIsEqualTo("foo", "foo"); [Benchmark] [BenchmarkCategory("String.IsEqualTo")] public void StringIsEqualToViaThat() => Ensure.That("foo", "test").IsEqualTo("foo"); [Benchmark] [BenchmarkCategory("String.IsEqualTo")] public void StringIsEqualToViaEnforcer() => Ensure.String.IsEqualTo("foo", "foo", ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Strings.HasItems")] public void StringsHasItems() => BaseLines.StringsHasItems(_strings); [Benchmark] [BenchmarkCategory("Strings.HasItems")] public void StringsHasItemsViaThat() => Ensure.That(_strings, "test").HasItems(); [Benchmark] [BenchmarkCategory("Strings.HasItems")] public void StringsHasItemsViaEnforcer() => Ensure.Collection.HasItems(_strings, ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Int.Is")] public void IntIs() => BaseLines.IntIs(42, 42); [Benchmark] [BenchmarkCategory("Int.Is")] public void IntIsViaThat() => Ensure.That(42, "test").Is(42); [Benchmark] [BenchmarkCategory("Int.Is")] public void IntIsViaEnforcer() => Ensure.Comparable.Is(42, 42, ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Int.IsGt")] public void IntIsGt() => BaseLines.IntIsGt(42, 41); [Benchmark] [BenchmarkCategory("Int.IsGt")] public void IntIsGtViaThat() => Ensure.That(42, "test").IsGt(41); [Benchmark] [BenchmarkCategory("Int.IsGt")] public void IntIsGtViaEnforcer() => Ensure.Comparable.IsGt(42, 41, ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Ints.HasItems")] public void IntsHasItems() => BaseLines.IntsHasItems(_ints); [Benchmark] [BenchmarkCategory("Ints.HasItems")] public void IntsHasItemsViaThat() => Ensure.That(_ints, "test").HasItems(); [Benchmark] [BenchmarkCategory("Ints.HasItems")] public void IntsHasItemsViaEnforcer() => Ensure.Collection.HasItems(_ints, ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Any.IsNotNull")] public void ThingIsNotNull() => BaseLines.ThingIsNotNullViaThat(_things[0]); [Benchmark] [BenchmarkCategory("Any.IsNotNull")] public void ThingIsNotNullViaThat() => Ensure.That(_things[0], "test").IsNotNull(); [Benchmark] [BenchmarkCategory("Any.IsNotNull")] public void ThingIsNotNullViaEnforcer() => Ensure.Any.IsNotNull(_things[0], ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Things.HasItems")] public void ThingsHasItems() => BaseLines.ThingsHasItems(_things); [Benchmark] [BenchmarkCategory("Things.HasItems")] public void ThingsHasItemsViaThat() => Ensure.That(_things, "test").HasItems(); [Benchmark] [BenchmarkCategory("Things.HasItems")] public void ThingsHasItemsViaEnforcer() => Ensure.Collection.HasItems(_things, ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Any.int.HasValue")] public void AnyHasValueWhenIntHasValueBaseLine() => BaseLines.NullableIntHasValue(NullableInt); [Benchmark] [BenchmarkCategory("Any.int.HasValue")] public void AnyHasValueWhenIntViaNotNull() => Ensure.Any.IsNotNull(NullableInt, ParamName); [Benchmark(Baseline = true)] [BenchmarkCategory("Any.string.HasValue")] public void AnyHasValueWhenStringBaseLine() => BaseLines.StringIsNotNull(string.Empty); private class MyThing { public string MyString { get; set; } public int MyInt { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Persons.Accessors; using Persons.DataEntity; namespace ConsoleClient { class Program { static private int mode; static private int entity; static private void Mode() { Console.WriteLine(@"Выберите хранилище данных: 1 - ОП 2 - Файл 3 - БД ADO.NET 4 - БД MyORM"); while (!Int32.TryParse(Console.ReadLine(), out mode) || !((mode > 0) && (mode < 5)) ) { Console.WriteLine("Ошибка ввода"); } } static private void Entity() { Console.WriteLine(@"Выберите сущность: 1 - Персоны 2 - Компании"); while (!Int32.TryParse(Console.ReadLine(), out entity) || !((entity > 0) && (entity < 3))) { Console.WriteLine("Ошибка ввода"); } } static private IEntityAccessor<BaseEntity> Accessor() { switch (mode) { } } static void Main(string[] args) { Mode(); Console.ReadKey(); } } }
using System; namespace VoxelSpace { /// <summary> /// Light values for a single voxel. /// </summary> public readonly struct VoxelLight { /// <summary> /// The total number of channels. See <see cref="VoxelLightChannel"/> /// </summary> public const int CHANNEL_COUNT = 7; /// <summary> /// The amount by which to decrement light during propagation. /// </summary> public const byte LIGHT_DECREMENT = MAX_LIGHT / 16; /// <summary> /// The maximum value for all channels. /// </summary> public const byte MAX_LIGHT = 255; public static readonly VoxelLight fullSun = new VoxelLight( MAX_LIGHT, MAX_LIGHT, MAX_LIGHT, MAX_LIGHT, MAX_LIGHT, MAX_LIGHT, 0, true ); /// <summary> /// A NULL value used in place of a Nullable. saves memory, lets us use refs and pointers /// </summary> public static readonly VoxelLight NULL = new VoxelLight(0, 0, 0, 0, 0, 0, 0, false); /// <summary>Sunlight from X+</summary> public readonly byte SunXp; /// <summary>Sunlight from Y+</summary> public readonly byte SunYp; /// <summary>Sunlight from Z+</summary> public readonly byte SunZp; /// <summary>Sunlight from X-</summary> public readonly byte SunXn; /// <summary>Sunlight from Y-</summary> public readonly byte SunYn; /// <summary>Sunlight from Z-</summary> public readonly byte SunZn; /// <summary>Light from point lights.</summary> public readonly byte Point; /// <summary>Is this NULL?</summary> public readonly bool IsNonNull; public VoxelLight(byte sunXp, byte sunYp, byte sunZp, byte sunXn, byte sunYn, byte sunZn, byte point, bool isNonNull) { SunXp = sunXp; SunYp = sunYp; SunZp = sunZp; SunXn = sunXn; SunYn = sunYn; SunZn = sunZn; Point = point; IsNonNull = isNonNull; } } /// <summary> /// Light data is stored in multiple channels. /// 6 for sunlight on all 3 axes +/-. /// 1 for point lights. /// </summary> public enum VoxelLightChannel { SunXp = 0, SunYp = 1, SunZp = 2, SunXn = 3, SunYn = 4, SunZn = 5, Point = 6, } /// <summary> /// Light data for an entire chunk. /// SoA is used here for more effecient propgation code, as each channel propagates independantly. /// </summary> public unsafe class VoxelChunkLightData : IDisposable { VoxelChunk.UnmanagedArray3<byte>[] data; /// <summary>Retrieve the data for a specific channel.</summary> public VoxelChunk.UnmanagedArray3<byte> this[VoxelLightChannel channel] => data[(int) channel]; /// <summary>Retrieve the data for a specific channel.</summary> public VoxelChunk.UnmanagedArray3<byte> this[int channel] => data[channel]; public VoxelChunkLightData() { data = new VoxelChunk.UnmanagedArray3<byte>[7]; for (int l = 0; l < 7; l ++) { data[l] = new VoxelChunk.UnmanagedArray3<byte>(); } } ~VoxelChunkLightData() { Dispose(); } public void Dispose() { if (data != null) { foreach (var channel in data) { channel.Dispose(); } } } /// <summary> /// Get a struct representing the light data for a specific voxel. /// We need this when generating light meshes! /// </summary> /// <param name="coords">Local coords to a voxel in this chunk</param> /// <returns></returns> public VoxelLight GetVoxelLight(Coords coords) { int offset = VoxelChunk.UnmanagedArray3<byte>.GetIndex(coords); return new VoxelLight( *data[0][offset], *data[1][offset], *data[2][offset], *data[3][offset], *data[4][offset], *data[5][offset], *data[6][offset], true ); } } }
using Assets.Scripts.Controllers.Fauna; using System.Collections; using Assets.Scripts.Models; using Assets.Scripts.Models.Ammo; using UnityEngine; namespace Assets.Scripts.Controllers { public class ArrowController : MonoBehaviour { public Rigidbody RigidBody; public float AdditionalForce = 100; public float SphereColliderRadius = 5; private bool _isShoot; private GameManager _gameManager; private bool _initializaed; void Awake() { RigidBody.useGravity = false; } public void Init(GameManager gameManager) { _gameManager = gameManager; _initializaed = true; } public void Shoot() { transform.parent = null; RigidBody.AddForce(transform.forward * AdditionalForce); RigidBody.useGravity = true; StartCoroutine(DelayDestory()); _isShoot = true; } void OnTriggerEnter(Collider other) { if (!_isShoot) return; if(other.tag == "Player") return; RigidBody.velocity = Vector3.zero; RigidBody.angularVelocity = Vector3.zero; RigidBody.useGravity = false; var animalLink = other.gameObject.GetComponent<AnimalColliderLink>(); if (animalLink != null) { var item = BaseObjectFactory.GetItem(typeof(Arrow)); animalLink.SetDamage(item.Damage, transform.position); } else { Vector3 forward = transform.TransformDirection(Vector3.forward) * SphereColliderRadius; Debug.DrawRay(transform.position, forward, Color.green); var location = transform.position; Collider[] objectsInRange = Physics.OverlapSphere(location, SphereColliderRadius); foreach (Collider col in objectsInRange) { var enemy = col.GetComponent<AnimalColliderLink>(); if (enemy != null) { var item = BaseObjectFactory.GetItem(typeof(Arrow)); enemy.SetDamage(item.Damage, transform.position); break; } //if (enemy != null) //{ // float proximity = (location - enemy.transform.position).magnitude; // float effect = 1 - (proximity / SphereColliderRadius); //} //var player = col.GetComponent<PlayerController>(); //if(player != null) //{ // float proximity = (location - col.transform.position).magnitude; // float effect = 1 - (proximity / SphereColliderRadius); // player.MakeDamage(100 * effect); //} } } StopAllCoroutines(); Destroy(gameObject); } private IEnumerator DelayDestory() { yield return new WaitForSeconds(5f); Destroy(gameObject); } void FixedUpdate() { transform.LookAt(transform.position + RigidBody.velocity); } } }
using System; using System.Reflection; using System.Text; using MinDbg.NativeApi; namespace MinDbg.CorMetadata { internal sealed class MetadataMethodInfo : MethodInfo { private readonly Int32 p_methodToken; private readonly Int32 p_classToken; private readonly IMetadataImport p_importer; private readonly String p_name; internal MetadataMethodInfo(IMetadataImport importer, Int32 methodToken) { p_importer = importer; p_methodToken = methodToken; int size; uint pdwAttr; IntPtr ppvSigBlob; uint pulCodeRVA, pdwImplFlags; uint pcbSigBlob; p_importer.GetMethodProps((uint)methodToken, out p_classToken, null, 0, out size, out pdwAttr, out ppvSigBlob, out pcbSigBlob, out pulCodeRVA, out pdwImplFlags); StringBuilder szMethodName = new StringBuilder(size); p_importer.GetMethodProps((uint)methodToken, out p_classToken, szMethodName, szMethodName.Capacity, out size, out pdwAttr, out ppvSigBlob, out pcbSigBlob, out pulCodeRVA, out pdwImplFlags); p_name = szMethodName.ToString(); //m_methodAttributes = (MethodAttributes)pdwAttr; } public override string Name { get { return p_name; } } public override int MetadataToken { get { return this.p_methodToken; } } public override MethodInfo GetBaseDefinition() { throw new NotImplementedException(); } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotImplementedException(); } } public override MethodAttributes Attributes { get { throw new NotImplementedException(); } } public override MethodImplAttributes GetMethodImplementationFlags() { throw new NotImplementedException(); } public override ParameterInfo[] GetParameters() { throw new NotImplementedException(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } public override RuntimeMethodHandle MethodHandle { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { throw new NotImplementedException(); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override Type ReflectedType { get { throw new NotImplementedException(); } } } }
using System.Threading.Tasks; using OrchardCore.ContentManagement; namespace DFC.ServiceTaxonomy.VersionComparison.Services { public class ContentNameService : IContentNameService { private readonly IContentManager _contentManager; public ContentNameService(IContentManager contentManager) { _contentManager = contentManager; } public async Task<string> GetContentNameAsync(string contentItemId) { if (string.IsNullOrWhiteSpace(contentItemId)) { return string.Empty; } var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest); if (contentItem != null) { return contentItem.DisplayText; } return string.Empty; } } }
using Tests.Data.Van.Input; namespace Tests.Data.Van { public class TestVoter { public Voter Voter = new Voter { LastName = "Tester", FirstName = "Boris", MiddleName = "V", Phone = "(899) 135-1064", VanId = "100417676", StreetAddress = "20 Green Street", City = "Boston", Zip = "02130-2562", Email = "borist@tester.com", County = "Mahoning" }; public string ExportFormat = "Standard Text"; public string State = "MA"; } }
using System; using LinkedListExample.Lib; //using UtilityLibraries; class Program { static void Main(string[] args) { IntegerLinkedList ill = new IntegerLinkedList(5); ill.Append(4); Console.WriteLine(ill.ToStr); } static int tester() { return 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using BELCORP.GestorDocumental.Common.Excepcion; using BELCORP.GestorDocumental.Common.Util; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.BL.DDP; using BELCORP.GestorDocumental.DA.Sharepoint; using System.Configuration; using BELCORP.GestorDocumental.BL.Contratos; namespace BELCORP.GestorDocumental.Contratos.TJ_ActualizarTareas { class TJ_ActualizarTareasContratos : SPJobDefinition { public const string JobName = "TJ_ActualizarTareas"; public TJ_ActualizarTareasContratos() : base() { } public TJ_ActualizarTareasContratos(string jobName, SPService service) : base(jobName, service, null, SPJobLockType.None) { this.Title = "Timer Job Actualizar Tareas Contratos"; } public TJ_ActualizarTareasContratos(string jobName, SPWebApplication webapp) : base(jobName, webapp, null, SPJobLockType.Job) { this.Title = "Timer Job Actualizar Tareas Contratos"; } public override void Execute(Guid targetInstanceId) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { SPWebApplication webApp = this.Parent as SPWebApplication; string URL_SitioContratos = webApp.Sites[0].Url + "/sitios/contratos"; if (string.IsNullOrEmpty(URL_SitioContratos)) throw new ErrorPersonalizado("URL de Sitio de Contratos no está configurado"); using (SPSite oSPSite = new SPSite(URL_SitioContratos)) { using (SPWeb oSPWeb = oSPSite.OpenWeb()) { string spQuery = "<Where>" + "<IsNull>" + "<FieldRef Name='CodigoSolicitud'></FieldRef>" + "</IsNull>" + "</Where>"; SPListItemCollection spliTareasNoSincronizadas = SharePointHelper.ObtenerInformacionLista(oSPWeb, ListasGestionContratos.Tareas, spQuery); foreach (SPListItem item in spliTareasNoSincronizadas) { if (item["RelatedItems"] != null) { EventFiring eventFiring = new EventFiring(); eventFiring.DisableHandleEventFiring(); ERGestorContratosTareasFlujoBL.Instance.ActualizarPropiedadesTarea(item); eventFiring.EnableHandleEventFiring(); } } } } }); } catch (ErrorPersonalizado ep) { //Se escribe en el log de sharepoint Logging.RegistrarMensajeLogSharePoint( Constantes.CATEGORIA_LOG_TJ_ACTUALIZAR_TAREAS_DDP, JobName, TraceSeverity.High, EventSeverity.Error, ep); //Se lanza el error para que se registre en el historial del timer job throw; } catch (Exception ex) { //Se escribe en el log de sharepoint Logging.RegistrarMensajeLogSharePoint(Constantes.CATEGORIA_LOG_TJ_ACTUALIZAR_TAREAS_DDP, JobName, ex); //Se lanza el error para que se registre en el historial del timer job throw; } } } }
using DotNetOpenAuth.OAuth2; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Web; namespace OAuthExample { class SelfServiceClient : WebServerClient { // read the base Self Service URL from the Web.config // this value is provided by NimbleUser for each Self Service site private static readonly Uri baseUrl = new Uri(ConfigurationManager.AppSettings["SelfServiceBaseUrl"]); private static readonly Uri authorizationEndpoint = new Uri(baseUrl, "oauth/authorize"); private static readonly Uri tokenEndpoint = new Uri(baseUrl, "oauth/token"); private static readonly Uri userInfoEndpoint = new Uri(baseUrl, "oauth/user"); private static readonly AuthorizationServerDescription SelfServiceDescription = new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint, TokenEndpoint = tokenEndpoint, }; public SelfServiceClient() : base(SelfServiceDescription) { } // makes a request to the userinfo endpoint using the OAuth authorization token // returns some standard claims plus custom ones depending on the implementation // these include: sub (unique identifier in Nimble AMS), given_name, family_name, // email, preferred_username, locale, language, company_name // http://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims public JObject GetUserInfo(IAuthorizationState authorizationState) { var request = (HttpWebRequest)HttpWebRequest.Create(userInfoEndpoint); AuthorizeRequest(request, authorizationState); try { var response = request.GetResponse(); { using (var streamReader = new StreamReader(response.GetResponseStream())) using (var jsonReader = new JsonTextReader(streamReader)) { return JObject.Load(jsonReader); } } } // TODO: error handling catch (WebException e) { using (StreamReader reader = new StreamReader(e.Response.GetResponseStream())) { throw new Exception(reader.ReadToEnd(), e); } } } } public partial class Default : System.Web.UI.Page { private static readonly SelfServiceClient client = new SelfServiceClient() { // read the client identifier and client secret from the Web.config // these values are provided by NimbleUser for each Self Service site ClientIdentifier = ConfigurationManager.AppSettings["ClientIdentifier"], ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["ClientSecret"]) }; protected void Page_Load(object sender, EventArgs e) { IAuthorizationState authorization = client.ProcessUserAuthorization(); // start the authorization process if we haven't already if (authorization == null) { // this will redirect to the Self Service site to start the authorization process // the openid scope is required in order for access to be granted to the userinfo endpoint // an alternate return URL can be specified if desired client.RequestUserAuthorization(new string[] { "openid" } /*, returnTo */); } else { // authorization process is complete, now we can hit the userinfo endpoint var userInfo = client.GetUserInfo(authorization); // debug output of the data returned by the userinfo endpoint LtResult.Text = string.Join("<br/>", userInfo.Properties().Select(x => HttpUtility.HtmlEncode(x.Name + " - " + x.Value.ToString()))); } } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CreateUser.Models { public class UserAlbum { [Key, Column(Order = 0)] public int UserId { get; set; } public virtual User User { get; set; } [Key, Column(Order = 1)] public int AlbumId { get; set; } public virtual Album Album { get; set; } public string UserRole { get; set; } } }
using Business.Abstract; using Business.BusinessAspects.Autofac; using Business.CCS; using Business.Constants; using Business.ValidationRules.FluentValidation; using Core.Aspects.Autofac.Caching; using Core.Aspects.Autofac.Validation; using Core.CrossCuttingConcerns.Validation; using Core.Utilities.Business; using Core.Utilities.Results; using DataAccess.Abstract; using Entities.Concrete; using Entities.DTOs; using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Business.Concrete { public class ProducerManager : IProducerService { IProducerDal _producerDal; public ProducerManager(IProducerDal producerDal) { _producerDal = producerDal; } //[SecuredOperation("product.add,admin")] //[ValidationAspect(typeof(ProductValidator))] [CacheRemoveAspect("IProducerService.Get")] public IResult Add(Producer producer) { //Aynı isimde ürün eklenemez //Eğer mevcut kategori sayısı 15'i geçtiyse sisteme yeni ürün eklenemez. ve //IResult result = BusinessRules.Run(CheckIfProductNameExists(product.ProductName) // //CheckIfProductCountOfCategoryCorrect(product.CategoryId), CheckIfCategoryLimitExceded()); //if (result != null) //{ // return result; //} _producerDal.Add(producer); return new SuccessResult(Messages.ProducerAdded); } public IResult Delete(int producerId) { throw new NotImplementedException(); } //public IResult Delete(int producerId) //{ // _producerDal.Delete(producerId); // return new SuccessResult(Messages.ProducerDeleted); //} [CacheAspect] public IDataResult<List<Producer>> GetAll() { //if (DateTime.Now.Hour == 1) //{ // return new ErrorDataResult<List<Product>>(Messages.MaintenanceTime); //} return new SuccessDataResult<List<Producer>>(_producerDal.GetAll(), Messages.ProductsListed); } //public IDataResult<List<Producer>> GetAllByCategoryId(int id) //{ // return new SuccessDataResult<List<Product>>(_productDal.GetAll(p => p.CategoryId == id)); //} [CacheAspect] public IDataResult<Producer> GetById(int producerId) { return new SuccessDataResult<Producer>(_producerDal.Get(p => p.Id == producerId)); } //public IDataResult<List<Producer>> GetByUnitPrice(decimal min, decimal max) //{ // return new SuccessDataResult<List<Product>>(_productDal.GetAll(p => p.UnitPrice >= min && p.UnitPrice <= max)); //} public IDataResult<List<ProducerDetailDto>> GetProducerDetails() { //if (DateTime.Now.Hour == 23) //{ // return new ErrorDataResult<List<ProductDetailDto>>(Messages.MaintenanceTime); //} //return new SuccessDataResult<List<ProducerDetailDto>>(_producerDal.); return null; } //[ValidationAspect(typeof(ProductValidator))] //[CacheRemoveAspect("IProductService.Get")] public IResult Update(Producer producer) { //var result = _producerDal.GetAll(p => p.CategoryId == product.CategoryId).Count; //if (result >= 10) //{ // return new ErrorResult(Messages.ProductCountOfCategoryError); //} //throw new NotImplementedException(); _producerDal.Update(producer); return new SuccessResult(Messages.ProducerAdded); } //private IResult CheckIfProductCountOfCategoryCorrect(int categoryId) //{ // //Select count(*) from products where categoryId=1 // var result = _productDal.GetAll(p => p.CategoryId == categoryId).Count; // if (result >= 15) // { // return new ErrorResult(Messages.ProductCountOfCategoryError); // } // return new SuccessResult(); //} //private IResult CheckIfProducerNameExists(string producerName) //{ // var result = _productDal.GetAll(p => p.pr == productName).Any(); // if (result) // { // return new ErrorResult(Messages.ProductNameAlreadyExists); // } // return new SuccessResult(); //} //private IResult CheckIfCategoryLimitExceded() //{ // var result = _categoryService.GetAll(); // if (result.Data.Count>15) // { // return new ErrorResult(Messages.CategoryLimitExceded); // } // return new SuccessResult(); //} //public IResult AddTransactionalTest(Product product) //{ // throw new NotImplementedException(); //} } }
using System; using System.Collections.Generic; using DevFitness.ConsoleApp.Usuarios; using DevFitness.ConsoleApp.Refeicoes; using System.Linq; namespace DevFitness.ConsoleApp { public class Program { #region Constantes private const string ERROR_ADMIN_MESSAGE = "Erro! Contate o administrador do sistema."; private const string FORMAT_MESSAGE_ERROR = "Erro! Formato da entrada inválido."; private const string INVALID_MESSAGE_ERROR = "Erro! Valor da entrada inválido."; private const string QUESTION_MENU_MESSAGE = "Digite o valor corresponde à opção desejada: "; #endregion public static void Main(string[] args) { #region Variáveis de execução int option; bool executar = true; var refeicoes = new List<Refeicao>(); #endregion Console.WriteLine(("--- Seja bem-vindo (a) ---\n\n").PadLeft(45) + "Antes de começar, precisamos de alguns dados.."); Usuario usuario = CadastrarUsuario(); while (executar) { option = ExibirMenuPrinciapal(); ExecutarOpcaoSelecionada(option, usuario, refeicoes, out executar); } Console.Write("\nFechando o aplicativo..."); System.Threading.Thread.Sleep(2500); } #region Métodos auxiliares /// <summary> /// Método que retorna o texto do menu principal da aplicação. /// </summary> private static int ExibirMenuPrinciapal() { Console.Clear(); Console.WriteLine(($"--- Seja bem-vindo (a) ao DevFitness ---\n\n").PadLeft(50) + $"[1] - Cadastrar nova refeição.\n" + $"[2] - Buscar refeição.\n" + $"[3] - Excluir refeição.\n" + $"[4] - Listar todas refeições.\n" + $"[0] - Fechar o aplicativo.\n"); return ValidarEntradaInt(QUESTION_MENU_MESSAGE, 4); } /// <summary> /// Método que retorna o tipo de refeição selecionado pelo usuário. /// </summary> /// <returns></returns> private static int MenuTipoRefeicao() { Console.WriteLine(("Tipos de Refeição disponíveis:\n").PadLeft(35) + "[1] - Bebida\n" + "[2] - Comida\n"); return ValidarEntradaInt(QUESTION_MENU_MESSAGE, 2, 1); } /// <summary> /// Método para executar a opção selecionada pelo usuário. /// </summary> /// <param name="opcao">Opção selecionada pelo usuário</param> /// <param name="executar"></param> private static void ExecutarOpcaoSelecionada(int opcao, Usuario usuario, IList<Refeicao> refeicoes, out bool executar) { executar = true; Console.Clear(); switch (opcao) { case 0: // Fechar o aplicativo executar = false; break; case 1: // Cadastrar nova refeição Console.WriteLine(($"--- Cadastrar uma nova refeição para o(a) {usuario.Nome} ---\n").PadLeft(50)); var refeicaoCadastrada = CadastrarRefeicao(refeicoes); if (refeicaoCadastrada != null) { Console.WriteLine($"Refeição cadastrada com sucesso, veja abaixo:\n\n{refeicaoCadastrada.ObterInformacoes()}"); } else { Console.WriteLine("Erro ao cadastrar a refeição! A refeição já está cadastrada."); } break; case 2: // Buscar refeição Console.WriteLine(("--- Buscar refeição ---\n").PadLeft(35)); var refeicaoBuscada = BuscarRefeicao(refeicoes); if (refeicaoBuscada != null) { Console.WriteLine($"Refeição encontrada com sucesso, veja abaixo:\n\n{refeicaoBuscada.ObterInformacoes()}"); } else { Console.WriteLine("Refeição não encontrada!"); } break; case 3: // Excluir refeição Console.WriteLine(("--- Excluir refeição ---\n").PadLeft(35)); var refeicaoDeletada = DeletarRefeicao(refeicoes); if (refeicaoDeletada != null) { Console.WriteLine($"Refeição excluída com sucesso, veja abaixo:\n\n{refeicaoDeletada.ObterInformacoes()}"); } else { Console.WriteLine("Erro ao excluir a refeição!"); } break; case 4: // Listar todas refeições Console.WriteLine(("--- Listar todas as refeições ---\n").PadLeft(45)); ListarRefeicoes(refeicoes); break; default: // Erro (em um funcionamento correto, não deve cair aqui) Console.WriteLine(ERROR_ADMIN_MESSAGE); executar = false; break; } if (opcao != 0) { Console.Write("\nTecle enter para voltar ao menu principal..."); Console.ReadLine(); } } /// <summary> /// Cadastrar um usuário /// </summary> /// <returns>Usuário cadastrado</returns> private static Usuario CadastrarUsuario() { string nome = string.Empty; while (nome.Length < 3) { Console.Write("Digite o seu nome: "); nome = Console.ReadLine().Trim(); if (nome.Length < 3) { Console.WriteLine(INVALID_MESSAGE_ERROR); } } string cpf = string.Empty; while (cpf.Length != 11) { Console.Write("Digite o seu CPF: "); cpf = Console.ReadLine().Trim(); if (cpf.Length != 11) { Console.WriteLine(INVALID_MESSAGE_ERROR); } } int idade = ValidarEntradaInt("Digite a sua idade: ", 140); int validacaoSexo = ValidarEntradaInt($"Sexo:\n" + $"[1] - Feminino\n" + $"[2] - Masculino\n" + $"{QUESTION_MENU_MESSAGE}", 2, 1); char sexo = validacaoSexo == 1 ? 'F' : 'M'; double altura = 0; while (altura == 0) { Console.Write("Digite a sua altura: "); double.TryParse(Console.ReadLine().Replace('.', ','), out altura); if (altura == 0) { Console.WriteLine(FORMAT_MESSAGE_ERROR); } else if (altura < 0 || altura > 3.5) { Console.WriteLine(INVALID_MESSAGE_ERROR); altura = 0; } } double peso = 0; while (peso == 0) { Console.Write("Digite o seu peso: "); double.TryParse(Console.ReadLine().Replace('.', ','), out peso); if (peso == 0) { Console.WriteLine(FORMAT_MESSAGE_ERROR); } else if (peso < 0 || peso > 500) { Console.WriteLine(INVALID_MESSAGE_ERROR); peso = 0; } } return new Usuario(nome, idade, sexo, altura, peso); } /// <summary> /// Cadastrar uma refeição. /// </summary> /// <returns>Refeição cadastrada</returns> private static Refeicao CadastrarRefeicao(IList<Refeicao> refeicoes) { Refeicao refeicao; var tipoRefeicao = MenuTipoRefeicao(); var tipoRefeicaoString = (tipoRefeicao == 1 ? "bebida" : "comida"); Console.Write($"Dê um nome ou descrição para a {tipoRefeicaoString}: "); string descricao = Console.ReadLine().Trim(); int calorias = ValidarEntradaInt($"Digite a quantidade total de calorias da {tipoRefeicaoString}: "); decimal preco = 0; while (preco == 0) { Console.Write($"Digite o preço da {tipoRefeicaoString}: "); decimal.TryParse(Console.ReadLine().Replace('.', ','), out preco); if (preco == 0) { Console.WriteLine(FORMAT_MESSAGE_ERROR); } } switch (tipoRefeicao) { case 1: // Cadastrar Bebida int mililitros = ValidarEntradaInt($"Digite a quantidade de mililitros (ml) da {tipoRefeicaoString}: "); refeicao = new Bebida(descricao, calorias, mililitros, preco); break; case 2: // Cadastrar Comida double peso = 0; while (peso == 0) { Console.Write($"Digite o peso da da {tipoRefeicaoString}: "); double.TryParse(Console.ReadLine().Replace('.', ','), out peso); if (peso == 0) { Console.WriteLine(FORMAT_MESSAGE_ERROR); } } refeicao = new Comida(descricao, calorias, peso, preco); break; default: // Erro (não pode cair aqui) Console.WriteLine(ERROR_ADMIN_MESSAGE); return null; } var refeicaoJaExiste = refeicoes .Any(r => r.Descricao == refeicao.Descricao && r.Calorias == refeicao.Calorias && r.Preco == refeicao.Preco); if (!refeicaoJaExiste) { refeicoes.Add(refeicao); return refeicao; } return null; } /// <summary> /// Buscar um refeição /// </summary> /// <param name="refeicoes">lista de refições do sistema</param> /// <returns>Refeição encontrada</returns> private static Refeicao BuscarRefeicao(IList<Refeicao> refeicoes) { Console.Write("Digite o nome ou descrição da refeição: "); string descricao = Console.ReadLine(); decimal preco = 0; while (preco == 0) { Console.Write($"Digite o preço da refeição: "); decimal.TryParse(Console.ReadLine().Replace('.', ','), out preco); if (preco == 0) { Console.WriteLine(FORMAT_MESSAGE_ERROR); } } return refeicoes .FirstOrDefault(r => r.Descricao.Equals(descricao, StringComparison.InvariantCultureIgnoreCase) && r.Preco == preco); } /// <summary> /// Deletar uma refeição /// </summary> /// <param name="refeicoes">Lista de refeições do sistema</param> /// <returns>Refeição deletada</returns> private static Refeicao DeletarRefeicao(IList<Refeicao> refeicoes) { Console.Write("Digite o nome ou descrição da refeição: "); string descricao = Console.ReadLine(); decimal preco = 0; while (preco == 0) { Console.Write($"Digite o preço da refeição: "); decimal.TryParse(Console.ReadLine().Replace('.', ','), out preco); if (preco == 0) { Console.WriteLine(FORMAT_MESSAGE_ERROR); } } var refeicao = refeicoes .FirstOrDefault(r => r.Descricao.Equals(descricao, StringComparison.InvariantCultureIgnoreCase) && r.Preco == preco); refeicoes.Remove(refeicao); return refeicao; } /// <summary> /// Listar todas as refeições. /// </summary> /// <param name="refeicoes">Lista de refeições do sistema</param> private static void ListarRefeicoes(IList<Refeicao> refeicoes) { if (!refeicoes.Any()) { Console.WriteLine("Nennhuma refeição cadastrada!"); } foreach (var refeicao in refeicoes) { if (refeicao.GetType() == typeof(Comida)) { Console.WriteLine(((Comida)refeicao).ObterInformacoes()); } else if (refeicao.GetType() == typeof(Bebida)) { Console.WriteLine(((Bebida)refeicao).ObterInformacoes()); } else { Console.WriteLine(((Refeicao)refeicao).ObterInformacoes()); } Console.WriteLine("\n"); } } /// <summary> /// Método para validar a entrada e transformar de string para int. /// </summary> /// <param name="msg">Mensagem a ser exibida para o usuário</param> /// <param name="maxValue">Valor máximo aceito para resposta (opcional)</param> /// <param name="minValue">Valor mínimo aceiro para a resposta (opcional)</param> /// <returns>Entrada do usuário validada e convertida para int</returns> public static int ValidarEntradaInt(string msg, int maxValue = 0, int minValue = 0) { int escolha, validacao = minValue - 1; do { try { Console.Write(msg); escolha = Convert.ToInt32(Console.ReadLine()); if (minValue != maxValue && (escolha < minValue || escolha > maxValue)) { throw new ArgumentException(); } } catch (FormatException) { Console.WriteLine(FORMAT_MESSAGE_ERROR); escolha = validacao; } catch (ArgumentException) { Console.WriteLine(INVALID_MESSAGE_ERROR); escolha = validacao; } } while (escolha == validacao); return escolha; } #endregion } }
using System; namespace Score.Models { public class Program { } public class Points { private string _word; public Points(string word) { _word = word; } public string CollectWord() { return _word; } public string LowerCase() { return _word.ToLower(); } public char[] ConvertString(string word) { char[] result = word.ToCharArray(); return result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; namespace ClientSimulator { class Log { private string filePath = "ClientSimulatorLogs.txt"; private Queue<string> writerQueue; private Queue<string> readerQueue1; private Queue<string> readerQueue2; private int currQueue; private static Log log; private ManualResetEvent writeWait = new ManualResetEvent(false); private string date = DateTime.Now.ToLongDateString() + " "; private Log() { writeWait.Reset(); readerQueue1 = new Queue<string>(); readerQueue2 = new Queue<string>(); writerQueue = readerQueue1; currQueue = 1; if (File.Exists(filePath)) { File.Delete(filePath); } Thread reader = new Thread(GetMessage); reader.Start(); } public static Log GetLog { get { if (log == null) { log = new Log(); } return log; } } public void Write(string message) { int count = 0; string dateTime = date + DateTime.Now.ToLongTimeString() + " : "; lock (writerQueue) { writerQueue.Enqueue(dateTime + message); count = writerQueue.Count; } writeWait.Set(); } private void GetMessage() { StringBuilder msg = new StringBuilder(); while (true) { writeWait.WaitOne(); if (currQueue == 1 && readerQueue2.Count != 0) { while (readerQueue2.Count != 0) { msg.AppendLine(readerQueue2.Dequeue()); if (msg.Length > 500) { WriteInFile(msg); msg.Clear(); } } if (msg.Length != 0) { WriteInFile(msg); msg.Clear(); } continue; } else if (currQueue == 2 && readerQueue1.Count != 0) { while (readerQueue1.Count != 0) { msg.AppendLine(readerQueue1.Dequeue()); if (msg.Length > 500) { WriteInFile(msg); msg.Clear(); } } if (msg.Length != 0) { WriteInFile(msg); msg.Clear(); } Swap(); continue; } writeWait.Reset(); Swap(); } } private void Swap() { if ((readerQueue1.Count + readerQueue2.Count) < 1000) return; if (currQueue == 1) { lock (writerQueue) writerQueue = readerQueue2; currQueue = 2; } else { lock (writerQueue) writerQueue = readerQueue1; currQueue = 1; } } private void WriteInFile(StringBuilder message) { // Console.WriteLine(message); using (StreamWriter streamWriter = new StreamWriter(filePath, true)) { streamWriter.Write(message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class TrackingIdRepetidoException : Exception { /// <summary>Constructor que recibe un mensaje. /// </summary> /// <param name="mensaje">mensaje</param> public TrackingIdRepetidoException(string mensaje) : base(mensaje) { } /// <summary>Constructor que recibe un mensaje y una Excepcion, sobrecarga el primer constructor. /// </summary> /// <param name="mensaje">mensaje</param> /// <param name="inner">inner</param> public TrackingIdRepetidoException(string mensaje, Exception inner) : base (mensaje,inner) { } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.App.Share.Rewards.Domain.Enums { /// <summary> /// 产品限制方式 /// </summary> [ClassProperty(Name = "产品限制方式")] public enum ProductLimitType { /// <summary> /// 产品线范围内 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "选择商品范围内")] Allow = 1, /// <summary> /// 非产品线内的 /// </summary> [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "选择商品范围外")] Refuse = 2 } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using streamdeck_client_csharp.Events; using streamdeck_client_csharp.Messages; using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace streamdeck_client_csharp { public class StreamDeckConnection { private const int BufferSize = 1024 * 1024; private ClientWebSocket m_WebSocket; private readonly SemaphoreSlim m_SendSocketSemaphore = new SemaphoreSlim(1); private readonly CancellationTokenSource m_CancelSource = new CancellationTokenSource(); private readonly string m_RegisterEvent; /// <summary> /// The port used to connect to the StreamDeck websocket /// </summary> public int Port { get; private set; } /// <summary> /// This is the unique identifier used to communicate with the register StreamDeck plugin. /// </summary> public string UUID { get; private set; } public event EventHandler<EventArgs> OnConnected; public event EventHandler<EventArgs> OnDisconnected; public event EventHandler<StreamDeckEventReceivedEventArgs<KeyDownEvent>> OnKeyDown; public event EventHandler<StreamDeckEventReceivedEventArgs<KeyUpEvent>> OnKeyUp; public event EventHandler<StreamDeckEventReceivedEventArgs<WillAppearEvent>> OnWillAppear; public event EventHandler<StreamDeckEventReceivedEventArgs<WillDisappearEvent>> OnWillDisappear; public event EventHandler<StreamDeckEventReceivedEventArgs<TitleParametersDidChangeEvent>> OnTitleParametersDidChange; public event EventHandler<StreamDeckEventReceivedEventArgs<DeviceDidConnectEvent>> OnDeviceDidConnect; public event EventHandler<StreamDeckEventReceivedEventArgs<DeviceDidDisconnectEvent>> OnDeviceDidDisconnect; public event EventHandler<StreamDeckEventReceivedEventArgs<ApplicationDidLaunchEvent>> OnApplicationDidLaunch; public event EventHandler<StreamDeckEventReceivedEventArgs<ApplicationDidTerminateEvent>> OnApplicationDidTerminate; public event EventHandler<StreamDeckEventReceivedEventArgs<SendToPluginEvent>> OnSendToPlugin; public event EventHandler<StreamDeckEventReceivedEventArgs<DidReceiveSettingsEvent>> OnDidReceiveSettings; public event EventHandler<StreamDeckEventReceivedEventArgs<DidReceiveGlobalSettingsEvent>> OnDidReceiveGlobalSettings; public event EventHandler<StreamDeckEventReceivedEventArgs<PropertyInspectorDidAppearEvent>> OnPropertyInspectorDidAppear; public event EventHandler<StreamDeckEventReceivedEventArgs<PropertyInspectorDidDisappearEvent>> OnPropertyInspectorDidDisappear; public StreamDeckConnection(int port, string uuid, string registerEvent) { this.Port = port; this.UUID = uuid; m_RegisterEvent = registerEvent; } public void Run() { if (m_WebSocket == null) { m_WebSocket = new ClientWebSocket(); _ = this.RunAsync(); } } public void Stop() { m_CancelSource.Cancel(); } public Task SetTitleAsync(string title, string context, SDKTarget target, int? state) { return SendAsync(new SetTitleMessage(title, context, target, state)); } public Task LogMessageAsync(string message) { return SendAsync(new LogMessage(message)); } public Task SetImageAsync(Image image, string context, SDKTarget target, int? state) { using (MemoryStream memoryStream = new MemoryStream()) { image.Save(memoryStream, ImageFormat.Png); byte[] imageBytes = memoryStream.ToArray(); // Convert byte[] to Base64 String string base64String = $"data:image/png;base64,{Convert.ToBase64String(imageBytes)}"; return SetImageAsync(base64String, context, target, state); } } public Task SetImageAsync(string base64Image, string context, SDKTarget target, int? state) { return SendAsync(new SetImageMessage(base64Image, context, target, state)); } public Task ShowAlertAsync(string context) { return SendAsync(new ShowAlertMessage(context)); } public Task ShowOkAsync(string context) { return SendAsync(new ShowOkMessage(context)); } public Task SetGlobalSettingsAsync(JObject settings) { return SendAsync(new SetGlobalSettingsMessage(settings, this.UUID)); } public Task GetGlobalSettingsAsync() { return SendAsync(new GetGlobalSettingsMessage(this.UUID)); } public Task SetSettingsAsync(JObject settings, string context) { return SendAsync(new SetSettingsMessage(settings, context)); } public Task GetSettingsAsync(string context) { return SendAsync(new GetSettingsMessage(context)); } public Task SetStateAsync(uint state, string context) { return SendAsync(new SetStateMessage(state, context)); } public Task SendToPropertyInspectorAsync(string action, JObject data, string context) { return SendAsync(new SendToPropertyInspectorMessage(action, data, context)); } public Task SwitchToProfileAsync(string device, string profileName, string context) { return SendAsync(new SwitchToProfileMessage(device, profileName, context)); } public Task OpenUrlAsync(string uri) { return OpenUrlAsync(new Uri(uri)); } public Task OpenUrlAsync(Uri uri) { return SendAsync(new OpenUrlMessage(uri)); } private Task SendAsync(IMessage message) { return SendAsync(JsonConvert.SerializeObject(message)); } private async Task SendAsync(string text) { try { if (m_WebSocket != null) { try { await m_SendSocketSemaphore.WaitAsync(); byte[] buffer = Encoding.UTF8.GetBytes(text); await m_WebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, m_CancelSource.Token); } finally { m_SendSocketSemaphore.Release(); } } } catch { await DisconnectAsync(); } } private async Task RunAsync() { try { await m_WebSocket.ConnectAsync(new Uri($"ws://localhost:{this.Port}"), m_CancelSource.Token); if (m_WebSocket.State != WebSocketState.Open) { await DisconnectAsync(); return; } await SendAsync(new RegisterEventMessage(m_RegisterEvent, this.UUID)); OnConnected?.Invoke(this, new EventArgs()); await ReceiveAsync(); } finally { await DisconnectAsync(); } } private async Task<WebSocketCloseStatus> ReceiveAsync() { byte[] buffer = new byte[BufferSize]; ArraySegment<byte> arrayBuffer = new ArraySegment<byte>(buffer); StringBuilder textBuffer = new StringBuilder(BufferSize); try { while (!m_CancelSource.IsCancellationRequested && m_WebSocket != null) { WebSocketReceiveResult result = await m_WebSocket.ReceiveAsync(arrayBuffer, m_CancelSource.Token); if (result != null) { if (result.MessageType == WebSocketMessageType.Close || (result.CloseStatus != null && result.CloseStatus.HasValue && result.CloseStatus.Value != WebSocketCloseStatus.Empty)) { return result.CloseStatus.GetValueOrDefault(); } else if (result.MessageType == WebSocketMessageType.Text) { textBuffer.Append(Encoding.UTF8.GetString(buffer, 0, result.Count)); if (result.EndOfMessage) { BaseEvent evt = BaseEvent.Parse(textBuffer.ToString()); if (evt != null) { switch (evt.Event) { case EventTypes.KeyDown: OnKeyDown?.Invoke(this, new StreamDeckEventReceivedEventArgs<KeyDownEvent>(evt as KeyDownEvent)); break; case EventTypes.KeyUp: OnKeyUp?.Invoke(this, new StreamDeckEventReceivedEventArgs<KeyUpEvent>(evt as KeyUpEvent)); break; case EventTypes.WillAppear: OnWillAppear?.Invoke(this, new StreamDeckEventReceivedEventArgs<WillAppearEvent>(evt as WillAppearEvent)); break; case EventTypes.WillDisappear: OnWillDisappear?.Invoke(this, new StreamDeckEventReceivedEventArgs<WillDisappearEvent>(evt as WillDisappearEvent)); break; case EventTypes.TitleParametersDidChange: OnTitleParametersDidChange?.Invoke(this, new StreamDeckEventReceivedEventArgs<TitleParametersDidChangeEvent>(evt as TitleParametersDidChangeEvent)); break; case EventTypes.DeviceDidConnect: OnDeviceDidConnect?.Invoke(this, new StreamDeckEventReceivedEventArgs<DeviceDidConnectEvent>(evt as DeviceDidConnectEvent)); break; case EventTypes.DeviceDidDisconnect: OnDeviceDidDisconnect?.Invoke(this, new StreamDeckEventReceivedEventArgs<DeviceDidDisconnectEvent>(evt as DeviceDidDisconnectEvent)); break; case EventTypes.ApplicationDidLaunch: OnApplicationDidLaunch?.Invoke(this, new StreamDeckEventReceivedEventArgs<ApplicationDidLaunchEvent>(evt as ApplicationDidLaunchEvent)); break; case EventTypes.ApplicationDidTerminate: OnApplicationDidTerminate?.Invoke(this, new StreamDeckEventReceivedEventArgs<ApplicationDidTerminateEvent>(evt as ApplicationDidTerminateEvent)); break; case EventTypes.SendToPlugin: OnSendToPlugin?.Invoke(this, new StreamDeckEventReceivedEventArgs<SendToPluginEvent>(evt as SendToPluginEvent)); break; case EventTypes.DidReceiveSettings: OnDidReceiveSettings?.Invoke(this, new StreamDeckEventReceivedEventArgs<DidReceiveSettingsEvent>(evt as DidReceiveSettingsEvent)); break; case EventTypes.DidReceiveGlobalSettings: OnDidReceiveGlobalSettings?.Invoke(this, new StreamDeckEventReceivedEventArgs<DidReceiveGlobalSettingsEvent>(evt as DidReceiveGlobalSettingsEvent)); break; case EventTypes.PropertyInspectorDidAppear: OnPropertyInspectorDidAppear?.Invoke(this, new StreamDeckEventReceivedEventArgs<PropertyInspectorDidAppearEvent>(evt as PropertyInspectorDidAppearEvent)); break; case EventTypes.PropertyInspectorDidDisappear: OnPropertyInspectorDidDisappear?.Invoke(this, new StreamDeckEventReceivedEventArgs<PropertyInspectorDidDisappearEvent>(evt as PropertyInspectorDidDisappearEvent)); break; } } else { // Consider logging or throwing an error here } textBuffer.Clear(); } } } } } catch { } return WebSocketCloseStatus.NormalClosure; } private async Task DisconnectAsync() { if (m_WebSocket != null) { ClientWebSocket socket = m_WebSocket; m_WebSocket = null; try { await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Disconnecting", m_CancelSource.Token); } catch { } try { socket.Dispose(); } catch { } OnDisconnected?.Invoke(this, new EventArgs()); } } } }
using System; using System.Runtime.CompilerServices; namespace DanialProject.Models.Others { public class ExternalLoginListViewModel { public string ReturnUrl { get; set; } public ExternalLoginListViewModel() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Patrol : MonoBehaviour { public Transform pointA; public Transform pointB; bool goToPointA = true; [Tooltip("Set true if your character is always facing the wrong way")] public bool flipFix = true; public float speed = 0.3f; Vector3 thisPosition; SpriteRenderer spriteRenderer; void Start() { thisPosition = transform.position; spriteRenderer = GetComponent<SpriteRenderer>(); CalculateClosestPoint(); } // Update is called once per frame void Update() { thisPosition = transform.position; if (!goToPointA) { transform.position = Vector3.MoveTowards(transform.position, pointB.position, speed); //Debug.Log("Going to B"); if (thisPosition.Equals(pointB.position)) { //Debug.Log("At B"); goToPointA = true; if (flipFix) { spriteRenderer.flipX = false; } else { spriteRenderer.flipX = true; } } } else { transform.position = Vector3.MoveTowards(transform.position, pointA.position, speed); //Debug.Log("Going to A"); if (thisPosition.Equals(pointA.position)) { //Debug.Log("At A"); goToPointA = false; if (flipFix) { spriteRenderer.flipX = true; } else { spriteRenderer.flipX = false; } } } } void CalculateClosestPoint() { float distA = Vector3.Distance(thisPosition, pointA.transform.position); Debug.Log($"A: {distA}"); float distB = Vector3.Distance(thisPosition, pointB.transform.position); Debug.Log($"B: {distB}"); if (distA >= distB) { goToPointA = false; } else { goToPointA = true; } Debug.Log($"Point A?: {goToPointA}"); } }
using System; using System.Collections.Generic; using System.Threading; using Framework.Core.Common; using Tests.Pages.Oberon.Modals; using Tests.Pages.Oberon.Search; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Oberon.Search { public class SearchExportForMailingModal : ModalBase { public SearchExportForMailingModal(Driver driver) : base(driver) { Thread.Sleep(1000); } #region Page Objects public IWebElement MailingInformation { get { return _driver.FindElement(By.Id("mailingInformation")); } } #endregion #region Methods /// <summary> /// sleeps 1 millisecond, then waits for postal mailing export dialog to display /// </summary> /// <summary> /// clicks do not household results radio /// </summary> public void ClickDoNotHouseholdResultsRadio() { _driver.Click(_driver.FindElement(By.XPath("//input[@value='DoNotHousehold']"))); } /// <summary> /// clicks create record checkbox /// </summary> public void ClickCreateRecordCheckbox() { _driver.Click(_driver.FindElement(By.Id("CreateRecord"))); } /// <summary> /// clicks log thank you checkbox /// </summary> public void ClickLogThankYouCheckbox() { _driver.Click(_driver.FindElement((By.Id("LogThankYou")))); } /// <summary> /// sets mailing name by name /// </summary> public void SetMailingName(string name) { _driver.SendKeys(MailingInformation.FindElement(By.Id("Name")), name); } /// <summary> /// sets mailing dscription by description /// </summary> public void SetMailingDescription(string description) { _driver.SendKeys(MailingInformation.FindElement(By.Id("Description")), description); } /// <summary> /// clicks run export button /// </summary> public void RunExport() { _driver.Click(_driver.FindElement(By.Id("runExportForMailing"))); _driver.WaitForNotPresent(TitleLocator); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyBehaviour : MonoBehaviour { public float individualHealth; public FloatData health; //public FloatData speed; public bool canDash; public WaitForSeconds wfs; public float holdTime = 2f; public void Start() { wfs = new WaitForSeconds(holdTime); individualHealth = health.value; } public void UpdateHealth() { individualHealth -= 1; if (individualHealth <= 0) { Destroy(gameObject); } } public void DragonDash() { //on trigger stay //find player position if (canDash) { MoveDragon(); } } private void MoveDragon() { //have head go after player then go back to normal gameObject.transform.position; StartCoroutine(HoldDash()); } private IEnumerator HoldDash() { canDash = false; yield return wfs; canDash = true; } }
using EasySave.Model.Job.Specialisation; using EasySave.Model.Task; using System; using System.Collections.Generic; using System.Text; namespace EasySave.Model.Job { /// <summary> /// Singleton class. Manage the differents commands and instanciate then. /// </summary> public sealed class JobManager : IJobManager { /// <summary> /// Map of the commands. /// </summary> public List<BaseJob> Map { get; } public JobManager(ITaskManager taskManager) { this.Map = new List<BaseJob>(); Map.Add(new HelpJob(this)); //Task management Map.Add(new TaskListJob(taskManager)); Map.Add(new TaskRemoveJob(taskManager)); Map.Add(new TaskAddJob(taskManager)); Map.Add(new TaskExecutesJob(taskManager, this)); //Save Map.Add(new SaveMirrorJob()); Map.Add(new SaveDifferentialJob()); } /// <summary> /// Get a command by its name. /// </summary> /// <param name="name">Command name</param> /// <returns>The command if found, else return null</returns> public BaseJob GetJobByName(string name) { return Map.Find(job => job.Info.Name == name); } } }
using Company.Master2.xmlmodel; using Microsoft.master2.model; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.master2.rules { class Heuristics { public static ArrayList updateRelevanceForSelect(ArrayList cSharpModel, string selectedClass,string selectedMethod){ foreach (CSharpClass existedClass in cSharpModel) { if (existedClass.Name == selectedClass) { ArrayList existedMethods = existedClass.Methods; foreach (CSharpMethod cSharpExistedMethod in existedMethods) { if (cSharpExistedMethod.Name == selectedMethod) { cSharpExistedMethod.Relevance += 0.5; } } } } return cSharpModel; } public static ArrayList updateRelevance(ArrayList cSharpModel, CSharpClass cSharpClass, bool isRefreshButton) { foreach (CSharpClass existedClass in cSharpModel) { if (existedClass.Equals(cSharpClass)) { if (!isRefreshButton) { existedClass.Relevance += 1;//cSharpClass.Relevance; } ArrayList existedMethods = existedClass.Methods; if (isRefreshButton) { foreach (CSharpMethod cSharpExistedMethod in existedMethods) { ArrayList methods = cSharpClass.Methods; if (cSharpExistedMethod.Name.Equals(cSharpClass.SelectedMethod)) { cSharpExistedMethod.Relevance += 0.1; } /* foreach (CSharpMethod cSharpMethod in methods) { if (cSharpExistedMethod.Name.Equals(cSharpClass.SelectedMethod)) { cSharpExistedMethod.Relevance += 0.1; } }*/ } ArrayList existedFields = existedClass.Fields; foreach (CSharpField cSharpExistedField in existedFields) { ArrayList fields = cSharpClass.Fields; foreach (CSharpField cSharpField in fields) { if (cSharpExistedField.Equals(cSharpField)) { cSharpExistedField.Relevance += cSharpField.Relevance; } } } } } else { if (existedClass.Relevance > 0) { existedClass.Relevance -= 0.1; } } } if (!cSharpModel.Contains(cSharpClass)) { cSharpClass.Relevance = 1; cSharpModel.Add(cSharpClass); } return cSharpModel; } } }
namespace RosPurcell.Web.ViewModels.Pages { using System.Web; using RosPurcell.Web.ViewModels.Media; using RosPurcell.Web.ViewModels.Pages.Base; public class HomePageViewModel : BasePageViewModel { public IHtmlString Copy { get; set; } public HeroImage Image { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MilitaryElite.Soldiers.Privates.SpecialisedSoldiers.Engineers; namespace MilitaryElite.Soldiers.Privates.SpecialisedSoldiers { public class Engineer:SpecialisedSoldier { public Engineer(string id, string firstName, string lastName, decimal salary, string corp) : base(id, firstName, lastName, salary, corp) { this.Repairs = new List<Repair>(); } public List<Repair> Repairs { get; set; } public override string ToString() { if (Repairs.Count == 0) { return $"Name: {FirstName} {LastName} Id: {ID} Salary: {Salary:f2}\nCorps: {Corp}\nRepairs:{String.Join("\n", Repairs.Select(x => x.ToString()))}"; } return $"Name: {FirstName} {LastName} Id: {ID} Salary: {Salary:f2}\nCorps: {Corp}\nRepairs:\n{String.Join("\n", Repairs.Select(x => x.ToString()))}"; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading.Tasks; namespace SolutionsAssembly { public class EvenFibonacciNumbersSolutions : ISolutionsContract { /// <summary> /// C#6 Expression Bodies! yay! /// </summary> public string ProblemDescription => "Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\r\n" + "1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\r\n" + "By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."; public string ProblemName => "Even Fibanacci Number Product"; public int ProblemNumber => 2; public string Solution() { return ProblemSolution().ToString(); } private int ProblemSolution() { int ans = 0, firstNum = 0, secondNum = 1, currentNum = 0; while (currentNum < 4000000) { currentNum = firstNum + secondNum; firstNum = secondNum; secondNum = currentNum; ans += currentNum % 2 == 0 ? currentNum : 0; } return ans; } } }
using Hangfire; using Hangfire.SqlServer; using Hangfire.Redis; using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Web { public partial class Startup { public void ConfigureHangfire(IAppBuilder app) { //Hangfire+SqlServer(免费版) //GlobalConfiguration.Configuration.UseSqlServerStorage("<name or connection string>"); //app.UseHangfireDashboard(); //app.UseHangfireServer(); //Hangfire_net40+Redis(version:1.1.1) //app.UseHangfire(config => //{ // config.UseRedisStorage("123123@127.0.0.1", 0, new Hangfire.Redis.RedisStorageOptions()); // config.UseServer(); //}); //Hangfire+Redis.StackExchange(免费版) GlobalConfiguration.Configuration.UseRedisStorage("localhost,password=123123", new Hangfire.Redis.RedisStorageOptions() { }); app.UseHangfireDashboard(); app.UseHangfireServer(); } } }
using Cs_Notas.Dominio.Entities; using Cs_Notas.Dominio.Interfaces.Repositorios; using Cs_Notas.Dominio.Interfaces.Servicos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Dominio.Servicos { public class ServicoEscrituras: ServicoBase<Escrituras>, IServicoEscrituras { private readonly IRepositorioEscrituras _repositorioEscrituras; public ServicoEscrituras(IRepositorioEscrituras repositorioEscrituras) : base(repositorioEscrituras) { _repositorioEscrituras = repositorioEscrituras; } public Escrituras ObterEscrituraPorSeloLivroFolhaAto(string selo, string aleatorio, string livro, int folhainicio, int folhaFim, int ato) { return _repositorioEscrituras.ObterEscrituraPorSeloLivroFolhaAto(selo, aleatorio, livro, folhainicio, folhaFim, ato); } public List<Escrituras> ObterEscriturasPorPeriodo(DateTime dataInicio, DateTime dataFim) { return _repositorioEscrituras.ObterEscriturasPorPeriodo(dataInicio, dataFim); } public List<Escrituras> ObterEscriturarPorLivro(string livro) { return _repositorioEscrituras.ObterEscriturarPorLivro(livro); } public List<Escrituras> ObterEscriturarPorAto(int numeroAto) { return _repositorioEscrituras.ObterEscriturarPorAto(numeroAto); } public List<Escrituras> ObterEscriturarPorSelo(string selo) { return _repositorioEscrituras.ObterEscriturarPorSelo(selo); } public List<Escrituras> ObterEscriturarPorParticipante(List<int> idsAto) { return _repositorioEscrituras.ObterEscriturarPorParticipante(idsAto); } } }
using UnityEngine; using System.Collections; public class PlayerBulletController : MonoBehaviour { // Will be populated automatically when the bullet is created in PlayerStateListener public GameObject playerObject = null; public float bulletSpeed = 15.0f; private float selfDestructTimer = 0.0f; public void lauchBullet() { // The local scale of the player object tells us which // diretion the player is looking. Rather than programming in extra // variables to store where the player is looking, just check what // already knows that information... the object scale! float mainXScale = playerObject.transform.localScale.x; Vector2 bulletForce; if (mainXScale < 0.0f) { // Fire bullet left bulletForce = new Vector2(bulletSpeed * -1.0f, 0.0f); } else { // Fire bullet right bulletForce = new Vector2(bulletSpeed, 0.0f); } GetComponent<Rigidbody2D>().velocity = bulletForce; selfDestructTimer = Time.time + 1.0f; } void Update() { if (selfDestructTimer > 0.0f) { if (selfDestructTimer < Time.time) { Destroy(gameObject); } } } }
using UnityEngine; public class Controlledbykeyboard : MonoBehaviour { public float step = 6.0f; // Update is called once per frame void Update() { Vector3 newPos = this.transform.position; if (Input.GetKeyDown(KeyCode.RightArrow)) newPos.z = Mathf.Round(newPos.z + step); if (Input.GetKeyDown(KeyCode.LeftArrow)) newPos.z = Mathf.Round(newPos.z - step); if (newPos.z <= 9.0f && newPos.z >= -3.0f) this.transform.position = newPos; } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; namespace DMS.Utils { public class clsIOUtil { public static String GenerateTempFolderName(String zipFile) { FileInfo file = new FileInfo(zipFile); String folder = file.DirectoryName; String tmpFolder = folder + "/Tmp"; if (!Directory.Exists(tmpFolder)) { return tmpFolder; } else { int i = 0; while (true) { String str = tmpFolder + i; if (!Directory.Exists(str)) return str; else i++; } } } public static String GetFirstFile(String folder) { DirectoryInfo dir = new DirectoryInfo(folder); if (!dir.Exists) return null; FileInfo[] files = dir.GetFiles(); if (files.Length == 0) return null; return files[0].FullName; } public static void DeleteFolder(String folder) { DirectoryInfo dir = new DirectoryInfo(folder); if (!dir.Exists) return; FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) file.Delete(); DirectoryInfo[] subDirs = dir.GetDirectories(); foreach (DirectoryInfo subDir in subDirs) { DeleteFolder(subDir.FullName); } dir.Delete(); } public static DataSet ReadZipFile(String filename) { FileInfo file = new FileInfo(filename); String tmpFolder = GenerateTempFolderName(file.FullName); Directory.CreateDirectory(tmpFolder); clsCryptography crypto = new clsCryptography(); String pwd = crypto.GenPWDByFilename(file.Name); clsZip.UnzipFile(file.FullName, tmpFolder, pwd); String filename2 = GetFirstFile(tmpFolder); DataSet ds = new DataSet(); ds.ReadXml(filename2); DeleteFolder(tmpFolder); return ds; } public static void SaveZipFile2(DataSet ds, String filename) { ds.WriteXml(filename, XmlWriteMode.WriteSchema); FileInfo file = new FileInfo(filename); String nameWithoutExt = GetNameWithoutExt(file.Name); String newName = file.DirectoryName + "/" + nameWithoutExt + ".zip"; clsCryptography crypto = new clsCryptography(); String pwd = crypto.GenPWDByFilename(newName); clsZip.ZipFiles(filename, newName, pwd); file.Delete(); } public static void SaveZipFile(DataSet ds, String filename) { FileInfo file = new FileInfo(filename); String nameWithoutExt = GetNameWithoutExt(file.Name); String newName = file.DirectoryName + "/" + nameWithoutExt + ".xml"; ds.WriteXml(newName, XmlWriteMode.WriteSchema); clsCryptography crypto = new clsCryptography(); String pwd = crypto.GenPWDByFilename(filename); clsZip.ZipFiles(newName, filename, pwd); File.Delete(newName); } public static String GetNameWithoutExt(String filename) { int i = filename.LastIndexOf('.'); if (i < 0) return filename; else { String str = filename.Substring(0, i); return str; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using System.Reflection; using System.Windows; namespace SoundServant { /// <summary> /// Interaction logic for App.xaml /// </summary> partial class App : Application { void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Logs.Error("FATAL UNHANDLED ERROR", "Sound Servant has encountered and unhandled error. It is vital that you report this error to your Sound Servant. Thank You.", e.ExceptionObject.ToString()); Process.Start(System.Reflection.Assembly.GetExecutingAssembly().CodeBase); ((Process)Process.GetCurrentProcess()).Kill(); } private void Application_Startup(object sender, StartupEventArgs e) { if (e.Args.Length == 0 || e.Args[0] != "DEGBUG") { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; namespace TrumpTown.Hubs { public class ScoreHub : Hub { private static ScoreTable _table = new ScoreTable(); public ScoreHub() { //Simple intialiser for getting the signals working. Need to get stuff from Mongo if (_table.Scores.Count < 1) { _table.Scores.Add(new PlayerScore() { Username = "Username 1", Score = 0 }); _table.Scores.Add(new PlayerScore() { Username = "Username 2", Score = 0 }); _table.Scores.Add(new PlayerScore() { Username = "Username 3", Score = 0 }); } } //probably not need. Would be invoked by logic in card hub public void RecordPlayerWin(string username) { _table.RecordPlayerWin(username); Clients.All.GetUpdatedScoreBoard(); } public void GetScores() { var json = new JavaScriptSerializer().Serialize(_table); Clients.All.OnScores(json); } } public class ScoreTable { public ScoreTable() { Scores = new List<PlayerScore>(); } public List<PlayerScore> Scores { get; set; } public void RecordPlayerWin(string username) { var player = Scores.Where(x => x.Username == username).First(); if (player != null) { player.Score += 10; } Scores = Scores.OrderByDescending(x => x.Score).ToList(); } } public class PlayerScore { public string Username { get; set; } public int Score { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Allyn.Application.Dto.Manage.Basic { /// <summary> /// 表示菜单实体的数据传输对象. /// </summary> [DataContractAttribute(Namespace = "http://www.allyn.com.cn/menu-dto")] public class MenuDto { /// <summary> /// 获取或设置菜单标识. /// </summary> [DataMemberAttribute(Order = 0)] public Guid Id { get; set; } /// <summary> /// 获取或设置菜单的父级. /// </summary> [DataMemberAttribute(Order = 1)] public Guid ParentKey { get; set; } /// <summary> /// 获取或设置菜单的父级. /// </summary> [DataMemberAttribute(Order = 2)] public string ParentName { get; set; } /// <summary> /// 获取或设置菜单名称. /// </summary> [DataMemberAttribute(Order = 3)] public string Name { get; set; } /// <summary> /// 获取或设置菜单连接路径. /// </summary> [DataMemberAttribute(Order = 4)] public string Url { get; set; } /// <summary> /// 获取或设置图标Class. /// </summary> [DataMemberAttribute(Order = 5)] public string Ico { get; set; } /// <summary> /// 获取或设置备注信息. /// </summary> [DataMemberAttribute(Order = 6)] public string Description { get; set; } /// <summary> /// 获取或设置创建时间. /// </summary> [DataMemberAttribute(Order = 7)] public DateTime CreateDate { get; set; } /// <summary> /// 获取或设置更新时间. /// </summary> [DataMemberAttribute(Order = 8)] public DateTime? UpdateDate { get; set; } /// <summary> /// 获取或设置锁定标识. /// </summary> [DataMemberAttribute(Order = 9)] public bool Disabled { get; set; } /// <summary> /// 获取或设置排序 /// </summary> [DataMemberAttribute(Order = 10)] public int Sort { get; set; } /// <summary> /// 获取或设置创建人. /// </summary> [DataMemberAttribute(Order = 11)] public Guid Creater { get; set; } /// <summary> /// 获取或设置修改者. /// </summary> [DataMemberAttribute(Order = 12)] public Guid? Modifier { get; set; } /// <summary> /// 获取或设置子菜单. /// </summary> [DataMemberAttribute(Order = 13)] public List<MenuDto> Children { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using UI.Entidades; using UI.Data; namespace UI.Models { public class BusInscripcion { public Response<List<Evento>> EventosConBus() { Response<List<Evento>> result = new Response<List<Evento>>(); result.code = -1; result.message = "Ocurrio un Error en Base de Datos al tratar de Obtener el Listado de Eventos"; result.data = new List<Evento>(); result.totalRecords = 0; try { using (var db = new EntitiesEvento()) { StringBuilder strSQL = new StringBuilder(); strSQL.Append(" select distinct ev.id_evento, ev.nombre_evento "); strSQL.Append(" from evento ev, bus_evento be "); strSQL.Append(" where ev.id_evento = be.id_evento "); strSQL.Append(" and ev.estado_registro = 'A' "); var list = db.Database.SqlQuery<Evento>(strSQL.ToString()).ToList<Evento>(); foreach (var item in list) { result.data.Add(item); } result.totalRecords = list.Count(); } result.code = 0; result.message = "Ok"; return result; } catch (Exception ex) { result.code = -1; result.message = "Ocurrio una Excepcion al tratar de obtener el Listado de Eventos"; result.messageError = ex.ToString(); return result; } } public Response<List<Participante>> ParticipantesPorEvento(decimal evento) { Response<List<Participante>> result = new Response<List<Participante>>(); result.code = -1; result.message = "Ocurrio un Error en Base de datos al tratar de obtener el Listado de Participantes"; result.data = new List<Participante>(); result.totalRecords = 0; try { using (var db = new EntitiesEvento()) { StringBuilder strSQL = new StringBuilder(); strSQL.Append(" select insc.id_participante id, insc.id_evento idevento, pa.nombre||' '||pa.apellido nombrec "); strSQL.Append(" from inscripcion insc, participante pa "); strSQL.Append(" where insc.id_participante = pa.id_participante "); strSQL.Append(" and insc.id_evento = :id_evento "); strSQL.Append(" order by pa.apellido "); var list = db.Database.SqlQuery<Participante>(strSQL.ToString(), new object[] { evento }).ToList<Participante>(); foreach (var item in list) { result.data.Add(item); } result.totalRecords = list.Count(); } result.code = 0; result.message = "Ok"; return result; } catch (Exception ex) { result.code = -1; result.message = "Ocurrio una Excepcion al momento de Obtener el Listado de Participantes"; result.messageError = ex.ToString(); return result; } } public Response<List<Bus>> BusesEvento(decimal evento) { Response<List<Bus>> result = new Response<List<Bus>>(); result.code = -1; result.message = "Ocurrio un Error en Base de Datos al obtener los Buses"; result.data = new List<Bus>(); result.totalRecords = 0; try { using (var db = new EntitiesEvento()) { StringBuilder strSQL = new StringBuilder(); strSQL.Append(" select id_evento, id_bus, no_bus, capacidad, disponible, ocupado, hora_salida "); strSQL.Append(" from bus_evento "); strSQL.Append(" where id_evento = :id_evento "); var list = db.Database.SqlQuery<Bus>(strSQL.ToString(), new object[] { evento }).ToList<Bus>(); foreach (var item in list) { result.data.Add(item); } result.totalRecords = list.Count(); } result.code = 0; result.message = "Ok"; return result; } catch (Exception ex) { result.code = -1; result.message = "Ocurrio una Excepcion al tratar de obtener el listado de Buses"; result.messageError = ex.ToString(); return result; } } } }
using CG.MovieApp.DataAccess.Interfaces.Dal; using CG.MovieAppEntity.Entities; using System; using System.Collections.Generic; using System.Text; namespace CG.MovieApp.DataAccess.Concrate.EntityFrameworkCore.Repository { public class FilmRepository:EfGenericRepository<Film>,IFilmDal { } }
using System; namespace Compiler.Exceptions { public class InvalidReturnParentException : Exception { public InvalidReturnParentException() { } public InvalidReturnParentException(string message) : base(message) { Message = message; } public override string Message { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace UI { internal class MyFormExc03 : Form { private string[] Colors = { "Red", "Yellow", "Blue", "Green" }; public MyFormExc03() : base() { Width = 300; Height = 300; Text = "Coloring Square"; ComboBox lists = new ComboBox(); lists.Font = new Font("Comic Sans MS", 13, FontStyle.Bold); lists.Location = new Point(25, 25); lists.Items.AddRange(Colors); lists.Text = "Red"; Controls.Add(lists); Label coloredLabel = new Label(); coloredLabel.SetBounds(lists.Right+10,lists.Top,50,50); coloredLabel.BorderStyle = BorderStyle.Fixed3D; coloredLabel.BackColor = Color.Red; Controls.Add(coloredLabel); lists.SelectedIndexChanged += (x, y) => { int index = lists.SelectedIndex; switch (index) { case 0: coloredLabel.BackColor = Color.Red; break; case 1: coloredLabel.BackColor = Color.Yellow; break; case 2: coloredLabel.BackColor = Color.Blue; break; case 3: coloredLabel.BackColor = Color.Green; break; default: coloredLabel.BackColor = Color.Red; break; } }; } } internal class Exc03 { [STAThread] public static void ExcMain03() { Application.Run(new MyFormExc03()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InheritanceAssignment { class Game { int numOfPlayers; string country; public int NumOfPlayers { get { return numOfPlayers; } set { numOfPlayers = value; } } public string Country { get { return country; } set { country = value; } } public Game() { } public Game(int _numOfPlayers, string _country) { numOfPlayers = _numOfPlayers; country = _country; } public string WorldCup() { DateTime now = DateTime.Today; return "WordCup : "+ now.ToString("yyyy"); } } class Cricket : Game { string coachName; public string CoachName { get { return coachName; } set { coachName = value; } } public Cricket() {} public Cricket(int _numOfplayers,string _country,string _coachName):base(_numOfplayers,_country) { coachName = _coachName; } } class Football : Game { string leagueName; public string LeagueName { get { return leagueName; } set { leagueName = value; } } public Football() {} public Football(int _numOfplayers,string _country,string _leagueName) :base(_numOfplayers,_country) { leagueName = _leagueName; } } class ShowGameDetails { public void ShowCricketDetails() { Console.WriteLine("----------CRICKET INFORMATION-----------"); } public void ShowFootBallDetails() { Console.WriteLine("---------FOOTBALL INFORMATION-----------"); } } class Program { static void Main(string[] args) { Cricket c = new Cricket(); c.Country = "India"; c.NumOfPlayers = 11; c.CoachName = "John Wright"; ShowGameDetails sh = new ShowGameDetails(); sh.ShowCricketDetails(); Console.WriteLine("Country : {0} No. Of Players : {1} Coach Name : {2}",c.Country,c.NumOfPlayers,c.CoachName); c.Country = "Australia"; c.NumOfPlayers = 11; c.CoachName = "John Buchanan"; Console.WriteLine("Country : {0} No. Of Players : {1} Coach Name : {2}", c.Country, c.NumOfPlayers, c.CoachName); sh.ShowFootBallDetails(); Football f = new Football(); f.Country = "Spain"; f.NumOfPlayers = 14; f.LeagueName = "Spanish League"; Console.WriteLine("Country : {0} No. Of Players : {1} Coach Name : {2}", f.Country, f.NumOfPlayers, f.LeagueName); f.Country = "England"; f.NumOfPlayers = 13; f.LeagueName = "English Premiur League"; Console.WriteLine("Country : {0} No. Of Players : {1} Coach Name : {2}", f.Country, f.NumOfPlayers, f.LeagueName); Game g = new Game(); Console.WriteLine(" "); Console.WriteLine("Australia have Won Cricket {0}",g.WorldCup()); Console.WriteLine("Spain have Won Cricket {0}", g.WorldCup()); Console.ReadLine(); } } }
using FluentValidation.TestHelper; using NUnit.Framework; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using SFA.DAS.ProviderCommitments.Web.Validators.Apprentice; using System; using System.Linq.Expressions; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Validators.Apprentice { [TestFixture] public class ConfirmEmployerRequestValidatorTests { [TestCase(0, false)] [TestCase(1, true)] public void ThenProviderIdIsValidated(long providerId, bool expectedValid) { var request = new ConfirmEmployerRequest { ProviderId = providerId }; AssertValidationResult(x => x.ProviderId, request, expectedValid); } private void AssertValidationResult<T>(Expression<Func<ConfirmEmployerRequest, T>> property, ConfirmEmployerRequest instance, bool expectedValid) { var validator = new ConfirmEmployerRequestValidator(); if (expectedValid) { validator.ShouldNotHaveValidationErrorFor(property, instance); } else { validator.ShouldHaveValidationErrorFor(property, instance); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Bb.Wordings { /// <summary> /// Evaluate two <see cref="Bb.Wordings.WordType" /> /// </summary> /// <seealso cref="System.Collections.Generic.IEqualityComparer{Bb.Wordings.WordType}" /> public class WordTypeComparer : IEqualityComparer<WordType> { /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <param name="x">The first object of type T to compare.</param> /// <param name="y">The second object of type T to compare.</param> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> public bool Equals(WordType x, WordType y) { return x.Text == y.Text; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <param name="obj">The object.</param> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public int GetHashCode(WordType obj) { return obj.Text.GetHashCode(); } } }
namespace NetEscapades.AspNetCore.SecurityHeaders.Infrastructure { /// <summary> /// Various constant values used internally /// </summary> internal static class Constants { /// <summary> /// A key for the per-request nonce /// </summary> internal const string DefaultNonceKey = "NETESCAPADES_NONCE"; /// <summary> /// The default number of bytes to use for generating a nonce /// </summary> internal const int DefaultBytesInNonce = 32; /// <summary> /// A key for per-request hashes for script-src /// </summary> internal const string DefaultScriptHashKey = "NETESCAPADES_HASHES_SCRIPT"; /// <summary> /// A key for per-request hashes for styles-src /// </summary> internal const string DefaultStylesHashKey = "NETESCAPADES_HASHES_STYLES"; } }
using System; namespace Parliament.ProcedureEditor.Web.Models { public class BusinessItemCandidateModel { public int WorkPackagedId { get; set; } public string WorkPackagedTripleStoreId { get; set; } public string WorkPackagedThingName { get; set; } public string ProcedureName { get; set; } public DateTimeOffset? MadeDate { get; set; } public DateTimeOffset? LaidDate { get; set; } public string WebUrl { get; set; } public int? Number { get; set; } public string Prefix { get; set; } public int ProcedureId { get; set; } } }
using System.Threading.Tasks; using TellMeMoreBlazor.Models.urlscanio; namespace TellMeMoreBlazor.Interfaces { public interface IUrlScanIoService { Task<urlScanIoNewScanResponse> PostAsync(string hostName); Task<urlScanIo> GetStatusAsync(string uuid); } }
// removed 2022-12-13
using System.Linq; using System.Collections.Generic; using System; namespace SchemaObjectMapper { public class FixedWidthSchemaObjectMapper<T> : ISchemaObjectMapper<T> where T : new() { private readonly ISchema _schema; public FixedWidthSchemaObjectMapper(ISchema schema) { this._schema = schema; } public T MapLine(string line) { var obj = new T(); foreach (FixedWidthMapping<T> mapping in this._schema.Mappings) { var rawValue = line.Substring(mapping.Start, mapping.Length); var value = Convert.ChangeType(mapping.Trim ? rawValue.Trim() : rawValue, mapping.PropertyInfo.PropertyType); mapping.PropertyInfo.SetValue(obj, value, null); } return obj; } } }
using System; using Messaging.Validators; using Messaging.Resolvers; using Xunit; namespace Messaging.Validators.Tests { public class SchemaValidatorTests { private readonly IResourceResolver _localResolver; public SchemaValidatorTests() { _localResolver = EmbeddedResourceResolver.Create(AssemblyType.Caller); } [Theory] [InlineData("POCD_IN150001UK06.xsd")] [InlineData("POCD_IN150001UK06")] public void Validate_NormalCall(string filename) { var schemaValidator = new SchemaValidator(new EmbeddedResourceResolver(typeof(Mim.V6301.POCD_IN150001UK06).Assembly)); var result =schemaValidator.Validate(filename, _localResolver.GetResourceStream("POCD_EX150001UK06_05.xml").GetText()); Assert.True(result.Status); } [Fact] public void Validate_SpecifyingUsingSchemaNames_NormalCall() { var schemaValidator = new SchemaValidator(new EmbeddedResourceResolver(typeof(Mim.V6301.POCD_IN150001UK06).Assembly)); var result = schemaValidator.Validate(Mim.V6301.SchemaNames.POCD_MT000001UK04.ToString(), _localResolver.GetResourceStream("POCD_EX150001UK06_05.xml").GetText()); Assert.True(result.Status); } [Fact] public void Validate_Failed() { var schemaValidator = new SchemaValidator(new EmbeddedResourceResolver(typeof(Mim.V6301.POCD_IN150001UK06).Assembly)); var result = schemaValidator.Validate("POCD_IN150001UK06.xsd", _localResolver.GetResourceStream("POCD_EX150001UK06_05Invalid.xml").GetText()); Assert.False(result.Status); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace StudyManagement.StudyManagement { public partial class ContactUs : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnRqusetInfoSubmit_Click(object sender, EventArgs e) { string connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; SqlConnection con = new SqlConnection(connectionString); string name = txt_usr_name.Text; string email = txt_usr_email.Text; string msg = txt_usr_msg.Text; SqlCommand cmd = new SqlCommand("SP_ContactUsMsg", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", name); cmd.Parameters.AddWithValue("@Email", email); cmd.Parameters.AddWithValue("@Message", msg); con.Open(); int result = cmd.ExecuteNonQuery(); con.Close(); if (result == 1) { Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Message sent successfully');</script>"); GetClear(); } else { Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Message not sent! try again!');</script>"); GetClear(); } } private void GetClear() { txt_usr_name.Text = ""; txt_usr_email.Text = ""; txt_usr_msg.Text = ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using System.Threading.Tasks; using DFC.ServiceTaxonomy.ContentApproval.Models; using DFC.ServiceTaxonomy.ContentApproval.Models.Enums; using DFC.ServiceTaxonomy.ContentApproval.ViewModels; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Localization; using OrchardCore.Contents.ViewModels; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; namespace DFC.ServiceTaxonomy.ContentApproval.Drivers { public class ContentApprovalContentsAdminListFilterDisplayDriver : DisplayDriver<ContentOptionsViewModel> { private readonly IStringLocalizer S; public ContentApprovalContentsAdminListFilterDisplayDriver( IStringLocalizer<ContentApprovalContentsAdminListFilterDisplayDriver> stringLocalizer) { S = stringLocalizer; } protected override void BuildPrefix(ContentOptionsViewModel model, string htmlFieldPrefix) { Prefix = Constants.ContentApprovalPartPrefix; } public override IDisplayResult Display(ContentOptionsViewModel model) { return Combine( View("ContentsAdminFilters_Thumbnail__ReviewStatus", model).Location("Thumbnail", "Content:50"), View("ContentsAdminFilters_Thumbnail__ReviewType", model).Location("Thumbnail", "Content:60")); } public override IDisplayResult Edit(ContentOptionsViewModel model, IUpdateModel updater) { return Initialize<ContentApprovalContentsAdminListFilterViewModel>("ContentsAdminList__ContentApprovalFilter", m => { model.FilterResult.MapTo(m); var reviewStatuses = new List<SelectListItem> { new SelectListItem { Text = S["All review statuses"], Value = "", Selected = string.IsNullOrEmpty(m.SelectedReviewStatus?.ToString())}, }; reviewStatuses.AddRange(GetSelectList(typeof(ReviewStatusFilterOptions), m.SelectedReviewStatus?.ToString())); m.ReviewStatuses = reviewStatuses; var reviewTypes = new List<SelectListItem> { new SelectListItem { Text = S["All reviewer types"], Value = "" , Selected = string.IsNullOrEmpty(m.SelectedReviewType?.ToString())}, }; reviewTypes.AddRange(GetSelectList(typeof(ReviewType), m.SelectedReviewType?.ToString())); m.ReviewTypes = reviewTypes; }).Location("Actions:20"); } private static IEnumerable<SelectListItem> GetSelectList(Type enumType, string? selectedValue) { FieldInfo[] enumFields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); return enumFields.Select(fi => (fi, da: fi.GetCustomAttribute<DisplayAttribute>())) .OrderBy(v => v.da?.Order ?? -1) .Select(v => new SelectListItem(v.da?.Name ?? v.fi.Name, v.fi.Name.ToLower(), !string.IsNullOrEmpty(selectedValue) && v.fi.Name.Equals(selectedValue, StringComparison.InvariantCultureIgnoreCase))); } public override async Task<IDisplayResult> UpdateAsync(ContentOptionsViewModel model, IUpdateModel updater) { var viewModel = new ContentApprovalContentsAdminListFilterViewModel(); if(await updater.TryUpdateModelAsync(viewModel, Constants.ContentApprovalPartPrefix)) { model?.FilterResult?.MapFrom(viewModel); } // Code conventions in STAX clashing with Orchard Core approach #pragma warning disable AsyncFixer02 // Long-running or blocking operations inside an async method #pragma warning disable CS8604 // Possible null reference argument. return Edit(model, updater); #pragma warning restore CS8604 // Possible null reference argument. #pragma warning restore AsyncFixer02 // Long-running or blocking operations inside an async method } } }
using Allure.Commons; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Remote; using System; using System.IO; namespace TUT.by.Tests { public class BaseTest : AllureReport { private readonly string Url = "https://www.tut.by/"; public IWebDriver driver; [SetUp] public void SetUp() { driver = new ChromeDriver(); ChromeOptions Options = new ChromeOptions(); Options.PlatformName = "WIN10"; driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), Options.ToCapabilities(), TimeSpan.FromSeconds(25000)); driver.Navigate().GoToUrl(Url); driver.Manage().Window.Maximize(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15); // Implicit waiter for WebDriver. } [TearDown] public void TearDown() { if (TestContext.Out == TestContext.Error) { TakeScreenshot(); } driver.Quit(); } public void TakeScreenshot() { Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot(); screenshot.SaveAsFile(Path.Combine(Environment.CurrentDirectory, "Screenshot " + TestContext.CurrentContext.Test.MethodName.ToString()), ScreenshotImageFormat.Jpeg); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Linq; namespace clustering { public class DBSCAN { private DataBase db = null; public DataBase DB { set { db = value; } } private float epsilon = 0; public float Epsilon { get { return epsilon; } set { if (value >= 0){ epsilon = value; } else { Console.WriteLine("epsilon must be positive"); } } } private int minPts = 0; public int MinPts { get { return minPts; } set { if (value >= 0) { minPts = value; } else { Console.WriteLine("minPts must be positive"); } } } private List<Point> noiseList; private List<Cluster> clusterList; public DBSCAN () { noiseList = new List<Point>(); clusterList = new List<Cluster>(); } public void RemoveOutput (string inputFile) { char[] array = inputFile.ToArray(); int inputNum = (int)Char.GetNumericValue(array[5]); for (int i=0; i<clusterList.Count; ++i) { File.Delete("output" + inputNum + "_cluster_" + i + ".txt"); } } private float GoodEpsilon (string inputFile) { float eps = 0; switch (inputFile) { case "input1.txt": eps = 11.90F; break; case "input2.txt": eps = 4.40F; break; case "input3.txt": eps = 6.65F; break; default: eps = 3.00F; break; } return eps; } private int GoodMinPts (string inputFile) { int minPoints = 0; switch (inputFile) { case "input1.txt": minPoints = 15; break; case "input2.txt": minPoints = 65; break; case "input3.txt": minPoints = 10; break; default: minPoints = 10; break; } return minPoints; } public void Clustering(string inputFile, int clusterNum) { float score = 0; Epsilon = GoodEpsilon(inputFile); MinPts = GoodMinPts(inputFile); DoDBSCAN(clusterNum); WriteOutput(inputFile); // do // { // db.Initialize(); // DoDBSCAN(); // WriteOutput(inputFile); // // score = Globals.ClusteringScore(inputFile); // // Console.WriteLine(inputFile + "-> Eps: " + Epsilon + ", MinPts: " + // MinPts + ", score: " + score + ", # of clusters: " + clusterList.Count); // // Epsilon += 0.05F; // RemoveOutput(inputFile); // // if (score >= 99.99) // break; //// if (clusterList.Count < clusterNum) //// break; // } // while(true); // WriteOutput(inputFile); } public void DoDBSCAN(int clusterNum) { clusterList = new List<Cluster>(); for (int i=0; i<db.Count(); ++i) { Point p = db[i]; if (p.Processed == false) { p.Processed = true; var neighbors = db.Neighbors(p, Epsilon); if (neighbors.Count < MinPts) noiseList.Add(p); else { Cluster cluster = new Cluster(); ExpandCluster(p, cluster, neighbors); clusterList.Add(cluster); } } } TrimClusters(clusterNum); } /// <summary> Remove clusters with smallest # of points</summary> public void TrimClusters(int clusterNum) { while (clusterList.Count > clusterNum) { int min = clusterList[0].Count; int minIndex = 0; for (int i=0; i<clusterList.Count; ++i) { Cluster c = clusterList[i]; if (min > c.Count) { min = c.Count; minIndex = i; } } clusterList.RemoveAt(minIndex); } } private void ExpandCluster (Point p, Cluster c, List<Point> neighbors) { c.Add(p); p.inCluster = true; // foreach (Point neighbor in neighbors) for (int i=0; i<neighbors.Count; ++i) { Point neighbor = neighbors[i]; if (neighbor.Processed == false) { neighbor.Processed = true; var newNeighbors = db.Neighbors(neighbor, Epsilon); if (newNeighbors.Count >= MinPts) { neighbors = neighbors.Union(newNeighbors).ToList(); } } if (neighbor.inCluster == false) { c.Add(neighbor); neighbor.inCluster = true; } } } public void WriteOutput (string inputFile) { // Console.WriteLine("# of clusters: " + clusterList.Count); char[] array = inputFile.ToArray(); int inputNum = (int)Char.GetNumericValue(array[5]); for (int i=0; i<clusterList.Count; ++i) { var writer = new StreamWriter("output" + inputNum + "_cluster_" + i + ".txt"); Cluster cluster = clusterList[i]; foreach (Point p in cluster) { writer.WriteLine(p.ID.ToString()); } writer.Close(); } } } }
public class Solution { public int Calculate(string s) { return Helper(s, 0).Item1; } public Tuple<int, int> Helper(string s, int start) { if (start >= s.Length) return new Tuple<int, int>(0, start); int res = 0; int i = start; bool isAdd = true; while (i<s.Length) { if (s[i] == ')') return new Tuple<int,int>(res, i); else if (s[i] == '(') { var t = Helper(s, i+1); i = t.Item2; res += (isAdd ? 1 : (-1)) * t.Item1; } else if (s[i] <= '9' && s[i] >= '0') { int tmp = i; while (i+1 < s.Length && s[i+1] <= '9' && s[i+1] >= '0') { i++; } res += (isAdd ? 1 : (-1)) * Int32.Parse(s.Substring(tmp, i+1-tmp)); } else if (s[i] == '+') { isAdd = true; } else if (s[i] == '-') { isAdd = false; } i++; } return new Tuple<int, int>(res, i); } }
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Moq; using NUnit.Framework; using Properties.Core.Interfaces; using Properties.Core.Objects; using Properties.Core.Services; namespace Properties.Tests.UnitTests.Services { [TestFixture] // ReSharper disable once InconsistentNaming public class VideoService_TestFixture { private const string Reference = "ABCD1234"; private Mock<IReferenceGenerator> _mockReferenceGenerator; private Mock<IVideoRepository> _mockRepository; private VideoService _videoService; [SetUp] public void Setup() { _mockReferenceGenerator = new Mock<IReferenceGenerator>(); _mockRepository = new Mock<IVideoRepository>(); _videoService = new VideoService(_mockRepository.Object, _mockReferenceGenerator.Object); } [Test] public void VideoService_NullRepository_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => new VideoService(null, _mockReferenceGenerator.Object)); } [Test] public void VideoService_NullReferenceGenerator_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => new VideoService(_mockRepository.Object, null)); } [Test] public void GetVideosForProperty_NullPropertyReference_ReturnsNull() { //act Assert.Throws<ArgumentNullException>(() => _videoService.GetVideosForProperty(string.Empty)); } [Test] public void GetVideosForProperty_CallsRepository() { //arrange _mockRepository.Setup(x => x.GetVideosForProperty(Reference)) .Returns(new List<Video> { new Video { } }); //act var result = _videoService.GetVideosForProperty(Reference); //assert result.Should().NotBeNull(); result.Any().Should().BeTrue(); _mockRepository.Verify(x => x.GetVideosForProperty(Reference), Times.Once); } [Test] public void GetVideoForProperty_NullPropertyReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.GetVideoForProperty(string.Empty, Reference)); } [Test] public void GetVideoForProperty_NullVideoReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.GetVideoForProperty(Reference, string.Empty)); } [Test] public void GetVideoForProperty_CallsRepository() { //arrange _mockRepository.Setup(x => x.GetVideoForProperty(Reference, Reference)).Returns(new Video()); //act var result = _videoService.GetVideoForProperty(Reference, Reference); //assert result.Should().NotBeNull(); _mockRepository.Verify(x => x.GetVideoForProperty(Reference, Reference), Times.Once); } [Test] public void CreateVideo_EmptyPropertyReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.CreateVideo(null, new Video())); } [Test] public void CreateVideo_NullVideo_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.CreateVideo(Reference, null)); } [Test] public void CreateVideo_ValidVideo_CallsReferenceGenerator() { //arrange _mockRepository.Setup(x => x.CreateVideo(Reference, It.IsAny<Video>())) .Returns(true); _mockReferenceGenerator.Setup(x => x.CreateReference(It.IsAny<int>())).Returns(Reference); //act var result = _videoService.CreateVideo(Reference, new Video()); //assert result.Should().Be(Reference); _mockReferenceGenerator.Verify(x => x.CreateReference(It.IsAny<int>()), Times.Once); } [Test] public void CreateVideo_ValidVideo_CallsRepository() { //arrange _mockRepository.Setup(x => x.CreateVideo(Reference, It.IsAny<Video>())) .Returns(true); _mockReferenceGenerator.Setup(x => x.CreateReference(It.IsAny<int>())).Returns(Reference); //act var result = _videoService.CreateVideo(Reference, new Video()); //assert result.Should().Be(Reference); _mockRepository.Verify(x => x.CreateVideo(Reference, It.IsAny<Video>()), Times.Once); } [Test] public void UpdateVideo_EmptyPropertyReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.UpdateVideo(null, Reference, new Video())); } [Test] public void UpdateVideo_EmptyVideoReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.UpdateVideo(Reference, null, new Video())); } [Test] public void UpdateVideo_NullVideo_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.UpdateVideo(Reference, Reference, null)); } [Test] public void UpdateVideo_ValidVideo_CallsRepository() { //arrange _mockRepository.Setup(x => x.UpdateVideo(Reference, Reference, It.IsAny<Video>())) .Returns(true); //act var result = _videoService.UpdateVideo(Reference, Reference, new Video()); //assert result.Should().BeTrue(); _mockRepository.Verify(x => x.UpdateVideo(Reference, Reference, It.IsAny<Video>()), Times.Once); } [Test] public void DeleteVideo_EmptyPropertyReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.DeleteVideo(null, Reference)); } [Test] public void DeleteVideo_EmptyVideoReference_ThrowsException() { //act Assert.Throws<ArgumentNullException>(() => _videoService.DeleteVideo(Reference, null)); } [Test] public void DeleteVideo_CallsRepository() { //arrange _mockRepository.Setup(x => x.DeleteVideo(Reference, Reference)) .Returns(true); //act var result = _videoService.DeleteVideo(Reference, Reference); //assert result.Should().BeTrue(); _mockRepository.Verify(x => x.DeleteVideo(Reference, Reference), Times.Once); } } }
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlServerCe; using System.Data.SqlClient; namespace StockAnalyzer { class stockData { DateTime today = DateTime.Today; DateTime beginningDate = DateTime.Now.AddYears(-5); DataTable companyInfo = new DataTable(); public DataTable getData(string symbol) { DataTable stockdata = new DataTable(); //Download csv file for last 5 years, up to last month and save it System.Net.WebClient csvDownloader = new System.Net.WebClient(); string stockUrl = "http://ichart.finance.yahoo.com/table.csv?s="+ symbol+ "&a="+ beginningDate.ToString("MM")+ "&b="+ beginningDate.ToString("dd")+ "&c="+ beginningDate.ToString("yyyy")+ "&d="+ today.ToString("MM")+ "&e="+ today.ToString("dd")+ "&f="+ today.ToString("yyyy")+ "&g=d&ignore=.csv"; //Download 5 years worth of EOD data try { csvDownloader.DownloadFile(stockUrl, "./" + symbol + ".csv"); } catch (Exception e) { Console.WriteLine("{0} Exception Caught.", e); } //DataTable stockData = new DataTable("prices"); stockdata.Columns.Add("date"); stockdata.Columns.Add("open"); stockdata.Columns.Add("high"); stockdata.Columns.Add("low"); stockdata.Columns.Add("close"); stockdata.Columns.Add("volume"); stockdata.Columns.Add("adjVolume"); stockdata.Rows.Clear(); using (StreamReader csvReader = new StreamReader("./" + symbol + ".csv")) { string line; string[] vals; while ((line = csvReader.ReadLine()) != null) { vals = line.Split(','); stockdata.Rows.Add(vals); } } stockdata.Rows[0].Delete(); //stockdata.DefaultView.Sort = "date" + " " + "ASC"; //stockdata = stockdata.DefaultView.ToTable(); //Open database connection string connectionStringLaptop = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\crommie\Dropbox\stock_analyzer\StockAnalyzer_windows\StockAnalyzer\prices.mdf;Integrated Security=True"; string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\aaron\documents\visual studio 2012\Projects\StockAnalyzer\StockAnalyzer\prices.mdf;Integrated Security=True"; SqlConnection db2Connection = new SqlConnection(connectionStringLaptop); db2Connection.Open(); using (SqlCommand cmd = db2Connection.CreateCommand()) { cmd.CommandText = @" IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + symbol + @"') BEGIN DROP TABLE " + symbol + @"; IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + symbol + @"') CREATE TABLE " + symbol + @" ( ID integer PRIMARY KEY NOT NULL IDENTITY, datetime varchar(20), openVal varchar(10), closeVal varchar(10), highVal varchar(10), lowVal varchar(10), volume varchar(20) ); END"; MessageBox.Show(cmd.CommandText); cmd.ExecuteNonQuery(); //try { cmd.ExecuteNonQuery(); } //catch (SqlException) { MessageBox.Show("SQL Exception creating table for company info"); } } //Delete contents of table - may want to rethink this step?? SqlCommand delCmd = new SqlCommand(@"DELETE FROM " + symbol + ";", db2Connection); delCmd.ExecuteNonQuery(); using (SqlBulkCopy copy = new SqlBulkCopy(connectionStringLaptop)) { copy.ColumnMappings.Add("date", "datetime"); copy.ColumnMappings.Add("open", "openVal"); copy.ColumnMappings.Add("close", "closeVal"); copy.ColumnMappings.Add("high", "highVal"); copy.ColumnMappings.Add("low", "lowVal"); copy.ColumnMappings.Add("volume", "volume"); copy.DestinationTableName = symbol; copy.WriteToServer(stockdata); } //Download Company information companyInfo.Columns.Add("symbol"); companyInfo.Columns.Add("openVal"); companyInfo.Columns.Add("ask"); companyInfo.Columns.Add("bid"); companyInfo.Columns.Add("avgDailyVol"); companyInfo.Columns.Add("change"); companyInfo.Columns.Add("eps"); companyInfo.Columns.Add("epsEst"); companyInfo.Columns.Add("dailyLow"); companyInfo.Columns.Add("dailyHigh"); companyInfo.Columns.Add("fiftytwoWeekLow"); companyInfo.Columns.Add("fiftytwoWeekHigh"); companyInfo.Columns.Add("mktCap"); companyInfo.Columns.Add("ps"); companyInfo.Columns.Add("pb"); companyInfo.Columns.Add("pe"); companyInfo.Columns.Add("targetOneYear"); companyInfo.Columns.Add("exchange"); companyInfo.Columns.Add("price"); companyInfo.Columns.Add("tradeTime"); companyInfo.Columns.Add("tradeDate"); companyInfo.Columns.Add("prevClose"); companyInfo.Columns.Add("div"); companyInfo.Columns.Add("divYield"); companyInfo.Columns.Add("name"); //Download csv file with company info and save it System.Net.WebClient csvInfoDownloader = new System.Net.WebClient(); string companyUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" + symbol + @"&f=sob2b3a2c6ee8ghjkj1p5p6rt8xk1t1d1pdy"; try { csvInfoDownloader.DownloadFile(companyUrl, "./" + symbol + "Info" + ".csv"); } catch (Exception e) { Console.WriteLine("{0} Exception Caught.", e); } companyInfo.Rows.Clear(); using (StreamReader csvCompanyReader = new StreamReader("./" + symbol + "Info" + ".csv")) { string line; string[] vals; while ((line = csvCompanyReader.ReadLine()) != null) { vals = line.Split(','); try { companyInfo.Rows.Add(vals); } catch (ArgumentException) { } } } //Download company name and save it System.Net.WebClient csvNameDownloader = new System.Net.WebClient(); string nameUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" + symbol + @"&f=n"; try { csvNameDownloader.DownloadFile(nameUrl, "./" + symbol + "Name" + ".csv"); } catch (Exception e) { Console.WriteLine("{0} Exception Caught.", e); } using (StreamReader csvNameReader = new StreamReader("./" + symbol + "Name" + ".csv")) { string line; while ((line = csvNameReader.ReadLine()) != null) { companyInfo.Rows[0]["name"] = line.Split('"', '"')[1]; } } //Rename Symbol in Table to not have quotes companyInfo.Rows[0]["symbol"] = companyInfo.Rows[0]["symbol"].ToString().Split('"', '"')[1]; using (SqlCommand cmd2 = db2Connection.CreateCommand()) { cmd2.CommandText = @" IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'companyData') BEGIN CREATE TABLE companyData ( ID integer PRIMARY KEY NOT NULL IDENTITY, symbol varchar(10), openVal varchar(20), ask varchar(20), bid varchar(20), avgDailyVol varchar(20), change varchar(20), eps varchar(20), epsEst varchar(20), dailyLow varchar(20), dailyHigh varchar(20), fiftytwoWeekLow varchar(20), fiftytwoWeekHigh varchar(20), mktCap varchar(20), ps varchar(20), pb varchar(20), pe varchar(20), targetOneYear varchar(20), exchange varchar(20), price varchar(30), tradeTime varchar(20), tradeDate varchar(20), prevClose varchar(20), div varchar(20), divYield varchar(20), name varchar(30), ); END"; cmd2.ExecuteNonQuery(); } //Delete contents of table - may want to rethink this step?? MessageBox.Show("About to delete company data"); SqlCommand delCompanyCmd = new SqlCommand(@"DELETE FROM companyData where symbol = '" + symbol + "';", db2Connection); delCompanyCmd.ExecuteNonQuery(); MessageBox.Show("Just deleted company data"); using (SqlBulkCopy copyCompany = new SqlBulkCopy(connectionStringLaptop)) { copyCompany.ColumnMappings.Add("symbol", "symbol"); copyCompany.ColumnMappings.Add("openVal", "openVal"); copyCompany.ColumnMappings.Add("ask", "ask"); copyCompany.ColumnMappings.Add("bid", "bid"); copyCompany.ColumnMappings.Add("avgDailyVol", "avgDailyVol"); copyCompany.ColumnMappings.Add("change", "change"); copyCompany.ColumnMappings.Add("eps", "eps"); copyCompany.ColumnMappings.Add("epsEst", "epsEst"); copyCompany.ColumnMappings.Add("dailyLow", "dailyLow"); copyCompany.ColumnMappings.Add("dailyHigh", "dailyHigh"); copyCompany.ColumnMappings.Add("fiftytwoWeekLow", "fiftytwoWeekLow"); copyCompany.ColumnMappings.Add("fiftytwoWeekHigh", "fiftytwoWeekHigh"); copyCompany.ColumnMappings.Add("mktCap", "mktCap"); copyCompany.ColumnMappings.Add("ps", "ps"); copyCompany.ColumnMappings.Add("pb", "pb"); copyCompany.ColumnMappings.Add("pe", "pe"); copyCompany.ColumnMappings.Add("targetOneYear", "targetOneYear"); copyCompany.ColumnMappings.Add("exchange", "exchange"); copyCompany.ColumnMappings.Add("price", "price"); copyCompany.ColumnMappings.Add("tradeTime", "tradeTime"); copyCompany.ColumnMappings.Add("tradeDate", "tradeDate"); copyCompany.ColumnMappings.Add("prevClose", "prevClose"); copyCompany.ColumnMappings.Add("div", "div"); copyCompany.ColumnMappings.Add("divYield", "divYield"); copyCompany.ColumnMappings.Add("name", "name"); copyCompany.DestinationTableName = "companyData"; copyCompany.WriteToServer(companyInfo); } db2Connection.Close(); return companyInfo; } } }
using Tomelt.ContentManagement; namespace Tomelt.Layouts.Framework.Drivers { public interface IContentImportSession { ContentItem GetItemFromSession(string id); } }
using System; using System.Globalization; using Xamarin.Forms; namespace XF40Demo.Converters { internal class PowerToColour : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return Color.Transparent; } string power = ((string)value).Trim().ToLower(); switch (power) { case "aisling": return "#0099FF"; case "delaine": return "#7FFF00"; case "ald": return "#7F00FF"; case "patreus": return "#00FFFF"; case "mahon": return "#00FF00"; case "winters": return "#FF7F00"; case "lyr": return "#BFFF00"; case "antal": return "#FFFF00"; case "grom": return "#FF4000"; case "hudson": return "#FF0000"; case "torval": return "#0040FF"; default: return Color.Black; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using Discord; using JhinBot.DiscordObjects; using JhinBot.Services; using JhinBot.Enums; using JhinBot.GlobalConst; using JhinBot.Utils; using System.Collections.Generic; using System.Threading.Tasks; using JhinBot.Factories.SubTypeFactories; using JhinBot.Conversation; using Discord.WebSocket; namespace JhinBot { public abstract class EmbedConversation : IEmbedConversation { protected static Dictionary<ConversationType, string> _conversationColors; public ulong UserId { get; } public ulong GuildId { get; } public ulong ChannelId { get; } public int CurrentStep { get; protected set; } = 0; public EmbedBuilder EmbedBuilder { get; private set; } public IUserMessage UserMsg { get; private set; } public ConversationType Type { get; protected set; } = ConversationType.None; public ConversationSubType SubType { get; protected set; } = ConversationSubType.None; protected List<string> _results = new List<string>(); protected List<ConversationStep> _steps = new List<ConversationStep>(); protected readonly IResourceService _resources; protected readonly IEmbedService _embedService; protected readonly IBotConfig _botConfig; protected readonly IDbService _dbService; protected readonly IOwnerLogger _ownerLogger; protected readonly DiscordSocketClient _client; protected string _username; protected string _completionMessage; protected string _modifiedObjectName; protected bool _startKeepingResults = false; protected PagedEmbed _pagedEmbed; private readonly ConvoSubTypeFactory _factory; private readonly IEmote arrowLeft = new Emoji("⬅"); public EmbedConversation(ulong userId, ulong guildId, ulong channelId, string username, IResourceService resources, IEmbedService embedService, IBotConfig botConfig, IDbService dbService, IOwnerLogger ownerLogger, DiscordSocketClient client, ConversationType type, ConversationSubType subType, ConvoSubTypeFactory factory) { UserId = userId; GuildId = guildId; ChannelId = channelId; _username = username; _resources = resources; _embedService = embedService; _botConfig = botConfig; _dbService = dbService; _ownerLogger = ownerLogger; _client = client; _factory = factory; CurrentStep = 0; SubType = subType; Type = type; var resxCompletion = Global.Convo.moduleActionSuccessResxStringName[SubType]; _completionMessage = _resources.GetFormattedString(resxCompletion, new string[] { Type.ToString() }); _conversationColors = new Dictionary<ConversationType, string>() { { ConversationType.None, _botConfig.NoneColor }, { ConversationType.Command, _botConfig.CommandColor }, { ConversationType.Event, _botConfig.EventColor }, }; } public async Task StartConversation(IUserMessage msg) { UserMsg = msg; if (_pagedEmbed != null) await _pagedEmbed.AddReactionsToPagedEmbed(UserMsg, _client); } public void DefineSteps() { _steps = _factory.CreateStepList(this); foreach (var step in _steps) { _results.Add(""); } switch (SubType) { case ConversationSubType.Create: _startKeepingResults = true; RebuildEmbedFields(); break; default: CreateBaseEmbedBuilder(); BuildObjectListEmbed(); break; } } public async Task<bool> TryHandlingInput(string input) { var result = _steps[CurrentStep].Execute(input); if (result.success) { if (_startKeepingResults) { _results[CurrentStep] = input; ++CurrentStep; } else { _steps.RemoveAt(0); _pagedEmbed = null; StoreObjectValuesPreModification(input); } if (!IsCurrentSubTypeDelete()) RebuildEmbedFields(); else RebuildDeleteEmbed(); } else if (!IsCurrentStepConfirmType()) { await ModifyEmbedDescription($"{result.errorMsg}\n\n{GetCurrentStepMessage()}"); } else { return true; } return ValidateEmbedCompletion(); } public virtual async Task EndConversation() { if (ValidateEmbedCompletion()) await ModifyEmbedDescription(_completionMessage); else if (IsCurrentStepConfirmType()) await ModifyEmbedDescription(_resources.GetString("conv_confirmfail_desc")); else await ModifyEmbedDescription(_resources.GetString("conv_earlyexit_desc")); } //Create/Update input steps protected void RebuildEmbedFields() { CreateBaseEmbedBuilder(); var stepMessage = ValidateEmbedCompletion() ? _completionMessage : GetCurrentStepMessage(); EmbedBuilder.WithDescription(stepMessage); for (var i = 0; i < _steps.Count; ++i) { //Consider changing this to avoid rebuilding everything? var stepType = _steps[i].StepType.ToString(); if (!IsStepAtIndexConfirmType(i)) { if (_results[i] != "") { if (i == CurrentStep) EmbedBuilder.AddCurrentResultField(stepType, _results[i]); else EmbedBuilder.AddResultField(stepType, _results[i]); } else { if (i == CurrentStep) EmbedBuilder.AddCurrentStepField(stepType); else EmbedBuilder.AddEmptyField(stepType); } } } } public virtual async Task CloseConversation() { if (UserMsg != null) await UserMsg.DeleteAfterShort(); } protected void CreateBaseEmbedBuilder() { EmbedBuilder = _embedService.CreateEmbed($"{Type} conversation for: {_username} | **{SubType}**", _conversationColors[Type], null, "", _botConfig.RoundAvatarUrl, _resources.GetFormattedString("conv_exit_footer", new string[] { Global.Params.CONVO_EXIT_STR })); } protected void FillResultList() { while (_steps.Count > _results.Count) { _results.Add(""); } } private async Task ModifyEmbedDescription(string text) { await Task.Run(() => { EmbedBuilder.WithDescription(text); }); } //public async Task AddReactionsToConversation() //{ //await UserMsg.AddReactionAsync(arrowLeft); //Action<SocketReaction> changePage = async r => //{ // try // { // if (r.UserId != _client.CurrentUser.Id && r.UserId == UserId) // { // if (r.Emote.Name == arrowLeft.Name) // { // if (currentPage == 0) // return; // ChangeEmbedPage(--currentPage); // await msg.ModifyAsync(x => x.Embed = EmbedBuilder.Build()).ConfigureAwait(false); // } // else if (r.Emote.Name == arrowRight.Name) // { // if (currentPage + 1 < GetPageCount()) // { // ChangeEmbedPage(++currentPage); // await msg.ModifyAsync(x => x.Embed = EmbedBuilder.Build()).ConfigureAwait(false); // } // } // } // } // catch (Exception e) // { // await _ownerLogger.LogExceptionAsEmbed(e); // } //}; //using (msg.OnReaction(client, changePage, changePage)) //{ // await Task.Delay(300000).ConfigureAwait(false); //} //await msg.RemoveAllReactionsAsync().ConfigureAwait(false); //} protected string GetCurrentStepMessage() => _steps[CurrentStep].StepMessage; protected bool ValidateEmbedCompletion() => CurrentStep > _steps.Count - 1; protected bool IsCurrentStepConfirmType() => _steps[CurrentStep].StepType == StepType.Confirm; protected bool IsStepAtIndexConfirmType(int index) => _steps[index].StepType == StepType.Confirm; protected bool IsCurrentSubTypeDelete() => SubType == ConversationSubType.Delete; protected abstract void StoreObjectValuesPreModification(string input); //Delete embed rebuild (no steps available) protected abstract void RebuildDeleteEmbed(); //Update/Delete first step protected abstract void BuildObjectListEmbed(); } }
using OctoFX.Core.Model; namespace OctoFX.Core.Repository { public interface IQuoteRepository : IOctoFXRepository<Quote> { } public class QuoteRepository : OctoFXRepository<Quote>, IQuoteRepository { public QuoteRepository(OctoFXContext context) { Context = context; } } }
namespace BenefitDeduction.EmployeeBenefitDeduction { public interface IBenefitDeductionItem { int EmployeeId { get; } int FamilyMemberId { get; } string FirstName { get; } string LastName { get; } string MiddleName { get; } bool IsChild { get; } bool IsEmployee { get; } bool IsSpouse { get; } int NumberOfPayPeriod { get; } decimal AnnualCostGross { get; } decimal AnnualCostNet { get; } int AnnualDiscountPerentage { get; } decimal PerPayPeriodCostGross { get; } decimal PerPayPeriodCostNet { get; } } }
using System; namespace NStandard.Converts { public static class StringConvert { /// <summary> /// Converts the specified string, which encodes binary data as url safe base-64 digits, to /// an equivalent 8-bit unsigned integer array. /// </summary> /// <param name="base64"></param> /// <returns></returns> public static string ConvertBase64ToUrlSafeBase64(string base64) { return base64.Replace("/", "_").Replace("+", "-").TrimEnd('='); } /// <summary> /// Converts an array of 8-bit unsigned integers to its equivalent string representation /// that is encoded with url safe base-64 digits. /// </summary> /// <param name="urlBase64"></param> /// <returns></returns> public static string ConvertUrlSafeBase64ToBase64(string urlBase64) { var mod = urlBase64.Length % 4; var padding = "=".Repeat(mod switch { 0 => 0, 2 => 2, 3 => 1, _ => throw new FormatException("The input is not a valid Base-64 string"), }); var content = urlBase64.Replace("_", "/").Replace("-", "+"); return $"{content}{padding}"; } /// <summary> /// Converts the specified string, which encodes binary data as base-64 digits, to /// an equivalent 8-bit unsigned integer array. /// </summary> /// <param name="this"></param> /// <returns></returns> public static byte[] Base64Bytes(string @this) => Convert.FromBase64String(@this); /// <summary> /// Converts the specified string, which encodes binary data as url safe base-64 digits, to /// an equivalent 8-bit unsigned integer array. /// </summary> /// <param name="this"></param> /// <returns></returns> public static byte[] UrlSafeBase64Bytes(string @this) => Convert.FromBase64String(ConvertUrlSafeBase64ToBase64(@this)); /// <summary> /// Converts the specified string, which encodes binary data as hex digits, to /// an equivalent 8-bit unsigned integer array. /// </summary> /// <param name="this"></param> /// <param name="separator"></param> /// <returns></returns> public static byte[] FromHexString(string @this) => FromHexString(@this, ""); /// <summary> /// Converts the specified string, which encodes binary data as hex digits, to /// an equivalent 8-bit unsigned integer array. /// </summary> /// <param name="this"></param> /// <param name="separator"></param> /// <returns></returns> public static byte[] FromHexString(string @this, string separator = "") { if (@this.IsNullOrEmpty()) { #if NETCOREAPP1_0_OR_GREATER || NETSTANDARD1_3_OR_GREATER || NET46_OR_GREATER return Array.Empty<byte>(); #else return ArrayEx.Empty<byte>(); #endif } var hexString = @this; if (!separator.IsNullOrEmpty()) hexString = hexString.Replace(separator, ""); var length = hexString.Length; if (length.IsOdd()) throw new FormatException("The specified string's length must be even."); var ret = new byte[length / 2]; for (int i = 0; i < ret.Length; i++) ret[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return ret; } } }
// Copyright (c) 2010 Michael B. Edwin Rickert // // See the file LICENSE.txt for copying permission. using DisplayWindow; using FrameGenerator; using ICSharpCode.SharpZipLib.BZip2; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using TtyRecDecoder; using System.Drawing.Imaging; using ICSharpCode.SharpZipLib.GZip; using SkiaSharp.Views.Desktop; using TtyRecMonkey.Windows; namespace TtyRecMonkey { [System.ComponentModel.DesignerCategory("")] public class PlayerForm : DCSSReplayWindow { private int TimeStepLengthMS = 5000; PlayerSearchForm playerSearch; ReplayTextSearchForm replayTextSearchForm; private readonly MainGenerator frameGenerator; private readonly List<DateTime> PreviousFrames = new List<DateTime>(); private Bitmap bmp = new Bitmap(1602, 1050, PixelFormat.Format32bppArgb); private DateTime PreviousFrame = DateTime.Now; private TimeSpan MaxDelayBetweenPackets = new TimeSpan(0,0,0,0,500);//millisecondss private int FrameStepCount; private int ConsoleSwitchLevel = 1; private int framerateControlTimeout = 5; private TileOverrideForm tileoverrideform; public PlayerForm() { this.Icon = Properties.Resource1.dcssreplay; frameGenerator = new MainGenerator(); tileoverrideform = new TileOverrideForm(); Configuration.Load(this); AfterConfiguration(); Visible = true; } void OpenFile() { Thread mt = new Thread(o => { var open = new OpenFileDialog() { CheckFileExists = true, DefaultExt = "ttyrec", Filter = @"TtyRec Files|*.ttyrec;*.ttyrec.bz2;*.ttyrec.gz|All Files|*", Multiselect = false, RestoreDirectory = true, Title = "Select a TtyRec to play" };//TODO: bring back multiselect? if (open.ShowDialog() != DialogResult.OK) return; var files = open.FileNames; using (open) { } open = null; DoOpenFiles(files); }); mt.SetApartmentState(ApartmentState.STA); mt.Start(); mt.Join(); } void DoOpenFiles(string[] files) { var delay = TimeSpan.Zero; //if (files.Length > 1) //{ // // multiselect! // var fof = new FileOrderingForm(files); // if (fof.ShowDialog(this) != DialogResult.OK) return; // files = fof.FileOrder.ToArray(); // delay = TimeSpan.FromSeconds(fof.SecondsBetweenFiles); //} var streams = TtyrecToStream(files); ttyrecDecoder = new TtyRecKeyframeDecoder(80, 24, streams, delay, MaxDelayBetweenPackets); ttyrecDecoder.PlaybackSpeed = +1; ttyrecDecoder.SeekTime = TimeSpan.Zero; } private IEnumerable<Stream> TtyrecToStream(string[] files) { return files.Select(f => { var extension = Path.GetExtension(f).Replace(".", ""); if (extension == "ttyrec") return File.OpenRead(f); Stream streamCompressed = File.OpenRead(f); return DecompressedStream(extension, streamCompressed); }); } private IEnumerable<Stream> TtyrecToStream(Dictionary<string, Stream> s) { return s.Select(f => { if (f.Key=="ttyrec") return f.Value; Stream streamCompressed = f.Value; return DecompressedStream(f.Key, streamCompressed); }); } private static Stream DecompressedStream(string compressionType, Stream streamCompressed) { Stream streamUncompressed = new MemoryStream(); try { switch (compressionType) { case "bz2": { BZip2.Decompress(streamCompressed, streamUncompressed, false); return streamUncompressed; } case "gz": { GZip.Decompress(streamCompressed, streamUncompressed, false); return streamUncompressed; } case "xz": { MessageBox.Show(" .XZ is not supported, download and extract to .ttyrec before running"); return null; } default: MessageBox.Show("The file is corrupted or not supported"); return null; } } catch { MessageBox.Show("The file is corrupted or not supported"); } return null; } void MainLoop() { Thread.Sleep(framerateControlTimeout); var now = DateTime.Now; PreviousFrames.Add(now); PreviousFrames.RemoveAll(f => f.AddSeconds(1) < now); var dt = Math.Max(0, Math.Min(0.1, (now - PreviousFrame).TotalSeconds)); PreviousFrame = now; if (ttyrecDecoder != null) { ShowControls(false); ttyrecDecoder.SeekTime += TimeSpan.FromSeconds(dt * ttyrecDecoder.PlaybackSpeed); if (ttyrecDecoder.SeekTime > ttyrecDecoder.Length) { ttyrecDecoder.SeekTime = ttyrecDecoder.Length; } if (ttyrecDecoder.SeekTime < TimeSpan.Zero) { ttyrecDecoder.SeekTime = TimeSpan.Zero; } if (FrameStepCount != 0) { ttyrecDecoder.FrameStep(FrameStepCount); //step frame index by count ttyrecDecoder.SeekTime = ttyrecDecoder.CurrentFrame.SinceStart; FrameStepCount = 0; } else { ttyrecDecoder.Seek(ttyrecDecoder.SeekTime); } var frame = ttyrecDecoder.CurrentFrame.Data; if (frame != null) { if (!frameGenerator.isGeneratingFrame) { frameGenerator.isGeneratingFrame = true; #if true ThreadPool.UnsafeQueueUserWorkItem(o => { try { bmp = frameGenerator.GenerateImage(frame, ConsoleSwitchLevel, tileoverrideform.tileoverides).ToBitmap(); Update2(bmp); frameGenerator.isGeneratingFrame = false; frame = null; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); //generator.GenerateImage(savedFrame); frameGenerator.isGeneratingFrame = false; } }, null); #else //non threaded image generation (slow) generator.GenerateImage(savedFrame); update2(bmp); frameGenerator.isGeneratingFrame = false; #endif } } } else { ShowControls(true); Update2(null); } UpdateTitle( $"DCSSReplay -- {PreviousFrames?.Count} " + $"FPS -- {(ttyrecDecoder == null ? "N/A" : PrettyTimeSpan(ttyrecDecoder.SeekTime)) } " + $"@ {(ttyrecDecoder == null ? "N/A" : PrettyTimeSpan(ttyrecDecoder.CurrentFrame.SinceStart))} " + $"of {(ttyrecDecoder == null ? "N/A" : PrettyTimeSpan(ttyrecDecoder.Length))} " + $"({(ttyrecDecoder == null ? "N/A" : ttyrecDecoder.Keyframes.ToString())} " + $"keyframes {(ttyrecDecoder == null ? "N/A" : ttyrecDecoder.PacketCount.ToString())} packets) -- Speed {ttyrecDecoder?.PlaybackSpeed}" ); UpdateTime(ttyrecDecoder == null ? "N/A" : PrettyTimeSpan(ttyrecDecoder.CurrentFrame.SinceStart), ttyrecDecoder == null ? "N/A" : PrettyTimeSpan(ttyrecDecoder.Length)); } private void Reconfigure() { var cfg = new ConfigurationForm(); if (cfg.ShowDialog(this) == DialogResult.OK) AfterConfiguration(); } private void AfterConfiguration() { TimeStepLengthMS = Configuration.Main.TimeStepLengthMS; framerateControlTimeout = Configuration.Main.framerateControlTimeout; if (MaxDelayBetweenPackets == new TimeSpan(0, 0, 0, 0, Configuration.Main.MaxDelayBetweenPackets)) return; ttyrecDecoder = null; MaxDelayBetweenPackets = new TimeSpan(0, 0, 0, 0, Configuration.Main.MaxDelayBetweenPackets); } protected override void OnKeyDown(KeyEventArgs e) { // bool resize = (WindowState == FormWindowState.Normal) && (ClientSize == ActiveSize); switch (e.KeyData) { case Keys.Escape: using (ttyrecDecoder) { } ttyrecDecoder = null; break; case Keys.Control | Keys.G: PlayerDownloadWindow(); break; //case Keys.Control | Keys.T: TileOverrideWindow(); break; case Keys.Control | Keys.O: OpenFile(); break; case Keys.Control | Keys.F: ReplayTextSearchWindow(); break; case Keys.Control | Keys.C: Reconfigure(); break; case Keys.Alt | Keys.Enter: if (FormBorderStyle == FormBorderStyle.None) { FormBorderStyle = FormBorderStyle.Sizable; WindowState = FormWindowState.Normal; } else { FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Maximized; } e.SuppressKeyPress = true; // also supresses annoying dings break; } if (ttyrecDecoder != null) { switch (e.KeyData) { case Keys.Z: ttyrecDecoder.PlaybackSpeed = -100; break; case Keys.X: ttyrecDecoder.PlaybackSpeed = -10; break; case Keys.C: ttyrecDecoder.PlaybackSpeed = -1; break; case Keys.B: ttyrecDecoder.PlaybackSpeed = +1; break; case Keys.N: ttyrecDecoder.PlaybackSpeed = +10; break; case Keys.M: ttyrecDecoder.PlaybackSpeed += +100; break; case Keys.F: ttyrecDecoder.PlaybackSpeed -= 1; break;//progresive increase/decrease case Keys.G: ttyrecDecoder.PlaybackSpeed += 1; break; case Keys.D: ttyrecDecoder.PlaybackSpeed -= 0.2; break;//progresive increase/decrease case Keys.H: ttyrecDecoder.PlaybackSpeed += 0.2; break; case Keys.Oemcomma: if (ttyrecDecoder.PlaybackSpeed != 0) { ttyrecDecoder.Pause(); } //pause when frame stepping FrameStepCount -= 1;//FrameStep -1 break; case Keys.OemPeriod: if (ttyrecDecoder.PlaybackSpeed != 0) { ttyrecDecoder.Pause(); }//pause when frame stepping FrameStepCount += 1; //FrameStep +1 break; case Keys.Left: ttyrecDecoder.SeekTime -= ttyrecDecoder.SeekTime - TimeSpan.FromMilliseconds(TimeStepLengthMS) > TimeSpan.Zero ? TimeSpan.FromMilliseconds(TimeStepLengthMS) : TimeSpan.Zero; break; case Keys.Right: ttyrecDecoder.SeekTime += ttyrecDecoder.SeekTime + TimeSpan.FromMilliseconds(TimeStepLengthMS) < ttyrecDecoder.Length ? TimeSpan.FromMilliseconds(TimeStepLengthMS) : ttyrecDecoder.Length; break; case Keys.A: ConsoleSwitchLevel = ConsoleSwitchLevel != 2 ? 2 : 1;//switch console and tile windows around when in normal layout mode break; case Keys.S: ConsoleSwitchLevel = ConsoleSwitchLevel != 3 ? 3 : 1;//switch to full console mode ound when in normal layout mode break; case Keys.V://Play / Pause case Keys.Space: PlayButton_Click(new object(), e); break; } } base.OnKeyDown(e); } private void TileOverrideWindow() { tileoverrideform.Visible = true; } private void PlayerDownloadWindow() { playerSearch = new PlayerSearchForm(); playerSearch.Visible = true; playerSearch.dataGridView1.CellDoubleClick += DownloadTTyRec; playerSearch.DownloadButton.Click += DownloadTTyRec; } private void ReplayTextSearchWindow() { if (replayTextSearchForm == null || replayTextSearchForm.IsDisposed) { replayTextSearchForm = new ReplayTextSearchForm(ttyrecDecoder); } replayTextSearchForm.Visible = true; replayTextSearchForm.BringToFront(); replayTextSearchForm.Focus(); } private async void DownloadTTyRec(object sender, EventArgs e) { await playerSearch.DownloadFileAsync(sender, e); var streams = TtyrecToStream(playerSearch.TtyrecStreamDictionary); var delay = TimeSpan.Zero; ttyrecDecoder = new TtyRecKeyframeDecoder(80, 24, streams, delay, MaxDelayBetweenPackets); ttyrecDecoder.PlaybackSpeed = +1; ttyrecDecoder.SeekTime = TimeSpan.Zero; } static string PrettyTimeSpan(TimeSpan ts) { return ts.Days == 0 ? string.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds) : string.Format("{3} days, {0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Days) ; } static string PrettyByteCount(long bytes) { if (bytes < 10000L) return string.Format("{0:0,0}B", bytes); bytes /= 1000; if (bytes < 10000L) return string.Format("{0:0,0}KB", bytes); bytes /= 1000; if (bytes < 10000L) return string.Format("{0:0,0}MB", bytes); bytes /= 1000; if (bytes < 10000L) return string.Format("{0:0,0}GB", bytes); bytes /= 1000; if (bytes < 10000L) return string.Format("{0:0,0}TB", bytes); bytes /= 1000; return string.Format("{0:0,0}PB", bytes); } private void Loop() { while (run) { MainLoop(); } } private static void Main(string[] args) { using var form = new PlayerForm(); if (args.Length > 0) form.DoOpenFiles(args); else { if (Configuration.Main.OpenFileSelect) { form.OpenFile(); } else if (Configuration.Main.OpenDownload) { form.PlayerDownloadWindow(); } } Thread m_Thread = new Thread(() => form.Loop()); m_Thread.Start(); Application.Run(form); } } }
using UBaseline.Shared.Navigation; using UBaseline.Shared.Property; namespace Uintra.Features.Navigation.Models { public interface IUintraNavigationComposition : INavigationComposition { PropertyModel<bool> ShowInSubMenu { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assets { class TimeCounter { private float overallTime; private float startTime; private float firstLevelTime; private float secondLevelTime; private float thirdLevelTime; private float fourthLevelTime; private float fifthLevelTime; private float sixthLevelTime; public float StartTime { get => startTime; set => startTime = value; } public float FirstLevelTime { get => firstLevelTime; set => firstLevelTime = value; } public float SecondLevelTime { get => secondLevelTime; set => secondLevelTime = value; } public float ThirdLevelTime { get => thirdLevelTime; set => thirdLevelTime = value; } public float FourthLevelTime { get => fourthLevelTime; set => fourthLevelTime = value; } public float FifthLevelTime { get => fifthLevelTime; set => fifthLevelTime = value; } public float SixthLevelTime { get => sixthLevelTime; set => sixthLevelTime = value; } public float OverallTime { get => overallTime; set => overallTime = value; } } }
// <copyright file="TableOfMAXP.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> namespace WaterTrans.GlyphLoader.Internal { /// <summary> /// Table of MAXP. /// </summary> internal sealed class TableOfMAXP { /// <summary> /// Initializes a new instance of the <see cref="TableOfMAXP"/> class. /// </summary> /// <param name="reader">The <see cref="TypefaceReader"/>.</param> internal TableOfMAXP(TypefaceReader reader) { TableVersionNumberMajor = reader.ReadUInt16(); TableVersionNumberMinor = reader.ReadUInt16(); NumGlyphs = reader.ReadUInt16(); if (TableVersionNumberMajor == 0 && TableVersionNumberMinor == 0x5000) { return; } MaxPoints = reader.ReadUInt16(); MaxContours = reader.ReadUInt16(); MaxCompositePoints = reader.ReadUInt16(); MaxCompositeContours = reader.ReadUInt16(); MaxZones = reader.ReadUInt16(); MaxTwilightPoints = reader.ReadUInt16(); MaxStorage = reader.ReadUInt16(); MaxFunctionDefs = reader.ReadUInt16(); MaxInstructionDefs = reader.ReadUInt16(); MaxStackElements = reader.ReadUInt16(); MaxSizeOfInstructions = reader.ReadUInt16(); MaxComponentElements = reader.ReadUInt16(); MaxComponentDepth = reader.ReadUInt16(); } /// <summary>Gets a major table version.</summary> public ushort TableVersionNumberMajor { get; } /// <summary>Gets a minor table version.</summary> public ushort TableVersionNumberMinor { get; } /// <summary>Gets a number of glyphs in the font.</summary> public ushort NumGlyphs { get; } /// <summary>Gets a maximum points in a non-composite glyph.</summary> public ushort MaxPoints { get; } /// <summary>Gets a maximum contours in a non-composite glyph.</summary> public ushort MaxContours { get; } /// <summary>Gets a maximum points in a composite glyph.</summary> public ushort MaxCompositePoints { get; } /// <summary>Gets a maximum contours in a composite glyph.</summary> public ushort MaxCompositeContours { get; } /// <summary>Gets a maximum zones.</summary> /// <remarks>1 if instructions do not use the twilight zone (Z0), or 2 if instructions do use Z0; should be set to 2 in most cases.</remarks> public ushort MaxZones { get; } /// <summary>Gets a maximum points used in Z0.</summary> public ushort MaxTwilightPoints { get; } /// <summary>Gets a number of Storage Area locations.</summary> public ushort MaxStorage { get; } /// <summary>Gets a number of FDEFs, equal to the highest function number + 1.</summary> public ushort MaxFunctionDefs { get; } /// <summary>Gets a number of IDEFs.</summary> public ushort MaxInstructionDefs { get; } /// <summary>Gets a maximum stack depth across Font Program ('fpgm' table), CVT Program ('prep' table) and all glyph instructions (in the 'glyf' table).</summary> public ushort MaxStackElements { get; } /// <summary>Gets a maximum byte count for glyph instructions.</summary> public ushort MaxSizeOfInstructions { get; } /// <summary>Gets a maximum number of components referenced at “top level” for any composite glyph.</summary> public ushort MaxComponentElements { get; } /// <summary>Gets a maximum levels of recursion; 1 for simple components.</summary> public ushort MaxComponentDepth { get; } } }
using System.Globalization; using System.Windows; namespace WindowsUpdateNotifier { public partial class PopupView : Window { public PopupView() { InitializeComponent(); var workingArea = SystemParameters.WorkArea; Left = CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft ? workingArea.Left + 10 : workingArea.Width + workingArea.Left - Width - 10; Top = workingArea.Height + workingArea.Top - Height - 10; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace CTC { public class GameEffect { protected double Elapsed = 0; protected double Duration = 0; public virtual void Update(GameTime Time) { Elapsed += Time.ElapsedGameTime.TotalSeconds; } public Boolean Expired { get { return Elapsed > Duration; } } } }
using UnityEngine; using UnityEngine.SceneManagement; public class Initialization : MonoBehaviour { private void Start() { // Show status bar Screen.fullScreen = false; // Skip login when user logged. if (PlayerPrefs.HasKey("token")) { SceneManager.LoadScene("MainPage"); } else { // Detect language the user's operating system is running in for first time. if (PlayerPrefs.HasKey("language")) { if (Application.systemLanguage == SystemLanguage.Thai) { PlayerPrefs.SetString("language", "th"); } else { PlayerPrefs.SetString("language", "en"); } } SceneManager.LoadScene("Login"); } } }
using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32; namespace ZapisCteniSouboru { class Program { //Každý řádek 1 číslo od 1 do 100 //Zjisti, které se generovalo nejčastěji static void Main(string[] args) { Random random = new Random(); string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\MojeData.txt"; using (Stream stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { using (StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8)) { for (int i = 0; i < 100; i++) { streamWriter.WriteLine(random.Next(0, 11)); } } } using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) { using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8)) { int[] array = new int[100]; string line; while ((line = streamReader.ReadLine()) != null) { array[Convert.ToInt32(line)] += 1; Console.WriteLine(line); } //TODO Change Console.WriteLine(array.Max()); } } Console.ReadKey(true); } } }
using System.Runtime.InteropServices; namespace Vanara.PInvoke { public static partial class Kernel32 { /// <summary>Retrieves the processor group affinity of the specified process.</summary> /// <param name="hProcess"> /// <para>A handle to the process.</para> /// <para> /// This handle must have the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. For more information, see /// Process Security and Access Rights. /// </para> /// </param> /// <param name="GroupCount"> /// On input, specifies the number of elements in GroupArray array. On output, specifies the number of processor groups written to /// the array. If the array is too small, the function fails with ERROR_INSUFFICIENT_BUFFER and sets the GroupCount parameter to the /// number of elements required. /// </param> /// <param name="GroupArray"> /// An array of processor group numbers. A group number is included in the array if a thread in the process is assigned to a /// processor in the group. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para> /// <para> /// If the error value is ERROR_INSUFFICIENT_BUFFER, the GroupCount parameter contains the required buffer size in number of elements. /// </para> /// </returns> // BOOL GetProcessGroupAffinity( _In_ HANDLE hProcess, _Inout_ PUSHORT GroupCount, _Out_ PUSHORT GroupArray); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405496(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dd405496")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetProcessGroupAffinity(HPROCESS hProcess, ref ushort GroupCount, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ushort[] GroupArray); /// <summary>Retrieves the processor group affinity of the specified thread.</summary> /// <param name="hThread"> /// <para>A handle to the thread for which the processor group affinity is desired.</para> /// <para> /// The handle must have the THREAD_QUERY_INFORMATION or THREAD_QUERY_LIMITED_INFORMATION access right. For more information, see /// Thread Security and Access Rights. /// </para> /// </param> /// <param name="GroupAffinity">A pointer to a GROUP_AFFINITY structure to receive the group affinity of the thread.</param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para> /// </returns> // BOOL GetThreadGroupAffinity( _In_ HANDLE hThread, _Out_ PGROUP_AFFINITY GroupAffinity); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405498(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dd405498")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetThreadGroupAffinity(HTHREAD hThread, out GROUP_AFFINITY GroupAffinity); /// <summary>Sets the processor group affinity for the specified thread.</summary> /// <param name="hThread"> /// <para>A handle to the thread.</para> /// <para>The handle must have the THREAD_SET_INFORMATION access right. For more information, see Thread Security and Access Rights.</para> /// </param> /// <param name="GroupAffinity"> /// A <c>GROUP_AFFINITY</c> structure that specifies the processor group affinity to be used for the specified thread. /// </param> /// <param name="PreviousGroupAffinity"> /// A pointer to a <c>GROUP_AFFINITY</c> structure to receive the thread's previous group affinity. This parameter can be NULL. /// </param> /// <returns> /// <para>If the function succeeds, the return value is nonzero.</para> /// <para>If the function fails, the return value is zero. To get extended error information, use <c>GetLastError</c>.</para> /// </returns> // BOOL SetThreadGroupAffinity( _In_ HANDLE hThread, _In_ const GROUP_AFFINITY *GroupAffinity, _Out_opt_ PGROUP_AFFINITY // PreviousGroupAffinity); https://msdn.microsoft.com/en-us/library/windows/desktop/dd405516(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dd405516")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetThreadGroupAffinity(HTHREAD hThread, in GROUP_AFFINITY GroupAffinity, out GROUP_AFFINITY PreviousGroupAffinity); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using Hackathon; public class TimeIndicator : TimeBehaviour { [SerializeField] private Slider slider; // Update is called once per frame void Start() { var puppeteer = FindObjectOfType<Puppeteer>(); slider.maxValue = puppeteer.lifetime; } void Update () { slider.value = timeline.time; } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Text; namespace PingoSnake { class SpawnManager { private List<SpawnController> SpawnControllers; public SpawnManager() { this.SpawnControllers = new List<SpawnController>(); } public void AddSpawnController(SpawnController spawnController) { this.SpawnControllers.Add(spawnController); } public void RemoveSpawnController(SpawnController spawnController) { this.SpawnControllers.Remove(spawnController); } public void Update(GameTime gameTime) { foreach (SpawnController spawnController in this.SpawnControllers) { spawnController.Update(gameTime); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Management; using System.Reflection; using System.Text.RegularExpressions; using Emanate.Core.Configuration; namespace Emanate.Service.Admin { class PluginConfigurationStorer { private Configuration appConfig; public IEnumerable<ConfigurationInfo> Load() { var currentFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); appConfig = GetServiceConfiguration(); foreach (var file in Directory.EnumerateFiles(currentFolder, "*.dll")) { var assembly = Assembly.LoadFrom(file); foreach (var type in assembly.GetTypes()) { if (type.IsAbstract || type.IsInterface || !type.IsPublic) continue; var configurationAttribute = (ConfigurationAttribute)type.GetCustomAttributes(typeof(ConfigurationAttribute), false).SingleOrDefault(); if (configurationAttribute == null) continue; var properties = GetConfigProperties(type, appConfig); yield return new ConfigurationInfo(configurationAttribute.Name, properties); } } } public void Save(IEnumerable<ConfigurationInfo> configurations) { if (appConfig == null) throw new InvalidOperationException("Cannot save configuration before it's been loaded"); appConfig.AppSettings.Settings.Clear(); foreach (var property in configurations.SelectMany(c => c.Properties)) { var value = property.Value != null ? property.Value.ToString() : ""; appConfig.AppSettings.Settings.Add(property.Key,value); } appConfig.Save(ConfigurationSaveMode.Full); } private static Configuration GetServiceConfiguration() { var mc = new ManagementClass("Win32_Service"); foreach (ManagementObject mo in mc.GetInstances()) { if (mo.GetPropertyValue("Name").ToString() == "EmanateService") { var pathToServiceExe = mo.GetPropertyValue("PathName").ToString().Trim('"'); return ConfigurationManager.OpenExeConfiguration(pathToServiceExe); } } throw new Exception("Could not find the service or the installed path."); } private IEnumerable<ConfigurationProperty> GetConfigProperties(Type configType, Configuration appConfig) { var properties = configType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var propertyInfo in properties) { var keyAttribute = (KeyAttribute)propertyInfo.GetCustomAttributes(false).Single(a => typeof(KeyAttribute).IsAssignableFrom(a.GetType())); var element = appConfig.AppSettings.Settings[keyAttribute.Key]; var value = element != null ? element.Value : null; yield return new ConfigurationProperty { Name = propertyInfo.Name, FriendlyName = Regex.Replace(propertyInfo.Name, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 "), Key = keyAttribute.Key, Type = propertyInfo.PropertyType, IsPassword = keyAttribute.IsPassword, Value = value }; } } } }
using NfePlusAlpha.Domain.Entities; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NfePlusAlpha.Infra.Data.EntityConfig { public class tbClienteConfig : EntityTypeConfiguration<tbCliente> { public tbClienteConfig() { HasKey(c => c.cli_codigo); Property(c => c.cli_cpfCnpj) .IsRequired() .HasMaxLength(14); Property(c => c.cli_nome) .IsRequired() .HasMaxLength(200); Property(c => c.cli_rgIe) .IsRequired() .HasMaxLength(20); Property(c => c.cli_fantasia) .IsOptional() .HasMaxLength(100); Property(c => c.cli_email) .IsOptional() .HasMaxLength(100); Property(c => c.cli_suframa) .IsOptional() .HasMaxLength(20); //Endereço Property(c => c.cli_enderecoLogradouro).HasMaxLength(200); Property(c => c.cli_enderecoNumero).HasMaxLength(10); Property(c => c.cli_enderecoBairro).HasMaxLength(100); Property(c => c.cli_enderecoComplemento) .IsOptional() .HasMaxLength(200); Property(c => c.cli_enderecoCep).HasMaxLength(8); Property(c => c.cli_telefone) .IsOptional() .HasMaxLength(13); Property(c => c.cli_celular) .IsOptional() .HasMaxLength(14); } } }
using System; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using Epic.Training.Project.Inventory; using Epic.Training.Project.SuppliedCode.Exceptions; using Epic.Training.Project.Inventory.Text.Exceptions; using Epic.Training.Project.Inventory.Text.Persistence; using Epic.Training.Project.Inventory.Text.Menus; using System.Runtime.CompilerServices; //FOUNDATIONS LAB B namespace Epic.Training.Project.Inventory.Text { /// <summary> /// The UI portion of your project /// </summary> class Program { private static string defaultBinDir = String.Format(@"{0}\{1}", Environment.GetEnvironmentVariable(Resource1.DefaultBinDirEnv), Resource1.DefaultBinDir); #region CUSTOM TESTS private static void TwoInventoriesSharedItem() { Inventory inv1 = new Inventory(); Inventory inv2 = new Inventory(); Item item1 = new Item("One", 1, 1, 1); Item item2 = new Item("Two", 1, 1, 1); Item item3 = new Item("Three", 1, 1, 1); inv1.Add(item1); inv2.Add(item1); inv2.Add(item2); //Changing item1's name to "2" should cause problems for inv2. inv2.Add(item3); Console.WriteLine("inv1"); foreach (Item item in inv1) { Console.WriteLine(item.Name); } Separator(); Console.WriteLine("inv2"); foreach (Item item in inv2) { Console.WriteLine(item.Name); } Separator(); try { item1.Name = "Four"; item3.Name = "seben"; item1.Name = "Three"; item3.Name = "Two"; } catch (DuplicateProductNameException ex) { Console.WriteLine("There exists an inventory with that product name already"); } Separator(); Console.WriteLine("inv1"); foreach (Item item in inv1) { Console.WriteLine(item.Name); } Separator(); Console.WriteLine("inv2"); foreach (Item item in inv2) { Console.WriteLine(item.Name); } } private static void BetterInputTest() { bool repeat = true; while (repeat) { Console.WriteLine("Menu Options lol"); string input; try { input = betterInput("stuff> "); } catch (EscapeKeyPressedException ex) { Console.WriteLine("\n\n[ESC] Pressed - back to menu"); System.Threading.Thread.Sleep(2500); Console.Clear(); continue; } Console.WriteLine("Input was: {0}", input); } } #endregion /// <summary> /// Calls MainMenu and processes optional command-line arguments to pass into MainMenu. /// </summary> /// <param name="args">Command-line arguments</param> [STAThread()] static void Main(string[] args) { Persist.createPersistentDir(); TextMenu.MainMenu(); //MainMenu(); //TwoInventoriesSharedItem(); //BetterInputTest(); //Console.ReadKey(); } #region MENU FORMATTING - Seperator;Version;TableHeader;DisplayRow;DisplayInventory /// <summary> /// Included in menus for clear separation between console output and user input. /// </summary> static void Separator() { Console.WriteLine(new String('-',25) + "\n"); } /// <summary> /// Displays version of UI build /// </summary> static void Version() { Console.WriteLine("InventoryTracker v1"); Separator(); } /// <summary> /// Displays TableHeader used when displaying inventory. Columns = {Order, Name, Wholesale (USD), Retail (USD), Quantity, Weight (Lbs) /// </summary> static void TableHeader() { Console.WriteLine(" |-------------------------------------------------------------------------"); Console.WriteLine(" | ORD | NAME | WHLSALE-USD | RTL-USD | QTY | WGT-LBS |"); Console.WriteLine(" |-------------------------------------------------------------------------"); } /// <summary> /// Displays a row containing columns of an Item's publicly facing properties. /// </summary> /// <param name="item">Item object to display row for.</param> /// <param name="order">Int - used for first column to track order of objects.</param> static void DisplayRow(Item item, int order) { Console.WriteLine(" |{0,5}|{1,26}|{2,13}|{3,9}|{4,5}|{5,9}|", order, item.Name, item.WholesalePrice, item.RetailPrice, item.QuantityOnHand, item.Weight); Console.WriteLine(" |-------------------------------------------------------------------------"); } /// <summary> /// Prints the contents of the currently loaded Inventory /// </summary> /// <param name="inv">Inventory to display</param> /// <param name="option">How to sort the Items in the Inventory before viewing</param> static void DisplayInventory(Inventory inv, SortOption option) { TableHeader(); int counter = 0; foreach (Item item in inv.GetSortedProducts(option)) { DisplayRow(item, counter++); } } #endregion #region ITEM PROPERTY VALIDATION - [GetName|GetQuantity|GetWholesale|GetWeight]FromUser /// <summary> /// Leave it up to calling function/menu to decide outcome. /// </summary> /// <param name="inv">Currently loaded inventory</param> /// <param name="proposedName">Proposed name of Item</param> /// <returns>{False, Invalid Name}; {True, Valid Name}</returns> static bool TestName(Inventory inv, out string proposedName) { Console.Write("\b<<Product name (MAX-26 chars)>> "); proposedName = Console.ReadLine(); if (string.IsNullOrWhiteSpace(proposedName)) { Console.WriteLine("\n[!Product name cannot be blank!]\n"); proposedName = null; return false; } else if (proposedName.Count() > 26) { Console.WriteLine("\n[!'{0}' too long of a name (MAXLENGTH = 26)!]\n", proposedName); proposedName = null; return false; } else if (inv.Contains(proposedName)) { Console.WriteLine("\n[!Product with name '{0}' already exists in the inventory!]\n", proposedName); proposedName = null; return false; } return true; } /// <summary> /// Retrieves and validates user input for item names. /// </summary> /// <param name="inv">Currently loaded Inventory</param> /// <param name="callerName">Name of calling Menu/method</param> /// <exception cref="Epic.Training.Project.Inventory.Text.Exceptions">Thrown when user presses [ESC] key</exception> /// <returns type="String">Name of Item</returns> private static string GetNameFromUser(Inventory inv, [CallerMemberName] string callerName="") { string proposedName; while (true) { try { proposedName = betterInput("\b<<Product NAME (MAX-26 chars)>> "); } catch (EscapeKeyPressedException ex) { throw ex; //Let the caller of this method handle it. } if (string.IsNullOrWhiteSpace(proposedName)) { Console.WriteLine("\n[! Product name cannot be blank !]\n"); continue; } else if (proposedName.Count() > 26) { Console.WriteLine("\n[! '{0}' too long of a name (MAXLENGTH = 26) !]\n", proposedName); continue; } else if (inv.Contains(proposedName)) { if (callerName == "CreateItem") { Console.WriteLine("Hi from CreateItem"); } Console.WriteLine("\n[! Product with name '{0}' already exists in the inventory !]\n", proposedName); continue; } Console.WriteLine("\n['{0}' is acceptable. Press Enter to continue or any other key to discard changes]\n", proposedName); if (Console.ReadKey().Key == ConsoleKey.Enter) { return proposedName; } else { continue; } } } private static int GetQuantityFromUser(Item itemStage) { bool result; int proposedQuantity; while (true) { //Console.Write("\b<<Quantity of {0}s on hand>> ", itemStage.Name); //string proposedAsString = Console.ReadLine(); string proposedAsString = null; try { proposedAsString = betterInput(String.Format("\b<<Quantity of {0}s on hand>> ", itemStage.Name)); } catch (EscapeKeyPressedException ex) { throw ex; } result = Int32.TryParse(proposedAsString, out proposedQuantity); if (result) { if (proposedQuantity < 0) { Console.WriteLine("\n[!'{0}' is negative. Enter a more suitable integer!]\n", proposedQuantity); continue; } Console.WriteLine("\n['{0}' is acceptable. Press 'Enter' to confirm or any other key to discard the change]\n", proposedQuantity); if (Console.ReadKey().Key == ConsoleKey.Enter) { return proposedQuantity; } } else { Console.WriteLine("\n[!Could not parse '{0}'. Entry too large, contains alpha chars, or is not an integer!]\n", proposedAsString); //TryParse is already going to fail an entry larger than type's MaxValue } } } private static decimal GetWholesaleFromUser(Item itemStage) { bool result; decimal proposedWholesale; while (true) { //Console.Write("\b<<Wholesale Price (USD) of one unit of {0}>> ", itemStage.Name); string proposedAsString = null; try { proposedAsString = betterInput(String.Format("\b<<Wholesale Price (USD) of one unit of {0}>> ", itemStage.Name)); } catch (EscapeKeyPressedException ex) { throw ex; } result = Decimal.TryParse(proposedAsString, out proposedWholesale); if (result) { if (proposedWholesale <= 0) { Console.WriteLine("\n[!'{0}' is negative, or zero. Please enter a more suitable number!]\n", proposedWholesale); continue; } Console.WriteLine("\n['{0}' is acceptable. Press 'Enter' to confirm or any other key to discard the change]\n", proposedWholesale); if (Console.ReadKey().Key == ConsoleKey.Enter) { return proposedWholesale; } } else { Console.WriteLine("\n[!Could not parse '{0}'. Entry too large or contains alpha chars!]\n", proposedWholesale); //TryParse is already going to fail an entry larger than type's MaxValue } } } private static double GetWeightFromUser(Item itemStage) { bool result; double proposedWeight; while (true) { //Console.Write("\b<<Weight (lb) of one unit of {0}>> ", itemStage.Name); string proposedAsString = null; try { proposedAsString = betterInput(String.Format("\b<<Weight (lb) of one unit of {0}>> ", itemStage.Name)); } catch (EscapeKeyPressedException ex) { throw ex; } result = Double.TryParse(proposedAsString, out proposedWeight); if (result) { if (proposedWeight <= 0) { Console.WriteLine("\n[!'{0}' is negative or zero. Please enter a more suitable number!]\n", proposedWeight); continue; } Console.WriteLine("\n['{0}' is acceptable. Press 'Enter' to confirm or any other key to discard the change]\n", proposedWeight); if (Console.ReadKey().Key == ConsoleKey.Enter) { return proposedWeight; } } else { Console.WriteLine("\n[!Could not parse '{0}'. Entry too large or contains alpha chars!]\n", proposedWeight); //TryParse is already going to fail an entry larger than type's MaxValue } } } #endregion #region MENU FUNCTIONS - MainMenu;InventoryMenu;CreateItem;EditItem;RemoveItem;DisplayInventory /// <summary> /// First Menu in the UI. Options - Load inventory from file; New inventory, Quit /// </summary> private static void MainMenu() { while (true) { Console.Clear(); Version(); Console.WriteLine("<<MAIN MENU>>\n"); Console.WriteLine("<<Please select a numbered option from below>>"); Console.WriteLine("[1]Load inventory from file"); Console.WriteLine("[2]New Inventory"); Console.WriteLine("[3]Quit"); Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': string filepath; Inventory inv = LoadInventory(out filepath); if (inv != null) { InventoryMenu(inv, filepath); } else { Console.WriteLine("[!Problem loading inventory from {0} - Creating New Inventory!]", filepath); System.Threading.Thread.Sleep(2500); inv = new Inventory(); InventoryMenu(inv, null); } break; case '2': inv = new Inventory(); InventoryMenu(inv); break; case '3': return; default: Console.WriteLine("\n[!Invalid selection - returning to Main Menu!]"); System.Threading.Thread.Sleep(1000); break; } } } /// <summary> /// Menu that contains options to manipulate the currently loaded inventory. /// </summary> /// <param name="inventory">Currently loaded inventory passed in from MainMenu()</param> private static void InventoryMenu(Inventory inventory, string filepath=null) { while (true) { Console.Clear(); Version(); if (filepath != null) { Console.WriteLine("<<INVENTORY MENU>> - Loaded from {0}\n", filepath); } else { Console.WriteLine("<<INVENTORY MENU>> - New Inventory\n"); } Console.WriteLine("<<Please select a numbered option from below>>"); Console.WriteLine("[1]View Inventory State"); Console.WriteLine("[2]Create New Item"); Console.WriteLine("[3]Edit Item"); Console.WriteLine("[4]Save Inventory"); Console.WriteLine("[5]Return to Main Menu"); Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': InventoryState(inventory); break; case '2': CreateItem(inventory); break; case '3': EditItem(inventory); break; case '4': SaveInventory(inventory, ref filepath); break; case '5': return; default: Console.WriteLine("\n[!Invalid selection - returning to Inventory menu!]"); System.Threading.Thread.Sleep(1000); break; } } } /// <summary> /// Menu for creating Items to be stored in the currently loaded inventory. /// </summary> /// <param name="inv">Currently loaded inventory.</param> static private void CreateItem(Inventory inv) { Console.Clear(); Version(); Console.WriteLine("<<ITEM CREATION>>\n"); Console.WriteLine("<<Press [ESC] at any time to return to previous Prompt or Menu>>\n"); bool repeat = true; int numOption = 0; //Keeps track of what the next prompt should be (Name, Quantity, Wholesale, Weight) Item itemStage = new Item("", 1, 1, 1m); while (repeat) { switch (numOption) { case 0: //Name try { itemStage.Name = GetNameFromUser(inv); numOption += 1; } catch (EscapeKeyPressedException ex) { Console.WriteLine("\n\n[Key [ESC] Pressed - Going back to Main Menu]\n"); System.Threading.Thread.Sleep(2000); return; } break; case 1: //Quantity try { itemStage.QuantityOnHand = GetQuantityFromUser(itemStage); numOption += 1; } catch (EscapeKeyPressedException ex) { Console.WriteLine("\n\n[Key [ESC] Pressed - Back to Name entry]\n"); numOption -= 1; } break; case 2: //Wholesale try { itemStage.WholesalePrice = GetWholesaleFromUser(itemStage); numOption += 1; } catch (EscapeKeyPressedException ex) { Console.WriteLine("\n\n[Key [ESC] Pressed - Back to Quantity entry]\n"); numOption -= 1; } break; case 3: //Weight try { itemStage.Weight = GetWeightFromUser(itemStage); repeat = false; } catch (EscapeKeyPressedException ex) { Console.WriteLine("\n\n[Key [ESC] Pressed - Back to Wholesale entry]"); numOption -= 1; } break; } } TableHeader(); DisplayRow(itemStage, 0); Console.WriteLine("\n<<Press 'Enter' to add Item '{0}' to the inventory or any other key to discard and return to Inventory Menu>>\n", itemStage.Name); if (Console.ReadKey().Key == ConsoleKey.Enter) { inv.Add(itemStage); } else { Console.WriteLine("\n[Discarding staged Item - Returning to Inventory Menu]"); System.Threading.Thread.Sleep(2000); } } /// <summary> /// Menu for editing pre-existing Items in the currently loaded inventory. /// </summary> /// <param name="inv">Currently loaded inventory.</param> private static void EditItem(Inventory inv) { while (true) { Console.Clear(); Version(); Console.WriteLine("<<Item Editor>>\n"); #region CHECK INVENTORY IS NOT EMPTY; DISPLAY ITEMS if (inv.TotalProducts < 1) { Console.WriteLine("[! There are no items in this Inventory yet. Returning to Inventory Menu !]"); System.Threading.Thread.Sleep(2000); return; } DisplayInventory(inv, SortOption.ByName); Console.WriteLine("\n<<Press [ESC] at any time to return to previous Prompt or Menu>>\n"); #endregion #region INSTANTIATE ITEMSTAGE; CHECK IF USER CHOSEN ITEM EXISTS Item itemStage = null; string itemName; do { try { itemName = betterInput("\n<<Enter the name of the Item you wish to edit>> "); if (inv.Contains(itemName)) { itemStage = inv[itemName]; } else { Console.WriteLine("\n[! No Item with name '{0}' exists in this inventory !]", itemName); } } catch (EscapeKeyPressedException ex) { Console.WriteLine("\n\n[Key [ESC] Pressed - Back to Inventory Menu]"); System.Threading.Thread.Sleep(2000); return; } } while (itemStage == null); #endregion Console.WriteLine("\n[Item '{0}' found. Select which property to edit]\n", itemStage.Name); TableHeader(); DisplayRow(itemStage, 0); Console.WriteLine(); Console.WriteLine("[1]Name"); Console.WriteLine("[2]Quantity On Hand"); Console.WriteLine("[3]Wholesale Price (USD)"); Console.WriteLine("[4]Weight (LBS)"); Console.WriteLine("[5]Remove Item from Inventory"); Console.WriteLine("[6]Cancel and return to Inventory Menu"); Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': string proposedName = null; if (TestName(inv, out proposedName) && proposedName != null) { itemStage.Name = proposedName; } else { System.Threading.Thread.Sleep(2500); } break; case '2': itemStage.QuantityOnHand = GetQuantityFromUser(itemStage); break; case '3': itemStage.WholesalePrice = GetWholesaleFromUser(itemStage); break; case '4': itemStage.Weight = GetWeightFromUser(itemStage); break; case '5': Console.WriteLine("<<Press 'Enter' to confirm Item removal or any other key to abort and return to Inventory Menu>>"); if (Console.ReadKey().Key == ConsoleKey.Enter) { inv.Remove(itemStage); Console.WriteLine("\n[Item '{0}' has been removed from Inventory]\n", itemStage.Name); } break; case '6': return; default: Console.WriteLine("\n[! Invalid selection - returning to Inventory menu !]"); System.Threading.Thread.Sleep(1000); return; } } } /// <summary> /// Menu for displaying inventory statistics of the currently loaded inventory, including its Item members. /// </summary> /// <param name="inv">Currently loaded inventory.</param> private static void InventoryState(Inventory inv) { Console.Clear(); Version(); Console.WriteLine("Total number of unique products: {0}", inv.TotalProducts); Console.WriteLine("Total number of products in stock: {0}", inv.ItemsInStock); Console.WriteLine("Total Wholesale-USD of Inventory: {0}", inv.TotalWholesalePrice); Console.WriteLine("Total Retail-USD of Inventory: {0}", inv.TotalRetailPrice); Separator(); while(true) { Console.WriteLine("\n<<Select a sorted view for the Inventory>>\n"); Console.WriteLine("[1]Sort Items alphabetically by name"); Console.WriteLine("[2]Sort Items by order entered into Inventory"); Console.WriteLine("[3]Display Inventory Statistics"); Console.WriteLine("[4]Return to Inventory Menu"); Separator(); switch (Console.ReadKey(true).KeyChar) { case '1': Console.WriteLine("\n"); DisplayInventory(inv, SortOption.ByName); break; case '2': Console.WriteLine("\n"); DisplayInventory(inv, SortOption.ByAdded); break; case '3': Console.Clear(); Console.WriteLine("Total number of unique products: {0}", inv.TotalProducts); Console.WriteLine("Total number of products in stock: {0}", inv.ItemsInStock); Console.WriteLine("Total Wholesale-USD of Inventory: {0}", inv.TotalWholesalePrice); Console.WriteLine("Total Retail-USD of Inventory: {0}", inv.TotalRetailPrice); Separator(); break; case '4': return; default: Console.WriteLine("\n[Invalid selection - returning to Inventory menu]"); System.Threading.Thread.Sleep(1000); break; } } } #endregion #region INVENTORY (DE)SERIALIZATION - GetFileName;SaveInventory;LoadInventory /// <summary> /// Creates a [Save|Open]FileDialog for *.bin files located in %APPDATA%\EpicInventory and [Saves|Opens] the selected filename. /// </summary> /// <param name="load">True: Loading Inventory. False: Saving Inventory</param> /// <returns>String - Absolute path of file</returns> private static string GetFilename(bool load, string currentPath = null) { string filePath = null; if (load) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "INVENTORY-TRACKER-LOADING"; dlg.Filter = "Binary files (*.bin)|*.bin"; dlg.InitialDirectory = defaultBinDir; if (dlg.ShowDialog() == DialogResult.OK) { filePath = dlg.FileName; } } else { SaveFileDialog slg = new SaveFileDialog(); slg.Title = "INVENTORY-TRACKER-SAVING"; slg.Filter = "Binary files (*.bin)|*.bin"; slg.InitialDirectory = defaultBinDir; slg.FileName = currentPath; //Defaults as the previously/currently loaded *.bin file. Empty if saving a new inventory if (slg.ShowDialog() == DialogResult.OK) { filePath = slg.FileName; } } return filePath; } private static void SaveInventory(Inventory inv, ref string currentName) { if (!String.IsNullOrWhiteSpace(currentName)) { Console.WriteLine("[File path of currently loaded inventory - {0}]\n", currentName); } string filePath = GetFilename(false, currentName); FileStream s; try { //s = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); s = File.Create(filePath); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); b.Serialize(s, inv); Console.WriteLine(@"Formatted inventory saved to {0}", filePath); s.Close(); currentName = filePath; } catch (ArgumentNullException) { Console.WriteLine("\n[! No valid file selection was made. Returning to Inventory Menu !]\n"); } catch (System.Runtime.Serialization.SerializationException ex) { Console.WriteLine("\n[! IOError: {0}\n Returning to Inventory Menu !]\n", ex.Message); } catch (Exception ex) { Console.WriteLine("\n[! Error: {0}\n Returning to Inventory Menu !]\n", ex.Message); } System.Threading.Thread.Sleep(2000); } public static Inventory LoadInventory(out string filePath) { filePath = GetFilename(true); FileStream s; try { s = File.OpenRead(filePath); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); Inventory inventory = (Inventory)b.Deserialize(s); s.Close(); return inventory; } catch (ArgumentNullException ex) { Console.WriteLine("\n[! No valid file selection was made. Returning to Main Menu !]\n"); } catch (System.Runtime.Serialization.SerializationException ex) { Console.WriteLine("\n[! IOError: {0}\n Returning to Main Menu !]\n", ex.Message); } catch (Exception ex) { Console.WriteLine("\n[! Error: {0}\n Returning to Main Menu !]\n", ex.Message); } System.Threading.Thread.Sleep(2000); return null; } #endregion #region BETTER INPUT - ESCAPE PROMPTS AT ANY TIME /// <summary> /// Allows escape from any user prompt, at any time. /// </summary> /// <param name="prompt">[String] Prompt displayed to user for input.</param> /// <returns>[String] if the Enter key is pressed. [null] if Escape key is pressed.</returns> private static string betterInput(string prompt) { StringBuilder input = new StringBuilder(); ConsoleKeyInfo cki = new ConsoleKeyInfo(); string inputAsStr = null; //Returned as input.ToString() bool inLoop = true; //Set to false when user hits [ENTER] Console.Write(prompt); while (inLoop) { cki = Console.ReadKey(); switch (cki.Key) { case ConsoleKey.Escape: throw new EscapeKeyPressedException(); case ConsoleKey.Backspace: if (input.Length > 0) { input.Remove(input.Length - 1, 1); int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(input.Length + prompt.Length - 1, Console.CursorTop); Console.Write(new string(' ', Console.WindowWidth)); //Clears/Overwrites character removed from input StringBuilder Console.SetCursorPosition(input.Length + prompt.Length - 1, currentLineCursor); //Brings cursor back to same position } else { ClearCurrentConsoleLine(); Console.Write(prompt); } break; case ConsoleKey.Enter: inputAsStr = input.ToString(); inLoop = false; break; default: if (Char.IsLetterOrDigit(cki.KeyChar) || Char.IsPunctuation(cki.KeyChar) || Char.IsSymbol(cki.KeyChar) || Char.IsSeparator(cki.KeyChar) || cki.KeyChar == ' ') { input.Append(cki.KeyChar); } break; } } Console.WriteLine(); return inputAsStr; } private static void ClearCurrentConsoleLine() { int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop); Console.Write(new string(' ', Console.WindowWidth)); Console.SetCursorPosition(0, currentLineCursor); } #endregion } }
using strange.extensions.pool.api; using ViewModelFramework; namespace ViewModelFramework { public interface IModelPool<T> : IPool<T> where T : BaseModel { T GetInstance(BaseModel parent, BaseModelParams param); } }
using Abp.Dapper; using Abp.EntityFrameworkCore.Configuration; using Abp.Modules; using Abp.Reflection.Extensions; using Abp.Zero.EntityFrameworkCore; using DapperExtensions; using DapperExtensions.Mapper; using Dg.KMS.EntityFrameworkCore.Seed; using Dg.KMS.People; using System.Collections.Generic; using System.Reflection; namespace Dg.KMS.EntityFrameworkCore { [DependsOn( typeof(KMSCoreModule), typeof(AbpZeroCoreEntityFrameworkCoreModule), typeof(AbpDapperModule))] public class KMSEntityFrameworkModule : AbpModule { /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */ public bool SkipDbContextRegistration { get; set; } public bool SkipDbSeed { get; set; } public override void PreInitialize() { if (!SkipDbContextRegistration) { Configuration.Modules.AbpEfCore().AddDbContext<KMSDbContext>(options => { if (options.ExistingConnection != null) { KMSDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection); } else { KMSDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString); } }); } } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(KMSEntityFrameworkModule).GetAssembly()); //这里会自动去扫描程序集中配置好的映射关系 DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(KMSEntityFrameworkModule).GetAssembly() }); } public override void PostInitialize() { if (!SkipDbSeed) { SeedHelper.SeedHostDb(IocManager); } } } public class PersonMapper : ClassMapper<Person> { public PersonMapper() { Table("Persons"); Map(x => x.Roles).Ignore(); AutoMap(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pyramid { class Program { static void PrintPyramid(int numOfRow) { for(var i = 1; i<= numOfRow; i ++) { for (var spaces = 1; spaces <= (numOfRow - i); spaces++) Console.Write(" "); for (var Number = 1; Number <= i; Number++) Console.Write("#"); for(var Number = (i-1); Number >=1; Number--) Console.Write("#"); Console.WriteLine(); } } static void Main(string[] args) { PrintPyramid(8); int numberoflayer = 6, Space, Number; Console.WriteLine("Print paramid"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Item_Serializable { new public string name = "New Item"; //public Sprite icon = null; public bool isDefaultItem = false; public int type; //0: Static //1: Equipable //2: Interactable //3: Consumable public int bonusAttack; public int bonusDefense; public int bonusMaxHP; public int bonusMaxSP; public bool equiped; //public GameObject rotatingItem; }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using OrgMan.DataContracts.Repository.RepositoryBase; using OrgMan.DataModel; using System.Data; namespace OrgMan.Data.Repository.Repositorybase { public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class, IEntityUID { internal OrgManEntities Context; internal DbSet<TEntity> DbSet; public GenericRepository(OrgManEntities context) { Context = context; DbSet = Context.Set<TEntity>(); } public virtual IEnumerable<TEntity> Get( List<Guid> mandatorUids, Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "", int? numberOfRows = null) { IQueryable<TEntity> query = DbSet; if (filter != null) { query = query.Where(filter); } if (!string.IsNullOrEmpty(includeProperties)) { foreach (var includeProperty in includeProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } } if (orderBy != null) { query = orderBy(query); } var list = query.ToList(); if (mandatorUids != null) { list = list.Where(q => q.MandatorUIDs != null && mandatorUids.Intersect(q.MandatorUIDs).Any()).ToList(); } if (numberOfRows != null) { list = list.Take(numberOfRows.Value).ToList(); } return list; } public virtual TEntity Get(List<Guid> mandatorUids, Guid uid) { var entity = DbSet.FirstOrDefault(t => t.UID == uid); if (entity.MandatorUIDs.Intersect(mandatorUids).Any()) { return entity; } else { throw new UnauthorizedAccessException(string.Format("{0} from another Mandator", entity.GetType().BaseType.Name)); } } public virtual TEntity Get(Guid uid) { return DbSet.FirstOrDefault(t => t.UID == uid); } public virtual void Insert(List<Guid> mandatorUids, TEntity entity) { if (entity.MandatorUIDs.Intersect(mandatorUids).Any()) { DbSet.Add(entity); } else { throw new UnauthorizedAccessException(string.Format("{0} from another Mandator", entity.GetType().BaseType.Name)); } } public virtual void Insert(TEntity entity) { DbSet.Add(entity); } public virtual void Delete(List<Guid> mandatorUids, Guid uid) { TEntity entityToDelete = DbSet.FirstOrDefault(e => e.UID == uid); if (entityToDelete != null) { if (entityToDelete.MandatorUIDs.Intersect(mandatorUids).Any()) { if (Context.Entry(entityToDelete).State == EntityState.Detached) { DbSet.Attach(entityToDelete); } DbSet.Remove(entityToDelete); } else { throw new UnauthorizedAccessException(string.Format("{0} from another Mandator", entityToDelete.GetType().BaseType.Name)); } } else { throw new DataException(string.Format("No Entity found to UID : {1}", uid)); } } public virtual void Delete(List<Guid> mandatorUids, TEntity entityToDelete) { if(entityToDelete != null) { if (entityToDelete.MandatorUIDs.Intersect(mandatorUids).Any()) { if (Context.Entry(entityToDelete).State == EntityState.Detached) { DbSet.Attach(entityToDelete); } DbSet.Remove(entityToDelete); } else { throw new UnauthorizedAccessException(string.Format("{0} from another Mandator", entityToDelete.GetType().BaseType.Name)); } } else { throw new DataException("No Entity found to delete"); } } public virtual void Delete(Guid uid) { TEntity entityToDelete = DbSet.FirstOrDefault(e => e.UID == uid); if (entityToDelete != null) { if (Context.Entry(entityToDelete).State == EntityState.Detached) { DbSet.Attach(entityToDelete); } DbSet.Remove(entityToDelete); } else { throw new DataException(string.Format("No Entity found to UID : {1}", uid)); } } public virtual void Delete(TEntity entityToDelete) { if (entityToDelete != null) { if (Context.Entry(entityToDelete).State == EntityState.Detached) { DbSet.Attach(entityToDelete); } DbSet.Remove(entityToDelete); } else { throw new DataException("No Entity found to delete"); } } public virtual bool Update(List<Guid> mandatorUids, TEntity entityToUpdate) { var entity = DbSet.Find(entityToUpdate.UID); if (entity == null) { return false; } else { Context.Entry(entity).CurrentValues.SetValues(entityToUpdate); } return true; } public virtual bool Update(TEntity entityToUpdate) { var entity = DbSet.Find(entityToUpdate.UID); if (entity == null) { return false; //Insert(entityToUpdate); } else { Context.Entry(entity).CurrentValues.SetValues(entityToUpdate); return true; } } } }
using Entity; using System; using System.Collections.Generic; using System.Data; using System.ServiceModel; namespace Contracts.MLA { [ServiceContract(SessionMode = SessionMode.Required, Namespace = "http://www.noof.com/", Name = "Addendum")] public interface IMLAService { [OperationContract] bool AddAddendum(MLAAddendum data); [OperationContract] bool AddContinent(string continent); [OperationContract] bool AddCountry(string continent, string country, int id); [OperationContract] bool AddDelivery(string delivery); [OperationContract] bool AddLicensePeriod(string licensePeriod); //[OperationContract] //bool AddRestrictedInternet(MLAAddendumRestrictedInternet data); [OperationContract] bool AddSpecialTerm(string term); //[OperationContract] //bool AddSubLicense(MLAAddendumSubLicense data); //[OperationContract] //bool AddToPurgeQueue(QueuePurge2 data); [OperationContract] bool AddUpdateStudioInfo(ComplianceStudioInfo data, bool isNew); [OperationContract] bool CheckTermExists(string term); [OperationContract] void CreateAddendumMethods(string connectionString, string userName, int instance); [OperationContract] bool DeleteAddendum(int id, string revision); [OperationContract] bool DeleteAddendumReport(string userName); [OperationContract] bool DeleteDelivery(string delivery); //[OperationContract] //bool DeleteItem(int id); [OperationContract] bool DeleteLicensePeriod(string licensePeriod); //[OperationContract] //bool DeleteRestrictedRight(int addendumId); [OperationContract] bool DeleteRights(int mlaId); [OperationContract] bool DeleteSpecialTerm(string term); [OperationContract] bool DeleteStudioInfo(string identifier); //[OperationContract] //bool DeleteSubLicense(int addendumId); //[OperationContract] //List<Actor> GetActors(); //[OperationContract] //DataTable GetAddendumCreateModify(int id); [OperationContract] double GetAmountMLA(int addendumId, int movieId); [OperationContract] DataTable GetAttachRights(int mlaId); [OperationContract] string GetCompanyStudio(int id); [OperationContract] string GetDelivery(string delivery); [OperationContract] List<string> GetDeliveryList(); [OperationContract] DataTable GetDerivatives(int id, string types); [OperationContract] DateTime GetFAD(int id); [OperationContract] string GetLicensePeriod(string license); [OperationContract] List<string> GetLicensePeriodList(); //[OperationContract] //string GetLicenseStartDate(DateTime scheduleDate, int masterId); [OperationContract] DataTable GetLicensors(bool showLFP, bool showInactive); //[OperationContract] //int GetMasterId(int screenerId); [OperationContract] int GetMaxTerritoryId(); [OperationContract] Entity.MLA GetMLAById(int mlaId); [OperationContract] DataTable GetMLAByStudio(int studioId); [OperationContract] DateTime GetMLADate(int mlaId); [OperationContract] List<int> GetMovieIdsMLA(int addendumId); [OperationContract] DataTable GetMovieInfo(int id); [OperationContract] Tuple<string, int> GetMovieInfoAddendum(int movieId); [OperationContract] int GetNextId(); //[OperationContract] //Movie GetMoviePurge(int id); //[OperationContract] //Tuple<int?, int?, int?> GetOptions(int mlaId); [OperationContract] Tuple<DateTime, string> GetOriginalCreateDateUserName(int mlaId, int addendumId, string revision); [OperationContract] List<string> GetPayTerms(); //[OperationContract] //DateTime GetProducedDate(int id); [OperationContract] List<string> GetRatingList(); //[OperationContract] //string GetRatings(int masterId); //[OperationContract] //string GetRatingsMaster(int screenerId); [OperationContract] DataTable GetReportData(int addendumId); [OperationContract] string GetRightById(int id); [OperationContract] DataTable GetRights(); [OperationContract] DataTable GetRightsByMLA(int mlaId); [OperationContract] List<string> GetRightsByYears(int addendumId, int? years); //[OperationContract] //DateTime GetRightsDate(int id, string rights); //[OperationContract] //List<MLATemplateRights> GetRightsForSave(int mlaId); [OperationContract] int GetRightsId(string rights); [OperationContract] string GetRightsString(); [OperationContract] int GetScreenerId(int movieId); //[OperationContract] //DataTable GetScreenerInfo(int screenerId); [OperationContract] int GetScreenerMovieId(int screenerId); //[OperationContract] //List<QueuePurge2> GetSelectedItemForPurge(int id); [OperationContract] string GetSpecialTerm(string term); [OperationContract] List<string> GetSpecialTermList(); [OperationContract] ComplianceStudioInfo GetStudioContact(string identifier); [OperationContract] List<string> GetStudioIdentifiers(); //[OperationContract] //string GetStudioName(int? studioId); [OperationContract] DataTable GetStudios(int id); [OperationContract] DataTable GetTerritories(); [OperationContract] string GetTerritoryById(int id); [OperationContract] int GetTerritoryId(string territory); [OperationContract] string GetTerritoryString(); //[OperationContract] //MLAAddendumTracking GetTrackingInfo(int id); [OperationContract] List<string> GetTypeList(); //[OperationContract] //string GetUserFullName(string loginName); [OperationContract] List<int?> GetYears(int addendumId); //[OperationContract] //bool IsArchivedToDVD(int id); //[OperationContract] //DataTable LoadMovies(DateTime scheduleDate); //[OperationContract] //bool RemoveId(int id); //[OperationContract] //bool ReplaceActor(int oldId, int newId); //[OperationContract] //bool SaveAcquisition(int indexCtr, DateTime scheduleDate, string licensor, string studio, string contractTitle, // string broadcastTitle, int screenerId, string notes); [OperationContract] bool SaveAddendumPrintout(ReportMLAPrintout data); [OperationContract] int SaveMLA(Entity.MLA data); [OperationContract] bool SaveMLADescription(int id, string text); //[OperationContract] //bool SaveNMCNotes(NotMaterialsComplete data); [OperationContract] bool SaveRightsList(List<MLATemplateRights> list); [OperationContract] bool SaveTerm(string term); //[OperationContract] //bool SaveTrackingData(MLAAddendumTracking data); //[OperationContract] //DataTable SearchAddendum(string addendumId); //[OperationContract] //DataTable SearchMaster(string addendumId); [OperationContract] bool UpdateAddendum(int addendumId, int movieId, DateTime fad); //[OperationContract] //bool UpdateBackgroundColor(NotMaterialsComplete data); [OperationContract] bool UpdateContinent(string oldName, string newName); [OperationContract] bool UpdateCountry(string country, string continent, int territoryId); //[OperationContract] //bool UpdateNotificationDate(DateTime date, int indexCtr); [OperationContract] bool UpdateRatings(string ratings, int screenerId, int masterId); [OperationContract] bool UserCanAccess(string moduleName, string settingName, string userName); } }
using System; class MyFirstVariable { static void Main() { int x; x = 7; Console.WriteLine(x); Console.ReadLine(); } }
using MySql.Data.MySqlClient; using System.Threading.Tasks; using System.Windows; namespace Carmotub.Data { public class SQLDataHelper { public MySqlConnection Connection { get; set; } public SQLDataHelper() { } private static SQLDataHelper _instance = null; public static SQLDataHelper Instance { get { if (_instance == null) _instance = new SQLDataHelper(); return _instance; } } public async Task<bool> OpenConnection() { try { string myConnectionString = "Database=carmotub;Data Source=localhost;User Id=root;Password="; Connection = new MySqlConnection(myConnectionString); Connection.Open(); return true; } catch (MySqlException ex) { switch (ex.Number) { case 0: MessageBox.Show("Cannot connect to server. Contact administrator"); break; case 1045: MessageBox.Show("Invalid username/password, please try again"); break; } return false; } } public bool CloseConnection() { try { Connection.Close(); return true; } catch (MySqlException ex) { MessageBox.Show(ex.Message); return false; } } } }