public void TestArray_Scenario_Result() { var strings = new[] { "Acme", "WB", "Universal" }; Console.WriteLine(strings.Length); Console.WriteLine(strings.Rank); Console.WriteLine(strings.GetLength(0)); Console.WriteLine(strings.GetUpperBound(0)); Console.WriteLine(strings.Count()); }
public void PlayExecutesSamePlayerOrderInEachRound() { var players = new[] { "Horse", "Car", "Hat" }; var mockTurn = new Mock<ITurn>(); var game = new Game(players, mockTurn.Object, new GuidShuffler<String>()); var controller = new GameController(game); var turnsTaken = new List<String>(); mockTurn.Setup(m => m.Take(It.IsAny<String>())).Callback((String p) => turnsTaken.Add(p)); controller.Play(); var lastRoundTurns = Enumerable.Empty<String>(); while (turnsTaken.Any()) { var roundTurns = turnsTaken.Take(players.Count()); if (lastRoundTurns.Any()) { for (var i = 0; i < lastRoundTurns.Count(); i++) Assert.AreEqual(roundTurns.ElementAt(i), lastRoundTurns.ElementAt(i)); } lastRoundTurns = roundTurns; turnsTaken.RemoveRange(0, players.Count()); } }
public void TestEnumerableIntConvert() { string input = "10,20,30"; IEnumerable<int> expected = new[] { 10, 20, 30 }; IEnumerable<int> result = PageFilterTypeConverter.Convert(input, typeof(IEnumerable<int>)) as IEnumerable<int>; Assert.IsNotNull(result); Assert.AreEqual(expected.Count(), result.Count()); for (int i = 0; i < expected.Count(); i++) { Assert.AreEqual(expected.ElementAt(i), result.ElementAt(i)); } }
public void TestEnumerableStringsConvert() { string input = "Mike,Jessy,Louis"; IEnumerable<string> expected = new[] { "Mike", "Jessy", "Louis" }; IEnumerable<string> result = PageFilterTypeConverter.Convert(input, typeof(IEnumerable<string>)) as IEnumerable<string>; Assert.IsNotNull(result); Assert.AreEqual(expected.Count(), result.Count()); for (int i = 0; i < expected.Count(); i++) { Assert.AreEqual(expected.ElementAt(i), result.ElementAt(i)); } }
public void DifferenceTest() { var a = new[] { 1, 2, 3, 4, 5, 6, 7 }; var b = new[] { 4, 5, 6, 7, 8, 9, 10 }; IEnumerable<int> expected = new[] { 1, 2, 3, 8, 9, 10 }; var result = a.Difference(b); Assert.AreEqual(expected.Count(), result.Count()); for (int x = 0; x < expected.Count(); ++x) Assert.AreEqual(expected.ElementAt(x), result.ElementAt(x)); }
public void TestEnumerableDateConvert() { string input = "2010-09-08,2009-08-07,2008-07-06"; IEnumerable<DateTime> expected = new[] { new DateTime(2010, 09, 08), new DateTime(2009, 08, 07), new DateTime(2008, 07, 06) }; IEnumerable<DateTime> result = PageFilterTypeConverter.Convert(input, typeof(IEnumerable<DateTime>)) as IEnumerable<DateTime>; Assert.IsNotNull(result); Assert.AreEqual(expected.Count(), result.Count()); for (int i = 0; i < expected.Count(); i++) { Assert.AreEqual(expected.ElementAt(i), result.ElementAt(i)); } }
public void Then_only_the_valid_ones_are_present_in_the_dates_returned() { //Given: string[] fileNames = new[] { "TeamCity_Backup_20131121_165032.zip", "TeamCity_Backup_20110323_103232.exe", "TeamCity_Backup_20110323_103232.zip", "TeamCity_20091230_065900.zip", "TeamCity_Backup_20091230_065900.zip", "TeamCity_Backup.zip", "" }; DateTime[] expectedBackupDates = new[] { new DateTime(2013, 11, 21, 16, 50, 32), new DateTime(2011, 03, 23, 10, 32, 32), new DateTime(2009, 12, 30, 06, 59, 00) }; TeamCityBackupFileDatesQuery teamCityBackupFileDatesQuery = GetSUT(); //When: var backupDateTimes = teamCityBackupFileDatesQuery.GetDates(fileNames).ToList(); //Then: foreach (var expectedBackupDate in expectedBackupDates) Assert.That(backupDateTimes.Any(b => b.BackupDateTime == expectedBackupDate)); Assert.That(backupDateTimes.Count(), Is.EqualTo(expectedBackupDates.Count())); }
public DocumentProcessResult Apply(ICollection<CodeSnippet> snippets) { var result = new DocumentProcessResult(); var inputFiles = new[] { "*.md", "*.mdown", "*.markdown" }.SelectMany( extension => Directory.GetFiles(docsFolder, extension, SearchOption.AllDirectories)) .ToArray(); result.Count = inputFiles.Count(); foreach (var inputFile in inputFiles) { var fileResult = Apply(snippets, inputFile); if (fileResult.RequiredSnippets.Any()) { // give up if we can't continue result.Include(fileResult.RequiredSnippets); return result; } result.Include(fileResult.Snippets); File.WriteAllText(inputFile, fileResult.Text); } return result; }
public void ReadLinesTest() { var source = new[] { "a", "b", "c" }; AssertEx.Throws<ArgumentNullException>(() => TextReaderExtensions.ReadLines(null).ToArray()); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { foreach (var s in source) { writer.WriteLine(s); } writer.Flush(); stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream)) { var array = reader.ReadLines().ToArray(); array.Count().Is(source.Count()); Enumerable.Range(0, array.Count()).All(i => array[i] == source[i]).IsTrue(); } } }
static bool IsValidImage(Stream imageStream) { if (imageStream.Length > 0) { byte[] header = new byte[4]; // Change size if needed. string[] imageHeaders = new[]{ "\xFF\xD8", // JPEG "BM", // BMP "GIF", // GIF Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71})}; // PNG imageStream.Read(header, 0, header.Length); bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0; if (isImageHeader == true) { try { System.Drawing.Image.FromStream(imageStream).Dispose(); imageStream.Close(); return true; } catch { } } } imageStream.Close(); return false; }
public void AddObject() { // Arrange this._dbFixture.TestInitialize(); const string name = "John Doe"; const string email = "*****@*****.**"; const bool isDisabled = false; var links = new[] { new Link() { Title = "SomeTitle", Url = @"http://somesite.com/" } }; User savedData = null; var cmd = new CreateUserCommand(name, email, isDisabled, links); // Act this._unitOfWorkFactory.ExecuteSingleCommand(cmd); using (var unitOfWork = this._unitOfWorkFactory.Create()) savedData = unitOfWork.ResolveQuery<IGetUserByIdQuery>().Execute(cmd.Id, includeLinks: true); // Assert Assert.NotNull(savedData); Assert.Equal(cmd.Id, savedData.Id); Assert.Equal(name, savedData.Name); Assert.Equal(email, savedData.Email); Assert.Equal(isDisabled, savedData.IsDisabled); Assert.NotNull(savedData.Links); Assert.Equal(links.Count(), savedData.Links.Count()); var link = savedData.Links.First(); Assert.Equal(savedData.Id, link.UserProfileId); Assert.Equal(links[0].Title, link.Title); Assert.Equal(links[0].Url, link.Url); }
public ActionAlternatesFactory(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; _actionAlternates = new Lazy<List<string>>(() => { var httpContext = _httpContextAccessor.Current(); if (httpContext == null) { return null; } var request = _httpContextAccessor.Current().Request; var actionSegments = new[] { request.RequestContext.RouteData.GetRequiredString("area").Replace("-", "__").Replace(".", "_"), request.RequestContext.RouteData.GetRequiredString("controller").Replace("-", "__").Replace(".", "_"), request.RequestContext.RouteData.GetRequiredString("action").Replace("-", "__").Replace(".", "_") }; return Enumerable.Range(1, actionSegments.Count()).Select(range => String.Join("__", actionSegments.Take(range))).ToList(); }); }
public void Test() { var pf = new PeakFittingViewModel { Input = TestSpectrum.Get(), SmoothingCutoffFrequency = 10, DataProcessRegion = new Region(2, 1200), BackgroundParameter0 = 100, BackgroundParameter1 = 0.5, Calibration = new EnergyCalibrationConstants { ChannelToEnergy = new Linear(20.01845971, -16.40027588), EnergyToResolution = new EnergyToPeakResolutionFunc(0.000083445639973, 8463.41525339) } }; var serializer = new XmlSerializer(typeof(Shell[])); var shells = (Shell[]) serializer.Deserialize( File.OpenRead(@"C:\Repository\Xbrt\XbrtTests\Spectral\shells.xml")); var expectedResults = new[] { new {Name = "Cu-K", Centroid = 8048.0, Intensity = 576.13}, new {Name = "Zn-K", Centroid = 8639.0, Intensity = 382.69}, new {Name = "Zr-K", Centroid = 15770.0, Intensity = 239.67}, //new {Number = 173, Name = "Ta-L", Centroid = 8146.10, Intensity = 0.00}, new {Name = "W-L", Centroid = 9671.0, Intensity = 0.00}, //new{Number = 180, Name = "Hg-L", Centroid = 9988.80, Intensity = 0.00}, new {Name = "Pb-L", Centroid = 12618.0, Intensity = 28.06} }; var lics = (from ss in shells.Where(s => expectedResults.Any(e => e.Name == s.Name)) let lis = (from lg in ss.LineGroups from l in lg.Lines select new LineInfo(lg.AtomicNumber, lg, l)) select new LineInfoCollection(ss.AtomicNumber, ss.Name, lis)).ToArray(); pf.LineInfo.AddRange(lics); pf.DoPeakFitting(1.0); var aSmoothed = pf.Smoothed; var eSmoothed = TestSpectrum.GetSmoothed(); Assert.IsNotNull(aSmoothed); foreach (var i in Enumerable.Range(0, 4096)) Assert.AreEqual(eSmoothed[i], aSmoothed[i], 0.001); var cases = (from n in pf.FittingResult from e in expectedResults where n.Line.Name == e.Name select new {Actual = n, Expected = e}).ToArray(); Assert.AreEqual(expectedResults.Count(), cases.Count()); foreach (var c in cases) { var a = c.Actual; var e = c.Expected; Assert.AreEqual(e.Name, a.Line.Name); Assert.AreEqual(e.Centroid, a.Line.Energy_eV, 0.01); Assert.AreEqual(e.Intensity, a.Intensity, 0.01); Console.WriteLine("{0}\t{1:F2}eV\t{2:F2}counts", a.Line.Name, a.Line.Energy_eV, a.Intensity); } }
public override object GetIndex(Func<object> proceed, object self, System.Collections.Generic.IEnumerable<object> keys) { if (keys.Count() == 1) { var key = System.Convert.ToString(keys.Single()); return GetMember(proceed, null, key); } return proceed(); }
protected Guid Save() { var oid = "ObjectId".Query().GlobalId(); var img = new[] { p0, p1, p2, p3 }.ToList(); var photo = img.Count(o => !o.Src.Contains("/Content/Images/Transparent.png")) == 0 ? new string[] { } : img.Where(o => !o.Src.Contains("/Content/Images/Transparent.png")).Select(o => o.Src).ToArray(); DataContext.DepotObjectEditX(oid, photo.Length > 0 ? photo[0] : "", photo.Length > 1 ? photo[1] : "", photo.Length > 2 ? photo[2] : "", photo.Length > 3 ? photo[3] : ""); return oid; }
public void PeoplesNamesToUppercase() { var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon" , "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"}; var people = names.Select(x => new People { Name = x }); // Create a new list of people but with the names to upper case var peopleUpperCase = people.Select(x => x.Name = x.Name.ToUpper()); Assert.AreEqual(names.Count(), peopleUpperCase.Count()); }
public void RealWorldDataTableTest() { // This is what a dynamic table would output, a list of rowsetups. var rowSetups = new List<RowSetup>(); rowSetups.Add( new RowSetup { IsHeader = true, CsvLine = new List<string> { "Name", "Company", "Location", "Url", "Phone" } } ); var names = new[] { "Sofeee", "Cathie", "Ann", "Jan", "Patty", "Cora" }; var surNames = new[] { "Norjaim", "Carbelt", "Wilson", "Middleberger", "Hewlett", "Taylor", "Danzen" }; var companies = new[] { "Synergy", "Enterprises", "Dancing", "Buzz", "Local", "of Rochester" }; var streets = new[] { "Broad Rd", "W Elm St", "Main", "James Ave", "Water Blvd", "West Way" }; for( var i = 0; i < 72; i++ ) { rowSetups.Add( new RowSetup { CsvLine = new List<string> { // Some random-looking values names[ i % names.Count() ] + " " + surNames[ i % surNames.Count() ], companies[ ( i + ( i / 2 ) ) % companies.Count() ] + " " + companies[ i % companies.Count() ], i + " " + streets[ i % streets.Count() ], "http://www.google.com/search?q=" + i, i.ToString( "D3" ) + "-867-5309" }, ClickScript = ClickScript.CreateRedirectScript( new ExternalResourceInfo( "http://google.com" ) ), CssClass = "gibberish_string_for_testing", IsHeader = false, RankId = i, ToolTip = "This is row " + i, UniqueIdentifier = "row" + i } ); } runTest( writer => { foreach( var rowSetup in rowSetups ) { if( rowSetup.IsHeader ) writer.DefaultWorksheet.AddHeaderToWorksheet( rowSetup.CsvLine.ToArray() ); else writer.DefaultWorksheet.AddRowToWorksheet( rowSetup.CsvLine.ToArray() ); } return "data_table"; } ); }
public void XML(System.Object[] CustomObject, String filename) { try { if (CustomObject != null && CustomObject.Count() > 0) { if (CustomObject[0].GetType() == typeof(PSObject)) { StreamWriter outfile = File.CreateText(filename); XmlTextWriter xmlwtr = new XmlTextWriter(outfile); xmlwtr.Formatting = Formatting.Indented; xmlwtr.WriteStartDocument(); xmlwtr.WriteStartElement("Collection"); foreach (PSObject pobj in CustomObject) { xmlwtr.WriteStartElement("PSObject"); foreach (PSPropertyInfo prop in pobj.Properties) { if (prop != null) { xmlwtr.WriteStartElement("PSNoteProperty"); xmlwtr.WriteAttributeString("Name", prop.Name); try { xmlwtr.WriteAttributeString("Value", (prop.Value ?? "").ToString()); } catch (GetValueException) { xmlwtr.WriteAttributeString("Value", ""); } xmlwtr.WriteEndElement(); } } xmlwtr.WriteEndElement(); } xmlwtr.WriteEndElement(); xmlwtr.WriteEndDocument(); xmlwtr.Flush(); xmlwtr.Close(); xmlwtr = null; } } } catch (Exception e) { if (e.InnerException != null) { MessageBox.Show("Unable to export object." + Environment.NewLine + e.Message + Environment.NewLine + e.InnerException.Message); } else { MessageBox.Show("Unable to export object." + Environment.NewLine + e.Message); } } }
public void Ctor_SetsTheDefaultOptions_ShouldGenerateUniqueClientId() { var options1 = new MongoStorageOptions(); var options2 = new MongoStorageOptions(); var options3 = new MongoStorageOptions(); IEnumerable<string> result = new[] { options1.ClientId, options2.ClientId, options3.ClientId }.Distinct(); Assert.Equal(3, result.Count()); }
public virtual ActionResult News() { var views = new[]{"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"}; var randomIndex = new Random().Next(0, views.Count()); Trace.Write("Randomly selected story number " + randomIndex); return PartialView(views[randomIndex]); }
public void Test_That_StoreJson_Can_Store_Arrays_As_Json() { var key = "Test_That_GetJson_Can_Retrieve_Arrays_As_Json"; var list = new []{ 1, 2, 3, 4 }; var result = Client.StoreJson(StoreMode.Set, key, list); Assert.IsTrue(result); var output = Client.GetJson<int[]>(key); Assert.AreEqual(list.Count(), output.Count()); }
public void TestMultipleItemsSource_ShouldInvokeActionMultipleTimes() { IEnumerable<int> source = new[] { 1, 10, 100, 1000 }; var actionInvocationsCount = 0; Action<int> action = item => { actionInvocationsCount++; }; source.ForEach(action); Assert.AreEqual(source.Count(), actionInvocationsCount, "Action should be invoked N times for an enumerable with N items."); }
public void LoadNames() { var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon" , "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"}; var people = from x in names select new People { Name = x, }; Assert.AreEqual(names.Count(), people.Count()); }
public void WithNotEmpty() { var source = new[] { "a1", "a2,", "a3" }; var result = source.With((string s) => s + "b").ToArray(); Assert.AreEqual(source.Count(), result.Count()); Assert.AreEqual(source[0] + "b", result[0]); Assert.AreEqual(source[1] + "b", result[1]); Assert.AreEqual(source[2] + "b", result[2]); }
public void PeoplesNameLength() { var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon" , "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"}; var people = names.Select(x => new People { Name = x }); /*create a list that holds the lengths of each people object and then turn it into an array */ var peopleNameLength = people.Select(x => x.Name.Length).ToArray(); Assert.AreEqual(names.Count(), peopleNameLength.Count()); }
public void Benchmark_Finding_First_Type_In_Assemblies() { var timer = new Stopwatch(); var assemblies = new[] { //both contain the type this.GetType().Assembly, typeof (MandatoryPropertyEditor).Assembly, //these dont contain the type typeof(NSubstitute.Substitute).Assembly, typeof(Remotion.Linq.DefaultQueryProvider).Assembly, typeof(NHibernate.IdentityEqualityComparer).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, typeof(System.Data.SQLite.CollationSequence).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(Umbraco.Hive.LazyRelation<>).Assembly, typeof(Umbraco.Framework.DependencyManagement.AbstractContainerBuilder).Assembly, typeof(Umbraco.Framework.Persistence.DefaultAttributeTypeRegistry).Assembly, typeof(Umbraco.Framework.Security.FixedPermissionTypes).Assembly }; //we'll use PropertyEditors for this tests since there are some int he text Extensions project var finder = new TypeFinder(); timer.Start(); var found1 = finder.FindClassesOfType<PropertyEditor, AssemblyContainsPluginsAttribute>(assemblies); timer.Stop(); Console.WriteLine("Total time to find propery editors (" + found1.Count() + ") in " + assemblies.Count() + " assemblies using AssemblyContainsPluginsAttribute: " + timer.ElapsedMilliseconds); timer.Start(); var found2 = finder.FindClassesOfType<PropertyEditor>(assemblies); timer.Stop(); Console.WriteLine("Total time to find propery editors (" + found2.Count() + ") in " + assemblies.Count() + " assemblies without AssemblyContainsPluginsAttribute: " + timer.ElapsedMilliseconds); }
public void WhenCallingForEachIterateEachItemInTheGivenCollection() { IEnumerable<int> testCollection = new[]{1, 1, 1}; int itemCount = 0; testCollection.ForEach(item => itemCount++); Assert.That(itemCount, Is.EqualTo(testCollection.Count())); }
public void RulePrinter_InstantiatesProperly() { const long start = 1; const long end = 100; var rules = new[] {new Rule(i => i%3 == 0, "fizz")}; var ruleprinter = new RulePrinter.Implementation.RulePrinters.RulePrinter(start, end, rules); Assert.AreEqual(start, ruleprinter.Start); Assert.AreEqual(end, ruleprinter.End); Assert.AreEqual(rules.Count(), ruleprinter.Rules.Count()); Assert.IsNotNull(ruleprinter.DefaultResult); }
public void PeopleOrderSmallName() { var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon" , "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"}; var people = names.Select(x => new People { Name = x }); /*create a new list of people witht he name shortened to just the first 3 letters * and ordered by name */ var peopleOrderedShortend = people.Select(x => new People { Name = x.Name.Substring(0, 3) }).OrderBy(x => x.Name); Assert.AreEqual(names.Count(), peopleOrderedShortend.Count()); }
public void PeoplesNameLength() { var names = new[] {"Bessie", "Vashti", "Frederica", "Nisha", "Kendall", "Magdalena", "Brendon" , "Eve", "Manda", "Elvera", "Miquel", "Tyra", "Lucie", "Marvella", "Tracee", "Ramiro", "Irene", "Davina", "Jeromy" , "Siu"}; var people = from x in names select new People { Name = x, }; var peopleNameLength = people.Select(x => x.Name.Length).ToArray(); Assert.AreEqual(names.Count(), peopleNameLength.Count()); }