I have a code that adds email id and name in Isolated space. But it is not able to add multiple data. Also, how can I update in case any data was entered incorrectly?
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings.ApplicationSettings.Add("email", "someone#somewhere.com");
IsolatedStorageSettings.ApplicationSettings.Add("name", "myname");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)IsolatedStorageSettings.ApplicationSettings["email"];
textBlock2.Text = (string)IsolatedStorageSettings.ApplicationSettings["name"];
}
}
}
Cleaned up your code a little for you, using a helper method to do the store:
namespace IsoStore
{
public partial class MainPage : PhoneApplicationPage
{
private IsolatedStorageSettings _appSettings;
// Constructor
public MainPage()
{
InitializeComponent();
_appSettings = IsolatedStorageSettings.ApplicationSettings;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
SaveSetting("email", "someone#somewhere.com");
SaveSetting("name", "myname");
}
private void button2_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = (string)_appSettings["email"];
textBlock2.Text = (string)_appSettings["name"];
}
private void SaveSetting( string setting, string value )
{
if (_appSettings.Contains(setting))
{
_appSettings[setting] = value;
}
else
{
_appSettings.Add(setting, value);
}
}
}
}
Try a few other examples to get your head around using IsolatedStorageSettings.
How to: Store and Retrieve Application Settings Using Isolated Storage
All about WP7 Isolated Storage - Store data in IsolatedStorageSettings
I have in mind 2 options, you either save your data to isolatedStorageFile MSDN Library OR ,this is what i might do in such case, You save under the key email all your emails as one string separate the emails with a char that is not allowed to be in an email, Coma "," lets say, when needed split your string and retrieve it to whatever makes you comfortable.
private void SaveSetting( string setting, string value )
{
if (_appSettings.Contains(setting))
{
_appSettings[settings] = _appSettings[settings] + "," + value;
}
else
{
_appSettings.Add(setting, value);
}
}
please note that this code segment is copied from HiTech Magic' answer.
Related
First of all, I'm new to C# and also programming. So, my situation is after I insert data from a textbox to MySql database, the new data does not appear. FYI, I have the navigation (next previous) button. I have to re-run the apps in order for the new data to be displayed. Here's part of the codes:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//MySql codes to display in textbox
showData(pos);
}
public void showData(int index)
{
txtDisplay.Text = table.Rows[index][0].ToString();
}
private void btnPrevious_Click(object sender, EventArgs e)
{
}
private void btnNext_Click(object sender, EventArgs e)
{
}
private void btnGenNext_Click(object sender, EventArgs e)
{
//codes to generate new data and also insert into db
}
}
Here's my full codes:
I'm working on a WP7 application and I need it to play the song in the first link if the current event on the calendar is "Meeting". However, with the current code, it plays the second song instead if the first one even though the event is set correctly.
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Appointments appts = new Appointments();
//Identify the method that runs after the asynchronous search completes.
appts.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(Appointments_SearchCompleted);
DateTime start = DateTime.Now;
DateTime end = DateTime.Now;
int max = 1;
//Start the asynchronous search.
appts.SearchAsync(start, end, max, "Appointments Test #1");
textBlock3.Text = DateTime.Now.ToString("hh:mm:ss tt");
}
void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
try
{
AppointmentResultsDataLINQ.DataContext =
from Appointment appt in e.Results
where appt.IsAllDayEvent == false
select appt;
}
catch (System.Exception)
{
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
{
mediaElement1.Source = new Uri("http://www.opendrive.com/files/NV8zNTMwNDYwX2hxRXZR/Crystallize.mp3", UriKind.Absolute);
}
else
{
mediaElement1.Source = new Uri("https://www.opendrive.com/files/NV8zMjAxODY0X0VBNDJY/Hetken%20tie%20on%20kevyt%20(piano%20cover)%20-%20YouTube.mp3", UriKind.Absolute);
}
mediaElement1.Play();
}
}
The problem appears to be this line:
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
You're comparing the result of calling the ToString() method on the Appointment instance with the string "Meeting".
You probably want:
if ((AppointmentResultsDataLINQ.DataContext as Appointment).Subject.Equals("Meeting"))
Update
You're actually checking an Enumerable of Appointments.
Here's how to check if any of them are "Meeting":
if ((AppointmentResultsDataLINQ.DataContext as IEnumerable<Appointment>).Any(app => app.Subject.Equals("Meeting")))
I would like to make a simple way to write/read to object element in WP7. Something is not working properly. My way of thinking and what I have already done is like that:
First I create a class that represents my object. I added static string just to see if everything works well:
namespace SimpleObject.Objects
{
public class Entry
{
public string entrytitle { get; set; }
public string entrycomment { get; set; }
public string entrycat = "works";
public Entry() { }
public Entry(string Entrytitle, string Entrycomment, string Entrycat)
{
this.entrytitle = Entrytitle;
this.entrycomment = Entrycomment;
this.entrycat = Entrycat;
}
public string entry { get; set; }
}
}
Then, as I read in some articles I need to make some changes in App.xaml.cs Here we go then:
using SimpleObject.Objects;
Before App() I put this:
public static Entry E;
Then in App() this:
UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Application_UnhandledException);
E = new Entry();
InitializeComponent();
Then my UI is two pages. One is a form to input data, second to read. Under application bar button I have:
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
Entry E = new Entry
{
entrytitle = TitleTextBox.Text,
entry = CommentTextBox.Text,
};
this.NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
MessageBox.Show("Category added!");
}
Finally page that present results:
private void button1_Click(object sender, RoutedEventArgs e)
{
TextBlock1.Text = App.E.entrycat;
TextBlock2.Text = App.E.entrytitle;
}
And second TextBlock gives me nothing...
You're never setting the global static values. In your button click, it should be this:
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
App.E.entrytitle = TitleTextBox.Text,
App.E.entrycat = CommentTextBox.Text,
this.NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
}
another option is to forgo the global variable which you're basically only using to pass the value from one page to the next.
You can do this with query string values just like in a web application and pick them up on your page load handler.
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
this.NavigationService.Navigate(new Uri("/Page2.xaml?title=TitleTextBox.Text&comment=CommentTextBox.Text", UriKind.Relative));
}
i am developing a c# user-control # work. the control just loads some infos & data and displays it.
now i want to provide the user of the control with an option to load the data asynchron .. smth like this:
Cntrl.LoadSmthAsync(..)
Cntrl.LoadSmthComplete //EventHandler to give feedback if the Load was successfull.
i decided to make the Download function Async and provide return values throu EventHandlers. but that code got rather complicated .. after all.
here some code to understand what the control should do:
public byte[] LoadByPos(int pos)
{
string url = Pos2Url(pos);
// update gui
this.textBox1.Text = url;
byte[] res = LoadByUrl(url);
// update gui
this.textBox2.Text = BytesToString(res);
return res;
}
public byte[] LoadByUrl(string url)
{
return Download(url);
}
//primary problem: download function
private byte[] Download(string url)
{
System.Threading.Thread.Sleep(1000 * 30);
return StringToBytes(url);
}
//secondary problem: an other function
private string Pos2Url(int pos)
{
System.Threading.Thread.Sleep(1000 * 5);
return pos.ToString();
}
// LoadByPosAsync
public delegate void LoadByPosDoneHandler(Object sender, byte[] e);
public event LoadByPosDoneHandler LoadByPosDone;
public void LoadByPosAsync(int pos)
{
string url = Pos2Url(pos);
// update gui
this.textBox1.Text = url;
LoadByUrlDone += new LoadByUrlDoneHandler(LoadByPosAsync_LoadByUrlDone);
LoadByUrlAsync(url);
}
public void LoadByPosAsync_LoadByUrlDone(object sender, byte[] e)
{
// update gui
this.textBox2.Text = BytesToString(e);
LoadByUrlDone = null;
LoadByPosDone(sender, e);
}
//LoadByUrlAsync
public delegate void LoadByUrlDoneHandler(Object sender, byte[] e);
public event LoadByUrlDoneHandler LoadByUrlDone;
public void LoadByUrlAsync(string url)
{
DownloadDone += new DownloadDoneHandler(LoadByUrlAsync_DownloadDone);
DownloadAsync(url);
}
private void LoadByUrlAsync_DownloadDone(object sender, byte[] e)
{
LoadByUrlDone(sender, e);
}
//DownloadAsync
private delegate void DownloadDoneHandler(Object sender, byte[] e);
private event DownloadDoneHandler DownloadDone;
private void DownloadAsync(string url)
{
BackgroundWorker bw_DownloadAsync = new BackgroundWorker();
bw_DownloadAsync.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_DownloadAsync_RunWorkerCompleted);
bw_DownloadAsync.DoWork += new DoWorkEventHandler(bw_DownloadAsync_DoWork);
bw_DownloadAsync.RunWorkerAsync(url);
}
void bw_DownloadAsync_DoWork(object sender, DoWorkEventArgs e)
{
byte[] res = Download((string)e.Argument);
e.Result = res;
}
void bw_DownloadAsync_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DownloadDone(sender, (byte[])e.Result);
}
is there an easier way to accomplish what i am intending to do ?
thx in advance
Is there an easier way to accomplish what I am intending to do?
There's the implementation side separately, but if you're using .NET 4 I would strongly advise you not to use this model for asynchrony. Rather than using event handlers, I'd encourage you to use Task<T>. You can use TaskCompletionSource to create the task if you don't have any inherent support for it, and it means your API will be much easier to use in C# 5, due to the async/await support. At that point, your UI-thread method would look like this:
public async Task<byte[]> LoadByPos(int pos)
{
string url = await Pos2UrlAsync(pos);
// update gui
this.textBox1.Text = url;
byte[] res = await LoadByUrlAsync(url);
// update gui
this.textBox2.Text = BytesToString(res);
return res;
}
The asynchrony will simply flow through your code naturally.
As most of you experienced, developing a console app is as easy as:
void mainloop(){
while (1){
giveInstructions();
getInput();
if (!process()) break;
printOutput();
}
}
int main(){
mainloop();
return 0;
}
However, in GUI it becomes an issue.
We can still giveInstructions(), process(), and printOutput(), but getInput() wouldn't work because it relies on an event, usually button click or key down.
How can I port a console app to a gui app with minimum code changes? (preferably do not change the main method, and as little change to the mainloop function as possible)
Note: I'm not too comfortable with threading yet.
Since there is no specific language given, I will show an example in C# where you would be able to use the same code as the console app with a simple GUI.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//using form-editor, double-click buttons or use the following
btnInput.Click += new EventHandler(btnInput_Click);
btnContinue.Click += new EventHandler(btnContinue_Click);
giveInstructions();
}
private void giveInstructions()
{
txtInfo.Text = "";
txtInput.Text = "";
//display instructions to multi-line textbox
}
private void btnInput_Click(object sender, EventArgs e)
{
//or you can just add another button for exit.
if (txtInput.Text == "expected value for exit")
{
Application.Exit();
}
else
{
getInput();
}
}
private void getInput()
{
string strInput = txtInput.Text;
//do stuff
printOutput();
}
private void printOutput()
{
//display output to multi-line textbox
}
private void btnContinue_Click(object sender, EventArgs e)
{
giveInstructions();
}
}