Iphone push notification issue - iphone

I am working on iphone push notification. I can able to get my device token. I am using .net for pushing json data. But the issue is i cant get the notification. I just want to know whether .net has to push json data over in hosted machine?
Regards,
sathish

I believe that is related to:
Add iPhone push notification using ASP.NET server
Read through the linked project in there. It is pretty comprehensive. You can actually just use that library... it is pretty good.
Unless I misunderstood the question?

Use following snippet to send Push Notification
public void PendingNotification(string DeviceToken,string message)
{
try
{
int port = 2195;
//Developer
String hostname = "gateway.sandbox.push.apple.com";
//Production
//String hostname = "gateway.push.apple.com";
String certificatePassword = "XXXXXXX";
string certificatePath = Server.MapPath("~/cer.p12");
TcpClient client = new TcpClient(hostname, port);
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certificatePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
//String DeviceToken = "XXXXXXXXXXXX";
String LoginName = "Name";
int Counter = 1; //Badge Count;
String Message = message;
String UID = "your choice UID";
string payload = "{\"aps\":{\"alert\":\"" + Message + "\",\"badge\":" + Counter + ",\"sound\":\"default\"},\"UID\":\"" + UID + "\",\"LoginName\":\"" + LoginName + "\"}";
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(DeviceToken.ToUpper()));
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
public static byte[] HexStringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false;
}

Related

simcard message trans/receiver simulator

We have a project that we should send message to a huge number of sim cards (more than 1 Million) and receive and handle answers.
For testing this, I am using Selenium SMPPSim to simulate sending a message.
this is work fine for sending messages. and with enabling callback server I can receive messages that I send on another port.
But my question is how can I send back a message to SMPP server?
I am using EasySMPP library for connecting to smpp server
My SMPP Server Code:
private SMPPClient _client;
private readonly object _lockObject = new object();
public SMPPClient GetClient()
{
if (_client != null)
{
return _client;
}
lock (_lockObject)
{
_client = new SMPPClient();
var smsc = new SMSC
{
Host = "127.0.0.1",
Port = 2775,
SystemId = "smppclient1",
Password = "password",
SourceTon = 5,
SourceNpi = 1,
AddrTon = 1,
AddrNpi = 1,
SystemType = "8945",
};
_client.OnDeliverSm += Client_OnDeliverSm;
Console.WriteLine("Client_OnDeliverSm added");
_client.OnSubmitSmResp += Client_OnSubmitSmResp;
Console.WriteLine("OnSubmitSmResp added");
_client.AddSMSC(smsc);
if (!_client.Connect())
throw new Exception($"Can not connect to smpp link: {smsc.Host} : {smsc.Port}");
return _client;
}
}
public void SendByCampaignItemId()
{
var smppClient = GetClient();
lock (smppClient)
{
var msgId = smppClient.SubmitSM(1, 1, "339123456789", 1, 1, "339632587436",
0x40, // EsmClass.UdhIndicator
0x7f, // protocol identifier
0, // priority flag level 0
DateTime.MinValue,
DateTime.MinValue,
// DateTime.Now.AddMinutes(10),
//DateTime.Now.AddHours(3),
(byte)DeliveryReportType.AlwaysSendDeliveryReport,
0x00, //replace if present
0xf6, // data coding
0, // default msg id
new byte[] { 0x02,0x70,0x00,0x34,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF});
}
}
private void Client_OnSubmitSmResp(SubmitSmRespEventArgs e)
{
Console.WriteLine("Submit Received");
}
private void Client_OnDeliverSm(DeliverSmEventArgs e)
{
Console.WriteLine("Deliver Received");
}
And here is my code which listens to port 3333:
static void Main(string[] args)
{
TcpListener server = null;
try
{
Int32 port = 3333;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
//WHAT SHOULD I DO HERE SO THAT I CAN SEND BACK A MESSAGE (DELIVER SM) TO SMPP SIM??!!!
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
And my SMPPSIM Config file :
SMPP_PORT=2775
SMPP_CONNECTION_HANDLERS=10
CONNECTION_HANDLER_CLASS=com.seleniumsoftware.SMPPSim.StandardConnectionHandler
PROTOCOL_HANDLER_CLASS=com.seleniumsoftware.SMPPSim.StandardProtocolHandler
LIFE_CYCLE_MANAGER=com.seleniumsoftware.SMPPSim.LifeCycleManager
MESSAGE_STATE_CHECK_FREQUENCY=5000
MAX_TIME_ENROUTE=10000
DELAY_DELIVERY_RECEIPTS_BY=0
PERCENTAGE_THAT_TRANSITION=75
PERCENTAGE_DELIVERED=90
PERCENTAGE_UNDELIVERABLE=6
PERCENTAGE_ACCEPTED=2
PERCENTAGE_REJECTED=2
DISCARD_FROM_QUEUE_AFTER=60000
HTTP_PORT=88
HTTP_THREADS=1
DOCROOT=www
AUTHORISED_FILES=/css/style.css,/index.htm,/inject_mo.htm,/favicon.ico,/images/logo.gif,/images/dots.gif,/user-guide.htm,/images/homepage.gif,/images/inject_mo.gif
INJECT_MO_PAGE=/inject_mo.htm
SYSTEM_IDS=smppclient1,smppclient2
PASSWORDS=password,password
OUTBIND_ENABLED=false
OUTBIND_ESME_IP_ADDRESS=127.0.0.1
OUTBIND_ESME_PORT=2776
OUTBIND_ESME_SYSTEMID=smppclient1
OUTBIND_ESME_PASSWORD=password
DELIVERY_MESSAGES_PER_MINUTE=0
DELIVER_MESSAGES_FILE=deliver_messages.csv
LOOPBACK=TRUE
ESME_TO_ESME=false
OUTBOUND_QUEUE_MAX_SIZE=1000
INBOUND_QUEUE_MAX_SIZE=1000
DELAYED_INBOUND_QUEUE_PROCESSING_PERIOD=60
DELAYED_INBOUND_QUEUE_MAX_ATTEMPTS=100
DECODE_PDUS_IN_LOG=true
CAPTURE_SME_BINARY=false
CAPTURE_SME_BINARY_TO_FILE=sme_binary.capture
CAPTURE_SMPPSIM_BINARY=false
CAPTURE_SMPPSIM_BINARY_TO_FILE=smppsim_binary.capture
CAPTURE_SME_DECODED=false
CAPTURE_SME_DECODED_TO_FILE=sme_decoded.capture
CAPTURE_SMPPSIM_DECODED=false
CAPTURE_SMPPSIM_DECODED_TO_FILE=smppsim_decoded.capture
CALLBACK=true
CALLBACK_ID=SIM1
CALLBACK_TARGET_HOST=localhost
CALLBACK_PORT=3333
DELIVER_SM_INCLUDES_USSD_SERVICE_OP=false
DELIVERY_RECEIPT_OPTIONAL_PARAMS=true
DELIVERY_RECEIPT_TLV=1403/0A/34343132333435363738
SMSCID=SMPPSim
SIMULATE_VARIABLE_SUBMIT_SM_RESPONSE_TIMES=false
And another question:
If SMPPSim is not a good choice for my work, what else can i use?
UPDATE 1:
I look a little more and I think I find a simpler question.
assume that i have to SMPPSims.
How can I send message from a SMPPSim to another one?

Server Socket cannot accepts client. (C# UWP Async Socket Programming)

i made a Async Server Socket Code using C# Socket.
Although i wrote a code, then test to Console Environment,
it was working, but i tested that code at UWP.
but, it was not working. cannot accepts client.
Bind, Listen, Accept there are all no error, but this socket code cannot accepts client!
how can i solve me?? please help me..
private Socket m_ServerSocket;
private List<Socket> m_ClientSocket;
private int m_iPort = 1123;
private int m_iClients = 8;
private int m_iBufferSize = 128;
public bool Open(int IN_iPort, int IN_iClients, int IN_iBufferSize)
{
try
{
m_iPort = IN_iPort;
m_iClients = IN_iClients;
m_iBufferSize = IN_iBufferSize;
m_ClientSocket = new List<Socket>();
m_ServerSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, m_iPort);
m_ServerSocket.Bind(ipep);
m_ServerSocket.Listen(m_iClients);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Accept_Completed);
m_ServerSocket.AcceptAsync(args);
}
catch (Exception e)
{
return false;
}
m_bIsOpen = true;
return true;
}
private void Accept_Completed(object sender, SocketAsyncEventArgs e)
{
Socket ClientSocket = e.AcceptSocket;
m_ClientSocket.Add(ClientSocket);
if (m_ClientSocket != null)
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
byte[] szData = new byte[m_iBufferSize];
args.SetBuffer(szData, 0, m_iBufferSize);
args.UserToken = m_ClientSocket;
args.Completed
+= new EventHandler<SocketAsyncEventArgs>(Receive_Completed);
ClientSocket.ReceiveAsync(args);
}
e.AcceptSocket = null;
m_ServerSocket.AcceptAsync(e);
}
I have check your code, there seems no issue existing in your code. Please check if you have checked Internet(Clent&Server)option in your project appxmanifest. For more detail you could refer to Sockets official documentation.

Half file transferring in c# via socket?

I am developing the file transfer application via middle level greedy routing in which file sends to greedy and greedy sends file again to router
but he problem is some time client receives complete file and some time it receive some part of file
Here my code goes
Server Side
IPAddress[] ipAddress = Dns.GetHostAddresses("127.0.0.1");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5655);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string filePath = "";
fileDes = fileDes.Replace("\\", "/");
while (fileDes.IndexOf("/") > -1)
{
filePath += fileDes.Substring(0, fileDes.IndexOf("/") + 1);
fileDes = fileDes.Substring(fileDes.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileDes);
lblError.Text = "";
lblError.Text = "Buffering ...";
byte[] fileData = File.ReadAllBytes(filePath + fileDes);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
lblError.Text = "";
lblError.Text = "Connection to server ...";
clientSock.Connect(ipEnd);
lblError.Text = "";
lblError.Text = "File sending...";
// System.Threading.Thread.Sleep(1000);
clientSock.Send(clientData);
label3.Text = clientData.Length.ToString();
lblError.Text = "";
lblError.Text = "Disconnecting...";
clientSock.Close();
lblError.Text = "";
lblError.Text = "File transferred.";
In client
class DestCode
{
IPEndPoint ipEnd;
Socket sock;
public DestCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string receivedPath;
public static string curMsg = "Stopped";
public static int res;
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath +"/"+ fileName, FileMode.Append)); ;
bWrite.Write(clientData,4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
res = receivedBytesLen;
if (receivedPath == "")
{
MessageBox.Show("No Path was selected to Save the File");
}
curMsg = "Saving file...";
bWrite.Close();
clientSock.Close();
curMsg = "File Received ...";
StartServer();
}
catch (Exception ex)
{
curMsg = "File Receving error.";
}
}
}
In Greedy
class ReceiverCode
{
IPEndPoint ipEnd;
Socket sock;
public ReceiverCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, 5655);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string receivedPath;
public static string curMsg = "Stopped";
public static string Rout = "";
public static int rlength = 0;
public static string MsgStatus = "";
public static byte[] send;
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
System.Threading.Thread.Sleep(5000);
rlength = receivedBytesLen;
curMsg = "Receiving data...";
int receive = clientSock.Receive(clientData);
send = new byte[receivedBytesLen];
Array.Copy(clientData, send, receivedBytesLen);
Rout = "Start";
clientSock.Close();
curMsg = "Reeived & Saved file; Server Stopped.";
StartServer();
}
catch (Exception ex)
{
curMsg = "File Receving error.";
}
}
}
Please somebody help me
The problem is that Socket.Receive does not guarantee that you'll receive all the bytes you asked for. So you write:
int receivedBytesLen = clientSock.Receive(clientData);
The documentation says:
If you are using a connection-oriented Socket, the Receive method will read as much data as is available, up to the size of the buffer.
The call to Receive is getting all of the bytes that are currently available. It could be that the sender hasn't yet sent all of the bytes, or that your network stack hasn't received them and made them available.
To reliably send and receive data, the receiver has to know one of two things: either how many bytes it's expecting, or that there is some sentinel value that says, "that's all, folks." You can't count on a single Receive call to get everything.
When transferring files, the sender typically includes the size of the file as the first four bytes of the data being sent. Your code then reads the first four bytes (making sure that you get all four bytes) to determine the size, and then spins a loop, reading data from the socket until all of the expected bytes are received.
Something like:
const int MaximumSize = 1000000;
// read the first four bytes
var sizeBytes = ReadBytesFromSocket(socket, 4);
int size = BitConverter.ToInt32(sizeBytes);
var dataBuffer = ReadBytesFromSocket(socket, size);
// you now have your data
byte[] ReadBytesFromSocket(Socket socket, int size)
{
var buff = new byte[size];
int totalBytesRead = 0;
while (totalBytesRead < size)
{
int bytesRead = socket.Receive(buff, totalBytesRead, size-totalBytesRead, SocketFlags.None);
if (bytesRead == 0)
{
// nothing received. The socket has been closed.
// maybe an error.
break;
}
totalBytesRead += bytesRead
}
return buff;
}
See my blog post on reading streams (and the linked parts 1 and 2) for more information. The blog posts talk about streams, but the concepts are the same with sockets.

IPN Listner not working MVC3

My IPN listner is not working.when i tried with IPN listner Error is showing as follows "We're sorry, we could not send an IPN."
But i can access the IPN Handler url from browser.
here is my IPN handler Code.
public ActionResult IPN()
{
LogMessage ("entering ipn action ");
var formVals = new Dictionary<string, string>();
formVals.Add("cmd", "_notify-validate");
string response = GetPayPalResponse(formVals, true);
LogMessage ("IPN Response received: " + response + " <-- That was response. . . ");
if (response == "VALID")
{
LogMessage("Response Was Verified");
}
else
{
LogMessage("RESPONSE WAS NOT VERIFIED");
}
return Json("Sucess",JsonRequestBehavior.AllowGet);
}
string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
{
string paypalUrl = useSandbox
? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
StringBuilder sb = new StringBuilder();
sb.Append(strRequest);
foreach (string key in formVals.Keys)
{
sb.AppendFormat("&{0}={1}", key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
return response;
}
We had faced same issue before I feel it may be because your MVC Application may be published in shared hosting environment Then you have to follow some step to to make MVC RC application works
Here is the blog which help me to solve the issue.Please check this
http://helpnshareidea.blogspot.in/2013/11/mvc3-applications-in-windows-shared.html

SocketException was Unhandled by user code

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json.Linq;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPush_Click(object sender, EventArgs e)
{
pushMessage(txtDeviceID.Text.Trim(), txtPayload.Text.Trim());
}
public void pushMessage(string deviceID, string Mesaj)
{
int port = 2195;
String hostname = "ssl://gateway.sandbox.push.apple.com:2195";
String certificatePath = HttpContext.Current.Server.MapPath("PushNotifi.p12");
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "taxmann");
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Ssl3, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0); //The command
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
writer.Write(HexStringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":{\body\":\"" + Mesaj + "\"},\"badge\":1,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
lblResponse.Text = "Sucess..";
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
lblResponse.Text = ex.Message;
}
catch (Exception e)
{
client.Close();
lblResponse.Text = e.Message;
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
else // Do not allow this client to communicate with unauthenticated servers.
return false;
}
private static byte[] HexStringToByteArray(String DeviceID)
{
//convert Devide token to HEX value.
byte[] deviceToken = new byte[DeviceID.Length / 2];
for (int i = 0; i < deviceToken.Length; i++)
deviceToken[i] = byte.Parse(DeviceID.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
return deviceToken;
}
}
}
This is my code. When I run this, then
SocketException was unhandled by user code
on line
TcpClient client = new TcpClient(host-name, port);
when googling system.net.sockets.socketexception and not recognize ssl://gateway.sandbox.push.apple.com:2195 host name
How can I fix this?
Basically this code is for sending Push Notifications to an iPhone application.
I'm using localhost as the server for sending the notification.
I think the problem is your hostname string:
int port = 2195;
String hostname = "ssl://gateway.sandbox.push.apple.com:2195";
TcpClient client = new TcpClient(hostname, port);
The port value (2195) is a separate constructor parameter, so I don't think you should be passing it in the hostname parameter, as well.
Also, the protocol (e.g. ssl://) shouldn't be part of the hostname. The SslStream tells .NET that this is SSL.
If you look at this similar question on stack overflow, you'll see that they use something like this:
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
TcpClient client = new TcpClient(hostname, port);
P.S. I think you also had it right, in your original question on this subject