Fetch Data from MySql to Windows Phone 8 - mysql

I create a windows phone 8 application. I have a remote MySql server and I want fetch data from it and display it in my windows phone 8 application in listview. How can I do this ?
Here is sample code of my listview
<ListBox Grid.Row="1" Width="450">
<ListBox.Items>
<ListBoxItem Margin="0,0,0,10" >
<ListBoxItem.Background>
<SolidColorBrush Color="#FF421212" Opacity="0.6"/>
</ListBoxItem.Background>
<StackPanel Orientation="Horizontal" Width="453">
<Image Source="images/news.png" Width="92"></Image>
<StackPanel Orientation="Vertical" Width="353">
<TextBlock VerticalAlignment="Top" Text="News" Margin="10,0,0,0" FontSize="30" Height="52"/>
<TextBlock Text="Breaking news update" VerticalAlignment="Bottom" Width="331" Height="42" HorizontalAlignment="Left" Margin="12,0,0,0"/>
</StackPanel>
</StackPanel>
</ListBoxItem>
</ListBox.Items>
</ListBox>

XAML:
<ListBox x:Name="LstNews" Grid.Row="1" Width="450">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="453" Background="#FF421212" Opacity="0.6">
<Image Source="{Binding Img_Path}" Width="92"></Image>
<StackPanel Orientation="Vertical" Width="353">
<TextBlock VerticalAlignment="Top" Text="{Binding NewsHeader}" Margin="10,0,0,0" FontSize="30" Height="52"/>
<TextBlock Text="{Binding NewsUpdate}" VerticalAlignment="Bottom" Width="331" Height="42" HorizontalAlignment="Left" Margin="12,0,0,0"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
cs:
public void LoadSampleData()
{
ObservableCollection<NewsData> obj = new ObservableCollection<NewsData>();
obj.Add(new NewsData("Your Image Path", "Sample Header", "Sample Update"));
obj.Add(new NewsData("Your Image Path1", "Sample Header1", "Sample Update1"));
obj.Add(new NewsData("Your Image Path2", "Sample Header2", "Sample Update2"));
LstNews.ItemsSource = obj;
}
public class NewsData
{
public string Img_Path { get; set; }
public string NewsHeader { get; set; }
public string NewsUpdate { get; set; }
public NewsData() { }
public NewsData(string Img_Path,string NewsHeader,string NewsUpdate)
{
this.Img_Path = Img_Path;
this.NewsHeader = NewsHeader;
this.NewsUpdate = NewsUpdate;
}
}

I don't think its a good idea to let you app communicate with the database directly. Why not build a service which will serve data to your application directly. This has the following advantages :
Your app can be ignorant of how the database is implemented. It would be served Json/Xml data based on how you design the service.
You can reuse the service for any other apps in the future.
You can build the service using any of the widely popular frameworks available (.NET, PHP, Java, just to name a few).

Related

How To Save Chat in Windows Phone 8

Hi All i am working on a windows phone chat application and i have done chatting with both end now i am facing issue when i reopen my app my all previous chat history is removed. how i can save my previous chat history please help me.
Thanks
i am using following code
<ListBox Name="listChat" Grid.Row="0" ItemsSource="{Binding Path=Instance.Messages,Source={StaticResource Binder}}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="430">
<cc:ChatBubble Width="380" HorizontalAlignment="{Binding Converter={StaticResource MType},ConverterParameter=align}" Opacity="{Binding Converter={StaticResource MType}}" ChatBubbleDirection="{Binding Converter={StaticResource MType},ConverterParameter=direction}" Margin="0,0,0,10" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" HorizontalAlignment="Left" FontSize="17" Text="{Binding Name}"></TextBlock>
<TextBlock Grid.Row="0" HorizontalAlignment="Right" FontSize="17" Text="{Binding SendingDate}"></TextBlock>
<TextBlock Grid.Row="1" Name="txt_Msg" Text="{Binding Text}" TextWrapping="Wrap" Width="430"></TextBlock>
</Grid>
</cc:ChatBubble>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
the easiest way is Isolated Storage
For example I have this helper class
public static class SettingsManager
{
private static IsolatedStorageSettings appSettings;
public static IsolatedStorageSettings AppSettings
{
get { return SettingsManager.appSettings; }
set { SettingsManager.appSettings = value; }
}
public static void LoadSettings()
{
if (appSettings == null)
appSettings = IsolatedStorageSettings.ApplicationSettings;
if (!appSettings.Contains(SettingValues.LoadedData))
appSettings[SettingValues.LoadedData] = false;
appSettings.Save();
}
public static void SaveValue(string key, object value)
{
appSettings[key] = value;
appSettings.Save();
}
}
Then you can use it as follows
SettingsManager.SaveValue("myname", someVariableYouWantToStore);
And after start, you can load it with
SettingsManager.AppSettings["myname"]

Binding listbox in listbox on Windows Phone 8

I want to bind AnswerList in QuestionList. When I run code, only have question list on the screen.
<ListBox x:Name="listques" ItemsSource="{Binding QuestionList }">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock x:Name="quesdetail" Text="{Binding QuestionContent.que_detail}" HorizontalAlignment="Left" Margin="27.669,34.338,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="252.564" Width="419.534" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto">
</TextBlock>
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock x:Name="ansdetail" Foreground="Blue" Text="{Binding Answer.ans_detail}">
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You should have a property AnswerList inside your Question object. Assign that as the itemsSource of the inner ListBox. So for each question you will have a list of answers.
<ListBox x:Name="InnerListBox" ItemsSource = "{Binding QuestionContent.AnswerList}">
#Bells is right. To elaborate his answer a little more, let me explain by an external example.
Example:-
// MainPage.xaml page
// eg. we have a nested ListBox for questions and answers
<ListBox x:Name="lbxRoot">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding que}" FontSize="30" />
<ListBox ItemsSource="{Binding lstAns}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}" Margin="20 0 0 0" FontSize="30"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
To assign ItemsSource to the RootListBox let's define one model class which contains one question and a list of answers of that question.
// MainPage.xaml.cs file add one class named Model as below
public class Model
{
public string que { get; set; }
public List<string> lstAns { get; set; }
}
Now, we are going to assign ItemsSource to root ListBox in Loaded event of the page so declare the event handler in the MainPage's Constructor.
this.Loaded += MainPage_Loaded;
and then define the Loaded event handler as below.
// MainPage.xaml.cs file
// Loaded event handler
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Model m1 = new Model()
{
que = "Question 1",
lstAns = new List<string>()
{
"que 1 - ans 1", "que 1 - ans 2", "que 1 - ans 3"
}
};
Model m2 = new Model()
{
que = "Question 2",
lstAns = new List<string>()
{
"que 2 - ans 1", "que 2 - ans 2", "que 3 - ans 3"
}
};
List<Model> lstModels = new List<Model>();
lstModels.Add(m1);
lstModels.Add(m2);
lbxRoot.ItemsSource = lstModels;
}
It will give output like below image:
And there you go..!!
Try to relate your scenario with this example, and you're done..!
Hope that helps..
A ListBoxItem will try to find the binding inside the properties of its current item in the ItemSource. So the first ListBox will try to find the properties on its ItemSource and the inner ListBox will try to find its bindings on its ItemSource.
If you want to bind the inner ListBox's ListBoxItem you have to specify the relativeSource (To make it clear prop1 means a property, no matter which one):
<ListBox ItemSource="{Binding list1}"
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding propList1}"/>
<ListBox ItemsSource="{Binding list2}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding DataContext.propList1,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
With this line
<TextBlock Text="{Binding DataContext.propList1,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}"/>
wpf will look for a parent of type ListBox in its visualtree, and use its DataContext, and its DataContext is the ListBoxItem of the outter ListBox.

How to filter an observable collection in Windows Phone 8?

I tried this How to: Filter Data in a View so i tried this approach but it didn't work for me because windows phone 8 environment couldn't find 'ListCollectionView'.
My collection is following.
//My observableCollection
ObservableCollection<ClonedWrapper> dsForProgress = new ObservableCollection<ClonedWrapper >();
//My Function which shows at first time.
private async Task CloudImages()
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
try
{
List<MainWrapper> serverdata = new List<MainWrappe>();
serverdata = await ImageUrlAsync();//This function is returning the Deserialize object of images
if (serverdata.Count != 0)
{
foreach (var imgInfo in serverdata)
{
string folderPath = "Fagbokforlaget/Books/" + BookInfo.Id.Trim();
ClonedWrapper item = new ClonedWrapper()
{
//Name, Cover, Info, Title, IsEnableButton, IsVisibleButton,
// IsVisible are the assigned keys to the xaml page
Id = imgInfo.Id,
Name = imgInfo.Name,
Cover = await GetCoverImage(imgInfo),
Info = imgInfo.Info,
Title = imgInfo.Title,
Url = imgInfo.Url,
IsEnableButton = "True",
IsVisible = "Collapsed",
Date = Convert.ToDateTime(imgInfo.Date)
};
if (isf.DirectoryExists(folderPath))
{
item.ButtonStatus = "Read";
item.IsVisibleBookDeleteButton = "Visible";
}
else
{
item.ButtonStatus = "Download";
item.IsVisibleBookDeleteButton = "Collapsed";
}
dsForProgress.Add(item);
}
}
else
{
MessageBox.Show("You have no any downloaded books!");
}
listCloudImages.ItemsSource = dsForProgress;
}
catch (Exception exe)//I am getting exception here on extreme first run in absense of internet.
{
MessageBox.Show(exe.Message);
}
}
//My xaml page is following. It is the default page that loaded at first time. you can say it is the face of the application. User download the images. and buttonStatus convert into the Read button. so now what i am doing i will keep two buttons in appliationbar one cloud second downloaded. ON Download button click i want to show only downloaded images.
<ListBox Name="listCloudImages" Visibility="Visible" Grid.Row="1" ScrollViewer.VerticalScrollBarVisibility="Auto" FontFamily="Segoe UI" FontStyle="Normal" FontWeight="Thin" Margin="0,0,0,50">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<tools:WrapPanel Orientation="Horizontal">
</tools:WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1" Background="#151414" CornerRadius="3" Margin="3" Width="150" TextOptions.DisplayColorEmoji="True" BorderBrush="#1c1b1b">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Image x:Name="imgBookImage" Source="{Binding Cover}" Visibility="Visible" VerticalAlignment="Top" HorizontalAlignment="Center"
Width="80" Height="100" ImageOpened="imgBookImage_ImageOpened"/>
<StackPanel Orientation="Horizontal">
<TextBlock Visibility="{Binding IsVisible}" Text="{Binding ProgressPercentage}" FontFamily="Segoe UI" FontSize="18" FontWeight="ExtraBold" Foreground="White" Margin="5,0"></TextBlock>
</StackPanel>
</StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Title}" FontFamily="Segoe UI" FontSize="13.5"
Foreground="White" TextTrimming="WordEllipsis"
VerticalAlignment="Top" HorizontalAlignment="Left"
TextWrapping="Wrap"
Width="300" Padding="2"/>
<TextBlock Text="{Binding Info}" FontSize="13.5" FontFamily="Segoe UI"
Foreground="White"
VerticalAlignment="Top" HorizontalAlignment="Left"
TextWrapping="Wrap"
Width="300" Padding="2"/>
<ProgressBar x:Name="downloadProgressBar" Foreground="Green" IsIndeterminate="True" VerticalAlignment="Center" Width="120" TextOptions.TextHintingMode="Animated" Visibility="{Binding IsVisible}" CharacterSpacing="2"/>
<Button Content="{Binding ButtonStatus}" x:Name="btnDownload" IsEnabled="{Binding IsEnableButton, Converter={StaticResource ButtonVisibilityIsEnableConverter}}"
Click="btnDownload_Click" Tag="{Binding}" Width="120" BorderThickness="1" FontSize="13.5" Margin="0,5"
FontFamily="Segoe UI" tools:SlideInEffect.LineIndex="2" HorizontalAlignment="Left" VerticalAlignment="Top"
Foreground="White">
</Button>
<Image x:Name="imgCancelImage" Source="/Assets/Tiles/CancelImage.png" Visibility="{Binding IsVisible}" VerticalAlignment="Center" Margin="97,-66,0,0"
Tap="imgCancelImage_Tap" HorizontalAlignment="Right" Width="25" Height="25" Tag="{Binding}"/>
<Button x:Name="btnDeleteImage" Click="btnDeleteImage_Click"
Tag="{Binding}" BorderThickness="1" Margin="97,-66,0,0"
Height="55" Width="55"
Visibility="{Binding ButtonStatus, Converter={StaticResource DeleteButtonVisibilityConverter}}">
<Button.Background>
<ImageBrush ImageSource="/Images/delete.png" Stretch="Fill"></ImageBrush>
</Button.Background>
</Button>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Based on your code, you can do something quite easy, if you wanna show only downloaded books try this:
private void ApplicationBarButtonShowAllDownLoaded(object sender, EventArgs e)
{
var c = (Application.Current as App).dsForProgress.Where(x => x.ButtonStatus.Equals("Download"));
listCloudImages.ItemsSource = c;
}
be sure that ObservableCollection<ClonedWrapper> dsForProgress is public
In your book model, you can pass a bool property IsDownload and when you download books you set this property to true.For your filter, just use linQ for take all books download or no dowload like this :
var noDownloadedBooks =
from b in yourObservableCollection
where b.IsDownload == false
select b;
var downloadedBooks =
from b in yourObservableCollection
where b.IsDownload == true
select b;
What you need to do is use a CollectionViewSource, this can point to your original collection and it can handle filtering!
Scott Hanselman has a great example blog post about it here... http://www.hanselman.com/blog/CollectionViewSourceIsCrazyUsefulForBindingToFilteredObservableCollectionsOnWindowsPhone8.aspx

How to Bind text value of a textblock inside a dataTempalte of Listfootertemplate of a Longlistselector

I have a TextBlock in the datatemplate of ListFooterTemplate of LongListSelector,to which I give a Collection as Itemssource,I want to bind the Text Property of TextBlock to a string in the Codebehind. Please tell me how to do it. Here is the xaml.
I am using VS2012 and WP8 SDK.
<toolkit:LongListSelector ItemsSource="{Binding Collection}">
<toolkit:LongListSelector.ListFooterTemplate>
<DataTemplate>
<TextBlock Text= "{Binding footertext}" />
</DataTemplate>
</toolkit:LongListSelector.ListFooterTemplate>
</toolkit:LongListSelector>
footertext is the string I have defined in the codebehind. I have implemented INotifyPropertyChanged also but footer doesnt show the text.
Just guessing here, but the most likely reason you're not seeing any footer is that you're not binding to the right object. The LongListSelector is binding to properties on its DataContext. If the Collection property lives on a different object than the footertext property that would cause this problem.
Here's some sample code that works for me:
Code-behind
namespace LongListSelector
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
SomeText = "This is my footer text from the code-behind";
}
public string SomeText { get; private set; }
}
}
XAML
<phone:PhoneApplicationPage
x:Class="LongListSelector.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"
xmlns:local="clr-namespace:LongListSelector"
mc:Ignorable="d"
x:Name="page"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.DataContext>
<local:SampleData/>
</phone:PhoneApplicationPage.DataContext>
<!--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>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector ItemsSource="{Binding Collection}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
<phone:LongListSelector.ListFooterTemplate>
<DataTemplate>
<TextBlock Text="{Binding SomeText,ElementName=page}"/>
</DataTemplate>
</phone:LongListSelector.ListFooterTemplate>
<phone:LongListSelector.ListHeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.HeaderText, ElementName=page, Mode=OneWay}"/>
</DataTemplate>
</phone:LongListSelector.ListHeaderTemplate>
</phone:LongListSelector>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Sample data object
using System.Collections.ObjectModel;
namespace LongListSelector
{
public class SampleData
{
public SampleData()
{
Collection = new ObservableCollection<string>( new string[] { "Item 1", "Item 2", "Item 3" } );
HeaderText = "This is my header text";
}
public ObservableCollection<string> Collection { get; private set; }
public string HeaderText { get; private set; }
}
}
Note that the ItemsSource property on the LongListSelector binds to the DataContext (as does the header) while footer binds to a property in the code-behind class.
Hope this helps.

How to display flatlist using LongListSelector phone control of WP8

In toolkit LongListSelector, there used to be a property IsFlatList which needed to be set to true to display flat list without any grouping. But in the LongListSelector provided in phone control, this property is missing. Here is what I am doing
<phone:LongListSelector Name="myList" IsGroupingEnabled="False" LayoutMode="List" ItemsSource="{Binding Source ={StaticResource SortedList} }" CacheMode="BitmapCache" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<components:MyControl CacheMode="BitmapCache" MyItem="{Binding}"/>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
If I change the control to ListBox and remove LongListSelector specific property then it display my list.
Can someone please tell me what I am missing?
I am following this(Remarks) documentation of LongListSelector
In the Windows Phone 8 Version of the LongListSelector setting LayoutMode to List and IsGroupingEnabled to false should display your databound data as a flat list like in the WP7 Toolkit version of the control.
For example,
Given an Entity class
public class Entity
{
public string Name
{
get;
set;
}
public string Info
{
get;
set;
}
public int ID
{
get;
set;
}
}
All I need to do is create an ObservableCollection of Entity on my page and bind it to the itemsource of my LongListSelector (named list).
ObservableCollection<Entity> data = new ObservableCollection<Entity>();
list.ItemsSourdce = data;
Then I create the entities and add them to the collection.
Here is the XAML for my LongListSelector:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector Name="list" HorizontalAlignment="Left" Height="609" VerticalAlignment="Top" Width="456" LayoutMode="List" IsGroupingEnabled="False" >
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Top">
<TextBlock FontWeight="Bold" Text="{Binding Name}" />
<TextBlock Text="{Binding Info}" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
LayoutMode ="List" that's all you need.