示例#1
0
        public void ProxySerialization()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            Node node = new Node();

            node.Id   = 1;
            node.Name = "Node 1";

            ISession s = OpenSession();

            s.Save(node);
            s.Flush();
            s.Close();

            s = OpenSession();
            Node nodeProxy = (Node)s.Load(typeof(Node), 1);

            // Test if it is really a proxy
            Assert.IsTrue(nodeProxy is INHibernateProxy);
            s.Close();

            // Serialize
            IFormatter   formatter = new BinaryFormatter();
            MemoryStream ms        = new MemoryStream();

            formatter.Serialize(ms, nodeProxy);

            // Deserialize
            ms.Seek(0, SeekOrigin.Begin);
            Node deserializedNodeProxy = (Node)formatter.Deserialize(ms);

            ms.Close();

            // Deserialized proxy should implement the INHibernateProxy interface.
            Assert.IsTrue(deserializedNodeProxy is INHibernateProxy);

            s = OpenSession();
            s.Delete("from Node");
            s.Flush();
            s.Close();
        }
        public void WorkAfterDeserialization()
        {
            TestsContext.AssumeSystemTypeIsSerializable();
            ValidatorEngine  ve   = new ValidatorEngine();
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Cfg.Environment.ValidatorMode]            = "UseAttribute";
            nhvc.Properties[Cfg.Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;
            ve.Configure(nhvc);

            RunSerializationTest(ve);

            ve   = new ValidatorEngine();
            nhvc = new XmlConfiguration();
            nhvc.Properties[Cfg.Environment.ValidatorMode]            = "UseExternal";
            nhvc.Properties[Cfg.Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;
            ve.Configure(nhvc);

            RunSerializationTest(ve);
        }
示例#3
0
        public void SerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            Prepare();
            ISession s = GetSessionUnderTest();

            Silly silly = new Silly("silly");

            s.Save(silly);

            // this should cause the CM to obtain a connection, and then Release it
            s.Flush();

            // both scroll() and iterate() cause the batcher to hold on
            // to resources, which should make aggresive-Release not Release
            // the connection (and thus cause serialization to fail)
            IEnumerable en = s.CreateQuery("from Silly").Enumerable();

            try
            {
                SerializationHelper.Serialize(s);
                Assert.Fail(
                    "Serialization allowed on connected session; or aggressive Release released connection with open resources");
            }
            catch (InvalidOperationException)
            {
                // expected behavior
            }

            // Closing the ScrollableResults does currently force the batcher to
            // aggressively Release the connection
            NHibernateUtil.Close(en);
            SerializationHelper.Serialize(s);

            s.Delete(silly);
            s.Flush();

            Release(s);
            Done();
        }
示例#4
0
        public void SerializationOnAfterStatementAggressiveRelease()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            Prepare();
            ISession s     = GetSessionUnderTest();
            Silly    silly = new Silly("silly");

            s.Save(silly);

            // this should cause the CM to obtain a connection, and then Release it
            s.Flush();

            // We should be able to serialize the session at this point...
            SerializationHelper.Serialize(s);

            s.Delete(silly);
            s.Flush();

            Release(s);
            Done();
        }
        public async Task PocoComponentTuplizerOfDeserializedConfiguration_Instantiate_UsesReflectonOptimizerAsync()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            MemoryStream    configMemoryStream = new MemoryStream();
            BinaryFormatter writer             = new BinaryFormatter();

            writer.Serialize(configMemoryStream, cfg);

            configMemoryStream.Seek(0, SeekOrigin.Begin);
            BinaryFormatter reader                        = new BinaryFormatter();
            Configuration   deserializedConfig            = (Configuration)reader.Deserialize(configMemoryStream);
            ISessionFactory factoryFromDeserializedConfig = deserializedConfig.BuildSessionFactory();

            using (ISession deserializedSession = factoryFromDeserializedConfig.OpenSession())
                using (deserializedSession.BeginTransaction())
                {
                    ComponentTestReflectionOptimizer.IsCalledForComponent = false;
                    await(deserializedSession.Query <Entity>().SingleAsync());
                    Assert.That(ComponentTestReflectionOptimizer.IsCalledForComponent, Is.True);
                }
        }
示例#6
0
 public ActionResult AllResults(AllResultsModel model)
 {
     if (!ModelState.IsValid)
     {
         ViewBag.ShowResults = false;
         return(View());
     }
     using (var dbMain = new TestsContext()) {
         ViewBag.Message     = "Search for test results";
         ViewBag.ShowResults = true;
         var res = dbMain.Tests.Where(x => x.RootHost.IndexOf(model.Hostname) != -1)
                   .OrderByDescending(x => x.TimeStart)
                   .Select(x => new TestResult()
         {
             Id          = x.Id,
             Url         = x.RootHost,
             PagesCount  = x.PageInfos.Count,
             ErrorsCount = x.PageInfos.Where(y => y.Status != 200).Count(),
             AvgTime     = x.PageInfos.Where(y => y.AvgTime < 99999.00).DefaultIfEmpty().Average(y => y.AvgTime)
         });
         ViewBag.data = res.ToArray();
     }
     return(View());
 }
示例#7
0
 public DashboardController(TestsContext context)
 {
     _context = context;
 }
 public UpdateTestHandler(TestsContext db)
 {
     _db = db;
 }
 public GetAllQuestionsHandler(TestsContext db)
 {
     _db = db;
 }
示例#10
0
 public SubjectsService(TestsContext testsContext) => _testsContext = testsContext;
示例#11
0
 private void DoWork()
 {
     using (var dbMain = new TestsContext()) {
         var root = new Test()
         {
             RootHost  = RootUrl.Host,
             TimeStart = DateTime.Now.Ticks
         };
         dbMain.Tests.Add(root);
         if (!Force)
         {
             DownloadSiteMap();
         }
         if (!UsedSiteMap)
         {
             _pages.Enqueue(RootUrl);
         }
         while (_pages.Count != 0 && WorkInProgress && PagesChecked < MaxPagesCount)
         {
             Uri currentUri;
             lock (_syncRootQueue) {
                 currentUri = _pages.Dequeue();
             }
             List <float> results = new List <float>(RequestsPerPage);
             long         time    = 0;
             string       content = "";
             try {
                 content = SendRequest(currentUri, false, out time);
             } catch (WebException exception) {
                 var response = exception.Response as HttpWebResponse;
                 if (response != null)
                 {
                     OnPageStateChanged(new PageStateChangedEventArgs()
                     {
                         MinTime    = 99999,
                         AvgTime    = 99999,
                         MaxTime    = 99999,
                         CurrentUrl = currentUri.ToString(),
                         Status     = (int)response.StatusCode
                     });
                     root.PageInfos.Add(new Page()
                     {
                         AvgTime = 99999,
                         MaxTime = 99999,
                         MinTime = 99999,
                         PageUrl = currentUri.ToString(),
                         Result  = root,
                         Status  = (int)response.StatusCode
                     });
                     dbMain.SaveChanges();
                 }
                 OnPageAnalyzeCompleted();
                 PagesChecked++;
                 if (!Force)
                 {
                     Thread.Sleep(500);
                 }
                 continue;
             } catch (Exception) {
                 continue;
             }
             if (string.IsNullOrEmpty(content))
             {
                 continue;
             }
             Task urlsReader = null;
             if (!UsedSiteMap)
             {
                 urlsReader = ReadUrls(content, currentUri);
             }
             results.Add((float)time / TimeSpan.TicksPerMillisecond);
             for (int i = 1; i < RequestsPerPage && WorkInProgress; i++)
             {
                 if (!Force)
                 {
                     Thread.Sleep(500);
                 }
                 try {
                     content = SendRequest(currentUri, false, out time);
                 } catch (WebException) {                            // for DOS filters
                     for (int j = 0; j < 100 && WorkInProgress; j++) // in case client want to abort job but dont wanna wait 10 secs
                     {
                         Thread.Sleep(100);
                     }
                     continue;
                 } catch (Exception) {
                     continue;
                 }
                 results.Add((float)time / TimeSpan.TicksPerMillisecond);
                 OnPageStateChanged(new PageStateChangedEventArgs()
                 {
                     MinTime    = results.Min(),
                     AvgTime    = results.Average(),
                     MaxTime    = results.Max(),
                     CurrentUrl = currentUri.ToString(),
                     Status     = 200
                 });
             }
             OnPageAnalyzeCompleted();
             root.PageInfos.Add(new Page()
             {
                 AvgTime = results.Average(),
                 MaxTime = results.Max(),
                 MinTime = results.Min(),
                 PageUrl = currentUri.ToString(),
                 Result  = root,
                 Status  = 200
             });
             dbMain.SaveChanges();
             PagesChecked++;
             urlsReader?.Wait();
             if (!Force)
             {
                 Thread.Sleep(1000);
             }
         }
         root.TimeStop = DateTime.Now.Ticks;
         dbMain.SaveChanges();
     }
     OnWorkerStopped();
 }
示例#12
0
 public TestsService(TestsContext testsContext) => _testsContext = testsContext;
 public GetQuestionHandler(TestsContext db)
 {
     _db = db;
 }
示例#14
0
 /// <summary>
 /// Speichert den über Dependency Injection übergebenen DB Context.
 /// Dabei ist in Startup.cs in ConfigureServices() die Zeile
 ///     services.AddDbContext<Model.TestsContext>();
 /// einzufügen.
 /// </summary>
 public PupilController(TestsContext context)
 {
     _context = context;
 }
        public async Task ExecutableCriteriaAsync()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            // All query below don't have sense, are only to test if all needed classes are serializable

            // Basic criterion
            DetachedCriteria dc = DetachedCriteria.For(typeof(Student))
                                  .Add(Expression.Between("Name", "aaaaa", "zzzzz"))
                                  .Add(Expression.EqProperty("Name", "Name"))
                                  .Add(Expression.Ge("Name", "a"))
                                  .Add(Expression.GeProperty("Name", "Name"))
                                  .Add(Expression.Gt("Name", "z"))
                                  .Add(Expression.GtProperty("Name", "Name"))
                                  .Add(Expression.IdEq(1))
                                  .Add(Expression.In("Name", new string[] { "Gavin", "Ralph" }))
                                  .Add(Expression.InsensitiveLike("Name", "GAVIN"))
                                  .Add(Expression.IsEmpty("Enrolments"))
                                  .Add(Expression.IsNotEmpty("Enrolments"))
                                  .Add(Expression.IsNotNull("PreferredCourse"))
                                  .Add(Expression.IsNull("PreferredCourse"))
                                  .Add(Expression.Le("Name", "a"))
                                  .Add(Expression.LeProperty("Name", "Name"))
                                  .Add(Expression.Lt("Name", "z"))
                                  .Add(Expression.LtProperty("Name", "Name"))
                                  .Add(Expression.Like("Name", "G%"))
                                  .Add(Expression.Not(Expression.Eq("Name", "Ralph")))
                                  .Add(Expression.NotEqProperty("Name", "Name"))
                                  .AddOrder(Order.Asc("StudentNumber"))
                                  .SetProjection(Property.ForName("StudentNumber"));

            await(SerializeAndListAsync(dc));

            // Like match modes
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.Anywhere))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.End))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.Exact))
                 .Add(Expression.Like("Name", "Gavin", MatchMode.Start));

            await(SerializeAndListAsync(dc));

            // Logical Expression
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Or(Expression.Eq("Name", "Ralph"), Expression.Eq("Name", "Gavin")))
                 .Add(
                Expression.And(Expression.Gt("StudentNumber", 1L),
                               Expression.Lt("StudentNumber", 10L)));

            await(SerializeAndListAsync(dc));

            // Projections
            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.Distinct(Projections.ProjectionList()
                                                     .Add(Projections.Property("StudentNumber"), "stNumber")
                                                     .Add(Projections.Property("CourseCode"), "cCode")))
                 .Add(Expression.Lt("StudentNumber", 668L));
            await(SerializeAndListAsync(dc));

            if (TestDialect.SupportsCountDistinct)
            {
                dc = DetachedCriteria.For(typeof(Enrolment))
                     .SetProjection(Projections.Count("StudentNumber").SetDistinct());
                await(SerializeAndListAsync(dc));
            }

            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.ProjectionList()
                                .Add(Projections.Count("StudentNumber"))
                                .Add(Projections.Max("StudentNumber"))
                                .Add(Projections.Min("StudentNumber"))
                                .Add(Projections.Avg("StudentNumber")));
            await(SerializeAndListAsync(dc));

            // Junctions
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Conjunction()
                      .Add(Expression.Eq("Name", "Ralph"))
                      .Add(Expression.Eq("StudentNumber", 1L)))
                 .Add(Expression.Disjunction()
                      .Add(Expression.Eq("Name", "Ralph"))
                      .Add(Expression.Eq("Name", "Gavin")));
            await(SerializeAndListAsync(dc));

            // Subquery
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Property.ForName("StudentNumber").Eq(232L))
                 .SetProjection(Property.ForName("Name"));

            DetachedCriteria dcs = DetachedCriteria.For(typeof(Student))
                                   .Add(Subqueries.PropertyEqAll("Name", dc));

            await(SerializeAndListAsync(dc));

            // SQLCriterion
            dc = DetachedCriteria.For(typeof(Student))
                 .Add(Expression.Sql("{alias}.Name = 'Gavin'"));
            await(SerializeAndListAsync(dc));

            // SQLProjection
            dc = DetachedCriteria.For(typeof(Enrolment))
                 .SetProjection(Projections.SqlProjection("1 as constOne, count(*) as countStar",
                                                          new String[] { "constOne", "countStar" },
                                                          new IType[] { NHibernateUtil.Int32, NHibernateUtil.Int32 }));
            await(SerializeAndListAsync(dc));

            dc = DetachedCriteria.For(typeof(Student))
                 .SetProjection(
                Projections.SqlGroupProjection("COUNT({alias}.studentId), {alias}.preferredCourseCode",
                                               "{alias}.preferredCourseCode",
                                               new string[] { "studentsOfCourse", "CourseCode" },
                                               new IType[] { NHibernateUtil.Int32, NHibernateUtil.Int32 }));
            await(SerializeAndListAsync(dc));

            // Result transformers
            dc = DetachedCriteria.For(typeof(Enrolment))
                 .CreateAlias("Student", "st")
                 .CreateAlias("Course", "co")
                 .SetProjection(Projections.ProjectionList()
                                .Add(Projections.Property("st.Name"), "studentName")
                                .Add(Projections.Property("co.Description"), "courseDescription")
                                )
                 .AddOrder(Order.Desc("studentName"))
                 .SetResultTransformer(Transformers.AliasToBean(typeof(StudentDTO)));
            await(SerializeAndListAsync(dc));
        }
 public DeleteTestHandler(TestsContext db)
 {
     _db = db;
 }
示例#17
0
 public AboutTest()
 {
     _testsContext = new TestsContext();
 }
示例#18
0
        public void Serialization()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            ISession s   = OpenSession();
            Master   m   = new Master();
            Detail   d1  = new Detail();
            Detail   d2  = new Detail();
            object   mid = s.Save(m);

            d1.Master = (m);
            d2.Master = (m);
            m.AddDetail(d1);
            m.AddDetail(d2);
            if (Dialect is MsSql2000Dialect)
            {
                s.Save(d1);
            }
            else
            {
                s.Save(d1, 666L);
            }
            s.Flush();
            s.Disconnect();
            MemoryStream    stream = new MemoryStream();
            BinaryFormatter f      = new BinaryFormatter();

            f.Serialize(stream, s);
            s.Close();
            stream.Position = 0;
            Console.WriteLine(stream.Length);

            s = (ISession)f.Deserialize(stream);
            stream.Close();

            s.Reconnect();
            Master m2 = (Master)s.Load(typeof(Master), mid);

            Assert.IsTrue(m2.Details.Count == 2, "serialized state");
            foreach (Detail d in m2.Details)
            {
                Assert.IsTrue(d.Master == m2, "deserialization");
                try
                {
                    s.GetIdentifier(d);
                    s.Delete(d);
                }
                catch (Exception)
                {
                    // Why are we ignoring exceptions here? /Oskar 2014-08-24
                }
            }
            s.Delete(m2);
            s.Flush();
            s.Close();

            s   = OpenSession();
            mid = s.Save(new Master());
            object mid2 = s.Save(new Master());

            s.Flush();
            s.Disconnect();
            stream = new MemoryStream();
            f.Serialize(stream, s);
            s.Close();
            stream.Position = 0;

            s = (ISession)f.Deserialize(stream);
            stream.Close();

            s.Reconnect();
            s.Delete(s.Load(typeof(Master), mid));
            s.Delete(s.Load(typeof(Master), mid2));
            s.Flush();
            s.Close();

            s = OpenSession();
            string db = s.Connection.Database;             //force session to grab a connection

            try
            {
                stream = new MemoryStream();
                f.Serialize(stream, s);
            }
            catch (Exception e)
            {
                Assert.IsTrue(e is InvalidOperationException, "illegal state");
                s.Close();
                return;
            }
            finally
            {
                stream.Close();
            }
            Assert.IsTrue(false, "serialization should have failed");
        }
示例#19
0
 /// <summary>
 /// Konstruktor. Setzt die ASP.NET Konfiguration und den DB Context.
 /// </summary>
 /// <param name="context">Wird über Depenency Injection durch services.AddDbContext() übergeben.</param>
 /// <param name="configuration">Wird über Depenency Injection von ASP.NET übergeben.</param>
 public UserService(TestsContext context, IConfiguration configuration)
 {
     this.configuration = configuration;
     this.db            = context;
 }
 public InterestRateTest()
 {
     _testsContext = new TestsContext();
 }
示例#21
0
 public GetTestHandler(TestsContext db)
 {
     _db = db;
 }
 public AddTestQuestionsHandler(TestsContext db)
 {
     _db = db;
 }
 public CheckQuestionsAreCorrectHandler(TestsContext db)
 {
     _db = db;
 }
示例#24
0
 public CreateQuestionHandler(TestsContext db)
 {
     _db = db;
 }
 public ProjectSearcherTest()
 {
     _context = TestsContext.Default;
 }
示例#26
0
        public void Basic_CRUD_should_work()
        {
            TestsContext.AssumeSystemTypeIsSerializable();

            Assembly assembly = Assembly.Load("NHibernate.DomainModel");
            var      cfg      = new Configuration();

            if (TestConfigurationHelper.hibernateConfigFile != null)
            {
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            }
            cfg.AddResource("NHibernate.DomainModel.ParentChild.hbm.xml", assembly);

            var formatter    = new BinaryFormatter();
            var memoryStream = new MemoryStream();

            formatter.Serialize(memoryStream, cfg);
            memoryStream.Position = 0;
            cfg = formatter.Deserialize(memoryStream) as Configuration;
            Assert.That(cfg, Is.Not.Null);

            var export = new SchemaExport(cfg);

            export.Execute(true, true, false);
            var    sf = cfg.BuildSessionFactory();
            object parentId;
            object childId;

            using (var session = sf.OpenSession())
                using (var tran = session.BeginTransaction())
                {
                    var parent = new Parent();
                    var child  = new Child();
                    parent.Child = child;
                    parent.X     = 9;
                    parent.Count = 5;
                    child.Parent = parent;
                    child.Count  = 3;
                    child.X      = 4;
                    parentId     = session.Save(parent);
                    childId      = session.Save(child);
                    tran.Commit();
                }

            using (ISession session = sf.OpenSession())
            {
                var parent = session.Get <Parent>(parentId);
                Assert.That(parent.Count, Is.EqualTo(5));
                Assert.That(parent.X, Is.EqualTo(9));
                Assert.That(parent.Child, Is.Not.Null);
                Assert.That(parent.Child.X, Is.EqualTo(4));
                Assert.That(parent.Child.Count, Is.EqualTo(3));
                Assert.That(parent.Child.Parent, Is.EqualTo(parent));
            }

            using (ISession session = sf.OpenSession())
                using (ITransaction tran = session.BeginTransaction())
                {
                    var p = session.Get <Parent>(parentId);
                    var c = session.Get <Child>(childId);
                    session.Delete(c);
                    session.Delete(p);
                    tran.Commit();
                }

            using (ISession session = sf.OpenSession())
            {
                var p = session.Get <Parent>(parentId);
                Assert.That(p, Is.Null);
            }

            TestCase.DropSchema(true, export, (ISessionFactoryImplementor)sf);
        }
示例#27
0
 /// <summary>
 /// Konstruktor. Setzt den DB Context.
 /// </summary>
 /// <param name="context">Der über services.AddDbContext() gesetzte Context.</param>
 public ClassesController(TestsContext context)
 {
     this._context = context;
 }
示例#28
0
 public GetAllTestsHandler(TestsContext db)
 {
     _db = db;
 }
示例#29
0
 public SchoolclassesController(TestsContext context)
 {
     _context = context;
 }
 public CreateTestHandler(TestsContext db)
 {
     _db = db;
 }