Pushsharp apple notification A call to SSPI failed error - c#

I am using PushSharp to send Apple Push Notification in C# , i have my production .pem file and its password. Below is my code snippet.Am always getting this error ..
"A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted-"
OR
"System.IO.IOException: Authentication failed because the remote party has closed the transport stream."
I tried almost all codes available in net.Even tried MoonAPNS but same error, For custom script also am getting this SSPI failure error. I use the same .pem file and run a php script to send push notification to APN from same server,it works.
var push = new PushBroker();
var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ck.pem"));
push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "pwd"));
push.QueueNotification(new AppleNotification()
.ForDeviceToken("XXXXXXXXXXXXXXX")
.WithAlert("Hello World!")
.WithBadge(7)
.WithSound("sound.caf"));
LogManager.Info("Waiting for Queue to Finish..");
push.StopAllServices();
Please help
Thanks in advance

I think your c# may be incorrect, To verify, rather than with a .pem, can you try with your p12 cert using the below code as a test...
Boolean bsandbox = true;
string p12fileName =AppDomain.CurrentDomain.BaseDirectory + "yourCert.p12";
string p12password = "1234";
string deviceID1 = "2909b25e0c699b2dc4864b4b9f719e67aac7e0fab791a72a086ffb788ba28f6a"; //
string msg = "This is the message sent at : ";
string alert = "Hello world at " + DateTime.Now.ToLongTimeString();
int badge = 1;
string soundstring = "default";
var payload1 = new NotificationPayload(deviceID1, alert, badge, soundstring);
payload1.AddCustom("custom1", msg);
var notificationList = new List<NotificationPayload> { payload1 };
var push = new PushNotification(bsandbox, p12fileName, p12password);
var rejected = push.SendToApple(notificationList);`

Related

DocuSign: Error calling CreateEnvelope

I have the following code for adding a new Envelope with a local file:
EnvelopeDefinition envelope = new EnvelopeDefinition
{
Status = "sent"
};
// Get the contract file
Byte[] bytes = File.ReadAllBytes("[Local Filename]");
// Add a document to the envelope
DocuSign.eSign.Model.Document doc = new DocuSign.eSign.Model.Document();
doc.DocumentBase64 = System.Convert.ToBase64String(bytes);
doc.Name = contract.FileName;
doc.DocumentId = "1";
envelope.Documents = new List<DocuSign.eSign.Model.Document>();
envelope.Documents.Add(doc);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Email = recipientEmail;
signer.Name = recipientName;
signer.RecipientId = "1";
// Create a |SignHere| tab somewhere on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.DocumentId = "1";
signHere.PageNumber = "1";
signHere.RecipientId = "1";
signHere.XPosition = "100";
signHere.YPosition = "150";
signer.Tabs.SignHereTabs.Add(signHere);
envelope.Recipients = new Recipients();
envelope.Recipients.Signers = new List<Signer>();
envelope.Recipients.Signers.Add(signer);
DocuSignAuthentication Creds = new DocuSignAuthentication
{
Username = "[My Username]",
Password = "[My Password]",
IntegratorKey = "[My Integration Key]"
};
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi/v2/accounts/XXXXXXX");
string authHeader = JsonConvert.SerializeObject(Creds);
DocuSign.eSign.Client.Configuration cfg = new DocuSign.eSign.Client.Configuration(apiClient);
cfg.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
EnvelopesApi envelopeApi = new EnvelopesApi(cfg);
EnvelopeSummary response = envelopeApi.CreateEnvelope("XXXXXXX", envelope);
The server returns a very little information in the error:
[ApiException: Error calling CreateEnvelope: ]
DocuSign.eSign.Api.EnvelopesApi.CreateEnvelopeWithHttpInfo(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in
Y:\dev\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:2606
DocuSign.eSign.Api.EnvelopesApi.CreateEnvelope(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in Y:\dev\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:2532
[Rest of the stack trace relates to our code]
If we try to use fiddler to capture any error messages from the server, the error becomes:
Could not establish trust relationship for the SSL/TLS secure channel
Is there anyway to get a more information about what's wrong with our request? Or is there an un-encrypted developer endpoint available to work through these kinds of issues? Any help you can spare would be greatly appreciated.
The error "Could not establish trust relationship for the SSL/TLS secure channel" means that the HTTPRequest call from the client (which can be your server, but is a client in the sense that it made the HTTPRequest) to the server (DocuSign in this case) could not use TLS over SSL (https:// address) to ensure that there's a certificate that allows to encrypt the information in the HTTPRequest and HttpResponse. This can happen for a variety of reasons including not having the current version of TLS on the client as well as having the wrong certificate or other issues with the network. I would recommend trying to make this call from a different server, potentially outside your corporate network to isolate the problem. Also, check the version of TLS to ensure it's at least 1.1

Getting unread count from gmail using C#

I've been trying to get the count of unread emails in Gmail but I'm encountering some problems. I did a search and I found ImapX library that should help me achieve this, but the code I found here on StackOverFlow on previews questions doesn't work. This is my code right now:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string username = "my_email#gmail.com";
string passwd = "my_pass";
int unread = 0;
ImapClient client = new ImapClient("imap.gmail.com", 993, true);
bool result = client.IsConnected;
if (result)
Console.WriteLine("Connection Established");
result = client.Login(username, passwd); // <-- Error here
if (result)
{
Console.WriteLine("Logged in");
FolderCollection folders = client.Folders;
// Message messages = client.Folders["INBOX"].Messages;
foreach (ImapX.Message m in client.Folders["INBOX"].Messages)
{
if (m.Seen == false)
unread++;
}
Console.WriteLine(unread);
}
}
}
}
The Error is:
The selected authentication mechanism is not supported" on line 26
which is result = client.Login(username, passwd);
Sample from ImapX:
var client = new ImapX.ImapClient("imap.gmail.com", 993, true);
client.Connection();
client.LogIn(userName, userPassword);
var messages = client.Folders["INBOX"].Search("ALL", true);
Maybe you have enabled Two-factor authentication and you need generate application password. Othery way you will receive an e-mail warning that something is trying to access your mailbox and you must add your application as an exception. As an alternate solution you can try https://github.com/jstedfast/MailKit sample code at the bottom of the README
Most likely, gmail is looking for you to do a STARTTLS command, which it appears ImapX does not support. If you look at the response to the IMAPX1 CAPABILITY request, you'll likely see a "LOGINDISABLED" element, which means the server won't accept the "LOGIN" statement yet. So even if you UseSSL, the server (Microsoft Exchange in my case) is still looking for the STARTTLS command before it will let me LOGIN.
You have to make the connection.
ImapClient client = new ImapClient("imap.gmail.com", 993, true);
client.Connect();
bool result = client.IsConnected;
So if you added the line client.Connect(), I think it solves your problem.

a call to sspi failed see inner exception. the message received was unexpected or badly formatted in windows 7]

I am getting the following error " a call to sspi failed see inner exception. the message received was unexpected or badly formatted in windows 7". i tried all the possible ways but no luck. please check it
Here is the code
int port = 2195;
String deviceID = "d6c597fcc4e3426993cf29a3a8857efbed3462d5d8e9e32c0f8b387djkdklldk";
String hostname = "gateway.sandbox.push.apple.com"; // TEST
//String hostname = "gateway.push.apple.com"; // REAL
string p12FilePassword = "password";
// #"cert.p12";
String certificatePath = HttpContext.Current.Server.MapPath("~/Certificate.p12");
X509Certificate2 clientCertificate = string.IsNullOrEmpty(p12FilePassword) ? new X509Certificate2(File.ReadAllBytes(certificatePath)) : new X509Certificate2(File.ReadAllBytes(certificatePath), p12FilePassword, X509KeyStorageFlags.MachineKeySet);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(client.GetStream(), false, ValidateServerCertificate, SelectLocalCertificate);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, System.Security.Authentication.SslProtocols.Tls, false);
}
catch (Exception e)
{
throw (e);
//client.Close();
//return;
}
I see this is an old post but I recently faced this problem. Application can work on my Windows10 and failed on Windows server 2008r2 and 2012r2.
The solution is get rid off SslStream and use libraries like openssl or bouncycastle for tls connections.

APNS Input string was not in a correct format. Disconnected

I am trying to set up apple push notifications, i am writing my own code for the server and as far as i know i have set up the app correctly. How ever i keep getting the following error come back from the log:
Payload queue received. Connecting to apple server. Creating SSL
connection. Conected. Payload generated for
"Token goes here i deleted it :
{"aps":{"alert":"test","badge":1,"sound":"default"}} Notification
successfully sent to APNS server for Device Toekn :
"Token here I've deleted it" An
error occurred while reading Apple response for token
"Token here I've deleted it" -
Input string was not in a correct format. Disconnected
This is my code.
var push = new PushNotification(true, #"C:\wwwroot\UltraNet\PushService\bin\Debug\206dist.p12", "ultrait");
var payload = new NotificationPayload("devicetoken here ive deleted it", "test", 1, "default");
var p = new List<NotificationPayload> { payload };
var result = push.SendToApple(p);
Console.ReadLine();
I have made sure that the certificates etc are set up correctly.
I am testing it as a adhoc app at the moment because it takes so long for a new version to be able to go live.
I really don't know where I'm going wrong if any one could help it would be brilliant thank you.
I also don't know what i need to do with the PEM files that i have created.
Edit***
I have the correct token this is another error that i receive
Payload generated for
df99286a1cb993cecba86b2e21f3fc4c04d214fcf7e0cf35a668fc822bdaa053 :
{"aps":{"alert":"test","badge":1,"sound":"default"}} Notification
successfully sent to APNS server for Device Toekn :
df99286a1cb993cecba86b2e21f3fc4c04d214fcf7e0cf35a668fc822bdaa053
Disconnected. An error occurred while reading Apple response for token
df99286a1cb993cecba86b2e21f3fc4c04d214fcf7e0cf35a668fc822bdaa053 -
Safe handle has been closed
Based on the code of ReadResponse (see below), the Input string was not in a correct format error message refers to the response received from Apple, and not to the notification you sent.
The code failed to properly read the error response from Apple.
Had it succeeded in reading the response, you would have known what the exact failure was and which message failed. Since you don't have the error response, it's a safe bet to assume the problem is your device token. That's the most common failure. If you can isolate the device token for which the error occurs, you should simply delete that token from your DB. Invalid Device Token error often occurs when you try to use sandbox tokens when pushing to production environment or vica versa.
private void ReadResponse(IAsyncResult ar)
{
if (!_conected)
return;
string payLoadId = "";
int payLoadIndex = 0;
try
{
var info = ar.AsyncState as MyAsyncInfo;
info.MyStream.ReadTimeout = 100;
if (_apnsStream.CanRead)
{
var command = Convert.ToInt16(info.ByteArray[0]);
var status = Convert.ToInt16(info.ByteArray[1]);
var ID = new byte[4];
Array.Copy(info.ByteArray, 2, ID, 0, 4);
payLoadId = Encoding.Default.GetString(ID);
payLoadIndex = ((int.Parse(payLoadId)) - 1000);
Logger.Error("Apple rejected palyload for device token : " + _notifications[payLoadIndex].DeviceToken);
Logger.Error("Apple Error code : " + _errorList[status]);
Logger.Error("Connection terminated by Apple.");
_rejected.Add(_notifications[payLoadIndex].DeviceToken);
_conected = false;
}
}
catch (Exception ex)
{
Logger.Error("An error occurred while reading Apple response for token {0} - {1}", _notifications[payLoadIndex].DeviceToken, ex.Message);
}
}
It was all to do with my certificates.
Because i hadn't turnt my combined PEM certificate back to a p12 file.

YouTube API, C#.net - Getting video info from YouTube failed some times

I'm trying to add comment to videos on YouTube , some times when I'm getting a video to add comment on it, YouTube send me the below error:
Execution of request failed: http://gdata.youtube.com/feeds/api/videos/ceVlltPBcHg/comments
The inner message of the exception is: "The remote server returned an error: (403) Forbidden."
public bool commentVideo(string videoId)
{
Uri Url = new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoId);
YouTubeRequestSettings s = new YouTubeRequestSettings(AppName, ApiKey,UserName,
Password);
s.Timeout = 10000000;
YouTubeRequest account = new YouTubeRequest(s);
account.Proxy = GetProxyForUser(user);
Video video = account.Retrieve<Video>(Url);//some times got exception
string rating = commentRepository.getRating();
Comment c = new Comment();
c.Content = commentRepository.getComment();
account.AddComment(video, c);
Console.WriteLine("Comment successfully added to : " + videoId);
return true;
}
What is wrong in my code?
It seems google's qouta security rules return error to my code. Code works correctly when I use the code in long intervals.

Categories