text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; using UnityEngine.UI; using TMPro; public class SettingsMenu : MonoBehaviour { public AudioMixer audioMixer; public TMP_Dropdown resolutionDropdown; public Slider SFXVolume; public Slider MasterVolume; public Slider MusicVolume; Resolution[] resolutions; void Start() { resolutions = Screen.resolutions; resolutionDropdown.ClearOptions(); List<string> options = new List<string>(); int currentResolutionIndex = 0; for (int i = 0; i < resolutions.Length; i++) { string option = resolutions[i].width + "x" + resolutions[i].height + ", " + resolutions[i].refreshRate + "hz"; options.Add(option); if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height) { currentResolutionIndex = i; } } resolutionDropdown.AddOptions(options); resolutionDropdown.value = currentResolutionIndex; resolutionDropdown.RefreshShownValue(); { audioMixer.GetFloat("Volume", out float volume); MasterVolume.value = volume; } { audioMixer.GetFloat("SFX", out float volume); SFXVolume.value = volume; } { audioMixer.GetFloat("Music", out float volume); MusicVolume.value = volume; } } public void SetResolution(int resolutionIndex) { Resolution resolution = resolutions[resolutionIndex]; Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen, resolution.refreshRate); } public void SetVolumeMaster(float volume) { audioMixer.SetFloat("Volume", volume); } public void SetVolumeSFX(float volume) { audioMixer.SetFloat("SFX", volume); audioMixer.SetFloat("Player", volume); } public void SetVolumeMusic(float volume) { audioMixer.SetFloat("Music", volume); } public void SetFullScreen(bool isFullscreen) { Screen.fullScreen = isFullscreen; } }
using BooksWebAPI.Server.Interfaces; using BooksWebAPI.Server.Models; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web; using System.Web.Hosting; using System.Xml.Serialization; namespace BooksWebAPI.Server.Repositories { public class BookRepository : IBookRepository { private CatalogEm Catalog { get; set; } public BookRepository() { #region deserialize books xml file XmlSerializer xmlSerializer = new XmlSerializer(typeof(CatalogEm)); using (var reader = new StreamReader(HostingEnvironment.MapPath(@"~/App_Data/books.xml"))) { Catalog = (CatalogEm)xmlSerializer.Deserialize(reader); } #endregion } public BookEm GetSingleById(string id) { BookEm retrieved = Catalog.Books.Where(b => b.Id == id).FirstOrDefault(); return retrieved == null ? null : retrieved; } public List<BookEm> GetAllByTitleString(string title) { return Catalog.Books.Where(b => b.Title.Contains(title)).ToList(); } public List<BookEm> GetAllByGenreString(string genre) { return Catalog.Books.Where(b => b.Genre == genre).ToList(); } } }
using System; using System.Collections.Generic; using System.Text; namespace OsuUtils.Configuration.Profile { public enum FrameSyncMode { VSync, PowerSaving, Optimal, Unlimited, } public interface IGraphics { public FrameSyncMode FrameSync { get; } public bool FpsCounter { get; } /// <summary> /// Compatibility mode /// </summary> public bool CompatibilityContext { get; } /// <summary> /// ForceFrameFlush /// </summary> public bool ForceFrameFlush { get; } public bool DetectPerformanceIssues { get; } public int Height { get; } public int Width { get; } public bool Fullscreen { get; } } }
namespace EPI.Sorting { /// <summary> /// Design an algorithm that takes as input two teams and the height of the players and checks if its /// possible to place players to take a photo subject to the placement constraint. /// The palcement constraint requires both teams to have the same number of players. All team members /// must be in the same row. And all players in the back row must be taller than the player in front of them. /// </summary> public static class TeamPhotoDay { public static bool IsPhotoPlacementPossible(int[] teamAPlayerHeights, int[] teamBPlayerHeights) { // sort each team's player height QuickSort<int>.Sort(teamAPlayerHeights); QuickSort<int>.Sort(teamBPlayerHeights); // let player at index 0 decide which team can be at front row bool isTeamAAtFrontRow = teamAPlayerHeights[0] < teamBPlayerHeights[0]; for (int i = 0; i < teamAPlayerHeights.Length && i < teamBPlayerHeights.Length; i++) { if (isTeamAAtFrontRow) { if (teamAPlayerHeights[i] >= teamBPlayerHeights[i]) { return false; } } else // team B is front row { if (teamBPlayerHeights[i] >= teamAPlayerHeights[i]) { return false; } } } return true; } } }
using System; using System.Collections.Generic; namespace DemoEF.Domain.Models { public partial class TbOrderMeasurement { public long Id { get; set; } public long? OrderFlowId { get; set; } public long? DecoratorFlowId { get; set; } public DateTime? AddTime { get; set; } public long? OptUser { get; set; } public string OptUsername { get; set; } public string EventType { get; set; } public string MeasurementState { get; set; } public string MeasurementIntention { get; set; } public DateTime? MeasurementFlowupTime { get; set; } public string MeasurementAddress { get; set; } public DateTime? MeasurementAppointmentTime { get; set; } public string MeasurementRecordtxt { get; set; } public DateTime? MeasurementNextflowupTime { get; set; } public DateTime? MeasurementTime { get; set; } public string MeasurementRecordtype { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SamOthellop.Model.Agents { public class AgentDict { public Dictionary<string, Type> AgentDictionary; public AgentDict() { var asm = Assembly.GetExecutingAssembly(); var agents = AgentDictHelper.GetTypesWithInterface(asm); IEnumerable<string> agentStrings = agents.Select((agent) => ((Type)agent).Name); AgentDictionary = agentStrings.Zip(agents, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v); } } public static class AgentDictHelper { public static IEnumerable<Type> GetTypesWithInterface(Assembly asm) { var it = typeof(IOthelloAgent); return asm.GetLoadableTypes().Where(it.IsAssignableFrom) .Where(t=>!(t.Equals(typeof(IOthelloAgent)))) .Where(t=>!(t.Equals(typeof(IEvaluationAgent)))).ToList(); } private static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } } } }
using System; namespace CustomDoublyLinkedList { public class Program { static void Main(string[] args) { var doubly = new CustomDoublyLinkedList<string>(); doubly.AddFirst("5");//5 doubly.AddLast("4");//5,4 doubly.AddFirst("4");//4,5,4 doubly.AddFirst("2");//2,4,5,4 doubly.AddFirst("3");//3,2,4,5,4 doubly.ForEach(Console.WriteLine); doubly.ForEach(Console.WriteLine); var arr = doubly.ToArray(); doubly.ForEach(Console.WriteLine); } } }
using Teste_CRUD_CiaTecnica.Domain.Entities; namespace Teste_CRUD_CiaTecnica.Domain.Interfaces.Services { public interface IPessoaFisicaService : IServiceBase<PessoaFisica> { bool CPFJaExiste(string cpf); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using SSISTeam9.Models; namespace SSISTeam9.DAO { public class StockCardDAO { public static List<StockCard> GetStockCardById(long ItemId) { List<StockCard> stockCards = new List<StockCard>(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); //display 50 rows of record string q = @"SELECT TOP 50 * FROM StockCard​ WHERE itemId = '" + ItemId + "' ORDER BY date"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { StockCard stockCard = new StockCard() { ItemId = (long)reader[1], Date = (DateTime)reader[2], SourceType = (int)reader[3], SourceId = (long)reader[4], Qty = (string)reader[5], Balance = (int)reader[6] }; stockCards.Add(stockCard); } } return stockCards; } public static void CreateStockCardFromDisburse(DisbursementListDetails disbursementDetails, DisbursementList disbursementList, int balance) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"INSERT INTO StockCard (itemId,date,sourceType,sourceId,qty,balance)" + "VALUES ('" + disbursementDetails.Item.ItemId + "','" + disbursementList.date.Year + "-" + disbursementList.date.Month + "-" + disbursementList.date.Day + " " + disbursementList.date.Hour + ":" + disbursementList.date.Minute + ":" + disbursementList.date.Second + "','2','" + disbursementList.Department.DeptId + "','- " + disbursementDetails.Quantity + "','" + balance + "')"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } public static void CreateStockCardFromOrder(StockCard stockCard) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"INSERT INTO StockCard (itemId,date,sourceType,sourceId,qty,balance)" + "VALUES ('" + stockCard.ItemId + "','" + stockCard.Date.Year + "-" + stockCard.Date.Month + "-" + stockCard.Date.Day + " " + stockCard.Date.Hour + ":" + stockCard.Date.Minute + ":" + stockCard.Date.Second + "','3','" + stockCard.SourceId + "','" + stockCard.Qty + "','" + stockCard.Balance + "')"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } public static void CreateStockCardFromAdj(StockCard stockCard) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"INSERT INTO StockCard (itemId,date,sourceType,sourceId,qty,balance)" + "VALUES ('" + stockCard.ItemId + "','" + stockCard.Date.Year + "-" + stockCard.Date.Month + "-" + stockCard.Date.Day + " " + stockCard.Date.Hour + ":" + stockCard.Date.Minute + ":" + stockCard.Date.Second + "','1','" + stockCard.SourceId + "','" + stockCard.Qty + "','" + stockCard.Balance + "')"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } } }
using System; namespace Piovra.Ds; public class PriorityQueue<T> where T : IComparable<T> { readonly BinaryHeap<T> _heap; PriorityQueue(BinaryHeap<T> heap) => _heap = ARG.NotNull(heap, nameof(heap)); public static PriorityQueue<T> Max(int capacity = INITIAL_CAPACITY) => new(new BinaryHeap<T>(capacity, true)); public static PriorityQueue<T> Min(int capacity = INITIAL_CAPACITY) => new(new BinaryHeap<T>(capacity, false)); public const int INITIAL_CAPACITY = 1; public bool IsMax => _heap.NonIncreasing; public bool IsEmpty() => _heap.IsEmpty(); public void Enqueue(T item) { _heap.Add(item); } public T Dequeue() { var result = _heap.Top(); _heap.Pop(); return result; } public T Peek() { return _heap.Top(); } }
using System; namespace SortingArrayOfObjects { public class Demo2 { public static void Run() { Person[] actress = new Person[5] { new Person("Ishihara", "Satomi"), new Person("Haruna", "kawaguchi"), new Person("Yui", "Aragaki"), new Person("Mikako", "Tabe"), new Person("Haruka", "Ayase") }; Console.WriteLine("Before sorting:"); foreach (Person a in actress) { Console.WriteLine("{0} {1}", a.firstName, a.lastName); } // Sorting actress array Array.Sort(actress); Console.WriteLine("\nAfter sorting:"); foreach (Person a in actress) { Console.WriteLine("{0} {1}", a.firstName, a.lastName); } } } }
using System; using System.Collections.Generic; using System.Globalization; using Atc.Extensions.BaseTypes; using Xunit; namespace Atc.Tests.Extensions { public class StringExtensionsTests { [Theory] [InlineData(new[] { 4, 7 }, "Hallo world", "o")] public void IndexersOf(int[] expected, string input, string pattern) => Assert.Equal(expected, input.IndexersOf(pattern)); [Theory] [InlineData(new[] { 4, 7, 24 }, "Hallo world. Over the top.", "o", false)] [InlineData(new[] { 4, 7, 13, 24 }, "Hallo world. Over the top.", "o", true)] public void IndexersOf_IgnoreCaseSensitive(int[] expected, string input, string pattern, bool ignoreCaseSensitive) => Assert.Equal(expected, input.IndexersOf(pattern, ignoreCaseSensitive)); [Theory] [InlineData(new[] { 4, 7, 24 }, "Hallo world. Over the top.", "o", false, false)] [InlineData(new[] { 4, 7, 13, 24 }, "Hallo world. Over the top.", "o", true, false)] [InlineData(new[] { 5, 8, 25 }, "Hallo world. Over the top.", "o", false, true)] [InlineData(new[] { 5, 8, 14, 25 }, "Hallo world. Over the top.", "o", true, true)] public void IndexersOf_IgnoreCaseSensitive_UseEndOfPatternToMatch(int[] expected, string input, string pattern, bool ignoreCaseSensitive, bool useEndOfPatternToMatch) => Assert.Equal(expected, input.IndexersOf(pattern, ignoreCaseSensitive, useEndOfPatternToMatch)); [Theory] [InlineData(1, "Hallo-world")] [InlineData(2, "Hallo world")] [InlineData(2, "Hallo world .")] public void WordCount(int expected, string input) => Assert.Equal(expected, input.WordCount()); [Theory] [InlineData(0, "Hallo world")] [InlineData(2, "Hest {0}, {1}")] [InlineData(-1, "Hest {0, {1}")] [InlineData(-1, "Hest {a}, {1}")] [InlineData(1, "Hest {0}, {0}")] [InlineData(-1, "Hest {{0}, {0}")] [InlineData(-1, "Hest {0{0}}, {0}")] [InlineData(-1, "Hest {{0}0}, {0}")] public void GetStringFormatParameterNumericCount(int expected, string input) => Assert.Equal(expected, input.GetStringFormatParameterNumericCount()); [Theory] [InlineData(0, "Hallo world")] [InlineData(1, "Hest {a}")] [InlineData(1, "Hest {a} {a}")] [InlineData(2, "Hest {a} {A}")] [InlineData(2, "Hest {a} {b}")] [InlineData(-1, "Hest {a, {1}")] [InlineData(-1, "Hest {a}, {1}")] [InlineData(-1, "Hest {0}, {0}")] [InlineData(-1, "Hest {{a}, {0}")] [InlineData(-1, "Hest {a{a}}, {a}")] [InlineData(-1, "Hest {{a}a}, {a}")] public void GetStringFormatParameterLiteralCount(int expected, string input) => Assert.Equal(expected, input.GetStringFormatParameterLiteralCount()); [Theory] [InlineData(new string[] { }, "Hallo World")] [InlineData(new string[] { }, "Hallo World {0}-{1}")] [InlineData(new[] { "{{0}}", "{{1}}", "{{A1}}" }, "Hallo World {{0}}-{{1}}-{{A1}}")] public void GetStringFormatParameterTemplatePlaceholders(string[] expected, string input) => Assert.Equal(expected, input.GetStringFormatParameterTemplatePlaceholders()); [Theory] [InlineData("Hallo World John-Doe-42", "Hallo World {{0}}-{{1}}-{{A1}}", new[] { "0", "John", "1", "Doe", "A1", "42" })] [InlineData("Hallo World John-Doe-42", "Hallo World {{0}}-{{1}}-{{A1}}", new[] { "{{0}}", "John", "{{1}}", "Doe", "{{A1}}", "42" })] public void SetStringFormatParameterTemplatePlaceholders(string expected, string input, string[] data) { // Arrange var replacements = new Dictionary<string, string>(StringComparer.Ordinal); for (var i = 0; i < data.Length; i += 2) { replacements.Add(data[i], data[i + 1]); } // Act var actual = input.SetStringFormatParameterTemplatePlaceholders(replacements); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("2000-12-01T23:47:37", "2000-12-01T23:47:37")] public void ParseDateFromIso8601(string expected, string input) { // Act var actual = input.ParseDateFromIso8601(); // Assert Assert.Equal(expected, actual.ToIso8601Date()); } [Theory] [InlineData(true, "2000-12-01T23:47:37")] [InlineData(false, "2000-12-01")] public void TryParseDateFromIso8601(bool expected, string input) => Assert.Equal(expected, input.TryParseDateFromIso8601(out var _)); [Theory] [InlineData(true, "03-24-2000")] [InlineData(false, "24-03-2000")] public void TryParseDate(bool expected, string input) => Assert.Equal(expected, input.TryParseDate(out var _)); [Theory] [InlineData(false, "03-24-2000")] [InlineData(true, "24-03-2000")] public void TryParseDate_DanishCultureCulture(bool expected, string input) => Assert.Equal(expected, input.TryParseDate(out var _, GlobalizationConstants.DanishCultureInfo)); [Theory] [InlineData(false, "03-24-2000", DateTimeStyles.None)] [InlineData(true, "24-03-2000", DateTimeStyles.None)] public void TryParseDate_DanishCultureCulture_DateTimeStyles(bool expected, string input, DateTimeStyles dateTimeStyles) => Assert.Equal(expected, input.TryParseDate(out var _, GlobalizationConstants.DanishCultureInfo, dateTimeStyles)); [Theory] [InlineData("Hallo world")] public void Base64Encode(string input) { // Act var encodeData = input.Base64Encode(); // Assert Assert.NotNull(encodeData); } [Theory] [InlineData("Hallo world")] public void Base64Decode(string input) { // Arrange var encodeData = input.Base64Encode(); // Act var decodeData = encodeData!.Base64Decode(); // Assert Assert.NotNull(decodeData); Assert.Equal(input.Length, decodeData.Length); } [Theory] [InlineData("<script>window.alert('Hallo')</script>", "<script>window.alert('Hallo')</script>", false)] [InlineData("&lt;script&gt;window.alert(&#39;Hallo&#39;)&lt;/script&gt;", "<script>window.alert('Hallo')</script>", true)] public void JavaScriptEncode(string expected, string input, bool htmlEncode) => Assert.Equal(expected, input.JavaScriptEncode(htmlEncode)); [Theory] [InlineData("<script>window.alert('Hallo')</script>", "<script>window.alert('Hallo')</script>", false)] [InlineData("<script>window.alert('Hallo')</script>", "&lt;script&gt;window.alert(&#39;Hallo&#39;)&lt;/script&gt;", true)] public void JavaScriptDecode(string expected, string input, bool htmlDecode) => Assert.Equal(expected, input.JavaScriptDecode(htmlDecode)); [Theory] [InlineData("&lt;root&gt;&lt;node name=&#39;TheName&#39;&gt;Hallo&lt;/node&gt;&lt;/root&gt;", "<root><node name='TheName'>Hallo</node></root>")] public void XmlEncode(string expected, string input) => Assert.Equal(expected, input.XmlEncode()); [Theory] [InlineData("<root><node name='TheName'>Hallo</node></root>", "&lt;root&gt;&lt;node name=&#39;TheName&#39;&gt;Hallo&lt;/node&gt;&lt;/root&gt;")] public void XmlDecode(string expected, string input) => Assert.Equal(expected, input.XmlDecode()); [Theory] [InlineData("abc", "abc")] [InlineData("abc", "bac")] [InlineData("Bac", "aBc")] [InlineData("Bac", "Bac")] public void Alphabetize(string expected, string input) => Assert.Equal(expected, input.Alphabetize()); [Theory] [InlineData("abc", "&agrave;bc")] [InlineData("abc", "&aacute;bc")] [InlineData("abc", "&acirc;bc")] [InlineData("abc", "&atilde;bc")] [InlineData("abc", "&auml;bc")] public void NormalizeAccents(string expected, string input) => Assert.Equal(expected, input.NormalizeAccents()); [Theory] [InlineData("abc", "&agrave;bc", LetterAccentType.Grave, true, true, true)] [InlineData("abc", "&aacute;bc", LetterAccentType.Acute, true, true, true)] [InlineData("abc", "&acirc;bc", LetterAccentType.Circumflex, true, true, true)] [InlineData("abc", "&atilde;bc", LetterAccentType.Tilde, true, true, true)] [InlineData("abc", "&auml;bc", LetterAccentType.Umlaut, true, true, true)] public void NormalizeAccents_LetterAccentType_LetterAccentType_Decode_ForLower_ForUpper(string expected, string input, LetterAccentType letterAccentType, bool decode, bool forLower, bool forUpper) => Assert.Equal(expected, input.NormalizeAccents(letterAccentType, decode, forLower, forUpper)); [Theory] [InlineData("Hallo world", "HalloWorld")] [InlineData("Hallo_ world", "Hallo_World")] public void NormalizePascalCase(string expected, string input) => Assert.Equal(expected, input.NormalizePascalCase()); [Theory] [InlineData("Hallo World", "HalloWorld")] [InlineData("Hallo World", "Hallo_World")] public void Humanize(string expected, string input) => Assert.Equal(expected, input.Humanize()); [Theory] [InlineData("halloWorld", "HalloWorld")] [InlineData("hallo world", "Hallo world")] [InlineData("hallo World", "Hallo World")] public void CamelCase(string expected, string input) => Assert.Equal(expected, input.CamelCase()); [Theory] [InlineData("HalloWorld", "halloWorld")] [InlineData("Hallo World", "hallo World")] [InlineData("Hallo World", "hallo world")] [InlineData("Hallo World-Yea", "HALLO WORLD-YeA")] public void PascalCase(string expected, string input) => Assert.Equal(expected, input.PascalCase()); [Theory] [InlineData("HalloWorld", "halloWorld", false)] [InlineData("Hallo World", "hallo World", false)] [InlineData("Hallo World", "hallo world", false)] [InlineData("Hallo World-Yea", "HALLO WORLD-YeA", false)] [InlineData("HalloWorld", "halloWorld", true)] [InlineData("HalloWorld", "hallo World", true)] [InlineData("HalloWorld", "hallo world", true)] [InlineData("HalloWorldYea", "HALLO WORLD-YeA", true)] public void PascalCase_RemoveSeparators(string expected, string input, bool removeSeparators) => Assert.Equal(expected, input.PascalCase(removeSeparators)); [Theory] [InlineData("HalloWorld", "halloWorld", new[] { ' ', '-' })] [InlineData("Hallo World", "hallo World", new[] { ' ', '-' })] [InlineData("Hallo World", "hallo world", new[] { ' ', '-' })] [InlineData("Hallo-World", "hallo-World", new[] { ' ', '-' })] [InlineData("Hallo-World", "hallo-world", new[] { ' ', '-' })] public void PascalCase_Separators(string expected, string input, char[] separators) => Assert.Equal(expected, input.PascalCase(separators)); [Theory] [InlineData("HalloWorld", "halloWorld", new[] { ' ', '-' }, false)] [InlineData("Hallo World", "hallo World", new[] { ' ', '-' }, false)] [InlineData("Hallo World", "hallo world", new[] { ' ', '-' }, false)] [InlineData("Hallo-World", "hallo-World", new[] { ' ', '-' }, false)] [InlineData("Hallo-World", "hallo-world", new[] { ' ', '-' }, false)] [InlineData("HalloWorld", "halloWorld", new[] { ' ', '-' }, true)] [InlineData("HalloWorld", "hallo World", new[] { ' ', '-' }, true)] [InlineData("HalloWorld", "hallo world", new[] { ' ', '-' }, true)] [InlineData("HalloWorld", "hallo-World", new[] { ' ', '-' }, true)] [InlineData("HalloWorld", "hallo-world", new[] { ' ', '-' }, true)] public void PascalCase_Separators_RemoveSeparators(string expected, string input, char[] separators, bool removeSeparators) => Assert.Equal(expected, input.PascalCase(separators, removeSeparators)); [Theory] [InlineData("Hallo{{NEWLINE}}World", "Hallo\r\nWorld")] [InlineData("Hallo{{NEWLINE}}World", "Hallo\nWorld")] [InlineData("Hallo{{NEWLINE}}World", "Hallo\rWorld")] [InlineData("Hallo{{NEWLINE}}World{{NEWLINE}}John{{NEWLINE}}Doe", "Hallo\r\nWorld\nJohn\rDoe")] public void EnsureEnvironmentNewLines(string expected, string input) => Assert.Equal(expected.Replace("{{NEWLINE}}", Environment.NewLine, StringComparison.Ordinal), input.EnsureEnvironmentNewLines()); [Theory] [InlineData("Hallo", "hallo")] public void EnsureFirstCharacterToUpper(string expected, string input) => Assert.Equal(expected, input.EnsureFirstCharacterToUpper()); [Theory] [InlineData("hallo", "Hallo")] public void EnsureFirstCharacterToLower(string expected, string input) => Assert.Equal(expected, input.EnsureFirstCharacterToLower()); [Theory] [InlineData("Hallo", "Hallo")] [InlineData("Hallo", "Hallos")] public void EnsureSingular(string expected, string input) => Assert.Equal(expected, input.EnsureSingular()); [Theory] [InlineData("Hallos", "Hallo")] [InlineData("Hallos", "Hallos")] public void EnsurePlural(string expected, string input) => Assert.Equal(expected, input.EnsurePlural()); [Theory] [InlineData("Hallo", "hallo")] [InlineData("Hallo", "hallos")] public void EnsureFirstCharacterToUpperAndSingular(string expected, string input) => Assert.Equal(expected, input.EnsureFirstCharacterToUpperAndSingular()); [Theory] [InlineData("Hallos", "hallo")] [InlineData("Hallos", "hallos")] public void EnsureFirstCharacterToUpperAndPlural(string expected, string input) => Assert.Equal(expected, input.EnsureFirstCharacterToUpperAndPlural()); [Theory] [InlineData(false, "Hallo World", "world")] [InlineData(true, "Hallo World", "World")] public void Contains(bool expected, string inputA, string inputB) => Assert.Equal(expected, inputA.Contains(inputB, StringComparison.Ordinal)); [Theory] [InlineData(false, "Hallo World", "world", false)] [InlineData(true, "Hallo World", "world", true)] public void Contains_IgnoreCaseSensitive(bool expected, string inputA, string inputB, bool ignoreCaseSensitive) => Assert.Equal(expected, inputA.Contains(inputB, ignoreCaseSensitive)); [Theory] [InlineData("Hallo Wo...", "Hallo World", 8)] [InlineData("Hallo World", "Hallo World", 20)] public void Cut(string expected, string input, int maxLength) => Assert.Equal(expected, input.Cut(maxLength)); [Theory] [InlineData("Hallo Wo#", "Hallo World", 8, "#")] [InlineData("Hallo World", "Hallo World", 20, "#")] public void Cut_AppendValue(string expected, string input, int maxLength, string appendValue) => Assert.Equal(expected, input.Cut(maxLength, appendValue)); [Theory] [InlineData("Hallo Wo#ld", "Hallo World", 8, '#')] public void ReplaceAt(string expected, string input, int index, char newChar) => Assert.Equal(expected, input.ReplaceAt(index, newChar)); [Theory] [InlineData("Hallo World John-Doe-42", "Hallo World 0-1-2", new[] { "0", "John", "1", "Doe", "2", "42" })] [InlineData("Hallo World John-Doe-42", "Hallo World {{0}}-{{1}}-{{A1}}", new[] { "{{0}}", "John", "{{1}}", "Doe", "{{A1}}", "42" })] public void ReplaceMany_ReplacementsKeyValue(string expected, string input, string[] data) { // Arrange var replacements = new Dictionary<string, string>(StringComparer.Ordinal); for (var i = 0; i < data.Length; i += 2) { replacements.Add(data[i], data[i + 1]); } // Act var actual = input.ReplaceMany(replacements); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("H#ll# W#rld", "Hallo World", new[] { 'a', 'o' }, '#')] public void ReplaceMany_Chars(string expected, string input, char[] chars, char replacement) => Assert.Equal(expected, input.ReplaceMany(chars, replacement)); [Theory] [InlineData("Hallo World", "Hallo\r\nWorld", " ")] [InlineData("Hallo World", "Hallo\nWorld", " ")] [InlineData("Hallo World", "Hallo\rWorld", " ")] [InlineData("Hallo World John Doe", "Hallo\r\nWorld\nJohn\rDoe", " ")] [InlineData("Hallo-World-John-Doe", "Hallo\r\nWorld\nJohn\rDoe", "-")] public void ReplaceNewLines(string expected, string input, string newValue) => Assert.Equal(expected, input.ReplaceNewLines(newValue)); [Theory] [InlineData("HalloWorld", "Hallo\r\nWorld")] [InlineData("HalloWorld", "Hallo\nWorld")] [InlineData("HalloWorld", "Hallo\rWorld")] [InlineData("HalloWorldJohnDoe", "Hallo\r\nWorld\nJohn\rDoe")] public void RemoveNewLines(string expected, string input) => Assert.Equal(expected, input.RemoveNewLines()); [Theory] [InlineData("llo World", "Hallo World", "Ha")] public void RemoveStart(string expected, string input, string startValue) => Assert.Equal(expected, input.RemoveStart(startValue)); [Theory] [InlineData("Hallo World", "Hallo World", "HA", false)] [InlineData("llo World", "Hallo World", "HA", true)] public void RemoveStart_IgnoreCaseSensitive(string expected, string input, string startValue, bool ignoreCaseSensitive) => Assert.Equal(expected, input.RemoveStart(startValue, ignoreCaseSensitive)); [Theory] [InlineData("Hallo Wor", "Hallo World", "ld")] public void RemoveEnd(string expected, string input, string endValue) => Assert.Equal(expected, input.RemoveEnd(endValue)); [Theory] [InlineData("Hallo World", "Hallo World", "LD", false)] [InlineData("Hallo Wor", "Hallo World", "LD", true)] public void RemoveEnd_IgnoreCaseSensitive(string expected, string input, string endValue, bool ignoreCaseSensitive) => Assert.Equal(expected, input.RemoveEnd(endValue, ignoreCaseSensitive)); [Theory] [InlineData("Hallo World", "Hallo World/")] public void RemoveEndingSlashIfExist(string expected, string input) => Assert.Equal(expected, input.RemoveEndingSlashIfExist()); [Theory] [InlineData("Hallo World", "Hallo\u0006World")] public void RemoveDataCrap(string expected, string input) => Assert.Equal(expected, input.RemoveDataCrap()); [Theory] [InlineData("Hallo Wo...", "Hallo World", 8)] [InlineData("Hallo World", "Hallo World", 20)] public void Truncate(string expected, string input, int maxLength) => Assert.Equal(expected, input.Truncate(maxLength)); [Theory] [InlineData("Hallo Wo#", "Hallo World", 8, "#")] [InlineData("Hallo World", "Hallo World", 20, "#")] public void Truncate_AppendValue(string expected, string input, int maxLength, string appendValue) => Assert.Equal(expected, input.Truncate(maxLength, appendValue)); [Theory] [InlineData("Hallo World.", " Hallo\tWorld.. ")] public void TrimSpecial(string expected, string input) => Assert.Equal(expected, input.TrimSpecial()); [Theory] [InlineData("Hallo World", "Hallo World")] [InlineData("Hallo World", " Hallo World ")] public void TrimExtended(string expected, string input) => Assert.Equal(expected, input.TrimExtended()); [Theory] [InlineData(new string[0], null)] [InlineData(new[] { "Hallo", "World" }, "Hallo\r\nWorld")] public void ToLines(string[] expected, string input) => Assert.Equal(expected, input.ToLines()); [Theory] [InlineData("MyData", "MyData")] [InlineData("MyData", "List<MyData>")] [InlineData("MyData", "Hallo world List<MyData> HalloFoo")] [InlineData("MyData Foo", "MyData Foo")] [InlineData("MyDataListFoo", "MyDataListFoo")] public void GetValueBetweenLessAndGreaterThanCharsIfExist(string expected, string input) => Assert.Equal(expected, input.GetValueBetweenLessAndGreaterThanCharsIfExist()); [Fact] public void ToStream() { // Arrange const string input = "Hallo word"; // Atc var actual = input.ToStream(); // Assert Assert.NotNull(actual); } [Fact] public void ToStreamFromBase64() { // Arrange var input = "Hallo word".Base64Encode(); // Atc var actual = input!.ToStreamFromBase64(); // Assert Assert.NotNull(actual); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WorldGenerator : MonoBehaviour { [Header("Random Generator")] public int seed = 0; public bool randomizeSeed = false; private System.Random randomGenerator; [Header("World Parameters")] public int chunkSize = 49; public int chunkDistance = 4; public GameObject chunkObject; public float chunkUnit = 2f; private Dictionary<Vector2, GameObject> loadedChunks; public Transform playerTransform; private Vector2 oldChunkIndex; [Header("Terrain Parameters")] public float noiseScale = 80f; public int noiseOctaves = 5; [Range(0f,1f)] public float noisePersistance = 0.35f; public float noiseLacunarity = 3f; public float noiseAmplitude = 10f; public float islandRadius = 60f; private Vector2 offset; [Header("Editor")] public bool autoUpdate = true; private void InitializeRandomGenerator() { if (randomizeSeed) { seed = Random.Range (-100000, 100000); } randomGenerator = new System.Random (seed); } public void GenerateChunks() { InitializeRandomGenerator (); for (int i = transform.childCount - 1; i >= 0; i--) { DestroyImmediate(transform.GetChild(i).gameObject); } offset = new Vector2 ( (float)randomGenerator.Next (-100000, 100000), (float)randomGenerator.Next (-100000, 100000) ); loadedChunks = new Dictionary<Vector2, GameObject> (); for (int y = -chunkDistance; y < chunkDistance + 1; y++) { for (int x = -chunkDistance; x < chunkDistance + 1; x++) { Vector2 chunkIndex = new Vector2 (x, y); GameObject chunk = GenerateChunk (x, y, offset); loadedChunks.Add (chunkIndex, chunk); } } } private GameObject GenerateChunk(int chunkIndexX, int chunkIndexY, Vector2 offset) { GameObject chunk = Instantiate(chunkObject); chunk.name = "Chunk_" + chunkIndexX.ToString () + "_" + chunkIndexY.ToString (); chunk.transform.position = new Vector3 (chunkIndexX * (chunkSize - 1), 0f, chunkIndexY * (chunkSize - 1)) * chunkUnit; chunk.transform.SetParent (transform, true); float[,] terrainHeightMap = TerrainGenerator.GenerateHeightMap (chunkIndexX, chunkIndexY, chunkSize, chunkUnit, noiseScale, noiseOctaves, noisePersistance, noiseLacunarity, noiseAmplitude, islandRadius, offset); Mesh terrainMesh = TerrainGenerator.GenerateMesh (terrainHeightMap, chunkUnit); chunk.GetComponent<MeshFilter> ().sharedMesh = terrainMesh; chunk.GetComponent<MeshCollider> ().sharedMesh = terrainMesh; return chunk; } private void Update() { Vector3 playerPosition = playerTransform.position; // Get chunk index the player is currently in int nX = 0; while (true) { if (Mathf.Abs (playerPosition.x) <= chunkSize * (nX + 0.5f)) { break; } else { nX++; } } int nY = 0; while (true) { if (Mathf.Abs (playerPosition.z) <= chunkSize * (nY + 0.5f)) { break; } else { nY++; } } Vector2 currentChunkIndex = new Vector2 (nX, nY); if (Vector2.Distance(currentChunkIndex, oldChunkIndex) <= Mathf.Epsilon) { // Disable all chunks around oldChunk for (int y = -chunkDistance + (int)oldChunkIndex.y; y < chunkDistance + (int)oldChunkIndex.y + 1; y++) { for (int x = -chunkDistance + (int)oldChunkIndex.x; x < chunkDistance + (int)oldChunkIndex.x + 1; x++) { Vector2 chunkIndex = new Vector2 (x, y); GameObject chunk = GenerateChunk (x, y, offset); loadedChunks [chunkIndex].SetActive (false); } } // Enable or create new chunks around currentChunk for (int y = -chunkDistance + (int)currentChunkIndex.y; y < chunkDistance + (int)currentChunkIndex.y + 1; y++) { for (int x = -chunkDistance + (int)currentChunkIndex.x; x < chunkDistance + (int)currentChunkIndex.x + 1; x++) { Vector2 chunkIndex = new Vector2 (x, y); if (loadedChunks.ContainsKey (chunkIndex)) { loadedChunks [chunkIndex].SetActive (true); } else { GameObject chunk = GenerateChunk (x, y, offset); } } } } } private void OnValidate() { if (chunkSize < 2) { Debug.Log ("chunkSize is smaller than 2!"); chunkSize = 2; } else if (chunkSize > 105) { Debug.Log("chunkSize is greater than 105!"); chunkSize = 105; } if (chunkDistance < 0) { Debug.Log ("chunkDistance is smaller than 0!"); chunkDistance = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Banco.Contas; namespace Banco.Filtros { class ContasComMenosDe100Reais : Filtro { public ContasComMenosDe100Reais(Filtro f) : base(f) { } public ContasComMenosDe100Reais() : base() {} public override IEnumerable<Conta> Filtra(IList<Conta> contas) { IEnumerable<Conta> filtradas = contas.Where(c => c.Saldo < 100).ToList(); IEnumerable<Conta> filtradasDoOutroFiltro = AplicaOutroFiltro(contas); IEnumerable<Conta> todas = filtradas.Concat(filtradasDoOutroFiltro); return todas; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace xKnight.Attacking { public class AttackAnnouncedEventArgs { public AttackAnnounceItem AnnounceItem { get; private set; } internal AttackAnnouncedEventArgs(AttackAnnounceItem announceItem) { AnnounceItem = announceItem; } } }
using System.IO; using System.Data.SQLite; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using SimplySqlSchema.SQLite; namespace SimplySqlSchema.Tests.Manager { [TestClass] public class SQLiteSchemaManagerTests : SqlManagerTestBase { protected string TestDbFile { get; } = "ManagerTest.db"; [TestInitialize] public void Setup() { this.Manager = new SQLiteSchemaManager(); this.Connection = new SQLiteConnection($"Data Source={TestDbFile};Version=3;"); } [TestMethod] public async Task TestGetSchemaNonExistantSchema() { await base.BaseTestGetSchemaNonExistantSchema(); } [TestMethod] public async Task TestGetSchemaCreatedSchema() { await base.BaseTestGetSchemaCreatedSchema(); } [TestMethod] public async Task TestCreateColumnForAllTypes() { await this.BaseTestCreateColumnForAllTypes(); } [TestMethod] public async Task TestAddColumnOnSchema() { await base.BaseTestAddColumnOnSchema(); } [TestCleanup] public void Cleanup() { this.Connection.Dispose(); if (File.Exists(this.TestDbFile)) { File.Delete(this.TestDbFile); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class kingwalk : MonoBehaviour { private Animator anim; public float maxSpeed = 3f; void FixedUpdate() { GetComponent<Rigidbody2D>().velocity = new Vector2(maxSpeed, GetComponent<Rigidbody2D>().velocity.y); } // Start is called before the first frame update void Start() { anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { anim.SetFloat("speed", Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x)); } }
// <copyright company="APX Labs, Inc."> // Copyright (c) APX Labs, Inc. All rights reserved. // </copyright> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Runtime.InteropServices; using Android.Runtime; using System.Collections.Generic; using System; using System.Diagnostics; using System.Collections; namespace ApxLabs.FastAndroidCamera { /// <summary> /// A wrapper around a Java array that reads elements directly from the pointer instead of through /// expensive JNI calls. /// </summary> public sealed class FastJavaByteArray : Java.Lang.Object, IList<byte> { #region Constructors /// <summary> /// Creates a new FastJavaByteArray with the given number of bytes reserved. /// </summary> /// <param name="length">Number of bytes to reserve</param> public FastJavaByteArray(int length) { if (length <= 0) throw new ArgumentOutOfRangeException(); IntPtr arrayHandle = JniEnvEx.NewByteArray(length); if (arrayHandle == IntPtr.Zero) throw new OutOfMemoryException(); // Retain a global reference to the byte array. NewByteArray() returns a local ref, and TransferLocalRef // creates a new global ref to the array and deletes the local ref. SetHandle(arrayHandle, JniHandleOwnership.TransferLocalRef); Count = length; bool isCopy = false; unsafe { // Get the pointer to the byte array using the global Handle Raw = JniEnvEx.GetByteArrayElements(Handle, isCopy); } } /// <summary> /// Creates a FastJavaByteArray wrapper around an existing Java/JNI byte array /// </summary> /// <param name="handle">Native Java array handle</param> /// <param name="readOnly">Whether to consider this byte array read-only</param> public FastJavaByteArray(IntPtr handle, bool readOnly = true) : base(handle, JniHandleOwnership.DoNotTransfer) { // DoNotTransfer is used to leave the incoming handle alone; that reference was created in Java, so it's // Java's responsibility to delete it. DoNotTransfer creates a global reference to use here in the CLR if (handle == IntPtr.Zero) throw new ArgumentNullException("handle"); IsReadOnly = readOnly; Count = JNIEnv.GetArrayLength(Handle); bool isCopy = false; unsafe { // Get the pointer to the byte array using the global Handle Raw = JniEnvEx.GetByteArrayElements(Handle, isCopy); } } #endregion protected override void Dispose(bool disposing) { unsafe { if (Raw != null) // tell Java that we're done with this array JniEnvEx.ReleaseByteArrayElements(Handle, Raw, IsReadOnly ? PrimitiveArrayReleaseMode.Release : PrimitiveArrayReleaseMode.CommitAndRelease); Raw = null; } base.Dispose(disposing); } #region IList<byte> Properties /// <summary> /// Count of bytes /// </summary> public int Count { get; private set; } /// <summary> /// Gets a value indicating whether this byte array is read only. /// </summary> /// <value><c>true</c> if read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get; private set; } /// <summary> /// Indexer /// </summary> /// <param name="index">Index of byte</param> /// <returns>Byte at the given index</returns> public byte this[int index] { get { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(); } byte retval; unsafe { retval = Raw[index]; } return retval; } set { if (IsReadOnly) { throw new NotSupportedException("This FastJavaByteArray is read-only"); } if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(); } unsafe { Raw[index] = value; } } } #endregion #region IList<byte> Methods /// <summary> /// Adds a single byte to the list. Not supported /// </summary> /// <param name="item">byte to add</param> public void Add(byte item) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Not supported /// </summary> public void Clear() { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Returns true if the item is found int he array /// </summary> /// <param name="item">Item to find</param> /// <returns>True if the item is found</returns> public bool Contains(byte item) { return IndexOf(item) >= 0; } /// <summary> /// Copies the contents of the FastJavaByteArray into a byte array /// </summary> /// <param name="array">The array to copy to.</param> /// <param name="arrayIndex">The zero-based index into the destination array where CopyTo should start.</param> public void CopyTo(byte[] array, int arrayIndex) { unsafe { Marshal.Copy(new IntPtr(Raw), array, arrayIndex, Math.Min(Count, array.Length - arrayIndex)); } } /// <summary> /// Retreives enumerator /// </summary> /// <returns>Enumerator</returns> [DebuggerHidden] public IEnumerator<byte> GetEnumerator() { return new FastJavaByteArrayEnumerator(this); } /// <summary> /// Retreives enumerator /// </summary> /// <returns>Enumerator</returns> [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return new FastJavaByteArrayEnumerator(this); } /// <summary> /// Gets the first index of the given value /// </summary> /// <param name="item">Item to search for</param> /// <returns>Index of found item</returns> public int IndexOf(byte item) { for (int i = 0; i < Count; ++i) { byte current; unsafe { current = Raw[i]; } if (current == item) return i; } return -1; } /// <summary> /// Not supported /// </summary> /// <param name="index"></param> /// <param name="item"></param> public void Insert(int index, byte item) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Not supported /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(byte item) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } /// <summary> /// Not supported /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { throw new NotSupportedException("FastJavaByteArray is fixed length"); } #endregion #region Public Properties /// <summary> /// Get the raw pointer to the underlying data. /// </summary> public unsafe byte* Raw { get; private set; } #endregion } }
using System.Collections.Generic; using Properties.Core.Objects; namespace Properties.Core.Interfaces { public interface IPostcodeAreaRepository { List<Area> GetAllAreas(); List<PostcodeArea> GetPostcodeAreas(); List<string> GetAvailablePropertyPostcodeAreas(); PostcodeArea GetPostcodeAreaByPostcodePrefix(string postcodePrefix); PostcodeArea GetPostcodeArea(string postcodeAreaReference); bool CreatePostcodeArea(PostcodeArea postcodeArea); bool UpdatePostcodeArea(string postcodeAreaReference, PostcodeArea postcodeArea); bool DeletePostcodeArea(string postcodeAreaReference); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class GameController : MonoBehaviour { public static GameController instance = null; public UnityAction onPickStar; private int _score = 0; public int Score { get { return _score; } } private void PickStar() { _score++; } void Awake() { if (instance == null) instance = this; } void OnEnable() { onPickStar += PickStar; } }
using UnityEngine; using System.Collections; public class TimerWidgetConfig : MonoBehaviour { public Sprite [] frames; public static TimerWidgetConfig instance; void Awake() { instance = this; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; class SceneControlGame : SceneControl { public override SceneControlType SceneType { get { return SceneControlType.SceneControl_Game; } } protected override void LinkSceneInfo() { } //这里的场景初始化只是做场景的构造,对场景的配置不应该放在这里 public override void Initialization() { base.Initialization(); //UniMessageBox.ShowWaring("怎么搞的啊!"); //最后都初始化完成后取消启动画面 if (SceneControl.gameBootFace != null) { SceneControl.gameBootFace.CloseGameBootFace(); SceneControl.gameBootFace = null; } } protected override void OnDestroyScene() { base.OnDestroyScene(); } }
using System; //TODO: Add other using statements here namespace com.Sconit.Entity.ISS { public partial class SMSStatus { #region Non O/R Mapping Properties public static readonly string SMSEventHeadler_MESSAGERECEIVEDINTERFACE = "MessageReceivedInterface"; public static readonly string SMSEventHeadler_STATUSRECEIVEDINTERFACE = "StatusReceivedInterface"; public static readonly string SMSEventHeadler_SUBMITRESPINTERFACE = "SubmitRespInterface"; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IPTables.Net.Netfilter { public interface INetfilterRule { void DeleteRule(bool usingPosition = true); void AddRule(); void ReplaceRule(INetfilterRule with); void DeleteRule(INetfilterAdapterClient client, bool usingPosition = true); void AddRule(INetfilterAdapterClient client); void ReplaceRule(INetfilterAdapterClient client, INetfilterRule with); int IpVersion { get; } PacketCounters Counters { get; } INetfilterChain Chain { get; set; } INetfilterRule ShallowClone(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MVP { public interface IPresenter { //void Form_Calc(object sender, EventArgs e); } }
using System.IO; using System.Threading.Tasks; namespace Welic.App.Implements.PDF.Interfaces { public interface ILocalFileProvider { Task<string> SaveFileToDisk(Stream stream, string fileName); } }
namespace UserService.Repository.CRUD { public interface IDelete<T> { void Delete(T entity); } }
using System; using System.Collections.Generic; using EPI.Sorting; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.Sorting { [TestClass] public class RenderCalendarUnitTest { [TestMethod] public void FindMaxConcurrentCalendarEvents() { List<RenderCalendar.CalendarEvent> calendar = new List<RenderCalendar.CalendarEvent>() { new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,1,0,0), new DateTime(2016,6,4,5,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,6,0,0), new DateTime(2016,6,4,10,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,11,0,0), new DateTime(2016,6,4,13,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,14,0,0), new DateTime(2016,6,4,15,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,2,0,0), new DateTime(2016,6,4,7,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,8,0,0), new DateTime(2016,6,4,9,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,12,0,0), new DateTime(2016,6,4,15,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,4,0,0), new DateTime(2016,6,4,5,0,0)), new RenderCalendar.CalendarEvent(new DateTime(2016,6,4,9,0,0), new DateTime(2016,6,4,17,0,0)) }; RenderCalendar.FindMaxConcurrentEvents(calendar).Should().Be(3); } } }
using LightingBook.Test.Api.Client.v4; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Rest; using LightingBook.Test.Api.Common; using LightingBook.Tests.Api.Proxy.Common; using CompanyReference = LightingBook.Test.Api.Client.v4.Models.TravelCTMOBTApiModelsv4CompanyReference; namespace LightingBook.Tests.Api.Proxy.v4 { public class ItineraryProxy { private readonly TokenResponse _tokenResponse; private Dictionary<string, string> _appConfigDetails; private const int API_VERSION = 4; public ItineraryProxy(TokenResponse tokenResponse, Dictionary<string, string> appConfigDetails) { _tokenResponse = tokenResponse; _appConfigDetails = appConfigDetails; } public async Task<List<CompanyReference>> GetCompanyReference(string id) { var token = new TokenCredentials(_tokenResponse.access_token, "Bearer"); var client = new ClientApi(new Uri(_appConfigDetails["EndPoint"]), token); // add custom header var customHeaders = new Dictionary<string, List<string>>() { { Constant.USER_AGENT_HEADER, new List<string>() { Constant.REST_SHARP_VERSION } } }; // call api var response = await client.ITINERARYCONTROLLERV4.GetCompanyReferenceByItineraryWithHttpMessagesAsync( id, API_VERSION, customHeaders); if (response?.Response?.StatusCode != System.Net.HttpStatusCode.OK) throw new Exception("Invalid request/response."); return response.Body.ToList(); } } }
using System; using System.Web.Configuration; namespace FC_TestFramework.Core.APIs { public class TestManager { private TestManager() { } private static string TFS = WebConfigurationManager.AppSettings["TFS"]; private string NomeProjeto = WebConfigurationManager.AppSettings["Projeto"]; private Uri UrlProjeto = new Uri(TFS); private string Versao = WebConfigurationManager.AppSettings["Versao"]; private string CaminhoKanban = WebConfigurationManager.AppSettings["CaminhoKanban"]; private string Ambiente = WebConfigurationManager.AppSettings["Ambiente"]; public int NumeroTarefa { get; set; } /**Cria uma tarefa durante a inicialização da execução dos testes*/ public virtual void CriarTarefa() { } /**Cria uma tarefa durante a inicialização da execução dos testes*/ public virtual void CriarBugAssociado(String Descricao) { } } }
using FeriaVirtual.Domain.Models.Users; using FeriaVirtual.Domain.Models.Users.Interfaces; using FeriaVirtual.Domain.SeedWork.Query; using FeriaVirtual.Infrastructure.Persistence.OracleContext; using FeriaVirtual.Infrastructure.Persistence.OracleContext.Configuration; using FeriaVirtual.Infrastructure.SeedWork; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FeriaVirtual.Infrastructure.Persistence.RelationalRepositories { public class UserRepository : IUserRepository { private readonly IUnitOfWork _unitOfWork; private readonly Dictionary<string, object> _parameters; public UserRepository() { _unitOfWork = new UnitOfWork(ContextManager.BuildContext(RelationalConfig.Build())); _parameters = new Dictionary<string, object>(); } public async Task Create(User user) { var tasks = Task.WhenAll( _unitOfWork.Context.OpenContextAsync(), _unitOfWork.Context.SaveByStoredProcedure<Credential>("sp_add_credential", user.GetCredential), _unitOfWork.Context.SaveByStoredProcedure<User>("sp_add_user", user), _unitOfWork.SaveChangesAsync() ); await tasks; } public async Task Update(User user) { var tasks = Task.WhenAll( _unitOfWork.Context.OpenContextAsync(), _unitOfWork.Context.SaveByStoredProcedure<Credential>("sp_update_credential", user.GetCredential), _unitOfWork.Context.SaveByStoredProcedure<User>("sp_update_user", user), _unitOfWork.SaveChangesAsync() ); await tasks; } public async Task EnableUser(System.Guid userId) { _parameters.Add("UserId", userId.ToString()); var tasks = Task.WhenAll( _unitOfWork.Context.OpenContextAsync(), _unitOfWork.Context.SaveByStoredProcedure("sp_enable_user", _parameters), _unitOfWork.SaveChangesAsync() ); await tasks; } public async Task DisableUser(System.Guid userId) { _parameters.Add("UserId", userId.ToString()); var tasks = Task.WhenAll( _unitOfWork.Context.OpenContextAsync(), _unitOfWork.Context.SaveByStoredProcedure("sp_disable_user", _parameters), _unitOfWork.SaveChangesAsync() ); await tasks; } public async Task<TResponse> SearchById<TResponse>(System.Guid userId) where TResponse : IQueryResponseBase { _parameters.Clear(); _parameters.Add("UserId", userId.ToString()); await _unitOfWork.Context.OpenContextAsync(); var response = await _unitOfWork.Context.Select<TResponse>("sp_get_user", _parameters); return response.FirstOrDefault(); } public async Task<IEnumerable<TResponse>> SearchByCriteria<TResponse> (System.Func<TResponse, bool> filters = null, int pageNumber = 0) where TResponse : IQueryResponseBase { _parameters.Clear(); _parameters.Add("PageNumber", pageNumber); await _unitOfWork.Context.OpenContextAsync(); var responses= await _unitOfWork.Context.Select<TResponse>("sp_get_allusers", _parameters); if(filters is not null) responses = responses.Where(filters); return responses.ToList(); } public async Task<int> CountAllUsers() { await _unitOfWork.Context.OpenContextAsync(); var response = await _unitOfWork.Context.Count("sp_count_allusers"); return response; } } }
namespace Vurdalakov { using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; public enum FirmwareTableType : UInt32 { Acpi = 0x41435049, Firm = 0x4649524D, Rsmb = 0x52534D42 } public static class FirmwareTables { public static UInt32[] EnumFirmwareTables(FirmwareTableType tableType) { return EnumFirmwareTables((UInt32)tableType); } public static UInt32[] EnumFirmwareTables(String tableType) { return EnumFirmwareTables(StringToUInt32(tableType)); } public static UInt32[] EnumFirmwareTables(UInt32 tableType) { var bufferSize = EnumSystemFirmwareTables(tableType, IntPtr.Zero, 0); if (0 == bufferSize) { ThrowWin32Exception("EnumSystemFirmwareTables"); } var buffer = Marshal.AllocHGlobal((Int32)bufferSize); var result = EnumSystemFirmwareTables(tableType, buffer, bufferSize); if (0 == result) { ThrowWin32Exception("EnumSystemFirmwareTables"); } var byteArray = ReadByteArray(buffer, 0, (Int32)bufferSize); var firmwareTables = new List<UInt32>(); for (int i = 0; i < byteArray.Length; i += sizeof(UInt32)) { var firmwareTable = BitConverter.ToUInt32(byteArray, i); firmwareTables.Add(firmwareTable); } return firmwareTables.ToArray(); } public static Byte[] GetFirmwareTable(FirmwareTableType tableType, String tableId) { return GetFirmwareTable((UInt32)tableType, StringToUInt32(tableId)); } public static Byte[] GetFirmwareTable(FirmwareTableType tableType, UInt32 tableId) { return GetFirmwareTable((UInt32)tableType, tableId); } public static Byte[] GetFirmwareTable(String tableType, String tableId) { return GetFirmwareTable(StringToUInt32(tableType), StringToUInt32(tableId)); } public static Byte[] GetFirmwareTable(UInt32 tableType, UInt32 tableId) { var firmwareTables = new List<UInt32>(); var bufferSize = GetSystemFirmwareTable(tableType, tableId, IntPtr.Zero, 0); if (0 == bufferSize) { ThrowWin32Exception("GetSystemFirmwareTable"); } var buffer = Marshal.AllocHGlobal((Int32)bufferSize); var result = GetSystemFirmwareTable(tableType, tableId, buffer, bufferSize); if (0 == result) { ThrowWin32Exception("GetSystemFirmwareTable"); } return ReadByteArray(buffer, 0, (Int32)bufferSize); } public static AcpiTable GetAcpiTable(String tableId) { return GetAcpiTable(StringToUInt32(tableId)); } public static AcpiTable GetAcpiTable(UInt32 tableId) { var data = FirmwareTables.GetFirmwareTable(FirmwareTableType.Acpi, tableId); return new AcpiTable(data); } public static UInt32 StringToUInt32(String tableType) { if (String.IsNullOrWhiteSpace(tableType) || (tableType.Length != 4)) { throw new ArgumentException(); } return ((UInt32)tableType[0] << 24) | ((UInt32)tableType[1] << 16) | ((UInt32)tableType[2] << 8) | (UInt32)tableType[3]; } public static String UInt32ToString(UInt32 tableType) { var tableTypeString = ""; tableTypeString += (char)((tableType >> 24) & 0xFF); tableTypeString += (char)((tableType >> 16) & 0xFF); tableTypeString += (char)((tableType >> 8) & 0xFF); tableTypeString += (char)((tableType >> 0) & 0xFF); return tableTypeString; } private static void ThrowWin32Exception(String functionName, String format = null, params Object[] args) { var ex = new Win32Exception(); var message = String.Format("{0}() function call failed with error {1}: {2}", functionName, ex.NativeErrorCode, ex.Message); throw new Exception(message, ex); } private static Byte[] ReadByteArray(IntPtr source, Int32 startIndex, Int32 length) { var byteArray = new Byte[length]; Marshal.Copy(source, byteArray, startIndex, length); return byteArray; } [DllImport("kernel32.dll", SetLastError = true)] private static extern UInt32 EnumSystemFirmwareTables(UInt32 firmwareTableProviderSignature, IntPtr firmwareTableBuffer, UInt32 bufferSize); [DllImport("kernel32.dll", SetLastError = true)] private static extern UInt32 GetSystemFirmwareTable(UInt32 firmwareTableProviderSignature, UInt32 firmwareTableID, IntPtr firmwareTableBuffer, UInt32 bufferSize); } }
namespace TripLog.Views { using Xamarin.Forms; using Xamarin.Forms.Maps; using Xamarin.Forms.Xaml; using ViewModels; [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DetailPage : ContentPage { private DetailViewModel _vm { get { return BindingContext as DetailViewModel; } } public DetailPage(BaseViewModel viewModel) { InitializeComponent(); BindingContext = viewModel; var position = new Position(_vm.Entry.Latitude, _vm.Entry.Longitude); map.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMiles(.5))); map.Pins.Add(new Pin { Type = PinType.Place, Label = _vm.Entry.Title, Position = position }); } } }
using EddiDataDefinitions; using System; using System.Collections.Generic; using Utilities; namespace EddiEvents { [PublicAPI] public class AsteroidProspectedEvent : Event { public const string NAME = "Asteroid prospected"; public const string DESCRIPTION = "Triggered when using a prospecting drone"; public const string SAMPLE = "{ \"timestamp\":\"2020-04-10T02:32:21Z\", \"event\":\"ProspectedAsteroid\", \"Materials\":[ { \"Name\":\"LowTemperatureDiamond\", \"Name_Localised\":\"Low Temperature Diamonds\", \"Proportion\":26.078022 }, { \"Name\":\"HydrogenPeroxide\", \"Name_Localised\":\"Hydrogen Peroxide\", \"Proportion\":10.189009 } ], \"MotherlodeMaterial\":\"Alexandrite\", \"Content\":\"$AsteroidMaterialContent_Low;\", \"Content_Localised\":\"Material Content: Low\", \"Remaining\":90.000000 }"; [PublicAPI("A list of objects describing the contents of the asteroid")] public List<CommodityPresence> commodities { get; private set; } [PublicAPI("The material content of the asteroid (high, medium, or low)")] public string materialcontent => materialContent.localizedName; [PublicAPI("The percentage of the asteroid's contents which remain available for surface mining")] public decimal remaining { get; private set; } [PublicAPI("The asteroid's motherlode (if any)")] public string motherlode => motherlodeCommodityDefinition != null ? motherlodeCommodityDefinition.localizedName : ""; // Not intended to be public facing public AsteroidMaterialContent materialContent { get; private set; } public CommodityDefinition motherlodeCommodityDefinition { get; private set; } public AsteroidProspectedEvent(DateTime timestamp, List<CommodityPresence> commodities, AsteroidMaterialContent materialContent, decimal remaining, CommodityDefinition motherlodeCommodityDefinition) : base(timestamp, NAME) { this.commodities = commodities; this.materialContent = materialContent; this.remaining = remaining; this.motherlodeCommodityDefinition = motherlodeCommodityDefinition; } } }
namespace BlockchainNet.Core.Communication { using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using BlockchainNet.Core.Models; using System; public class Communicator { private readonly ICommunicationServer<List<Block>> server; private readonly ICommunicationClientFactory<List<Block>> clientFactory; private readonly List<ICommunicationClient<List<Block>>> nodes; public Blockchain Blockchain { get; set; } /// <summary> /// Конструктор коммуникатора /// </summary> /// <param name="server">Сервер</param> /// <param name="clientFactory">Фаблика клиентов</param> public Communicator( ICommunicationServer<List<Block>> server, ICommunicationClientFactory<List<Block>> clientFactory) { this.server = server; this.clientFactory = clientFactory; nodes = new List<ICommunicationClient<List<Block>>>(); server.MessageReceivedEvent += Server_MessageReceivedEvent; server.ClientConnectedEvent += Server_ClientConnectedEvent; server.ClientDisconnectedEvent += Server_ClientDisconnectedEvent; server.Start(); } public Task SyncAsync(bool onlyGet = false) { if (Blockchain == null) throw new InvalidOperationException("Blockchain must be setted"); var sendedList = onlyGet ? new List<Block>() : Blockchain.Chain.ToList(); return Task .WhenAll(nodes .Select(node => node.SendMessageAsync(sendedList))); } public void ConnectTo(IEnumerable<string> serversId) { foreach (var serverId in serversId) { var nodeClient = clientFactory.CreateNew(serverId); nodeClient.ResponceServerId = server.ServerId; nodeClient.Start(); nodes.Add(nodeClient); } } public void Close() { server.Stop(); foreach (var nodeClient in nodes) nodeClient.Stop(); } private void Server_ClientConnectedEvent(object sender, ClientConnectedEventArgs e) { if (nodes.All(c => c.ServerId != e.ClientId)) { var nodeClient = clientFactory.CreateNew(e.ClientId); nodeClient.ResponceServerId = server.ServerId; nodeClient.Start(); nodes.Add(nodeClient); } } private void Server_ClientDisconnectedEvent(object sender, ClientDisconnectedEventArgs e) { var node = nodes.FirstOrDefault(n => n.ServerId == e.ClientId); if (node != null) { node.Stop(); nodes.Remove(node); } } private async void Server_MessageReceivedEvent(object sender, MessageReceivedEventArgs<List<Block>> e) { if (Blockchain == null) throw new InvalidOperationException("Blockchain must be setted"); var replaced = Blockchain.TrySetChainIfValid(e.Message); // Если не заменено, то входящяя цепочка или невалидна, или меньше существующей // Есть смысл отправить отправителю свою цепочку для замены if (!replaced) { var nodeClient = nodes.FirstOrDefault(c => c.ServerId == e.ClientId); await nodeClient.SendMessageAsync(Blockchain.Chain.ToList()); } } } }
using Newtonsoft.Json; namespace DevilDaggersCore.Spawnsets.Web { [JsonObject(MemberSerialization.OptIn)] public class SpawnsetFile { [JsonProperty] public string Path { get; set; } public string FileName => System.IO.Path.GetFileName(Path); public string Name => GetName(FileName); public string Author => GetAuthor(FileName); [JsonProperty] public SpawnsetFileSettings settings; [JsonProperty] public SpawnsetData spawnsetData; public static string GetName(string fileName) { return fileName.Substring(0, fileName.LastIndexOf('_')); } public static string GetAuthor(string fileName) { return fileName.Substring(fileName.LastIndexOf('_') + 1); } } }
using SFA.DAS.ProviderCommitments.Interfaces; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Infrastructure { public class ApprovalsOuterApiClient : IApprovalsOuterApiClient { private readonly IApprovalsOuterApiHttpClient _client; public ApprovalsOuterApiClient(IApprovalsOuterApiHttpClient client) { _client = client; } public async Task<ProviderCourseDeliveryModels> GetProviderCourseDeliveryModels( long providerId, string courseCode, long accountLegalEntityId, CancellationToken cancellationToken = default) { return await _client.Get<ProviderCourseDeliveryModels> ($"providers/{providerId}/courses?trainingCode={courseCode}&accountLegalEntityId={accountLegalEntityId}", cancellationToken: cancellationToken); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Atomic.DbProvider { /// <summary> /// 标准查询提供者接口 /// </summary> public interface IDbQueryProvider { /// <summary> /// 创建一个新的查询 /// </summary> /// <typeparam name="M"></typeparam> /// <param name="expression"></param> /// <returns></returns> IDbQueryable<M> CreateQuery<M>(Expression expression) where M : IDbModel; } }
using Komodo_Insurance_Repository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Komodo_Insurance { public class ProgramUI { private readonly BadgeRepo _repo = new BadgeRepo(); bool isProgramRunning = true; public void Run() { while (isProgramRunning) { Console.Clear(); Console.WriteLine("Welcome to the Komodo Insurance. Please choose a number.\n" + "1) Add a New Badge\n" + "2) Edit Badge\n" + "3) Delete all Doors from a Badge\n" + "4) View All Badges\n" + "5) Exit"); switch (Console.ReadLine()) { case "1": CreateNewBadge(); break; case "2": UpdateDoorsByBadgeID(); break; case "3": DeleteAllDoors(); break; case "4": ViewBadges(); break; case "5": isProgramRunning = false; break; default: Console.WriteLine("Please choose a valid option. Press any key to continue."); Console.ReadLine(); break; } } } private void CreateNewBadge() { Console.Clear(); Console.WriteLine("What is the Badge ID? "); int badgeID = int.Parse(Console.ReadLine()); Console.WriteLine("What is the Badge Name? "); string badgeName = Console.ReadLine(); bool moreDoors = true; List<string> doorNames = new List<string>(); do { Console.WriteLine("Enter a door. Type 'done' when finished."); string door = Console.ReadLine(); if (door.ToLower() != "done") { doorNames.Add(door); } else { moreDoors = false; } } while (moreDoors); Badge badge = new Badge(badgeID, badgeName, doorNames); _repo.AddNewBadge(badge); } private void DeleteAllDoors() { Console.Clear(); Console.WriteLine("Which badge ID do you want to clear the doors from? "); int chosenNumber = int.Parse(Console.ReadLine()); if (_repo.DeleteAllDoorsFromBadge(_repo.GetBadgeByBadgeID(chosenNumber))) { Console.WriteLine("The doors were successfully deleted."); } else { Console.WriteLine("Couldn't find that badge number."); } Console.WriteLine("Press any key to continue."); Console.ReadLine(); } private void DisplayBadgeByBadgeID(int badgeID) { var badge = _repo.GetBadgeByBadgeID(badgeID); } private void ViewBadges() { Console.Clear(); var badges = _repo.GetAllBadges(); foreach (var badge in badges) { Console.WriteLine($"Badge ID: {badge.BadgeID}\n" + $"Badge Name: {badge.BadgeName}\n" + "List of Doors: "); foreach (string door in badge.DoorNames) { Console.WriteLine($"\t\t\t{door}"); } } Console.ReadLine(); } private void UpdateDoorsByBadgeID() { Console.Clear(); Console.WriteLine("Which badge ID do you want to edit? "); int chosenNumber = int.Parse(Console.ReadLine()); Badge badge = _repo.GetBadgeByBadgeID(chosenNumber); bool moreDoors = true; while (moreDoors) { Console.WriteLine("Do you want to Add a Door, Delete a Door, or Finished (A, D, F)?"); string choice = Console.ReadLine().ToUpper(); switch (choice) { case "A": Console.WriteLine("Which door do you want to add?"); string doorAdd = Console.ReadLine(); badge.DoorNames.Add(doorAdd); break; case "D": Console.WriteLine("Which door do you want to delete?"); string doorDelete = Console.ReadLine(); badge.DoorNames.Remove(doorDelete); break; case "F": moreDoors = false; break; default: break; } } } } }
using System; using System.Dynamic; namespace Profiling2.Domain.Extensions { public static class EntityAsOfDateExtensions { public static bool HasAsOfDate<T>(this T subject) where T : IAsOfDate { return subject.YearAsOf > 0 || subject.MonthAsOf > 0 || subject.DayAsOf > 0; } /// <summary> /// Printable date which doesn't attempt to fill in empty values. /// </summary> /// <returns></returns> public static string GetAsOfDateString<T>(this T subject) where T : IAsOfDate { string y, m, d; y = subject.YearAsOf > 0 ? subject.YearAsOf.ToString() : "-"; m = subject.MonthAsOf > 0 ? subject.MonthAsOf.ToString() : "-"; d = subject.DayAsOf > 0 ? subject.DayAsOf.ToString() : "-"; return string.Join("/", new string[] { y, m, d }); } public static DateTime GetDateTime(int year, int month, int day) { return new DateTime(year > 0 ? year : 1, month > 0 ? month : 1, day > 0 ? day : 1); } /// <summary> /// Replaces missing date parameters with the value '1' - usable in date boundary calculations or sorting. /// </summary> /// <returns></returns> public static DateTime? GetStartDate<T>(this T subject) where T : IAsOfDate { if (subject.YearOfStart > 0 || subject.MonthOfStart > 0 || subject.DayOfStart > 0) return GetDateTime(subject.YearOfStart, subject.MonthOfStart, subject.DayOfStart); return null; } /// <summary> /// Replaces missing date parameters with the value '1' - usable in date boundary calculations or sorting. /// </summary> /// <returns></returns> public static DateTime? GetEndDate<T>(this T subject) where T : IAsOfDate { if (subject.YearOfEnd > 0 || subject.MonthOfEnd > 0 || subject.DayOfEnd > 0) return GetDateTime(subject.YearOfEnd, subject.MonthOfEnd, subject.DayOfEnd); return null; } /// <summary> /// Replaces missing date parameters with the value '1' - usable in date boundary calculations or sorting. /// </summary> /// <returns></returns> public static DateTime? GetAsOfDate<T>(this T subject) where T : IAsOfDate { if (subject.YearAsOf > 0 || subject.MonthAsOf > 0 || subject.DayAsOf > 0) return GetDateTime(subject.YearAsOf, subject.MonthAsOf, subject.DayAsOf); return null; } /// <summary> /// Returns best date to use in order to sort careers chronologically. /// </summary> /// <returns></returns> public static DateTime GetSortDate<T>(this T subject) where T : IAsOfDate { DateTime? a = subject.GetAsOfDate(); DateTime? s = subject.GetStartDate(); DateTime? e = subject.GetEndDate(); if (a.HasValue) return a.Value; else if (s.HasValue) return s.Value; else if (e.HasValue) return e.Value; return new DateTime(); } public static object GetIncompleteAsOfDate<T>(this T subject) where T : IAsOfDate { if (subject.HasAsOfDate()) { dynamic o = new ExpandoObject(); if (subject.YearAsOf > 0) o.year = subject.YearAsOf; if (subject.MonthAsOf > 0) o.month = subject.MonthAsOf; if (subject.DayAsOf > 0) o.day = subject.DayAsOf; return o; } return null; } } }
using DevExpress.Mvvm; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Runtime.InteropServices; using WpfGridControlTest01.Classes; namespace WpfGridControlTest01.Models { public class Product2 : BindableBase, ICloneable { public Product2() { } bool _IsMine = false; public bool IsMine { get { return _IsMine; } set { SetValue(ref _IsMine, value); } } bool _Chk1; public bool Chk1 { get { return _Chk1; } set { SetValue(ref _Chk1, value); } } string _BandWide; public string BandWide { get { return _BandWide; } set { SetValue(ref _BandWide, value); } } bool _Chk2; public bool Chk2 { get { return _Chk2; } set { SetValue(ref _Chk2, value); } } string _Freq; public string Freq { get { return _Freq; } set { SetValue(ref _Freq, value); } } ProductType _SelectedProdcutType; public ProductType SelectedProdcutType { get { return _SelectedProdcutType; } set { SetValue(ref _SelectedProdcutType, value); System.Diagnostics.Debug.WriteLine(string.Format("set SelectedProdcutType: Id={0} TypeName={1}", value.Id, value.TypeName)); } } int _SelectedProdcutId = 3; public int SelectedProdcutId { get { return _SelectedProdcutId; } set { SetValue(ref _SelectedProdcutId, value); System.Diagnostics.Debug.WriteLine(string.Format("set SelectedProdcutId: Id={0}", value)); } } string _SelectedMode = "다라마"; public string SelectedMode { get { return _SelectedMode; } set { SetValue(ref _SelectedMode, value); System.Diagnostics.Debug.WriteLine(string.Format("set SelectedMode: {0}", value)); } } int _SelectedModeIdx = 2; public int SelectedModeIdx { get { return _SelectedModeIdx; } set { SetValue(ref _SelectedModeIdx, value); System.Diagnostics.Debug.WriteLine(string.Format("set SelectedModeIdx: {0}", value)); } } int _SelectedCate = 0; public int SelectedCate { get { return _SelectedCate; } set { SetValue(ref _SelectedCate, value); System.Diagnostics.Debug.WriteLine("set SelectedCate"); } } string _SelectedCate2 = "123"; public string SelectedCate2 { get { return _SelectedCate2; } set { SetValue(ref _SelectedCate2, value); System.Diagnostics.Debug.WriteLine("set SelectedCate2"); } } int _SelectedCate22 = 0; public int SelectedCate22 { get { return _SelectedCate22; } set { SetValue(ref _SelectedCate22, value); System.Diagnostics.Debug.WriteLine("set SelectedCate22"); } } List<string> _Cates22 = new List<string>() { "123", "234", "345", "456", "789", "890" }; public List<string> Cates22 { get { return _Cates22; } set { SetValue(ref _Cates22, value); } } public object Clone() { return this.MemberwiseClone(); } public override string ToString() { var properties = this.GetType().GetProperties(); foreach (PropertyInfo property in properties) { var itm = this.GetType().GetProperty(property.Name).GetValue(this); System.Diagnostics.Debug.Write(string.Format("\t{0} : {1}", property.Name, itm)); } return base.ToString(); } public void SetValues(string propertyName, object value) { this.GetType().GetProperty(propertyName).SetValue(this, value); } public T InputStruct<T>() where T : struct { T stuff = new T(); var properties = this.GetType().GetProperties(); foreach (var p in properties) { // var name0 = stuff.GetType().GetField("BandWide"); // var name = stuff.GetType().GetField(p.Name).GetValue(stuff).GetType().Name; var name = stuff.GetType().GetField(p.Name).FieldType.Name; switch (name) { case "Byte": stuff.GetType().GetField(p.Name).SetValue(stuff, Convert.ToByte(p.GetValue(this))); break; case "Char[]": stuff.GetType().GetField(p.Name).SetValue(stuff, p.GetValue(this).ToString().ToCharArray()); break; } } return stuff; } //public T InputClass<T>(object st) where T : struct //{ // var properties = st.GetType().GetProperties(); // foreach (var property in properties) // { // // this.GetType().GetProperty(property.Name).SetValue(this, ); // } // return stuff; //} public bool HasSameValues(Product2 other) { if (this.Chk1 != other.Chk1) return false; if (this.BandWide != other.BandWide) return false; if (this.Chk2 != other.Chk2) return false; if (this.Freq != other.Freq) return false; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Theatre.Model; using Theatre.ViewModel; using Xamarin.Forms; using Platform = Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.Xaml; using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; namespace Theatre.View.PerformancePage { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CalendarResultPage : ContentPage { public CalendarResultPage(CalendarResultListViewModel viewModel) { InitializeComponent(); BindingContext = viewModel; viewModel.Navigation = Navigation; PerformanceLV.On<Platform::Android>().SetIsFastScrollEnabled(true); } private void OnItemTapped(object sender, ItemTappedEventArgs e) { (BindingContext as CalendarResultListViewModel).GoToDetail((Performance)e.Item); } private void OnItemSelected(object sender, SelectedItemChangedEventArgs e) { ((Xamarin.Forms.ListView)sender).SelectedItem = null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; //using System.IO; ( UNCOMMENT IF USING CODE BELOW ) namespace SOFT152_Assignment { public partial class frmAddLocation : Form { public static frmAddLocation frmkeepAddLocation = null; public frmAddLocation() { InitializeComponent(); frmkeepAddLocation = this; } private void btnNewLocation_Click(object sender, EventArgs e) { string newLocName; string newLocStreet; string newLocCountry; string newLocPostcode; string newLocLatitude; string newLocLongitude; int newLocNumYears; newLocName = txtNewLocName.Text; newLocStreet = txtNewLocStreet.Text; newLocCountry = txtNewLocCountry.Text; newLocPostcode = txtNewLocPostcode.Text; newLocLatitude = txtNewLocLatitude.Text; newLocLongitude = txtNewLocLongitude.Text; //if any of the boxes are empty, throw up an error. if ((newLocName == "") || (newLocStreet == "") || (newLocCountry == "") || (newLocPostcode == "") || (newLocLatitude == "") || (newLocLongitude == "")) { MessageBox.Show("Please make sure all boxes are filled"); } else { //this will try convert the new number of years into an integer, and if it cant it will throw up an error, if it //can though it will continue to do the rest of the code. try { newLocNumYears = Convert.ToInt32(txtNewLocNumYears.Text); Array.Resize(ref Data.locations, Data.locations.Length + 1); int newLocationPos = Data.locations.Length - 1; Data.locations[newLocationPos] = new Location(newLocName, newLocStreet, newLocCountry, newLocPostcode, newLocLatitude, newLocLongitude, newLocNumYears, new Year[newLocNumYears]); for (int i = 0; i < newLocNumYears; i++) { Data.locations[newLocationPos].getyearinfo()[i] = new Year("0", "0", new Month[12]); for (int j = 0; j < 12; j++) { Data.locations[newLocationPos].getyearinfo()[i].getmonthinfo()[j] = new Month(Convert.ToString(j + 1), "0", "0", "0", "0", "0"); } } MessageBox.Show("New location added with empty years and months. to edit the ears and months, please use the edit year and edit month form"); } catch (Exception ex) { MessageBox.Show("Please make sure that the number of years only contains numbers."); } } } private void btnBack_Click(object sender, EventArgs e) { DisplayInfo.frmkeepDisplayInfo.Show(); frmkeepAddLocation.Close(); } } }
using Framework.Core.Common; using Tests.Pages.Van.Main.Common; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Van.Main.Report { public class ReportFormatDetailsPage : VanBasePage { #region Elements public By EditButtonLocator = (By.Id("ctl00_ContentPlaceHolderVANPage_VANSectionHeadingPreview_ButtonConfigure")); public IWebElement EditReportFormatPageCheck { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_LabelHeadline1")); } } public IWebElement EditButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANSectionHeadingPreview_ButtonConfigure")); } } public IWebElement RemoveCommitteeAccessButton { get { return _driver.FindElement(By.XPath("//input[@value = 'Remove']")); } } public IWebElement AddCommitteeAccessButton { get { return _driver.FindElement(By.XPath("//input[@value = 'Add']")); } } #endregion public ReportFormatDetailsPage(Driver driver) : base(driver) { } #region Methods /// <summary> /// searches in helpers->data->minivan data /// </summary> public void EditFile() { _driver.WaitForElementToDisplayBy(EditButtonLocator); _driver.Movetobottom(EditButton); _driver.Click(EditButton); } #endregion } }
using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Aplicacao.Interfaces { public interface IAppServicoRegimes: IAppServicoBase<Regimes> { } }
using MediatR; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebsiteManagerPanel.Commands.UsersInsertCommand { public class UserInsertCommand:IRequest<int> { public string Email { get; set; } public string Password { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TargetGimmick : MonoBehaviour { [SerializeField] Rigidbody bombrigidbody; [SerializeField] Transform EmojiPos; [SerializeField] CapsuleCollider thisCollider; [SerializeField] EmojiEffectTrigger emojiEffectTrigger; [SerializeField] Transform EmojiParent; [SerializeField] bool OnEmoji; [HideInInspector] public bool _clear; [HideInInspector] public bool IsBonus; [HideInInspector] public int BonusCoin; [HideInInspector] public TargetHit targetHit; [HideInInspector] public bool IsLastAreaTarget; bool EmojiStart = false; public void Clear() { _clear = true; StartEmoji("Dead"); SoundManager.Instance.Play("Hit"); GetComponent<Animator>().enabled = false; CoinManager.Instance.StageStandardCoinUp(10); } private void Update() { if (EmojiStart == true) { emojiEffectTrigger.followEmoji(EmojiPos.position); } } public bool CheckClear() { return _clear; } public void BombClear(float explosionForce, Vector3 position, float explosionRadius, float upwardsModifier) { thisCollider.enabled = false; if (IsLastAreaTarget) { if (targetHit.CheckLastTarget()) { StartCoroutine(BombCo(explosionForce, position, explosionRadius, upwardsModifier)); return; } } Clear(); bombrigidbody.AddExplosionForce(explosionForce, position, explosionRadius, upwardsModifier, ForceMode.Impulse); } IEnumerator BombCo(float explosionForce, Vector3 position, float explosionRadius, float upwardsModifier) { targetHit.LastTargetHit(transform); Time.timeScale = 0; yield return new WaitForSecondsRealtime(1f); Time.timeScale = 1; Clear(); bombrigidbody.AddExplosionForce(explosionForce, position, explosionRadius, upwardsModifier, ForceMode.Impulse); SoundManager.Instance.Play("PerfectHit"); } public void PressClear() { EffectManager.Instance.EffectPlay("CleanHit", transform.position); SoundManager.Instance.Play("PerfectHit"); thisCollider.enabled = false; gameObject.SetActive(false); Clear(); } private void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Bullet") { StartCoroutine(TriggetEnter(other.transform)); } } IEnumerator TriggetEnter(Transform other) { if (!IsBonus) { if (IsLastAreaTarget) { if (targetHit.CheckLastTarget()) { targetHit.LastTargetHit(transform); Time.timeScale = 0; yield return new WaitForSecondsRealtime(1f); Time.timeScale = 1; EffectManager.Instance.EffectPlay("CleanHit", transform.position); SoundManager.Instance.Play("PerfectHit"); CoinManager.Instance.StageExternalCoinUp(5); } } Bullet bullet = other.gameObject.GetComponent<Bullet>(); float inclination = (Mathf.Tan(bullet.rad) - 2 * bullet.direction * (other.transform.position.z - bullet.initz) * ((Mathf.Pow(bullet.rad, 2f)) * 0.09f / Mathf.Pow(Mathf.Cos(bullet.rad), 2))) * 1.44f; Vector2 forward = new Vector2(0.1f, 0.1f * inclination); Vector2 dir = new Vector2(transform.position.z - other.transform.position.z, transform.position.x - other.transform.position.x); float angle = Mathf.Acos(Vector2.Dot(forward.normalized, dir.normalized)); if (!IsLastAreaTarget) { if (angle < 0.64) { EffectManager.Instance.EffectPlay("CleanHit", transform.position); CoinManager.Instance.StageExternalCoinUp(5); SoundManager.Instance.Play("PerfectHit"); } else { EffectManager.Instance.EffectPlay("Hit", bullet.transform.position); } } thisCollider.enabled = false; } else { gameObject.SetActive(false); EffectManager.Instance.EffectPlay("BonusHit", transform.position + new Vector3(0, 1f, 0)); EffectManager.Instance.EffectPlay("CleanHit", transform.position); SoundManager.Instance.Play("coinSplash"); CoinManager.Instance.StageStandardCoinUp(10); } Clear(); } public void StartEmoji(string Emoji) { if (!OnEmoji) return; emojiEffectTrigger.StartEffect(EmojiParent, Emoji, EmojiPos.position); if (Emoji == "Dead") EmojiStart = true; Invoke("OffEmoji", 1.9f); } void OffEmoji() { EmojiStart = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { interface IStream { String GetBuffer(String aBuffer); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace CRL.LambdaQuery { public enum CRLExpressionType { Tree, Binary, Name, Value, MethodCall } public class CRLQueryExpression { /// <summary> /// 对象类型,FullName /// </summary> public string Type { get; set; } public CRLExpression Expression { get; set; } public int PageSize { get; set; } public int PageIndex { get; set; } public string ToJson() { return CoreHelper.StringHelper.SerializerToJson(this); } /// <summary> /// CRLQueryExpression json /// </summary> /// <param name="json"></param> /// <returns></returns> public static CRLQueryExpression FromJson(string json) { var result = (CRLQueryExpression)CoreHelper.StringHelper.SerializerFromJSON(System.Text.Encoding.UTF8.GetBytes(json), typeof(CRLQueryExpression)); return result; } } public class CRLExpression { public override string ToString() { return CoreHelper.StringHelper.SerializerToJson(this); } public CRLExpression Left { get; set; } public CRLExpression Right { get; set; } /// <summary> /// 节点类型 /// </summary> public CRLExpressionType Type { get; set; } /// <summary> /// 数据 /// </summary> public object Data { get; set; } /// <summary> /// 左右操作类型 /// </summary> public string ExpressionType; } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Caserraria.Projectiles { public class TideArrowProj : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Tide Arrow"); //The English name of the projectile } public override void SetDefaults() { projectile.width = 18; projectile.height = 32; projectile.timeLeft = 2500000; projectile.penetrate = 1; projectile.friendly = true; projectile.hostile = false; projectile.tileCollide = true; projectile.ignoreWater = true; projectile.ranged = true; projectile.aiStyle = 1; projectile.arrow = true; aiType = ProjectileID.WoodenArrowFriendly; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Drawing.Printing; using System.Configuration; using FastReport; using DevExpress.XtraEditors; using IRAP.Global; using IRAP.Client.Global; using IRAP.Client.User; using IRAP.Entities.Asimco; using IRAP.Entities.MDM; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.AsimcoPrdtPackage.Editor { public partial class frmPackageLabelPrint : frmCustomBase { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private WaitPackageSO mo = null; private bool isProgramChanged = false; public frmPackageLabelPrint() { InitializeComponent(); for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++) { cboPrinters.Properties.Items.Add(PrinterSettings.InstalledPrinters[i]); } PrintDocument prntDoc = new PrintDocument(); string printerName = prntDoc.PrinterSettings.PrinterName; if (ConfigurationManager.AppSettings["LabelPrinter"] != null) { printerName = ConfigurationManager.AppSettings["LabelPrinter"]; } if (cboPrinters.Properties.Items.Count > 0) { cboPrinters.SelectedIndex = cboPrinters.Properties.Items.IndexOf(printerName); } else { btnLabelPrint.Enabled = false; IRAPMessageBox.Instance.ShowErrorMessage( "当前电脑没有安装打印机,无法打印标签"); } } public frmPackageLabelPrint( WaitPackageSO mo, List<PackageLine> lines) : this() { this.mo = mo; foreach (PackageLine line in lines) { cboPackageLines.Properties.Items.Add(line); } } /// <summary> /// 根据订单号和行号获取客户 /// </summary> /// <param name="moNumber"></param> /// <param name="moLineNo"></param> /// <returns></returns> private List<PackageClient> GetCustomersFromPrdt( string moNumber, int moLineNo) { string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}"; WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; List<PackageClient> datas = new List<PackageClient>(); AsimcoPackageClient.Instance.ufn_GetList_PackageClient( IRAPUser.Instance.CommunityID, moNumber, moLineNo, IRAPUser.Instance.SysLogID, ref datas, out errCode, out errText); WriteLog.Instance.Write($"({errCode}){errText}", strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.ShowErrorMessage(errText); } return datas; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } /// <summary> /// 根据打印交易号,打印标签 /// </summary> /// <param name="transactNo"></param> private void PrintLabel(long transactNo) { string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}"; int errCode = 0; string errText = ""; List<Carton> cartons = new List<Carton>(); AsimcoPackageClient.Instance.ufn_GetList_Carton( IRAPUser.Instance.CommunityID, transactNo, IRAPUser.Instance.SysLogID, ref cartons, out errCode, out errText); WriteLog.Instance.Write( $"({errCode}]{errText}", strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.ShowErrorMessage( $"获取标签打印信息时发生错误,请发起重打申请!"); XtraMessageBox.Show( $"错误信息:{errText}", "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (cartons.Count == 0) { IRAPMessageBox.Instance.ShowErrorMessage( $"未获取到打印交易号 [{transactNo}] 的外包装标签数据," + "请联系系统开发人员,并发起重打申请!"); return; } int t117LeafID = 0; string labelTemplate = ""; foreach (Carton carton in cartons) { if (t117LeafID != carton.T117LeafID) { #region 根据 T117LeafID 获取标签打印模板 TemplateContent template = new TemplateContent(); IRAPMDMClient.Instance.ufn_GetInfo_TemplateFMTStr( IRAPUser.Instance.CommunityID, carton.T117LeafID, IRAPUser.Instance.SysLogID, ref template, out errCode, out errText); WriteLog.Instance.Write( $"({errCode}){errText}", strProcedureName); if (errCode != 0 || template.TemplateFMTStr.Trim() == "") { IRAPMessageBox.Instance.ShowErrorMessage( $"无法获取到 [T117LeafID={carton.T117LeafID}] 的模板"); labelTemplate = ""; return; } else { t117LeafID = carton.T117LeafID; labelTemplate = template.TemplateFMTStr; } #endregion } if (labelTemplate != "") { PrintCartonLabel(carton, labelTemplate); } } IRAPMessageBox.Instance.ShowInformation("标签打印完成。"); } private void PrintCartonLabel(Carton cartonInfo, string labelTemplate) { string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}"; Report rpt = new Report(); try { rpt.LoadFromString(labelTemplate); } catch (Exception error) { WriteLog.Instance.Write( $"外包装标签打印模板装载失败:{error.Message},", strProcedureName); IRAPMessageBox.Instance.ShowErrorMessage( $"外包装标签打印模板装载失败:{error.Message},\n" + "请联系系统开发人员,并发起重打申请!"); return; } #region 打印外包装标签 PrinterSettings prntSettings = new PrinterSettings(); //prntSettings.Copies = Convert.ToInt16(cartonInfo.PrintQty); prntSettings.PrinterName = (string)cboPrinters.SelectedItem; rpt.Parameters.FindByName("Model").Value = cartonInfo.Model; rpt.Parameters.FindByName("DrawingID").Value = cartonInfo.DrawingID; rpt.Parameters.FindByName("MaterialCategory").Value = cartonInfo.MaterialCategory; rpt.Parameters.FindByName("CartonQty").Value = $"{cartonInfo.CartonQty} {cartonInfo.UnitOfMeasure}"; rpt.Parameters.FindByName("CartonProductNo").Value = cartonInfo.CartonProductNo; rpt.Parameters.FindByName("LotNumber").Value = cartonInfo.LotNumber; rpt.Parameters.FindByName("SupplyCode").Value = cartonInfo.SupplyCode; rpt.Parameters.FindByName("T134AlternateCode").Value = cartonInfo.T134AlternateCode; rpt.Parameters.FindByName("BarCode").Value = $"{cartonInfo.CartonProductNo}/" + $"{cartonInfo.CartonNumber}/" + $"{cartonInfo.CartonQty.ToString()}"; if (rpt.Prepare()) { for (int i = 0; i < cartonInfo.PrintQty; i++) { rpt.PrintPrepared(prntSettings); } } #endregion #region 获取内包装标签列表 int errCode = 0; string errText = ""; List<BoxOfCarton> boxes = new List<BoxOfCarton>(); AsimcoPackageClient.Instance.ufn_GetList_BoxOfCarton( IRAPUser.Instance.CommunityID, cartonInfo.CartonNumber, IRAPUser.Instance.SysLogID, ref boxes, out errCode, out errText); WriteLog.Instance.Write( $"({errCode}){errText}", strProcedureName); if (errCode != 0) { IRAPMessageBox.Instance.ShowErrorMessage( $"获取标签打印信息时发生错误,请发起重打申请!"); XtraMessageBox.Show( $"错误信息:{errText}", "", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (boxes.Count == 0) { IRAPMessageBox.Instance.ShowErrorMessage( $"未获取到外包装号 [{cartonInfo.CartonNumber}] 的内包装标签数据," + "请联系系统开发人员,并发起重打申请!"); return; } #endregion #region 打印内标签 int t117LeafID = 0; string boxLabelTemplate = ""; foreach (BoxOfCarton box in boxes) { if (t117LeafID != box.T117LeafID) { #region 根据 T117LeafID 获取标签打印模板 TemplateContent template = new TemplateContent(); IRAPMDMClient.Instance.ufn_GetInfo_TemplateFMTStr( IRAPUser.Instance.CommunityID, box.T117LeafID, IRAPUser.Instance.SysLogID, ref template, out errCode, out errText); WriteLog.Instance.Write( $"({errCode}){errText}", strProcedureName); if (errCode != 0 || template.TemplateFMTStr.Trim() == "") { IRAPMessageBox.Instance.ShowErrorMessage( $"无法获取到 [T117LeafID={box.T117LeafID}] 的模板"); boxLabelTemplate = ""; } else { t117LeafID = box.T117LeafID; boxLabelTemplate = template.TemplateFMTStr; } #endregion } if (boxLabelTemplate != "") { PrintBoxLabel(box, boxLabelTemplate); } } #endregion } private void PrintBoxLabel(BoxOfCarton box, string labelTemplate) { string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}"; Report rpt = new Report(); try { rpt.LoadFromString(labelTemplate); } catch (Exception error) { WriteLog.Instance.Write( $"内包装标签打印模板装载失败:{error.Message},", strProcedureName); IRAPMessageBox.Instance.ShowErrorMessage( $"内包装标签打印模板装载失败:{error.Message},\n" + "请联系系统开发人员,并发起重打申请!"); return; } #region 打印内包装标签 PrinterSettings prntSettings = new PrinterSettings(); //prntSettings.Copies = Convert.ToInt16(box.PrintQty); prntSettings.PrinterName = (string)cboPrinters.SelectedItem; rpt.Parameters.FindByName("Model").Value = box.Model; rpt.Parameters.FindByName("DrawingID").Value = box.DrawingID; rpt.Parameters.FindByName("MaterialCategory").Value = box.MaterialCategory; rpt.Parameters.FindByName("BoxQty").Value = $"{box.MaterialQty} {box.UnitOfMeasure}"; rpt.Parameters.FindByName("MaterialCode").Value = box.BoxMaterialNo; rpt.Parameters.FindByName("LotNumber").Value = box.LotNumber; rpt.Parameters.FindByName("CylinderID").Value = box.CylinderID; rpt.Parameters.FindByName("SupplyCode").Value = box.SupplyCode; rpt.Parameters.FindByName("T134AlternateCode").Value = box.T134AlternateCode; rpt.Parameters.FindByName("BarCode").Value = box.CylinderID; if (rpt.Prepare()) { for (int i = 0; i < box.PrintQty; i++) { rpt.PrintPrepared(prntSettings); } } #endregion } private void frmPackageLabelPrint_Shown(object sender, EventArgs e) { if (mo != null) { #region 获取当前订单可配送的客户清单 List<PackageClient> customers = GetCustomersFromPrdt( mo.MONumber, mo.MOLineNo); int idx = -1; isProgramChanged = true; try { for (int i = 0; i < customers.Count; i++) { if (customers[i].T105Code == mo.CustomerCode) { idx = i; } cboCustomers.Properties.Items.Add(customers[i]); } } finally { isProgramChanged = false; } cboCustomers.SelectedIndex = idx; cboCustomers.Enabled = idx < 0; #endregion } } private void cboCustomers_SelectedIndexChanged(object sender, EventArgs e) { PackageClient customer = cboCustomers.SelectedItem as PackageClient; if (customer != null) { edtCartonNumber.Value = customer.NumberOfCarton; edtBoxNumber.Value = customer.NumberOfBox; } } private void edtCartonNumber_Validating(object sender, CancelEventArgs e) { if (!isProgramChanged) { int t105LeafID = 0; long maxNumberOfCarton = 0; if (cboCustomers.SelectedItem == null) { IRAPMessageBox.Instance.ShowErrorMessage( "未选择客户"); return; } else { t105LeafID = (cboCustomers.SelectedItem as PackageClient).T105LeafID; maxNumberOfCarton = (cboCustomers.SelectedItem as PackageClient).NumberOfCarton; } if (edtCartonNumber.Value > maxNumberOfCarton) { IRAPMessageBox.Instance.ShowErrorMessage( $"外箱数量不能大于 [{maxNumberOfCarton}] !"); edtCartonNumber.Value = 0; e.Cancel = true; return; } string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}"; WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; int cartonNumber = Convert.ToInt32(edtCartonNumber.Value); int boxNumber = 0; AsimcoPackageClient.Instance.usp_PokaYoke_Package( IRAPUser.Instance.CommunityID, mo.MONumber, mo.MOLineNo, t105LeafID, cartonNumber, IRAPUser.Instance.SysLogID, out boxNumber, out errCode, out errText); WriteLog.Instance.Write( $"({errCode}){errText}", strProcedureName); if (errCode == 0) { edtBoxNumber.Value = boxNumber; } else { IRAPMessageBox.Instance.ShowErrorMessage(errText); cboCustomers_SelectedIndexChanged(cboCustomers, null); } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } private void btnLabelPrint_Click(object sender, EventArgs e) { string strProcedureName = $"{className}.{MethodBase.GetCurrentMethod().Name}"; long numberOfCarton = 0; if (cboCustomers.SelectedItem == null) { IRAPMessageBox.Instance.ShowErrorMessage("请选择客户!"); cboCustomers.Focus(); return; } else { PackageClient customer = cboCustomers.SelectedItem as PackageClient; numberOfCarton = customer.NumberOfCarton; } if (cboPackageLines.SelectedItem == null) { IRAPMessageBox.Instance.ShowErrorMessage("请选择包装线!"); cboPackageLines.Focus(); return; } if (edtCartonNumber.Value <= 0) { IRAPMessageBox.Instance.ShowErrorMessage("外箱数量不能小于等于零!"); edtCartonNumber.Focus(); return; } if (Convert.ToInt64(edtCartonNumber.Value) > numberOfCarton) { IRAPMessageBox.Instance.ShowErrorMessage( $"外箱数量不能大于 [{numberOfCarton}]"); edtCartonNumber.Value = numberOfCarton; edtCartonNumber.Focus(); return; } if (cboPrinters.SelectedItem == null) { IRAPMessageBox.Instance.ShowErrorMessage( "请选择一台打印机!"); cboPrinters.Focus(); return; } WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; long transactNo = 0; long numberOfBox = Convert.ToInt64(edtBoxNumber.Value); long cartonNumber = Convert.ToInt64(edtCartonNumber.Value); PackageClient customer = cboCustomers.SelectedItem as PackageClient; PackageLine line = cboPackageLines.SelectedItem as PackageLine; AsimcoPackageClient.Instance.usp_SaveFact_PackagePrint( IRAPUser.Instance.CommunityID, mo.MONumber, mo.MOLineNo, 0, cartonNumber, customer.T105LeafID, line.T134LeafID, numberOfBox, IRAPUser.Instance.SysLogID, ref transactNo, out errCode, out errText); WriteLog.Instance.Write( $"({errCode}){errText}", strProcedureName); if (errCode == 0) { WriteLog.Instance.Write($"得到打印交易号 [{transactNo}]。", strProcedureName); PrintLabel(transactNo); btnCancel.PerformClick(); } else { IRAPMessageBox.Instance.ShowErrorMessage(errText); } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void cboPrinters_SelectedIndexChanged(object sender, EventArgs e) { IRAPConst.Instance.SaveParams( "LabelPrinter", (string)cboPrinters.SelectedItem); } } }
//********************************************************************************** //* Copyright (C) 2007,2016 Hitachi Solutions,Ltd. //********************************************************************************** #region Apache License // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion //********************************************************************************** //* クラス名 :OAuth2AndOIDCConst //* クラス日本語名 :OAuth2とOIDCの各種定数 //* //* 作成者 :生技 西野 //* 更新履歴 : //* //* 日時 更新者 内容 //* ---------- ---------------- ------------------------------------------------- //* 2018/08/10 西野 大介 新規作成(汎用認証サイトからのコード移行) //********************************************************************************** // urnはClaimのurnで、 // ASP.NETとClaimとJwtのMember間のインターフェイスを形成する。 namespace Touryo.Infrastructure.Framework.Authentication { /// <summary>OAuth2とOIDCの各種定数</summary> public class OAuth2AndOIDCConst { #region param /// <summary>grant_type</summary> public const string grant_type = "grant_type"; /// <summary>response_type</summary> public const string response_type = "response_type"; /// <summary>response_mode</summary> public const string response_mode = "response_mode"; /// <summary>redirect_uri</summary> public const string redirect_uri = "redirect_uri"; /// <summary>scope</summary> public const string scope = "scope"; /// <summary>state</summary> public const string state = "state"; /// <summary>code</summary> public const string code = "code"; /// <summary>assertion</summary> public const string assertion = "assertion"; /// <summary>token</summary> public const string token = "token"; #region WebAPI /// <summary>token</summary> public const string token_type = "token_type"; /// <summary>token_type_hint</summary> public const string token_type_hint = "token_type_hint"; #endregion #endregion #region token /// <summary>AccessToken</summary> public const string AccessToken = "access_token"; /// <summary>RefreshToken</summary> public const string RefreshToken = "refresh_token"; /// <summary>IDToken</summary> public const string IDToken = "id_token"; #endregion #region GrantType /// <summary>Authorization Codeグラント種別</summary> public const string AuthorizationCodeGrantType = "authorization_code"; /// <summary>Implicitグラント種別</summary> public const string ImplicitGrantType = "implicit"; // well-knownで利用。 /// <summary>Resource Owner Password Credentialsグラント種別</summary> public const string ResourceOwnerPasswordCredentialsGrantType = "password"; /// <summary>Client Credentialsグラント種別</summary> public const string ClientCredentialsGrantType = "client_credentials"; /// <summary>Refresh Tokenグラント種別</summary> public const string RefreshTokenGrantType = RefreshToken; /// <summary>JWT bearer token authorizationグラント種別</summary> public const string JwtBearerTokenFlowGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"; #endregion #region ResponseType /// <summary>Authorization Codeグラント種別</summary> public const string AuthorizationCodeResponseType = code; /// <summary>Implicitグラント種別</summary> public const string ImplicitResponseType = token; /// <summary>OIDC - Implicit</summary> public const string OidcImplicit1_ResponseType = IDToken; /// <summary>OIDC - Implicit2</summary> public const string OidcImplicit2_ResponseType = IDToken + " " + token; /// <summary>OIDC - Hybrid(IdToken)</summary> public const string OidcHybrid2_IdToken_ResponseType = code + " " + IDToken; /// <summary>OIDC - Hybrid(Token)</summary> public const string OidcHybrid2_Token_ResponseType = code + " " + token; /// <summary>OIDC - Hybrid(IdToken and Token)</summary> public const string OidcHybrid3_ResponseType = code + " " + IDToken + " " + token; #endregion #region HTTP Header /// <summary>Location</summary> public const string HttpHeader_Location = "Location"; #region Authorization /// <summary>Authorization</summary> public const string HttpHeader_Authorization = "Authorization"; /// <summary>Basic</summary> public const string Basic = "Basic"; /// <summary>Bearer</summary> public const string Bearer = "Bearer"; #endregion #endregion #region Scope #region 標準 /// <summary>profileを要求するscope</summary> public const string Scope_Profile = "profile"; /// <summary>emailを要求するscope</summary> public const string Scope_Email = "email"; /// <summary>phoneを要求するscope</summary> public const string Scope_Phone = "phone"; /// <summary>addressを要求するscope</summary> public const string Scope_Address = "address"; #endregion #region 拡張 /// <summary>authを要求するscope(認可画面を出さない)</summary> public const string Scope_Auth = "auth"; /// <summary>useridを要求するscope</summary> public const string Scope_UserID = "userid"; /// <summary>rolesを要求するscope</summary> public const string Scope_Roles = "roles"; #endregion #region id_token /// <summary>id_tokenを要求するscope</summary> public const string Scope_Openid = "openid"; #endregion #endregion #region Claims // ★ Scopeと同じ文字列は定義しない。 /// <summary>ベース部分</summary> public static readonly string Claim_Base = "urn:oauth:"; #region 予約 #region 末端 /// <summary>iss</summary> public const string iss = "iss"; /// <summary>aud</summary> public const string aud = "aud"; /// <summary>sub</summary> public const string sub = "sub"; /// <summary>exp</summary> public const string exp = "exp"; /// <summary>nbf</summary> public const string nbf = "nbf"; /// <summary>iat</summary> public const string iat = "iat"; /// <summary>jti</summary> public const string jti = "jti"; #endregion #region urn /// <summary>issuerクレームのurn</summary> public static readonly string Claim_Issuer = Claim_Base + iss; /// <summary>audienceクレームのurn</summary> public static readonly string Claim_Audience = Claim_Base + aud; /// <summary>subjectクレームのurn</summary> public static readonly string Claim_Subject = Claim_Base + sub; /// <summary>expクレームのurn</summary> public static readonly string Claim_ExpirationTime = Claim_Base + exp; /// <summary>nbfクレームのurn</summary> public static readonly string Claim_NotBefore = Claim_Base + nbf; /// <summary>iatクレームのurn</summary> public static readonly string Claim_IssuedAt = Claim_Base + iat; /// <summary>jtiクレームのurn</summary> public static readonly string Claim_JwtId = Claim_Base + jti; #endregion #endregion #region 標準 #region 末端 /// <summary>email_verified</summary> public const string email_verified = "email_verified"; /// <summary>phone_number</summary> public const string phone_number = "phone_number"; /// <summary>phone_number_verified</summary> public const string phone_number_verified = "phone_number_verified"; #endregion #region urn /// <summary>emailクレームのurn</summary> public static readonly string Claim_Email = Claim_Base + Scope_Email; /// <summary>email_verifiedクレームのurn</summary> public static readonly string Claim_EmailVerified = Claim_Base + email_verified; /// <summary>phone_numberクレームのurn</summary> public static readonly string Claim_PhoneNumber = Claim_Base + phone_number; /// <summary>phone_number_verifiedクレームのurn</summary> public static readonly string Claim_PhoneNumberVerified = Claim_Base + phone_number_verified; #endregion #endregion #region OIDC #region 末端 /// <summary>nonce</summary> public const string nonce = "nonce"; /// <summary>at_hash</summary> public const string at_hash = "at_hash"; /// <summary>c_hash</summary> public const string c_hash = "c_hash"; #endregion #region urn /// <summary>nonceクレームのurn</summary> public static readonly string Claim_Nonce = Claim_Base + nonce; /// <summary>at_hashクレームのurn</summary> public static readonly string Claim_AtHash = Claim_Base + at_hash; /// <summary>c_hashクレームのurn</summary> public static readonly string Claim_CHash = Claim_Base + c_hash; #endregion #endregion #region FAPI #region 末端 /// <summary>s_hash</summary> public const string s_hash = "s_hash"; /// <summary>cnf</summary> public const string cnf = "cnf"; /// <summary>x5t</summary> public const string x5t = "x5t"; /// <summary>x5u</summary> public const string x5u = "x5u"; // 独自 /// <summary>fapi</summary> public const string fapi = "fapi"; #endregion #region urn /// <summary>s_hashクレームのurn</summary> public static readonly string Claim_SHash = Claim_Base + s_hash; /// <summary>cnfクレームのurn</summary> public static readonly string Claim_Cnf = Claim_Base + cnf; /// <summary>x5tクレームのurn</summary> public static readonly string Claim_CnfX5t = Claim_Cnf + ":" + x5t; /// <summary>x5uクレームのurn</summary> public static readonly string Claim_CnfX5u = Claim_Cnf + ":" + x5u; // 独自 /// <summary>fapiクレームのurn</summary> public static readonly string Claim_FApi = Claim_Base + fapi; #endregion #endregion #region 拡張 #region 末端 /// <summary>scopes</summary> public const string scopes = "scopes"; #endregion #region urn /// <summary>scopeクレームのurn</summary> public static readonly string Claim_Scopes = Claim_Base + scopes; #endregion #endregion #endregion #region PKCE /// <summary>code_verifier</summary> public const string code_verifier = "code_verifier"; /// <summary>code_challenge</summary> public const string code_challenge = "code_challenge"; /// <summary>code_challenge_method</summary> public const string code_challenge_method = "code_challenge_method"; /// <summary>PKCE plain</summary> public const string PKCE_plain = "plain"; /// <summary>PKCE S256</summary> public const string PKCE_S256 = "S256"; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace POSServices.Models { public class UploadSyncDetailTable { } public class syncUploadDetail { public int syncDetailsId { get; set; } public int JobId { get; set; } public string StoreId { get; set; } public string TableName { get; set; } public string UploadPath { get; set; } public DateTime Synchdate { get; set; } public string CreateTable { get; set; } public int RowFatch { get; set; } public int MinId { get; set; } public int MaxId { get; set; } } public class bracketSyncUploadDetail { public List<syncUploadDetail> uploadDetails { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfApp1 { class DrugDTO { public List<string> ingredient { get; set; } public string drugType { get; set; } public string Name { get; set; } public int Id { get; set; } public int Quantity { get; set; } public string ExpirationDate { get; set; } public string Producer { get; set; } public DrugDTO() { } public DrugDTO(DrugDTO d) { this.ingredient = d.ingredient; this.drugType = d.drugType; this.Name = d.Name; this.Id = d.Id; this.Quantity = d.Quantity; this.ExpirationDate = d.ExpirationDate; this.Producer = d.Producer; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Restart : MonoBehaviour { public float restartTime; bool restartNow = false; float resetTime; void Start() { } // Update is called once per frame [System.Obsolete] void Update() { if (restartNow && resetTime <= Time.time) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); //Application.LoadLevel(Application.loadedLevel); } } public void restartGame() { restartNow = true; resetTime = Time.time + restartTime; } }
namespace CapaPresentacion { using CapaAplicacion; using System; using System.Web.UI; public partial class Default : Page { /// <summary> /// evento del botón Ejecutar /// </summary> protected void RealizarCalculo(object sender, EventArgs e) { CA_Principal mainprogram = new CA_Principal(txb_Entrada.Text); txb_Salida.Text = mainprogram.Execute().Replace(@"\r\n\r\n", @"\r\n"); } } }
namespace DistCWebSite.Core.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public partial class CC_RocheSupport { public int ID { get; set; } [StringLength(20)] public string DistributorCode { get; set; } [StringLength(100)] public string DistributorName { get; set; } [StringLength(50)] public string SACodeGroup { get; set; } public DateTime? Month { get; set; } } }
using System; using Mall.Domain.SellingPrice.IRepositories; using Mall.Domain.SellingPrice.MemberPrice.ValueObject; namespace Mall.Infrastructure.Repositories { public class RoleDiscountRelationRepository : IRoleDiscountRelationRepository { public RoleDiscountRelation Get(string roleId) { throw new NotImplementedException(); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Yaringa.Models.Token { public class TokenInfoParser { public static TokenInfo Parse(string accessToken) { if (string.IsNullOrWhiteSpace(accessToken)) { throw new Exception("Empty token payload"); } string[] parts = accessToken.Split('.'); if (parts.Length != 3) { throw new Exception("Invalid token"); } var part1 = parts[1]; string incoming = part1.Replace('_', '/').Replace('-', '+'); switch (part1.Length % 4) { case 2: incoming += "=="; break; case 3: incoming += "="; break; } byte[] bytes = Convert.FromBase64String(incoming); string payload = Encoding.UTF8.GetString(bytes, 0, bytes.Length); TokenInfo info = JsonConvert.DeserializeObject<TokenInfo>(payload); return info; } } }
namespace RotateAndSum { using System; using System.Linq; public class StartUp { public static void Main() { var array = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); var rotationTimes = int.Parse(Console.ReadLine()); var sumArrays = new int[array.Length]; for (int i = 0; i < rotationTimes; i++) { var tempNum = array.Last(); for (int j = array.Length - 1; j > 0; j--) { array[j] = array[j - 1]; } array[0] = tempNum; for (int j = 0; j < sumArrays.Length; j++) { sumArrays[j] += array[j]; } } Console.WriteLine(string.Join(" ", sumArrays)); } } }
using Iris.Infrastructure.Models; namespace Iris.Infrastructure.Contracts { public delegate void MousePositionUpdateEventHandler(MousePosition position); public delegate void NetworkDataReceivedEventHandler(byte[] data); }
// Copyright (C) 2008 Jesse Jones // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using MObjc.Helpers; using System; using System.Diagnostics; namespace MObjc { /// <summary>Wrapper around the <see cref = "NSObject">NSObject</see> indexer.</summary> /// <remarks>This allows you to get and set the native instance values associated /// with the class. Note that these normally map to the same names as those set within /// Interface Builder. Also it's usually easiest to just use the <see cref = "NSObject">NSObject</see> indexer.</remarks> public sealed class IBOutlet<T> : IEquatable<IBOutlet<T>> where T : NSObject { /// <param name = "owner">The object which owns the outlet. Usually <c>this</c>.</param> /// <param name = "name">The name of the outlet. Usually the name set within Interface Builder.</param> public IBOutlet(NSObject owner, string name) { Contract.Requires(!NSObject.IsNullOrNil(owner), "owner is null or nil"); Contract.Requires(!string.IsNullOrEmpty(name), "name is null or empty"); m_owner = owner; m_name = name; } /// <summary>The current value of the outlet.</summary> public T Value { get {NSObject o = m_owner[m_name]; return NSObject.IsNullOrNil(o) ? null : (T) o;} set {m_owner[m_name] = value;} } public override bool Equals(object rhsObj) { if (rhsObj == null) return false; IBOutlet<T> rhs = rhsObj as IBOutlet<T>; return this == rhs; } public bool Equals(IBOutlet<T> rhs) { return this == rhs; } public static bool operator==(IBOutlet<T> lhs, IBOutlet<T> rhs) { if (object.ReferenceEquals(lhs, rhs)) return true; if ((object) lhs == null || (object) rhs == null) return false; return lhs.m_owner.Equals(rhs.m_owner) && lhs.m_name == rhs.m_name; } public static bool operator!=(IBOutlet<T> lhs, IBOutlet<T> rhs) { return !(lhs == rhs); } public override int GetHashCode() { int hash = 47; unchecked { hash += 23*m_owner.GetHashCode(); hash += 23*m_name.GetHashCode(); } return hash; } private NSObject m_owner; private string m_name; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Anywhere2Go.Library { public class PagingCriteria { public int PageIndex { get; set; } public int PageSize { get; set; } public override bool Equals(object obj) { if (Object.ReferenceEquals(this,obj)) return true; PagingCriteria criteria = obj as PagingCriteria; if (criteria == null) return false; return (this.PageIndex == criteria.PageIndex) && (this.PageSize == criteria.PageSize); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio14 { class Conversoes2 { static void Main(string[] args) { { string S = "99"; int I = Convert.ToInt16(S); I = I + 1; Console.Clear(); Console.WriteLine(I); string X = Convert.ToString(I); Console.WriteLine(X + "tem " + X.Length + " dígitos"); } } } }
using System; using System.Collections.Specialized; using System.Data.SqlClient; using System.Linq; using System.Threading; using System.Windows; using SqlServerRunnerNet.Infrastructure; using SqlServerRunnerNet.ViewModel; namespace SqlServerRunnerNet { /// <summary> /// Interaction logic for BrowseConnectionStringWindow.xaml /// </summary> public partial class BrowseConnectionStringWindow : Window { public ConnectionStringViewModel Model { get; private set; } public string ConnectionString { get { return GetConnectionString(); } set { SetConnectionString(value); } } public BrowseConnectionStringWindow() { InitializeComponent(); Model = new ConnectionStringViewModel(this); DataContext = Model; LoadSettings(); } public BrowseConnectionStringWindow(Window parent) : this() { Owner = parent; } private void SetConnectionString(string connectionString) { SqlConnectionStringBuilder builder; try { builder = new SqlConnectionStringBuilder(connectionString); } catch { builder = new SqlConnectionStringBuilder(); } Model.NewServerName = builder.DataSource; var isSqlUser = !string.IsNullOrWhiteSpace(connectionString) && !builder.IntegratedSecurity; Model.AuthenticationType = !isSqlUser ? AuthenticationType.WindowsAuthentication : AuthenticationType.SqlServerAuthentication; if (isSqlUser) { Model.SqlServerUsername = builder.UserID; Model.Password = builder.Password; } else { Model.SqlServerUsername = string.Empty; Model.Password = string.Empty; } Model.DatabaseName = builder.InitialCatalog; } private string GetConnectionString() { var builder = new SqlConnectionStringBuilder(); builder.Clear(); builder.DataSource = Model.ServerName; if (Model.AuthenticationType == AuthenticationType.WindowsAuthentication) { builder.IntegratedSecurity = true; } else { builder.IntegratedSecurity = false; builder.UserID = Model.SqlServerUsername; builder.Password = Model.Password; } builder.InitialCatalog = Model.DatabaseName; return builder.ConnectionString; } private void OkButton_OnClick(object sender, RoutedEventArgs e) { DialogResult = true; } private void BrowseServersButton_OnClick(object sender, RoutedEventArgs e) { var browserWindow = new ServerBrowserWindow(this); if (browserWindow.ShowDialog() == true) { Model.NewServerName = browserWindow.SqlServerInstanceName; } } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { SaveSettings(); } private void LoadSettings() { if (Properties.Settings.Default.RecentServerNames == null) return; Model.RecentServerNames.Clear(); foreach (var serverName in Properties.Settings.Default.RecentServerNames) { Model.RecentServerNames.Add(serverName); } } private void SaveSettings() { if (Properties.Settings.Default.RecentServerNames == null) Properties.Settings.Default.RecentServerNames = new StringCollection(); Properties.Settings.Default.RecentServerNames.Clear(); Properties.Settings.Default.RecentServerNames.AddRange(Model.RecentServerNames.ToArray()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class RankingManager : MonoBehaviour { private static RankingManager instance; public static RankingManager Instance { get { return instance; } } private GameManager gameManager; private List<GameObject> path = null; public GameObject waypointHolder; WaypointManager waypointManager; private Dictionary<int, List<GameObject>> currentPosition; //현재 public int playerRank; private void Start() { if(instance == null) { instance = this; } else { Destroy(this.gameObject); } gameManager = GetComponent<GameManager>(); waypointManager = waypointHolder.GetComponent<WaypointManager>(); path = waypointManager.wayPoints; currentPosition = new Dictionary<int, List<GameObject>>(); } /// <summary> /// 플레이어의 앞에 몇 대의 차가 존재하는지 알아보고 랭크를 갱신한다. /// </summary> private void UpdateRanking() { int i = 0; GameObject player = GameManager.Instance.playerCar; currentPosition=currentPosition.OrderBy(x => x.Key).Reverse().ToDictionary(x=>x.Key, x=>x.Value); foreach (List<GameObject> cars in currentPosition.Values) { if(cars.Contains(player)) { i += cars.IndexOf(player) + 1; //index는 0부터 시작하므로 1을 늘려야한다. break; } else { i += cars.Count; } } playerRank = i; HUDManager.Instance.UpdateRankUI(playerRank); } public void SetCurrentPosition(GameObject carObj, int lapNow, int checkPointNum, bool isPlayer = false) { int totalCheckPointNum = lapNow * (path.Count - 1) + checkPointNum; if (totalCheckPointNum > path.Count - 1) //처음이 1lap이어서 0이 아니라 좌측의 값이 시작이다. 시작지점 이전의 totalCheckPointNum은 존재하지 않으므로 패스 { currentPosition[totalCheckPointNum - 1].Remove(carObj); //이전 체크포인트 관련 값 삭제 if (currentPosition[totalCheckPointNum - 1].Count == 0) //빈 체크포인트 값은 딕셔너리 자리만 차지한다. { currentPosition.Remove(totalCheckPointNum-1); } } if (!currentPosition.ContainsKey(totalCheckPointNum)) { currentPosition.Add(totalCheckPointNum, new List<GameObject>()); } currentPosition[totalCheckPointNum].Add(carObj); if (isPlayer) { UpdateRanking(); } } }
using EntityFrameworkCoreDemo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EntityFrameworkCoreDemo.Helpers { public static class Extension { public static IList<Course> AssignSchool<T>(this IList<Course> courses, T school) where T : BaseObject { foreach (var item in courses) { item.Schoold = school.Id; } return courses; } public static IList<Subject> AssignCourses<T>(this IList<Subject> subjects, IList<T> courses) where T : BaseObject { foreach (var course in courses) { foreach (var subject in subjects) { subject.CourseId = course.Id; } } return subjects; } public static IList<Student> AssignCourses<T>(this IList<Student> students, IList<T> courses) where T : BaseObject { foreach (var course in courses) { foreach (var student in students) { student.CourseId = course.Id; } } return students; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using MovementMod.Framework; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using SFarmer = StardewValley.Farmer; namespace MovementMod { /// <summary>The main entry point.</summary> public class ModEntry : Mod { /********* ** Properties *********/ /// <summary>The mod configuration.</summary> private ModConfig Config; private Keys SprintKey; private int CurrentSpeed; private Vector2 PrevPosition; private float ElapsedSeconds => (float)Game1.currentGameTime.ElapsedGameTime.TotalMilliseconds / 1000f; /********* ** Public methods *********/ /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides methods for interacting with the mod directory, such as read/writing a config file or custom JSON files.</param> public override void Entry(IModHelper helper) { this.Config = helper.ReadConfig<ModConfig>(); this.SprintKey = this.Config.GetSprintKey(this.Monitor); helper.Events.GameLoop.UpdateTicked += this.OnUpdateTicked; helper.Events.Input.ButtonPressed += this.OnButtonPressed; this.Monitor.Log("Initialized (press F5 to reload config)"); } /********* ** Private methods *********/ /// <summary>Raised after the game state is updated (≈60 times per second).</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) { if (!Context.IsWorldReady || Game1.paused || Game1.activeClickableMenu != null) return; if (Game1.currentLocation.currentEvent != null) { this.CurrentSpeed = 0; return; } SFarmer player = Game1.player; if (this.Config.HorseSpeed != 0 && player.mount != null) this.CurrentSpeed = this.Config.HorseSpeed; if (this.Config.PlayerRunningSpeed != 0 && player.running) this.CurrentSpeed = this.Config.PlayerRunningSpeed; else this.CurrentSpeed = 0; if (Game1.oldKBState.IsKeyDown(this.SprintKey)) { if (this.Config.SprintingStaminaDrainPerSecond != 0 && player.position != this.PrevPosition) { float loss = this.Config.SprintingStaminaDrainPerSecond * this.ElapsedSeconds; if (player.stamina - loss > 0) { player.stamina -= loss; this.CurrentSpeed *= this.Config.PlayerSprintingSpeedMultiplier; } } else this.CurrentSpeed *= this.Config.PlayerSprintingSpeedMultiplier; } player.addedSpeed = this.CurrentSpeed; this.PrevPosition = player.position; } /// <summary>Raised after the player presses a button on the keyboard, controller, or mouse.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void OnButtonPressed(object sender, ButtonPressedEventArgs e) { if (e.Button == SButton.F5) { this.Config = this.Helper.ReadConfig<ModConfig>(); this.SprintKey = this.Config.GetSprintKey(this.Monitor); this.Monitor.Log("Config reloaded", LogLevel.Info); } } } }
using FluentMigrator; namespace Profiling2.Migrations.Migrations { [Migration(201307151701)] public class AddActiveScreening : Migration { public override void Down() { Delete.Table("PRF_ActiveScreening"); } public override void Up() { Create.Table("PRF_ActiveScreening") .WithColumn("ActiveScreeningID").AsInt32().PrimaryKey().Identity().NotNullable() .WithColumn("PersonID").AsInt32().NotNullable() .WithColumn("RequestID").AsInt32().Nullable() .WithColumn("DateActivelyScreened").AsDateTime().NotNullable() .WithColumn("ScreenedByID").AsInt32().Nullable() .WithColumn("Notes").AsString(int.MaxValue).Nullable(); Create.ForeignKey().FromTable("PRF_ActiveScreening").ForeignColumn("PersonID").ToTable("PRF_Person").PrimaryColumn("PersonID"); Create.ForeignKey().FromTable("PRF_ActiveScreening").ForeignColumn("RequestID").ToTable("SCR_Request").PrimaryColumn("RequestID"); Create.ForeignKey().FromTable("PRF_ActiveScreening").ForeignColumn("ScreenedByID").ToTable("PRF_AdminUser").PrimaryColumn("AdminUserID"); } } }
using DLib.DAL; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; namespace BLL.DLib { public class CmsPage { #region vars private static DlibEntities Db { get { if (HttpContext.Current.Session["DB"] == null) { var entities = new DlibEntities(); HttpContext.Current.Session["DB"] = entities; return entities; } else return HttpContext.Current.Session["DB"] as DlibEntities; } } public tblCmsPage tblcmspage = null; #endregion public static CmsPage GetCmsPage(int PageID) { var q = PageID > 0 ? Db.tblCmsPage.FirstOrDefault(c => c.ID == PageID) : new tblCmsPage(); return new CmsPage { tblcmspage = q }; } public static CmsPage GetCmsMasterPage(int LibID) { var q = Db.tblCmsPage.FirstOrDefault(c => c.LibID == LibID && c.IsMasterPage == true); return new CmsPage { tblcmspage = q }; } public int Save() { if (tblcmspage.ID == 0) Db.tblCmsPage.Add(tblcmspage); Db.SaveChanges(); return tblcmspage.ID; } public void Update() { Db.SaveChanges(); } public string Delete() { while (tblcmspage.tblCmsMenu.Count > 0) tblcmspage.tblCmsMenu.Remove(tblcmspage.tblCmsMenu.FirstOrDefault()); foreach (var op in (from c in Db.tblCmsPageOptionValue where c.PageID == tblcmspage.ID select c)) { tblcmspage.tblCmsPageOptionValue.Remove(op); Db.tblCmsPageOptionValue.Remove(op); } Db.tblCmsPage.Remove(tblcmspage); Db.SaveChanges(); return "حذف شد"; } public string SetMasterPage() { int LibID=tblcmspage.LibID.Value; foreach (var p in Db.tblCmsPage.Where(c => c.LibID == LibID)) { p.IsMasterPage = false; } tblcmspage.IsMasterPage = true; Db.SaveChanges(); return "تنظیم شد"; } public static void DeletePageOptionValues(int PageID) { var pov = Db.tblCmsPageOptionValue.Where(c => c.PageID == PageID); //foreach } public static IList GetPageTypeList() { return Db.tblCmsPageType.ToList(); } public static tblCmsPageType GetPageType(int PageTypeID) { return Db.tblCmsPageType.FirstOrDefault(c => c.ID == PageTypeID); } public static IList GetCmsPages(int LibID) { return Db.tblCmsPage.Where(c => LibID == 0 ? true : c.LibID == LibID).ToList(); } public string GetContentOfPage(int LangID) { string output = ""; switch (tblcmspage.tblCmsPageType.Name) { case "ShowContent": string HtmlCode = tblcmspage.tblCmsPageOptionValue.FirstOrDefault().Value; output = HtmlCode; break; case "ShowRecord": var q = tblcmspage.tblCmsPageOptionValue.FirstOrDefault(); if (q != null) { int RecID = HttpContext.Current.Request["RecID"] == null ? q.Value.ToInt32() : HttpContext.Current.Request["RecID"].ToInt32(); Records rec = Records.GetRecord(RecID,LangID); output = "<p style='font:bold 12px Tahoma'>" + rec.Title + "</p>"; var picField = tblcmspage.tblLibrary.tblLibRecFields.FirstOrDefault(c => c.Name == "PictureUrl"); if (picField != null) { string PictureUrl = rec.GetDynamicData(picField.ID); output += "<img width='400' src='" + PictureUrl + "'><p>"; } output += LibRecTags.ExecuteTags(rec.body, ""); } break; case "RecordList": int OptionID = tblcmspage.tblCmsPageType.tblCmsPageTypeOption.FirstOrDefault().ID; var q1 = tblcmspage.tblCmsPageOptionValue.FirstOrDefault(cc => cc.OptionID == OptionID); if (q1 != null) { int TreeID = q1.Value.ToInt32(); string tbl = "<div><table width='100%' style='border:1px gray solid; border-radius:4px; font:normal 12px Tahoma' dir='rtl'>"; if (TreeID > 0) { string keyword = HttpContext.Current.Request["keyword"]; var pg = tblcmspage.tblLibrary.tblCmsPage.FirstOrDefault(c => c.PageTypeID == 2); int ShowPageID = pg == null ? 0 : pg.ID; foreach (vwRecords rec in Records.GetListInNode(TreeID,LangID,keyword)) { string Title = rec.Title; tbl += "<tr><td>"; tbl += "<a style='font:bold 12px tahoma' href='/?PageID=" + ShowPageID + "&RecID=" + rec.ID + "&LID=" + tblcmspage.LibID + "'>" + Title + "</a>"; string pic = ""; var picField = tblcmspage.tblLibrary.tblLibRecFields.FirstOrDefault(c => c.Name == "PictureUrl"); if (picField != null) { string PictureUrl = Records.GetRecord(rec.ID,LangID).GetDynamicData(picField.ID); tbl += "</td><td rowspan='2'><img width='100' src='"+PictureUrl + "'></td>"; } else tbl += "</td><td rowspan='2'></td>"; tbl += "</tr>"; string brief = rec.Body != null ? rec.Body.Substring(0, 200) + "..." : ""; tbl += "<tr><td>" + brief+ "</td></tr><tr><td colspan='2'><hr></td></tr>"; } } tbl += "</table></div>"; output = tbl; } break; case "Gallery": var q23 = tblcmspage.tblCmsPageOptionValue.FirstOrDefault(c => c.tblCmsPageTypeOption.Option == "GalleryImagesCount"); int GalleryImagesCount = q23.Value.ToInt32(); if (GalleryImagesCount > 0) { output = "<table border='0' cellspacing='0' cellpadding='20' dir='rtl' align='center' style='font:normal 11px tahoma; border:1px gray solid; border-radius:5px; padding:10px' width='100%'><tr>"; int ReqTreeID = HttpContext.Current.Request["TreeID"] == null ? 0 : HttpContext.Current.Request["TreeID"].ToInt32(); var q33 = tblcmspage.tblCmsPageOptionValue.FirstOrDefault(c => c.tblCmsPageTypeOption.Option == "GalleryImages"); string GalleryImages = q33.Value; if (ReqTreeID > 0) { int i = 1; foreach (tblLibRecords rec in Records.GetListInTree(ReqTreeID)) { output += "<td align='center' style='width:200px' valign='top'>" + "<a target='_blank' href='/includes/Show.aspx?ID=" + rec.FileID.Value + "'><img width='150' style='border:1px gray solid; border-radius:5px' src='/includes/download.ashx?ID=" + rec.FileID.Value + "'><br>" + rec.tblLibRecordsLang.FirstOrDefault(c => c.LangID == 1).Title +"</a>"+ "</td>"; if (i > 0 && i % 4 == 0) output += "</tr><tr>"; i++; } } else { for (int i = 0; i < GalleryImagesCount; i++) { int TreeID = CmsModule.GetElementOfGallery(GalleryImages, i, 0).ToInt32(); int RecID = CmsModule.GetElementOfGallery(GalleryImages, i, 1).ToInt32(); if (RecID > 0) { int FileID = Records.GetRecord(RecID,LangID).FileID; if (FileID > 0) { output += "<td align='center' style='width:200px' valign='top'>" + "<a href='/?PageID=" + tblcmspage.ID + "&TreeID=" + TreeID + "'><img width='150' style='border:1px gray solid; border-radius:5px' src='/includes/download.ashx?ID=" + FileID + "'><br>" + LibRecTree.GetLibRecTree(TreeID,LangID).Title + "</a>" + "</td>"; } } if (i > 0 && i % 4 == 0) output += "</tr><tr>"; } } output += "</table>"; } break; case "Search": var q26 = tblcmspage.tblCmsPageOptionValue.FirstOrDefault(c => c.tblCmsPageTypeOption.Option == "SearchText"); string _keyword=HttpContext.Current.Request["keyword"]; output = "<script>" + "function srch(event) {" + " if (event.keyCode == 13 && document.getElementById('__keyword__').value != '') {" + " window.open('/?PageID=" + tblcmspage.ID + "&keyword='+document.getElementById('__keyword__').value,'_self');" + " }" + "}" + "</script>"+ "<div><table border=0 cellpadding=5 cellspacing=0 dir=rtl style='height:40px; width:500px'><tr>"; output += "<td align=left><input type='text' style='width:400px;height:30px; font:normal 20px Tahoma' onfocus=\"if(this.value=='" + (q26 == null ? "" : q26.Value) + "') this.value='';\" onblur=\"if(this.value=='') this.value='" + (q26 == null ? "" : q26.Value) + "';\" value='" + _keyword + "' alt='" + (q26 == null ? "" : q26.Value) + "' maxlength='20' id='__keyword__' name='__keyword__' onkeyup='srch(event)' onkeydown='srch(event)'/></td>" + "<td align=right><input type='submit' value='جستجو' style='width:70px; height:34px; font:normal 12px Tahoma' onclick=\"window.open('/?PageID=" + tblcmspage.ID + "&keyword='+document.getElementById('__keyword__').value,'_self')\" /></td>"; output += "</tr></table></div>"; int _count=0; LuceneSearch LuceneSearchObj = new LuceneSearch { LibID = tblcmspage.LibID.Value }; List<LuceneSearch.SearchResult> SearchResults = LuceneSearchObj.SearchLuceneCondition(_keyword, HttpContext.Current, LangID, out _count, 10); if (SearchResults.Count > 0) { output += "<div><table border=0 cellpadding=5 cellspacing=0 dir=rtl style='width:500px'>"; int RowNum = 1; foreach (LuceneSearch.SearchResult sr in SearchResults) { output += string.Format("<tr><td>{4}</td><td><a href='/?PageID={0}&RecID={1}&LID={2}'>{3}</a></td></tr>", tblcmspage.ID, sr.RecID, tblcmspage.LibID, sr.Title ,RowNum); RowNum++; } output += "</table></div>"; } break; } return output; } public string GetOutputOfPage(int LangID) { string buffer = ""; if (tblcmspage.tblCmsTheme != null) { buffer = tblcmspage.tblCmsTheme.HtmlBody; foreach (var s in tblcmspage.tblCmsTheme.tblCmsThemeSection) { string sec = ""; string output = ""; foreach (var sm in s.tblCmsThemeModule.OrderBy(cc => cc.Order)) { output = CmsModule.GetMuduleOutput(sm.ModuleID.Value, LangID); output = sm.ShowTitle.Value ? "<div style='font:normal 12px Tahoma; padding:5px; background:#999; color:white' dir='rtl'>" + sm.Title + "</div>" + output : output; output = sm.ShowBox.Value ? "<div dir='rtl' style='border:1px gray solid; border-radius:5px'>" + output + "</div>" : output; sec += output; } buffer = buffer.Replace("{sec:" + s.Section + "}", sec); } buffer = buffer.Replace("{sec_content}", GetContentOfPage(LangID)); } return buffer; } } }
public class PairCardValue : CardValue { private int pairNumber; private int lastNumber; public PairCardValue(int number, int pairNumber) { this.lastNumber = number; this.pairNumber = pairNumber; } public override bool CompareValue(CardValue otherValue) { var a = (PairCardValue)otherValue; if(this.pairNumber != a.pairNumber) return true; else return this.lastNumber >= a.lastNumber; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InimigoDano : MonoBehaviour { TomaDano dano; public int dFogo; public int dRaio; public int dNaoSei; public int dAtaqueBasico; public int dFogoArea; public float duracaoSnare; Snared snare; // Start is called before the first frame update void Start() { snare = GetComponent<Snared>(); dano = GetComponent<TomaDano>(); } // Update is called once per frame void Update() { snare.Desnare(duracaoSnare); } private void OnDisable() { dano.vida = 50; } private void OnTriggerEnter(Collider other) { switch (other.gameObject.tag) { case "bolaFogo": dano.gameObject.GetComponent<TomaDano>().TomarDanos(dFogo); break; case "Raio": dano.gameObject.GetComponent<TomaDano>().TomarDanos(dRaio); break; case "NaoSei": if (snare.gameObject.CompareTag("inimigoMadeira")) { dano.gameObject.GetComponent<TomaDano>().TomarDanos(dNaoSei); } else { snare.gameObject.GetComponent<Snared>().Snare(); dano.gameObject.GetComponent<TomaDano>().TomarDanos(dNaoSei); } break; case "RaizDoPlayer": snare.gameObject.GetComponent<Snared>().Snare(); dano.gameObject.GetComponent<TomaDano>().TomarDanos(dNaoSei); break; case "ataqueBasico": dano.gameObject.GetComponent<TomaDano>().TomarDanos(dAtaqueBasico); break; case "pegaFogo": dano.gameObject.GetComponent<TomaDano>().TomarDanos(dFogoArea); break; } } }
using System; using System.Collections.Generic; using System.Text; namespace JTNE.DotNetty.Abstractions.Dtos { public class JTNETcpSessionInfoDto { /// <summary> /// 最后上线时间 /// </summary> public DateTime LastActiveTime { get; set; } /// <summary> /// 上线时间 /// </summary> public DateTime StartTime { get; set; } /// <summary> /// 终端VIN /// </summary> public string Vin { get; set; } /// <summary> /// 远程ip地址 /// </summary> public string RemoteAddressIP { get; set; } } }
using JetBrains.Annotations; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Windows.Input; namespace WPF.NewClientl.ViewModel.Dialogs { public class MeetingLoadingViewMode : INotifyPropertyChanged { private readonly ICommand _closeCommand; private readonly ICommand _confrimCommand; private string _ShowMessage; public MeetingLoadingViewMode(Action<MeetingLoadingViewMode> closeHandler) { _closeCommand = new BaseCommand { ExecuteDelegate = o => closeHandler(this) }; } public MeetingLoadingViewMode(Action<MeetingLoadingViewMode> closeHandler, Action<MeetingLoadingViewMode> confirmHandler) { _closeCommand = new BaseCommand { ExecuteDelegate = o => closeHandler(this) }; _confrimCommand = new BaseCommand { ExecuteDelegate = o => confirmHandler(this) }; } public string ShowMessage { get { return _ShowMessage; } set { _ShowMessage = value; OnPropertyChanged(); } } public ICommand CloseCommand { get { return _closeCommand; } } public ICommand ConfirmCommand { get { return _confrimCommand; } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace EmberMemory.Readers { public abstract class DirectMemoryReader { public Process Process { get; } public DirectMemoryReader(Process process) { this.Process = process; } public abstract void Reload(); public abstract void ResetRegion(); public abstract bool TryFindPattern(byte[] pattern, string mask, int offset, out IntPtr result); public abstract bool TryReadIntPtr(IntPtr address, out IntPtr value); public abstract bool TryReadInt(IntPtr address, out int value); public abstract bool TryReadShort(IntPtr address, out short value); public abstract bool TryReadUShort(IntPtr address, out ushort value); public abstract bool TryReadDouble(IntPtr address, out double value); public abstract bool TryReadString(IntPtr address, out string value); public abstract bool TryReadList<T>(IntPtr address, out List<T> value) where T : struct; } }
namespace WebApiToTypeScript.Types { public class MemberWithCSharpType { public string Name { get; set; } public CSharpType CSharpType { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IWorkFlow.DataBase; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("B_OA_Organization", "id")] public class B_OA_Organization : QueryInfo { /// <summary> /// 主键 /// </summary> [DataField("id", "B_OA_Organization", false)] public int id { get { return _id; } set { _id = value; } } private int _id; /// <summary> /// 简称 /// </summary> [DataField("shortName", "B_OA_Organization")] public string shortName { get { return _shortName; } set { _shortName = value; } } private string _shortName; /// <summary> /// 全称 /// </summary> [DataField("fullName", "B_OA_Organization")] public string fullName { get { return _fullName; } set { _fullName = value; } } private string _fullName; [DataField("pId", "B_OA_Organization")] public int pId { get { return _pId; } set { _pId = value; } } private int _pId; [DataField("isParent", "B_OA_Organization")] public bool isParent { get { return _isParent; } set { _isParent = value; } } private bool _isParent; public string parentName { get { return _parentName; } set { _parentName = value; } } private string _parentName; /// <summary> /// 是否选择 /// </summary> public bool isSelected { get { return _isSelected; } set { _isSelected = value; } } private bool _isSelected; } }
using System; class Program { static void Main() { } } Console.ReadLine(); using System; class jdfj { static void Main() { } } using System; class fsdfds { static void Main() { } } kak
using System; using System.Collections.Generic; using System.Windows.Forms; using HTBAntColonyTSP; using Microsoft.VisualBasic; namespace HTBWorldView { public partial class MainForm : Form { private Map m_Map; private System.Threading.Thread m_TspThread; public MainForm() { InitializeComponent(); } private void MapPicture_MouseUp(object sender, MouseEventArgs e) { switch (e.Button) { case MouseButtons.Left: if (m_Map.FindCity(e.Location) == null) { m_Map.AddCity(e.Location); } break; case MouseButtons.Right: m_Map.RemoveCity(e.Location); break; } } private void StartButton_Click(object sender, EventArgs e) { StopTsp(); if (m_Map.CityCount < 4) { Interaction.MsgBox("At least 4 cities are needed.", MsgBoxStyle.Information, "Error"); return; } StopButton.Enabled = true; StartButton.Enabled = false; m_TspThread = new System.Threading.Thread(StartTsp); m_TspThread.IsBackground = true; m_TspThread.Start(); } private void StopButton_Click(object sender, EventArgs e) { StopTsp(); } private void ClearButton_Click(object sender, EventArgs e) { StopTsp(); m_Map.Clear(); } private void ShowLabelsCheck_CheckedChanged(object sender, EventArgs e) { m_Map.ShowLabels = ShowLabelsCheck.Checked; } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { StopTsp(); } private void ShowDebugCheck_CheckedChanged(object sender, EventArgs e) { DebugWindow.Instance.Visible = ShowDebugCheck.Checked; } private void StartTsp() { Invoke(new Action(DebugWindow.Instance.Clear)); var w = m_Map.ConstructTsp(); w.Update += World_Update; var best_tour = w.FindTour(-1, false); Invoke(new Action<IEnumerable<TspCity>>(m_Map.DrawBestTour), best_tour); Invoke(new Action(StopTsp)); } private void StopTsp() { StopButton.Enabled = false; if (m_TspThread != null && m_TspThread.IsAlive) { m_TspThread.Abort(); } StartButton.Enabled = true; } private void World_Update(World sender, UpdateEventArgs e) { if (InvokeRequired) { Invoke(new Action<World, UpdateEventArgs>(World_Update), sender, e); System.Threading.Thread.Sleep(100); return; } m_Map.Redraw(sender, e); DebugWindow.Instance.AddItem(e.ToString()); } private void MainForm_Load(object sender, EventArgs e) { // OpenPictureDialog.Filter = SupportedPictureFilters() // StopButton.Enabled = False m_Map = new Map(MapPicture); } } }
using System; using System.Threading.Tasks; using GreenPipes; using MassTransit; namespace Retries { internal static class Program { static async Task Main(string[] args) { var busControl = CreateBusControl(); await StartBusControl(busControl); } private static IBusControl CreateBusControl() { return Bus.Factory.CreateUsingRabbitMq(cfg => { cfg.Host("localhost"); // Enable redelivery. cfg.UseDelayedExchangeMessageScheduler(); cfg.ReceiveEndpoint("message-queue", e => { // Configure redelivery retries. e.UseScheduledRedelivery(retryConfigurator => { // Do not retry "NameTooShortException" exception. retryConfigurator.Ignore(typeof(NameTooShortException)); retryConfigurator.Intervals( TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(2), TimeSpan.FromMinutes(3) ); } ); e.UseMessageRetry(retryConfigurator => { // Do not retry "NameTooShortException" exception. retryConfigurator.Ignore(typeof(NameTooShortException)); retryConfigurator.Incremental( 3, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(15) ); } ); e.Consumer<Consumer>(); }); }); } private static async Task StartBusControl(IBusControl busControl) { await busControl.StartAsync(); await busControl.Publish<IMessage>( new Message(Guid.NewGuid().ToString(), "Valid name") ); await busControl.Publish<IMessage>( new Message(Guid.NewGuid().ToString(), "Short") ); Console.WriteLine("Press any key to exit"); await Task.Run(() => Console.ReadKey()); await busControl.StopAsync(); } } }
using Xamarin.Forms; namespace AsNum.XFControls { /// <summary> /// 单选按钮(模拟) /// </summary> public class Radio : ContentView { #region value /// <summary> /// 单选项的值 /// </summary> public static BindableProperty ValueProperty = BindableProperty.Create("Value", typeof(object), typeof(Radio)); /// <summary> /// 单选项的值 /// </summary> public object Value { get { return this.GetValue(ValueProperty); } set { this.SetValue(ValueProperty, value); } } #endregion #region isSelected /// <summary> /// 是否选中 /// </summary> public static BindableProperty IsSelectedProperty = BindableProperty.Create("IsSelected", typeof(bool), typeof(Radio), false, BindingMode.TwoWay, propertyChanged: IsSelectedChanged ); /// <summary> /// /// </summary> /// <param name="bindable"></param> /// <param name="oldValue"></param> /// <param name="newValue"></param> private static void IsSelectedChanged(BindableObject bindable, object oldValue, object newValue) { var radio = (Radio)bindable; var source = (bool)newValue ? Checked : Unchecked; radio.Icon.Source = source; //new BytesImageSource(datas); } /// <summary> /// 是否选中 /// </summary> public bool IsSelected { get { return (bool)this.GetValue(IsSelectedProperty); } set { this.SetValue(IsSelectedProperty, value); } } #endregion #region Text /// <summary> /// 标签文本 /// </summary> public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(Radio), "", propertyChanged: TextChanged ); private static void TextChanged(BindableObject bindable, object oldValue, object newValue) { var radio = (Radio)bindable; radio.Lbl.Text = (string)newValue; } /// <summary> /// 标签文本 /// </summary> public string Text { get { return (string)this.GetValue(TextProperty); } set { this.SetValue(TextProperty, value); } } #endregion #region TextAlignment /// <summary> /// 标签文本的对齐方式 /// </summary> public static readonly BindableProperty TextAlignmentProperty = BindableProperty.Create("TextAlignment", typeof(TextAlignment), typeof(Radio), TextAlignment.Start ); /// <summary> /// 标签文本的对齐方式 /// </summary> public TextAlignment TextAlignment { get { return (TextAlignment)this.GetValue(TextAlignmentProperty); } set { this.SetValue(TextAlignmentProperty, value); } } #endregion #region Size /// <summary> /// 单选按钮的大小, 对标签文本无效 /// </summary> internal static readonly BindableProperty SizeProperty = BindableProperty.Create("Size", typeof(double), typeof(Radio), 25D, propertyChanged: IconSizeChanged); /// <summary> /// 单选按钮的大小, 对标签文本无效 /// </summary> internal double Size { get { return (double)this.GetValue(SizeProperty); } set { this.SetValue(SizeProperty, value); } } private static void IconSizeChanged(BindableObject bindable, object oldValue, object newValue) { var chk = (Radio)bindable; chk.Icon.WidthRequest = chk.Icon.HeightRequest = (double)newValue; } #endregion #region ShowRadio /// <summary> /// 是否显示按钮图标(用于RadioButton) /// </summary> public static readonly BindableProperty ShowRadioProperty = BindableProperty.Create("ShowRadio", typeof(bool), typeof(Radio), true ); /// <summary> /// 是否显示按钮图标(用于RadioButton) /// </summary> public bool ShowRadio { get { return (bool)this.GetValue(ShowRadioProperty); } set { this.SetValue(ShowRadioProperty, value); } } #endregion /// <summary> /// 按钮的模拟图片,图片必须是嵌入的资源 /// </summary> private static readonly ImageSource Checked; private static readonly ImageSource Unchecked; static Radio() { Unchecked = ImageSource.FromResource("AsNum.XFControls.Imgs.Radio-Unchecked.png"); //GetImg("AsNum.XFControls.Imgs.Radio-Unchecked.png"); Checked = ImageSource.FromResource("AsNum.XFControls.Imgs.Radio-Checked.png"); //GetImg("AsNum.XFControls.Imgs.Radio-Checked.png"); } //private static byte[] GetImg(string imgFile) { // var asm = typeof(Radio).GetTypeInfo().Assembly; // using (var stm = asm.GetManifestResourceStream(imgFile)) { // return stm.GetBytes(); // } //} private Image Icon; private Label Lbl; public Radio() { var layout = new StackLayout() { Orientation = StackOrientation.Horizontal }; this.Content = layout; this.Icon = new Image() { Source = Unchecked, //new BytesImageSource(Unchecked), WidthRequest = this.Size, HeightRequest = this.Size }; this.Icon.SetBinding(Image.IsVisibleProperty, new Binding("ShowRadio", source: this)); layout.Children.Add(this.Icon); this.Lbl = new Label(); this.Lbl.SetBinding(Label.HorizontalTextAlignmentProperty, new Binding("TextAlignment", source: this)); this.Lbl.Text = this.Text; layout.Children.Add(this.Lbl); } } }
using System.Collections.Generic; namespace MultiLingualPlayings.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<MultiLingualPlayings.MyDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(MultiLingualPlayings.MyDbContext context) { var monitorsCategory = context.Categories.FirstOrDefault(c => c.Name == "Monitors"); if (monitorsCategory == null) { monitorsCategory = context.Categories.Add(new Category {Name = "Monitors"}); context.SaveChanges(); } var keyboardsCategory = context.Categories.FirstOrDefault(c => c.Name == "Keyboards"); if (keyboardsCategory == null) { keyboardsCategory = context.Categories.Add(new Category { Name = "Keyboards" }); context.SaveChanges(); } var asusMonitor = context.Products.FirstOrDefault(p => p.CategoryId == monitorsCategory.Id && p.Price == 699); if (asusMonitor == null) { asusMonitor = context.Products.Add( new Product { CategoryId = monitorsCategory.Id, Price = 699, Translations = new List<ProductTranslation> { new ProductTranslation { Language = "en", Title = "A monitor English title", Description = "A monitor English description" }, new ProductTranslation { Language = "tr", Title = "A monitor Turkish title", Description = "A monitor Turkish description" } } }); context.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.OleDb; namespace QLBSX_DAL_WS { [System.Xml.Serialization.XmlInclude(typeof(BienSoXeRomooc))] public class BienSoXeRomooc : BienSoXe { #region - Attribute private int _NamSanXuat; private KichThuocBao _Ktb; private int _TaiTrong; private DateTime _NgayHetHan; #endregion #region - Property public int NamSanXuat { get { return _NamSanXuat; } set { _NamSanXuat = value; } } public KichThuocBao Ktb { get { return _Ktb; } set { _Ktb = value; } } public int TaiTrong { get { return _TaiTrong; } set { _TaiTrong = value; } } public DateTime NgayHetHan { get { return _NgayHetHan; } set { _NgayHetHan = value; } } #endregion //public BienSoXeRomooc() //{ // _TenChuXe = _DiaChi = _NhanHieu = _MauSon = _SoKhung = _BienSo = ""; // _NgayDangKyLanDau = new DateTime(1900, 1, 1); // _VoHieuHoa = false; //} //public BienSoXeRomooc(BienSoXe bs) //{ // _MaBienSo = bs.MaBienSo; // _TenChuXe = bs.TenChuXe; // _DiaChi = bs.DiaChi; // _NhanHieu = bs.NhanHieu; // _MauSon = bs.MauSon; // _SoKhung = bs.SoKhung; // _BienSo = bs.BienSo; // _NgayDangKyLanDau = bs.NgayDangKyLanDau; // _VoHieuHoa = bs.VoHieuHoa; //} public override string GetInfo() { string info = "<BS l='Romooc' " + "nsx ='" + NamSanXuat + "' " + "tat='" + TaiTrong + "' " + "nhh='" + NgayHetHan.ToShortDateString() + "'>" + "<KTB " + "d='" + Ktb.Dai + "' " + "r='" + Ktb.Rong + "' " + "c='" + Ktb.Cao + "'/>" + "</BS>"; return info; } public static BienSoXeRomooc ConvertToRomooc(object bs) { if (bs is BienSoXeRomooc) { BienSoXeRomooc temp = new BienSoXeRomooc(); temp = (BienSoXeRomooc)bs; return temp; } else return null; } public static BienSoXeRomooc FromDataReader(OleDbDataReader dr) { BienSoXeRomooc bs = new BienSoXeRomooc(); bs.MaBienSo = dr.GetInt32(0); if (!dr.IsDBNull(1)) bs.TenChuXe = dr.GetString(1); if (!dr.IsDBNull(2)) bs.DiaChi = dr.GetString(2); if (!dr.IsDBNull(3)) bs.NhanHieu = dr.GetString(3); if (!dr.IsDBNull(4)) bs.MauSon = dr.GetString(4); if (!dr.IsDBNull(5)) bs.SoKhung = dr.GetString(5); if (!dr.IsDBNull(6)) bs.BienSo = dr.GetString(6); if (!dr.IsDBNull(7)) bs.NgayDangKyLanDau = dr.GetDateTime(7); if (!dr.IsDBNull(8)) bs.VoHieuHoa = dr.GetBoolean(8); return bs; } public override BienSoXe Clone() { return (BienSoXe)this.MemberwiseClone(); } } }
using AimaTeam.WebFormLightAPI.httpEntity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace AimaTeam.WebFormLightAPI.httpCore.ReqKernal { /// <summary> /// 定义一个对ReqCache管理的工厂接口(可以通过实现此接口来改变对请求的ReqCache对象进行管理) /// </summary> public interface IReqCacheDb { /// <summary> /// 获取ReqCache请求信息缓存数据库中的缓存的ReqCache对象,有缓存返回缓存的ReqCache,否则返回null /// </summary> /// <param name="request">HttpRequest对象</param> ReqCache Get(HttpRequest request); /// <summary> /// 获取ReqCache请求信息缓存数据库中的缓存的ReqCache对象,有缓存返回缓存的ReqCache,否则new ReqCache返回 /// </summary> /// <param name="key">缓存键</param> /// <param name="isCached">对象是否是缓存的(输出参数)</param> /// <returns></returns> ReqCache Get(string key, out bool isCached); /// <summary> /// 获取ReqCache请求信息缓存数据库中的缓存的ReqCache对象,有缓存返回缓存的ReqCache,否则返回null /// </summary> /// <param name="key">缓存键</param> /// <returns></returns> ReqCache GetReqCache(string key); /// <summary> /// 缓存ReqCache到ReqCache请求信息缓存数据库中 /// </summary> /// <param name="request">HttpRequest对象</param> /// <param name="key">缓存键</param> /// <param name="reqCache">缓存值</param> /// <param name="isCached">是否是已经缓存过的值</param> /// <param name="isForever">是否永远缓存</param> bool Set(HttpRequest request, string key, ReqCache reqCache, bool isCached, bool isForever); /// <summary> /// 移除ReqCache的IsBadIP标识 /// </summary> /// <param name="reqCache">ReqCache对象</param> /// <param name="isForce">是否不检验reqCache.IsBadIP标识进行强制重置IdBadIP</param> void RemoveBadIP(ref ReqCache reqCache, bool isForce = false); /// <summary> /// 将ReqCache的Req_Allow_Clear_IsBadIP_Date添加到最大时间(此ReqCache对象将永远被禁止访问,直到解除为止) /// </summary> /// <param name="reqCache">ReqCache对象</param> void SetBadIPForever(ref ReqCache reqCache); /// <summary> /// 将ReqCache的IsPassBadIPValid设置为True,标识此ReqCache永远在黑名单IP外 /// </summary> /// <param name="reqCache">ReqCache对象</param> void SetIsValidIPForever(ref ReqCache reqCache); /// <summary> /// 添加/减少请求挂起的次数(addNum大于0,表示添加,否则减少) /// </summary> /// <param name="reqCache">需要调整的ReqCache对象</param> /// <param name="addNum">添加/减少的次数</param> void AddReq_Wait_Count(ref ReqCache reqCache, int addNum); /// <summary> /// 添加/减少单位时间内的请求次数(addNum大于0,表示添加,否则减少) /// </summary> /// <param name="reqCache">需要调整的ReqCache对象</param> /// <param name="addNum">添加/减少的次数</param> void AddReq_Seconds_Count(ref ReqCache reqCache, int addNum); /// <summary> /// 校验IP地址是否不属于黑名单IP /// </summary> /// <param name="reqCache">需要校验的ReqCache对象</param> /// <returns></returns> bool IsValidIP(ReqCache reqCache); /// <summary> /// 清除ReqCacheDb中所有的ReqCache对象 /// </summary> void ClearReqCache(); /// <summary> /// 从ReqCacheDb中删除ReqCache对象 /// </summary> /// <param name="reqKey">ReqCache的键</param> bool Remove(string reqKey); } }
using System.Globalization; namespace Eda.Integrations.Delivery { /// <inheritdoc /> /// <summary> /// The data contract for the country. /// </summary> public interface ICountry : INamedObject { /// <summary> /// Gets the country culture. /// </summary> CultureInfo Culture { get; } /// <summary> /// Gets the country currency. /// Not used now. /// </summary> object Currency { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TBQuestGame.Models; using System.Collections.ObjectModel; namespace TBQuestGame.Models { class WinTickets : GameItem { public int WinChange { get; set; } public WinTickets(int id, string name, int value, int winChange, string description) : base(id, name, value, description) { WinChange = winChange; } //public WinTickets(int id, string name, int value, string description, string useMessage) //{ //} public override string InformationString() { if (WinChange != 0) { return $"{Name}: {Description}\nWin: {WinChange}"; } else { return $"{Name}: {Description}"; } } } }
using System; using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class Loading : MonoBehaviour { public int SceneIndex { get; set; } // Use this for initialization void Start () { StartCoroutine(LoadAsync(SceneIndex)); StartCoroutine(LoadAsyncUI()); } IEnumerator LoadAsync(int index) { yield return SceneManager.LoadSceneAsync(index); } IEnumerator LoadAsyncUI() { yield return SceneManager.LoadSceneAsync("GameUI", LoadSceneMode.Additive); } }
using System; using System.Collections; using System.Data; using System.Reflection; using HTB.Database; using HTB.Database.Views; using HTB.v2.intranetx.util; using HTBAktLayer; using HTBExtras.XML; using HTBUtilities; using System.Security; namespace HTB.v2.intranetx.aktenint.tablet { public partial class DownloadAktTablet2 : System.Web.UI.Page { private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType); protected void Page_Load(object sender, EventArgs e) { int aktId = GlobalUtilArea.GetZeroIfConvertToIntError(Request.Params[GlobalHtmlParams.INTERVENTION_AKT]); if (aktId <= 0) { Response.Write("Error: Kein Akttyp ID!"); return; } qryAktenInt qryAkt = HTBUtils.GetInterventionAktQry(aktId); if (qryAkt == null) { Response.Write("Error: Akt [" + aktId + "] Nicht Gefunden"); return; } try { var rec = new XmlInterventionAkt2(); rec.Assign(qryAkt); rec.aktIntAmounts = AktInterventionUtils.GetAktAmounts(qryAkt, false); rec.aktIntAmounts.GetTotal(); var sv = (SingleValue)HTBUtils.GetSqlSingleRecord("SELECT COUNT(*) IntValue FROM tblAktenIntAction WHERE AktIntActionAkt = " + aktId, typeof(SingleValue)); try { rec.AktHasActions = sv.IntValue > 0; } catch { } AddAktDocuments(rec); AddAktAddressesAndPhones(rec); AddAktJournal(rec); var protocol = (tblProtokol)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblProtokol WHERE AktIntID = " + aktId + " ORDER BY ProtokolID DESC", typeof(tblProtokol)); if (protocol != null) { rec.protocol = protocol; } var protocolUbername = (tblProtokolUbername)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblProtokolUbername WHERE UbernameAktIntID = " + aktId, typeof(tblProtokolUbername)); if (protocolUbername != null) { rec.protocolUbername = protocolUbername; } Response.Write(rec.ToXmlString().Replace("XmlInterventionAkt2", "XmlInterventionAkt")); } catch (Exception ex) { Response.Write(ex.Message); Response.Write(ex.StackTrace); Log.Error("AktId: " + aktId + " "+ex.Message); Log.Error(ex); } } private void AddAktJournal(XmlInterventionAkt2 akt) { ArrayList list = HTBUtils.GetStoredProcedureRecords("spGetAktJournal", new ArrayList { new StoredProcedureParameter("intAktId", SqlDbType.Int, akt.AktIntID) }, typeof(XmlJournalRecord) ); foreach (XmlJournalRecord rec in list) { rec.ActionMemo = SecurityElement.Escape(rec.ActionMemo); akt.AddJournal(rec); } } private void AddAktDocuments(XmlInterventionAkt2 akt) { ArrayList docsList = HTBUtils.GetSqlRecords("SELECT * FROM qryDoksIntAkten WHERE AktIntID = " + akt.AktIntID, typeof(qryDoksIntAkten)); if (akt.IsInkasso()) HTBUtils.AddListToList(HTBUtils.GetSqlRecords("SELECT * FROM qryDoksInkAkten WHERE CustInkAktID = " + akt.AktIntCustInkAktID, typeof(qryDoksInkAkten)), docsList); foreach (Record doc in docsList) { akt.AddDocument(doc, Request.Url.Scheme, Request.Url.Host); } } private void AddAktAddressesAndPhones(XmlInterventionAkt2 akt) { foreach (Record rec in HTBUtils.GetSqlRecords("SELECT * FROM tblGegnerAdressen WHERE GAGegner = " + akt.GegnerID, typeof(XmlGegnerAddress))) { akt.addAddress(rec); } foreach (Record rec in HTBUtils.GetSqlRecords("SELECT * FROM tblGegnerAdressen WHERE GAGegner = " + akt.Gegner2ID, typeof(XmlGegner2Address))) { akt.addAddress2(rec); } foreach (Record rec in HTBUtils.GetSqlRecords("SELECT * FROM qryGegnerPhone WHERE GPhoneGegnerID = " + akt.GegnerID, typeof(XmlGegnerPhone))) { akt.addPhone(rec); } foreach (Record rec in HTBUtils.GetSqlRecords("SELECT * FROM qryGegnerPhone WHERE GPhoneGegnerID = " + akt.Gegner2ID, typeof(XmlGegner2Phone))) { akt.addPhone2(rec); } } } }
using System; using System.Collections.Generic; using FluentAssertions; using ILogging; using Moq; using NUnit.Framework; using ServiceDeskSVC.Controllers.API; using ServiceDeskSVC.Controllers.API.AssetManager; using ServiceDeskSVC.DataAccess; using ServiceDeskSVC.DataAccess.AssetManager; using ServiceDeskSVC.DataAccess.Models; using ServiceDeskSVC.Domain.Entities.ViewModels.AssetManager; using ServiceDeskSVC.Managers; using ServiceDeskSVC.Managers.Managers; using ServiceDeskSVC.Managers.Managers.AssetManager; namespace ServiceDeskSVC.Tests.Controllers { [TestFixture] public class ModelsControllerTest { private ModelsController _ModelsController; private Mock<IAssetManagerModelsRepository> _assetModelsRepository; private IAssetManagerModelsManager _assetModelsManager; private Mock<ILogger> _logger; [SetUp] public void BeforeEach() { _assetModelsRepository = new Mock<IAssetManagerModelsRepository>(); _logger = new Mock<ILogger>(); _assetModelsManager = new AssetManagerModelsManager(_assetModelsRepository.Object, _logger.Object); _ModelsController = new ModelsController(_assetModelsManager, _logger.Object); } [Test] public void TestEntities_ConfirmMapsIntoViewModel() { // Arrange _assetModelsRepository.Setup(x => x.GetAllModels()).Returns(GetModelsList); // Act var allModels = _ModelsController.Get(); var expectedResult = GetModelsList_ResultForMappingToVM(); // Assert Assert.IsNotNull(allModels, "Result is null"); allModels.ShouldBeEquivalentTo(expectedResult); } [Test] public void TestAddingNewModels_DoesntReturnNull_ReturnsNewModelsID() { // Arrange _assetModelsRepository.Setup(x => x.CreateModel(It.IsAny<AssetManager_Models>())) .Returns(PostModels_ResultFromPostReturnInt()); // Act var postTaskTypeID = _ModelsController.Post(PostModels()); // Assert Assert.IsNotNull(postTaskTypeID, "Result is null"); postTaskTypeID.ShouldBeEquivalentTo(1); } [Test] public void TestEditingModels_DoesntReturnNull_ReturnsSameTaskTypeID() { //Arrange _assetModelsRepository.Setup( x => x.EditModel(It.IsAny<int>(), It.IsAny<AssetManager_Models>())) .Returns(PutModels_ResultFromPutReturnInt()); //Act var putModelsID = _ModelsController.Put(1, PutModels()); //Assert Assert.IsNotNull(putModelsID, "Result is null"); putModelsID.ShouldBeEquivalentTo(1); } [Test] public void TestDeleteModels_ReturnedTrue() { //Arrange _assetModelsRepository.Setup(x => x.DeleteModels(It.IsAny<int>())).Returns(true); //Act var isDeleted = _ModelsController.Delete(1); //Assert Assert.IsTrue(isDeleted); } private List<AssetManager_Models> GetModelsList() { var ModelsValues = new List<AssetManager_Models> { new AssetManager_Models { Id = 1, ModelName = "Model1", CompanyId = 1, DescriptionNotes = "description model1", ManufacturerWebsite = "www.google.com", SupportWebsite = "www.google.com" }, new AssetManager_Models { Id = 2, ModelName = "Model2", CompanyId = 1, DescriptionNotes = "description model2", ManufacturerWebsite = "www.google.com", SupportWebsite = "www.google.com" } }; return ModelsValues; } private List<AssetManager_Models_vm> GetModelsList_ResultForMappingToVM() { var ModelsValues_Result = new List<AssetManager_Models_vm> { new AssetManager_Models_vm { Id = 1, ModelName = "Model1", CompanyId = 1, DescriptionNotes = "description model1", ManufacturerWebsite = "www.google.com", SupportWebsite = "www.google.com" }, new AssetManager_Models_vm { Id = 2, ModelName = "Model2", CompanyId = 1, DescriptionNotes = "description model2", ManufacturerWebsite = "www.google.com", SupportWebsite = "www.google.com" } }; return ModelsValues_Result; } private AssetManager_Models_vm PostModels() { return new AssetManager_Models_vm { Id = 3, ModelName = "Model3", CompanyId = 1, DescriptionNotes = "description model3", ManufacturerWebsite = "www.google.com", SupportWebsite = "www.google.com" }; } private int PostModels_ResultFromPostReturnInt() { return 1; } private AssetManager_Models_vm PutModels() { return new AssetManager_Models_vm { Id = 1, ModelName = "Model1 Changed", CompanyId = 1, DescriptionNotes = "description model1 changed", ManufacturerWebsite = "www.google.com", SupportWebsite = "www.google.com" }; } private int PutModels_ResultFromPutReturnInt() { return 1; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace AstronomyCalculator { public partial class astCalcForm : Form { private IDictionary<string, string> spaceInfo = null; private void tabInfo_Enter(object sender, EventArgs e) { if (null == spaceInfo) { spaceInfo = new Dictionary<string, string>(); loadInfoText(); } } private void listInfo_SelectedIndexChanged(object sender, EventArgs e) { displayInfo(listInfo.Text.Trim()); } private void displayInfo(string item) { string info; try { info = spaceInfo[item]; } catch (KeyNotFoundException) { info = "Data Not Found for " + item; } tInfo.Text = info; tInfo.SelectionStart = 0; tInfo.ScrollToCaret(); } private void tInfoSearch_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) { return; } e.Handled = true; e.SuppressKeyPress = true; string searchTerm = tInfoSearch.Text.ToLower(); tInfo.Text = "Searching for " + searchTerm + Environment.NewLine; bool found = false; foreach (KeyValuePair<string, string> kvp in spaceInfo) { if (kvp.Value.ToLower().Contains(searchTerm)) { found = true; string[] lines = kvp.Value.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i< lines.Length; i++) { StringBuilder block = new StringBuilder(lines[i]); int idx = i; // Need to find "blocks" of text e.g. // Albedo 0.367 geometric // 0.306 Bond // Should be treated as one item. while (idx+1<lines.Length && (lines[idx+1].StartsWith(" ")||lines[idx+1].StartsWith("\t"))) // lookahead { block.Append(Environment.NewLine).Append("\t\t\t").Append(lines[idx + 1]); idx++; } if (block.ToString().ToLower().Contains(searchTerm)) { tInfo.AppendText(kvp.Key + "\t\t" + block.ToString() + Environment.NewLine); } i = idx; } } } if (!found) { tInfo.AppendText(Environment.NewLine + "\tSearch term not found"); } } private void loadInfoText() { Assembly assembly = typeof(astCalcForm).Assembly; Regex sequenced = new Regex(@"^\d\d\d"); string[] resourceNames = assembly.GetManifestResourceNames(); Array.Sort(resourceNames); int datFiles = resourceNames.Count(r => r.EndsWith(".dat")); object[] infoNames = new object[datFiles]; int idx = 0; foreach (string resource in resourceNames) { //Console.WriteLine("Found resource: " + resource); string[] tokens = resource.Split('.'); string name = tokens[tokens.Length - 2]; string ext = tokens[tokens.Length - 1]; if (ext != "dat") { continue; } // Check to see if we have a sequencing prefix on the resources e.g. 000Sol 010Mercury bool subItem = true; if (sequenced.Match(name).Success) { if (name.Substring(2, 1).Equals("0")) // ends with a 0 is not a subitem { subItem = false; } name = name.Substring(3); } else { subItem = false; // not subitem if no prefix } if (subItem) { infoNames[idx++] = " " + name; } else { infoNames[idx++] = name; } StreamReader sr = new StreamReader(assembly.GetManifestResourceStream(resource)); string fileText = sr.ReadToEnd(); spaceInfo.Add(name, fileText); } listInfo.Items.AddRange(infoNames); } } }
using System.Collections.Generic; using Profiling2.Domain.Prf.Persons; namespace Profiling2.Domain.Contracts.Queries { public interface IWantedTasks { IList<Person> GetWantedCommanders(); } }
using gView.Drawing.Pro.Filters; using System; using System.Collections.Generic; using System.IO; namespace gView.Drawing.Pro { public enum ImageProcessingFilters { Default, GrayscaleBT709, GrayscaleRMY, GrayscaleY, Channel_Red, Channel_Green, Channel_Blue, Channel_Alpha } public enum ImageProcessingFilterCategory { All = 0, Standard = 1, Art = 2, Color = 4, Correction = 8 } public class ImageProcessing { #region Filters (System.Drawing) private static byte[] ApplyFilter(byte[] imageBytes, IFilter filter, System.Drawing.Imaging.ImageFormat format = null) { if (imageBytes == null) return null; try { using (var from = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(new MemoryStream(imageBytes))) { using (System.Drawing.Bitmap bm = filter.Apply(from)) { return ImageOperations.Image2Bytes(bm, format ?? from.RawFormat); } } } catch (Exception ex) { string msg = ex.Message; } return null; } public static byte[] ApplyFilter(System.Drawing.Image image, ImageProcessingFilters filter, System.Drawing.Imaging.ImageFormat format = null) { try { return ApplyFilter(ImageOperations.Image2Bytes(image), filter, format); } catch { return null; } } public static byte[] ApplyFilter(byte[] imageBytes, ImageProcessingFilters filter, System.Drawing.Imaging.ImageFormat format = null) { IFilter baseFilter = null; switch (filter) { case ImageProcessingFilters.Default: return imageBytes; case ImageProcessingFilters.GrayscaleBT709: baseFilter = Grayscale.BT709; break; case ImageProcessingFilters.GrayscaleRMY: baseFilter = Grayscale.RMY; break; case ImageProcessingFilters.GrayscaleY: baseFilter = Grayscale.Y; break; case ImageProcessingFilters.Channel_Red: baseFilter = ExtractChannel.R; break; case ImageProcessingFilters.Channel_Green: baseFilter = ExtractChannel.G; break; case ImageProcessingFilters.Channel_Blue: baseFilter = ExtractChannel.B; break; case ImageProcessingFilters.Channel_Alpha: baseFilter = ExtractChannel.A; break; } if (baseFilter == null) return null; return ApplyFilter(imageBytes, baseFilter, format); } #endregion #region Filters (GraphicsEngine) public static byte[] ApplyFilter(byte[] imageBytes, ImageProcessingFilters filter, GraphicsEngine.ImageFormat format) { IFilter baseFilter = null; switch (filter) { case ImageProcessingFilters.Default: return imageBytes; case ImageProcessingFilters.GrayscaleBT709: baseFilter = Grayscale.BT709; break; case ImageProcessingFilters.GrayscaleRMY: baseFilter = Grayscale.RMY; break; case ImageProcessingFilters.GrayscaleY: baseFilter = Grayscale.Y; break; case ImageProcessingFilters.Channel_Red: baseFilter = ExtractChannel.R; break; case ImageProcessingFilters.Channel_Green: baseFilter = ExtractChannel.G; break; case ImageProcessingFilters.Channel_Blue: baseFilter = ExtractChannel.B; break; case ImageProcessingFilters.Channel_Alpha: baseFilter = ExtractChannel.A; break; } // DoTo using(var iBitmap = GraphicsEngine.Current.Engine.CreateBitmap(new MemoryStream(imageBytes))) { } return imageBytes; } #endregion } }
//============================================================================== // Copyright (c) 2012-2020 Fiats Inc. All rights reserved. // https://www.fiats.asia/ // namespace Financial.Extensions.Trading { public enum PositionState { Active, Closed, } }
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Concurrent; using System; using System.Linq; namespace carto.Models { public class RepositoryAdapterStub<T> : IRepositoryAdapter<T> { private readonly ConcurrentDictionary<long, T> _dico; private readonly Func<T, long> _idGetter; public RepositoryAdapterStub(Func<T, long> idGetter, IEnumerable<T> seed) { _idGetter = idGetter; _dico = new ConcurrentDictionary<long, T>(seed.ToDictionary(x => _idGetter(x))); } public IEnumerable<T> ReadAll() { return _dico.Values; } public IEnumerable<T> ReadAll(long graphId) { return ReadAll(); } public T Create(T item) { _dico.TryAdd(_idGetter(item), item); return item; } public T Update(T item) { _dico[_idGetter(item)]= item; return item; } public bool Delete(long id) { T item; return _dico.TryRemove(id, out item); } public long ReadMaxId() { if (_dico.Any()) { return _dico.Keys.Max(); } else { return 0; } } public T Read(long id) { return _dico[id]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PL.Models; using PL.Views; using PL.Commands; using BE; using System.ComponentModel; using System.Windows; using System.Windows.Forms; namespace PL.ViewModel { public class UpdateShopVM: INotifyPropertyChanged { public UpdateShopVM(UpdateShopUC updateShopUC) { CurrentModel = new UpdateShopModel(); CurrentModel.MyShop = updateShopUC.shop; this.UpdateShopUC = updateShopUC; updateShopUC.Password.Password = CurrentModel.MyShop.Password; updateShopUC.ConfirmPassword.Password = CurrentModel.MyShop.Password; this.MyCommand = new SpecialCommand(); MyCommand.callComplete += UpdateShop; ImageCommand = new Command(); ImageCommand.callComplete += OpenFileCommand; } private string image { get; set; } public UpdateShopModel CurrentModel { get; set; } public event PropertyChangedEventHandler PropertyChanged; public Command ImageCommand { get; set; } public string Image { get { return CurrentModel.MyShop.images[0]; } } public string Id { get { return CurrentModel.MyShop.Id; } set { CurrentModel.MyShop.Id = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Id")); } } public string Password { private get { return CurrentModel.MyShop.Password; } set { CurrentModel.MyShop.Password = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Password")); } } public string Adress { private get { return CurrentModel.MyShop.Adress; } set { CurrentModel.MyShop.Adress = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Adress")); } } public string Phone { private get { return CurrentModel.MyShop.Phone; } set { CurrentModel.MyShop.Phone = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Phone")); } } public string FaceBook { private get { return CurrentModel.MyShop.FaceBookLink; } set { CurrentModel.MyShop.FaceBookLink = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("FaceBookLink")); } } public string WebSite { private get { return CurrentModel.MyShop.WebSiteLink; } set { CurrentModel.MyShop.WebSiteLink = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("WebSiteLink")); } } private UpdateShopUC UpdateShopUC; public SpecialCommand MyCommand { get; set; } #region functions public void UpdateShop(string parameter) { if( image != null) { CurrentModel.MyShop.images.RemoveAt(0); CurrentModel.MyShop.images.Add(image); } CurrentModel.MyShop.UpdateData(); CurrentModel.MyShop.UpdateLists(); CurrentModel.UpdateShop(UpdateShopUC.shop, CurrentModel.MyShop); //private ShopAreaUC shopAreaUC = new ShopAreaUC(UpdateShopUC.shop.Id); //profileBarUC = new ProfileBarUC(shop); } private void OpenFileCommand() { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Image files (*.png;*.jpg)|*.png;*.jpg|All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) { image = open.FileName; } //this.MyImage = Image; // GraduationUC.addimage.ImageSource = Image; } #endregion } }
// File Prologue // Name: Darren Moody // CS 1400 Section 005 // Project: Lab 22 // Date: 11/14/2013 // // // I declare that the following code was written by me or provided // by the instructor for this project. I understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. // --------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lab22 { class Program { const int SIZE = 100; static void Main(string[] args) { int arrayCount = 0; int[] numArray = new int[SIZE]; for (int i = 0; i < SIZE; i++) { Console.WriteLine("Please enter an integer (to stop inputting integers and calculate enter 0): "); string number = Console.ReadLine(); if (number == "0") { Console.WriteLine("\nCalculating...\n"); break; } numArray[i] = int.Parse(number); arrayCount = i + 1; } Console.WriteLine("\nThe product of the integers is: {0}", MultiplyEm(numArray, arrayCount)); Console.ReadLine(); } //The MultiplyEm method //Pupose: get the product of all the array numbers //Parameters: array of integers and array size //Return: The product of the multiplication static int MultiplyEm(int[] numbers, int size) { int multi = 1; for (int i = 0; i < size; i++) { multi *= numbers[i]; } return multi; } } }
using System; namespace GangOfFourDesignPatterns.Structural.Façade { internal class PlaneFlightPlan { string _flightPlan = ""; public void PlanFlight(string flightPlan) { _flightPlan = flightPlan; Console.WriteLine($"Flight planned: {String.Join(",", _flightPlan)}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IWorkFlow.DataBase; using System.Data; using IWorkFlow.Host; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("B_OA_Notice", "NewsId")] public class B_OA_Notice : QueryInfo { #region Model /// <summary> /// id /// </summary> /// [DataField("NewsId", "B_OA_Notice")] public string NewsId { set { _NewsId = value; } get { return _NewsId; } } private string _NewsId; /// <summary> /// 标题 /// </summary> /// [DataField("NewsTitle", "B_OA_Notice")] public string NewsTitle { set { _NewsTitle = value; } get { return _NewsTitle; } } private string _NewsTitle; /// <summary> /// 类型id /// </summary> /// [DataField("NewsTypeId", "B_OA_Notice")] public string NewsTypeId { set { _NewsTypeId = value; } get { return _NewsTypeId; } } private string _NewsTypeId; /// <summary> /// 部门id /// </summary> /// [DataField("NewsFromDept", "B_OA_Notice")] public string NewsFromDept { set { _NewsFromDept = value; } get { return _NewsFromDept; } } private string _NewsFromDept; /// <summary> /// 部门名称 /// </summary> /// [DataField("NewsFromDeptName", "B_OA_Notice")] public string NewsFromDeptName { set { _NewsFromDeptName = value; } get { return _NewsFromDeptName; } } private string _NewsFromDeptName; /// <summary> /// 内容 /// </summary> /// [DataField("NewsText", "B_OA_Notice")] public string NewsText { set { _NewsText = value; } get { return _NewsText; } } private string _NewsText; /// <summary> /// 新闻图片路径 /// </summary> /// [DataField("NewsImageUrl", "B_OA_Notice")] public string NewsImageUrl { set { _NewsImageUrl = value; } get { return _NewsImageUrl; } } private string _NewsImageUrl; /// <summary> /// 附件名称 /// </summary> /// [DataField("AttachmentName", "B_OA_Notice")] public string AttachmentName { set { _AttachmentName = value; } get { return _AttachmentName; } } private string _AttachmentName; /// <summary> /// 文件是否共享 /// </summary> /// [DataField("ShareAttachment", "B_OA_Notice")] public string ShareAttachment { set { _ShareAttachment = value; } get { return _ShareAttachment; } } private string _ShareAttachment; /// <summary> /// 创建人ID /// </summary> /// [DataField("CreaterId", "B_OA_Notice")] public string CreaterId { set { _CreaterId = value; } get { return _CreaterId; } } private string _CreaterId; /// <summary> /// 创建人姓名 /// </summary> /// [DataField("CreateMan", "B_OA_Notice")] public string CreateMan { set { _CreateMan = value; } get { return _CreateMan; } } private string _CreateMan; /// <summary> /// 创建时间 /// </summary> [DataField("CreateTime", "B_OA_Notice")] public string CreateTime { set { _CreateTime = value; } get { return _CreateTime; } } private string _CreateTime; /// <summary> /// 审核 /// </summary> /// [DataField("Chk", "B_OA_Notice")] public string Chk { set { _Chk = value; } get { return _Chk; } } private string _Chk = "0"; /// <summary> /// 审核人 /// </summary> /// [DataField("ChkM", "B_OA_Notice")] public string ChkM { set { _ChkM = value; } get { return _ChkM; } } private string _ChkM; /// <summary> /// 审核人 /// </summary> /// [DataField("ChkMId", "B_OA_Notice")] public string ChkMId { set { _ChkMId = value; } get { return _ChkMId; } } private string _ChkMId; /// <summary> /// 审核时间 /// </summary> [DataField("Chkdate", "B_OA_Notice")] public string Chkdate { set { _Chkdate = value; } get { return _Chkdate; } } private string _Chkdate; //附件路径 [DataField("AttachmentUrl", "B_OA_Notice")] public string AttachmentUrl { set { _AttachmentUrl = value; } get { return _AttachmentUrl; } } private string _AttachmentUrl; //外键相关表OA_FileType,文档中心的目录类型的区分,此字段用来存储ID [DataField("documentTypeId", "B_OA_Notice")] public string documentTypeId { set { _documentTypeId = value; } get { return _documentTypeId; } } private string _documentTypeId; //外键相关表OA_FileType,文档中心的目录类型的区分,此字段用来存储名称 [DataField("documentTypeName", "B_OA_Notice")] public string documentTypeName { set { _documentTypeName = value; } get { return _documentTypeName; } } private string _documentTypeName; //发布范围 0所有人员查看1指定人员查看 [DataField("publicRange", "B_OA_Notice")] public int publicRange { set { _publicRange = value; } get { return _publicRange; } } private int _publicRange; //指定人员查看用来存储 id [DataField("rangeCheckManId", "B_OA_Notice")] public string rangeCheckManId { set { _rangeCheckManId = value; } get { return _rangeCheckManId; } } private string _rangeCheckManId; //指定人员查看名字 [DataField("rangeCheckManName", "B_OA_Notice")] public string rangeCheckManName { set { _rangeCheckManName = value; } get { return _rangeCheckManName; } } private string _rangeCheckManName; //是否发布到外网 [DataField("isPublicToOutLine", "B_OA_Notice")] public bool isPublicToOutLine { set { _isPublicToOutLine = value; } get { return _isPublicToOutLine; } } private bool _isPublicToOutLine; //首页弹出通知 [DataField("isHomeDisplay", "B_OA_Notice")] public bool isHomeDisplay { set { _isHomeDisplay = value; } get { return _isHomeDisplay; } } private bool _isHomeDisplay; //会议通知 [DataField("isConferenceInform", "B_OA_Notice")] public bool isConferenceInform { set { _isConferenceInform = value; } get { return _isConferenceInform; } } private bool _isConferenceInform; //阅读记录 [DataField("isReadRecord", "B_OA_Notice")] public bool isReadRecord { set { _isReadRecord = value; } get { return _isReadRecord; } } private bool _isReadRecord; //可对本文发表意见 [DataField("isTextSuggetion", "B_OA_Notice")] public bool isTextSuggetion { set { _isTextSuggetion = value; } get { return _isTextSuggetion; } } private bool _isTextSuggetion; //邮件送达 [DataField("isSendEmail", "B_OA_Notice")] public bool isSendEmail { set { _isSendEmail = value; } get { return _isSendEmail; } } private bool _isSendEmail; //邮件送达人名 [DataField("sendEmailToManName", "B_OA_Notice")] public string sendEmailToManName { set { _sendEmailToManName = value; } get { return _sendEmailToManName; } } private string _sendEmailToManName; //邮件送达人ID [DataField("sendEmailToManId", "B_OA_Notice")] public string sendEmailToManId { set { _sendEmailToManId = value; } get { return _sendEmailToManId; } } private string _sendEmailToManId; //会议通知截止时间 [DataField("conferenceEndDate", "B_OA_Notice")] public string conferenceEndDate { set { _conferenceEndDate = value; } get { return _conferenceEndDate; } } private string _conferenceEndDate; //会议通知截止时间 [DataField("status", "B_OA_Notice")] public string status { set { _status = value; } get { return _status; } } private string _status; /// <summary> ///是否在门户中显示 /// </summary> [DataField("isSeeInDoor", "B_OA_Notice_Addvice")] public bool isSeeInDoor { get { return _isSeeInDoor; } set { _isSeeInDoor = value; } } private bool _isSeeInDoor; /// <summary> /// 用于收发文或者业务流归档时,通过caseid可查找到审核流程等相关信息 /// </summary> [DataField("caseid", "B_OA_Notice_Addvice")] public string caseid { get { return _caseid; } set { _caseid = value; } } private string _caseid; //是否紧急 [DataField("isUrgent", "B_OA_Notice")] public bool isUrgent { set { _isUrgent = value; } get { return _isUrgent; } } private bool _isUrgent; //审核通过 审核不通过 public string ChkResultName { set { _ChkResultName = value; } get { return _ChkResultName; } } private string _ChkResultName; //选择 public bool isSelected { set { _isSelected = value; } get { return _isSelected; } } private bool _isSelected; /// <summary> /// 查找文字 /// </summary> private string _sText; public string sText { set { _sText = value; } get { return _sText; } } /// <summary> /// check标题 /// </summary> private bool _sCheckTittle; public bool sCheckTittle { set { _sCheckTittle = value; } get { return _sCheckTittle; } } /// <summary> /// check正文 /// </summary> private bool _sCheckText; public bool sCheckText { set { _sCheckText = value; } get { return _sCheckText; } } /// <summary> /// 开始时间 /// </summary> private string _sDate; public string sDate { set { _sDate = value; } get { return _sDate; } } /// <summary> /// 结束时间 /// </summary> private string _sEndDate; public string sEndDate { set { _sEndDate = value; } get { return _sEndDate; } } /// <summary> /// 部门名称 /// </summary> public string DPName { set { _DPName = value; } get { return _DPName; } } private string _DPName; #endregion Model } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MAS_Końcowy.Model { public class ContractIngredient { public int ContractId { get; set; } public Contract Contract { get; set; } public int IngredientId { get; set; } public Ingredient Ingredient { get; set; } public ContractIngredient() { } public ContractIngredient(Contract contract, Ingredient ingredient) { Contract = contract; Ingredient = ingredient; } public void a() { using (var context = new MASContext()) { var contract = context.Contracts.Include(a => a.ContractIngredients).First(b => b.Id == 1); if (contract == null) { throw new Exception("nie działa"); } var i1 = new Ingredient("Chleb", 10.00m); var i2 = new Ingredient("Ser", 19.00m); var i3 = new Ingredient("Wołowina", 34.00m); var i4 = new Ingredient("Sałata", 5.00m); var ic1 = new ContractIngredient(); using (var tran = context.Database.BeginTransaction()) { try { context.Update(contract); context.SaveChanges(); context.Ingredients.Add(i1); context.Ingredients.Add(i2); context.Ingredients.Add(i3); context.Ingredients.Add(i4); context.SaveChanges(); context.ContractIngredients.Add(new ContractIngredient(contract, i1)); context.ContractIngredients.Add(new ContractIngredient(contract, i2)); context.ContractIngredients.Add(new ContractIngredient(contract, i3)); context.ContractIngredients.Add(new ContractIngredient(contract, i4)); context.SaveChanges(); tran.Commit(); } catch (Exception) { tran.Rollback(); } } context.SaveChanges(); } } } }
 using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class Vitals { [Space(10)] [Header("Health")] public int healthCurrent; public int healthMax; [Space(10)] [Header("Stunning")] public float stunCurrent; public float stunMax; public float stunThreshold; [Space(10)] [Header("Booleans")] public bool isDead = false; public bool isConscious = false; }