I tried to send Apple push notification with PushSharp library like that:
public class Push
{
private readonly PushBroker _push;
private static Push _instance;
public static Push Instance
{
get { return _instance ?? (_instance = new Push()); }
}
public Push()
{
_push = new PushBroker();
_push.OnNotificationSent += new NotificationSentDelegate(_push_OnNotificationSent);
_push.OnNotificationFailed += new NotificationFailedDelegate(_push_OnNotificationFailed);
_push.OnServiceException += new ServiceExceptionDelegate(_push_OnServiceException);
_push.OnChannelCreated += new ChannelCreatedDelegate(_push_OnChannelCreated);
_push.OnChannelDestroyed += new ChannelDestroyedDelegate(_push_OnChannelDestroyed);
_push.OnChannelException += new ChannelExceptionDelegate(_push_OnChannelException);
_push.OnNotificationRequeue += new NotificationRequeueDelegate(_push_OnNotificationRequeue);
_push.RegisterAppleService(new ApplePushChannelSettings(false, File.ReadAllBytes(#"C:\PathToCertificate\Name.p12"), "***"), "myAppId", new PushServiceSettings()
{
Channels = 1,
AutoScaleChannels = false
});
}
void _push_OnNotificationRequeue(object sender, NotificationRequeueEventArgs e)
{
Debug.Print("requeue");
}
void _push_OnChannelException(object sender, IPushChannel pushChannel, Exception error)
{
Debug.Print("channel exception");
}
void _push_OnChannelDestroyed(object sender)
{
Debug.Print("channel destroyed");
}
void _push_OnChannelCreated(object sender, IPushChannel pushChannel)
{
Debug.Print("channel created");
}
void _push_OnServiceException(object sender, System.Exception error)
{
Debug.Print("service exception");
}
void _push_OnNotificationFailed(object sender, INotification notification, System.Exception error)
{
Debug.Print("failed");
}
void _push_OnNotificationSent(object sender, INotification notification)
{
Debug.Print("sent");
}
public void Send(Notification notification)
{
_push.QueueNotification(notification);
_push.StopAllServices("biz.sintek.Rotapost", true);
}
public void SendAppleNotification(string deviceToken, string text)
{
Send(new AppleNotification()
.ForDeviceToken(deviceToken)
.WithAlert(text)
.WithSound("default"));
}
}
I'm calling SendAppleNotification method. It returns in no time but no exceptions throwed, no events called, no notifications sent and no notifications received.
I am using developer push certificate converted to .p12 format.
Double checked provisioning profile.
QueueNotification method of PushBroker class is generic. It using generic type parameter to identify which service to use for notification send.
Solution is to pass new AppleNotification()... directly to the QueueNotification
Related
I have created my own MSMQ wrapper class like this:
public class MsgQueue
{
private MessageQueue messageQueue;
public delegate void ReadMessageDelegate(string message);
public event ReadMessageDelegate NewMessageAvailable;
public MsgQueue(string queueName)
{
var queuePath = #".\Private$\" + queueName;
if (!MessageQueue.Exists(queuePath)) MessageQueue.Create(queuePath);
messageQueue = new MessageQueue(queuePath);
messageQueue.Label = queueName;
messageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string)});
messageQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MsgReceivedHandler);
messageQueue.BeginReceive();
}
private void MsgReceivedHandler(object sender, ReceiveCompletedEventArgs e)
{
try
{
MessageQueue mq = (MessageQueue)sender;
var message = mq.EndReceive(e.AsyncResult);
NewMessageAvailable(message.Body.ToString());
mq.BeginReceive();
}
catch (MessageQueueException)
{
// Handle sources of MessageQueueException.
}
return;
}
public void SendMessage(string message)
{
messageQueue.Send(message);
}
}
I tested it on two separate WinForms applications.
First app sends a text message when button is clicked:
private void btn_Click(object sender, EventArgs e)
{
var queue = new MsgQueue.MsgQueue("GBMqueue");
queue.SendMessage("some message text");
}
Second app is listening for any incoming messages and then tries to process it:
// declaration
private MsgQueue queue;
// preparation of the queue
private void Form1_Load(object sender, EventArgs e)
{
queue = new MsgQueue.MsgQueue("GBMqueue");
queue.NewMessageAvailable += Queue_NewMessageAvailable;
}
// Handler for the incoming messages
private void Queue_NewMessageAvailable(string message)
{
// Hits here very rarely!!!
}
The problem is that I can send the message from App1 several times, but the Queue_NewMessageAvailable handler catches only one random message, not the first one - just one of those which were sent.
No exception is thrown, it just does not catch the incoming messages.
What am I doing wrong here?
I think the first App should not listen for new messages. It's possible that it takes away the messages for the second App. It should only send messages.
When you split the functionality it should work.
so bascially i have a console application acting as a client software receiving data from a WCF feed. this works just fine when i want to do a console.writeline and print the data i'm getting in the console. I don't control the service end of the WCF feed so i have to use this console client software to access the data.
I'm trying to build an ASP.net web api application to pass this data to my own client via REST api. There are other complex reasons i have to do it this way but when it comes down to it i have to. I've built the basic web api for doing a GET to get the information. added the console application as a resource to the web api application but get an error message when I make the GET call.
This is the URL i'm using to make the GET call.
http://localhost:60421/api/CallData?skillNumber=92
After i make this call i get the below error message
[ERROR] System.InvalidOperationException occurred
HResult=0x80131509
Message=Could not find default endpoint element that references contract 'FeedService.IFeedService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
Source=
StackTrace:
The error occurs in this cs file. I've commented at the line it occurs in.
using ScoreBoardClientTest.FeedService;
namespace ScoreBoardClientTest
{
public class FeedServiceAgent : IFeedServiceAgent, IFeedServiceCallback
{
private static FeedServiceClient _feedServiceClient;
private ConnectionStats.ConnectionStatus _connectionStatus;
private bool _retrying;
private bool _disposed;
public FeedServiceAgent() //(IEventAggregator eventAggregator)
{
//Guard.ArgumentNotNull(eventAggregator, "eventAggregator");
//_eventAggregator = eventAggregator;
InitializeServiceClient();
}
public event MessageReceivedEventHandler MessageReceived;
public void InitializeServiceClient()
{
// The error message occurs at the line right below this
_feedServiceClient = new FeedServiceClient(new InstanceContext(this));
_feedServiceClient.InnerChannel.Opening += OnOpening;
_feedServiceClient.InnerChannel.Opened += OnOpened;
_feedServiceClient.InnerChannel.Closing += OnClosing;
_feedServiceClient.InnerChannel.Closed += OnClosed;
_feedServiceClient.InnerChannel.Faulted += OnFaulted;
}
private void DisposeServiceClient()
{
if (_feedServiceClient == null)
return;
try
{
_feedServiceClient.InnerChannel.Opening -= OnOpening;
_feedServiceClient.InnerChannel.Opened -= OnOpened;
_feedServiceClient.InnerChannel.Closing -= OnClosing;
_feedServiceClient.InnerChannel.Closed -= OnClosed;
_feedServiceClient.InnerChannel.Faulted -= OnFaulted;
_feedServiceClient.Abort();
}
catch
{
//Don't care.
}
finally
{
_feedServiceClient = null;
}
}
public ConnectionStats.ConnectionStatus ConnectionStatus
{
get { return _connectionStatus; }
set
{
_connectionStatus = value;
PublishConnectionStatus();
}
}
private void PublishConnectionStatus()
{
}
private void ProcessCmsData(A cmsData)
{
if (cmsData == null)
return;
var skill = new Skill();
var agents = new List<Agent>();
var cmLookupdata = new List<CmLookupData>();
// LookupData lookupdata = new LookupData();
if (cmsData.C != null && cmsData.C.Length > 0)
LookupDataTranslator.Translate(cmsData.C, cmLookupdata);
if (cmsData.AMember != null)
SkillTranslator.Translate(cmsData.AMember, skill, cmLookupdata);
if (cmsData.B != null && cmsData.B.Length > 0)
AgentTranslator.Translate(cmsData.B, agents, cmsData.AMember.A, cmsData.AMember.CmId); // passing skill params to validate the cmid to discard bad data
var mappedCmsData = new CmsData(skill, agents, cmLookupdata);
if (MessageReceived != null)
MessageReceived(this, new MessageReceivedEventArgs(mappedCmsData, null));
}
#region FeedServiceClient Channel Events
private void OnOpening(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Connecting;
}
private void OnOpened(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Connected;
}
private void OnClosing(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnecting;
}
private void OnClosed(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
}
private void OnFaulted(object sender, EventArgs eventArgs)
{
_connectionStatus = ConnectionStats.ConnectionStatus.Disconnected;
if (!_retrying)
ThreadPool.QueueUserWorkItem(delegate
{
Reconnect();
});
}
#endregion
private void Reconnect()
{
_retrying = true;
_connectionStatus = ConnectionStats.ConnectionStatus.Reconnecting;
// We don't want each client attempting the first reconnect all at the same time.
var random = new Random();
int randomWaitValue = random.Next(1, 10000);
Thread.Sleep(randomWaitValue);
// Try reconnecting 10 times.
for (int i = 1; i <= 10; i++)
{
try
{
DisposeServiceClient();
_feedServiceClient = new FeedServiceClient(new InstanceContext(this));
_feedServiceClient.Open();
_feedServiceClient.InnerChannel.Opening += OnOpening;
_feedServiceClient.InnerChannel.Opened += OnOpened;
_feedServiceClient.InnerChannel.Closing += OnClosing;
_feedServiceClient.InnerChannel.Closed += OnClosed;
_feedServiceClient.InnerChannel.Faulted += OnFaulted;
_connectionStatus = ConnectionStats.ConnectionStatus.Reconnected;
_retrying = false;
//_logger.Info(String.Format("The Scoreboard Client was able to reconnect after {0} retries.", i)) ;
return;
}
catch (Exception exception)
{
//_logger.Error(String.Format("The Scoreboard Client is unable to reconnect: {0}", exception)) ;
// Wait 30 seconds between retries to reduce network congestion.
Thread.Sleep(30000);
}
}
//_logger.Info("The Scoreboard Client was unable to reconnect after 10 retries.") ;
_connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
}
#region Implementation of IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
if (disposing)
{
// Dispose managed resources here.
DisposeServiceClient();
}
_disposed = true;
}
#endregion
public void NotifyCmsData(A cmsData)
{
ThreadPool.QueueUserWorkItem(delegate
{
ProcessCmsData(cmsData);
});
}
public void Subscribe(string eventTopic, int cmId)
{
if (String.IsNullOrEmpty(eventTopic))
return;
InvokeAction(x => x.Subscribe(eventTopic, cmId));
}
public void Unsubscribe(string eventTopic, int cmId)
{
if (String.IsNullOrEmpty(eventTopic))
return;
InvokeAction(x => x.Unsubscribe(eventTopic, cmId));
}
public void RefreshCmsData()
{
throw new NotImplementedException();
}
public LookupData GetLookupData()
{
LookupData lookupdata = new LookupData();
try
{
LookupDataTranslator.Translate(_feedServiceClient.GetLookupData(), lookupdata);
}
catch (Exception e)
{
//if (_logger != null)
// _logger.Error("Exception in finding the lookup data. Exception:" + e.Message);
throw e;
}
return lookupdata;
}
private void InvokeAction(Action<IFeedService> action)
{
try
{
action(_feedServiceClient);
}
catch (Exception exception)
{
//_logger.Error(" Exception in FeedService InvokeAction:" + exception.ToString());
_connectionStatus = ConnectionStats.ConnectionStatus.UnableToConnect;
}
}
}
}
The console application has a properly configured config file for the console application which is what the error message suggests does not exist. also, as i said above the console application functions fully by itself.
QUESTION
How do you use a WCF console application as a resource for a web api successfully?
I had to include the FeedService web URL inside of the web api service as long as the console application
I'm trying to fetch emails as soon as they arrive in my inbox using MailSystem.NET library. Everything works fine IMAP client gets connected but my NewMessageReceived event is never fired.
Please Help
Below is the code:
public static Imap4Client _imap = new Imap4Client();
public string SenderEmailAddress = System.Configuration.ConfigurationManager.AppSettings["EmailAddress"];
public string SenderEmailPassword = System.Configuration.ConfigurationManager.AppSettings["EmailPassword"];
public static Mailbox inbox = new Mailbox();
protected void Application_Start()
{
var worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(StartIdleProcess);
if (worker.IsBusy)
worker.CancelAsync();
worker.RunWorkerAsync();
}
private void StartIdleProcess(object sender, DoWorkEventArgs e)
{
try
{
if (_imap != null && _imap.IsConnected)
{
_imap.StopIdle();
_imap.Disconnect();
}
_imap = new Imap4Client();
_imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
_imap.ConnectSsl("imap.gmail.com", 993);
_imap.Login(SenderEmailAddress, SenderEmailPassword);
inbox = _imap.SelectMailbox("inbox");
int[] ids = inbox.Search("UNSEEN");
inbox.Subscribe();
_imap.StartIdle();
}
catch (Exception ex)
{
}
}
public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
{
int offset = e.MessageCount - 2;
Message message = inbox.Fetch.MessageObject(offset);
Debug.WriteLine("message subject: " + message.Subject);
// Do something with the source...
_imap.StopIdle();
}
I can't tell you the exact reason but it seems that interacting with the imapclient from the NewMessageReceived event just doesn't work.
In NewMessageReceived call _imap.StopIdle() then continue in your main execution flow and restart idle. Then use a boolean to drop out of the loop entirely.
private bool _stop = false;
private void StartIdle(object sender, DoWorkEventArgs e)
{
//Setup client
_imap = new Imap4Client();
_imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
StartRepeatExecution();
}
public void StartRepeatExecution()
{
_imap.StartIdle();
if(_stop) return;
//Handle your new messages here! dummy code
var mailBox = _imap.SelectMailBox("inbox");
var messages = mailBox.SearchParse("").Last();
StartRepeatExecution();
}
public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
{
//StopIdle will return to where _imap.StartIdle() was called.
_imap.StopIdle();
}
public void StopRepeatExecution()
{
_stop = true;
}
I am trying to Send Apple Push Notification. And, only ChannelCreated event gets called at my end, and not NotificationFailed or NotificationSent. Also,Notification does not gets sent to that specific Apple Device. I have also run telnet command to fix this issue, but in vain.
public static void SendApplePushNotification(string DeviceToken, String PostData)
{
try
{
string AppleapiPassKey = ConfigurationManager.AppSettings["ApplePushPassword"];
//AppleapiPassKey = string.Empty;
var push = new PushBroker();
push.OnNotificationSent += NotificationSent;
push.OnChannelException += ChannelException;
push.OnServiceException += ServiceException;
push.OnNotificationFailed += NotificationFailed;
push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
push.OnChannelCreated += ChannelCreated;
push.OnChannelDestroyed += ChannelDestroyed;
var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin/private_key_noenc.p12"));
//push.RegisterAppleService(new ApplePushChannelSettings(true,appleCert, AppleapiPassKey)); //Extension method
push.RegisterAppleService(new ApplePushChannelSettings(appleCert, AppleapiPassKey)); //Extension method
var message = new Message() { ChainId = 12, CreatedDate = DateTime.Now, Message1 = "hi how are you" };
push.QueueNotification(new AppleNotification()
.ForDeviceToken(DeviceToken)
.WithAlert(PostData)
.WithSound("Default")
//.WithCustomItem("content-available", message)
//.WithContentAvailable(1)
);
//push.StopAllServices(true);
}
catch (Exception ex)
{
LogError.LogErrorToFile(ex);
}
}
public static void DeviceSubscriptionChanged(object sender,
string oldSubscriptionId, string newSubscriptionId, INotification notification)
{
}
public static void NotificationSent(object sender, INotification notification)
{
}
public static void NotificationFailed(object sender,
INotification notification, Exception notificationFailureException)
{
}
public static void ChannelException
(object sender, IPushChannel channel, Exception exception)
{
}
public static void ServiceException(object sender, Exception exception)
{
}
public static void DeviceSubscriptionExpired(object sender,
string expiredDeviceSubscriptionId,
DateTime timestamp, INotification notification)
{
}
public static void ChannelDestroyed(object sender)
{
}
public static void ChannelCreated(object sender, IPushChannel pushChannel)
{
}
I'm currently working on a project and one of the featured devices is a Windows Tablet. To "connect" it to other devices (like some Raspberry Pi) in the project environment UDP is used to send messages. The Windows Tablet is intended to be some controlling device with soem touch functionality. Therefore I'm writing an App (and the intention of the App is not to put it into the Windows Store). The UDP part in this work is quite painful because I had to do much research since I started with no experience in App programming. More painful than the programming is, that I practically finished the work only to start over again because the App didn't receive UDP anymore.
Here's my code (I removed elements not relevant to the actual problem). I apologize for the bad coding....
App.xaml.cs:
sealed partial class App : Application
{
NetworkInterface ni = new NetworkInterface();
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
ni.MessageReceived += OnMessageReceived;
ni.Connect(new HostName("127.0.0.1"), "5556");
}
private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
Debug.WriteLine("Processing");
Debug.WriteLine(e.Message.Data);
}
public static new App Current
{
get { return Application.Current as App; }
}
private DatagramSocket _socket;
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Update_Timer();
}
DispatcherTimer timer = new DispatcherTimer();
private void Update_Timer()
{
timer.Start();
timer.Interval = new TimeSpan(0,0,0,0,500);
timer.Tick += alive;
}
private void alive(object sender, object e)
{
if (start == 0) {
Debug.WriteLine("App-Startup");
ni.SendMessage("Startup...");
start++;
}
else
{
Debug.WriteLine("App-Alive");
ni.SendMessage("alive");
start++;
}
}
}
This part of code is to send and receive Messages in the backgrond in the whole App.
And a NetworkInterface class:
class NetworkInterface
{
private DatagramSocket _socket;
public bool IsConnected { get; set; }
public NetworkInterface()
{
IsConnected = false;
_socket = new DatagramSocket();
_socket.MessageReceived += OnSocketMessageReceived;
}
public async void Connect(HostName remoteHostName, string remoteServiceNameOrPort)
{
if (IsConnected != true)
{
await _socket.BindServiceNameAsync("5321");
await _socket.ConnectAsync(remoteHostName, remoteServiceNameOrPort);
}
IsConnected = true;
}
public void alive(object sender, object e)
{
Debug.WriteLine("alive");
}
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
var reader = args.GetDataReader();
var count = reader.UnconsumedBufferLength;
var data = reader.ReadString(count);
Debug.WriteLine(args);
if (MessageReceived != null)
{
var ea = new MessageReceivedEventArgs();
ea.Message = new Message() { Data = data };
ea.RemoteHostName = args.RemoteAddress;
ea.RemotePort = args.RemotePort;
MessageReceived(this, ea);
}
}
DataWriter _writer = null;
public async void SendMessage(string message)
{
if (_writer == null)
{
var stream = _socket.OutputStream;
_writer = new DataWriter(stream);
}
_writer.WriteString(message);
await _writer.StoreAsync();
}
}
The main problems are:
If I dont send something before receiving, I won't be able top get an message.
If I send before I have random Faults at this line:
var reader = args.GetDataReader();
If nothing fails, I'm not able to receive messages from a local Python script (which works) but I can send messages from a local program which the App receives.
Does anyone know how I can fix these problems?
Thanks in advance!