Exemple #1
0
        static void Main(string[] args)
        {
            #region Data
            Cat            garf     = new Cat("Garfield", 8, 3, true);
            Cat            tom      = new Cat("Tom", 11, 1, false);
            Dog            toby     = new Dog("Toby", 5, true, "PorkRibs");
            Dog            spike    = new Dog("Spike", 11, false, "Flesh");
            Fish           goldie   = new Fish("Goldie", 5, "golden", "XXL");
            Fish           carp     = new Fish("Carp", 3, "black", "Mediym");
            PetStore <Pet> milenici = new PetStore <Pet>();
            milenici.Add(garf); milenici.Add(tom); milenici.Add(toby); milenici.Add(spike); milenici.Add(goldie); milenici.Add(carp);
            PetStore <Fish> fishes = new PetStore <Fish>();
            fishes.Add(goldie); fishes.Add(carp);
            PetStore <Dog> doggies = new PetStore <Dog>();
            doggies.Add(toby); doggies.Add(spike);
            PetStore <Cat> catz = new PetStore <Cat>();
            catz.Add(garf); catz.Add(tom);
            #endregion



            Console.WriteLine(milenici.PrintPets());
            Console.WriteLine("\n \n");
            Console.WriteLine(fishes.PrintPets());
            Console.WriteLine("\n");
            Console.WriteLine(doggies.PrintPets());
            Console.WriteLine("\n");
            Console.WriteLine(catz.PrintPets());
            Console.WriteLine("\n");
            milenici.BuyPet("Carp");
            catz.BuyPet("Tom");

            Console.WriteLine(milenici.PrintPets());
        }
Exemple #2
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Price,Name,Description,Nutritional_Information,Weight,Type_of_animal_food_is_for,Animal,AName,ADescription")] PetStore petStore)
        {
            if (id != petStore.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(petStore);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PetStoreExists(petStore.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(petStore));
        }
Exemple #3
0
        static void Main(string[] args)
        {
            PetStore <Dog>  dogsStore = new PetStore <Dog>();
            PetStore <Cat>  catsStore = new PetStore <Cat>();
            PetStore <Fish> fishStore = new PetStore <Fish>();


            dogsStore.Insert(new Dog("Bobs", 3, true, "meat"));
            dogsStore.Insert(new Dog("Jacky", 5, false, "bread"));

            catsStore.Insert(new Cat("Jenny", 2, false, 6));
            catsStore.Insert(new Cat("Jane", 4, true, 3));

            fishStore.Insert(new Fish("Nemo", 1, "blue", 4));
            fishStore.Insert(new Fish("Mui", 2, "green", 7));


            dogsStore.BuyPet("Bobs");
            catsStore.BuyPet("Mia");

            Console.WriteLine("--------------------------------------------");


            Console.WriteLine("These are the available pets in the stores:");
            dogsStore.PrintPets();
            catsStore.PrintPets();
            fishStore.PrintPets();
        }
Exemple #4
0
        static void Main(string[] args)
        {
            PetStore <Pet> .Pets.Add(new Dog("Stinky", "Bulldog", 3, "Steak"));

            PetStore <Pet> .Pets.Add(new Dog("Rex", "German Shepherd", 5, "Dog meal"));

            PetStore <Pet> .Pets.Add(new Cat("Bella", "Persian Cat", 1, true, 8));

            PetStore <Pet> .Pets.Add(new Cat("Kitty", "Ragdoll", 2, false, 7));

            PetStore <Pet> .Pets.Add(new Fish("Gray Triggerfish", "Goldfish", 1, "gold", 1.5));

            PetStore <Pet> .Pets.Add(new Fish("King Mackerel", "Guppy", 1, "grey", 1.2));

            PetStore <Pet> .PrintsPets();

            Console.WriteLine("============================");

            PetStore <Pet> .BuyPet(PetStore <Pet> .Pets[1]);

            PetStore <Pet> .BuyPet(PetStore <Pet> .Pets[2]);

            PetStore <Pet> .PrintsPets();


            Console.ReadLine();
        }
Exemple #5
0
        public async Task <IActionResult> Create([Bind("Id,Price,Name,Description,Nutritional_Information,Weight,Type_of_animal_food_is_for,Animal,AName,ADescription")] PetStore petStore)
        {
            if (ModelState.IsValid)
            {
                _context.Add(petStore);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(petStore));
        }
        public object Execute(object system)
        {
            Account  account = null;
            PetStore ps      = (PetStore)system;

            if (!ps.checkCreateAccount(this.login, this.password))
            {
                throw new ArgumentException("Invalid account parameters.");
            }
            account = new Account(this.login, this.password);
            ps.addAccount(account);
            return(account);
        }
        static void Main(string[] args)
        {
            PetStore <Dog> Dog1 = new PetStore <Dog>();
            PetStore <Dog> Dog2 = new PetStore <Dog>();

            PetStore <Cat> Cat1 = new PetStore <Cat>();
            PetStore <Cat> Cat2 = new PetStore <Cat>();

            PetStore <Fish> Fish1 = new PetStore <Fish>();
            PetStore <Fish> Fish2 = new PetStore <Fish>();

            Dog1.Insert(new Dog()
            {
                Name = "Dog1", Age = 5, FavouriteFood = "bacon", GoodBoi = true, Type = "Beagle"
            });
            Dog2.Insert(new Dog()
            {
                Name = "Dog2", Age = 6, FavouriteFood = "meat", GoodBoi = true, Type = "Labrador"
            });

            Cat1.Insert(new Cat()
            {
                Name = "Cat1", Age = 2, IsLazy = true, Type = "Some cat type", LivesLeft = 9
            });
            Cat2.Insert(new Cat()
            {
                Name = "Cat2", Age = 3, IsLazy = true, Type = "Some cat type3", LivesLeft = 8
            });

            Fish1.Insert(new Fish()
            {
                Name = "Fish1", Age = 1, Type = "Goldfish", Color = "gold", Size = 2
            });
            Fish2.Insert(new Fish()
            {
                Name = "Fish2", Age = 2, Type = "Goldfish2", Color = "gold", Size = 3
            });

            Dog1.PrintPets();
            Dog2.PrintPets();

            Cat1.PrintPets();
            Cat2.PrintPets();

            Fish1.PrintPets();
            Fish2.PrintPets();

            Dog1.BuyPet("Dog3");
            Cat1.BuyPet("Cat1");
        }
        public object Execute(object system)
        {
            PurchaseOrder purchaseOrder = null;
            PetStore      ps            = (PetStore)system;
            long          id            = ps.nextPurchaseOrderId();

            if (!PurchaseOrder.checkCreate(id, ps.getAccount(accountLogin), this.shippingInfo, this.billingInfo, this.items, PrevalenceEngine.Now))
            {
                throw new ArgumentException("Invalid purchase order parameters.");
            }
            purchaseOrder = new PurchaseOrder(id, ps.getAccount(accountLogin), shippingInfo, billingInfo, items, PrevalenceEngine.Now);
            ps.addPurchaseOrder(purchaseOrder);
            return(purchaseOrder);
        }
Exemple #9
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            PetStore = await _context.PetStore.FirstOrDefaultAsync(m => m.PSID == id);

            if (PetStore == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Exemple #10
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            PetStore = await _context.PetStore.FindAsync(id);

            if (PetStore != null)
            {
                _context.PetStore.Remove(PetStore);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Exemple #11
0
        static void Main(string[] args)
        {
            //Basic static method Call
            //Statics.Multiply(5, 5);

            //Console.WriteLine(Statics.Divide(20, 4));

            //Statics.Divide();

            //Statics.StringTrimmer();

            //In class assignment:

            //Create two more animals of your choice
            //Create a constructor that inherits the parameters of the base constructor
            //override the Speak() and ToString() methods


            //PART TWO:
            //Create a new Class called PetStore
            //Pet store should have one prop that is a LIST of type ANIMAL

            //PetStore should have a default constructor (no parameters). Inside the constructor, create a new instance of your
            //animals list. Add one of each of your animals with a name

            //PetStore should have 2 Methods:
            //1 StoreNoise()  :  StoreNoise will return a string. It will take each animal in your animal list, and print
            // {AnimalName} says : and then that animals noise. each name and noise should be on a separate line

            //2 GetAllAnimalTypes() : GetAllAnimalTypes will return a string. For each animal in your animal list it will print there name,
            //and say what "type" it is. Each on a new line.

            //GetAllAnimalTypes Hint: To get the animal type use the GetType() method (it is part of the object class)
            //GetType() example foreach(Person p in People)
            //{
            // p.GetType()
            //}

            PetStore p = new PetStore();

            Console.WriteLine(p.StoreNoise());
            Console.WriteLine(p.GetAllAnimalTypes());
        }
Exemple #12
0
        static void Main(string[] args)
        {
            Dog dog1 = new Dog("Sparky", "Shepard", 5, "bone", false);
            Dog dog2 = new Dog("Spic", "Doga", 4, "meat", true);
            Dog dog3 = new Dog("Balto", "Doberman", 2, "pizza", true);

            Cat cat1 = new Cat("Tom", "domestic", 1, 9, true);
            Cat cat2 = new Cat("Smokey", "Siamese", 3, 5, false);
            Cat cat3 = new Cat("Sammy", "Persian", 6, 2, false);

            Fish fish1 = new Fish("Nemo", "Mollies", 1, "Yellow", "medium");
            Fish fish2 = new Fish("Bubbles", "Zebra Danios", 2, "Blue", "small");
            Fish fish3 = new Fish("Captain", "Platies", 2, "Black", "big");

            PetStore <Dog> dogStore = new PetStore <Dog>();

            dogStore.addPets(dog1);
            dogStore.addPets(dog2);
            dogStore.PrintPets();
            dogStore.BuyPet(dog3);
            Console.WriteLine("================================");

            PetStore <Cat> catStore = new PetStore <Cat>();

            catStore.addPets(cat3);
            catStore.addPets(cat1);
            catStore.PrintPets();
            catStore.BuyPet(cat3);
            Console.WriteLine("================================");

            PetStore <Fish> fishStore = new PetStore <Fish>();

            fishStore.addPets(fish2);
            fishStore.addPets(fish3);
            fishStore.PrintPets();
            fishStore.BuyPet(fish3);
            Console.ReadLine();
        }
        static void Main(string[] args)
        {
            #region Exercise
            //      Create 4 classes:
            //  Pet( abstract ) with Name, Type, Age and abstract PrintInfo()
            //  Dog(from Pet) with GoodBoi and FavoriteFood
            //  Cat(from Pet) with Lazy and LivesLeft
            //  Fish(from Pet) with color, size

            //      Create a PetStore generic class with :
            //  Generic list of pets - Dogs, Cats or Fish depending on what is passed as T
            //  Generic method printsPets() - Prints Dogs, Cats or Fish depending on what is passed as T
            //  BuyPet() - Method that takes ‘name’ as parameter, find the first pet by that name, removes it from the list and gives a success message.If there is no pet by that name, inform the customer
            //      Create a Dog, Cat and fish store with 2 pets each
            //  Buy a dog and a cat from the Dog and Cat store
            //  Call PrintPets() method on all stores
            #endregion

            PetStore <Dog>  dogStore  = new PetStore <Dog>();
            PetStore <Cat>  catStore  = new PetStore <Cat>();
            PetStore <Fish> fishStore = new PetStore <Fish>();

            dogStore.Insert(new Dog()
            {
                Type = "dog", Name = "Nero", Age = 14, isGood = true, FavouriteFood = "chicken"
            });
            dogStore.Insert(new Dog()
            {
                Type = "dog", Name = "Shegy", Age = 10, isGood = true, FavouriteFood = "beaf meat"
            });
            dogStore.Insert(new Dog()
            {
                Type = "dog", Name = "Puppy", Age = 5, isGood = false, FavouriteFood = "eggs"
            });
            dogStore.Insert(new Dog()
            {
                Type = "dog", Name = "Bully", Age = 7, isGood = true, FavouriteFood = "beaf meat"
            });

            Console.WriteLine("---------All Dogs in Dog Store:---------");
            dogStore.PrintPets();
            dogStore.BuyPet("shegy ");

            catStore.Insert(new Cat()
            {
                Type = "cat", Name = "Mario", isLazy = true, LivesLeft = 10, Age = 2
            });
            catStore.Insert(new Cat()
            {
                Type = "cat", Name = "Luiji", isLazy = false, LivesLeft = 10, Age = 2
            });
            catStore.Insert(new Cat()
            {
                Type = "cat", Name = "Mimi", isLazy = false, LivesLeft = 9, Age = 3
            });


            Console.WriteLine("---------All Cats in Cat Store:---------");
            catStore.PrintPets();
            catStore.BuyPet("Mimi");

            fishStore.Insert(new Fish()
            {
                Type = "fish", Name = "Boo", Color = "Blue", Size = 4.3f, Age = 4
            });
            fishStore.Insert(new Fish()
            {
                Type = "fish", Name = "Loly", Color = "Purple", Size = 3.5f, Age = 3
            });

            Console.WriteLine("---------All Fishes in Fish Store:---------");
            fishStore.PrintPets();
            fishStore.BuyPet("jiM ");
        }
Exemple #14
0
        static async Task Main(string[] args)
        {
            // Load Configuration Files
            using var authMessagesStream = typeof(IAuthProcess).Assembly.GetManifestResourceStream("LazyStackAuth.AuthMessages.json");
            using var methodMapStream    = typeof(PetStore).Assembly.GetManifestResourceStream("PetStoreClientSDK.MethodMap.json");
            using var awsSettingsStream  = typeof(Program).Assembly.GetManifestResourceStream("PetStoreConsoleApp.AwsSettings.json");
            using var localApisStream    = typeof(Program).Assembly.GetManifestResourceStream("PetStoreConsoleApp.LocalApis.json");
            appConfig = new ConfigurationBuilder()
                        .AddJsonStream(authMessagesStream)
                        .AddJsonStream(methodMapStream)
                        .AddJsonStream(awsSettingsStream)
                        .AddJsonStream(localApisStream)
                        .Build();

            IServiceCollection services = new ServiceCollection();
            IServiceProvider   serviceProvider;

            services.AddSingleton <IConfiguration>(appConfig);
            // LoginFormat(IConfiguration)
            services.AddSingleton <ILoginFormat, LoginFormat>();

            // PasswordFormat(IConfiguration)
            services.AddSingleton <IPasswordFormat, PasswordFormat>();

            // EmailFormat(IConfiguration)
            services.AddSingleton <IEmailFormat, EmailFormat>();

            // PhoneFormat(IConfiguration)
            services.AddSingleton <IPhoneFormat, PhoneFormat>();

            // CodeFormat(IConfiguration)
            services.AddSingleton <ICodeFormat, CodeFormat>();

            // AuthProviderCognito(IConfiguration, ILoginFormat, IPasswordFormat, IEmailFormat, ICodeFormat, IPhoneFormat)
            services.AddSingleton <IAuthProvider, AuthProviderCognito>();

            // AuthProcess(IConfiguration, IAuthProvider)
            services.AddSingleton <IAuthProcess, AuthProcess>(); // depends on IConfiguration, IAuthProvider

            serviceProvider = services.BuildServiceProvider();

            var authProvider = serviceProvider.GetService <IAuthProvider>() as AuthProviderCognito;
            var authProcess  = serviceProvider.GetService <IAuthProcess>();
            var lzHttpClient = new LzHttpClient(appConfig, authProvider, "Local");
            // Init PetStore library -- provides easy to use calls against AWS ApiGateways
            var petStore = new PetStore(lzHttpClient);

            // Ask the user if they want to use LocalApi Controller Calls
            // Note that this does not influence calls to Cognito for authentication
            Console.WriteLine("Welcome to the PetStoreConsoleApp program");
            Console.Write("Use LocalApi? y/n:");
            var useLocalApi = Console.ReadLine();

            lzHttpClient.UseLocalApi = useLocalApi.Equals("Y", StringComparison.OrdinalIgnoreCase);

            var input         = string.Empty;
            var alertMsg      = string.Empty;
            var menuMsg       = string.Empty;
            var lastAuthEvent = AuthEventEnum.AuthChallenge;

            while (true)
            {
                alertMsg = (lastAuthEvent > AuthEventEnum.Alert)
                    ? appConfig[$"AuthAlertMessages:{currentLanguage}:{lastAuthEvent}"]
                    : string.Empty;
                if (!string.IsNullOrEmpty(alertMsg))
                {
                    Console.WriteLine($"Alert: {alertMsg}");
                }


                switch (authProcess.CurrentAuthProcess)
                {
                case AuthProcessEnum.None:
                    if (authProcess.IsNotSignedIn)
                    {
                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.SigningUp}"];
                        Console.WriteLine($"1. {menuMsg}");

                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.SigningIn}"];
                        Console.WriteLine($"2. {menuMsg}");

                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.ResettingPassword}"];
                        Console.WriteLine($"3. {menuMsg}");

                        Console.WriteLine("4. Quit");

                        Console.Write(">");
                        input = Console.ReadLine();
                        switch (input)
                        {
                        case "1":
                            lastAuthEvent = await authProcess.StartSignUpAsync();

                            break;

                        case "2":
                            lastAuthEvent = await authProcess.StartSignInAsync();

                            break;

                        case "3":
                            lastAuthEvent = await authProcess.StartResetPasswordAsync();

                            break;

                        case "4":
                            return;         // exit program

                        default:
                            Console.WriteLine("Sorry, didn't understand that input. Please try again.");
                            continue;
                        }
                    }
                    else
                    {
                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.SigningOut}"];
                        Console.WriteLine($"1. {menuMsg}");

                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.UpdatingPassword}"];
                        Console.WriteLine($"2. {menuMsg}");

                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.UpdatingPhone}"];
                        Console.WriteLine($"3. {menuMsg}");

                        menuMsg = appConfig[$"AuthProcessLabels:{currentLanguage}:{AuthProcessEnum.UpdatingLogin}"];
                        Console.WriteLine($"4. {menuMsg}");

                        Console.WriteLine("5. Seed Pets data");
                        Console.WriteLine("6. Get Pet 1");
                        Console.WriteLine("7. See Available Pets");
                        Console.WriteLine("8. GetUserId");
                        Console.WriteLine("9. Quit");
                        Console.Write(">");
                        input = Console.ReadLine();
                        switch (input)
                        {
                        case "1":
                            lastAuthEvent = await authProcess.SignOutAsync();

                            break;

                        case "2":
                            lastAuthEvent = await authProcess.StartUpdatePasswordAsync();

                            break;

                        case "3":
                            lastAuthEvent = await authProcess.StartUpdatePhoneAsync();

                            break;

                        case "4":
                            lastAuthEvent = await authProcess.StartUpdateLoginAsync();

                            break;

                        case "5":
                            try
                            {
                                await petStore.SeedPetsAsync();

                                Console.WriteLine("Pets added to database");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Could not add pets to database. {e.Message}");
                            }
                            break;

                        case "6":
                            try
                            {
                                var pet = await petStore.GetPetByIdAsync(1);

                                Console.WriteLine($"pet: {pet.Id} {pet.Name} {pet.PetStatus}");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Could not retrieve pet. {e.Message}");
                            }
                            break;

                        case "7":
                            try
                            {
                                var petStatus = new List <PetStatus> {
                                    PetStatus.Available
                                };
                                var pets = await petStore.FindPetsByStatusAsync(petStatus);

                                if (pets.Count == 0)
                                {
                                    Console.WriteLine("Sorry - No Pets Found");
                                }
                                else
                                {
                                    foreach (var pet in pets)
                                    {
                                        Console.WriteLine($"- Id: {pet.Id} Name: {pet.Name}");
                                    }
                                }
                                Console.WriteLine();
                            } catch (Exception e)
                            {
                                Console.WriteLine($"Could not get pets. {e.Message}");
                            }
                            break;

                        case "8":
                            try
                            {
                                var userId = await petStore.GetUserAsync();

                                Console.WriteLine($"UserId={userId}");
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine($"Could not get userId. {e.Message}");
                            }
                            break;

                        case "9":
                            return;         // exit program

                        default:
                            Console.WriteLine("Sorry, didn't understand that input. Please try again.");
                            continue;
                        }
                    }
                    break;

                default:     // Some AuthProcess is active so process CurrentChallenge
                    var prompt = appConfig[$"AuthChallengeMessages:{currentLanguage}:{authProcess.CurrentChallenge}"];
                    switch (authProcess.CurrentChallenge)
                    {
                    case AuthChallengeEnum.Login:
                        Console.Write($"{prompt}: ");
                        authProcess.Login = Console.ReadLine();
                        lastAuthEvent     = string.IsNullOrEmpty(authProcess.Login)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyLoginAsync();

                        break;

                    case AuthChallengeEnum.Password:
                        Console.Write($"{prompt}: ");
                        authProcess.Password = Console.ReadLine();
                        lastAuthEvent        = string.IsNullOrEmpty(authProcess.Password)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyPasswordAsync();

                        break;

                    case AuthChallengeEnum.Email:
                        Console.Write($"{prompt}: ");
                        authProcess.Email = Console.ReadLine();
                        lastAuthEvent     = string.IsNullOrEmpty(authProcess.Email)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyEmailAsync();

                        break;

                    case AuthChallengeEnum.Code:
                        Console.Write($"{prompt}: ");
                        authProcess.Code = Console.ReadLine();
                        if (string.IsNullOrEmpty(authProcess.Code))
                        {
                            Console.Write("Resend Code? y/n");
                            var resendCode = Console.ReadLine();
                            lastAuthEvent = resendCode.Equals("y", StringComparison.OrdinalIgnoreCase)
                                        ? await CancelAsync()
                                        : await authProcess.ResendCodeAsync();
                        }
                        else
                        {
                            lastAuthEvent = await authProcess.VerifyCodeAsync();
                        }

                        if (lastAuthEvent == AuthEventEnum.SignedUp)
                        {
                            Console.WriteLine("You are Signed Up! You can now SignIn.");
                        }
                        break;

                    case AuthChallengeEnum.Phone:
                        Console.Write($"{prompt}: ");
                        authProcess.Phone = Console.ReadLine();
                        lastAuthEvent     = string.IsNullOrEmpty(authProcess.Phone)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyPhoneAsync();

                        break;

                    case AuthChallengeEnum.NewLogin:
                        Console.Write($"{prompt}: ");
                        authProcess.NewLogin = Console.ReadLine();
                        lastAuthEvent        = string.IsNullOrEmpty(authProcess.NewLogin)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyNewLoginAsync();

                        break;

                    case AuthChallengeEnum.NewPassword:
                        Console.Write($"{prompt}: ");
                        authProcess.NewPassword = Console.ReadLine();
                        lastAuthEvent           = string.IsNullOrEmpty(authProcess.NewPassword)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyNewPasswordAsync();

                        break;

                    case AuthChallengeEnum.NewEmail:
                        Console.Write($"{prompt}: ");
                        authProcess.NewEmail = Console.ReadLine();
                        lastAuthEvent        = string.IsNullOrEmpty(authProcess.NewEmail)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyNewEmailAsync();

                        break;

                    case AuthChallengeEnum.NewPhone:
                        Console.Write($"{prompt}: ");
                        authProcess.NewPhone = Console.ReadLine();
                        lastAuthEvent        = string.IsNullOrEmpty(authProcess.NewPhone)
                                    ? await CancelAsync()
                                    : await authProcess.VerifyNewPhoneAsync();

                        break;

                    default:
                        Console.WriteLine("Error: Unknown Challenge!");
                        lastAuthEvent = await CancelAsync();

                        break;
                    }
                    break;
                }
            }
        }
Exemple #15
0
        public async Task TestMethod1()
        {
            using var authMessagesStream = typeof(IAuthProcess).Assembly.GetManifestResourceStream("LazyStackAuth.AuthMessages.json");
            using var awsSettingsStream  = typeof(PetStoreIntegrationTest).Assembly.GetManifestResourceStream("PetStoreTests.AwsSettings.json");
            using var methodMapStream    = typeof(PetStore).Assembly.GetManifestResourceStream("PetStoreClientSDK.MethodMap.json");
            IConfiguration appConfig = new ConfigurationBuilder()
                                       .AddUserSecrets <PetStoreIntegrationTest>() //  used to get gmail account credentials for auth code
                                       .AddJsonStream(awsSettingsStream)
                                       .AddJsonStream(authMessagesStream)
                                       .AddJsonStream(methodMapStream)
                                       .Build();

            IServiceCollection services = new ServiceCollection();
            IServiceProvider   serviceProvider;

            services.AddSingleton <IConfiguration>(appConfig);
            // LoginFormat(IConfiguration)
            services.AddSingleton <ILoginFormat, LoginFormat>();

            // PasswordFormat(IConfiguration)
            services.AddSingleton <IPasswordFormat, PasswordFormat>();

            // EmailFormat(IConfiguration)
            services.AddSingleton <IEmailFormat, EmailFormat>();

            // PhoneFormat(IConfiguration)
            services.AddSingleton <IPhoneFormat, PhoneFormat>();

            // CodeFormat(IConfiguration)
            services.AddSingleton <ICodeFormat, CodeFormat>();

            // AuthProviderCognito(IConfiguration, ILoginFormat, IPasswordFormat, IEmailFormat, ICodeFormat, IPhoneFormat)
            services.AddSingleton <IAuthProvider, AuthProviderCognito>();

            // AuthProcess(IConfiguration, IAuthProvider)
            services.AddSingleton <IAuthProcess, AuthProcess>(); // depends on IConfiguration, IAuthProvider

            serviceProvider = services.BuildServiceProvider();

            var authProvider = serviceProvider.GetService <IAuthProvider>() as AuthProviderCognito;
            var authProcess  = serviceProvider.GetService <IAuthProcess>();

            // Signup
            var now      = DateTime.Now;
            var login    = $"TestUser{now.Year}-{now.Month}-{now.Day}-{now.Hour}-{now.Minute}-{now.Second}";
            var password = "******";

            // Use Google email alias feature to allow us to use a single gmail account for our testing
            // ex: [email protected] becomes [email protected]
            // This avoids AWS complaining that the email already exists
            // These are one-time use aliases and Cognito accounts
            var email      = appConfig["Gmail:Email"];
            var emailParts = email.Split("@");

            email = emailParts[0] + "+" + login + "@" + emailParts[1];

            // Start Sign Up process
            Assert.IsTrue(await authProcess.StartSignUpAsync() == AuthEventEnum.AuthChallenge);
            Assert.IsTrue(authProcess.CurrentAuthProcess == AuthProcessEnum.SigningUp);

            // Simulate collection of Login from user
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.Login);
            authProcess.Login = login;
            Assert.IsTrue(await authProcess.VerifyLoginAsync() == AuthEventEnum.AuthChallenge);

            // Simulate collection of Password from user
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.Password);
            authProcess.Password = password;
            Assert.IsTrue(await authProcess.VerifyPasswordAsync() == AuthEventEnum.AuthChallenge);

            // Simulate collection of Email from user
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.Email);
            authProcess.Email = email;
            var verificationCodeSendTime = DateTime.UtcNow; // verificationCode sent after this time

            Thread.Sleep(5000);                             // Account for a little drive among local and remote clock
            Assert.IsTrue(await authProcess.VerifyEmailAsync() == AuthEventEnum.AuthChallenge);

            // Simulate collection of Code from user - AWS Sends the code to the email account
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.Code);
            var verificationCode = AuthEmail.GetAuthCode(appConfig, email);

            Assert.IsNotNull(verificationCode);
            authProcess.Code = verificationCode;
            // Verifying the code finalizes the sign up process
            Assert.IsTrue(await authProcess.VerifyCodeAsync() == AuthEventEnum.SignedUp);
            Assert.IsTrue(authProcess.CurrentAuthProcess == AuthProcessEnum.None);
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.None);
            Assert.IsTrue(authProcess.IsSignedIn == false);

            // Start SignIn process
            Assert.IsTrue(await authProcess.StartSignInAsync() == AuthEventEnum.AuthChallenge);
            Assert.IsTrue(authProcess.CurrentAuthProcess == AuthProcessEnum.SigningIn);

            // Simulate collection of Password from user
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.Login);
            authProcess.Password = password;
            Assert.IsTrue(await authProcess.VerifyLoginAsync() == AuthEventEnum.AuthChallenge);

            // Simulate collection of Password from user
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.Password);
            authProcess.Password = password;
            // Verifying password finalizes SigningIn process
            Assert.IsTrue(await authProcess.VerifyPasswordAsync() == AuthEventEnum.SignedIn);
            Assert.IsTrue(authProcess.CurrentAuthProcess == AuthProcessEnum.None);
            Assert.IsTrue(authProcess.CurrentChallenge == AuthChallengeEnum.None);
            Assert.IsTrue(authProcess.IsSignedIn == true);

            //////////////////////////////////////////////////////////////
            // Use PetStore library to call the ApiGateways in our stack
            //////////////////////////////////////////////////////////////

            // Creating the LzHttpClient which knows how to make secure calls against AWS ApiGateways
            var lzHttpClient = new LzHttpClient(appConfig, authProvider, null);

            // Create the PetStore lib instance that makes calling the stack easy
            var petStore = new PetStore(lzHttpClient);

            // Call PetStore.SeedPetsAsync -- it's ok if the pet records already exist
            await petStore.SeedPetsAsync();

            // Retrieve pet record by Id
            var pet = await petStore.GetPetByIdAsync(1);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            Dog kuce = new Dog {
                Age = 10, FavoriteFood = "bones", Name = "Labrador", Type = "Labrador"
            };
            Dog kuce1 = new Dog {
                Age = 10, FavoriteFood = "meat", Name = "Malinois", Type = "Malinois"
            };
            Dog kuce2 = new Dog {
                Age = 10, FavoriteFood = "macki", Name = "Beagle", Type = "Beagle"
            };

            Cat mace = new Cat {
                Name = "Persiska", Age = 100, isLazy = true, LivesLeft = 8, Type = "Persiska"
            };
            Cat mace1 = new Cat {
                Name = "Domasnomace", Age = 80, isLazy = false, LivesLeft = 4, Type = "Domasno"
            };
            Cat mace2 = new Cat {
                Name = "UlicnoMace", Age = 10, isLazy = false, LivesLeft = 1, Type = "Ulicno"
            };

            Fish ripce = new Fish {
                Name = "Nemo", Age = 10, Type = "Nemo", Color = "White", Size = 10
            };
            Fish ripce1 = new Fish {
                Name = "Cilchild", Age = 5, Type = "Cichild", Color = "Yellow", Size = 9
            };
            Fish ripce2 = new Fish {
                Name = "Shark", Age = 5, Type = "Shark", Color = "Black", Size = 8
            };



            PetStore <Dog> dogStore = new PetStore <Dog>()
            {
            };
            PetStore <Cat> catStore = new PetStore <Cat>()
            {
            };
            PetStore <Fish> fishStore = new PetStore <Fish>()
            {
            };

            List <Dog> listOfCDOgs = dogStore.ListOfPets = new List <Dog> {
                kuce, kuce1, kuce2
            };
            List <Cat> listOfCats = catStore.ListOfPets = new List <Cat> {
                mace, mace1, mace2
            };


            //dogStore.BuyPet("Labrador");
            //dogStore.BuyPet("Malinois");


            Console.WriteLine("Enter a pet name to buy");
            string input = Console.ReadLine();

            catStore.BuyPet(input);
            Thread.Sleep(1000);

            Console.ForegroundColor = ConsoleColor.Yellow;
            catStore.PrintPets();
        }
        public static void Main(String[] args)
        {
            ArrayList arrlist = new ArrayList();              // non-generic ArrayList -- the SERIALIZER WILL NOT WORK

            List <Pet> myPetList1 = new List <Pet>();         // just a list

            PetListWrapper myPetList2 = new PetListWrapper(); // a list inside a wrapper class

            PetStore myPetStore = new PetStore();             // a list and some other items inside a wrappr class

            myPetStore.PetStoreName = "Polly's Furry Pets";
            myPetStore.PetStoreCity = "St. Louis";
            myPetStore.PetStoreZip  = 63011;

            String[] ptypes  = new String[] { "Dog", "Dog", "Dog", "Dog", "Cat" };
            String[] names   = new String[] { "Rover", "Spot", "Lassie", "Fido", "Fluffy" };
            String[] breeds  = new String[] { "Beagle", "Dalmation", "Collie", "Boxer", "Calico" };
            int[]    weights = new int[] { 30, 50, 60, 60, 12 };

            for (int i = 0; i < names.Length; i++)
            {
                Pet p = new Pet(ptypes[i], names[i], breeds[i], weights[i]);
                myPetList1.Add(p);
                myPetList2.PetList.Add(p);
                myPetStore.PetList.Add(p);
                arrlist.Add(p);
            }

            Console.WriteLine("\n\nAn individual object:\n");
            Pet p1 = new Pet("fish", "Wanda", "Goldfish", 0);

            //new XmlSerializer(typeof(Pet)).Serialize(Console.Out, p1); // this works
            var xmlser = new XmlSerializer(typeof(Pet)); // note that this can be done in two conventional steps - create object
            XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();

            xmlns.Add("davejjj", "https://github.com/davejjj");                                  // create some customized xmlns settings
            xmlser.Serialize(Console.Out, p1, xmlns);                                            // and then use the object

            Console.WriteLine("\n\nA typed list of objects in a wrapper class:\n");              // the "encoding=IBM437" is only seen in the Console, not in the file
            new XmlSerializer(typeof(PetListWrapper)).Serialize(Console.Out, myPetList2, xmlns); // this works

            Console.WriteLine("\n\nA typed list of objects:\n");
            new XmlSerializer(typeof(List <Pet>)).Serialize(Console.Out, myPetList1, xmlns); // this works

            //Console.WriteLine("\n\nA NON-TYPED COLLECTION such as an ordinary ArrayList:\n");
            //new XmlSerializer(typeof(ArrayList)).Serialize(Console.Out, arrlist, xmlns); // this DOES NOT work

            String fpath = @"C:\Temp\Test01\test.xml";

            Console.WriteLine("\n\nSave a list of objects to an xml file: {0}", fpath);
            FileStream fs = new FileStream(fpath, FileMode.Create);                 // create or overwrite file

            new XmlSerializer(typeof(List <Pet>)).Serialize(fs, myPetList1, xmlns); // this works
            fs.Flush();
            fs.Close();
            Console.WriteLine("Filestream closed");

            Console.WriteLine("\n\nA petstore:\n");
            new XmlSerializer(typeof(PetStore)).Serialize(Console.Out, myPetStore, xmlns); // this works

            Console.WriteLine("\n\nPress a key...");
            Console.ReadKey();

            Console.WriteLine("\n\nNow Read the file back... Press a key...");
            Console.ReadKey();

            Console.WriteLine("\n\nRead an xml file to create a list of objects: {0}", fpath);
            XmlSerializer rxfstrm    = new XmlSerializer(typeof(List <Pet>));
            FileStream    rfs        = new FileStream(fpath, FileMode.Open);
            List <Pet>    newpetlist = (List <Pet>)rxfstrm.Deserialize(rfs);

            foreach (Pet x in newpetlist)
            {
                Console.WriteLine("\nPettype:{0} \nPetname:{1} \nBreed:{2} \nWeight:{3}", x.PetType, x.PetName, x.Breed, x.Weight);
            }
            rfs.Flush();
            rfs.Dispose();

            Console.WriteLine("\n\nPress a key...");
            Console.ReadKey();
        } // end of Main