wp8 Handle raw push notification in more than one pages - windows-phone-8

I am developing a wp8 application and the need is the above:
My server sends some raw push notifications that i can handle in my mainpage successful. But i have more pages so i need my app continue to get and handle notifications when the user is on the other pages.
As far i have tried to add the same code as i have put in the main page to handle notifications
string channelName = "test";
pushChannel = HttpNotificationChannel.Find(channelName);
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
//pushChannel.BindToShellToast();
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
// pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
}
and the handlers methods
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
cSettings.device_notify_id = e.ChannelUri.ToString();
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
cSettings set = new cSettings();
set.LogEx(new Exception((String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))));
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string message;
VibrationDevice vibr = VibrationDevice.GetDefault();
vibr.Vibrate(TimeSpan.FromSeconds(3));
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
cSettings set = new cSettings();
string n_type = "";
string n_header = "";
//var obj = set.parse_stringfromnotify(message, ref n_type, ref n_header);
Dispatcher.BeginInvoke(() => nofication_received_action(message, n_type, ""));
}
private void nofication_received_action(string n_header, string n_type, object data)
{
MessageBoxResult result;
CallSrvData cdata = new CallSrvData();
Exception ex = null;
WP_MemberData m;
WP_MemberRules wpmr;
cSettings set;
MemberRules mr;
Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
Rules c_rules;
Notify.data = data;
Notify.msg_box_text = String.Format("{0}", n_header);
//dose k data sth forma
toast = new Microsoft.Phone.Shell.ShellToast();
toast.Content = "Invitation received";
toast.Title = "Title : ";
//SetProperty(toast, "Sound", new Uri("/data/alert.mp3", UriKind.Relative));
toast.NavigationUri = new Uri("/forms/Notify.xaml?type=0", UriKind.Relative);
toast.Show();
}
When the app is in background and i successfully get the notification and navigate to Notify.xaml the mechanism works fine, but when i go back or i press start button to leave from Notify.xaml and i resend a notification nothing happens. I have tried to add the same code and in Notify.xaml but again nothing happen when i send notification. In comparison with android where you just register listeners once in your app and then you can receive notification in in any page even the app is "closed" who can i succeed something like that or can i succeed something like that?
Thx a lot for your contribution.

I have found that i can create all the notification functionality in a class which will initialize on app.cs or any time is needed.

Related

MySql Query Sent by Email

I have a simple query that select some fields from a few different tables and I need it to run once a month. I know i can schedule a monthly "job" with the CREATE EVENT, however, is it possible to have that information emailed to some addresses after the query runs? That way i don't need to log into the server and look at the new file?
I think that Mysql doesn't support Email sending.
In this case, you can develop an auxiliary program that sends the file created, and execute it with - scheduled task, Cron ...(It depends on the Operating System of the server you're using).
The auxiliary program can be like this code adding the file/s you want to attach (attachFiles variable).
public class EmailAttachmentSender {
public static void sendEmailWithAttachments(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, String[] attachFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Test sending e-mail with attachments
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "your-email-address";
String password = "your-email-password";
// message info
String mailTo = "your-friend-email";
String subject = "New email with attachments";
String message = "I have some attachments for you.";
// attachments
String[] attachFiles = new String[3];
attachFiles[0] = "e:/Test/Picture.png";
attachFiles[1] = "e:/Test/Music.mp3";
attachFiles[2] = "e:/Test/Video.mp4";
try {
sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
subject, message, attachFiles);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
Mysql does not support that functionality.
You can use a cron job (Quartz) to schedule a job every month,
where you can fetch the data and shoot an email containing your data.
Refer the below link for quartz job :
http://www.mkyong.com/java/example-to-run-multiple-jobs-in-quartz/
is it possible to have that information emailed to some addresses
after the query runs?
If you are looking for a MySQL built in solution then probably NO. This particular should be handled in application end.
So, if you are scheduling the query as cron job in linux (OR) batch job in windows then you can configure cron (or) batch to send an email to list of recipients once the query finishes.
How to configure cron to send mail can be checked HERE
I haven't done this myself but I see no reason why it shouldn't work: create a UDF (user defined function) that takes the e-mail parameters and sends out the e-mail. You can write UDFs e.g. in C++ and have so all necesssary libraries at hand.

WebException thrown when locking screen of the Emulator (WindowsPhone8)

I have a webrequest to get a xml.That works great but when i press F12(lock screen) while the the server is requested by my app...I got a WebException.
I use a taskCompeltionSource object...Here is my code
public async Task<String> Query(DataRequestParam dataRequestParam)
{
_dataRequestParam = dataRequestParam;
try
{
Result = "";
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)//ERROR IS CAUGHT HERE
{
throw new WebException(we.Message);
}
catch (Exception ex)
{
throw new MyException(ex.Message);
}
return Result;
}
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
If you haven't disabled ApplisationIdleDetection, your process is stopped while entering Lock screen - thus you probably get the exception - like I've said in comment. Disabling will solve this issue, but you must be aware of few things:
you will still get the exception when hitting Start Button (or other case putting your app to dormant state). In this case your app is stopped and there is no way to prevent this behaviour.
you must fulfill certification requirements when disabling App Idle Detection - point 6.3
if you want to download files in the Background (lock screen, after closing/leaving app) then you can think of Background Transfers

Infinite wait loading remote image into BitmapImage() in Background Agent

I have a valid URL for a remote JPEG which I'm trying to load in the background. But I find I never get control back after invoking the BitmapImage() constructor. My question is, should this approach work, or should I pitch it all, load up BcpAsync project from NuGet and start working with WebClient asynch methods?
A sample URL for which it fails is
http://image.weather.com/images/maps/current/garden_june_720x486.jpg
It is valid. .UpdateAsync() references it from AppViewModel.Instance, it's not explicitly referenced here.
Here's the background agent:
protected override async void OnInvoke(ScheduledTask task)
{
AppViewModel.LoadData();
await AppViewModel.Instance.RemoteImageProxy.UpdateAsync();
AppViewModel.Instance.ImageUrl = AppViewModel.Instance.RemoteImageProxy.LocalFileUri;
AppViewModel.Instance.UpdateCount++;
PinnedTile.Update();
}
AppViewModel.SaveData();
#if DEBUG
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(AppViewModel.Instance.BgAgentInterval));
#endif
NotifyComplete();
}
Here's the invoked method:
public Task<double> UpdateAsync() {
LastCheckedTime = DateTime.UtcNow;
CompletionTask = new TaskCompletionSource<double>();
// Not usually called on UI thread, not worth optimizing for that case here.
Deployment.Current.Dispatcher.BeginInvoke(() => { //todo determine whether System.Windows.Deployment.Dispatcher can be called from main app, or just bgAgent.
HelperImageControl = new Image();
HelperImageControl.Loaded += im_Loaded;
HelperImageControl.ImageFailed += im_ImageFailed;
HelperImageControl.ImageOpened += im_ImageOpened;
// breakpoint here
HelperImageControl.Source = new BitmapImage(SourceUri);
// stepping over the function, control does not return here. Nor are any of the above events fired.
});
return CompletionTask.Task; // this will be completed in one of the subsequent control events...
}
You need to call CompletionTask.SetResult(); to return control back to the caller method.
This works (I'm returning 100 in case of successful download because you set the task to return double).
TaskCompletionSource<double> CompletionTask;
public Task<double> UpdateAsync()
{
CompletionTask = new TaskCompletionSource<double>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var HelperImageControl = new Image();
var bmp = new BitmapImage();
bmp.ImageOpened += bmp_ImageOpened;
bmp.ImageFailed += bmp_ImageFailed;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = new Uri("http://image.weather.com/images/maps/current/garden_june_720x486.jpg", UriKind.Absolute);
HelperImageControl.Source = bmp;
});
return CompletionTask.Task;
}
void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
CompletionTask.SetException(e.ErrorException);
}
void bmp_ImageOpened(object sender, RoutedEventArgs e)
{
CompletionTask.SetResult(100);
}

How to post messages to yammer private network

I want to post messages to yammer in different network. For this I have wrote the below code ,
it's giving the server not found exception.
rawtoken = Security.GetRawToken();
//TODO
//get list of Yammer tokens for this user
WebClient wc = new System.Net.WebClient();
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
wc.DownloadStringAsync(new Uri("https://www.yammer.com/api/v1/oauth/tokens.json?access_token=" + rawtoken));
void wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
string tokens = e.Result;
MessageBox.Show(tokens);
List<Response> myDeserializedObjList = (List<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(tokens,typeof(List<Response>));
List<Response> response = myDeserializedObjList.Where(item => item.network_id == "992371").ToList();
accessToken = response[0].token;
WebClient wc = new System.Net.WebClient();
Uri uri = new Uri("https://www.yammer.com/api/v1/messages.json?access_token=" + accessToken);
student ns = new student();
// wc.Headers["Authorization"] = "Bearer " + accessToken; //use discoEN token here
String data = "group-id=" + ns.group_id + "&body=" + ns.body;
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
wc.UploadStringTaskAsync(uri, data);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
You should use the SDK for Windows Mobile rather than rolling your own code. It is available from the Yammer Developer site. Your code also passes the token on a URL parameter. This is no longer supported and you need to pass it on the authentication header.
A ServerNotFoundException highlights a connectivity problem. Perhaps you are not connected to the network, cannot route connections, or cannot resolve www.yammer.com via DNS.

writing output to textarea in another class

hi i am new to java and am stuck here, been quite a while now that i can move forward; i have created a GUI interface for a chat system(although very rough because i have used the java help file and alot i have never done before). but i have another code which is standing on its own, no GUI at all, all out put are on command prompt. now i want to append all the output to the GUI that i have created. please help take a look at the codes below and suggest ways and stepps to help figure it out... please this is not an assignment from college, i am a graduate and working so i do this when i have time, because i believe knowing java is a great knowledge. thank you for your time.
this is the chat GUI Class that i created
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainView extends JFrame {
protected JLabel msgLabel, bannerLabel;
protected JButton sendBtn;
protected JTextArea genMsg, frndLst;
protected JTextField msgF;
protected JMenuBar menubar;
protected JMenu loginmenu, aboutmenu;
protected JMenuItem loginitem, disconnectitem, seperatoritem, quititem, aboutitem;
protected Toolkit toolkit;
MultiThreadChatClient chatClient;
public MainView() {
toolkit = Toolkit.getDefaultToolkit();
if(toolkit.getScreenSize().getWidth() > 600)
setSize(600, 575);
else
setSize((int)toolkit.getScreenSize().getWidth(),(int toolkit.getScreenSize().getHeight() - 20);
setResizable(false);
Dimension dimension = getSize();
setLayout(new FlowLayout());
setTitle("FRESHER MARKETING COMPANY");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) { System.exit(0);}});
menubar = new JMenuBar();
loginmenu = new JMenu("Login");
loginitem = new JMenuItem("Login");
disconnectitem = new JMenuItem("Disconnect");
seperatoritem = new JMenuItem("---------------");
quititem = new JMenuItem("Quit");
loginmenu.add(loginitem);
loginmenu.add(disconnectitem);
loginmenu.add(seperatoritem);
loginmenu.add(quititem);
aboutmenu = new JMenu("Help ");
aboutitem = new JMenuItem("About ");
aboutmenu.add(aboutitem);
menubar.add(loginmenu);
menubar.add(aboutmenu);
setJMenuBar(menubar);
Container container = getContentPane();
container.setLayout(new FlowLayout());
// create an ImageIcon
ImageIcon banner =new ImageIcon("images\\defaultbanner.gif");
bannerLabel = new JLabel(banner);
container.add(bannerLabel);
// create General Message Screen
genMsg = new JTextArea(30,45);
genMsg.setEditable(false);
genMsg.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
genMsg.setLineWrap(true);
container.add( new JScrollPane( genMsg ));
// create Friend List View
frndLst = new JTextArea(30, 15);
frndLst.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
container.add( new JScrollPane( frndLst));
frndLst.setEditable(false);
frndLst.setLineWrap(true);
msgLabel = new JLabel ("Message:");
container.add(msgLabel);
// create Message Field
msgF = new JTextField(38);
msgF.setEnabled( true );
msgF.setText("");
msgF.requestFocus();
msgF.addActionListener(
new ActionListener()
{
// send message to client
public void actionPerformed( ActionEvent event )
{
// sendData( event.getActionCommand() );
}
} // end anonymous inner class
); // end call to addActionListener
container.add(msgF);
// create Send Button
sendBtn = new JButton ("Send");
container.add(sendBtn);
setVisible( true );
}
public static void main(String[] args)
{
MainView application = new MainView();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
and this is the Chat multithread system that i want to append.
import java.io.*;
import java.net.*;
public class MultiThreadChatServer{
// Declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
// This chat server can accept up to 10 clients' connections
static clientThread t[] = new clientThread[10];
public static void main(String args[]) {
// The default port
int port_number=2222;
if (args.length < 1)
{
System.out.println("Usage: java MultiThreadChatServer \n"+
"Now using port number="+port_number);
} else {
port_number=Integer.valueOf(args[0]).intValue();
}
// Initialization section:
// Try to open a server socket on port port_number (default 2222)
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
serverSocket = new ServerSocket(port_number);
}
catch (IOException e)
{System.out.println(e);}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams for this socket will be created in
// client's thread since every client is served by the server in
// an individual thread
while(true){
try {
clientSocket = serverSocket.accept();
for(int i=0; i<=9; i++){
if(t[i]==null)
{
(t[i] = new clientThread(clientSocket,t)).start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);}
}
}
}
// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the
//server about the fact that a new client has joined the chat room,
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates.
class clientThread extends Thread{
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
clientThread t[];
public clientThread(Socket clientSocket, clientThread[] t){
this.clientSocket=clientSocket;
this.t=t;
}
public void run()
{
String line;
String name;
try{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name.");
name = is.readLine();
os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
while (true) {
line = is.readLine();
if(line.startsWith("/quit")) break;
for(int i=0; i<=9; i++)
if (t[i]!=null) t[i].os.println("<"+name+"> "+line);
}
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
os.println("*** Bye "+name+" ***");
// Clean up:
// Set to null the current thread variable such that other client could
// be accepted by the server
for(int i=0; i<=9; i++)
if (t[i]==this) t[i]=null;
// close the output stream
// close the input stream
// close the socket
is.close();
os.close();
clientSocket.close();
}
catch(IOException e){};
}
}
any suggestions would do really. be it steps to achieve this, links to make things easier, a code snippet... thank you..
i would like an example on how to append the ouputs from MultiThreadChatServer class to the textarea in MainView class
EDIT: re-read the code and noticed that the gui code actually holds an instance of the chat client. Have you considered making the chat client observable for chat client events and then setting the gui as a listener for those events?