I was wondering if there was a way to display a messagebox in WP8 just once i.e. on app opening.
I have the following code already, very basic.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
MessageBox.Show("Hi");
}
However, this shows every time the app is opened. I only want it to show the first time.
Is that possible?
I have used this successfully in WP 8.0 Silverlight apps. Create a reusable class, OneTimeDialog:
using System.Windows;
using System.IO.IsolatedStorage;
namespace MyApp
{
public static class OneTimeDialog
{
private static readonly IsolatedStorageSettings _settings = IsolatedStorageSettings.ApplicationSettings;
public static void Show(string uniqueKey, string title, string message)
{
if (_settings.Contains(uniqueKey)) return;
MessageBox.Show(message, title, MessageBoxButton.OK);
_settings.Add(uniqueKey, true);
_settings.Save();
}
}
}
Then use it anywhere in your app, like this:
OneTimeDialog.Show("WelcomeDialog", "Welcome", "Welcome to my app! You'll only see this once.")
Showing a "Hint" or "Welcome" dialog just once is helpful in lots of different types of apps, so I actually have the code above in a Portable Class Library so I can reference it from multiple projects.
Since you need to persist a state across sessions, an isolated storage key-value pair is a good choice. Just check before, and then update:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.ContainsKey("messageShown") && (bool)settings["messageShown"] == true)
{
MessageBox.Show("Hi");
settings["messageShown"] = true;
}
}
Related
Is there any possibility to open Contacts App in Xamarin IOS,
For android the below code worked for me.
var activity = Forms.Context as Activity;
var intent = new Intent(Intent.ActionInsert);
intent.SetType(ContactsContract.Contacts.ContentType);
activity.StartActivity(intent);
Where as for IOS I have't find any code can any one have solution for this.
Apple has released two new frameworks, Contacts and ContactsUI, that replace the existing Address Book and Address Book UI frameworks used by iOS 8 and earlier.
You could use these two frameworks to deal with all situation which involve contacts.
To make it clear, I create a simple app to show how to display contact app in ios.
you can open the contacts app with code like:
public override void ViewDidLoad()
{
base.ViewDidLoad();
picker1.TouchDown += Picker1_TouchDown;
}
private void Picker1_TouchDown(object sender, EventArgs e)
{ //create a picker
var picker = new CNContactPickerViewController();
//set the delegate
picker.Delegate = new ContactPickerDelegate();
//display picker
PresentViewController(picker, true, null);
}
The ContactPickerDelegate is what you need to create and used to respond to the user's interaction with the picker.
The code is like:
public class ContactPickerDelegate: CNContactPickerDelegate
{
#region Constructors
public ContactPickerDelegate ()
{
}
public ContactPickerDelegate (IntPtr handle) : base (handle)
{
}
#endregion
#region Override Methods
public override void ContactPickerDidCancel (CNContactPickerViewController picker)
{
Console.WriteLine ("User canceled picker");
}
public override void DidSelectContact (CNContactPickerViewController picker, CNContact contact)
{
Console.WriteLine ("Selected: {0}", contact);
}
public override void DidSelectContactProperty (CNContactPickerViewController picker, CNContactProperty contactProperty)
{
Console.WriteLine ("Selected Property: {0}", contactProperty);
}
#endregion
}
Screenshots:
For more information, you can refer to https://learn.microsoft.com/en-us/xamarin/ios/platform/contacts
I would like to add a REST API server to my WinForms application. I have chosen to use Grapveine for that purpose.
Here's my code:
namespace RestServerTest
{
public partial class Form1 : Form
{
private RestServer mServer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
mServer = new RestServer();
mServer.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
mServer.Stop();
mServer.Dispose();
}
}
[RestResource]
class MyRoute
{
[RestRoute]
public IHttpContext HelloWorld(IHttpContext context)
{
// Todo: how access form object from here?
context.Response.SendResponse("Hello, world.");
return context;
}
}
}
Currently I have no idea how to actually access my Form object from the REST route (without using an ugly global/static variable).
How would one do that elegantly?
If you want the current form (or any other object/variable in your project) to be accessible to your routes, you can take advantage of Dynamic Properties. Both the IRestServer and IHttpContext implement IDynamicProperties, which gives you two ways to accomplish your goal.
Add either of these to your Form1_Load() method.
Add a Reference On The Server
server.Properties.Add("CurrentForm", this);
Add a BeforeRouting Event Handler
server.Router.BeforeRouting += cxt =>
{
cxt.Properties.Add("CurrentForm", this);
};
Access a Property In a Route
In either case, you can access the property using the built in extensions methods:
// On the server
var form = context.Server.GetPropertyValueAs<Form1>("CurrentForm");
// On the context
var form = context.GetPropertyValueAs<Form1>("CurrentForm");
I have an application that schedules jobs using Quartz.Net. It works on my development laptop perfectly both as a winforms application (with start and stop buttons) and as a Windows Services whose OnStart() and OnStop() event code matches the start and stop button code of the winforms application. They're both in the same solution using the same "model" code (in its own project).
If I run the winforms application on the production computer it works perfectly, the jobs are executed according to their schedule as expected. However if I install and run it as a Windows Service on the production PC nothing happens! The jobs do not run.
I have no idea how to debug this. Please let me know if you have any suggestions as to what might be wrong.
Also please let me know what other information I should be providing.
Oh - dev PC is running Windows 7, production PC is running Windows 8.1! Could that be the problem? I built the service by following this tutorial: http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx which does not indicate that anything special needs to be done for deploying to Windows 8?
Could this have something to do with environment variables (which I know nothing about)?
Here is some code which may be relevant:
The service:
namespace DataPump
{
public partial class DataPumpService : ServiceBase
{
private TaskManager _taskManager;
public DataPumpService()
{
InitializeComponent();
_taskManager = new TaskManager();
}
protected override void OnStart(string[] args)
{
_taskManager.Go();
}
protected override void OnStop()
{
_taskManager.Stop();
}
}
}
The form code (different project):
namespace DataPump
{
public partial class Form1 : Form
{
private TaskManager _taskManager = new TaskManager();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
_taskManager.Go(); //Loops infinitely, does not block
label1.Text = "Running...";
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = "Stopping...";
_taskManager.Stop();
label1.Text = "Idle";
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_taskManager.Stop();
}
}
}
Selected code from TaskManager code (third project which the first two each reference):
public class TaskManager
{
//...
private IScheduler _scheduler = StdSchedulerFactory.GetDefaultScheduler();
//...
public void Go()
{
if (_scheduler.GetCurrentlyExecutingJobs().Count() == 0)
{
_scheduler.Start();
_scheduler.AddCalendar(CalendarName, MakeSAPublicHolidayCalendar(), false, true);
foreach (DatapumpJob job in JobList)
{
_scheduler.ScheduleJob(MakeJob(job), MakeTriggerCron(job));
}
}
}
//...
public void Stop()
{
foreach (string name in _scheduler.GetCurrentlyExecutingJobs().Select(j => j.JobDetail.Key.Name))
{
_scheduler.Interrupt(new JobKey(name));
}
_scheduler.Shutdown(true);
}
//...
}
Where JobList is a get only property that generates a List<DatapumpJob>where DatapumpJob implements IInterrutableJob but adds common features including a job name which gets use by the three methods beginning Make... which are all private methods within the TaskManager class.
This code is to answer a question from the comments regarding ServiceBase.Run():
Program.cs (auto-generated):
namespace DataPump
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new DataPumpService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
This turned out to be a network permissions issue. The service was running, it was just unable to access the network drive. So really my question was mi-specified.
After trying this: https://serverfault.com/questions/177139/windows-service-cant-access-network-share we eventually got it to work by setting the service to run as a specific user account on the PC.
I have the following code in Windows Phone:
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_LogIn_Click(object sender, RoutedEventArgs e)
{
Service1SoapClient web_service = new Service1SoapClient();
web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
web_service.LogInCompleted += new EventHandler<LogInCompletedEventArgs>(login_complete);
}
private void login_complete(object obj, ClientWebService.LogInCompletedEventArgs e)
{
string answer = e.Result.ToString();
if (answer.Equals("Success") || answer.Equals("success"))
{
NavigationService.Navigate(new Uri("/Authenticated.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("The log-in details are invalid!");
}
}
}
The code makes use of a web service in order to log-in the user into the system. The log-in system works as it should.
My question is, where should I insert the try catch statement in order to catch exception when the web service is NOT running? I tried in the button_click event handler to no avail and even in the line when I am getting the result.
It's not clear what type your Service1SoapClient is based upon so the statements below may not be accurate. It doesn't appear that you're using the Mobile Services Client since you're passing in a username and password and returning some other state.
However, the ...Async suffix on the LoginAsync method name indicates that this API returns a Task<T> which means that this API is built to be used by the new async and await keywords of C# 5.
Therefore, I recommend altering your code to read as follows:
```
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
}
private async void Button_LogIn_Click(object sender, RoutedEventArgs e)
{
try
{
Service1SoapClient web_service = new Service1SoapClient();
string answer = await web_service.LogInAsync(TextBox_Username.Text, TextBox_Password.Password);
if (answer.ToLower().Equals("success"))
{
NavigationService.Navigate(new Uri("/Authenticated.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("The log-in details are invalid!");
}
catch (<ExceptionType> e)
{
// ... handle exception here
}
}
}
```
Note that one of the side-benefits of async and await is that they allow you to write your code logically, including your exception handling code which, prior to async and await was hard to get right!
I am new to c#. I have created main windows that I am adding usercontrols to switch between screens with command:
Switcher.Switch(new NewPage());
The class Switcher is:
public static class Switcher
{
public static MainWindow pageSwitcher;
public static void Switch(UserControl newPage)
{
pageSwitcher.Navigate(newPage);
}
public static void Switch(UserControl newPage, object state)
{
pageSwitcher.Navigate(newPage, state);
}
}
But how to I exit the user control? I wish to finish it (like back button). I can use:
Switcher.Switch(new PreviousPage());
but it will keep the new page in memory and will not release it.
Example of NewPage class:
namespace MyProject.Screens
{
public partial class NewPage : UserControl
{
public NewPage()
{
InitializeComponent();
}
private void back_button_Click_(object sender, RoutedEventArgs e)
{
//what to put here?
}
}
}
The framework does a lot of the heavy lifting for navigation for you, including the "back" operation that you're interested in.
Take a look at http://msdn.microsoft.com/en-us/library/ms750478.aspx
NavigationService.GoBack is what you'll use.
In the off-chance that you're working on a Windows Store App, let me know, since my answer will be different.
You should really try and use the standard Navigation services available with WPF. This will give you configurable oage caching and journalling.
http://msdn.microsoft.com/en-GB/library/ms750478(v=vs.100).aspx
Try this:
private void back_button_Click_(object sender, RoutedEventArgs e)
{
Window parentWindow = (Window)this.Parent;
parentWindow.Close();
}