コード例 #1
0
        public BikeTest()
        {
            var builder = new DbContextOptionsBuilder <CyclepathDbContext>();

            builder.UseInMemoryDatabase();
            var options = builder.Options;

            dataBase       = new CyclepathDbContext(options);
            bikeRepository = new BikeRepository(dataBase);
        }
コード例 #2
0
        private static Bike InitBike(string make, string model)
        {
            var repository = new BikeRepository();
            var bike       = new Bike {
                Make = make, Model = model
            };

            repository.Add(bike);
            return(bike);
        }
コード例 #3
0
        public void GetRentpointTest()
        {
            var bikes = new List <Bike>
            {
                new Bike
                {
                    Id          = 1,
                    Description = "Montain",
                    Price       = 20,
                    Disponible  = true,
                    Image       = "123456",
                    RentPointId = 1
                },
                new Bike
                {
                    Id          = 2,
                    Description = "Street",
                    Price       = 25,
                    Disponible  = true,
                    Image       = "1234",
                    RentPointId = 1
                },
                new Bike
                {
                    Id          = 2,
                    Description = "Garden",
                    Price       = 30,
                    Disponible  = true,
                    Image       = "25649",
                    RentPointId = 2
                },
            }.AsQueryable();
            var mockSet = new Mock <DbSet <Bike> >();

            mockSet.As <IQueryable <Bike> >().SetupGet(m => m.Provider).Returns(bikes.Provider);
            mockSet.As <IQueryable <Bike> >().SetupGet(m => m.Expression).Returns(bikes.Expression);
            mockSet.As <IQueryable <Bike> >().SetupGet(m => m.ElementType).Returns(bikes.ElementType);
            mockSet.As <IQueryable <Bike> >().Setup(m => m.GetEnumerator()).Returns(bikes.GetEnumerator());
            var mockContext = new Mock <CyclepathDbContext>();

            mockContext.Setup(c => c.Bikes).Returns(mockSet.Object);

            var service = new BikeRepository(mockContext.Object);

            var rentPoints = service.GetRentPointBikes(1).ToList();

            Assert.AreEqual(2, rentPoints.Count);
            Assert.AreEqual("Montain", rentPoints[0].Description);
            Assert.AreEqual("Street", rentPoints[1].Description);
        }
コード例 #4
0
        public void GetOneBikeTest()
        {
            var bikes = new List <Bike>
            {
                new Bike
                {
                    Id          = 1,
                    Description = "Montain",
                    Price       = 20,
                    Disponible  = true,
                    Image       = "123456",
                    RentPointId = 1
                },
                new Bike
                {
                    Id          = 2,
                    Description = "Street",
                    Price       = 25,
                    Disponible  = true,
                    Image       = "1234",
                    RentPointId = 1
                },
            }.AsQueryable();
            var mockSet = new Mock <DbSet <Bike> >();

            mockSet.As <IQueryable <Bike> >().SetupGet(m => m.Provider).Returns(bikes.Provider);
            mockSet.As <IQueryable <Bike> >().SetupGet(m => m.Expression).Returns(bikes.Expression);
            mockSet.As <IQueryable <Bike> >().SetupGet(m => m.ElementType).Returns(bikes.ElementType);
            mockSet.As <IQueryable <Bike> >().Setup(m => m.GetEnumerator()).Returns(bikes.GetEnumerator());
            var mockContext = new Mock <CyclepathDbContext>();

            mockContext.Setup(c => c.Bikes).Returns(mockSet.Object);

            var  service  = new BikeRepository(mockContext.Object);
            Bike bike     = service.GetOne(2);
            var  expected = bikes.ToList()[1];

            Assert.AreEqual(expected.Description, bike.Description);
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: nickdmug/csharp-1
        public static void OtherInterestingFeatures()
        {
            // OPTIONAL PARAMETERS
            MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
            MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones

            // BY REF AND OUT PARAMETERS
            int maxCount = 0, count; // ref params must have value

            MethodSignatures(ref maxCount, out count);

            // EXTENSION METHODS
            int i = 3;

            i.Print(); // Defined below

            // NULLABLE TYPES - great for database interaction / return values
            // any value type (i.e. not a class) can be made nullable by suffixing a ?
            // <type>? <var name> = <value>
            int?nullable = null;  // short hand for Nullable<int>

            Console.WriteLine("Nullable variable: " + nullable);
            bool hasValue = nullable.HasValue; // true if not null

            // ?? is syntactic sugar for specifying default value (coalesce)
            // in case variable is null
            int notNullable = nullable ?? 0; // 0

            // ?. is an operator for null-propagation - a shorthand way of checking for null
            nullable?.Print(); // Use the Print() extension method if nullable isn't null

            // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is:
            var magic = "magic is a string, at compile time, so you still get type safety";

            Console.WriteLine(magic);
            // magic = 9; will not work as magic is a string, not an int

            // GENERICS
            //
            var phonebook = new Dictionary <string, string>()
            {
                { "Sarah", "212 555 5555" } // Add some entries to the phone book
            };

            // Calling SETDEFAULT defined as a generic above
            Console.WriteLine(SetDefault <string, string>(phonebook, "Shaun", "No Phone")); // No Phone
            // nb, you don't need to specify the TKey and TValue since they can be
            // derived implicitly
            Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555

            // LAMBDA EXPRESSIONS - allow you to write code in line
            Func <int, int> square = (x) => x * x; // Last T item is the return value

            Console.WriteLine(square(3));          // 9

            // ERROR HANDLING - coping with an uncertain world
            try
            {
                var funBike = PennyFarthing.CreateWithGears(6);

                // will no longer execute because CreateWithGears throws an exception
                string some = "";
                if (true)
                {
                    some = null;
                }
                some.ToLower(); // throws a NullReferenceException
            }
            catch (NotSupportedException)
            {
                Console.WriteLine("Not so much fun now!");
            }
            catch (Exception ex) // catch all other exceptions
            {
                throw new ApplicationException("It hit the fan", ex);
                // throw; // A rethrow that preserves the callstack
            }
            // catch { } // catch-all without capturing the Exception
            finally
            {
                // executes after try or catch
            }

            // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
            // Most of objects that access unmanaged resources (file handle, device contexts, etc.)
            // implement the IDisposable interface. The using statement takes care of
            // cleaning those IDisposable objects for you.
            using (StreamWriter writer = new StreamWriter("log.txt"))
            {
                writer.WriteLine("Nothing suspicious here");
                // At the end of scope, resources will be released.
                // Even if an exception is thrown.
            }

            // PARALLEL FRAMEWORK
            // https://devblogs.microsoft.com/csharpfaq/parallel-programming-in-net-framework-4-getting-started/

            var words = new List <string> {
                "dog", "cat", "horse", "pony"
            };

            Parallel.ForEach(words,
                             new ParallelOptions()
            {
                MaxDegreeOfParallelism = 4
            },
                             word =>
            {
                Console.WriteLine(word);
            }
                             );

            // Running this will produce different outputs
            // since each thread finishes at different times.
            // Some example outputs are:
            // cat dog horse pony
            // dog horse pony cat

            // DYNAMIC OBJECTS (great for working with other languages)
            dynamic student = new ExpandoObject();

            student.FirstName = "First Name"; // No need to define class first!

            // You can even add methods (returns a string, and takes in a string)
            student.Introduce = new Func <string, string>(
                (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
            Console.WriteLine(student.Introduce("Beth"));

            // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of
            // very useful Map / Filter / Reduce style methods
            var bikes = new List <Bicycle>();

            bikes.Sort();                                           // Sorts the array
            bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels
            var result = bikes
                         .Where(b => b.Wheels > 3)                  // Filters - chainable (returns IQueryable of previous type)
                         .Where(b => b.IsBroken && b.HasTassles)
                         .Select(b => b.ToString());                // Map - we only this selects, so result is a IQueryable<string>

            var sum = bikes.Sum(b => b.Wheels);                     // Reduce - sums all the wheels in the collection

            // Create a list of IMPLICIT objects based on some parameters of the bike
            var bikeSummaries = bikes.Select(b => new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });

            // Hard to show here, but you get type ahead completion since the compiler can implicitly work
            // out the types above!
            foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
            {
                Console.WriteLine(bikeSummary.Name);
            }

            // ASPARALLEL
            // And this is where things get wicked - combine linq and parallel operations
            var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
            // this will happen in parallel! Threads will automagically be spun up and the
            // results divvied amongst them! Amazing for large datasets when you have lots of
            // cores

            // LINQ - maps a store to IQueryable<T> objects, with delayed execution
            // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document
            var db = new BikeRepository();

            // execution is delayed, which is great when querying a database
            var filter = db.Bikes.Where(b => b.HasTassles); // no query run

            if (42 > 6)                                     // You can keep adding filters, even conditionally - great for "advanced search" functionality
            {
                filter = filter.Where(b => b.IsBroken);     // no query run
            }
            var query = filter
                        .OrderBy(b => b.Wheels)
                        .ThenBy(b => b.Name)
                        .Select(b => b.Name); // still no query run

            // Now the query runs, but opens a reader, so only populates as you iterate through
            foreach (string bike in query)
            {
                Console.WriteLine(result);
            }
        }
コード例 #6
0
 public ValuesController(BikeRepository bikeRepository)
 {
     _bikeRepository = bikeRepository;
 }
コード例 #7
0
ファイル: BikeController.cs プロジェクト: bob7007/FirstWebApp
 public BikeController()
 {
     bikeRepo   = new BikeRepository();
     branchRepo = new BranchRepository();
 }
コード例 #8
0
ファイル: BikesController.cs プロジェクト: dSiles98/CyclePath
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="context"></param>
 public BikesController(CyclepathDbContext context)
 {
     bikesRepository = new BikeRepository(context);
 }