Beispiel #1
0
        /// <summary>
        /// This is the main entry point for the SHRD host service.
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Globals.InitializeProgram(exePath, "Self Hosted Remote Desktop", true);
            PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "SHRD_Log.txt");

            FileInfo fiExe = new FileInfo(exePath);

            Environment.CurrentDirectory = fiExe.Directory.FullName;

            System.Windows.Forms.Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException       += CurrentDomain_UnhandledException;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            //byte[] buf = new byte[4];
            //ByteUtil.WriteFloat(5, buf, 0);
            //float f = ByteUtil.ReadFloat(buf, 0);
            //Logger.Info(f.ToString());

            if (Environment.UserInteractive)
            {
                bool cmd = args.Length > 0 && args[0] == "cmd";
                if (cmd || Debugger.IsAttached)
                {
                    BPUtil.NativeWin.WinConsole.Initialize();
                    Logger.logType = LoggingMode.Console | LoggingMode.File;
                    Logger.Info("Console environment detected. Logging to console is enabled.");
                    ServiceWrapper.Initialize();
                    ServiceWrapper.Start();
                    do
                    {
                        Console.WriteLine("Type \"exit\" to close");
                    }while (Console.ReadLine().ToLower() != "exit");
                    ServiceWrapper.Stop();
                    return;
                }
                else
                {
                    Logger.logType = LoggingMode.File;
                }

                string             Title           = "SelfHostedRemoteDesktop " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " Service Manager";
                string             ServiceName     = "SelfHostedRemoteDesktop";
                ButtonDefinition   btnStartCmdTest = new ButtonDefinition("Test w/console", btnStartCmdTest_Click);
                ButtonDefinition[] customButtons   = new ButtonDefinition[] { btnStartCmdTest };

                System.Windows.Forms.Application.Run(new ServiceManager(Title, ServiceName, customButtons));
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new SelfHostedRemoteDesktopSvc()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
Beispiel #2
0
        public void LastIpLookedUpTest()
        {
            var target = new PrivateAccessor(new ConcreteService());
            var result = target.CallMethod("LogUserInfo", "123.123.123.123");

            Assert.AreEqual("123.123.123.123", target.GetField("_lastIpLookedUp"));
        }
Beispiel #3
0
        static void Main()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Globals.Initialize(exePath);
            PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "Advisor_Log.txt");

            FileInfo fiExe = new FileInfo(exePath);

            Environment.CurrentDirectory = fiExe.Directory.FullName;

            settings = new AdvisorSettings();
            settings.Load();
            if (string.IsNullOrWhiteSpace(settings.secret))
            {
                settings.secret = Hash.GetSHA256Hex(Guid.NewGuid().ToString());
                settings.Save();
            }
            settings.SaveIfNoExist();

            RegistryUtil.Force32BitRegistryAccess = settings.bi32OnWin64;

            AutoFixBad32BitSetting();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        public void Match_ShouldRemoveSingleUseRulesThatWereUsed()
        {
            IEnumerable <Transaction> testTransactions = StatementModelTestData.TestData1().Transactions;
            var testMatchingRules = new List <MatchingRule>
            {
                new SingleUseMatchingRule(this.mockBucketRepo)
                {
                    Amount     = -95.15M,
                    And        = true,
                    BucketCode = StatementModelTestData.PhoneBucket.Code,
                    Reference1 = "skjghjkh",
                    MatchCount = 1 // Artificially set to simulate a match
                },
                new MatchingRule(this.mockBucketRepo)
                {
                    Amount     = -11.11M,
                    BucketCode = StatementModelTestData.CarMtcBucket.Code
                }
            };

            this.mockMatchMaker.Setup(m => m.Match(testTransactions, testMatchingRules)).Returns(true);
            this.mockBucketRepo.GetOrCreateNew(TestDataConstants.PowerBucketCode, () => new SpentMonthlyExpenseBucket(TestDataConstants.PowerBucketCode, "Foo"));
            this.mockBucketRepo.GetOrCreateNew(TestDataConstants.PhoneBucketCode, () => new SpentMonthlyExpenseBucket(TestDataConstants.PhoneBucketCode, "Foo"));
            PrivateAccessor.InvokeMethod(this.subject, "InitialiseTheRulesCollections", testMatchingRules);
            PrivateAccessor.SetField <TransactionRuleService>(this.subject, "rulesStorageKey", "lksjgjklshgjkls");

            var success = this.subject.Match(testTransactions);

            Assert.IsTrue(success);
            Assert.IsFalse(this.subject.MatchingRules.Any(r => r is SingleUseMatchingRule));
        }
        /// <summary>
        ///     Makes sure that the IsNew property on LedgerBook EntryLines is not set to true, as it will be when they are newly
        ///     created.
        ///     Also ensures the StoredInAccount property for each ledger is set.
        /// </summary>
        internal static void Finalise(LedgerBook book, bool unlock = false)
        {
            if (book.Reconciliations.None())
            {
                return;
            }
            var ledgers = new Dictionary <BudgetBucket, LedgerBucket>();

            foreach (LedgerEntryLine line in book.Reconciliations)
            {
                if (!unlock)
                {
                    PrivateAccessor.SetProperty(line, "IsNew", false);
                }
                foreach (LedgerEntry entry in line.Entries)
                {
                    if (!unlock)
                    {
                        PrivateAccessor.SetField(entry, "isNew", false);
                    }
                    if (entry.LedgerBucket.StoredInAccount == null)
                    {
                        entry.LedgerBucket.StoredInAccount = StatementModelTestData.ChequeAccount;
                    }
                    if (!ledgers.ContainsKey(entry.LedgerBucket.BudgetBucket))
                    {
                        ledgers.Add(entry.LedgerBucket.BudgetBucket, entry.LedgerBucket);
                    }
                }
            }

            book.Ledgers = ledgers.Values;
        }
Beispiel #6
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            Globals.Initialize(Application.ExecutablePath);
            PrivateAccessor.SetStaticFieldValue(typeof(Globals), "configFilePath", Globals.WritableDirectoryBase + "IpCameraSpeedometerSettings.xml");

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            if (Environment.UserInteractive)
            {
                ServiceWrapper.settings.SaveIfNoExist(Globals.ConfigFilePath);
                string           Title            = "IpCameraSpeedometer " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " Service Manager";
                ButtonDefinition btnConfiguration = new ButtonDefinition("Configuration", btnConfiguration_Click);
                ServiceManager   serviceManager   = new ServiceManager(Title, ServiceWrapper.settings.ServiceName, new ButtonDefinition[] { btnConfiguration }, new ServiceName(ServiceWrapper.settings.ServiceName, ServiceNameChange));
                Application.Run(serviceManager);
                while (ServiceWrapper.restartServiceManager)
                {
                    ServiceWrapper.restartServiceManager = false;
                    serviceManager = new ServiceManager(Title, ServiceWrapper.settings.ServiceName, new ButtonDefinition[] { btnConfiguration }, new ServiceName(ServiceWrapper.settings.ServiceName, ServiceNameChange));
                    Application.Run(serviceManager);
                }
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new IpCameraSpeedometer()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
        public void SqlTraceIsSentToAggregator()
        {
            var commandText      = "Select * from Table1";
            var duration         = TimeSpan.FromMilliseconds(500);
            var datastoreSegment = TestTransactions.BuildSegment(null, DatastoreVendor.MSSQL, "Table1", commandText, new TimeSpan(), duration, null, null, null, "myhost", "myport", "mydatabase");
            var segments         = Enumerable.Empty <Segment>();

            segments = segments.Concat(new[] { datastoreSegment });

            var transaction     = TestTransactions.CreateTestTransactionWithSegments(segments);
            var transactionName = _transactionMetricNameMaker.GetTransactionMetricName(transaction.TransactionName);

            Mock.Arrange(() => _configuration.SlowSqlEnabled).Returns(true);
            Mock.Arrange(() => _configuration.SqlExplainPlanThreshold).Returns(TimeSpan.FromMilliseconds(100));

            var privateTransactionTransformer = new PrivateAccessor(_transactionTransformer);
            var args = new object[] { transaction, transactionName };

            privateTransactionTransformer.CallMethod("Transform", args);

            var privateSqlTraceStatsInAggregator = new PrivateAccessor(_sqlTraceAggregator).GetField("_sqlTraceStats");
            var privateSqlTraceStatsCollection   = (SqlTraceStatsCollection)privateSqlTraceStatsInAggregator;
            var tracesCount = ((IDictionary <long, SqlTraceWireModel>)privateSqlTraceStatsCollection.Collection).Count;

            Assert.AreEqual(tracesCount, 1);
        }
Beispiel #8
0
        public void TestPrivateMethodGetTotalAmount()
        {
            //Arrange
            using (JMRadForm form = new JMRadForm())
            {
                List <Order> orders = form.GetData();
                form.Grid.DataSource = orders;

                //Create a mocked instance of your class under test
                var orderMock = Mock.Create <Order>();
                //Arrange your expectations
                Mock.NonPublic.Arrange <float>(orderMock, "GetTotalAmount").Returns(5f);

                // Act
                //Create new PrivateAccessor with the mocked instance as an argument
                var inst = new PrivateAccessor(orderMock);

                //Call the non-public method by giving its exact name
                var actual = inst.CallMethod("GetTotalAmount");

                // Assert
                //Finally, you can assert against its expected return value
                Assert.AreEqual(5f, actual);
            }
        }
Beispiel #9
0
        public static void MainMethod()
        {
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Globals.Initialize(exePath);
            PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "MJpegCameraErrors.txt");

            if (Environment.UserInteractive)
            {
                string             Title         = "CameraProxy " + CameraProxyGlobals.Version + " Service Manager";
                string             ServiceName   = "MJpegCameraProxy";
                ButtonDefinition   btnCmd        = new ButtonDefinition("Command Line Test", btnCmd_Click);
                ButtonDefinition[] customButtons = new ButtonDefinition[] { btnCmd };

                Application.Run(new ServiceManager(Title, ServiceName, customButtons));
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new CameraProxyService()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
Beispiel #10
0
        public void TestLogUserInfo()
        {
            var target = new PrivateAccessor(new ConcreteService());
            var result = target.CallMethod("LogUserInfo", "172.217.1.174");

            Assert.IsInstanceOfType(result, typeof(bool));
            Assert.IsTrue((bool)result);
        }
Beispiel #11
0
        public void LogPropertyTest()
        {
            var target = new PrivateAccessor(new ConcreteService());
            var log    = target.GetProperty("_log");

            Assert.IsNotNull(log);
            Assert.AreEqual("NLog.Logger", ((NLog.Logger)log).ToString());
        }
Beispiel #12
0
        public void JustMock_Has_Reflection_Helper_Methods_To_Set_Fields_Of_Static_Classes()
        {
            var configurationHolderAccessor = PrivateAccessor.ForType(typeof(StaticClassWithGetterOnly));

            configurationHolderAccessor.SetField("_value", "Geänderter Wert");

            StaticClassWithGetterOnly.Value.Should().Be("Geänderter Wert");
        }
Beispiel #13
0
        private void SaveSetup()
        {
            PrivateAccessor.SetField(this.subject, "budgetAnalyserDatabase", new Mock <ApplicationDatabase>().Object);
            this.mockService1.Setup(m => m.ValidateModel(It.IsAny <StringBuilder>())).Returns(true);
            this.mockService2.Setup(m => m.ValidateModel(It.IsAny <StringBuilder>())).Returns(true);

            this.subject.NotifyOfChange(ApplicationDataType.Budget);
        }
Beispiel #14
0
 public static StatementModel WithNullBudgetBuckets(this StatementModel instance)
 {
     foreach (var txn in instance.AllTransactions)
     {
         PrivateAccessor.SetField(txn, "budgetBucket", null);
     }
     return(instance);
 }
        internal static LedgerEntry SetTransactionsForTesting(this LedgerEntry entry, List <LedgerTransaction> transactions)
        {
            PrivateAccessor.SetField(entry, "transactions", transactions);
            decimal newBalance = entry.Balance + entry.NetAmount;

            entry.Balance = newBalance < 0 ? 0 : newBalance;
            return(entry);
        }
Beispiel #16
0
        public void Reconcile_ShouldNotThrow_GivenTestData1AndUnclassifiedTransactionsOutsideReconPeriod()
        {
            Transaction aTransaction = this.testDataStatement.AllTransactions.First();

            PrivateAccessor.SetField(aTransaction, "budgetBucket", null);

            Act(new DateTime(2013, 9, 15));
        }
Beispiel #17
0
        public void Close_ShouldCloseAllServices()
        {
            PrivateAccessor.SetField(this.subject, "budgetAnalyserDatabase", new Mock <ApplicationDatabase>().Object);

            this.subject.Close();

            this.mockService1.Verify(m => m.Close());
            this.mockService2.Verify(m => m.Close());
        }
        public void TestInitialise()
        {
            this.testData = new FixedBudgetProjectBucket(FixedProjectCode, "Foo bar dum-de-dum", 1000);
            PrivateAccessor.SetProperty(this.testData, "Created", this.testDataCreatedDate);

            var subject = new Mapper_BudgetBucketDto_BudgetBucket(new BudgetBucketFactory());

            this.result = subject.ToDto(this.testData);
        }
Beispiel #19
0
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main()
		{
			string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
			Globals.Initialize(exePath);
			PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "BiUpdateHelper_Log.txt");

			FileInfo fiExe = new FileInfo(exePath);
			Environment.CurrentDirectory = fiExe.Directory.FullName;

			settings = new BiUpdateHelperSettings();
			settings.Load();
			if (string.IsNullOrWhiteSpace(settings.secret))
			{
				settings.secret = Hash.GetSHA256Hex(Guid.NewGuid().ToString());
				settings.Save();
			}
			settings.SaveIfNoExist();

			RegistryUtil.Force32BitRegistryAccess = settings.bi32OnWin64;

			AutoFixBad32BitSetting();

			PerformanceData.PerformanceDataCollector.onReportUploaded = () =>
			{
				settings.Load();
				settings.lastUsageReportAt = TimeUtil.GetTimeInMsSinceEpoch();
				settings.Save();
			};
			PerformanceData.PerformanceDataCollector.getSecretString = () =>
			{
				return Program.settings.secret;
			};

			if (Environment.UserInteractive)
			{
				string Title = "BiUpdateHelper " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + " Service Manager";
				string ServiceName = "BiUpdateHelper";
				ButtonDefinition btnRegKey = new ButtonDefinition("BI Registration Info", btnRegkey_Click);
				ButtonDefinition btnSettings = new ButtonDefinition("Edit Service Settings", btnSettings_Click);
				ButtonDefinition btnCameraConfigLinks = new ButtonDefinition("Camera Config Links", btnCameraConfigLinks_Click);
				ButtonDefinition btnRegistryBackupNow = new ButtonDefinition("Take Registry Backup Now", btnRegistryBackupNow_Click);
				ButtonDefinition btnPerfData = new ButtonDefinition("Performance Data", btnPerfData_Click);
				ButtonDefinition[] customButtons = new ButtonDefinition[] { btnRegKey, btnSettings, btnCameraConfigLinks, btnRegistryBackupNow, btnPerfData };

				System.Windows.Forms.Application.Run(new ServiceManager(Title, ServiceName, customButtons));
			}
			else
			{
				ServiceBase[] ServicesToRun;
				ServicesToRun = new ServiceBase[]
				{
					new MainSvc()
				};
				ServiceBase.Run(ServicesToRun);
			}
		}
Beispiel #20
0
        public MJpegWrapper()
        {
            if (Environment.UserInteractive)
            {
                Logger.logType = LoggingMode.Console | LoggingMode.File;
            }
            string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            Globals.Initialize(exePath);
            PrivateAccessor.SetStaticFieldValue(typeof(Globals), "errorFilePath", Globals.WritableDirectoryBase + "MJpegCameraErrors.txt");

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            System.Net.ServicePointManager.Expect100Continue      = false;
            System.Net.ServicePointManager.DefaultConnectionLimit = 640;

            cfg = new ProxyConfig();
            if (File.Exists(CameraProxyGlobals.ConfigFilePath))
            {
                cfg.Load(CameraProxyGlobals.ConfigFilePath);
            }
            else
            {
                if (cfg.users.Count == 0)
                {
                    cfg.users.Add(new User("admin", "admin", 100));
                }
                cfg.Save(CameraProxyGlobals.ConfigFilePath);
            }
            SimpleHttpLogger.RegisterLogger(Logger.httpLogger);
            bool killed = false;

            try
            {
                foreach (var process in Process.GetProcessesByName("live555ProxyServer"))
                {
                    try
                    {
                        process.Kill();
                        killed = true;
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex, "Trying to kill existing live555ProxyServer process");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Debug(ex, "Trying to iterate through existing live555ProxyServer processes");
            }
            if (killed)
            {
                Thread.Sleep(500);
            }
        }
Beispiel #21
0
        public void PrivateAccessor_ShouldCallPrivateMethod()
        {
            // ACT
            // Wrapping the instance holding the private method.
            var inst = new PrivateAccessor(new ClassWithNonPublicMembers());
            // Calling the non-public method by giving its exact name.
            var actual = inst.CallMethod("MePrivate");

            // ASSERT
            Assert.AreEqual(1000, actual);
        }
Beispiel #22
0
        public void PrivateAccessor_ShouldCallPrivateStaticMethod()
        {
            // ACT
            // Wrapping the instance holding the private method by type.
            var inst = PrivateAccessor.ForType(typeof(ClassWithNonPublicMembers));
            // Calling the non-public static method by giving its exact name.
            var actual = inst.CallMethod("MeStaticPrivate");

            // ASSERT
            Assert.AreEqual(2000, actual);
        }
        private void ArrangeForCreateNewRule()
        {
            this.mockRuleFactory
            .Setup(m => m.CreateNewSingleUseRule(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string[]>(), It.IsAny <string>(), It.IsAny <decimal?>(), It.IsAny <bool>()))
            .Returns(new SingleUseMatchingRule(this.mockBucketRepo)
            {
                BucketCode = "Foo"
            });

            // This is to bypass validating that Initialise has happened when adding a new rule
            PrivateAccessor.SetField <TransactionRuleService>(this.subject, "rulesStorageKey", "Anything");
        }
Beispiel #24
0
        public void PrivateAccessor_ShouldGetSetProperty()
        {
            // ACT
            // Wrapping the instance holding the private property.
            var inst = new PrivateAccessor(new ClassWithNonPublicMembers());

            // Setting the value of the private property.
            inst.SetProperty("Prop", 555);

            // ASSERT - Asserting with getting the value of the private property.
            Assert.AreEqual(555, inst.GetProperty("Prop"));
        }
Beispiel #25
0
 static TypeUtil()
 {
     BODY_START        = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "BODY_START");
     BODY_END          = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "BODY_END");
     FOLDER_BODY_START = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "FOLDER_BODY_START");
     FOLDER_BODY_END   = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "FOLDER_BODY_END");
     WEAR_START        = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "WEAR_START");
     WEAR_END          = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "WEAR_END");
     SET_START         = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "SET_START");
     SET_END           = PrivateAccessor.Get <int>(typeof(MPN_TYPE_RANGE), "SET_END");
     PARTS_COLOR_START = PrivateAccessor.Get <MaidParts.PARTS_COLOR>(typeof(MaidParts.PARTS_COLOR), "NONE") + 1;
     PARTS_COLOR_END   = PrivateAccessor.Get <MaidParts.PARTS_COLOR>(typeof(MaidParts.PARTS_COLOR), "MAX") - 1;
 }
        public void GlobalCache_ReplaceValueInConcurrentAccess_CorrectData(int iterationNumber, int totalRepeats)
        {
            var dummy = iterationNumber; // to clear xUnit1026 warning

            dummy = totalRepeats;

            //arrange
            _config.HeadersInFirstInputRow = true;
            _config.GlobalCacheElements    = new string[] { "STR|Exes", "DT|5/12/2011" };
            _config.ClusterMarker          = (r, pr, n) =>
            {
                r.GlobalCache.ReplaceValue <string, string>("STR", s => s + "X");
                return(true);
            };
            _config.TransformerType        = TransformerType.ClusterFilter;
            _config.ClusterFilterPredicate = c =>
            {
                c.GlobalCache.ReplaceValue <DateTime, DateTime>("DT", d => d.AddMonths(1));
                return(true);
            };
            _config.RouterType   = RouterType.PerRecord;
            _config.RecordRouter = (r, c) =>
            {
                r.GlobalCache.ReplaceValue <string, string>("STR", s => s + "x");
                r.GlobalCache.ReplaceValue <DateTime, DateTime>("DT", d => d.AddDays(1));
                return(1);
            };

            var orchestrator      = new EtlOrchestrator(_config);
            var orchestratorPA    = new PrivateAccessor(orchestrator);
            var unclusteringBlock = (TransformManyBlock <KeyValCluster, KeyValRecord>)orchestratorPA.GetField("_unclusteringBlock");

            unclusteringBlock.LinkTo(_resultsExtractor, new DataflowLinkOptions {
                PropagateCompletion = true
            });

            //act
            var result = orchestrator.ExecuteAsync().Result;

            _resultsExtractor.Completion.Wait();

            //assert
            result.CompletionStatus.Should().Be(CompletionStatus.IntakeDepleted);
            result.RowsRead.Should().Be(4);
            result.ClustersRead.Should().Be(3);
            result.ClustersWritten.Should().Be(3);
            result.RowsWritten.Should().Be(0); //no output invoked during the test

            ((string)result.GlobalCache["STR"]).ToLower().Should().Be("exesxxxxxx");
            ((DateTime)result.GlobalCache["DT"]).Should().Be(new DateTime(2011, 8, 15));
        }
        private DynamicMetaObject DoBindSetMember(ExpressionContainer wrapper, Type returnType, string memberName, bool ignoreCase, DynamicMetaObject value)
        {
            var valueExpr = wrapper.Expression;
            var property  = PrivateAccessor.ResolveProperty(valueExpr.Type, memberName, ignoreCase, new object[0], !wrapper.IsStatic, value.Value, getter: false);

            if (property == null)
            {
                ThrowMissingMemberException(valueExpr.Type, memberName);
            }

            var memberExpr = Expression.Assign(Expression.Property(!wrapper.IsStatic ? valueExpr : null, property), FromArg(value));

            return(CreateRecorder(memberExpr, returnType));
        }
Beispiel #28
0
        public void TestBadIpAddress()
        {
            var target = new PrivateAccessor(new ConcreteService());

            try
            {
                var result = target.CallMethod("LogUserInfo", "");
                Assert.Fail("Should have failed");
            }
            catch (Exception ex)
            {
                Assert.AreEqual(ex.Message, "The call to ipinfo faied");
            }
        }
        public void SqlTracesCollectedMetricIsAccurate()
        {
            var generatedMetrics = new MetricStatsDictionary <string, MetricDataWireModel>();

            Mock.Arrange(() => _metricAggregator.Collect(Arg.IsAny <TransactionMetricStatsCollection>())).DoInstead <TransactionMetricStatsCollection>(txStats => generatedMetrics = txStats.GetUnscopedForTesting());

            Mock.Arrange(() => _configuration.SlowSqlEnabled).Returns(true);
            Mock.Arrange(() => _configuration.SqlExplainPlanThreshold).Returns(TimeSpan.FromMilliseconds(100));
            var segments = new List <Segment>();

            int nextId         = 0;
            var txSegmentState = Mock.Create <ITransactionSegmentState>();

            Mock.Arrange(() => txSegmentState.AttribDefs).Returns(() => new AttributeDefinitions(new AttributeFilter(new AttributeFilter.Settings())));
            Mock.Arrange(() => txSegmentState.ParentSegmentId()).Returns(() =>
                                                                         nextId == 0 ? (int?)null : nextId);
            Mock.Arrange(() => txSegmentState.CallStackPush(Arg.IsAny <Segment>())).Returns(() => ++ nextId);

            var commandText       = "Select * from Table1";
            var duration          = TimeSpan.FromMilliseconds(500);
            var datastoreSegment1 = TestTransactions.BuildSegment(txSegmentState, DatastoreVendor.MSSQL, "Table1", commandText, new TimeSpan(), duration, null, null, null, "myhost", "myport", "mydatabase");

            segments.Add(datastoreSegment1);

            commandText = "Select * from Table2";
            duration    = TimeSpan.FromMilliseconds(1000);
            var datastoreSegment2 = TestTransactions.BuildSegment(txSegmentState, DatastoreVendor.MSSQL, "Table1", commandText, new TimeSpan(), duration, null, null, null, "myhost", "myport", "mydatabase");

            segments.Add(datastoreSegment2);

            commandText = "Select * from Table2";
            duration    = TimeSpan.FromMilliseconds(900);
            var datastoreSegment3 = TestTransactions.BuildSegment(txSegmentState, DatastoreVendor.MSSQL, "Table1", commandText, new TimeSpan(), duration, null, null, null, "myhost", "myport", "mydatabase");

            segments.Add(datastoreSegment3);

            var transaction     = TestTransactions.CreateTestTransactionWithSegments(segments);
            var transactionName = _transactionMetricNameMaker.GetTransactionMetricName(transaction.TransactionName);

            var privateTransactionTransformer = new PrivateAccessor(_transactionTransformer);
            var args = new object[] { transaction, transactionName };

            privateTransactionTransformer.CallMethod("Transform", args);

            string sqlTracesCollectedMetricName = "Supportability/SqlTraces/TotalSqlTracesCollected";

            Assert.IsTrue(generatedMetrics.TryGetValue(sqlTracesCollectedMetricName, out MetricDataWireModel data));
            Assert.AreEqual(3, data.Value0);
        }
Beispiel #30
0
        public void GetNumberOfPeople_TotalPeopleGreaterThenNotInterest_Positive()
        {
            //Arrange
            IManual manual = new Mock <IManual>().Object;
            Order   order  = new Order {
                NumberOfPeople = 100, NumberOfPeopleNotInterest = 50
            };
            var target = new PrivateAccessor(new JuiceBuilder(manual));

            //Act
            var original = target.CallMethod("GetNumberOfPeople", order);

            //Assert
            Assert.AreEqual(original, 50);
        }