Errors when editting existing WP8 project - c#

So I am just starting out with this stuff and have run into some strife. There was a pivot soundboard application that I needed to change into a series of panorama pages but have the same functionality.
I have finished all the xaml and c# appropriately but I think because I had to create a new MainPage and delete the older one I have created several errors. I suspect they all have a similar cause so I will just provide three.
Error 1 The type 'SoundBoard.MainPage' already contains a definition
for 'LayoutRoot' \SoundBoard\obj\Debug\Cartoons.g.cs
Error 30 The name 'AudioPlayer' does not exist in the current
context \SoundBoard\Cartoons.xaml.cs
Error 7 Type 'SoundBoard.MainPage' already defines a member called
'InitializeComponent' with the same parameter types
\SoundBoard\obj\Debug\Cartoons.g.cs
I'll link my current MainPage and Cartoons and hopefully you guys can help me out.
MainPage.xaml:
<phone:PhoneApplicationPage
x:Class="SoundBoard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignData SampleData/SampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="SoundBoard" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Categories" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Warnings" HorizontalAlignment="Left" Margin="244,304,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_3"/>
<Button Content="Taunts" HorizontalAlignment="Left" Margin="27,304,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_2"/>
<Button Content="Cartoons" HorizontalAlignment="Left" Margin="244,123,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click_1"/>
<Button Content="Animals" HorizontalAlignment="Left" Margin="27,123,0,0" VerticalAlignment="Top" Height="160" Width="182" Background="Red" Click="Button_Click"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace SoundBoard
{
public partial class FirstPage : PhoneApplicationPage
{
public FirstPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Animals.xaml", UriKind.Relative));
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Cartoons.xaml", UriKind.Relative));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Taunts.xaml", UriKind.Relative));
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Warnings.xaml", UriKind.Relative));
}
}
}
Cartoons.xaml:
<phone:PhoneApplicationPage
x:Class="SoundBoard.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DataContext="{d:DesignData SampleData/SampleData.xaml}"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot contains the root grid where all other page content is placed-->
<Grid x:Name="LayoutRoot">
<phone:Panorama Title="{Binding Path=LocalizedResources.ApplicationTitle,
Source={StaticResource LocalizedStrings}}">
<!--Panorama item one-->
<phone:PanoramaItem Header="Cartoons">
<Grid>
<Image HorizontalAlignment="Center" Height="431" Margin="10,10,0,0" VerticalAlignment="Top" Width="400" Source="/Assets/cartoon.jpg"/>
</Grid>
</phone:PanoramaItem>
<!--Panorama item two-->
<phone:PanoramaItem Header="Sounds">
<phone:LongListSelector
Margin="0,0,-12,0"
ItemsSource="{Binding Cartoons.Items}"
LayoutMode="Grid"
GridCellSize="150,150"
>
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<Grid Background="{StaticResource PhoneAccentBrush}">
<Grid VerticalAlignment="Top" HorizontalAlignment="Right"
Width="40" Height="40" Margin="0,6,6,0">
<Ellipse Stroke="{StaticResource PhoneForegroundBrush}"
StrokeThickness="3" />
<Image Source="Assets/AppBar/Play.png" />
</Grid>
<StackPanel VerticalAlignment="Bottom">
<TextBlock Text="{Binding Title}"
Margin="6,0,0,6"/>
</StackPanel>
</Grid>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</phone:PanoramaItem>
<!--Panorama item three-->
<phone:PanoramaItem Header="Record">
<Grid>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<MediaElement x:Name="AudioPlayer" AutoPlay="False" />
<StackPanel>
<ToggleButton Content="Record"
Checked="RecordAudioChecked"
Unchecked="RecordAudioUnchecked"/>
<Grid Width="200"
Height="200"
Name="ReelGrid"
RenderTransformOrigin=".5,.5">
<Grid.RenderTransform>
<CompositeTransform />
</Grid.RenderTransform>
<Ellipse Fill="{StaticResource PhoneAccentBrush}" />
<Ellipse Height="20"
Width="20"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,20,0,20"
VerticalAlignment="Top"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,20,0,20"
VerticalAlignment="Bottom"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="0,0,20,0"
HorizontalAlignment="Right"
Fill="{StaticResource PhoneForegroundBrush}" />
<Rectangle Height="20"
Width="20"
Margin="20,0,0,0"
HorizontalAlignment="Left"
Fill="{StaticResource PhoneForegroundBrush}" />
</Grid>
<Button Name="PlayAudio" Content="Play" Click="PlayAudioClick" />
</StackPanel>
</Grid>
</Grid>
</phone:PanoramaItem>
</phone:Panorama>
</Grid>
</phone:PhoneApplicationPage>
Cartoons.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SoundBoard.Resources;
using Coding4Fun.Toolkit.Audio;
using Coding4Fun.Toolkit.Audio.Helpers;
using System.IO;
using System.IO.IsolatedStorage;
using Coding4Fun.Toolkit.Controls;
using SoundBoard.ViewModels;
using Newtonsoft.Json;
namespace SoundBoard
{
public partial class Cartoons : PhoneApplicationPage
{
private MicrophoneRecorder _recorder = new MicrophoneRecorder();
private IsolatedStorageFileStream _audioStream;
private string _tempFileName = "tempWav.wav";
public Cartoons()
{
InitializeComponent();
DataContext = App.ViewModel;
BuildLocalizedApplicationBar();
}
// Load data for the ViewModel Items
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
// verifying our sender is actually a LongListSelector
if (selector == null)
return;
SoundData data = selector.SelectedItem as SoundData;
// verifying our sender is actually SoundData
if (data == null)
return;
if (File.Exists(data.FilePath))
{
AudioPlayer.Source = new Uri(data.FilePath, UriKind.RelativeOrAbsolute);
}
else
{
using (var storageFolder = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream(data.FilePath, FileMode.Open, storageFolder))
{
AudioPlayer.SetSource(stream);
}
}
}
selector.SelectedItem = null;
}
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBarIconButton recordAudioAppBar =
new ApplicationBarIconButton();
recordAudioAppBar.IconUri = new Uri("/Assets/AppBar/Save.png", UriKind.Relative);
recordAudioAppBar.Text = AppResources.AppBarSave;
recordAudioAppBar.Click += recordAudioAppBar_Click;
ApplicationBar.Buttons.Add(recordAudioAppBar);
ApplicationBar.IsVisible = false;
}
void recordAudioAppBar_Click(object sender, EventArgs e)
{
InputPrompt fileName = new InputPrompt();
fileName.Message = "What should we call the sound?";
fileName.Completed += FileNameCompleted;
fileName.Show();
}
private void FileNameCompleted(object sender, PopUpEventArgs<string, PopUpResult> e)
{
if (e.PopUpResult == PopUpResult.Ok)
{
// Create a sound data object
SoundData soundData = new SoundData();
soundData.FilePath = string.Format("/customAudio/{0}.wav", DateTime.Now.ToFileTime());
soundData.Title = e.Result;
// Save the wav file into the DIR /customAudio/
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
if (!isoStore.DirectoryExists("/customAudio/"))
isoStore.CreateDirectory("/customAudio/");
isoStore.MoveFile(_tempFileName, soundData.FilePath);
}
// Add the SoundData to App.ViewModel.CustomSounds
App.ViewModel.CustomSounds.Items.Add(soundData);
// Save the list of CustomSounds to isolatedStorage.ApplicationSettings
var data = JsonConvert.SerializeObject(App.ViewModel.CustomSounds);
IsolatedStorageSettings.ApplicationSettings[SoundModel.CustomSoundKey] = data;
IsolatedStorageSettings.ApplicationSettings.Save();
// We'll need to modify sound model to retrieve CustomSounds
//from isolatedStorage.ApplicationSettings
NavigationService.Navigate(new Uri("", UriKind.RelativeOrAbsolute));
}
}
private void RecordAudioChecked(object sender, RoutedEventArgs e)
{
PlayAudio.IsEnabled = false;
ApplicationBar.IsVisible = false;
RotateCirlce.Begin();
_recorder.Start();
}
private void RecordAudioUnchecked(object sender, RoutedEventArgs e)
{
_recorder.Stop();
SaveTempAudio(_recorder.Buffer);
PlayAudio.IsEnabled = true;
ApplicationBar.IsVisible = true;
RotateCircle.Stop();
}
private void SaveTempAudio(MemoryStream buffer)
{
//defensive...
if (buffer == null)
throw new ArgumentNullException("Attempting a save on empty sound buffer.");
//Clean out hold on audioStream
if (_audioStream != null)
{
AudioPlayer.Stop();
AudioPlayer.Source = null;
_audioStream.Dispose();
}
var bytes = buffer.GetWavAsByteArray(_recorder.SampleRate);
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
if (isoStore.FileExists(_tempFileName))
isoStore.DeleteFile(_tempFileName);
_tempFileName = string.Format("{0}.wav", DateTime.Now.ToFileTime());
_audioStream = isoStore.CreateFile(_tempFileName);
_audioStream.Write(bytes, 0, bytes.Length);
//Play ... SetSource of a mediaElement
AudioPlayer.SetSource(_audioStream);
}
}
private void PlayAudioClick(object sender, RoutedEventArgs e)
{
AudioPlayer.Play();
}
}
}
As I said it is probably something dumb but I am really stuck so would really appreciate any advice.
Thanks in advance.

It seems that all the problems reside in auto-generated files Cartoons.g.cs. The only error that points to non fully auto-generated file is this :
The name 'AudioPlayer' does not exist in the current context \SoundBoard\Cartoons.xaml.cs
Which complaining about AudioPlayer doesn't exists when it does exist, declared in Cartoons.xaml. So that's all weird errors.
First thing I will do is clean up (from visual studio, or manually delete bin and debug folders) and rebuild the project, and or even restart Visual Studio. Those steps can fix weird errors most of the time.

The problem is that both Cartoons.xaml and MainPage.xaml have the same line x:Class="SoundBoard.MainPage". I'm not sure but think that Cartoons.xaml should have different value for x:Class attribute

Related

wpf Can i display images in DocumentViewer?

I want to display xps Image in DocumentViewer, but without success.
Does DocumentViewer support displaying images?
If it is possible to display a picture in DocumentView, how can I do it?
Any reply will be helpful.
My code is as follows:
<StackPanel Orientation="Horizontal" >
<FlowDocumentReader Height="150" Width="170">
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<Grid>
<Image Source="C:\Users\Admin\Downloads\XpsTest-main\XpsTest-main\33.jpg" Width="200" Height="200" />
<TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Red" />
</Grid>
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
<StackPanel>
<Button Click="Button_Click" Content="save"/>
<Button Click="Button_Click_1" Content="show"/>
</StackPanel>
<DocumentViewer Name="viewer" Width="600"/>
</StackPanel>
C#
using System.IO;
using System.IO.Packaging;
using System.Printing;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
namespace XpsTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void PrintVisual(Visual visual)
{
PrintDocumentImageableArea imageArea = null;
XpsDocumentWriter xpdw = PrintQueue.CreateXpsDocumentWriter(ref imageArea);
if (xpdw != null)
{
xpdw.Write(visual);
}
}
public static void SaveAsXps(string path, FlowDocument document)
{
using (var package = Package.Open(path, FileMode.Create))
{
using (var xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum))
{
var xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
var documentPaginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
xpsSerializationManager.SaveAsXaml(documentPaginator);
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveAsXps(#"C:\Users\Admin\Desktop\temp.xps", flowDocument);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
XpsDocument xpsDocument = new XpsDocument(#"C:\Users\Admin\Desktop\temp.xps", FileAccess.Read);
FixedDocumentSequence fds = xpsDocument.GetFixedDocumentSequence();
viewer.Document = fds;
}
}
}
Test the above code, the picture cannot be displayed normally in DocumentView.
This is caused by an security update from Windows
KB5022083 Change in how WPF-based applications render XPS documents
XPS documents ... . Additionally, some inline images may not display correctly when XPS documents are loaded into WPF-based readers.
This regression was introduced in the December 13, 2022, cumulative security updates for .NET and .NET Framework.
Microsoft is actively investigating an additional update which restores compatibility while also resolving the underlying security issue.
I think the problem here is likely to be because Image is a UI control.
You could try putting it in a blockUIcontainer.
Try:
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<BlockUIContainer>
<Image Source="C:\Users\Admin\Downloads\XpsTest-main\XpsTest-main\33.jpg" Width="200" Height="200" />
</BlockUIContainer>
</Paragraph>
</FlowDocument>
I am doubtful about textblock as well. That should probably be a run or paragraph.
I used the exact same code to test in .NetFramework 4.8 and in .NET6 respectively. It doesn't show pictures in .NetFramework 4.8 and shows pictures in .NET6(.NET5).
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="0" Grid.Column="1" HorizontalAlignment="Center" Width="80" Click="Button_Click_1">save as xps</Button>
<FlowDocumentReader Height="150" Width="170" Grid.Column="1" Grid.Row="1">
<FlowDocument Name="flowDocument" ColumnWidth="400" FontSize="14" FontFamily="Georgia">
<Paragraph>
<Grid>
<Image Source="C:\Users\Admin\Downloads\WpfApp3\45.jpg" Width="200" Height="300" />
<TextBlock Text="Hello World!" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Red" />
</Grid>
</Paragraph>
</FlowDocument>
</FlowDocumentReader>
<Button Grid.Row="0" HorizontalAlignment="Center" Width="80" Click="Button_Click">open xps file</Button>
<DocumentViewer Name="viewer" Grid.Row="1"/>
Codebehind:
public static void SaveAsXps(string path, FlowDocument document)
{
using (var package = Package.Open(path, FileMode.Create))
{
using (var xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum))
{
var xpsSerializationManager = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false);
var documentPaginator = ((IDocumentPaginatorSource)document).DocumentPaginator;
xpsSerializationManager.SaveAsXaml(documentPaginator);
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
{
string sFileName = #"C:\...\printPreview.xps";
XpsDocument doc = new XpsDocument(sFileName, System.IO.FileAccess.Read);
viewer.Document = doc.GetFixedDocumentSequence();
return;
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SaveAsXps(#"C:\...\printPreview.xps", flowDocument);
}
The result in .NetFramework 4.8 :
The result in .NET6(.NET5) :

Barcode scanner with ZXing not working anymore

I have created a barcode scanner in C# for Windows Phone 8 using ZXing.NET. It worked fine but since this morning, it displays the error Unable to initialize camera. I haven't changed the code inside the page. Anyone familair with this problem or knows a solution?
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Devices;
using System.Threading;
using System.Windows.Media.Imaging;
using ZXing;
using System.Windows.Threading;
using ZXing.QrCode;
using System.Xml.Linq;
namespace PhoneApp2
{
public partial class Scan : PhoneApplicationPage
{
private PhotoCamera _phoneCamera;
private IBarcodeReader _barcodeReader;
private DispatcherTimer _scanTimer;
private WriteableBitmap _previewBuffer;
public Scan()
{
InitializeComponent();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
// Initialize the camera object
_phoneCamera = new PhotoCamera();
_phoneCamera.Initialized += cam_Initialized;
CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed;
//Display the camera feed in the UI
viewfinderBrush.SetSource(_phoneCamera);
// This timer will be used to scan the camera buffer every 250ms and scan for any barcodes
_scanTimer = new DispatcherTimer();
_scanTimer.Interval = TimeSpan.FromMilliseconds(250);
_scanTimer.Tick += (o, arg) => ScanForBarcode();
base.OnNavigatedTo(e);
}
void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e)
{
_phoneCamera.Focus();
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
//we're navigating away from this page, we won't be scanning any barcodes
_scanTimer.Stop();
if (_phoneCamera != null)
{
// Cleanup
_phoneCamera.Dispose();
_phoneCamera.Initialized -= cam_Initialized;
CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed;
}
}
void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
{
try
{
if (e.Succeeded)
{
this.Dispatcher.BeginInvoke(delegate()
{
_phoneCamera.FlashMode = FlashMode.Off;
_previewBuffer = new WriteableBitmap((int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height);
_barcodeReader = new BarcodeReader();
// By default, BarcodeReader will scan every supported barcode type
// If we want to limit the type of barcodes our app can read,
// we can do it by adding each format to this list object
//var supportedBarcodeFormats = new List<BarcodeFormat>();
//supportedBarcodeFormats.Add(BarcodeFormat.QR_CODE);
//supportedBarcodeFormats.Add(BarcodeFormat.DATA_MATRIX);
//_bcReader.PossibleFormats = supportedBarcodeFormats;
var supportedBarcodeFormats = new List<BarcodeFormat>();
supportedBarcodeFormats.Add(BarcodeFormat.EAN_8);
supportedBarcodeFormats.Add(BarcodeFormat.EAN_13);
supportedBarcodeFormats.Add(BarcodeFormat.UPC_A);
supportedBarcodeFormats.Add(BarcodeFormat.UPC_E);
supportedBarcodeFormats.Add(BarcodeFormat.UPC_EAN_EXTENSION);
_barcodeReader.PossibleFormats = supportedBarcodeFormats;
_barcodeReader.TryHarder = true;
_barcodeReader.ResultFound += _bcReader_ResultFound;
_scanTimer.Start();
});
}
else
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Unable to initialize the camera");
});
}
}
catch (Exception myExc)
{
Console.WriteLine(myExc.Message);
}
}
void _bcReader_ResultFound(Result obj)
{
// If a new barcode is found, vibrate the device and display the barcode details in the UI
if (!obj.Text.Equals(tbBarcodeData.Text))
{
VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));
tbBarcodeType.Text = obj.BarcodeFormat.ToString();
tbBarcodeData.Text = obj.Text;
}
}
private void ScanForBarcode()
{
if (_phoneCamera.IsFocusSupported == true)
{
//Focus when a capture is not in progress.
try
{
_phoneCamera.Focus();
}
catch (Exception focusError)
{
// Cannot focus when a capture is in progress.
this.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = focusError.Message;
});
}
}
//grab a camera snapshot
_phoneCamera.GetPreviewBufferArgb32(_previewBuffer.Pixels);
_previewBuffer.Invalidate();
//scan the captured snapshot for barcodes
//if a barcode is found, the ResultFound event will fire
_barcodeReader.Decode(_previewBuffer);
}
}
}
XAML:
<phone:PhoneApplicationPage
x:Class="PhoneApp2.Scan"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Canvas x:Name="viewfinderCanvas">
<!--Camera viewfinder -->
<Canvas.Background>
<VideoBrush x:Name="viewfinderBrush">
<VideoBrush.RelativeTransform>
<CompositeTransform
x:Name="viewfinderTransform"
CenterX="0.5"
CenterY="0.5"
Rotation="90"/>
</VideoBrush.RelativeTransform>
</VideoBrush>
</Canvas.Background>
<TextBlock Height="40" HorizontalAlignment="Left" x:Name="txtDebug" VerticalAlignment="Top" Width="462" FontSize="24" FontWeight="ExtraBold" Canvas.Left="10" Canvas.Top="618" />
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="26" Canvas.Top="201.36" Width="143.77"/>
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="310.23" Canvas.Top="201.36" Width="143.77"/>
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="310.23" Canvas.Top="493.36" Width="143.77"/>
<Path Data="M443.885,209.007 L248.921,209.007" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="5" Canvas.Left="26" Canvas.Top="493.36" Width="143.77"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="449" Canvas.Top="199" Width="5"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="26" Canvas.Top="399.081" Width="5"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="26" Canvas.Top="199" Width="5"/>
<Path Data="M387.983,239.245 L387.983,399.76" Stretch="Fill" Stroke="White" StrokeThickness="5" UseLayoutRounding="False" Height="101.779" Canvas.Left="449" Canvas.Top="399.081" Width="5"/>
</Canvas>
<!--Used for debugging >-->
<StackPanel Grid.Row="1" Margin="20, 0">
<TextBlock x:Name="tbBarcodeType" FontWeight="ExtraBold" />
<TextBlock x:Name="tbBarcodeData" FontWeight="ExtraBold" TextWrapping="Wrap" />
</StackPanel>
</Grid>
</phone:PhoneApplicationPage>

how to remove XamlParseException in windows phone 8?

When I run my app in windows phone 8 emulator, I am getting this Exception thrown after which I can't run my app.
MainPage.xaml
<phone:PhoneApplicationPage
x:Class="LightBrowser.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Light Browser" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button x:Name="Go" Content="Go" HorizontalAlignment="Right" Margin="0,27,0,0" VerticalAlignment="Top" Click="Button_Click_1" Width="79"/>
<phone:WebBrowser x:Name="Light_Browser" Margin="0,99,0,0"/>
<Button x:Name="Back" Content="Back" HorizontalAlignment="Right" Margin="343,-24,0,0" VerticalAlignment="Top" Height="65" Click="Back_Click"/>
<Button x:Name="Refresh" Content="Refresh" Margin="170,-24,159,0" VerticalAlignment="Top" Height="65" Click="Back_Click" HorizontalAlignment="Center"/>
<TextBox x:Name="URL" Margin="0,27,68,0" VerticalAlignment="Top" Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" TextOptions.TextHintingMode="Animated" AcceptsReturn="True" Text="http://www.google.co.in/"/>
<Button x:Name="Home" Content="Home" HorizontalAlignment="Left" Margin="3,-23,0,0" VerticalAlignment="Top" Click="Home_Click" Height="67" Width="110"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
MainPage.xaml.cs
namespace LightBrowser
{
public partial class MainPage : PhoneApplicationPage
{
private Stack<Uri> _history = new Stack<Uri>();
private string home = "http://www.google.co.in/";
private Uri _current = null;
// Constructor
public MainPage()
{
InitializeComponent();
Light_Browser.Navigate(new Uri("http://www.google.co.in/", UriKind.Absolute));
Light_Browser.IsScriptEnabled = true;
}
private void Button_Click_1(object sender, NavigatingEventArgs e)
{
Uri url = e.Uri;
URL.Text = url.ToString();
string site = URL.Text;
Light_Browser.Navigate(new Uri(site, UriKind.Absolute));
}
private void Home_Click(object sender, NavigatingEventArgs e)
{
Light_Browser.Navigate(new Uri(home, UriKind.Absolute));
Uri url = e.Uri;
URL.Text = url.ToString();
}
private void Back_Click(object sender, NavigatingEventArgs e)
{
Light_Browser.GoBack();
Uri url = e.Uri;
URL.Text = url.ToString();
}
private void Refresh_Click(object sender, NavigatingEventArgs e)
{
Uri url = e.Uri;
URL.Text = url.ToString();
string site=URL.Text;
Light_Browser.Navigate(new Uri(site, UriKind.RelativeOrAbsolute));
}
private void Browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
{
MessageBox.Show("Navigation to this page failed, check your internet connection");
}
private async void Browser_Navigated(object sender, NavigationEventArgs e)
{
// If we navigated back, pop the last entry
if (_history.Count > 0 && _history.Peek() == e.Uri)
{
_history.Pop();
}
// Otherwise, if this isn't the first navigation, push the current
else if (_current != null)
{
_history.Push(_current);
}
// The current page is now the one we've navigated to
_current = e.Uri;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) {
base.OnBackKeyPress(e);
if (_history.Count == 0)
{
// No history, allow the back button
// Or do whatever you need to do, like navigate the application page
return;
}
// Otherwise, if this isn't the first navigation, push the current
else
Light_Browser.GoBack();
}
}
}
XamlParseException Occured
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.ni.dll
And this error points to InitializeComponent();

Windows Phone App Crashes on ListPicker Selected Item

My (first) Windows Phone app keeps crashing when the code takes the selection from a ListPicker, and a webbrowser navigates to that selection. It builds without errors, but crashed when I run it and press the button. I am a beginner when it comes to coding, so please dumb-down your answers :)
Heres my code:
XAML:
<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
x:Class="SecurityCamera.Page1"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="ListPickerItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="10 0 0 0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Name="ListPickerFullModeItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="10 0 0 0"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Security Camera Access" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Specify IP" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Margin="12,138,12,0" Grid.RowSpan="2" Opacity="0.99">
<TextBox x:Name="box1" HorizontalAlignment="Left" Height="70" Margin="31,172,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box2" HorizontalAlignment="Left" Height="70" Margin="31,242,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box3" HorizontalAlignment="Left" Height="70" Margin="31,312,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box4" HorizontalAlignment="Left" Height="70" Margin="31,382,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<Button Content="Connect" HorizontalAlignment="Left" Height="80" Margin="84,527,0,0" VerticalAlignment="Top" Width="305" Click="Button_Click_1"/>
<Button Content="Save" HorizontalAlignment="Left" Height="80" Margin="84,457,0,0" VerticalAlignment="Top" Width="305" Click="Button_Click_2"/>
<TextBlock HorizontalAlignment="Left" Margin="10,119,0,0" TextWrapping="Wrap" Text="Write IP's below to save - Include http:// before all addresses!" VerticalAlignment="Top"/>
</Grid>
<toolkit:ListPicker x:Name="defaultPicker" SelectionChanged="OnListPickerChanged" ExpansionMode="FullScreenOnly" Header="Saved IP's:" Margin="72,0,72,489" Grid.Row="1"/>
<phone:WebBrowser x:Name="webBrowser" HorizontalAlignment="Left" Margin="12,143,0,0" VerticalAlignment="Top" Width="456" Grid.RowSpan="2" Height="615" Opacity="100" Visibility="Visible"/>
</Grid>
</phone:PhoneApplicationPage>
XAML.CS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Xml;
using System.IO.IsolatedStorage;
using System.IO;
namespace SecurityCamera
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
webBrowser.Visibility = System.Windows.Visibility.Collapsed;
// DEBUG MESSAGE - DELETE
MessageBox.Show("Visibility set to Collapsed (startup)");
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
------------------------THIS IS WHERE IT CRASHES --------------------------
//DEBUG MESSAGE - DELETE
MessageBox.Show("Button Pressed!");
string selectedItem;
selectedItem = (sender as ListPicker).SelectedItem.ToString();
// Do what you want with selectedItem
webBrowser.Navigate(new Uri(selectedItem));
//DEBUG MESSAGE - DELETE
MessageBox.Show("webBrowser.Navigate Executed...Making Visible");
webBrowser.Visibility = System.Windows.Visibility.Visible;
// DEBUG MESSAGE - DELETE
MessageBox.Show("webBrowser navigation sent - webBrowser Visibility set to Visible - Button Press");
}
private void OnListPickerChanged(object sender, SelectionChangedEventArgs e)
{
string selectedItem;
selectedItem = (sender as ListPicker).SelectedItem.ToString();
// Do what you want with selectedItem
// webBrowser.Navigate(new Uri(selectedItem));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
// Write Text's into param
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
//create new file
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ip1.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
string someTextData = "{ box1.Text }";
writeFile.WriteLine(someTextData);
writeFile.Close();
}
}
}
}
I believe this cast is failing:
selectedItem = (sender as ListPicker).SelectedItem.ToString();
instead try:
selectedItem = defaultPicker.SelectedItem.ToString();

Problem with refreshing Data c#

My problem is first I'm downladin xml file from server like this:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
//pobieranie danych z pliku xml znajdujacego sie na serwerze
WebClient client = new WebClient();
client.DownloadStringCompleted += HttpsCompleted;
client.DownloadStringAsync(new Uri("Myurl/baza.xml"));
}
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc3 = XDocument.Parse(e.Result, LoadOptions.None);
var data = from query in xdoc3.Descendants("Item")
select new Item
{
name = (string)query.Element("name"),
prise = (int)query.Element("prise"),
howmany = (int)query.Element("howmany")
};
items_listBox.ItemsSource = data;
status_textBlock.Text = "Data ok";
}
else {
status_textBlock.Text = "Fail";
kup_button.Visibility = 0;
}
Then i'v made a refresh button, and add function to it, basicly the same code:
private void button1_Click(object sendera, RoutedEventArgs a)
{
WebClient client2 = new WebClient();
client2.DownloadStringCompleted += HttpsCompleteda;
client2.DownloadStringAsync(new Uri(Myurl/baza.xml"));
}
private void HttpsCompleteda(object sendera, DownloadStringCompletedEventArgs a)
{
#region server_ok
if (a.Error == null
{
#region refresh
XDocument xdoca = XDocument.Parse(a.Result, LoadOptions.None);
var new_data = from query in xdoca.Descendants("Item")
select new Item
{
name = (string)query.Element("name"),
prise = (int)query.Element("prise"),
howmany = (int)query.Element("howmany")
};
items_listBox.ItemsSource = new_data;
}
After laod first xml, it (xml file) is chenged(i can see via my web browser) but when i refresh it looks steel the same in
items_listBox.ItemsSource
any ideas? thanks for help
xaml code
x:Class="Sklep.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Sklep" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Sklep" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" Height="49" Width="456" FontSize="30" />
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="zamow" Height="70" HorizontalAlignment="Left" Margin="-12,474,0,0" Name="kup_button" VerticalAlignment="Top" Width="480" Click="kup_button_Click" />
<TextBlock HorizontalAlignment="Left" Margin="230,550,0,74" Name="textBlock1" Text="Ilość sztuk" Width="190" />
<TextBox Height="57" HorizontalAlignment="Left" Margin="0,536,0,0" Name="order_textBox" Text="1" VerticalAlignment="Top" Width="224" TextAlignment="Right" FontSize="18" />
<CheckBox Content="zapłacone" Height="86" HorizontalAlignment="Left" Margin="171,568,0,0" Name="pay_box" VerticalAlignment="Top" Width="261" />
<ListBox x:Name="items_listBox" MinHeight="200" MinWidth="300" Margin="6,62,6,174" MaxHeight="500">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10" >
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding prise}"/>
<TextBlock Text="{Binding howmany}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Height="53" HorizontalAlignment="Left" Margin="1,3,0,0" Name="status_textBlock" Text="" VerticalAlignment="Top" Width="449" TextAlignment="Center" />
<Button Content="Odswież" Height="103" HorizontalAlignment="Left" Margin="339,545,0,0" Name="button1" VerticalAlignment="Top" Width="114" FontSize="15" Click="button1_Click" />
</Grid>
</Grid>
The request will be cached by the WebClient.
The easiest solution is to make the request look like a different one by adding something unique to the query string.
client.DownloadStringAsync(new Uri("Myurl/baza.xml?rand=" + Guid.NewGuid()));
Your problem seems more to be a data binding problem than about a web service call. You should give your XAML code.
I've solved it using
static public WebClient public_webclient

Categories

Resources