Using .net PUT to IBM MQ queue no longer sending message - c#

In c#, PUT is no longer sending messages but the try catch is not throwing an error. I can not find a trace or error log on the client. Please let me know where else to look for a clue to what has changed.
The client is on a Windows 2012 server and MQ is on a mainframe.
// in class constuctor
try
{
_queueManager = new MQQueueManager(queueManagerName, channelName, connectionName);
_requestQueue = _queueManager.AccessQueue(queueName, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING); //added | MQC.MQOO_INQUIRE
}
catch (MQException MQexp)
{
Console.WriteLine("Error:" + MQexp.Message);
Console.Read();
}
public string Queue_PutTestMsgs(string message)
{
MQMessage queueMessage = new MQMessage();
MQPutMessageOptions queuePutMessageOptions = new MQPutMessageOptions();
try
{
queueMessage.Format = MQC.MQFMT_STRING;
queueMessage.MessageType = MQC.MQMT_REQUEST;
queueMessage.ReplyToQueueManagerName = _responseQueueManagerName;//added
queueMessage.ReplyToQueueName = _responseQueueName;
queueMessage.WriteString(message);
_requestQueue.Put(queueMessage, queuePutMessageOptions);
}
catch (MQException MQexp)
{
Console.WriteLine("Error:" + MQexp.Message);
Console.Read();
}
return message;
}

Related

UdpClient wont connect to IpAdress.Any

I'm trying to listen for UDP packets from unknown source. But can't bind on the "unspecified adress" (0.0.0.0 or ::)
I've already tried listening on ::1. But from what i tested that only works for local connections that don't pass the network interface.
public async void AwaitDiscoveryReply()
{
try
{
using (var client = new UdpClient(AddressFamily.InterNetworkV6))
{
client.Connect(IPAddress.IPv6Any,4568);
var result = await client.ReceiveAsync();
Debug.WriteLine("Received DR");
var stateProtocol = StateProtocol.FromBytes(result.Buffer);
var robeatsDevice = new RobeatsDevice
{
Id = stateProtocol.DeviceId,
Name = stateProtocol.DeviceName,
EndPoint = client.Client.RemoteEndPoint,
StateProtocol = stateProtocol
};
OnDiscoveryReply(new DeviceDiscoveryEventArgs {RobeatsDevice = robeatsDevice});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
This keeps throwing the exception: The requested address is not valid in its context [::]:4568
UDP sockets are connectionless. "Connect" methods on UDP socket implementations, by convention (don't ask me why) establish default endpoints / filter traffic. If you want to receive traffic from any address, you don't need to "connect" at all. Use the constructor with signature UdpClient(Int32, AddressFamily) and delete the Connect() invocation:
public async void AwaitDiscoveryReply()
{
try
{
using (var client = new UdpClient(4568,AddressFamily.InterNetworkV6))
{
var result = await client.ReceiveAsync();
Debug.WriteLine("Received DR");
var stateProtocol = StateProtocol.FromBytes(result.Buffer);
var robeatsDevice = new RobeatsDevice
{
Id = stateProtocol.DeviceId,
Name = stateProtocol.DeviceName,
EndPoint = client.Client.RemoteEndPoint,
StateProtocol = stateProtocol
};
OnDiscoveryReply(new DeviceDiscoveryEventArgs {RobeatsDevice = robeatsDevice});
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}

IOS Push Notification doesn't work using PushSharp

Im using PushSHarp on my project via Nuget and VisualStudio (c#) to try to send push notification through APN.
I created all of the file that required using my Apple account(development certificate, .p12 files etc).
Each time i used the right code i stil have the same error( i recreated all of the thing to be sure my token id is not bad):
ID= 1 Code= ConnectionError
PushSharp.Common.NotificationException: Invalid DeviceToken à
PushSharp.Apple.ApnsNotification.ToBytes() à
PushSharp.Apple.ApnsConnection.createBatch(List1 toSend) à
PushSharp.Apple.ApnsConnection.<SendBatch>d__21.MoveNext() Message
Apns notification error: 'ConnectionError' String
PushSharp.Apple.ApnsNotificationException: Apns notification error:
'ConnectionError' ---> PushSharp.Common.NotificationException: Invalid
DeviceToken à PushSharp.Apple.ApnsNotification.ToBytes() à
PushSharp.Apple.ApnsConnection.createBatch(List1 toSend) à
PushSharp.Apple.ApnsConnection.d__21.MoveNext()
Can you help me in this issue please? i really dont understand what happened.
I am using the below code given in their git wiki page to send the notifications here is the code
string TokenId = "f38205ce2137862735bd32e85b581dc85e2dc0abc04a2702e2899bddb9114543";
PushNotificationApple _notifservice = new PushNotificationApple();
_notifservice.SendAppleNotification(TokenId, "Test1");
public void SendAppleNotification(string tokenId, string message)
{
byte[] appleCert = null;
try
{
appleCert = File.ReadAllBytes("F:\\Dev\\ap.p12");
System.Diagnostics.Debug.WriteLine("OK LECTURE APPLE CERT");
}
catch (Exception ex)
{
var toto = ex.Message;
System.Diagnostics.Debug.WriteLine(" Exception lecture"+ ex.Message);
}
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "BrumbySolution99");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
System.Diagnostics.Debug.WriteLine("ERRREUR NOTIFICATION");
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
System.Diagnostics.Debug.WriteLine("Apple Notification Failed: ID= " + notificationException.Notification.Identifier+" Code= "+ statusCode);
System.Diagnostics.Debug.WriteLine("link "+ ex.HelpLink);
System.Diagnostics.Debug.WriteLine("Inner "+ ex.InnerException);
System.Diagnostics.Debug.WriteLine("Message " + ex.Message);
System.Diagnostics.Debug.WriteLine("String " + ex.ToString());
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
System.Diagnostics.Debug.WriteLine("Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
System.Diagnostics.Debug.WriteLine("APPLE NOTIFICATION SENT");
// Console.WriteLine("Apple Notification Sent!");
};
// Start the broker
apnsBroker.Start();
var notification_message = "{\"aps\":{\"alert\":{\"title\":\" Title " + message + "\",\"body\":\"Body " + message + "\"},\"badge\":\"1\"}}";
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = tokenId,
Payload = JObject.Parse(notification_message)
});
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
}
}

Microsoft.Azure.NotificationHub - Async call in sync method

I currently have to provide a sync as async method in my API: Please find the code below. The only problem is that I don’t have a
sync method in the backend. I use Azure.NotificationHub client. That client has only *Async methods. Is my way reasonable?
public PushHubNotificationResult SendPushMessage(string userId, string message)
{
PushHubNotificationResult result = new PushHubNotificationResult();
try
{
result = SendPushMessageAsync(userId, message).GetAwaiter().GetResult();
} catch (Exception ex)
{
result.Status = PushHubNotificationResultType.Error;
result.Error = ex.Message;
result.Exception = ex;
}
return result;
}
public async Task<PushHubNotificationResult> SendPushMessageAsync(string userId, string message)
{
PushHubNotificationResult result = new PushHubNotificationResult();
// EnableTestSend see: https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-push-notification-fixer/#self-diagnose-tips
// Create a new Notification Hub client.
Microsoft.Azure.NotificationHubs.NotificationHubClient hub =
Microsoft.Azure.NotificationHubs.NotificationHubClient.CreateClientFromConnectionString(NotificationHub, NotificationHubName);
// Sending the message so that all template registrations that contain "messageParam"
// will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
Dictionary<string, string> templateParams = new Dictionary<string, string>();
templateParams["messageParam"] = message;
string userTag = "_UserId:" + userId; // That line sets the IMEI or SerialNo (WLAN only device) == userId to which the push message is sent
try
{
// Send the push notification and log the results.
NotificationOutcome outcome = await hub.SendTemplateNotificationAsync(templateParams, userTag);
result.Status = PushHubNotificationResultType.Success;
foreach (RegistrationResult hubResult in outcome.Results)
{
result.PushNotificationHub = hubResult.ApplicationPlatform;
result.RegistrationId = hubResult.RegistrationId;
result.Outcome = hubResult.Outcome;
}
}
catch (System.Exception ex)
{
result.Status = PushHubNotificationResultType.Error;
result.Error = ex.Message;
result.Exception = ex;
}
return result;
}
thanks for any advice,
Eric
If you want to use sync-over-async, it's very important that you use ConfigureAwait(false) in your async code, otherwise you are very likely to get a deadlock.
NotificationOutcome outcome =
await hub.SendTemplateNotificationAsync(templateParams, userTag).ConfigureAwait(false);
The async method already converts exceptions to PushHubNotificationResultType.Error, why does the sync version do it too?

Can I read messages from gmail using gmail api and c#?

I want read all messages in my gmail account using c# and gmail api.
Can I do this?
I read a lot of articles in Gmail API, but i couldn't read messages.
Also I want to read a body of messages or header.
I will be very glad if someone can help me :)
I use this code snippet:
public static List<Message> ListMessages(GmailService service, String userId)
{
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
And this:
foreach (var item in ListMessages(service,"me"))
MessageBox.Show(item.Snippet);
But in a result I have empty message box.
It works for me
var inboxlistRequest = service.Users.Messages.List("your-email-address");
inboxlistRequest.LabelIds = "INBOX";
inboxlistRequest.IncludeSpamTrash = false;
//get our emails
var emailListResponse = inboxlistRequest.Execute();
foreach (var mail in emailListResponse.Messages)
{
var mailId = mail.Id;
var threadId = mail.ThreadId;
Message message = service.Users.Messages.Get("your-email-address", mailId).Execute();
Console.WriteLine(message.Snippet);
}
Yes you should have no issue doing what you say. I would suggest reading the documentation a bit more.
First you have to authenticate - the following shows how to do this with a service account (more details here https://developers.google.com/gmail/api/auth/web-server)
serviceAccountEmail = primaryLink.serviceEmailAddress;
certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "certs//" + primaryLink.certificate, primaryLink.certificatePassword, X509KeyStorageFlags.Exportable);
try
{
credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = z.us.emailAccount,
Scopes = new[] { "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://mail.google.com/" }
}.FromCertificate(certificate));
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
gs = new GmailService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = "Example",
HttpClientInitializer = credential
});
}
else
{
throw new Exception("gmail authentication Error.");
}
}
catch (Exception ex)
{
throw ex;
}
ListMessagesResponse respM = reqM.Execute();
if (respM.Messages != null)
{
foreach (Message m in respM.Messages)
{}
}
Once you have the message List you can iterate through the messages and either use a MIME parser or traverse the message structure to get the header, body etc.
There are lots of posts in this forum which go through how to do that.
I searched for a full example, without luck, but this is my working example. Based on https://developers.google.com/gmail/api/guides
Authenticate : https://developers.google.com/gmail/api/auth/web-server
get ALL emails
loop through all emails by Id, and request message etc.
here is the code snippet to get the first email's atachments, but you can simply loop over all foundIds to get all emails, and use message.snippet to get body :
List<string> foundIds = new List<string>();
string outputDir = "/EXAMPLE/EXAMPLE/"; // your preferred Dir to save attachments to
List<Google.Apis.Gmail.v1.Data.Thread> resultThread = new List<Google.Apis.Gmail.v1.Data.Thread>();
UsersResource.ThreadsResource.ListRequest requestThread = service.Users.Threads.List("me");
do
{
try
{
ListThreadsResponse responseThread = requestThread.Execute();
resultThread.AddRange(responseThread.Threads);
foreach (var item in responseThread.Threads )
{
foundIds.Add(item.Id);
}
requestThread.PageToken = responseThread.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(requestThread.PageToken));
try
{
Message message = service.Users.Messages.Get("me", foundIds[0]).Execute();
IList<MessagePart> parts = message.Payload.Parts;
foreach (MessagePart part in parts)
{
if (!String.IsNullOrEmpty(part.Filename))
{
String attId = part.Body.AttachmentId;
MessagePartBody attachPart = service.Users.Messages.Attachments.Get("me", foundIds[0], attId).Execute();
// Converting from RFC 4648 base64 to base64url encoding
// see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
String attachData = attachPart.Data.Replace('-', '+');
attachData = attachData.Replace('_', '/');
byte[] data = Convert.FromBase64String(attachData);
File.WriteAllBytes(Path.Combine(outputDir, part.Filename), data);
}
}
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
I would suggest taking a look at this article on how to handle the actual response structure. It can be somewhat complex with the way the Gmail API gives the results back to you.
https://sigparser.com/developers/email-parsing/gmail-api/
#BlackCat, Your ListMessages looks good. Now, to get the message body, you have to decode MimeType "text/plain" or "text/html". For eg:
public static void GetBody(GmailService service, String userId, String messageId, String outputDir)
{
try
{
Message message = service.Users.Messages.Get(userId, messageId).Execute();
Console.WriteLine(message.InternalDate);
if (message.Payload.MimeType == "text/plain")
{
byte[] data = FromBase64ForUrlString(message.Payload.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
}
else
{
IList<MessagePart> parts = message.Payload.Parts;
if (parts != null && parts.Count > 0)
{
foreach (MessagePart part in parts)
{
if (part.MimeType == "text/html")
{
byte[] data = FromBase64ForUrlString(part.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
}
}
}
}
Console.WriteLine("----");
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}

Error accessing wcf service asynchronously in c# .net: unauthorised

I am building a standard odata client using: Microsoft.Data.Services.Client.Portable Windows 8 VS2013
I have added a service reference to the project (TMALiveData) with authorisation. Now I want to retrieve data but when I do I get the following error: DataServiceQueryException.InvalidOperationException
I looked at the DataServiceQueryResult object the status code is: System.Net.HttpStatusCode.Unauthorized
When I added the reference it asked me for my credentials, so I assumed this would be sent with each query, but it clearly isn't. How do I add the credentials (password and username) in the DataServiceQuery object? Below is my current code:
public class testLSCon
{
static string mResult;
public static string result { get { return mResult; } }
public static void testREADLiveConnection()
{
Uri tmaLiveDataRoot = new Uri("https://xxx.azurewebsites.net/xxx.svc/");
TMLiveData.TMALiveData mLiveData = new TMLiveData.TMALiveData(tmaLiveDataRoot);
mResult = null;
DataServiceQuery<TMLiveData.JobType> query = (DataServiceQuery<TMLiveData.JobType>)mLiveData.JobTypes.Where(c => c.IsActive == true);
mResult = "Trying to READ the data";
try
{
query.BeginExecute(OnQueryComplete, query);
}
catch (Exception ex)
{
mResult = "Error on beginExecute: " + ex.Message;
}
}
private static void OnQueryComplete(IAsyncResult result)
{
DataServiceQuery<TMLiveData.JobType> query = (DataServiceQuery<TMLiveData.JobType>) result.AsyncState;
mResult = "Done!";
try
{
foreach (TMLiveData.JobType jobType in query.EndExecute(result))
{
mResult += jobType.JobType1 + ",";
}
}
catch (DataServiceClientException ex)
{
mResult = "Error looping for items: (DataServiceClientException)" + ex.Message;
}
catch (DataServiceQueryException ex2)
{
mResult = "Error looping for items: (DataServiceQueryException)" ;
}
catch (Exception ex3)
{
mResult = "Error looping for items: (general exception)" + ex3.Message;
}
}
}
You can either set it to the credentials of the current user (so the credentials of the user the client is running as)
mLiveData.Credentials = CredentialCache.DefaultCredentials;
or if you need to impersonate another user you can use this (obviously swap the strings for the details you need - maybe passed in from config.
mLiveData.Credentials = new System.Net.NetworkCredential("UserName", "Password", "Domain");

Categories