예제 #1
0
        private static IEnumerable <Tag> ExtractTagsFromPropertyWithSpecificAttribute(object objValue, PropertyInfo objProperty, HubTagAttribute attribute)
        {
            if (objProperty != null)
            {
                objValue = objProperty.GetValue(objValue);
                if (objValue == null)
                {
                    //don't save "null" values
                    yield break;
                }
                if (objValue.GetType().IsAssignableFrom(typeof(bool)) && objValue as bool? == false)
                {
                    //don't save "false" values
                    yield break;
                }
                if (objValue.GetType().IsAssignableFrom(typeof(int)) && objValue as int? == 0)
                {
                    //don't save "0" values
                    yield break;
                }
            }
            else if (objValue == null)
            {
                yield break;
            }
            Type objValueType = objValue.GetType();

            Tag tag = new Tag(objValue, attribute)
            {
                TagValue = !string.IsNullOrEmpty(attribute.TagValueFromProperty)
                    ? objValueType.GetProperty(attribute.TagValueFromProperty)?.GetValue(objValue, null)?.ToString() ?? string.Empty
                    : objValue.ToString(),
                TagName = !string.IsNullOrEmpty(attribute.TagName)
                    ? attribute.TagName
                    : !string.IsNullOrEmpty(objProperty?.Name)
                        ? objProperty.Name
                        : objValue.ToString()
            };

            tag.SetTagTypeEnumFromCLRType(objValueType);
            if (!string.IsNullOrEmpty(attribute.TagNameFromProperty))
            {
                try
                {
                    tag.TagName += objValueType.GetProperty(attribute.TagNameFromProperty)?.GetValue(objValue, null)?.ToString() ?? string.Empty;
                }
                catch (Exception)
                {
#if DEBUG
                    Debugger.Break();
#else
                    throw;
#endif
                }
            }

            if (objProperty != null)
            {
                tag.Tags = new List <Tag>(ExtractTagsFromAttributes(objValue));
            }
            yield return(tag);
        }
예제 #2
0
        private static int Main(string[] args)
        {
            if (Environment.GetEnvironmentVariable("BREAK") != null)
            {
                Console.WriteLine(
                    "Attach a debugger to process {0} and press any key to continue.",
                    Process.GetCurrentProcess().Id);

                try
                {
                    Console.ReadKey(true);        /* throw */
                }
                catch (InvalidOperationException) // Console.ReadKey
                {
                    // do nothing.
                }

                Debugger.Break();
            }

            string arg = null;

            if ((args != null) && (args.Length > 0))
            {
                arg = args[0];
            }

            if (arg == null)
            {
                arg = "";
            }

            arg = arg.Trim().TrimStart('-', '/').ToLowerInvariant();

            switch (arg)
            {
            case "":   // String.Empty
            case "old":
            {
                return(OldTests());
            }

            case "skip":
            {
                int pageSize = 0;

                if (args.Length > 1)
                {
                    arg = args[1];

                    if (arg != null)
                    {
                        pageSize = int.Parse(arg.Trim());
                    }
                }

                return(SkipTest(pageSize));
            }

            case "endswith":
            {
                string value = null;

                if (args.Length > 1)
                {
                    value = args[1];

                    if (value != null)
                    {
                        value = value.Trim();
                    }
                }

                return(EndsWithTest(value));
            }

            case "startswith":
            {
                string value = null;

                if (args.Length > 1)
                {
                    value = args[1];

                    if (value != null)
                    {
                        value = value.Trim();
                    }
                }

                return(StartsWithTest(value));
            }

            case "eftransaction":
            {
                bool value = false;

                if (args.Length > 1)
                {
                    if (!bool.TryParse(args[1], out value))
                    {
                        Console.WriteLine(
                            "cannot parse \"{0}\" as boolean",
                            args[1]);

                        return(1);
                    }
                }

                return(EFTransactionTest(value));
            }

            default:
            {
                Console.WriteLine("unknown test \"{0}\"", arg);
                return(1);
            }
            }
        }
예제 #3
0
        protected override string VerifyIndex(string entityName, string fieldName, FieldOrder searchOrder, IDbConnection connection)
        {
            bool localConnection = false;

            if (connection == null)
            {
                localConnection = true;
                connection      = GetConnection(true);
            }
            try
            {
                var indexName = string.Format("ORM_IDX_{0}_{1}_{2}", entityName, fieldName,
                                              searchOrder == FieldOrder.Descending ? "DESC" : "ASC");

                if (m_indexNameCache.FirstOrDefault(ii => ii.Name == indexName) != null)
                {
                    return(indexName);
                }

                using (var command = GetNewCommandObject())
                {
                    command.Connection = connection;

                    var sql = string.Format("select COUNT(*) from sys.indexes where name = '{0}' and Object_ID = Object_ID(N'{1}')", indexName, entityName);
                    command.CommandText = sql;
                    OnSqlStatementCreated(command, null);

                    int i = (int)command.ExecuteScalar();

                    if (i == 0)
                    {
                        sql = string.Format("CREATE INDEX {0} ON {1}({2} {3})",
                                            indexName,
                                            entityName,
                                            fieldName,
                                            searchOrder == FieldOrder.Descending ? "DESC" : string.Empty);

                        Debug.WriteLine(sql);

                        command.CommandText = sql;
                        OnSqlStatementCreated(command, null);
                        command.ExecuteNonQuery();
                    }

                    var indexinfo = new IndexInfo
                    {
                        Name = indexName
                    };

                    sql = string.Format("SELECT CHARACTER_MAXIMUM_LENGTH FROM information_schema.columns WHERE TABLE_NAME = '{0}' AND COLUMN_NAME = '{1}'"
                                        , entityName, fieldName);

                    command.CommandText = sql;
                    OnSqlStatementCreated(command, null);
                    using (var reader = command.ExecuteReader())
                    {
                        // this should always return true
                        if (reader.Read())
                        {
                            var length = reader[0];
                            if (length != DBNull.Value)
                            {
                                indexinfo.MaxCharLength = Convert.ToInt32(length);
                            }
                        }
                        else
                        {
                            if (Debugger.IsAttached)
                            {
                                Debugger.Break();
                            }
                        }
                    }

                    m_indexNameCache.Add(indexinfo);
                }

                return(indexName);
            }
            finally
            {
                if (localConnection)
                {
                    DoneWithConnection(connection, true);
                }
            }
        }
 public static void Main(string[] args)
 {
     // The program will stop here.
     // Open up the immediate window and play around!
     Debugger.Break();
 }
예제 #5
0
        private void TestCascadingInsert(List <ITestClass> tests)
        {
            var testBooks = new Book[]
            {
                new Book
                {
                    Title    = "CSS: The Missing Manual",
                    BookType = BookType.NonFiction
                },

                new Book
                {
                    Title    = "JavaScript: The Missing Manual",
                    BookType = BookType.NonFiction
                },

                new Book
                {
                    Title    = "Dreamweaver: The Missing Manual",
                    BookType = BookType.NonFiction
                },
            };

            // ensures that the entity *and its references* get inserted
            Author a = new Author
            {
                Name = "David McFarland",

                Books = testBooks
            };


            foreach (var t in tests)
            {
                var initialCount = t.GetBookCount();

                t.Insert(a);

                var author = t.GetAuthorById(a.AuthorID);
                var count  = t.GetBookCount();

                var diff = count - initialCount;
                // diff should == 3
                if (diff != 3)
                {
                    Debugger.Break();
                }
            }

            // create a new author with the same books - the books should *not* get re-inserted - plus one new book
            List <Book> newList = new List <Book>(testBooks);

            newList.Add(
                new Book
            {
                Title    = "My Coauthors Book",
                BookType = BookType.NonFiction
            }
                );

            Author a2 = new Author
            {
                Name = "Test CoAuthor",

                Books = newList.ToArray()
            };

            foreach (var t in tests)
            {
                var initialCount = t.GetBookCount();

                t.Insert(a2);

                var author = t.GetAuthorById(a.AuthorID);
                var count  = t.GetBookCount();
                var diff   = count - initialCount;

                // diff should == 1
                if (diff != 1)
                {
                    Debugger.Break();
                }
            }
        }
예제 #6
0
    public static void user()
    {
        Debugger.Break();

        Debugger.Log(5, Debugger.IsLogging() ? "A" : "", "B");
    }
 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     Debugger.Break();
     return(value);
 }
예제 #8
0
        private static string[] ReadUpdateXml(string url)
        {
            Log.Info("Reading update xml");
            var values = new string[3];

            try
            {
                Log.InfoFormat("Downloading info from {0}", url);
                WebRequest wr = WebRequest.Create(url);
                wr.Timeout = 15000;
                WebResponse resp = wr.GetResponse();
                Stream      rgrp = resp.GetResponseStream();
                Log.Info("Got stream");
                if (rgrp != null)
                {
                    Log.Info("Creating reader");
                    using (XmlReader reader = XmlReader.Create(rgrp))
                    {
                        Log.Info("Created reader...reading");

                        while (reader.Read())
                        {
                            if (!reader.IsStartElement())
                            {
                                continue;
                            }
                            if (reader.IsEmptyElement)
                            {
                                continue;
                            }
                            switch (reader.Name.ToLowerInvariant())
                            {
                            case "version":
                                if (reader.Read())
                                {
                                    Log.InfoFormat("Reading version {0}", reader.Value);
                                    values[0] = reader.Value;
                                }
                                break;

                            case "updatepath":
                                //if (reader.Read())
                                //values[1] = Program.WebsitePath + reader.Value;
                                break;

                            case "installpath":
                                if (reader.Read())
                                {
                                    Log.InfoFormat("Reading paths {0} {1}", reader.Value, reader.Value);
#if (Release_Test)
                                    values[2] = "https://s3.amazonaws.com/octgn/releases/test/" + reader.Value.Replace("downloadtest/", "");
                                    values[1] = "https://s3.amazonaws.com/octgn/releases/test/" + reader.Value.Replace("downloadtest/", "");
#else
                                    values[2] = "https://s3.amazonaws.com/octgn/releases/live/" + reader.Value.Replace("download/", "");
                                    values[1] = "https://s3.amazonaws.com/octgn/releases/live/" + reader.Value.Replace("download/", "");
#endif
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (WebException e)
            {
                Log.Warn("", e);
            }
            catch (Exception e)
            {
                Log.Error("Error", e);
                Debug.WriteLine(e);
#if (DEBUG)
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
#endif
            }
            return(values);
        }
예제 #9
0
        public static Task <int> MainCore(string[] args, ILogger log)
        {
#if DEBUG
            if (args.Contains("--debug"))
            {
                args = args.Skip(1).ToArray();
                while (!Debugger.IsAttached)
                {
                }

                Debugger.Break();
            }
#endif

            var assemblyVersion = NuGetVersion.Parse(typeof(Program).GetTypeInfo().Assembly.GetName().Version.ToString());

            var app = new CommandLineApplication();
            app.Name     = "NupkgWrench";
            app.FullName = "nupkg wrench";
            app.HelpOption(Constants.HelpOption);
            app.VersionOption("--version", assemblyVersion.ToNormalizedString());

            NuspecCommand.Register(app, log);
            FilesCommand.Register(app, log);
            IdCommand.Register(app, log);
            VersionCommand.Register(app, log);
            ExtractCommand.Register(app, log);
            CompressCommand.Register(app, log);
            ListCommand.Register(app, log);
            UpdateFileNameCommand.Register(app, log);
            ReleaseCommand.Register(app, log);
            ValidateCommand.Register(app, log);

            app.OnExecute(() =>
            {
                app.ShowHelp();

                return(0);
            });

            var exitCode = 0;

            try
            {
                exitCode = app.Execute(args);
            }
            catch (CommandParsingException ex)
            {
                ex.Command.ShowHelp();
            }
            catch (AggregateException ex)
            {
                exitCode = 1;

                foreach (var inner in ex.InnerExceptions)
                {
                    log.LogError(inner.Message);
                    log.LogDebug(inner.ToString());
                }
            }
            catch (Exception ex)
            {
                exitCode = 1;
                log.LogError(ex.Message);
                log.LogDebug(ex.ToString());
            }

            return(Task.FromResult(exitCode));
        }
예제 #10
0
        public void Can_Authenticate_LinkedIN_With_OAuth()
        {
            const string consumerKey    = "TODO_CONSUMER_KEY_HERE";
            const string consumerSecret = "TODO_CONSUMER_SECRET_HERE";

            // request token
            var client = new RestClient
            {
                BaseUrl       = new Uri("https://api.linkedin.com/uas/oauth"),
                Authenticator = OAuth1Authenticator.ForRequestToken(
                    consumerKey, consumerSecret,
                    "http://localhost"
                    )
            };
            var requestTokenRequest  = new RestRequest("requestToken");
            var requestTokenResponse = client.Execute(requestTokenRequest);

            Assert.NotNull(requestTokenResponse);
            Assert.AreEqual(HttpStatusCode.OK, requestTokenResponse.StatusCode);

            var requestTokenResponseParameters = HttpUtility.ParseQueryString(requestTokenResponse.Content);
            var requestToken  = requestTokenResponseParameters["oauth_token"];
            var requestSecret = requestTokenResponseParameters["oauth_token_secret"];

            Assert.NotNull(requestToken);
            Assert.NotNull(requestSecret);

            // redirect user
            requestTokenRequest = new RestRequest("authenticate?oauth_token=" + requestToken);

            var redirectUri = client.BuildUri(requestTokenRequest);

            Process.Start(redirectUri.ToString());

            const string requestUrl = "TODO: put browser URL here";

            // replace this via the debugger with the return url from LinkedIN. Simply copy it from the opened browser

            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }

            Debugger.Break();

            // get the access token
            var requestTokenQueryParameters = HttpUtility.ParseQueryString(new Uri(requestUrl).Query);
            var requestVerifier             = requestTokenQueryParameters["oauth_verifier"];

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, requestToken, requestSecret, requestVerifier
                );

            var requestAccessTokenRequest  = new RestRequest("accessToken");
            var requestActionTokenResponse = client.Execute(requestAccessTokenRequest);

            Assert.NotNull(requestActionTokenResponse);
            Assert.AreEqual(HttpStatusCode.OK, requestActionTokenResponse.StatusCode);

            var requestActionTokenResponseParameters = HttpUtility.ParseQueryString(requestActionTokenResponse.Content);
            var accessToken  = requestActionTokenResponseParameters["oauth_token"];
            var accessSecret = requestActionTokenResponseParameters["oauth_token_secret"];

            Assert.NotNull(accessToken);
            Assert.NotNull(accessSecret);
        }
 public void OnJsonError(object source, ErrorEventArgs error)
 {
     Debugger.Break();
 }
예제 #12
0
        private void CoreThreadLoop()
        {
            int idleCount = 0;

            //Bilge.Log("MexCore::CoreThreadLoop is initialised");
            while (m_continueRunning)
            {
                try {
                    // Autorefresh has been changed to be timer based rather than instance based.

                    if (WorkManager.WorkOutstanding)
                    {
                        WorkManager.DoWork();
                    }
                    else
                    {
                        // there was nothing for this thread to do
                        // todo : look up background housekeeping tasks to do

                        // First house keeping task, check the incomming message queue and see if there stuff waiting to be processed.
                        if (MexCore.TheCore.MessageManager.IncomingMessagesQueued)
                        {
                            // The message manager has messages queued, therefore we need to add a task to process these.
                            MexCore.TheCore.WorkManager.AddJob(new Job_CheckIncommingQueue());
                            continue;
                        }

                        // Ok done all housekeeping tasks, now return to messing around
                        Thread.Sleep(0);
                        idleCount++;
                        if (idleCount == 100)
                        {
                            idleCount = 0;
                            //Bilge.VerboseLog("MexCore::CoreThreadLoop - nothing to do - sleeping 10 secs");
                            MexCore.TheCore.ViewManager.AddUserNotificationMessageByIndex(ViewSupportManager.UserMessages.MexIsIdle, ViewSupportManager.UserMessageType.InformationMessage, "ZzzzZZzzzZ");
                            // At this point the app hasnt recieved a message in a while and is therefore this thread is going to go to sleep.
                            for (int killTime = 0; killTime < 1000; killTime++)
                            {
                                if ((WorkManager.WorkOutstanding) || (!m_continueRunning) || (MexCore.TheCore.MessageManager.IncomingMessagesQueued))
                                {
                                    //Bilge.Log("MexCore::CoreThreadLoop - Awoken, work has arrived");
                                    break;
                                }
                                Thread.Sleep(10);
                            }
                            //Bilge.VerboseLog("MexCore::CoreThreadLoop - Sleep loop ended (Check whether awoken occured in last log entry).");
                        }
                    }
                } catch (Exception ex) {
#if DEBUG
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                        //Bilge.Log("Omg its all gone terribly wrong");
                    }
#endif
                    // There was an error during our work processing
                    //Bilge.Warning("CORE THREAD CRASH..... UNEXPECTED BEHAVIOUR ABOUT TO KICK IN .........................");
                    //Bilge.Dump(ex, "MexCore::CoreThreadLoop Exception type caught during thread loop.  Unexpected operation during the core thread operation. ");
                    throw;
                }
            }

            //Bilge.Log("MexCore::CoreThreadLoop - terminating");
        }
예제 #13
0
            private static void GateThreadStart()
            {
                bool disableStarvationDetection =
                    AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.DisableStarvationDetection", false);
                bool debuggerBreakOnWorkStarvation =
                    AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.DebugBreakOnWorkerStarvation", false);

                // The first reading is over a time range other than what we are focusing on, so we do not use the read other
                // than to send it to any runtime-specific implementation that may also use the CPU utilization.
                CpuUtilizationReader cpuUtilizationReader = default;

                _ = cpuUtilizationReader.CurrentUtilization;

                PortableThreadPool threadPoolInstance   = ThreadPoolInstance;
                LowLevelLock       threadAdjustmentLock = threadPoolInstance._threadAdjustmentLock;
                DelayHelper        delayHelper          = default;

                if (BlockingConfig.IsCooperativeBlockingEnabled)
                {
                    // Initialize memory usage and limits, and register to update them on gen 2 GCs
                    threadPoolInstance.OnGen2GCCallback();
                    Gen2GcCallback.Register(threadPoolInstance.OnGen2GCCallback);
                }

                while (true)
                {
                    RunGateThreadEvent.WaitOne();
                    int currentTimeMs = Environment.TickCount;
                    delayHelper.SetGateActivitiesTime(currentTimeMs);

                    while (true)
                    {
                        bool wasSignaledToWake = DelayEvent.WaitOne((int)delayHelper.GetNextDelay(currentTimeMs));
                        currentTimeMs = Environment.TickCount;

                        // Thread count adjustment for cooperative blocking
                        do
                        {
                            PendingBlockingAdjustment pendingBlockingAdjustment = threadPoolInstance._pendingBlockingAdjustment;
                            if (pendingBlockingAdjustment == PendingBlockingAdjustment.None)
                            {
                                delayHelper.ClearBlockingAdjustmentDelay();
                                break;
                            }

                            bool previousDelayElapsed = false;
                            if (delayHelper.HasBlockingAdjustmentDelay)
                            {
                                previousDelayElapsed =
                                    delayHelper.HasBlockingAdjustmentDelayElapsed(currentTimeMs, wasSignaledToWake);
                                if (pendingBlockingAdjustment == PendingBlockingAdjustment.WithDelayIfNecessary &&
                                    !previousDelayElapsed)
                                {
                                    break;
                                }
                            }

                            uint nextDelayMs = threadPoolInstance.PerformBlockingAdjustment(previousDelayElapsed);
                            if (nextDelayMs <= 0)
                            {
                                delayHelper.ClearBlockingAdjustmentDelay();
                            }
                            else
                            {
                                delayHelper.SetBlockingAdjustmentTimeAndDelay(currentTimeMs, nextDelayMs);
                            }
                        } while (false);

                        //
                        // Periodic gate activities
                        //

                        if (!delayHelper.ShouldPerformGateActivities(currentTimeMs, wasSignaledToWake))
                        {
                            continue;
                        }

                        if (ThreadPool.EnableWorkerTracking && NativeRuntimeEventSource.Log.IsEnabled())
                        {
                            NativeRuntimeEventSource.Log.ThreadPoolWorkingThreadCount(
                                (uint)threadPoolInstance.GetAndResetHighWatermarkCountOfThreadsProcessingUserCallbacks());
                        }

                        int cpuUtilization = cpuUtilizationReader.CurrentUtilization;
                        threadPoolInstance._cpuUtilization = cpuUtilization;

                        bool needGateThreadForRuntime = ThreadPool.PerformRuntimeSpecificGateActivities(cpuUtilization);

                        if (!disableStarvationDetection &&
                            threadPoolInstance._pendingBlockingAdjustment == PendingBlockingAdjustment.None &&
                            threadPoolInstance._separated.numRequestedWorkers > 0 &&
                            SufficientDelaySinceLastDequeue(threadPoolInstance))
                        {
                            bool addWorker = false;
                            threadAdjustmentLock.Acquire();
                            try
                            {
                                // Don't add a thread if we're at max or if we are already in the process of adding threads.
                                // This logic is slightly different from the native implementation in CoreCLR because there are
                                // no retired threads. In the native implementation, when hill climbing reduces the thread count
                                // goal, threads that are stopped from processing work are switched to "retired" state, and they
                                // don't count towards the equivalent existing thread count. In this implementation, the
                                // existing thread count includes any worker thread that has not yet exited, including those
                                // stopped from working by hill climbing, so here the number of threads processing work, instead
                                // of the number of existing threads, is compared with the goal. There may be alternative
                                // solutions, for now this is only to maintain consistency in behavior.
                                ThreadCounts counts = threadPoolInstance._separated.counts;
                                while (
                                    counts.NumProcessingWork < threadPoolInstance._maxThreads &&
                                    counts.NumProcessingWork >= counts.NumThreadsGoal)
                                {
                                    if (debuggerBreakOnWorkStarvation)
                                    {
                                        Debugger.Break();
                                    }

                                    ThreadCounts newCounts         = counts;
                                    short        newNumThreadsGoal = (short)(counts.NumProcessingWork + 1);
                                    newCounts.NumThreadsGoal = newNumThreadsGoal;

                                    ThreadCounts countsBeforeUpdate =
                                        threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts, counts);
                                    if (countsBeforeUpdate == counts)
                                    {
                                        HillClimbing.ThreadPoolHillClimber.ForceChange(
                                            newNumThreadsGoal,
                                            HillClimbing.StateOrTransition.Starvation);
                                        addWorker = true;
                                        break;
                                    }

                                    counts = countsBeforeUpdate;
                                }
                            }
                            finally
                            {
                                threadAdjustmentLock.Release();
                            }

                            if (addWorker)
                            {
                                WorkerThread.MaybeAddWorkingWorker(threadPoolInstance);
                            }
                        }

                        if (!needGateThreadForRuntime &&
                            threadPoolInstance._separated.numRequestedWorkers <= 0 &&
                            threadPoolInstance._pendingBlockingAdjustment == PendingBlockingAdjustment.None &&
                            Interlocked.Decrement(ref threadPoolInstance._separated.gateThreadRunningState) <= GetRunningStateForNumRuns(0))
                        {
                            break;
                        }
                    }
                }
            }
예제 #14
0
        private void ShellWinProc(Message msg)
        {
            if (msg.Msg == WM_SHELLHOOKMESSAGE)
            {
                try
                {
                    lock (_windowsLock)
                    {
                        switch ((HSHELL)msg.WParam.ToInt32())
                        {
                        case HSHELL.WINDOWCREATED:
                            ShellLogger.Debug("TasksService: Created: " + msg.LParam);
                            if (!Windows.Any(i => i.Handle == msg.LParam))
                            {
                                addWindow(msg.LParam);
                            }
                            else
                            {
                                ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);
                                win.UpdateProperties();
                            }
                            break;

                        case HSHELL.WINDOWDESTROYED:
                            ShellLogger.Debug("TasksService: Destroyed: " + msg.LParam);
                            removeWindow(msg.LParam);
                            break;

                        case HSHELL.WINDOWREPLACING:
                            ShellLogger.Debug("TasksService: Replacing: " + msg.LParam);
                            if (Windows.Any(i => i.Handle == msg.LParam))
                            {
                                ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);
                                win.State = ApplicationWindow.WindowState.Inactive;
                                win.SetShowInTaskbar();
                            }
                            else
                            {
                                addWindow(msg.LParam);
                            }
                            break;

                        case HSHELL.WINDOWREPLACED:
                            ShellLogger.Debug("TasksService: Replaced: " + msg.LParam);
                            // TODO: If a window gets replaced, we lose app-level state such as overlay icons.
                            removeWindow(msg.LParam);
                            break;

                        case HSHELL.WINDOWACTIVATED:
                        case HSHELL.RUDEAPPACTIVATED:
                            ShellLogger.Debug("TasksService: Activated: " + msg.LParam);

                            foreach (var aWin in Windows.Where(w => w.State == ApplicationWindow.WindowState.Active))
                            {
                                aWin.State = ApplicationWindow.WindowState.Inactive;
                            }

                            if (msg.LParam != IntPtr.Zero)
                            {
                                ApplicationWindow win = null;

                                if (Windows.Any(i => i.Handle == msg.LParam))
                                {
                                    win       = Windows.First(wnd => wnd.Handle == msg.LParam);
                                    win.State = ApplicationWindow.WindowState.Active;
                                    win.SetShowInTaskbar();
                                }
                                else
                                {
                                    win = addWindow(msg.LParam, ApplicationWindow.WindowState.Active);
                                }

                                if (win != null)
                                {
                                    foreach (ApplicationWindow wind in Windows)
                                    {
                                        if (wind.WinFileName == win.WinFileName && wind.Handle != win.Handle)
                                        {
                                            wind.SetShowInTaskbar();
                                        }
                                    }
                                }
                            }
                            break;

                        case HSHELL.FLASH:
                            ShellLogger.Debug("TasksService: Flashing window: " + msg.LParam);
                            if (Windows.Any(i => i.Handle == msg.LParam))
                            {
                                ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);

                                if (win.State != ApplicationWindow.WindowState.Active)
                                {
                                    win.State = ApplicationWindow.WindowState.Flashing;
                                }

                                redrawWindow(win);
                            }
                            else
                            {
                                addWindow(msg.LParam, ApplicationWindow.WindowState.Flashing, true);
                            }
                            break;

                        case HSHELL.ACTIVATESHELLWINDOW:
                            ShellLogger.Debug("TasksService: Activate shell window called.");
                            break;

                        case HSHELL.ENDTASK:
                            ShellLogger.Debug("TasksService: EndTask called: " + msg.LParam);
                            removeWindow(msg.LParam);
                            break;

                        case HSHELL.GETMINRECT:
                            ShellLogger.Debug("TasksService: GetMinRect called: " + msg.LParam);
                            SHELLHOOKINFO winHandle = (SHELLHOOKINFO)Marshal.PtrToStructure(msg.LParam, typeof(SHELLHOOKINFO));
                            winHandle.rc = new NativeMethods.Rect {
                                Bottom = 100, Left = 0, Right = 100, Top = 0
                            };
                            Marshal.StructureToPtr(winHandle, msg.LParam, true);
                            msg.Result = winHandle.hwnd;
                            return;     // return here so the result isnt reset to DefWindowProc

                        case HSHELL.REDRAW:
                            ShellLogger.Debug("TasksService: Redraw called: " + msg.LParam);
                            if (Windows.Any(i => i.Handle == msg.LParam))
                            {
                                ApplicationWindow win = Windows.First(wnd => wnd.Handle == msg.LParam);

                                if (win.State == ApplicationWindow.WindowState.Flashing)
                                {
                                    win.State = ApplicationWindow.WindowState.Inactive;
                                }

                                redrawWindow(win);
                            }
                            else
                            {
                                addWindow(msg.LParam, ApplicationWindow.WindowState.Inactive, true);
                            }
                            break;

                        // TaskMan needs to return true if we provide our own task manager to prevent explorers.
                        // case HSHELL.TASKMAN:
                        //     SingletonLogger.Instance.Info("TaskMan Message received.");
                        //     break;

                        default:
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShellLogger.Error("TasksService: Error in ShellWinProc. ", ex);
                    Debugger.Break();
                }
            }
            else if (msg.Msg == WM_TASKBARCREATEDMESSAGE)
            {
                ShellLogger.Debug("TasksService: TaskbarCreated received, setting ITaskbarList window");
                setTaskbarListHwnd(_HookWin.Handle);
            }
            else
            {
                // Handle ITaskbarList functions, most not implemented yet

                ApplicationWindow win = null;

                switch (msg.Msg)
                {
                case (int)WM.USER + 50:
                    // ActivateTab
                    // Also sends WM_SHELLHOOK message
                    ShellLogger.Debug("TasksService: ITaskbarList: ActivateTab HWND:" + msg.LParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 60:
                    // MarkFullscreenWindow
                    ShellLogger.Debug("TasksService: ITaskbarList: MarkFullscreenWindow HWND:" + msg.LParam + " Entering? " + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 64:
                    // SetProgressValue
                    ShellLogger.Debug("TasksService: ITaskbarList: SetProgressValue HWND:" + msg.WParam + " Progress: " + msg.LParam);

                    win = new ApplicationWindow(this, msg.WParam);
                    if (Windows.Contains(win))
                    {
                        win = Windows.First(wnd => wnd.Handle == msg.WParam);
                        win.ProgressValue = (int)msg.LParam;
                    }

                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 65:
                    // SetProgressState
                    ShellLogger.Debug("TasksService: ITaskbarList: SetProgressState HWND:" + msg.WParam + " Flags: " + msg.LParam);

                    win = new ApplicationWindow(this, msg.WParam);
                    if (Windows.Contains(win))
                    {
                        win = Windows.First(wnd => wnd.Handle == msg.WParam);
                        win.ProgressState = (TBPFLAG)msg.LParam;
                    }

                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 67:
                    // RegisterTab
                    ShellLogger.Debug("TasksService: ITaskbarList: RegisterTab MDI HWND:" + msg.LParam + " Tab HWND: " + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 68:
                    // UnregisterTab
                    ShellLogger.Debug("TasksService: ITaskbarList: UnregisterTab Tab HWND: " + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 71:
                    // SetTabOrder
                    ShellLogger.Debug("TasksService: ITaskbarList: SetTabOrder HWND:" + msg.WParam + " Before HWND: " + msg.LParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 72:
                    // SetTabActive
                    ShellLogger.Debug("TasksService: ITaskbarList: SetTabActive HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 75:
                    // Unknown
                    ShellLogger.Debug("TasksService: ITaskbarList: Unknown HWND:" + msg.WParam + " LParam: " + msg.LParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 76:
                    // ThumbBarAddButtons
                    ShellLogger.Debug("TasksService: ITaskbarList: ThumbBarAddButtons HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 77:
                    // ThumbBarUpdateButtons
                    ShellLogger.Debug("TasksService: ITaskbarList: ThumbBarUpdateButtons HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 78:
                    // ThumbBarSetImageList
                    ShellLogger.Debug("TasksService: ITaskbarList: ThumbBarSetImageList HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 79:
                    // SetOverlayIcon - Icon
                    ShellLogger.Debug("TasksService: ITaskbarList: SetOverlayIcon - Icon HWND:" + msg.WParam);

                    win = new ApplicationWindow(this, msg.WParam);
                    if (Windows.Contains(win))
                    {
                        win = Windows.First(wnd => wnd.Handle == msg.WParam);
                        win.SetOverlayIcon(msg.LParam);
                    }

                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 80:
                    // SetThumbnailTooltip
                    ShellLogger.Debug("TasksService: ITaskbarList: SetThumbnailTooltip HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 81:
                    // SetThumbnailClip
                    ShellLogger.Debug("TasksService: ITaskbarList: SetThumbnailClip HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 85:
                    // SetOverlayIcon - Description
                    ShellLogger.Debug("TasksService: ITaskbarList: SetOverlayIcon - Description HWND:" + msg.WParam);

                    win = new ApplicationWindow(this, msg.WParam);
                    if (Windows.Contains(win))
                    {
                        win = Windows.First(wnd => wnd.Handle == msg.WParam);
                        win.SetOverlayIconDescription(msg.LParam);
                    }

                    msg.Result = IntPtr.Zero;
                    return;

                case (int)WM.USER + 87:
                    // SetTabProperties
                    ShellLogger.Debug("TasksService: ITaskbarList: SetTabProperties HWND:" + msg.WParam);
                    msg.Result = IntPtr.Zero;
                    return;
                }
            }

            msg.Result = DefWindowProc(msg.HWnd, msg.Msg, msg.WParam, msg.LParam);
        }
        public void CAN_OpenAllConnection()
        {
            lock (LockCanIdsDic) {
                hasChangeInNodesList = true;

                Canlib.canInitializeLibrary();
                foreach (var value in dic_CanChanels.Where(x => x.Value >= 0).Select(x => x.Value))
                {
                    Canlib.canBusOff(value);
                    Canlib.canClose(value);
                }
                //lastOpenedChanel = 0;
                dic_CanChanels.Clear();
                foreach (var entry in Globals.Vm_scis.Where(entry => entry != null))
                {
                    dic_CanChanels[entry.NodeId] = -1;
                }
                foreach (var key in dic_CanChanels.Select(x => x.Key).ToList())
                {
                    int openedChanel = Canlib.canOpenChannel(lastOpenedChanel + 1, key);
                    if (openedChanel >= 0)
                    {
                        dic_CanChanels[key] = openedChanel;
                    }
                }

                foreach (var entry in dic_CanChanels.Where(x => x.Value >= 0))
                {
                    Canlib.canSetBusParams(
                        handle: entry.Value,
                        freq: CANDesiredBitRate,
                        tseg2: 0,
                        tseg1: 0,
                        sjw: 0,
                        noSamp: 0,
                        syncmode: 0
                        );
                    Canlib.canBusOn(entry.Value);

                    //if (!setCanCardName() || !getCanBitRate()) {
                    //    CANStatus = Consts.BOOL_FAILED;
                    //    CANHandle = -1;
                    //}

                    //initialize the node
                    Canlib.canWrite(
                        handle: entry.Value,
                        id: 0,
                        msg: new byte[] { 1, (byte)entry.Key },
                        dlc: 2,    //size of msg
                        flag: 2    //we have defined this as const
                        );
                }
            }
            //get multiply value
            WriteToAll("AD", 0, true, true);

            //get ISR
            WriteToAll("AE", 0, true, true);
            graphStarted = false;
            //start Graph
            //todo fix for each nodeId
            Task.Factory.StartNew(() => {
                int i = 0;
                do
                {
                    if (Globals.Vm_scis.Count > 0)
                    {
                        Globals.Vm_scis[0].HighFrequencyOn = false;
                        FrequencyManager.SendCCComand(vm_sci: Globals.Vm_scis[0]);
                        Thread.Sleep(5);
                    }
                    else
                    {
                        Debugger.Break();
                    }
                } while (!graphStarted && i < 500 && Globals.Vm_scis.Count > 0);  //max 25 seconds
            });
        }
예제 #16
0
        /// <summary>
        /// Read the next serialized packet from the pipe.  Blocks until a packet is detected or the connection fails.
        /// </summary>
        /// <returns>Null if the connection fails or an IPacket that is the next available packet</returns>
        /// <remarks>This will automatically handle transitions from the network reader to the packet reader, but you can't transition the other way.</remarks>
        protected IPacket ReadSerializedPacket()
        {
            if (m_PacketReader == null)
            {
                //we haven't set up our packet reader - we're switching to serialized packet reading, so set everything up.
                m_PacketStream = new PipeStream(NetworkReadBufferLength);
                m_PacketReader = new PacketReader(m_PacketStream, false, m_MajorVersion, m_MinorVersion); //we keep writing to that memory stream, so its length will constantly change

                //register our packet factories we need
                OnPacketFactoryRegister(m_PacketReader);

                //before we jump in we need to transfer any buffeNetworkClientr remnant from the network serializer that
                //represents data the writer has already put into the pipeline
                if (m_NetworkSerializer != null)
                {
                    byte[] bufferTail = m_NetworkSerializer.UnusedData;

                    if ((bufferTail != null) && (bufferTail.Length > 0))
                    {
                        AppendToStream(m_PacketStream, bufferTail, bufferTail.Length);
                    }
                }
            }

            bool    socketClosed = false;
            IPacket nextPacket   = null;

#if GUARDBYTESONLY
            do
            {
                //instead of the packet reader we have to just compare against guardbytes.
                while (m_PacketStream.Position < m_PacketStream.Length)
                {
                    byte providedByte = (byte)m_PacketStream.ReadByte();
                    byte guardByte    = m_GuardPattern[m_BytesReceived % 4];
                    if (providedByte != guardByte)
                    {
                        Console.WriteLine("LiveStream: Read next byte as {0:x} but expected {1:x}", providedByte, guardByte);
                        Debugger.Break();
                    }
                    m_BytesReceived++;
                }

                //go into a blocking wait on the socket..  we'll loop until we get the whole buffer into the stream.
                byte[] buffer;
                int    newDataLength = ReadSocket(out buffer);

                if (newDataLength == 0)
                {
                    //this is the signal that the other end shut down the pipe.
                    socketClosed = true;
                }
                else
                {
                    AppendToStream(m_PacketStream, buffer, newDataLength);
                }
            } while ((socketClosed == false) && (nextPacket == null));
#else
            do
            {
                //see if we have another packet in the buffer...
                while ((m_PacketReader.DataAvailable) && (nextPacket == null)) //this has us loop over all bad packets in the buffer...
                {
                    try
                    {
                        nextPacket = m_PacketReader.Read();
                    }
                    catch (Exception ex)
                    {
                        m_HasCorruptData = true;
                        m_PacketsLostCount++;

                        GibraltarSerializationException serializationException = ex as GibraltarSerializationException;
                        if ((serializationException != null) && //and really this should always be the case...
                            (serializationException.StreamFailed))
                        {
                            if (!Log.SilentMode)
                            {
                                Log.Write(LogMessageSeverity.Error, LogWriteMode.Queued, ex, LogCategory, "Exception during packet stream read, unable to continue deserializing data",
                                          "While attempting to deserialize a packet an exception was reported. This has failed the stream so serialization will stop.\r\nException: {0}", ex.Message);
                            }

                            throw; //rethrow because this is terminal
                        }
                        else
                        {
                            if (!Log.SilentMode)
                            {
                                Log.Write(LogMessageSeverity.Error, LogWriteMode.Queued, ex, LogCategory, "Exception during packet read, discarding packet and continuing",
                                          "While attempting to deserialize a packet an exception was reported.  Since this may be a problem with just this one packet, we'll continue deserializing.\r\nException: {0}", ex.Message);
                            }
                        }
                    }
                }

                if (nextPacket == null) //at this point we know we've exhausted the read buffer and haven't found a valid packet.
                {
                    //go into a blocking wait on the socket..  we'll loop until we get the whole buffer into the stream.
                    byte[] buffer;
                    int    newDataLength = ReadSocket(out buffer);

                    if (newDataLength == 0)
                    {
                        //this is the signal that the other end shut down the pipe.
                        socketClosed = true;
                    }
                    else
                    {
                        AppendToStream(m_PacketStream, buffer, newDataLength);
                    }
                }
            } while ((socketClosed == false) && (nextPacket == null));

            m_PacketStream.Trim(); //we need to periodically let it release memory.
#endif
            return(nextPacket);
        }
        /// <summary>
        /// Discovers all SolidDna plug-ins
        /// </summary>
        /// <param name="loadAll">True to find all plug-ins in the same folder as the SolidDna dll</param>
        /// <returns></returns>
        public static List <SolidPlugIn> SolidDnaPlugIns(bool loadAll = true)
        {
            // Create new empty list
            var assemblies = new List <SolidPlugIn>();

            // Find all dll's in the same directory
            if (loadAll)
            {
                if (UseDetachedAppDomain)
                {
                    // Invalid combination... cannot load all from cross domain
                    // (we don't create the PlugInDetails class for each item
                    Debugger.Break();
                }

                // Clear old list
                PlugInDetails = new Dictionary <string, List <PlugInDetails> >();

                // Add new based on if found
                foreach (var path in Directory.GetFiles(PlugInFolder, "*.dll", SearchOption.TopDirectoryOnly))
                {
                    GetPlugIns(path, (plugin) => assemblies.Add(plugin));
                }
            }
            // Or load explicit ones
            else
            {
                // For each assembly
                foreach (var p in PlugInDetails)
                {
                    // And each plug-in inside it
                    foreach (var path in p.Value)
                    {
                        try
                        {
                            // If we are called in the main domain, cross-load
                            if (UseDetachedAppDomain)
                            {
                                // Create instance of the plug-in via cross-domain and cast back
                                var plugin = (dynamic)PlugInAppDomain.CreateInstanceAndUnwrap(
                                    path.AssemblyFullName,
                                    path.TypeFullName);

                                // If we got it, add it to the list
                                if (plugin != null)
                                {
                                    assemblies.Add(plugin);
                                }
                            }
                            else
                            {
                                GetPlugIns(path.FullPath, (plugin) => assemblies.Add(plugin));
                            }
                        }
                        catch
                        {
                            // TOOD: Report error
                        }
                    }
                }
            }

            return(assemblies);
        }
예제 #18
0
        private void Transpose(int direction)
        {
            int lineNum = 1;

            foreach (var item in lines)
            {
                if (item.ToString().Length > 0 && lineNum > 2)
                {
                    Char[] letters = item.ToString().ToCharArray();
                    if (letters[0] == '-')
                    {
                        for (int index = 0; index < letters.Length; index++)
                        {
                            if (Char.IsNumber(letters[index]))
                            {
                                int oldValue = Convert.ToInt16(letters[index].ToString());
                                int newValue = 0;
                                if (Char.IsNumber(letters[index + 1]))
                                {
                                    oldValue = (Convert.ToInt16(letters[index].ToString()) * 10) +
                                               (Convert.ToInt16(letters[index + 1].ToString()));
                                }

                                newValue = oldValue + direction;
                                if (newValue < 0)
                                {
                                    Debugger.Break();
                                }
                                if (newValue < 10 && oldValue > 9)
                                {
                                    letters[index]     = '-';
                                    letters[index + 1] = newValue.ToString().ToCharArray()[0];
                                    index++;
                                }
                                else if (newValue < 10 && oldValue < 10)
                                {
                                    letters[index] = newValue.ToString().ToCharArray()[0];
                                }
                                else
                                {
                                    letters[index]     = newValue.ToString().ToCharArray()[0];
                                    letters[index + 1] = newValue.ToString().ToCharArray()[1];
                                    index++;
                                }

                                if (index > letters.Length)
                                {
                                    break;
                                }
                            }
                        }
                        lines[lineNum - 1] = new String(letters);
                    }
                    else
                    {
                        for (int index = 1; index < letters.Length; index++)
                        {
                            if (Char.IsLetter(letters[index]) && Char.IsWhiteSpace(letters[index - 1]) &&
                                Char.IsUpper(letters[index]) &&
                                Array.Exists(ScaleUp, letter => letter == letters[index].ToString()))
                            {
                                if (index + 1 == letters.Length || letters[index + 1] == 'm' ||
                                    Char.IsNumber(letters[index + 1]) || Char.IsWhiteSpace(letters[index + 1]))
                                {
                                    string oldValue = letters[index].ToString();
                                    string newValue = String.Empty;
                                    if (direction < 0)
                                    {
                                        int oldValIndex = Array.IndexOf(ScaleDown, oldValue);
                                        if (oldValIndex < ScaleDown.Length)
                                        {
                                            newValue = ScaleDown[oldValIndex + 1];
                                        }
                                        else
                                        {
                                            newValue = ScaleDown.First();
                                        }
                                    }
                                    else
                                    {
                                        int oldValIndex = Array.IndexOf(ScaleDown, oldValue);
                                        if (oldValIndex < ScaleUp.Length)
                                        {
                                            newValue = ScaleUp[oldValIndex + 1];
                                        }
                                        else
                                        {
                                            newValue = ScaleUp.First();
                                        }
                                    }
                                    if (newValue.Length > 1)
                                    {
                                        letters[index - 1] = newValue.ToCharArray()[0];
                                        letters[index]     = newValue.ToCharArray()[1];
                                    }
                                    else
                                    {
                                        letters[index] = newValue.ToCharArray()[0];
                                    }
                                }
                            }
                        }
                        lines[lineNum - 1] = new String(letters);
                    }
                }
                lineNum++;
            }
            listBox1.Items.Clear();
            listBox1.Items.AddRange(lines);
        }
예제 #19
0
        /// <summary>
        /// Performs the regular backup
        /// </summary>
        public void PerformBackup(dynamic backupOptions = null)
        {
            if (DateTime.Now.Subtract(_LastBackupCheck).TotalMinutes > 30)
            {
                _LastBackupCheck = DateTime.Now;
            }
            else
            {
                // No Need to do the backup now
                return;
            }

#if DEBUG
            Debugger.Break();
#endif
            Action cleanUp = null;

            var compression  = 1;
            var mode         = "hourly";
            var databaseFile = this.DatabaseFileName;

            string backupPath = Path.Combine(this.DatabaseDirectory, "Backups");

            if (backupOptions != null)
            {
                if (backupOptions.compression != null)
                {
                    compression = (int)backupOptions.compression;
                }

                if (backupOptions.uncpath != null)
                {
                    var existed = DriveInfo.GetDrives().ToDictionary(d => d.Name);
                    var chosen  = '\0';
                    for (char i = 'A'; i < 'Z'; i++)
                    {
                        if (existed.ContainsKey(i + @":\") == false)
                        {
                            chosen = i;
                            break;
                        }
                    }

                    if (chosen != '\0')
                    {
                        string command = string.Empty;

                        if (backupOptions.username != null && backupOptions.password != null)
                        {
                            command = string.Format("use {0}: {1} /u:{2} {3}",
                                                    chosen,
                                                    backupOptions.uncpath,
                                                    backupOptions.username,
                                                    backupOptions.password);
                        }
                        else
                        {
                            command = string.Format("use {0}: {1}",
                                                    chosen,
                                                    backupOptions.uncpath);
                        }

                        var process = Process.Start("net.exe", command);
                        process.WaitForExit();

                        if (process.ExitCode == 0)
                        {
                            cleanUp = () =>
                            {
                                string cmd = string.Format("use {0}: /delete",
                                                           chosen);

                                var p2 = Process.Start("net.exe", cmd);
                                p2.WaitForExit();
                            };

                            backupPath = chosen + ":\\";
                        }
                    }
                }

                if (backupOptions.sitename != null)
                {
                    backupPath = Path.Combine(backupPath, (string)backupOptions.sitename);
                }
            }

            try
            {
                if (mode == "hourly")
                {
                    backupPath = Path.Combine(backupPath, "DatabaseBackup-Hourly");
                    Directory.CreateDirectory(backupPath);

                    // create hourly backup
                    var backupFile = Path.Combine(backupPath, string.Format("hourlybackup-{0:HH}.sqlite.bz2", DateTime.Now));
                    if (File.Exists(backupFile) == false)
                    {
                        NancyBlackDatabase.BZip(databaseFile, backupFile);
                    }
                    else
                    {
                        // check modified date
                        if (File.GetLastWriteTime(backupFile).Date < DateTime.Now.Date)
                        {
                            // it was the yesterday's file, replace it
                            NancyBlackDatabase.BZip(databaseFile, backupFile);
                        }
                    }
                }

                if (mode == "daily")
                {
                    backupPath = Path.Combine(backupPath, "DatabaseBackup-Hourly");
                    Directory.CreateDirectory(backupPath);

                    var dailybackupFile = Path.Combine(backupPath, string.Format("dailybackup-{0:dd-MM-yyyy}.sqlite.bz2", DateTime.Now));
                    if (File.Exists(dailybackupFile) == false)
                    {
                        NancyBlackDatabase.BZip(databaseFile, dailybackupFile, 9); // max compression for daily backup
                    }

                    var backupFiles = Directory.GetFiles(backupPath, "dailybackup-*.sqlite.bz2");
                    var now         = DateTime.Now;
                    var maxDay      = 30;

                    if (backupOptions.dailyretention != null)
                    {
                        maxDay = (int)backupOptions.dailyretention;
                    }

                    foreach (var file in backupFiles)
                    {
                        if (now.Subtract(File.GetCreationTime(file)).TotalDays > maxDay)
                        {
                            try
                            {
                                File.Delete(file); // delete backup older than 30 days
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                // retry backup again
                _LastBackupCheck = DateTime.MinValue;
            }
            finally
            {
                if (cleanUp != null)
                {
                    cleanUp();
                }
            }
        }
 public UC_Plot1()
 {
     DataContext = this;
     InitializeComponent();
     Loaded += (a, e) => { Debugger.Break(); };
 }
예제 #21
0
        /// <summary>
        /// This method is syntaxtic sugar for atempting to read a data field
        /// from an XmlNode. This version sets the output variable to its
        /// default value in case of a failed read and can be used for
        /// initializing variables
        /// </summary>
        /// <typeparam name="T">The type to convert to</typeparam>
        /// <param name="node">The XmlNode to read from</param>
        /// <param name="field">The field to try and extract from the XmlNode</param>
        /// <param name="read">The variable to save the read to</param>
        /// <param name="onError">The value to return in case of failure. This parameter is optional</param>
        /// <returns>true if successful read</returns>
        public static bool TryGetField <T>(this XmlNode node, String field, out T read, T onError = default(T)) where T : IConvertible
        {
            /*
             * This extension method allows easier access of xml, instead of
             * the old TryCatch blocks, not even logging the error
             *
             * It works because most of the types we read from the XmlNode is
             * IConvertible that can be converted to or from string with just
             * a type argument, first known at runtime (not true, but generics)
             *
             * because it is now a generic method, instead of
             * try{convert();}
             * catch{noop();}
             *
             * We can do some acctual error checking instead of relying on exceptions
             * in case anything happens. We could do that before, but typing 10
             * lines to read a single variable 100 times would be insane
             *
             * That means this should be an order of magnitude faster in case of
             * missing fields and a little bit slower in case of fields being there
             *
             * To use this method, call it like this
             *
             * aXmlNode.TryGetField("fieldname", out myVariable);
             *
             * The compiler will fill out <T> itself, unless you specificaly
             * tell it to be something else
             *
             * in case you need to act on weither the read was successfull
             * do it like this
             * if(aXmlNode.TryGetField("fieldname", out myVariable))
             * {
             *     success();
             * }
             * else
             * {
             *     failure();
             * }
             */
            string fieldValue = null;

            if (!CheckGetField <T>(node, field, ref fieldValue))
            {
                read = onError;
                return(false);
            }


            try
            {
                read = (T)Convert.ChangeType(fieldValue, typeof(T));
                return(true);
            }
            catch (Exception)
            {
                //If we are debugging, great
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                //Otherwise just log it
#if DEBUG
                System.Reflection.MethodBase mth
                    = new StackTrace().GetFrame(1).GetMethod();
                String errorMsg = String.Format("Tried to read missing field \"{0}\" in {1}.{2}", field, mth.ReflectedType.Name, mth);
#else
                String errorMsg = String.Format("Tried to read missing field \"{0}\"", field);
#endif
                Log.Error(errorMsg);

                //Finaly, we have to assign an out parameter something, so default
                //null or 0 most likeley
                read = onError;
                return(false);
            }
        }
예제 #22
0
        private async void Hyperlink_Click(TLTextUrl urlText)
        {
            if (urlText.WebPageId == _webpageId)
            {
                var fragmentStart = urlText.Url.IndexOf('#');
                if (fragmentStart > 0)
                {
                    var name = urlText.Url.Substring(fragmentStart + 1);
                    if (_anchors.TryGetValue(name, out Border anchor))
                    {
                        ScrollingHost.ScrollIntoView(anchor);
                        //anchor.StartBringIntoView();
                        return;

                        if (_scrollingHost == null)
                        {
                            _scrollingHost = ScrollingHost.Descendants <ScrollViewer>().FirstOrDefault() as ScrollViewer;
                        }

                        if (_scrollingHost != null)
                        {
                            var transform = anchor.TransformToVisual(ScrollingHost.ItemsPanelRoot);
                            var position  = transform.TransformPoint(new Point());

                            _scrollingHost.ChangeView(null, Math.Max(0, position.Y - 8), null, false);
                        }
                    }
                }
            }
            else if (urlText.WebPageId != 0)
            {
                var protoService = (MTProtoService)MTProtoService.Current;
                protoService.SendInformativeMessageInternal <TLWebPageBase>("messages.getWebPage", new TLMessagesGetWebPage {
                    Url = urlText.Url, Hash = 0
                },
                                                                            result =>
                {
                    Execute.BeginOnUIThread(() =>
                    {
                        ViewModel.NavigationService.Navigate(typeof(InstantPage), result);
                    });
                },
                                                                            fault =>
                {
                    Debugger.Break();
                });
            }
            else
            {
                var url = urlText.Url;
                if (url.StartsWith("http") == false)
                {
                    url = "http://" + url;
                }

                if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
                {
                    if (Constants.TelegramHosts.Contains(uri.Host))
                    {
                        MessageHelper.HandleTelegramUrl(urlText.Url);
                    }
                    else
                    {
                        await Launcher.LaunchUriAsync(uri);
                    }
                }
            }
        }
예제 #23
0
 private void DbgButton_Click(object sender, RoutedEventArgs e)
 {
     Debugger.Break();
 }
예제 #24
0
        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                Debugger.Break();
            }
            else
            {
                //ATT: Programatically exiting app...
                if (e.Exception.Message == "Cannot go back when CanGoBack is false.")
                {
                    return;
                }

                string sException = "RootFrame_NavigationFailed...\n\nMessage:\n" + e.Exception.Message +
                                    "\n\nStack Trace:\n" + e.Exception.StackTrace;

                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();

                string sPath = "System";
                if (!store.DirectoryExists(sPath))
                {
                    store.CreateDirectory(sPath);
                }
                sPath += "\\Events";
                if (!store.DirectoryExists(sPath))
                {
                    store.CreateDirectory(sPath);
                }

                DateTime dNow = DateTime.Now;
                sPath += "\\";
                sPath += dNow.Year.ToString() + "-";
                if (dNow.Month < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Month.ToString() + "-";
                if (dNow.Day < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Day.ToString();
                sPath += "_";
                if (dNow.Hour < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Hour.ToString() + "-";
                if (dNow.Minute < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Minute.ToString() + "-";
                if (dNow.Second < 10)
                {
                    sPath += "0";
                }
                sPath += dNow.Second.ToString();

                string sPathWrk = sPath;
                int    i        = 0;
                for (;;)
                {
                    sPathWrk = sPath + "_" + i.ToString();
                    if (!store.FileExists(sPathWrk + ".error"))
                    {
                        break;
                    }
                    i++;
                }
                sPath = sPathWrk + ".error";
                IsolatedStorageFileStream stream = store.CreateFile(sPath);
                StreamWriter sw = new StreamWriter(stream);
                sw.Write(sException);
                sw.Close();
                stream.Close();

                MessageBox.Show(sException);
            }
        }
        public static void Run()
        {
            var monitoringTimeSec = 10;

            Out.WriteLine("******************** KernelAndClrMonitor DEMO (Win7) ********************");
            Out.WriteLine("Printing both Kernel and CLR (user mode) events simultaneously");
            Out.WriteLine("The monitor will run for a maximum of {0} seconds", monitoringTimeSec);
            Out.WriteLine("Press Ctrl-C to stop monitoring early.");
            Out.WriteLine();
            Out.WriteLine("Start a .NET program to see some events!");
            Out.WriteLine();
            if (TraceEventSession.IsElevated() != true)
            {
                Out.WriteLine("Must be elevated (Admin) to run this program.");
                Debugger.Break();
                return;
            }

            // Set up Ctrl-C to stop both user mode and kernel mode sessions
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs cancelArgs) =>
            {
                StopSessions();
                cancelArgs.Cancel = true;
            };

            // Note that because there are different sessions, the events may not be printed
            // in time order since the different sessions may flush their buffers at different
            // times.   If you care, you must buffer the events and order them by event
            // timestamp.   Note that the timestamps however ARE accurate.
            Out.WriteLine("Setup up threads to process the events");

            // start processing kernel events on a thread pool thread
            var task1 = Task.Run(() =>
            {
                // Note that TraceEventSession and EtwTraceEventParser are IN GENERAL NOT THREADSAFE,
                // Normally this is not a hardship you just set up the session TraceDispacher on one
                // thread.  It is OK to call a session's Dispose() and 'Enable and Disable provider APIS
                // from another thread, but things associated with ETWTraceEventSource and TraceEventParsers
                // should all be on the same thread.
                Out.WriteLine("Kernel event Thread Starting");
                Out.WriteLine("Enabling Image load, thread and process kernel events.");
                using (s_kernelSession = new TraceEventSession(KernelTraceEventParser.KernelSessionName))
                {
                    // Enable the events we care about for the kernel in the kernel session
                    // For this instant the session will buffer any incoming events.
                    // If you only have to run on Win8 systems you can use one session for both.
                    // Here we turn in process, thread and Image load events.
                    s_kernelSession.EnableKernelProvider(
                        KernelTraceEventParser.Keywords.ImageLoad |
                        KernelTraceEventParser.Keywords.Process |
                        KernelTraceEventParser.Keywords.Thread);

                    // You should do all processing from a single source on a single thread.
                    // Thus call calls to .Source, or Process() should be on the same thread.
                    s_kernelSession.Source.Kernel.All += Print;
#if DEBUG
                    // in debug builds it is useful to see any unhandled events because they could be bugs.
                    s_kernelSession.Source.UnhandledEvents += Print;
#endif
                    // process events until Ctrl-C is pressed

                    Out.WriteLine("Waiting on kernel events.");
                    s_kernelSession.Source.Process();
                }
                Out.WriteLine("Thread 1 dieing");
            });

            // start processing CLR events on a thread pool thread
            var task2 = Task.Run(() =>
            {
                // Note that TraceEventSession and EtwTraceEventParser are IN GENERAL NOT THREADSAFE,
                // Normally this is not a hardship you just set up the session TraceDispacher on one
                // thread.  It is OK to call a session's Dispose() and 'Enable and Disable provider APIS
                // from another thread, but things associated with ETWTraceEventSource and TraceEventParsers
                // should all be on the same thread.
                using (s_userSession = new TraceEventSession("MonitorKernelAndClrEventsSession"))
                {
                    Out.WriteLine("Enabling CLR GC and Exception events.");
                    // Enable the events we care about for the CLR (in the user session).
                    // unlike the kernel session, you can call EnableProvider on other things too.
                    // For this instant the ;session will buffer any incoming events.
                    s_userSession.EnableProvider(
                        ClrTraceEventParser.ProviderGuid,
                        TraceEventLevel.Informational,
                        (ulong)(ClrTraceEventParser.Keywords.GC | ClrTraceEventParser.Keywords.Exception));

                    // s_userSession.Source.Clr.GCHeapStats += (GCHeapStatsTraceData data) => Out.WriteLine(" ", data.GenerationSize0);

                    Out.WriteLine("User event Thread  Starting");
                    s_userSession.Source.Clr.All += Print;
#if DEBUG
                    // in debug builds it is useful to see any unhandled events because they could be bugs.
                    s_userSession.Source.UnhandledEvents += Print;
#endif
                    // process events until Ctrl-C is pressed or timeout expires
                    Out.WriteLine("Waiting on user events.");
                    s_userSession.Source.Process();
                }
                Out.WriteLine("Thread 2 dieing");
            });

            // Set up a timer to stop processing after monitoringTimeSec
            var timer = new Timer(delegate(object state)
            {
                Out.WriteLine("Stopped Monitoring after {0} sec", monitoringTimeSec);
                StopSessions();
            }, null, monitoringTimeSec * 1000, Timeout.Infinite);

            // Wait until tasks are complete
            Out.WriteLine("Waiting for processing tasks to complete");
            Task.WaitAll(task1, task2);
            Out.WriteLine("Monitoring stopped");
            timer.Dispose();
        }
예제 #26
0
        public Path[] GetAllPaths(PathfinderNode[] StartNodes, PathfinderNode FinishNode, int MinClearance)
        {
            var StartNodeCount   = StartNodes.GetUpperBound(0) + 1;
            var LayerStartNodes  = new PathfinderNode[32, StartNodeCount];
            var LayerFinishNodes = new PathfinderNode[32];
            var LayerNum         = 0;
            var FloodRouteDArgs  = new sFloodRouteAllArgs();
            var FinalLayer       = 0;
            var StartCanReach    = new bool[StartNodeCount];
            var tmpNodeA         = default(PathfinderNode);
            var CanReachCount    = 0;
            var FirstLayer       = 0;
            var SubPaths         = new Path[32];
            var Nodes_Nodes      = NetworkLargeArrays.Nodes_Nodes;
            var Visit            = NetworkLargeArrays.Nodes_Booleans;
            var NodeValues       = NetworkLargeArrays.Nodes_ValuesA;
            var NodeValuesB      = NetworkLargeArrays.Nodes_ValuesB;
            var A = 0;
            var B = 0;
            var C = 0;
            var D = 0;

            FinalLayer = StartNodes[0].Layer.Network_LayerNum;
            LayerFinishNodes[FinalLayer] = FinishNode;
            B = FinalLayer;
            do
            {
                if (LayerFinishNodes[B].ParentNode == null)
                {
                    FirstLayer = B;
                    break;
                }
                LayerFinishNodes[B + 1] = LayerFinishNodes[B].ParentNode;
                B++;
            } while (true);
            for (A = 0; A <= StartNodeCount - 1; A++)
            {
                LayerStartNodes[FinalLayer, A] = StartNodes[A];
                B = FinalLayer;
                do
                {
                    if (LayerStartNodes[B, A].ParentNode == null)
                    {
                        if (LayerStartNodes[B, A] == LayerFinishNodes[B])
                        {
                            StartCanReach[A] = true;
                            CanReachCount++;
                        }
                        break;
                    }
                    LayerStartNodes[B + 1, A] = LayerStartNodes[B, A].ParentNode;
                    B++;
                } while (true);
            }
            if (CanReachCount == 0)
            {
                return(null);
            }
            LayerNum                     = FirstLayer;
            SubPaths[LayerNum]           = new Path();
            SubPaths[LayerNum].Nodes     = new[] { LayerFinishNodes[LayerNum] };
            SubPaths[LayerNum].NodeCount = 1;
            var LastLayer = 0;

            do
            {
                LastLayer = LayerNum;
                LayerNum--;
                if (LayerNum < FinalLayer)
                {
                    break;
                }
                for (A = 0; A <= SubPaths[LastLayer].NodeCount - 1; A++)
                {
                    tmpNodeA = SubPaths[LastLayer].Nodes[A];
                    for (B = 0; B <= tmpNodeA.ConnectionCount - 1; B++)
                    {
                        C        = tmpNodeA.Connections[B].GetOtherNode(tmpNodeA).Layer_NodeNum;
                        Visit[C] = false;
                    }
                }
                for (A = 0; A <= SubPaths[LastLayer].NodeCount - 1; A++)
                {
                    tmpNodeA = SubPaths[LastLayer].Nodes[A];
                    C        = tmpNodeA.Layer_NodeNum;
                    Visit[C] = true;
                    for (D = 0; D <= tmpNodeA.NodeCount - 1; D++)
                    {
                        C              = tmpNodeA.Nodes[D].Layer_NodeNum;
                        NodeValues[C]  = float.MaxValue;
                        NodeValuesB[C] = float.MaxValue;
                    }
                }
                FloodRouteDArgs               = new sFloodRouteAllArgs();
                FloodRouteDArgs.FinishNode    = LayerFinishNodes[LayerNum];
                FloodRouteDArgs.Visit         = Visit;
                FloodRouteDArgs.NodeValuesA   = NodeValues;
                FloodRouteDArgs.SourceNodes   = Nodes_Nodes;
                FloodRouteDArgs.NodeValuesB   = NodeValuesB;
                FloodRouteDArgs.MinClearance  = MinClearance;
                FloodRouteDArgs.BestTolerance = (float)(Math.Pow(1.1D, LayerNum));
                FloodRouteDArgs.StartNodes    = new PathfinderNode[StartNodeCount];
                for (A = 0; A <= StartNodeCount - 1; A++)
                {
                    if (StartCanReach[A])
                    {
                        FloodRouteDArgs.StartNodes[FloodRouteDArgs.StartNodeCount] = LayerStartNodes[LayerNum, A];
                        FloodRouteDArgs.StartNodeCount++;
                    }
                }
                Array.Resize(ref FloodRouteDArgs.StartNodes, FloodRouteDArgs.StartNodeCount);
                FloodRouteAll(ref FloodRouteDArgs);
                SubPaths[LayerNum]       = new Path();
                SubPaths[LayerNum].Nodes = new PathfinderNode[FloodRouteDArgs.BestNodeCount];
                for (A = 0; A <= FloodRouteDArgs.BestNodeCount - 1; A++)
                {
                    SubPaths[LayerNum].Nodes[A] = FloodRouteDArgs.SourceNodes[A];
                }
                SubPaths[LayerNum].NodeCount = FloodRouteDArgs.BestNodeCount;
                if (FloodRouteDArgs.BestNodeCount == 0)
                {
                    Debugger.Break();
                    return(SubPaths);
                }
            } while (true);
            return(SubPaths);
        }
예제 #27
0
        static public AjaxCallResult ProcessTransactionReceived(string guid, string txHash)
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture(); // just to make sure we're called properly
            BitcoinChain       chain    = BitcoinChain.Cash;

            string bitcoinAddress = (string)GuidCache.Get(guid);

            if (BitcoinUtility.TestUnspents(chain, bitcoinAddress))
            {
                HotBitcoinAddressUnspents unspents = HotBitcoinAddress.FromAddress(chain, bitcoinAddress).Unspents;
                Int64 satoshisReceived             = unspents.Last().AmountSatoshis;

                if (unspents.Last().TransactionHash != txHash && txHash.Length > 0)
                {
                    // Race condition.
                    Debugger.Break();
                }

                HotBitcoinAddressUnspent utxoToReturn = unspents.Last();

                Swarmops.Logic.Financial.Money moneyReceived = new Swarmops.Logic.Financial.Money(satoshisReceived,
                                                                                                  Currency.BitcoinCash);

                // Make sure that the hotwallet native currency is bitcoin
                authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.ForeignCurrency = Currency.BitcoinCash;

                // Create success message and ledger transaction
                string successMessage = string.Empty;

                // TODO: Get the tx, get the input

                string returnAddress = BitcoinUtility.GetInputAddressesForTransaction(chain, txHash) [0]; // assumes at least one input address

                // Return the money, too. Set fee for a 300-byte transaction.

                ReturnBitcoinEchoUtxoOrder backendOrder = new ReturnBitcoinEchoUtxoOrder(utxoToReturn);
                backendOrder.Create(authData.CurrentOrganization, authData.CurrentUser);

                string tx1Description = "Bitcoin technical echo test (will be repaid immediately)";


                if (authData.CurrentOrganization.Currency.IsBitcoinCash)
                {
                    // The ledger is native bitcoin, so cent units are satoshis

                    FinancialTransaction ledgerTx1 = FinancialTransaction.Create(authData.CurrentOrganization,
                                                                                 DateTime.UtcNow, tx1Description);
                    ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, -(satoshisReceived), authData.CurrentUser);
                    ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, satoshisReceived, authData.CurrentUser);
                    ledgerTx1.BlockchainHash = txHash;

                    // The return payment will be logged when made, so its hash can be recorded

                    if (satoshisReceived % 100 == 0)
                    {
                        successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative,
                                                       (satoshisReceived / 100.0).ToString("N0"));
                    }
                    else
                    {
                        successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceivedNative,
                                                       (satoshisReceived / 100.0).ToString("N2"));
                    }
                }
                else
                {
                    // The ledger is NOT native bitcoin, so we'll need to convert currencies

                    long orgNativeCents            = moneyReceived.ToCurrency(authData.CurrentOrganization.Currency).Cents;
                    FinancialTransaction ledgerTx1 = FinancialTransaction.Create(authData.CurrentOrganization,
                                                                                 DateTime.UtcNow, tx1Description);
                    ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.DebtsOther, -orgNativeCents, authData.CurrentUser);
                    ledgerTx1.AddRow(authData.CurrentOrganization.FinancialAccounts.AssetsBitcoinHot, orgNativeCents, authData.CurrentUser).AmountForeignCents = new Swarmops.Logic.Financial.Money(satoshisReceived, Currency.BitcoinCash);
                    ledgerTx1.BlockchainHash = txHash;

                    // The second transaction is logged when executed in the back-end order

                    successMessage = string.Format(Resources.Pages.Admin.BitcoinEchoTest_FundsReceived,
                                                   authData.CurrentOrganization.Currency.DisplayCode, orgNativeCents / 100.0, satoshisReceived / 100.0);
                }

                return(new AjaxCallResult()
                {
                    DisplayMessage = successMessage, Success = true
                });

                // TODO: Ack donation via mail?
                // TODO: Notify CFO/etc of donation?
            }

            return(new AjaxCallResult()
            {
                Success = false
            });
        }
예제 #28
0
        public PathList[] GetPath(PathfinderNode[] StartNodes, PathfinderNode FinishNode, int Accuracy, int MinClearance)
        {
            var StartNodeCount   = StartNodes.GetUpperBound(0) + 1;
            var Paths            = new PathList[NodeLayerCount];
            var LayerStartNodes  = new PathfinderNode[NodeLayerCount, StartNodeCount];
            var LayerFinishNodes = new PathfinderNode[NodeLayerCount];
            var LayerNum         = 0;
            var Destinations     = new PathfinderNode[24];
            var DestinationCount = 0;
            var FinishIsParent   = default(bool);
            var CalcNodeCount    = new int[24];
            var FloodRouteArgs   = new sFloodRouteArgs();
            var FinalLayer       = 0;
            var StartCanReach    = new bool[StartNodeCount];
            var tmpNodeA         = default(PathfinderNode);
            var tmpNodeB         = default(PathfinderNode);
            var CanReachCount    = 0;
            var FirstLayer       = 0;
            var BestPaths        = new Path[24];
            var BestValues       = new float[24];
            var PathNum          = 0;
            var StopMultiPathing = default(bool);
            var Visit            = NetworkLargeArrays.Nodes_Booleans;
            var NodeValues       = NetworkLargeArrays.Nodes_ValuesA;
            var Nodes_Nodes      = NetworkLargeArrays.Nodes_Nodes;
            var StartPath        = NetworkLargeArrays.Nodes_Path;
            var A = 0;
            var B = 0;
            var C = 0;
            var D = 0;
            var E = 0;

            FinalLayer = StartNodes[0].Layer.Network_LayerNum;
            LayerFinishNodes[FinalLayer] = FinishNode;
            B = FinalLayer;
            do
            {
                if (LayerFinishNodes[B].ParentNode == null)
                {
                    FirstLayer = B;
                    break;
                }
                LayerFinishNodes[B + 1] = LayerFinishNodes[B].ParentNode;
                B++;
            } while (true);
            for (A = 0; A <= StartNodeCount - 1; A++)
            {
                LayerStartNodes[FinalLayer, A] = StartNodes[A];
                B = FinalLayer;
                do
                {
                    if (LayerStartNodes[B, A].ParentNode == null)
                    {
                        if (LayerStartNodes[B, A] == LayerFinishNodes[B])
                        {
                            StartCanReach[A] = true;
                            CanReachCount++;
                        }
                        break;
                    }
                    LayerStartNodes[B + 1, A] = LayerStartNodes[B, A].ParentNode;
                    B++;
                } while (true);
            }
            if (CanReachCount == 0)
            {
                return(null);
            }
            LayerNum = FirstLayer;
            Paths[LayerNum].Paths              = new Path[0];
            Paths[LayerNum].Paths[0]           = new Path();
            Paths[LayerNum].PathCount          = 1;
            Paths[LayerNum].Paths[0].Nodes     = new PathfinderNode[1];
            Paths[LayerNum].Paths[0].Nodes[0]  = LayerFinishNodes[LayerNum];
            Paths[LayerNum].Paths[0].NodeCount = 1;
            var LastLayer = 0;

            do
            {
                LastLayer = LayerNum;
                LayerNum--;
                if (LayerNum < FinalLayer)
                {
                    break;
                }
                if (StopMultiPathing)
                {
                    if (Accuracy < 0)
                    {
                        Debugger.Break();
                    }
                    for (PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++)
                    {
                        CalcNodeCount[PathNum] = Math.Min(Accuracy, Convert.ToInt32(Paths[LastLayer].Paths[PathNum].NodeCount - 1));
                    }
                    Destinations[0]  = Paths[LastLayer].Paths[0].Nodes[CalcNodeCount[0]];
                    DestinationCount = 1;
                    FinishIsParent   = true;
                }
                else
                {
                    if (Accuracy >= 0)
                    {
                        for (PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++)
                        {
                            if (Paths[LastLayer].Paths[PathNum].NodeCount > Accuracy)
                            {
                                StopMultiPathing = true;
                                break;
                            }
                        }
                    }
                    Destinations[0] = LayerFinishNodes[LayerNum];
                    if (LayerNum == FinalLayer)
                    {
                        DestinationCount = 1;
                    }
                    else
                    {
                        for (A = 0; A <= Destinations[0].ConnectionCount - 1; A++)
                        {
                            Destinations[1 + A] = Destinations[0].Connections[A].GetOtherNode(Destinations[0]);
                        }
                        DestinationCount = 1 + Destinations[0].ConnectionCount;
                    }
                    for (PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++)
                    {
                        CalcNodeCount[PathNum] = Paths[LastLayer].Paths[PathNum].NodeCount - 1;
                    }
                    FinishIsParent = false;
                }
                for (PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++)
                {
                    for (A = 0; A <= CalcNodeCount[PathNum]; A++)
                    {
                        tmpNodeA = Paths[LastLayer].Paths[PathNum].Nodes[A];
                        for (D = 0; D <= tmpNodeA.ConnectionCount - 1; D++)
                        {
                            tmpNodeB = tmpNodeA.Connections[D].GetOtherNode(tmpNodeA);
                            for (E = 0; E <= tmpNodeB.ConnectionCount - 1; E++)
                            {
                                C        = tmpNodeB.Connections[E].GetOtherNode(tmpNodeB).Layer_NodeNum;
                                Visit[C] = false;
                            }
                        }
                    }
                }
                for (PathNum = 0; PathNum <= Paths[LastLayer].PathCount - 1; PathNum++)
                {
                    for (A = 0; A <= CalcNodeCount[PathNum]; A++)
                    {
                        tmpNodeA = Paths[LastLayer].Paths[PathNum].Nodes[A];
                        C        = tmpNodeA.Layer_NodeNum;
                        Visit[C] = true;
                        for (E = 0; E <= tmpNodeA.NodeCount - 1; E++)
                        {
                            C             = tmpNodeA.Nodes[E].Layer_NodeNum;
                            NodeValues[C] = float.MaxValue;
                        }
                        for (D = 0; D <= tmpNodeA.ConnectionCount - 1; D++)
                        {
                            tmpNodeB = tmpNodeA.Connections[D].GetOtherNode(tmpNodeA);
                            C        = tmpNodeB.Layer_NodeNum;
                            Visit[C] = true;
                            for (E = 0; E <= tmpNodeB.NodeCount - 1; E++)
                            {
                                C             = tmpNodeB.Nodes[E].Layer_NodeNum;
                                NodeValues[C] = float.MaxValue;
                            }
                        }
                    }
                }
                FloodRouteArgs                 = new sFloodRouteArgs();
                FloodRouteArgs.CurrentPath     = StartPath;
                FloodRouteArgs.FinishNodes     = Destinations;
                FloodRouteArgs.FinishNodeCount = DestinationCount;
                FloodRouteArgs.FinishIsParent  = FinishIsParent;
                FloodRouteArgs.Visit           = Visit;
                FloodRouteArgs.NodeValues      = NodeValues;
                FloodRouteArgs.SourceNodes     = Nodes_Nodes;
                FloodRouteArgs.MinClearance    = MinClearance;
                for (A = 0; A <= DestinationCount - 1; A++)
                {
                    BestPaths[A]  = null;
                    BestValues[A] = float.MaxValue;
                }
                for (A = 0; A <= StartNodeCount - 1; A++)
                {
                    if (StartCanReach[A])
                    {
                        StartPath.NodeCount      = 1;
                        StartPath.Nodes[0]       = LayerStartNodes[LayerNum, A];
                        StartPath.Value          = 0.0F;
                        FloodRouteArgs.BestPaths = new Path[DestinationCount];
                        FloodRoute(ref FloodRouteArgs);
                        for (PathNum = 0; PathNum <= DestinationCount - 1; PathNum++)
                        {
                            if (FloodRouteArgs.BestPaths[PathNum] != null)
                            {
                                if (FloodRouteArgs.BestPaths[PathNum].Value < BestValues[PathNum])
                                {
                                    BestValues[PathNum] = FloodRouteArgs.BestPaths[PathNum].Value;
                                    BestPaths[PathNum]  = FloodRouteArgs.BestPaths[PathNum];
                                }
                            }
                        }
                    }
                }
                Paths[LayerNum].Paths     = new Path[DestinationCount];
                Paths[LayerNum].PathCount = 0;
                for (PathNum = 0; PathNum <= DestinationCount - 1; PathNum++)
                {
                    if (BestPaths[PathNum] != null)
                    {
                        Paths[LayerNum].Paths[Paths[LayerNum].PathCount] = BestPaths[PathNum];
                        Paths[LayerNum].PathCount++;
                    }
                }
                Array.Resize(ref Paths[LayerNum].Paths, Paths[LayerNum].PathCount);
                if (Paths[LayerNum].PathCount == 0)
                {
                    return(null);
                }
            } while (true);
            return(Paths);
        }
예제 #29
0
        private async Task RecognizeInkerText()
        {
            try
            {
                var inkRecognizer      = new InkRecognizerContainer();
                var recognitionResults = await inkRecognizer.RecognizeAsync(_inker.InkPresenter.StrokeContainer, InkRecognitionTarget.All);

                List <TextBox> boxes = new List <TextBox>();

                var   ttv          = _contentPresenter.TransformToVisual(Window.Current.Content);
                Point offsetCoords = ttv.TransformPoint(new Point(0, 0));
                foreach (var result in recognitionResults)
                {
                    List <UIElement> elements = new List <UIElement>(
                        VisualTreeHelper.FindElementsInHostCoordinates(
                            new Rect(
                                new Point(
                                    result.BoundingRect.X + offsetCoords.X,
                                    result.BoundingRect.Y + offsetCoords.Y),
                                new Size(result.BoundingRect.Width, result.BoundingRect.Height)),
                            _contentPresenter));

                    // find one with overlap
                    var textBoxes = elements.Where(el => el is TextBox && (el as TextBox).IsEnabled);

                    var     maxOverlapArea = 0d;
                    TextBox box            = null;

                    foreach (var textBox in textBoxes)
                    {
                        var bounds      = textBox.TransformToVisual(_contentPresenter).TransformBounds(new Rect(0, 0, textBox.RenderSize.Width, textBox.RenderSize.Height));
                        var xOverlap    = Math.Max(0, Math.Min(result.BoundingRect.Right, bounds.Right) - Math.Max(result.BoundingRect.Left, bounds.Left));
                        var yOverlap    = Math.Max(0, Math.Min(result.BoundingRect.Bottom, bounds.Bottom) - Math.Max(result.BoundingRect.Top, bounds.Top));
                        var overlapArea = xOverlap * yOverlap;

                        if (overlapArea > maxOverlapArea)
                        {
                            maxOverlapArea = overlapArea;
                            box            = textBox as TextBox;
                        }
                    }

                    //TextBox box = elements.Where(el => el is TextBox && (el as TextBox).IsEnabled).FirstOrDefault() as TextBox;

                    if (box != null)
                    {
                        var text = result.GetTextCandidates().FirstOrDefault().Trim();

                        if (!boxes.Contains(box))
                        {
                            boxes.Add(box);

                            box.Text = text;
                        }
                        else
                        {
                            box.Text += " " + text;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
            finally
            {
                _inker.InkPresenter.StrokeContainer.Clear();
            }
        }
예제 #30
0
        /// <summary>
        /// Connect to this bluetooth device
        /// </summary>
        /// <returns>Connection task</returns>
        public bool Connect()
        {
            var ret      = false;
            var debugMsg = "Connect: ";

            try
            {
                if (BluetoothLEDevice == null)
                {
                    // Try to get the cached device (if any) for this id
                    BluetoothLEDevice = BluetoothLEDevice.FromIdAsync(DeviceInfo.Id).GetAwaiter().GetResult();
                }
                else
                {
                    Debug.WriteLine(debugMsg + "Previously connected, not calling BluetoothLEDevice.FromIdAsync");
                }

                if (BluetoothLEDevice == null)
                {
                    ret = false;
                    Debug.WriteLine(debugMsg + "BluetoothLEDevice is null");
                }
                else
                {
                    Debug.WriteLine(debugMsg + "BluetoothLEDevice is " + BluetoothLEDevice.Name);

                    // Setup our event handlers
                    BluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged;
                    BluetoothLEDevice.NameChanged             += BluetoothLEDevice_NameChanged;

                    IsPaired    = DeviceInfo.Pairing.IsPaired;
                    IsConnected = BluetoothLEDevice.ConnectionStatus == BluetoothConnectionStatus.Connected;
                    Name        = BluetoothLEDevice.Name;

                    // Get all the services for this device
                    _result = BluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached).GetAwaiter().GetResult();

                    if (_result.Status == GattCommunicationStatus.Success)
                    {
                        Debug.WriteLine(debugMsg + "GetGattServiceAsync SUCCESS");
                        foreach (var serv in _result.Services)
                        {
                            _services.Add(new GattDeviceServiceWrapper(serv));
                        }

                        ret = true;
                    }
                    else if (_result.Status == GattCommunicationStatus.ProtocolError)
                    {
                        ErrorText = debugMsg + "GetGattServiceAsync Error: Protocol Error - " +
                                    _result.ProtocolError.Value;
                        Debug.WriteLine(ErrorText);
                    }
                    else if (_result.Status == GattCommunicationStatus.Unreachable)
                    {
                        ErrorText = debugMsg + "GetGattServiceAsync Error: Unreachable";
                        Debug.WriteLine(ErrorText);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(debugMsg + "Exception - " + ex.Message);
                var msg = String.Format("Message:\n{0}\n\nInnerException:\n{1}\n\nStack:\n{2}", ex.Message,
                                        ex.InnerException, ex.StackTrace);

                // Debugger break here so we can catch unknown exceptions
                Debugger.Break();
            }

            if (ret)
            {
                Debug.Write(debugMsg + "Now connected");
            }
            else
            {
                Debug.Write(debugMsg + "Not connected");
            }
            return(ret);
        }