public static void Should_not_throw_DbUpdateException()
        {
            var options = new DbContextOptionsBuilder()
                          .UseSqlServer($"Data Source=(local);Initial Catalog=Test_{nameof(GH15666_Explicit)};Integrated Security=SSPI;").Options;

            using (var db = new TestContext(options))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var counterparty = new Counterparty()
                {
                    Name = "Foo"
                };

                db.Add(counterparty);

                db.SaveChanges();

                var left = new FollowUpInteraction()
                {
                    InteractedWithCounterparty = counterparty
                };

                db.Add(left);

                db.SaveChanges();
            }
        }
        public static void Should_not_throw_InvalidOperationException_when_using_enum_as_discriminator(bool applyColumnType)
        {
            var options = new DbContextOptionsBuilder()
                          .UseSqlServer($"Data Source=(local);Initial Catalog=Test_{nameof(GH11454)}_{applyColumnType};Integrated Security=SSPI;").Options;

            using (var db = new TestContext(options, applyColumnType))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                // TODO write save logic
                var left = new Left()
                {
                };

                db.Add(left);

                var right = new Right()
                {
                };

                db.Add(right);

                db.SaveChanges();
            }
        }
Exemple #3
0
 public IActionResult Create(User user)
 {
     if (ModelState.IsValid)
     {
         if (dbContext.Users.Any(u => u.Email == user.Email))
         {
             ModelState.AddModelError("Email", "Email already in use!");
             return(View("Register"));
         }
         if (dbContext.Users.Any(u => u.Username == user.Username))
         {
             ModelState.AddModelError("Username", "Username already in use!");
             return(View("Register"));
         }
         PasswordHasher <User> Hasher = new PasswordHasher <User>();
         user.Password = Hasher.HashPassword(user, user.Password);
         dbContext.Add(user);
         dbContext.SaveChanges();
         HttpContext.Session.SetInt32("UserId", user.UserId);
         return(RedirectToAction("HomePage"));
     }
     else
     {
         return(View("Register"));
     }
 }
        public static void One_Child_TablePerHierarchy_SanityCheck(bool applyColumnType)
        {
            var options = new DbContextOptionsBuilder()
                          .UseSqlServer($"Data Source=(local);Initial Catalog=Test_{nameof(ProgramOneChildTphSanityCheck)}_{applyColumnType};Integrated Security=SSPI;").Options;

            using (var db = new TestContext(options, applyColumnType))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                // TODO write save logic
                var goodChild = new GoodChild()
                {
                    GoodChildData = Random30Characters()
                };

                db.Add(goodChild);

                var badChild = new BadChild()
                {
                };

                db.Add(badChild);

                db.SaveChanges();
            }
        }
Exemple #5
0
        public static void One_TablePerHierarchy_To_One_TablePerHierarchy_Different_Discriminator_Names_With_Identity_Insert()
        {
            var options = new DbContextOptionsBuilder()
                          .UseSqlServer($"Data Source=(local);Initial Catalog=Test_{nameof(ProgramOneTphToOneTphDifferentDiscriminatorNamesWithIdentityInsert)};Integrated Security=SSPI;").Options;

            using (var db = new TestContext(options))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                // TODO write save logic
                var goodChild = new GoodChild()
                {
                    Parent           = new GoodParent()
                    {
                    }, GoodChildData = Random30Characters()
                };

                db.Add(goodChild);

                var badChild = new BadChild()
                {
                    Parent          = new BadParent()
                    {
                    }, BadChildData = Random30Characters()
                };

                db.Add(badChild);

                var goodParent = new GoodParent()
                {
                    Child = new GoodChild()
                    {
                        GoodChildData = Random30Characters()
                    },
                    GoodParentData = Random30Characters()
                };

                db.Add(goodParent);

                var badParent = new BadParent()
                {
                    Child = new BadChild()
                    {
                        BadChildData = Random30Characters()
                    },
                    BadParentData = Random30Characters()
                };

                db.Add(badParent);

                db.SaveChanges();
            }
        }
Exemple #6
0
        public bool Check(Guid userId, string path)
        {
            //if (CheckDuplicateCall(userId, path)) return false; //Check for duplicate calls

            var requestLimit = GetLimit(path);
            var timeDiff     = GetDiff(path);
            var requests     = _context.Requests.Where(r => r.UserId == userId && r.RequestTime > timeDiff).Select(r => r).ToList();

            if (requests.Count <= requestLimit)
            {
                var request = new Request()
                {
                    UserId      = userId,
                    Path        = path,
                    RequestTime = DateTime.Now
                };
                _context.Add(request);
                _context.SaveChanges();
                _context.Dispose();
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public static void Should_not_throw_InvalidOperationException_when_using_enum_as_discriminator(ConversionStrategy conversionStrategy, bool applyColumnType)
        {
            var options = new DbContextOptionsBuilder()
                          .UseSqlServer($"Data Source=(local);Initial Catalog=Test_{nameof(MsftDocsValueConversionExample)}_{conversionStrategy}_{applyColumnType};Integrated Security=SSPI;").Options;

            using (var db = new TestContext(options, conversionStrategy, applyColumnType))
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                // TODO write save logic
                var rider = new Rider()
                {
                    Mount = EquineBeast.Horse
                };

                db.Add(rider);

                db.SaveChanges();

                var sameRider = db.Set <Rider>().FirstOrDefault(r => r.Id == rider.Id);
                Assert.True(sameRider != null);
                var sameRider2 = db.Set <Rider>().FirstOrDefault(r => r.Mount == EquineBeast.Horse);
                Assert.True(sameRider2 != null);
            }
        }
Exemple #8
0
        public void WithDbUpdateExceptionDestructurerShouldNotLogDbValues()
        {
            // Arrange
            var     jsonWriter = new StringWriter();
            ILogger logger     = new LoggerConfiguration()
                                 .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder().WithDefaultDestructurers().WithDestructurers(new[] { new TestDbUpdateExceptionDestructurer() }))
                                 .WriteTo.Sink(new TestTextWriterSink(jsonWriter, new JsonFormatter()))
                                 .CreateLogger();

            using var ctx = new TestContext();
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();

            var entry = ctx.Add(new User
            {
                UserId = Guid.NewGuid().ToString(),
            });

            // Act
            logger.Error(new TestDbUpdateException("DbUpdate Error", entry), "Error");

            // Assert
            var writtenJson = jsonWriter.ToString();

            writtenJson.Should().NotContain(TestContext.UserIdIDoNotWantToSee);
        }
Exemple #9
0
        public async Task <IActionResult> Create([Bind("MgaaId,MgaaMbdcClasse,MgaaMatricola,MgaaDescr,MgaaNote,MgaaDataIns,MgaaDataUltMod")] MgAnaArt mgAnaArt)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var emptyComponent = new MgAnaArt();

                    _context.Add(mgAnaArt);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException ex)
            {
                string msg = "Unable to save changes. " +
                             "Try again, and if the problem persists " +
                             "see your system administrator.";
                if (ex.InnerException.Message.Contains("UNIQUE"))
                {
                    msg = "Attribute Code must be unique";
                }
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", msg);
            }
            return(View(mgAnaArt));
        }
        public async Task ExecuteAsync_does_not_call_Commit_if_existing_transaction(bool async)
        {
            using (var context = new TestContext())
            {
                var connection  = SetupConnection(context);
                var transaction = new FakeDbTransaction(connection);
                context.Database.UseTransaction(transaction);

                context.Add(
                    new Foo
                {
                    Id = "1"
                });

                if (async)
                {
                    await context.SaveChangesAsync();
                }
                else
                {
                    context.SaveChanges();
                }

                Assert.Empty(connection.DbTransactions);
                Assert.Equal(0, transaction.CommitCount);
            }
        }
        public override void PreWebTest(object sender, PreWebTestEventArgs e)
        {
            ITestContext context = new TestContext(e, AuthenticationInfo.Authorization);

            context.Add(TestContextConst.BaseUri, e.WebTest.Context[TestContextConst.BaseUri]);
            context.SetEventArgs(e);
            e.WebTest.Context[TestContextConst.ContextKey] = context;
            //TestContext.Context = context;
            //TestContext.Context.SetEventArgs(e);

            base.PreWebTest(sender, e);
            string     loginUri     = TemplateHelper.CompileTemplate(this.Url, context);
            var        loginRequest = new LoginRequest(this.UserName, this.Password);
            IConnector connector    = new RESTConnector();
            IResponseData <LoginResponse> response = connector.Post <LoginRequest, LoginResponse>(loginUri, loginRequest);

            if (response.HasError())
            {
                e.WebTest.Stop();
                return;
            }
            e.WebTest.Context.Add(LoadTestConst.Authorization, response.Data.Authorization);
            AuthenticationInfo.Authorization = new Authorization(response.Data.Authorization, response.Data.AuthToken);

            context = e.WebTest.Context[TestContextConst.ContextKey] as ITestContext;
            context.SetAuthorization(AuthenticationInfo.Authorization);
        }
Exemple #12
0
        public async Task Test1()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <TestContext>()
                              .UseSqlite(connection);

                using (var context = new TestContext(options.Options))
                {
                    await context.Database.EnsureCreatedAsync();
                }

                var org1Id  = Guid.NewGuid();
                var user1Id = Guid.NewGuid();

                using (var context = new TestContext(options.Options))
                {
                    context.Add(new OrganisationRecord
                    {
                        Id   = org1Id,
                        Name = "Org 1",
                    });

                    context.Add(new UserRecord
                    {
                        OrganisationId = org1Id,
                        Id             = user1Id,
                        Name           = "user 1",
                    });

                    await context.SaveChangesAsync();
                }

                using (var context = new TestContext(options.Options))
                {
                }
            }
            finally
            {
                connection.Close();
            }
        }
Exemple #13
0
 public Response <Client> Save(Client client)
 {
     try {
         _context.Add(client);
         _context.SaveChanges();
         return(new Response <Client>(client));
     } catch (Exception e) {
         return(new Response <Client>($"Error del aplicacion: {e.Message}"));
     }
 }
Exemple #14
0
        public async Task <IActionResult> Create([Bind("ID,UnitName")] Unit unit)
        {
            if (ModelState.IsValid)
            {
                _context.Add(unit);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(unit));
        }
Exemple #15
0
        public async Task <IActionResult> Create([Bind("MbmgId,MbmgMag,MbmgDescr,MbmgDataFinVal,MbmgCode")] MbMag mbMag)
        {
            if (ModelState.IsValid)
            {
                _context.Add(mbMag);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(mbMag));
        }
        public async Task <IActionResult> Create([Bind("Id,MovieName,Genre,Rating,ReleaseYear,ImdbLink")] MovieList movieList)
        {
            if (ModelState.IsValid)
            {
                _context.Add(movieList);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(movieList));
        }
Exemple #17
0
        public async Task <IActionResult> Create([Bind("ID,Name,Uri")] ApiModel apiModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(apiModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(apiModel));
        }
Exemple #18
0
        public async Task <IActionResult> Create([Bind("Id,Question,Answer1,Answer2,Answer3,Answer4,RightAnswer,Notification")] Test test)
        {
            if (ModelState.IsValid)
            {
                _context.Add(test);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(test));
        }
Exemple #19
0
        public async Task <IActionResult> Create([Bind("PkanId,PkanNum,PkanData,PkanDesc,PkanNote,PkanScaric,PkanYear")] PkAnag pkAnag)
        {
            if (ModelState.IsValid)
            {
                _context.Add(pkAnag);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(pkAnag));
        }
Exemple #20
0
        public async Task <IActionResult> Create([Bind("ProductId,Name,Category,Color,UnitPrice,AvailableQuantity,CratedDate")] Products products)
        {
            if (ModelState.IsValid)
            {
                _context.Add(products);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(products));
        }
Exemple #21
0
        public async Task <IActionResult> Create([Bind("ID,Name,Variables,Urls")] TestModel testModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(testModel);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(testModel));
        }
Exemple #22
0
        public async Task <IActionResult> Create([Bind("Id,Description,IsEnabled")] Permission permission)
        {
            if (ModelState.IsValid)
            {
                _context.Add(permission);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(permission));
        }
        public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,Age,BirthDate,IsEnabled")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(user));
        }
Exemple #24
0
        public async Task <IActionResult> Create([Bind("ID,Name,Vorname,Email")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(user));
        }
Exemple #25
0
        public async Task <IActionResult> Create([Bind("StandardId,StandardName,StandardYear")] Standard standard)
        {
            if (ModelState.IsValid)
            {
                _context.Add(standard);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(standard));
        }
        public async Task <IActionResult> Create([Bind("Id,Name")] ClassM classM)
        {
            if (ModelState.IsValid)
            {
                _context.Add(classM);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(classM));
        }
Exemple #27
0
        public async Task <IActionResult> Create([Bind("Id,text")] Table1 table1)
        {
            if (ModelState.IsValid)
            {
                _context.Add(table1);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(table1));
        }
        public async Task <IActionResult> Create([Bind("Sn,Name,Hight,Weight,Birthday,Photo,Memo,ClassId")] Student student)
        {
            if (ModelState.IsValid)
            {
                _context.Add(student);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ClassId"] = new SelectList(_context.ClassMs, "Id", "Name", student.ClassId);
            return(View(student));
        }
        public async Task <IActionResult> Create([Bind("MgauId,MgauMbmgId,MgauCodice,MgauCodCompl,MgauDescr,MgauTreeCtrl,MgauDataIns,MgauLivello,MgauProfondita,MgauLarghezza,MgauAltezza,MgauBloccata,MgauPrenotata,MgauUbiDef")] MgAnaUbicazioni mgAnaUbicazioni)
        {
            if (ModelState.IsValid)
            {
                _context.Add(mgAnaUbicazioni);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["MgauMbmgId"] = new SelectList(_context.MbMag, "MbmgId", "MbmgCode", mgAnaUbicazioni.MgauMbmgId);
            return(View(mgAnaUbicazioni));
        }
        public async Task <IActionResult> Create([Bind("SId,SName,SAddress,StandardId")] Student student)
        {
            if (ModelState.IsValid)
            {
                _context.Add(student);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["StandardId"] = new SelectList(_context.Standards, "StandardId", "StandardName", student.StandardId);
            return(View(student));
        }