Пример #1
0
        public IAsyncResult BeginExecuteScalar(AsyncCallback callback)
        {
            var asyncContext = new AsyncContext
            {
                InitiallyClosed = _connection.State == System.Data.ConnectionState.Closed,
                StartTime       = PerformanceTimer.TimeNow
            };

            try
            {
                if (asyncContext.InitiallyClosed)
                {
                    _connection.Open();
                }
                asyncContext.Result = _command.ExecuteScalar();
                _repository.RecordSuccess(this, PerformanceTimer.TicksToSeconds(PerformanceTimer.TimeNow - asyncContext.StartTime));
                if (asyncContext.InitiallyClosed)
                {
                    _connection.Close();
                }
            }
            catch (Exception ex)
            {
                _repository.RecordFailure(this);
                _errorReporter.ReportError(ex, "Failed to ExecuteScalar on PostgrSql " + _repository.Name, _repository, this);
                throw;
            }
            return(new SyncronousResult(asyncContext, callback));
        }
Пример #2
0
        public void SortedTests()
        {
            Console.WriteLine("<<< Generally ascending data >>>");

            var r = new Random(seed);

            int[] a     = new int[maxSize];
            int[] b     = new int[maxSize];
            int   value = int.MinValue;

            Console.WriteLine("Preparing...");
            for (int i = 0; i < maxSize; i++)
            {
                value =
                    r.Next(100) < 80
                                        ? value + r.Next(100)
                                        : value - r.Next(100);
                a[i] = b[i] = value;
            }

            Console.WriteLine("Sorting...");
            PerformanceTimer.Debug("builtin", 1, () => Array.Sort(b, Compare), maxSize);
            PerformanceTimer.Debug("timsort", 1, () => a.TimSort(Compare), maxSize);

            Console.WriteLine("Testing...");
            for (int i = 0; i < maxSize; i++)
            {
                Assert.AreEqual(a[i], b[i]);
            }
        }
Пример #3
0
        private static void RunPuzzleA()
        {
            // Intro message.
            Console.WriteLine("--- Begin Day 10 - Puzzle A ---");
            Console.WriteLine();

            // Prompt for input.
            Console.Write("Enter number of elements: ");
            int numberOfElements = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter puzzle input: ");
            string lengths = Console.ReadLine();

            PerformanceTimer.Start();

            int result = PuzzleA.HashGenerator.GenerateHashFromLengths(
                numberOfElements,
                lengths);

            PerformanceTimer.Stop();

            // Display results.
            Console.WriteLine();
            Console.WriteLine($"Puzzle A result: {result}");
            PerformanceTimer.LogTime();

            Console.WriteLine();
        }
Пример #4
0
        private static void MapCurrentFlowResidualOutput(Output output)
        {
            Dictionary <string, OutputMeasurement> currentFlowResiduals = m_network.Model.CurrentResidualOutput.ToDictionary(x => x.Key, x => x);

            PerformanceTimer.Reset();
            PerformanceTimer.Start();
            for (int i = 0; i < output.OutputMeta.CurrentFlowMagnitudeResiduals.Length; i++)
            {
                string            magnitudeKey = output.OutputMeta.CurrentFlowMagnitudeResiduals[i].ID.ToString();
                OutputMeasurement magnitude    = null;
                currentFlowResiduals.TryGetValue(magnitudeKey, out magnitude);
                if (magnitude != null)
                {
                    output.OutputData.CurrentFlowMagnitudeResiduals[i] = magnitude.Value;
                }

                string            angleKey = output.OutputMeta.CurrentFlowAngleResiduals[i].ID.ToString();
                OutputMeasurement angle    = null;
                currentFlowResiduals.TryGetValue(angleKey, out angle);
                if (angle != null)
                {
                    output.OutputData.CurrentFlowAngleResiduals[i] = angle.Value;
                }
            }
            PerformanceTimer.Stop();
            m_network.PerformanceMetrics.OutputPreparationExecutionTime += PerformanceTimer.ElapsedTicks;
        }
Пример #5
0
        private static void MapCircuitBreakerStatusOutput(Output output)
        {
            Dictionary <string, OutputMeasurement> circuitBreakerStatuses = new Dictionary <string, OutputMeasurement>();

            foreach (OutputMeasurement measurement in m_network.Model.CircuitBreakerStatusOutput)
            {
                if (!circuitBreakerStatuses.ContainsKey(measurement.Key))
                {
                    circuitBreakerStatuses.Add(measurement.Key, measurement);
                }
            }

            PerformanceTimer.Reset();
            PerformanceTimer.Start();
            for (int i = 0; i < output.OutputMeta.CircuitBreakerStatuses.Length; i++)
            {
                string            key    = output.OutputMeta.CircuitBreakerStatuses[i].ID.ToString();
                OutputMeasurement status = null;
                circuitBreakerStatuses.TryGetValue(key, out status);
                if (status != null)
                {
                    output.OutputData.CircuitBreakerStatuses[i] = status.Value;
                }
            }
            PerformanceTimer.Stop();
            m_network.PerformanceMetrics.OutputPreparationExecutionTime += PerformanceTimer.ElapsedTicks;
        }
        public async Task ExecuteCommand(SocketMessage message)
        {
            using (var perfTimer = new PerformanceTimer <DiscordCommandHandler>(_logger, "Dialog Processing"))
            {
                var userState = _stateHandler.GetUserOrAdd(message);
                if (_stateHandler.UserInDialog(userState))
                {
                    await _storyComs.ContinueStory(userState, message);

                    return;
                }
            }


            if (_commandToFunc.TryGetValue(_tryFindCommand(message), out Func <SocketMessage, string[], Task <CommandResult> > commandFunc))
            {
                string[] parameters = message.Content.Split(" ").ToArray();

                var commandResult = await commandFunc(message, parameters);

                if (commandResult.Success)
                {
                    if (commandResult.Embed != null)
                    {
                        await message.Channel.SendMessageAsync(commandResult.Message, false, commandResult.Embed.Build());
                    }
                    else
                    {
                        await message.Channel.SendMessageAsync(commandResult.Message);
                    }
                }
            }
        }
Пример #7
0
        private static void ExecuteProgramUnchecked(string[] args)
        {
            Dictionary <string, string> argLookup = FlagParser.Parse(args);

            if (argLookup.ContainsKey(FlagParser.GEN_DEFAULT_PROJ))
            {
                DefaultProjectGenerator         generator = new DefaultProjectGenerator(argLookup[FlagParser.GEN_DEFAULT_PROJ].Trim());
                Dictionary <string, FileOutput> project   = generator.Validate().Export();

                string directory = System.IO.Path.Combine(
                    System.IO.Directory.GetCurrentDirectory(),
                    generator.ProjectID);
                new FileOutputExporter(directory).ExportFiles(project);

                Console.WriteLine("Empty project exported to directory '" + generator.ProjectID + "/'");
            }
            else
            {
                Program.Compile(argLookup);
            }
#if DEBUG
            if (argLookup != null)
            {
                if (argLookup.ContainsKey(FlagParser.SHOW_PERFORMANCE_MARKERS))
                {
                    string summary = PerformanceTimer.GetSummary();
                    Console.WriteLine(summary);
                }
            }
#endif
        }
Пример #8
0
        public void RandomTests_NativeGuid()
        {
            Console.WriteLine("<<< Random data >>>");

            var length = maxMem / 16;
            var r      = new Random(seed);

            Guid[] a = new Guid[length];
            Guid[] b = new Guid[length];

            Console.WriteLine("Preparing...");
            for (int i = 0; i < length; i++)
            {
                a[i] = b[i] = Guid.NewGuid();
            }

            Console.WriteLine("Sorting...");
            PerformanceTimer.Debug("builtin", 1, () => Array.Sort(b), maxSize);
            PerformanceTimer.Debug("timsort", 1, () => a.TimSort(), maxSize);

            Console.WriteLine("Testing...");
            for (int i = 0; i < length; i++)
            {
                Assert.AreEqual(a[i], b[i]);
            }
        }
Пример #9
0
        static void Main(string[] args)
        {
            int[]            t1    = { 1, 2, 3, 4, 5 };
            int[]            t2    = { 4, 5, 6, 7, 8 };
            PerformanceTimer timer = new PerformanceTimer();

            timer.Start();
            Compare(t1, t2);
            timer.Stop();
            Console.Write("{0}", timer.Duration);

            PerformanceTimer timer2 = new PerformanceTimer();

            timer2.Start();
            var count = Compare(t1, t2, out int[] res);

            if (count > 0)
            {
                foreach (var n in res)
                {
                    Console.Write(n + " ");
                }
            }
            timer2.Stop();
            Console.Write("{0}", timer2.Duration);

            Console.Read();
        }
Пример #10
0
        /// <summary>
        /// starts the database process if it's not running
        /// </summary>
        /// <param name="Parameter"></param>
        public DBProcess(DBProcessParams Parameter)
        {
            m_Params = Parameter;

            m_wasRunning = IsListenerOnPort(m_Params.Port);
            
            if(!m_wasRunning)
            {
                ProcessStartInfo psi;

                // start the DB server process
                if(Debugger.IsAttached)
                { 
                    psi                         = new ProcessStartInfo(m_Params.Commandline,m_Params.Commandargs);
                    psi.WorkingDirectory        = m_Params.Workingdirectory;
                    psi.WindowStyle             = ProcessWindowStyle.Normal;
                    psi.CreateNoWindow          = false;
                    psi.RedirectStandardOutput  = false;
                    psi.UseShellExecute         = true;
                }
                else
                { 
                    psi                         = new ProcessStartInfo(m_Params.Commandline,m_Params.Commandargs);
                    psi.WorkingDirectory        = m_Params.Workingdirectory;
                    psi.WindowStyle             = ProcessWindowStyle.Hidden;
                    psi.CreateNoWindow          = true;
                    psi.RedirectStandardOutput  = false;
                    psi.UseShellExecute         = true;
                     
                }

                m_Process = System.Diagnostics.Process.Start(psi);

                // wait for db ready state
                Boolean isRunning = false;
                PerformanceTimer pc = new PerformanceTimer();

                pc.startMeasuring();
                System.Threading.Thread.Sleep(1000);

                if (!m_Process.HasExited)
                {
                    do
                    {

                        isRunning = IsListenerOnPort(m_Params.Port);

                        if(!isRunning)
                            System.Threading.Thread.Sleep(1000);
                    
                        Debug.Print("Waiting " + pc.currentMeasuring().ToString());

                    } while ((!isRunning) && ((pc.currentMeasuring() / 1000) < m_Params.DBStartTimeout));
                }
                else
                {
                    throw new Exception("can't start sql server !");
                }
            }
        }
Пример #11
0
        public void RandomTests()
        {
            Console.WriteLine("<<< Random data >>>");

            var r = new Random(seed);

            int[] a = new int[maxSize];
            int[] b = new int[maxSize];

            Console.WriteLine("Preparing...");
            for (int i = 0; i < maxSize; i++)
            {
                a[i] = b[i] = r.Next();
            }

            Console.WriteLine("Sorting...");
            PerformanceTimer.Debug("builtin", 1, () => Array.Sort(b, Compare), maxSize);
            PerformanceTimer.Debug("timsort", 1, () => a.TimSort(Compare), maxSize);

            Console.WriteLine("Testing...");
            for (int i = 0; i < maxSize; i++)
            {
                Assert.AreEqual(a[i], b[i]);
            }
        }
Пример #12
0
        private static void RunPuzzleB()
        {
            // Intro message.
            Console.WriteLine("--- Begin Day 15 - Puzzle B ---");
            Console.WriteLine();

            // Prompt for input.
            Console.Write("Enter Generator A Start Value: ");
            int generatorAStartValue = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Generator B Start Value: ");
            int generatorBStartValue = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter Number of Iterations: ");
            int numberOfIterations = Convert.ToInt32(Console.ReadLine());

            PerformanceTimer.Start();

            int result = PuzzleB.GeneratorJudge.JudgeGenerators(
                generatorAStartValue,
                generatorBStartValue,
                numberOfIterations);

            PerformanceTimer.Stop();

            // Display results.
            Console.WriteLine();
            Console.WriteLine($"Puzzle B result: {result}");
            PerformanceTimer.LogTime();

            Console.WriteLine();
        }
        public static void CheckSorting(IEnumerable <int> source, int n)
        {
            int count    = 0;
            int errCount = 0;

            PerformanceTimer.Time(() => {
                int prev = -1;
                foreach (int value in source)
                {
                    count++;
                    if (value < prev)
                    {
                        errCount++;
                    }
                    prev = value;
                }
            }, 1, "Iteraing items");

            if (count != n)
            {
                Console.WriteLine("Count mismatch: count={0}", count);
            }

            if (errCount == 0)
            {
                Console.WriteLine("Sorting OK");
            }
            else
            {
                Console.WriteLine("{0} Sorting ERRORS !!!", errCount);
                string values = "{" + String.Join(",", source) + "}";
                Console.WriteLine(values);
            }
        }
Пример #14
0
        public ThreadBase(String name)
        {
            _startupEvent        = new MutexEvent();
            _shutdownEvent       = new MutexEvent();
            _pausedEvent         = new MutexEvent();
            _resumeEvent         = new MutexEvent();
            _threadCompleteEvent = new MutexEvent();

            _name         = name;
            _didNiceAbort = false;
            _state        = ThreadState.Stopped;

            _interval = 0;

            _startupTimeout  = DEFAULT_STARTUP_TIMEOUT_MS;
            _shutdownTimeout = DEFAULT_SHUTDOWN_TIMEOUT_MS;

            _runCount = 0;

            _startTime = DateTime.MinValue;

            _performanceTimer = new PerformanceTimer(name);

            Tag     = null;
            Message = String.Empty;
        }
Пример #15
0
        public void ReversedTests_List()
        {
            Console.WriteLine("<<< Generally descending data (buffered List<T>) >>>");

            var r = new Random(seed);
            var a = new List <int>(maxSize);

            int[] b     = new int[maxSize];
            int   value = int.MaxValue;

            Console.WriteLine("Preparing...");
            for (int i = 0; i < maxSize; i++)
            {
                value =
                    r.Next(100) < 80
                                        ? value - r.Next(100)
                                        : value + r.Next(100);
                b[i] = value;
            }
            a.AddRange(b);

            Console.WriteLine("Sorting...");
            PerformanceTimer.Debug("builtin", 1, () => Array.Sort(b, Compare), maxSize);
            PerformanceTimer.Debug("timsort", 1, () => a.TimSort(Compare), maxSize);

            Console.WriteLine("Testing...");
            for (int i = 0; i < maxSize; i++)
            {
                Assert.AreEqual(a[i], b[i]);
            }
        }
Пример #16
0
        public void PerformanceTest()
        {
            PerformanceTimer aTimer = new PerformanceTimer();

            ManualResetEvent aCompleted = new ManualResetEvent(false);
            object           aLock      = new object();
            int aSum = 0;


            // Using synchronized keyword
            aTimer.Start();

            for (int i = 0; i < 10; ++i)
            {
                ThreadPool.QueueUserWorkItem(x =>
                {
                    for (int j = 0; j < 1000000; ++j)
                    {
                        lock (aLock)
                        {
                            ++aSum;
                            if (aSum == 10000000)
                            {
                                aCompleted.Set();
                            }
                        }
                    }
                });
            }

            aCompleted.WaitOne();
            aTimer.Stop();

            // Using ThreadLock
            aCompleted.Reset();
            aTimer.Start();
            aSum = 0;

            for (int i = 0; i < 10; ++i)
            {
                ThreadPool.QueueUserWorkItem(x =>
                {
                    for (int j = 0; j < 1000000; ++j)
                    {
                        using (ThreadLock.Lock(aLock))
                        {
                            ++aSum;
                            if (aSum == 10000000)
                            {
                                aCompleted.Set();
                            }
                        }
                    }
                });
            }

            aCompleted.WaitOne();
            aTimer.Stop();
        }
Пример #17
0
        /// <summary>
        /// starts the database process if it's not running
        /// </summary>
        /// <param name="Parameter"></param>
        public DBProcess(DBProcessParams Parameter)
        {
            m_Params = Parameter;

            m_wasRunning = IsListenerOnPort(m_Params.Port);

            if (!m_wasRunning)
            {
                ProcessStartInfo psi;

                // start the DB server process
                if (Debugger.IsAttached)
                {
                    psi = new ProcessStartInfo(m_Params.Commandline, m_Params.Commandargs);
                    psi.WorkingDirectory       = m_Params.Workingdirectory;
                    psi.WindowStyle            = ProcessWindowStyle.Normal;
                    psi.CreateNoWindow         = false;
                    psi.RedirectStandardOutput = false;
                    psi.UseShellExecute        = true;
                }
                else
                {
                    psi = new ProcessStartInfo(m_Params.Commandline, m_Params.Commandargs);
                    psi.WorkingDirectory       = m_Params.Workingdirectory;
                    psi.WindowStyle            = ProcessWindowStyle.Hidden;
                    psi.CreateNoWindow         = true;
                    psi.RedirectStandardOutput = false;
                    psi.UseShellExecute        = true;
                }

                m_Process = System.Diagnostics.Process.Start(psi);

                // wait for db ready state
                Boolean          isRunning = false;
                PerformanceTimer pc        = new PerformanceTimer();

                pc.startMeasuring();
                System.Threading.Thread.Sleep(1000);

                if (!m_Process.HasExited)
                {
                    do
                    {
                        isRunning = IsListenerOnPort(m_Params.Port);

                        if (!isRunning)
                        {
                            System.Threading.Thread.Sleep(1000);
                        }

                        Debug.Print("Waiting " + pc.currentMeasuring().ToString());
                    } while ((!isRunning) && ((pc.currentMeasuring() / 1000) < m_Params.DBStartTimeout));
                }
                else
                {
                    throw new Exception("can't start sql server !");
                }
            }
        }
        public override CrayonWorkerResult DoWorkImpl(CrayonWorkerResult[] args)
        {
#if DEBUG
            string summary = PerformanceTimer.GetSummary();
            Console.WriteLine(summary);
#endif
            return(new CrayonWorkerResult());
        }
Пример #19
0
        public static PerformanceTimer GetPerformanceTimer(ClassificationDeclaration classificationDeclaration)
        {
            PerformanceTimer timer = PerformanceTimer.StartNew(
                RollbarPerformanceMonitor.Instance,
                PerformanceUtil.GetClassification(classificationDeclaration)
                );

            return(timer);
        }
Пример #20
0
        internal StationHistory()
        {
            AutoSave       = true;
            _maxLength     = 100;
            History        = new List <StationVisit>();
            RetryTimer     = new PerformanceTimer();
            m_lastInserted = String.Empty;

            RetryTimer.startMeasuring();
        }
Пример #21
0
        public GameMain()
        {
            Globals.Graphics      = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            Globals.Content       = Content;
            IsMouseVisible        = true;

            _gameUpdatePerformance = new PerformanceTimer();
            _gameDrawPerformance   = new PerformanceTimer();
        }
Пример #22
0
        internal StationHistory()
        { 
            AutoSave        = true;   
            _maxLength      = 100;
            History         = new List<StationVisit>();
            RetryTimer      = new PerformanceTimer();
            m_lastInserted  = String.Empty;

            RetryTimer.startMeasuring();
        }
Пример #23
0
        public override void RuntimeInitialize(MethodBase method)
        {
            if (typeof(ILogger).IsAssignableFrom(_loggerServiceType) == false)
                throw new Exception("Wrong Log Service Manager");

            _logService = (ILogger) Activator.CreateInstance(_loggerServiceType);
            _performanceTimer = Activator.CreateInstance<PerformanceTimer>();

            base.RuntimeInitialize(method);
        }
Пример #24
0
        public static void Main(string[] args)
        {
            RunPuzzleA();

            Console.WriteLine("Press any key to begin Puzzle B");
            Console.Read();
            PerformanceTimer.Reset();

            RunPuzzleB();
        }
Пример #25
0
        private void SendOfflineBroadcastResponseMessage(string channelId, object broadcastMessage,
                                                         int numberOfClients, int numberOfMessages,
                                                         int openConnectionTimeout,
                                                         int allMessagesReceivedTimeout)
        {
            ThreadPool.SetMinThreads(50, 2);

            ClientMockFarm aClientFarm = new ClientMockFarm(MessagingSystem, channelId, numberOfClients);
            ServiceMock    aService    = new ServiceMock(MessagingSystem, channelId);

            try
            {
                aService.InputChannel.StartListening();

                // Send broadcasts.
                for (int i = 0; i < numberOfMessages; ++i)
                {
                    aService.InputChannel.SendResponseMessage("*", broadcastMessage);
                }

                Thread.Sleep(500);

                aClientFarm.OpenConnectionsAsync();

                aClientFarm.WaitUntilAllConnectionsAreOpen(openConnectionTimeout);
                aService.WaitUntilResponseReceiversConnectNotified(numberOfClients, openConnectionTimeout);
                Assert.AreEqual(aClientFarm.Clients.Count(), aService.ConnectedResponseReceivers.Count());
                foreach (ClientMock aClient in aClientFarm.Clients)
                {
                    Assert.IsTrue(aService.ConnectedResponseReceivers.Any(x => x.ResponseReceiverId == aClient.OutputChannel.ResponseReceiverId));
                }

                PerformanceTimer aStopWatch = new PerformanceTimer();
                aStopWatch.Start();

                aClientFarm.WaitUntilAllResponsesAreReceived(numberOfMessages, allMessagesReceivedTimeout);

                aStopWatch.Stop();

                foreach (DuplexChannelMessageEventArgs aResponseMessage in aClientFarm.ReceivedResponses)
                {
                    Assert.AreEqual(broadcastMessage, aResponseMessage.Message);
                }
            }
            finally
            {
                EneterTrace.Debug("CLEANING AFTER TEST");

                aClientFarm.CloseAllConnections();
                aService.InputChannel.StopListening();

                //EneterTrace.StopProfiler();
                Thread.Sleep(500);
            }
        }
Пример #26
0
        private void LoadXmlFile()
        {
            var timer = new PerformanceTimer();

            timer.Start();
            _xmlDoc.Load(_XmlFileName);
            timer.Stop();
            statusBar.Text          = "Xml Document Load Time: " + timer.ElapsedTime + " ms";
            btnExecuteQuery.Enabled = true;
            FillXmlDocument(_xmlDoc);
        }
Пример #27
0
 private static void MapInput(Input inputData, _InputMeta inputMeta)
 {
     PerformanceTimer.Reset();
     PerformanceTimer.Start();
     MapVoltagePhasorInput(inputData, inputMeta);
     MapCurrentPhasorInput(inputData, inputMeta);
     MapStatusWordInput(inputData, inputMeta);
     MapDigitalsInput(inputData, inputMeta);
     PerformanceTimer.Stop();
     m_network.PerformanceMetrics.ParsingExecutionTime = PerformanceTimer.ElapsedTicks;
 }
Пример #28
0
        private void LoadXmlFile()
        {
            PerformanceTimer timer = new PerformanceTimer();

            timer.Start();
            this._xmlDoc.Load(this._XmlFileName);
            timer.Stop();
            this.statusBar.Text          = "Xml Document Load Time: " + timer.ElapsedTime.ToString() + " ms";
            this.btnExecuteQuery.Enabled = true;
            this.FillXmlDocument(this._xmlDoc);
        }
Пример #29
0
        public GameMain()
        {
            Globals.Graphics      = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            Globals.Content       = Content;
            IsMouseVisible        = true;

            _gameDrawPerformance = new PerformanceTimer();
            _tweenPerformance    = new PerformanceTimer();
            _tweenPerformance.CountEachExecution = true;
        }
Пример #30
0
 /// <summary>
 /// constructor
 /// </summary>
 public EliteDBIO()
 {
     try
     {
         m_EventTimer = new PerformanceTimer();
         m_EventTimer.startMeasuring();
     }
     catch (Exception ex)
     {
         throw new Exception("Error in constructor", ex);
     }
 }
Пример #31
0
        public T ExecuteScalar <T>()
        {
            var initiallyClosed = _connection.State == ConnectionState.Closed;
            var startTime       = PerformanceTimer.TimeNow;

            try
            {
                if (initiallyClosed)
                {
                    OpenConnection();
                }
                var result = _sqlCommand.ExecuteScalar();

                var elapsedSeconds = PerformanceTimer.TicksToSeconds(PerformanceTimer.TimeNow - startTime);
                _repository.RecordSuccess(this, elapsedSeconds);
                AnalyticRecorder?.CommandCompleted(new CommandAnalyticInfo
                {
                    Connection     = this,
                    Command        = _command,
                    ElapsedSeconds = elapsedSeconds
                });

                if (result == null)
                {
                    return(default(T));
                }
                var resultType = typeof(T);
                if (resultType.IsNullable())
                {
                    resultType = resultType.GetGenericArguments()[0];
                }
                return((T)Convert.ChangeType(result, resultType));
            }
            catch (Exception ex)
            {
                _repository.RecordFailure(this);
                AnalyticRecorder?.CommandFailed(new CommandAnalyticInfo
                {
                    Connection = this,
                    Command    = _command,
                });
                _errorReporter.ReportError(ex, _sqlCommand, "Failed to ExecuteScalar on SQL Server " + _repository.Name, _repository, this);
                throw;
            }
            finally
            {
                if (initiallyClosed && _connection.State == System.Data.ConnectionState.Open)
                {
                    _connection.Close();
                }
            }
        }
Пример #32
0
        protected override void Draw(GameTime gameTime)
        {
            _gameDrawPerformance.Begin();
            GraphicsDevice.Clear(Color.CornflowerBlue);

            base.Draw(gameTime);
            _gameDrawPerformance.End();

            // Refresh here as the end-of-frame
            PerformanceTimer.FrameRefresh();
            _gameUpdatePerformance.Refresh();
            _gameDrawPerformance.Refresh();

            // Draw the results onto the screen
            _spriteBatch.Begin();

            _spriteBatch.DrawString(_FPS.SpriteFont,
                                    _FPS & XenString.Temporary(PerformanceTimer.CurrentFramerate, 2) & _space &
                                    XenString.Temporary(PerformanceTimer.MinFramerate, 2) & _space &
                                    XenString.Temporary(PerformanceTimer.MaxFramerate, 2) & _space &
                                    XenString.Temporary(PerformanceTimer.AverageFramerate, 2), Vector2.Zero, Color.White);
            _spriteBatch.DrawString(_update.SpriteFont,
                                    _update & XenString.Temporary(_gameUpdatePerformance.Current, 2) & _space &
                                    XenString.Temporary(_gameUpdatePerformance.Min, 2) & _space &
                                    XenString.Temporary(_gameUpdatePerformance.Max, 2) & _space &
                                    XenString.Temporary(_gameUpdatePerformance.Average, 2), Vector2.UnitY * 20, Color.White);
            _spriteBatch.DrawString(_draw.SpriteFont,
                                    _draw & XenString.Temporary(_gameDrawPerformance.Current, 2) & _suffix & _space &
                                    XenString.Temporary(_gameDrawPerformance.Min, 2) & _suffix & _space &
                                    XenString.Temporary(_gameDrawPerformance.Max, 2) & _suffix & _space &
                                    XenString.Temporary(_gameDrawPerformance.Average, 2) & _suffix, Vector2.UnitY * 40, Color.White);

            //_spriteBatch.DrawString( _font, "CurFPS: " + PerformanceTimer.CurrentFramerate.ToString( "0.00" ), Vector2.Zero, Color.White );
            //_spriteBatch.DrawString( _font, "MinFPS: " + PerformanceTimer.MinFramerate.ToString( "0.00" ), Vector2.UnitY * 20, Color.White );
            //_spriteBatch.DrawString( _font, "MaxFPS: " + PerformanceTimer.MaxFramerate.ToString( "0.00" ), Vector2.UnitY * 40, Color.White );
            //_spriteBatch.DrawString( _font, "AvgFPS: " + PerformanceTimer.AverageFramerate.ToString( "0.00" ), Vector2.UnitY * 60, Color.White );

            //_spriteBatch.DrawString( _font, "CurUpdate: " + _gameUpdatePerformance.Current.ToString( "0.00ms" ), Vector2.UnitY * 100, Color.Blue );
            //_spriteBatch.DrawString( _font, "MinUpdate: " + _gameUpdatePerformance.Min.ToString( "0.00ms" ), Vector2.UnitY * 120, Color.Blue );
            //_spriteBatch.DrawString( _font, "MaxUpdate: " + _gameUpdatePerformance.Max.ToString( "0.00ms" ), Vector2.UnitY * 140, Color.Blue );
            //_spriteBatch.DrawString( _font, "AvgUpdate: " + _gameUpdatePerformance.Average.ToString( "0.00ms" ), Vector2.UnitY * 160, Color.Blue );

            //_spriteBatch.DrawString( _font, "CurDraw: " + _gameDrawPerformance.Current.ToString( "0.00ms" ), Vector2.UnitY * 200, Color.Red );
            //_spriteBatch.DrawString( _font, "MinDraw: " + _gameDrawPerformance.Min.ToString( "0.00ms" ), Vector2.UnitY * 220, Color.Red );
            //_spriteBatch.DrawString( _font, "MaxDraw: " + _gameDrawPerformance.Max.ToString( "0.00ms" ), Vector2.UnitY * 240, Color.Red );
            //_spriteBatch.DrawString( _font, "AvgDraw: " + _gameDrawPerformance.Average.ToString( "0.00ms" ), Vector2.UnitY * 260, Color.Red );
            _spriteBatch.End();

            // Let the next 'frame' begin now because Draw() is throttled internally
            PerformanceTimer.FrameTick();
        }
Пример #33
0
        static void Main(string[] args)
        {
            Dictionary <string, string> argLookup = null;

            using (new PerformanceSection("Crayon"))
            {
#if DEBUG
                args = GetEffectiveArgs(args);

                // First chance exceptions should crash in debug builds.
                argLookup = FlagParser.Parse(args);
                Program.Compile(argLookup);

                // Crash if there were any graphics contexts that weren't cleaned up.
                // This is okay on Windows, but on OSX this is a problem, so ensure that a
                // regressions are quickly noticed.
                SystemBitmap.Graphics.EnsureCleanedUp();
#else
                if (args.Length == 0)
                {
                    System.Console.WriteLine(USAGE);
                }
                else
                {
                    try
                    {
                        argLookup = FlagParser.Parse(args);
                        Program.Compile(argLookup);
                    }
                    catch (InvalidOperationException e)
                    {
                        System.Console.Error.WriteLine(e.Message);
                    }
                    catch (ParserException e)
                    {
                        System.Console.Error.WriteLine(e.Message);
                    }
                }
#endif
            }
#if DEBUG
            if (argLookup != null)
            {
                if (argLookup.ContainsKey(FlagParser.SHOW_PERFORMANCE_MARKERS))
                {
                    string summary = PerformanceTimer.GetSummary();
                    Console.WriteLine(summary);
                }
            }
#endif
        }
Пример #34
0
        /// <summary>
        /// Checks if the system is existing and adds it, if not.
        /// Also sets the visited-flag if not set.
        /// </summary>
        /// <param name="newSystemName"></param>
        /// <param name="newStationName"></param>
        /// <param name="setVisitedFlag"></param>
        /// <param name="name"></param>
        public void checkPotentiallyNewSystemOrStation(String newSystemName, String newStationName, Point3Dbl coordinates = null, Boolean setVisitedFlag = true)
        {
            String sqlString;
            Int32 systemID = 0;
            Int32 stationID = 0;
            Boolean systemFirstTimeVisited = false;
            Boolean stationFirstTimeVisited = false;
            DataTable Data = new DataTable();
            Boolean Visited;
            PerformanceTimer pt = new PerformanceTimer();

            try
            {
                pt.startMeasuring();

                newSystemName = newSystemName.Trim();
                newStationName = newStationName.Trim();

                if (!String.IsNullOrEmpty(newSystemName))
                {
                    sqlString = "select id, visited from tbSystems where Systemname = " + DBConnector.SQLAEscape(newSystemName);
                    if (Program.DBCon.Execute(sqlString, Data) > 0)
                    {
                        // system is existing, check or update the visited-flag
                        systemID    = (Int32)(Data.Rows[0]["ID"]);
                        Visited     = (Boolean)(Data.Rows[0]["visited"]);

                        if (!Visited && setVisitedFlag)
                        {
                            sqlString = String.Format("update tbSystems set visited = 1 where id = {0};" +
                                                      "insert ignore into tbVisitedSystems(system_id, time) values" +
                                                      " ({0},{1});", 
                                                      systemID.ToString(), 
                                                      DBConnector.SQLDateTime(DateTime.UtcNow));

                            Program.DBCon.Execute(sqlString);

                            // set flag in the memory table
                            var system = Program.Data.BaseData.tbsystems.FindByid(systemID);
                            if(system != null)
                                system.visited = setVisitedFlag;

                            systemFirstTimeVisited = setVisitedFlag;
                        }

                        if((coordinates != null) && (coordinates.Valid))
                        {
                            var system = Program.Data.BaseData.tbsystems.FindByid(systemID);
                            if(system != null)
                            {
                                if((system.x == null) || (Math.Abs(system.x - coordinates.X.Value) > 0.001) ||
                                   (system.y == null) || (Math.Abs(system.y - coordinates.Y.Value) > 0.001) ||
                                   (system.z == null) || (Math.Abs(system.z - coordinates.Z.Value) > 0.001))
                                {
                                    sqlString = String.Format("update tbSystems set x={0}, y={1}, z={2}, updated_at = UTC_TIMESTAMP()" +
                                                              " where ((ABS(x-{0}) > 0.001) or (ABS(y-{1}) > 0.001) or (ABS(z-{2}) > 0.001)) and id = {3}", 
                                                              DBConnector.SQLDecimal(coordinates.X.Value), 
                                                              DBConnector.SQLDecimal(coordinates.Y.Value), 
                                                              DBConnector.SQLDecimal(coordinates.Z.Value), 
                                                              systemID);

                                    if(Program.DBCon.Execute(sqlString)>0)
                                    {
                                        system.x = coordinates.X.Value;
                                        system.y = coordinates.Y.Value;
                                        system.z = coordinates.Z.Value;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // add a new system
                        Program.DBCon.TransBegin();

                        try
                        {
                            systemID = Program.DBCon.Execute<Int32>("select min(ID)-1 from tbsystems");
                        
                            sqlString = String.Format("insert into tbSystems(id, systemname, x, y, z, updated_at, visited) values ({0},{1},{2},{3},{4},{5},{6});" +
                                                      "insert ignore into tbVisitedsystems(system_id, time) values ({0},{5});",
                                                      systemID, 
                                                      DBConnector.SQLAEscape(newSystemName), 
                                                      coordinates.Valid ? DBConnector.SQLDecimal(coordinates.X.Value) : "null", 
                                                      coordinates.Valid ? DBConnector.SQLDecimal(coordinates.Y.Value) : "null", 
                                                      coordinates.Valid ? DBConnector.SQLDecimal(coordinates.Z.Value) : "null",
                                                      DBConnector.SQLDateTime(DateTime.UtcNow), 
                                                      "1"); 
                            Program.DBCon.Execute(sqlString);
                            Program.DBCon.TransCommit();
                        }
                        catch (Exception ex)
                        {
                                Program.DBCon.TransRollback();
                                throw new Exception("Error while inserting a new system");
                        }


                        systemFirstTimeVisited = setVisitedFlag;

                        dsEliteDB.tbsystemsRow newSystemRow = (dsEliteDB.tbsystemsRow)Program.Data.BaseData.tbsystems.NewRow();

                        newSystemRow.id         = systemID;
                        newSystemRow.systemname = DBConnector.SQLAEscape(newSystemName);
                        if(coordinates.Valid)
                        {
                            newSystemRow.x          = coordinates.X.Value;
                            newSystemRow.y          = coordinates.X.Value;
                            newSystemRow.z          = coordinates.X.Value;
                        }
                        newSystemRow.updated_at = DateTime.UtcNow;
                        newSystemRow.visited    = setVisitedFlag;

                        Program.Data.BaseData.tbsystems.Rows.Add(newSystemRow);
                    }

                    /////////////////////////////////////////////////////////////////////////////////////////////////////

                    if (!String.IsNullOrEmpty(newStationName))
                    {
                        Data.Clear();

                        sqlString = "select St.ID, St.visited from tbSystems Sy, tbStations St" +
                                       " where Sy.ID = St. System_ID" +
                                       " and   Sy.ID          = " + systemID +
                                       " and   St.Stationname = " + DBConnector.SQLAEscape(newStationName);

                        if (Program.DBCon.Execute(sqlString, Data) > 0)
                        {
                            // station is existing, check or update the visited-flag
                            stationID = (Int32)(Data.Rows[0]["ID"]);
                            Visited = (Boolean)(Data.Rows[0]["visited"]);

                            if (!Visited && setVisitedFlag)
                            {
                                sqlString = String.Format("update tbStations set visited = 1 where id = {0};" +
                                                          "insert ignore into tbVisitedStations(station_id, time) values" +
                                                          " ({0},{1});", stationID.ToString(), DBConnector.SQLDateTime(DateTime.UtcNow));
                                Program.DBCon.Execute(sqlString);

                                // set flag in the memory table
                                var station = Program.Data.BaseData.tbstations.FindByid(stationID);
                                if(station != null)
                                    station.visited = setVisitedFlag;

                                stationFirstTimeVisited = setVisitedFlag;
                            }
                        }
                        else
                        {
                            // add a new station
                            Program.DBCon.TransBegin();
                            try
                            {
                                stationID = Program.DBCon.Execute<Int32>("select min(ID)-1 from tbStations");

                                sqlString = String.Format("insert into tbStations(id, stationname, system_id, updated_at, visited) values ({0},{1},{2},{3},{4});" +
                                                          "insert ignore into tbVisitedstations(station_id, time) values ({0},{3});",
                                                          stationID, 
                                                          DBConnector.SQLAEscape(newSystemName), 
                                                          systemID, 
                                                          DBConnector.SQLDateTime(DateTime.UtcNow), 
                                                          "1"); 
                                Program.DBCon.Execute(sqlString);
                                Program.DBCon.TransCommit();
                            }
                            catch (Exception ex)
                            {
                                Program.DBCon.TransRollback();
                                throw new Exception("Error while inserting a new station");
                            }

                            stationFirstTimeVisited = setVisitedFlag;

                            dsEliteDB.tbstationsRow newStationRow = (dsEliteDB.tbstationsRow)Program.Data.BaseData.tbstations.NewRow();

                            newStationRow.id            = stationID;
                            newStationRow.system_id     = systemID;
                            newStationRow.stationname   = DBConnector.SQLAEscape(newStationName);
                            newStationRow.updated_at    = DateTime.UtcNow;
                            newStationRow.visited       = setVisitedFlag;

                            Program.Data.BaseData.tbstations.Rows.Add(newStationRow);

                        }
                    }


                    if(systemFirstTimeVisited && (Program.Data.BaseData.tbvisitedsystems.Select("System_ID = " + systemID).Count() == 0))
                    {
                        dsEliteDB.tbvisitedsystemsRow newVisSystemRow = (dsEliteDB.tbvisitedsystemsRow)Program.Data.BaseData.tbvisitedsystems.NewRow();
                        newVisSystemRow.system_id   = systemID;
                        newVisSystemRow.time        = DateTime.UtcNow;
                        Program.Data.BaseData.tbvisitedsystems.Rows.Add(newVisSystemRow);
                    }
                    if(stationFirstTimeVisited && (Program.Data.BaseData.tbvisitedstations.Select("Station_ID = " + stationID).Count() == 0))
                    {
                        dsEliteDB.tbvisitedstationsRow newVisStationRow = (dsEliteDB.tbvisitedstationsRow)Program.Data.BaseData.tbvisitedstations.NewRow();
                        newVisStationRow.station_id  = stationID;
                        newVisStationRow.time        = DateTime.UtcNow;
                        Program.Data.BaseData.tbvisitedstations.Rows.Add(newVisStationRow);
                    }

                    if (((systemFirstTimeVisited) || (stationFirstTimeVisited)) && 
                        (stationID != 0) && 
                        (Program.Data.BaseData.visystemsandstations.Select("SystemID = " + systemID + " and StationID = " + stationID).Count() == 0))
                    {
                        dsEliteDB.visystemsandstationsRow newVisStationRow = (dsEliteDB.visystemsandstationsRow)Program.Data.BaseData.visystemsandstations.NewRow();
                        newVisStationRow.SystemName = newSystemName;
                        newVisStationRow.SystemID = systemID;
                        newVisStationRow.StationName = newStationName;
                        newVisStationRow.StationID = stationID;
                        Program.Data.BaseData.visystemsandstations.Rows.Add(newVisStationRow);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while checking for potentially new system or station", ex);
            }
        }
Пример #35
0
//        private Dictionary<DataTable, MySql.Data.MySqlClient.MySqlDataAdapter>     m_BaseData_UpdateObjects = new Dictionary<DataTable, MySql.Data.MySqlClient.MySqlDataAdapter>();
        



        /// <summary>
        /// loads the data from the basetables into memory. For correct initialization it is
        /// necessary to call this fuction with a unset tableName
        /// 
        /// </summary>
        /// <param name="m_BaseData"></param>
        internal void PrepareBaseTables(String TableName = "", Boolean saveChanged = false)
        {
            PerformanceTimer Runtime;
            //MySql.Data.MySqlClient.MySqlDataAdapter dataAdapter;
            DBConnector currentDBCon;

            try
            {
                Runtime = new PerformanceTimer();

                if(String.IsNullOrEmpty(TableName))
                { 
                    if(m_BaseData == null)
                    {
                        m_BaseData              = new dsEliteDB();
                        m_BaseData_Connector    = new Dictionary<DataTable, DBConnector>();
                    }

                    foreach (String BaseTable in BaseTables_Systems)
                    {
                        if (!m_BaseData_Connector.TryGetValue(m_BaseData.Tables[BaseTable], out currentDBCon))
                        {
                            // each basetable gets it's own DBConnector, because 
                            // the contained DataReaders will be hold open for possible 
                            // changes (MySQL doesn't support MARS "Multiple Active result Sets")

                            currentDBCon = new DBConnector(Program.DBCon.ConfigData);
                            m_BaseData_Connector.Add(m_BaseData.Tables[BaseTable], currentDBCon);

                            currentDBCon.Connect();
                        }

                        Runtime.startMeasuring();
                        m_BaseData.Tables[BaseTable].Clear();

                        if (!Program.SplashScreen.IsDisposed)
                            Program.SplashScreen.InfoAdd("...loading basetable '" + BaseTable + "'...");                            

                        // preload all tables with base data
                        currentDBCon.TableRead(String.Format("select * from {0}", BaseTable), BaseTable, m_BaseData);
                        
                        if (!Program.SplashScreen.IsDisposed)
                            Program.SplashScreen.InfoAppendLast("<OK>");                            

                        Runtime.PrintAndReset("loading full table '" + BaseTable + "':");
                    }
                }
                else if(BaseTables_Systems.Contains(TableName))
                {
                    currentDBCon = m_BaseData_Connector[m_BaseData.Tables[TableName]];

                    if(saveChanged)
                    {
                        // save all containing changes
                        Runtime.PrintAndReset("saving changes in table '" + TableName + "':");
                        currentDBCon.TableUpdate(TableName, m_BaseData);
                    }
                    else
                    {
                        Runtime.startMeasuring();

                        m_BaseData.Tables[TableName].Clear();

                        // reload selected table
                        currentDBCon.TableRead("", TableName, m_BaseData);

                        Runtime.PrintAndReset("re-loading full table '" + TableName + "':");
                    }
                }
                else
                {
                    throw new Exception(string.Format("Attempt to load an unknown basetable : <{0}>", TableName));
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Error while preparing base tables", ex);
            }
        }
Пример #36
0
        /// <summary>
        /// starts the database process if it's not running
        /// </summary>
        /// <param name="Parameter"></param>
        public DBProcess(DBProcessParams Parameter)
        {
            IPGlobalProperties      ipGlobalProperties;
            IPEndPoint[]            tcpConnInfoArray;

            m_Params = Parameter;

            ipGlobalProperties      = IPGlobalProperties.GetIPGlobalProperties();
            tcpConnInfoArray        = ipGlobalProperties.GetActiveTcpListeners();

            // check if the port is open - if open we assume the db is running
            foreach (IPEndPoint tcpi in tcpConnInfoArray)
                if (tcpi.Port == m_Params.Port)
                {
                    m_wasRunning = true;
                    break;
                }

            if(!m_wasRunning)
            {
                ProcessStartInfo psi;

                // start the DB server process
                if(Debugger.IsAttached)
                {
                    psi                         = new ProcessStartInfo(m_Params.Commandline,m_Params.Commandargs);
                    psi.WorkingDirectory        = m_Params.Workingdirectory;
                    psi.WindowStyle             = ProcessWindowStyle.Normal;
                    psi.CreateNoWindow          = false;
                    psi.RedirectStandardOutput  = false;
                    psi.UseShellExecute         = true;
                }
                else
                {
                    psi                         = new ProcessStartInfo(m_Params.Commandline,m_Params.Commandargs);
                    psi.WorkingDirectory        = m_Params.Workingdirectory;
                    psi.WindowStyle             = ProcessWindowStyle.Hidden;
                    psi.CreateNoWindow          = true;
                    psi.RedirectStandardOutput  = false;
                    psi.UseShellExecute         = true;

                }

                m_Process = System.Diagnostics.Process.Start(psi);

                // wait for db ready state
                Boolean isRunning = false;
                PerformanceTimer pc = new PerformanceTimer();

                pc.startMeasuring();
                System.Threading.Thread.Sleep(1000);

                if (!m_Process.HasExited)
                {
                    do
                    {
                        ipGlobalProperties      = IPGlobalProperties.GetIPGlobalProperties();
                        tcpConnInfoArray        = ipGlobalProperties.GetActiveTcpListeners();

                        foreach (IPEndPoint tcpi in tcpConnInfoArray)
                            if (tcpi.Port == m_Params.Port)
                            {
                                isRunning = true;
                                break;
                            }

                        if(!isRunning)
                            System.Threading.Thread.Sleep(1000);

                        Debug.Print("Waiting " + pc.currentMeasuring().ToString());

                    } while ((!isRunning) && ((pc.currentMeasuring() / 1000) < m_Params.DBStartTimeout));
                }
                else
                {
                    throw new Exception("can't start sql server !");
                }
            }
        }