none
Run Time prtoblem. RRS feed

  • Question

  • Hi,

    I have a WPF project where several pages are lorded via a user click-request.

    The project work perfectly on a debugging-development-session; however when test-published and executed, it only works partially i.e. the MainWindow is loaded but he ‘Home’ page and all the other subsequent clicked pages are not found (a local try/catch, traps this exception).

    I feel my relative URI is not correct but, since I have no problem during debugging, I have no idea how to resolve this, tried all different combination to no avails.

     

    Current environ:

    Windows 10, Version 10.0.17134 Build 17134

    Microsoft Visual Studio Community 2019

    Version 16.1.6

    VisualStudio.16.Release/16.1.6+29102.190

    Microsoft .NET Framework

    Version 4.7.03056

     

    PS if anyone is willing to dig into this problem, I I'd gladly send a short version of my code.

    Thank you, Fred



    • Edited by Fredd123 Tuesday, August 13, 2019 6:41 AM
    Tuesday, August 13, 2019 6:39 AM

Answers

  • Hi    Fredd123,

    Try the following code. It works well.

        void Window1_Loaded(object sender, RoutedEventArgs e)
            {
                var xe = DataTree.Items[0] as XmlElement;
                var xeMenu = xe.ChildNodes[0] as XmlElement;
    
                //"pack://application:,,,/ResourceFile.xaml"
                //Page = new Uri(xeMenu.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                Page = new Uri("pack://application:,,,/" + xeMenu.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                OpenPage();
            }
            void This_MouseUp(object sender, MouseButtonEventArgs e)
            {
                var xe = DataTree.SelectedItem as XmlElement;
                if (xe.Name != "visiblePage")
                {
                    return;
    
                }
                //"pack://application:,,,/
                //Page = new Uri(xe.GetAttribute("page"), UriKind.RelativeOrAbsolute);
    
                Page = new Uri("pack://application:,,,/" + xe.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                OpenPage();
    
            }
    
    
            public void OpenPage()
            {
    
                try
                {
                    ContentFrame.Source = Page;
    
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                //var folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    
                //string file = folder + @"\" + Page;
    
                //if (System.IO.File.Exists(file))
                //{
    
                    //ContentFrame.Source = Page;
    
                //}
                //else
                //{
                //    MessageBox.Show("This message is the result of IF ‘System.IO.File.Exists’ Absolute path:" + " \n" + file + "\nURI=" + Page);
                //}
            }
    

    and App.cs file :

    /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            public App()
            {
                Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }
    
    
            void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
            {
                MessageBox.Show(e.Exception.ToString()); 
    
                e.Handled = true; 
            }
    
            void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                MessageBox.Show( e.ExceptionObject.ToString());
            }
     
        }
    
    Best regards

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Fredd123 Friday, August 16, 2019 11:03 AM
    Friday, August 16, 2019 9:52 AM
    Moderator

All replies


  • Hi  Fredd123,

    >>I have a WPF project where several pages are lorded via a user click-request.

    How do you lord several pages via a click-request?

    >>I feel my relative URI is not correct but, since I have no problem during debugging, I have no idea how to resolve this, tried all different combination to no avails.

    Have check the following articles?

    Pack URIs in WPF


    It would be appreciated if you could post all necessary code snippets for anyone else to be able to reproduce your issue from scratch along with a detailed description about the results including any exception messages.

    Or provide a minimal runnable demo(Including your test material and remove all private information) which could reproduce this issue.

    Thank you for your understanding.

    Best regards

    Yong Lu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, August 14, 2019 1:57 AM
    Moderator
  • Hi Yong,

    Thank you for your answer.

    >>How do you lord several pages via a click-request?

    My apologies for creating unnecessary confusion – my terse sentence should have been formulated a little bit more clearly. What I meant to say, of course, is not several-pages-at-the-same-time; rather the project contains several pages which can be individually opened via a user mouse click

    MouseButtonEventHandler/MouseButtonEventArgs).

    The article you suggest, along with other of similar content, have been my Bible for the past few days - again no luck.

    A very good example with identical problem, i.e. works perfectly while debugging but do not work when deployed, can be downloaded from:

    https://www.codemag.com/Article/0907111/Dressing-Up-Your-Data-with-WPF-DataTemplates

    This example is very well documented and most likely did work in the past.

     

    Thank you for your time,

    Fred


    Wednesday, August 14, 2019 11:33 AM
  • Hi   Fredd123,  

    >>i.e. works perfectly while debugging but do not work when deployed,

    How do you deploy your wpf application? clickonce?  Normally, it will not happen.

    Or provide a minimal runnable demo(Including your test material and remove all private information) which could reproduce this issue.

    Best regards

    Yong Lu

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, August 15, 2019 5:51 AM
    Moderator
  • Hello Yong,

    >>How do you deploy your wpf application? clickonce?  Normally, it will not happen.

    Again, What I have done up to now is to put some structure in the project and test what can and cannot be done. All in good hope, whit in the Visual Studio realm, in my local machine - no real 'deployment' to end-users has taken place.

    My 'deployment' consist of the following steeps from the BUILD MENU:

    Clean Solution, Rebuild Solution, Publish into the project local publish folder.

    Then I install the executable via the setup.exe - all of this absolutely painless.

    However, upon execution, the problem shows immediately - the home page is not found and all the other pages defined in the navigation pane, which, by the way is correctly rendered, are also not found.

    I enclose, as requested, a minimal set of classes that can be used to build an executable. Please take note of the following:

    1. The DataRepo.xml must be located in the project root directory.
    2. The only debugging information available at run-time is a message resulting from test if  System.IO.File.Exists.
    3. The only test material available (quite sufficient) is the presence or otherwise of pages.
    4. Running the project in VS. the Home Page and Current Wednesday Comp will render because they are defined, whereas Older Wednesday Comps etc. will not render because the do not physically exist.
    5. I expect the above behavior to be identical also when the executable is locally installed and run - that is not happening - an that is the problem.

    USE THE FOLLOWING CODE IN VS TO BUILD A PROJECT AS PER SBOVE TIRADE

    DataRepo.xml

    <?xml version="1.0" encoding="utf-8" ?>
    <DataContainer>
    	<category categoryName="Start Here">
    		<visiblePage header ="Home Page" page="..\..\1HomePage.xaml" />
    
    	</category>
    	<category categoryName="Data Entry">
    		<visiblePage header ="Current Wednesday Comp"
    					page="..\..\2CurrentWedComp.xaml"
    					 />
    		<visiblePage header ="Older Wednesday Comps"
    					page="..\..\2OlderWedComps.xaml"
    					 />
    	
    	</category>
    
    	<category categoryName="More Pages ...">
    		<visiblePage header ="Page n."
    					page="..\..\Page n.xaml"
    					 />
    
    	</category>
    
    
    <!-- ========================= SGC  Data ==================== -->
    <CompsDetail1>" "</CompsDetail1>
    <CompsDetail2>" "</CompsDetail2>
    <CompsDetail3>" "</CompsDetail3>
    
    </DataContainer>

    MainWindow.xaml

    <Window x:Class="YongLuDemo.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:YongLuDemo"
            mc:Ignorable="d"
            Title="YongLuDemo"  Width="1024"  Height="768" WindowState='Maximized'>
        <Window.Resources>
            <Style TargetType='Border'
               x:Key='smooth'>
                <Setter Property='BorderBrush'
                  Value='DarkGray' />
                <Setter Property='BorderThickness'
                  Value='2' />
                <Setter Property='Margin'
                  Value='10' />
                <Setter Property='CornerRadius'
                  Value='5' />
                <Setter Property='Padding'
                  Value='5' />
                <Setter Property='Background'
                  Value='Gainsboro' />
            </Style>
       
            <XmlDataProvider x:Key="dataProvider"
                         Source='DataRepo.xml'
                         XPath="DataContainer" />
            <HierarchicalDataTemplate DataType="category"
                                  ItemsSource="{Binding XPath=*}">
                <TextBlock Text="{Binding XPath=@categoryName}"
                     Foreground="Black"
                     FontWeight="Bold"
                     MinWidth="150" />
            </HierarchicalDataTemplate>
            <DataTemplate DataType="visiblePage"
                      x:Key='nodeTemplate'>
                <Border BorderThickness=".8"
                  Padding="2"
                  SnapsToDevicePixels="True">
                    <Border.RenderTransform>
                        <TranslateTransform X='-20' />
                    </Border.RenderTransform>
                    <StackPanel Orientation="Horizontal">
                        <Rectangle  x:Name='Bullet'
                          Width='10'
                          Height='8'
                          Stroke='DarkGoldenrod'
                          StrokeThickness='0.5'
                          Margin='0,0,5,0'
                          Fill='LightGoldenrodYellow'
                          RadiusX='5' />
                        <TextBlock  Text="{Binding XPath=@header}"
                          Padding='5,1' />
                    </StackPanel>
                </Border>
    
            </DataTemplate>
            <Style TargetType="TreeViewItem">
                <Setter Property="TreeViewItem.IsExpanded"
                  Value="True" />
    
            </Style>
            <Brush x:Key="{x:Static SystemColors.HighlightBrushKey}">LightGoldenrodYellow</Brush>
            <Brush x:Key="{x:Static SystemColors.HighlightTextBrushKey}">Black</Brush>
        </Window.Resources>
        <DockPanel Margin="5">
            <TextBlock Foreground='#999999'
                   DockPanel.Dock='Bottom'
                   FontWeight='Bold'
                   FontFamily='Calibri'
                   Padding='20,0,10,3'
                   FontSize='12'>WPF Data-Binding </TextBlock>
            <Border Style='{StaticResource smooth}'
                DockPanel.Dock='Left'>
                <Expander ExpandDirection='Right'
                    IsExpanded='True'
                    x:Name='mainExpander'>
                    <DockPanel VerticalAlignment='Stretch'
                       HorizontalAlignment='Center'>
                        <TreeView  x:Name='DataTree'
                         DockPanel.Dock='Top'
                         MinHeight='600'
                         ItemsSource="{Binding Source=
    						{StaticResource dataProvider},XPath=category}" />
                    </DockPanel>
                </Expander>
            </Border>
            <Border Style='{StaticResource smooth}'>
                <DockPanel>
                    <TabControl x:Name='mainTab'
                        HorizontalContentAlignment='Stretch'>
                        <TabItem Header='Yong Lu Demo'
                       x:Name='demoTab'
                       HorizontalAlignment='Stretch'>
                            <Frame Name="ContentFrame"
                       NavigationUIVisibility="Hidden"
                       Focusable="false" />
                        </TabItem>
                    </TabControl>
                </DockPanel>
            </Border>
        </DockPanel>
    </Window>

    MainWindow.xaml.cs

    using System;
    using System.IO;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Input;
    using System.Xml;
    
    namespace YongLuDemo
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                Loaded += Window1_Loaded;
                DataTree.MouseUp += new MouseButtonEventHandler(This_MouseUp);
    
            }
    
            void Window1_Loaded(object sender, RoutedEventArgs e)
            {
                var xe = DataTree.Items[0] as XmlElement;
                var xeMenu = xe.ChildNodes[0] as XmlElement;
    
                Page = new Uri(xeMenu.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                OpenPage();
            }
            void This_MouseUp(object sender, MouseButtonEventArgs e)
            {
                var xe = DataTree.SelectedItem as XmlElement;
                if (xe.Name != "visiblePage")
                {
                    return;
    
                }
                Page = new Uri(xe.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                OpenPage();
    
            }
    
    
            public void OpenPage()
            {
                var folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    
                string file = folder + @"\" + Page;
            
                if (System.IO.File.Exists(file))
                {
    
                    ContentFrame.Source = Page;
    
                }
                else
                {
                    MessageBox.Show("This message is the result of IF ‘System.IO.File.Exists’ Absolute path:" + " \n" + file + "\nURI=" + Page);
                }
            }
    
            #region Properties
     
            public static readonly DependencyProperty PageProperty =
                    DependencyProperty.Register("Page", typeof(Uri), typeof(MainWindow));
    
            public Uri Page
            {
                get { return (Uri)GetValue(PageProperty); }
                set { SetValue(PageProperty, value); }
            }
            #endregion
    
        }
    }

    1HomePage.xaml

    <Page x:Class="YongLuDemo.FirstPage"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="SamplePage">
        <Page.Resources>
    
        </Page.Resources>
    
        <Grid Margin='20' Background='{DynamicResource Faded}'>
            <Grid.RowDefinitions>
                <RowDefinition Height='Auto' />
    
            </Grid.RowDefinitions>
    
    
            <TextBlock x:Name='titleText' FontFamily='Aharoni' VerticalAlignment='Top' FontSize='47' Margin='108,50,108,0' TextWrapping='Wrap' Text='Wednesday Ball Competition' HorizontalAlignment='Center' Foreground='Purple' />
    
            <TextBlock Name ="FirtLine" FontSize='30' HorizontalAlignment="Center" TextWrapping="Wrap" Padding="6"  VerticalAlignment="Center" Margin="108,164,108,41" Height="auto" Width="auto" Text="%Today is %"/>
    
            <TextBlock Name ="SecondLine" FontSize='20' HorizontalAlignment="Center" TextWrapping="Wrap" Padding="6"  VerticalAlignment="Center" Margin="55,226,34,-9" Height="auto" Width="auto" Text="" />
    
    
    
        </Grid>
    
    </Page>

    1HomePage.xaml.cs

    using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace YongLuDemo

    { public partial class FirstPage : Page { public FirstPage() { InitializeComponent(); var dayToday = DateTime.Now.DayOfWeek; if (dayToday == DayOfWeek.Tuesday) { // Wednesday Competition date FirtLine.Text = DateTime.Now.DayOfWeek + " " + DateTime.Now.ToString("dd MMM yyyy"); SecondLine.Inlines.Add(new Run("Today Competition is ")); // { FontWeight = FontWeights.Bold }); switch (DateTime.Now.DayOfWeek) { case DayOfWeek.Tuesday: Console.WriteLine("Tuesday"); break; case DayOfWeek.Saturday: Console.WriteLine("The weekend"); break; case DayOfWeek.Monday: Console.WriteLine("The first day of the work week."); break; case DayOfWeek.Friday: Console.WriteLine("The last day of the work week."); break; default: Console.WriteLine("The middle of the work week."); break; } } else { // Not a competition date FirtLine.Text = "Today is " + DateTime.Now.DayOfWeek; SecondLine.Text = "To enter retrospective competition data please use the tab \n "; SecondLine.Inlines.Add(new Run("Older Wednesday Comps") { FontWeight = FontWeights.Bold }); SecondLine.TextAlignment = TextAlignment.Center; // SecondLine.Inlines.Add(new Run("underlined") { FontSize = 44 }); } } } }

    2CurrentWedComp.xaml

    <Page x:Class="YongLuDemo.CurrentWedComp"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="SamplePage">
        <Page.Resources>
    
        </Page.Resources>
    
        <Grid Margin='20' Background='{DynamicResource Faded}'>
            <Grid.RowDefinitions>
                <RowDefinition Height='Auto' />
    
            </Grid.RowDefinitions>
    
    
            <TextBlock x:Name='titleText' FontFamily='Aharoni' VerticalAlignment='Top' FontSize='47' Margin='108,50,108,0' TextWrapping='Wrap' Text='Wednesday Ball Competition' HorizontalAlignment='Center' Foreground='Purple' />
    
            <TextBlock Name ="FirtLine" FontSize='30' HorizontalAlignment="Center" TextWrapping="Wrap" Padding="6"  VerticalAlignment="Center" Margin="108,164,108,41" Height="auto" Width="auto" Text="%Today is %"/>
    
            <TextBlock Name ="SecondLine" FontSize='20' HorizontalAlignment="Center" TextWrapping="Wrap" Padding="6"  VerticalAlignment="Center" Margin="55,226,34,-9" Height="auto" Width="auto" Text="" />
    
    
    
        </Grid>
    
    </Page>

    2CurrentWedComp.xaml.cs

    using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace YongLuDemo

    { public partial class CurrentWedComp : Page { public CurrentWedComp() { InitializeComponent(); var dayToday = DateTime.Now.DayOfWeek; if (dayToday == DayOfWeek.Wednesday) { // Competition date FirtLine.Text = DateTime.Now.DayOfWeek + " " + DateTime.Now.ToString("dd MMM yyyy") + " ddddd You need to use TextBlock because TextBlock accepts as children a collection of Inline objects. "; } else { // Not a competition date // FirtLine.Text = "Today is " + DateTime.Now.DayOfWeek; // SecondLine.Text = "To enter retrospective competition data please use the tab \n "; SecondLine.Inlines.Add(new Run("Older Wednesday Comps") { FontWeight = FontWeights.Bold }); SecondLine.TextAlignment = TextAlignment.Center; // SecondLine.Inlines.Add(new Run("underlined") { FontSize = 44 }); } } } }




    • Edited by Fredd123 Thursday, August 15, 2019 11:47 AM
    Thursday, August 15, 2019 11:35 AM
  • Hi    Fredd123,

    Try the following code. It works well.

        void Window1_Loaded(object sender, RoutedEventArgs e)
            {
                var xe = DataTree.Items[0] as XmlElement;
                var xeMenu = xe.ChildNodes[0] as XmlElement;
    
                //"pack://application:,,,/ResourceFile.xaml"
                //Page = new Uri(xeMenu.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                Page = new Uri("pack://application:,,,/" + xeMenu.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                OpenPage();
            }
            void This_MouseUp(object sender, MouseButtonEventArgs e)
            {
                var xe = DataTree.SelectedItem as XmlElement;
                if (xe.Name != "visiblePage")
                {
                    return;
    
                }
                //"pack://application:,,,/
                //Page = new Uri(xe.GetAttribute("page"), UriKind.RelativeOrAbsolute);
    
                Page = new Uri("pack://application:,,,/" + xe.GetAttribute("page"), UriKind.RelativeOrAbsolute);
                OpenPage();
    
            }
    
    
            public void OpenPage()
            {
    
                try
                {
                    ContentFrame.Source = Page;
    
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                //var folder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    
                //string file = folder + @"\" + Page;
    
                //if (System.IO.File.Exists(file))
                //{
    
                    //ContentFrame.Source = Page;
    
                //}
                //else
                //{
                //    MessageBox.Show("This message is the result of IF ‘System.IO.File.Exists’ Absolute path:" + " \n" + file + "\nURI=" + Page);
                //}
            }
    

    and App.cs file :

    /// <summary>
        /// Interaction logic for App.xaml
        /// </summary>
        public partial class App : Application
        {
            public App()
            {
                Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }
    
    
            void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
            {
                MessageBox.Show(e.Exception.ToString()); 
    
                e.Handled = true; 
            }
    
            void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                MessageBox.Show( e.ExceptionObject.ToString());
            }
     
        }
    
    Best regards

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Fredd123 Friday, August 16, 2019 11:03 AM
    Friday, August 16, 2019 9:52 AM
    Moderator
  • Thankyou Yong! Woks just beautifully.

    I just had a quick test to validate your code - great. I have now marked my post as answered.

    All the best, Fred 

    Friday, August 16, 2019 11:14 AM