Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

BlackBerry Push Development

Reply
New Contributor
anilat87
Posts: 3
Registered: ‎05-09-2013
My Device: 9700
My Carrier: Airtel

How Send Push Notifcation Using C#.Net Code In Blackberry

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Net;

namespace BlackberryPUSH
{
public partial class _Default : System.Web.UI.Page
{

 

protected void Page_Load(object sender, EventArgs e)
{
// pushMessage("hi", "220");

}


public void pushMessage(string pushedMessage, string pushPin)
{

string appid = "3457-B730k4394m49rOr96r33M8t74303c51k728";
string password = "smnBIWO3";

 


String BESAddress = "http://pushapi.eval.blackberry.com/mss/PD_pushRequest";
String BESWebserverListenPort = "pushPort";
String widgetNotificationUrl = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";

String pushUserName = "pushUserName";
String pushPassword = "pushPassword";
String pushPort = "pushPort ";
string Boundary = "Boundary ";
string DeliverBefore = DateTime.UtcNow.AddMinutes(5).ToString("s",

System.Globalization.CultureInfo.InvariantCulture) + "Z";
Response.Write(DeliverBefore);

bool success = true;
StringBuilder Data = new StringBuilder();
Data.AppendLine("--" + Boundary);
Data.AppendLine("Content-Type: application/xml; charset=utf-8");
Data.AppendLine("");
Data.AppendLine("<?xml version=\"1.0\"?>");
Data.AppendLine("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\">");
Data.AppendLine("<pap>");
Data.AppendLine("<push-message push-id=" + (char)34 + ID + (char)34 + " deliver-before-timestamp=" +

(char)34 + DeliverBefore + (char)34 + " source-reference=" + (char)34 + pushUserName + (char)34 + ">");
Data.AppendLine("<address address-value=\"" + pushPin + "\"/>");
Data.AppendLine("<quality-of-service delivery-method=\"unconfirmed\"/>");
Data.AppendLine("</push-message>");
Data.AppendLine("</pap>");
Data.AppendLine("--" + Boundary);
Data.AppendLine("Content-Type: text/plain");
Data.AppendLine("Push-Message-ID: " + ID);
Data.AppendLine("");
Data.AppendLine(pushedMessage);
Data.AppendLine("--" + Boundary + "--");
Data.AppendLine("");
byte[] bytes = Encoding.ASCII.GetBytes(Data.ToString());

Stream requestStream = null;
HttpWebResponse HttpWRes = null;
HttpWebRequest HttpWReq = null;

try
{
//http://<BESName>:<BESPort>/push?DESTINATTION=<PIN/EMAIL>&PORT=<PushPort>&REQUESTURI=/
// Build the URL to define our connection to the BES.
string httpURL = BESAddress + ":" + BESWebserverListenPort
+ "/push?DESTINATION=" + pushPin + "&PORT=" + pushPort
+ "&REQUESTURI=/";

//make the connection
HttpWReq = (HttpWebRequest)WebRequest.Create(httpURL);
HttpWReq.Method = ("POST");
//add the headers nessecary for the push
HttpWReq.ContentType = "text/plain";
HttpWReq.ContentLength = bytes.Length;
// ******* Test this *******
HttpWReq.Headers.Add("X-Rim-Push-Id", pushPin + "~" + DateTime.Now); //"~" +pushedMessage +
HttpWReq.Headers.Add("X-Rim-Push-Reliability", "application-preferred");
HttpWReq.Headers.Add("X-Rim-Push-NotifyURL", (widgetNotificationUrl + pushPin + "~" + pushedMessage

+ "~" + DateTime.Now).Replace(" ", ""));

// *************************

HttpWReq.Credentials = new MDSCredentials(pushUserName, pushPassword);
Console.WriteLine(pushedMessage);
requestStream = HttpWReq.GetRequestStream();
//Write the data from the source
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
//get the response
HttpWRes = (HttpWebResponse)HttpWReq.GetResponse();

//if the MDS received the push parameters correctly it will either respond with okay or accepted
if (HttpWRes.StatusCode == HttpStatusCode.OK || HttpWRes.StatusCode == HttpStatusCode.Accepted)
{
success = true;
}
else
{
success = false;
}
//Close the streams

HttpWRes.Close();
requestStream.Close();
}
catch (System.Exception e)
{
success = false;
}

return success;
}

}
}

 

 

This is My Server side coe I have used same Logic In Php it working FIne But in >net am phsing problem I am Unable to Get Notifcation On device so please check My code where i m doing wrong I have set Correct Pornt NUmber an all same Portnumber and user id and pass word when i use it php am getting NOtifcation But in C#.net am not able to Get notifcation whicle code gives Sucess response .

Please use plain text.
Contributor
sarahfarukh
Posts: 40
Registered: ‎06-25-2012
My Device: BlackBerry Curver 9300
My Carrier: Etisalat

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

I am having the exact same issue. Any luck solving it?

Please use plain text.
BlackBerry Development Advisor (Retired)
gbeukeboom
Posts: 2,559
Registered: ‎10-16-2009
My Device: BlackBerry Z10
My Carrier: Bell

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

Please use the "Insert Code" button when posting code to help it keep its formatting. 

 

Which line is throwing the error? Whatis the resulting output XML from your code?

Garett
@garettBeuk
--
Goodbye everybody!
Please use plain text.
Contributor
sarahfarukh
Posts: 40
Registered: ‎06-25-2012
My Device: BlackBerry Curver 9300
My Carrier: Etisalat

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

The return "Success" is received when debugging the server side code but the device never receives the message. The php server side code written successfully delivers the message to the device. My c# code is as below:

 

string userName = "<app ID>";
string userPW = "<password>";
public static void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
public static void SetProxy(WebRequest req)
{
Uri newUri = new Uri("PROXYURL");
WebProxy proxy = new WebProxy();
proxy.Address = newUri;
proxy.Credentials = new NetworkCredential("<portalUsername", "<portalPassword");
req.Proxy = proxy;
}
public bool pushTest(string msg)
{
HttpWebResponse HttpWRes = null;
HttpWebRequest HttpWReq = null;
string pin = "<BBpin>"; // or actual pin of device
string applicationID = "<appID>";
string BOUNDARY = "Boundary";
string msg1 = "testing c#"; // the message to send
string userName = "appID";
string userPW = "password";
string url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";
HttpWReq = (HttpWebRequest)WebRequest.Create(url);
//SetProxy(HttpWReq);
HttpWReq.Method = ("POST");
HttpWReq.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
HttpWReq.Credentials = new NetworkCredential(userName, userPW);
HttpWReq.PreAuthenticate = true;
HttpWReq.ContentType = "multipart/related; boundary=" + BOUNDARY + "; type=application/xml";
SetBasicAuthHeader(HttpWReq, userName, userPW);
StringBuilder dataToSend = new StringBuilder();
dataToSend.AppendLine("--" + BOUNDARY);
dataToSend.AppendLine("Content-Type: application/xml; charset=UTF-8");
dataToSend.AppendLine("");
dataToSend.AppendLine("<?xml version=\"1.0\"?>");
dataToSend.AppendLine("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\">");
dataToSend.AppendLine("<pap>");
string myPushId = DateTime.Now.ToFileTime().ToString();
dataToSend.AppendLine("<push-message push-id=\"" + myPushId + "\" source-reference=\"" + applicationID + "\">");
dataToSend.AppendLine("<address address-value=\"" + pin + "\"/>");
dataToSend.AppendLine("<quality-of-service delivery-method=\"unconfirmed\"/>");
dataToSend.AppendLine("</push-message>");
dataToSend.AppendLine("</pap>");
dataToSend.AppendLine("--" + BOUNDARY);
dataToSend.AppendLine("Content-Type: text/plain");
dataToSend.AppendLine("Push-Message-ID: " + myPushId);
dataToSend.AppendLine("");
dataToSend.AppendLine(msg);
dataToSend.AppendLine("--" + BOUNDARY + "--");
dataToSend.AppendLine("");
Stream requestStream = null;
string pushResult = "";
try
{
requestStream = HttpWReq.GetRequestStream();
}
catch (Exception ex)
{
pushResult = "Push failed! " + ex.ToString();
}
byte[] outStr = new ASCIIEncoding().GetBytes(dataToSend.ToString());
requestStream.Write(outStr, 0, outStr.Length);
requestStream.Close();
try
{
HttpWRes = (HttpWebResponse)HttpWReq.GetResponse();
// MessageBox.show(""+HttpWRes);

}
catch (Exception ex)
{
//push failed
}
if (HttpWRes != null)
{
HttpWRes.Close();
}
return true;
}

 I am not sure whether I am entering the correct credentials. I am struggling with this for a very long time now. Your help is much needed. Do I need to perform any other task before running the above c# code on the server? Kindly help.

Please use plain text.
BlackBerry Development Advisor (Retired)
gbeukeboom
Posts: 2,559
Registered: ‎10-16-2009
My Device: BlackBerry Z10
My Carrier: Bell

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

What is the resulting PAP message generated by this code? What response do you receive from the server?

 

What code are you running on the device? Has the device created a channel successfully? And does the PHP server code you have still send the push messages successfully to the same client?

Garett
@garettBeuk
--
Goodbye everybody!
Please use plain text.
Contributor
sarahfarukh
Posts: 40
Registered: ‎06-25-2012
My Device: BlackBerry Curver 9300
My Carrier: Etisalat

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

My php code is still delivering the push message successfully.I get the following error while running the above code:

Push failed!System.Net.WebException:Unable to connect to the remote server --->System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 68.171.224.60:80   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,SocketAddress socketAddress)   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,Socket s4,Socket s6,Socket& socket,IPAddress& address,ConnectSocketState state,IAsyncResult asyncResult,Int32 timeout,Exception& exception)---End of inner exception stack trace ---   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)   at System.Net.HttpWebRequest.GetRequestStream()

 

Please use plain text.
Contributor
sarahfarukh
Posts: 40
Registered: ‎06-25-2012
My Device: BlackBerry Curver 9300
My Carrier: Etisalat

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

The following code returns an "OK" response but Length = 'requestStream.Length' threw an exception of type 'System.NotSupportedException' is thrown at the following line:

 

try
        {
            requestStream = HttpWReq.GetRequestStream();
        }

 The complete method is as below:

 

private void Pushtest()
    {
        HttpWebResponse HttpWRes = null;
        HttpWebRequest HttpWReq = null;
        string pin = "xxxxxx"; // or actual pin of device
        string applicationID = "xxxx-xxxxxxxxxxxxxx";
        string BOUNDARY = "mPsbVQo0a68eIL3OAxnm";
        string msg = "testing c#"; // the message to send

        string userName = "xxxx-xxxxxxxxxxxxxxxxxxx";
        string userPW = "xxxxx";

        string url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest";

        HttpWReq = (HttpWebRequest)WebRequest.Create(url);
        HttpWReq.Method = ("POST");
        HttpWReq.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";

        //HttpWReq.Credentials = new NetworkCredential(userName, userPW);
        string rawCredentials = string.Format("{0}:{1}", userName, userPW);
        HttpWReq.Headers.Add("Authorization",
            string.Format(
                "Basic {0}",
                Convert.ToBase64String(Encoding.UTF8.GetBytes(rawCredentials))));

        HttpWReq.PreAuthenticate = true;
        HttpWReq.ContentType = "multipart/related; boundary=" + BOUNDARY + "; type=application/xml";
        string DeliverBefore = DateTime.UtcNow.AddMinutes(5).ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "Z";
        Response.Write(DeliverBefore);
        StringBuilder dataToSend = new StringBuilder();

        dataToSend.AppendLine("--" + BOUNDARY);
        dataToSend.AppendLine("Content-Type: application/xml; charset=UTF-8");

        dataToSend.AppendLine("");
        dataToSend.AppendLine("<?xml version=\"1.0\"?>");
        dataToSend.AppendLine("<!DOCTYPE pap PUBLIC \"-//WAPFORUM//DTD PAP 2.1//EN\" \"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\">");
        dataToSend.AppendLine("<pap>");
        string myPushId = DateTime.Now.ToFileTime().ToString();
        dataToSend.AppendLine("<push-message push-id=\"" + myPushId + "\" source-reference=\"" + applicationID + "\">");
        dataToSend.AppendLine("<address address-value=\"" + pin + "\"/>");
        dataToSend.AppendLine("<quality-of-service delivery-method=\"unconfirmed\"/>");
        dataToSend.AppendLine("</push-message>");
        dataToSend.AppendLine("</pap>");
        dataToSend.AppendLine("--" + BOUNDARY);

        dataToSend.AppendLine("Content-Type: text/plain");
        dataToSend.AppendLine("Push-Message-ID: " + myPushId);
        dataToSend.AppendLine("");

        dataToSend.AppendLine(msg);

        dataToSend.AppendLine("--" + BOUNDARY + "--");
        dataToSend.AppendLine("");

        Stream requestStream = null;
        string pushResult = "";
        try
        {
            requestStream = HttpWReq.GetRequestStream();
        }
        catch (Exception ex)
        {
            pushResult = "Push failed! " + ex.ToString();
        }
        byte[] outStr = new ASCIIEncoding().GetBytes(dataToSend.ToString());
        requestStream.Write(outStr, 0, outStr.Length);
        requestStream.Close();

        try
        {
            HttpWRes = (HttpWebResponse)HttpWReq.GetResponse();
        }
        catch (Exception ex)
        {
            //push failed
        }

        if (HttpWRes != null)
        {
            HttpWRes.Close();
        }
    }

 Please help!

Please use plain text.
BlackBerry Development Advisor (Retired)
gbeukeboom
Posts: 2,559
Registered: ‎10-16-2009
My Device: BlackBerry Z10
My Carrier: Bell

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

In your earlier post you stated that the code returned "Success", in your last post you provided the error response, could you clarify what is happening?

 

Are the C# and PHP apps being run from the same server?

 

From the error I see the IP is resolved correctly but the port is 80 when I would expect 443, using HTTPS:

68.171.224.60:80 

Do you have any proxies, firewalls or complex networking between your server and the Internet?

Garett
@garettBeuk
--
Goodbye everybody!
Please use plain text.
Contributor
sarahfarukh
Posts: 40
Registered: ‎06-25-2012
My Device: BlackBerry Curver 9300
My Carrier: Etisalat

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

I am sorry but the code contained in my first post return the error as reported. I debugged my code and noted down the error. The next post that contains the method Pushtest() returns "OK" but the message is not received. The PHP and C# code are not running on the same server. I am sorry but I do not know what the port number should be and why is it 80. Am I providing the right credentials at the right place? 

 

public static void SetProxy(WebRequest req)
    {
        Uri newUri = new Uri("http://cpadmin.pushapi.eval.blackberry.com/mss/CP_login");
        WebProxy proxy = new WebProxy();
        proxy.Address = newUri;
        proxy.Credentials = new NetworkCredential("portalUsername", "portalPassowrd");

        req.Proxy = proxy;
    }

 

Please use plain text.
BlackBerry Development Advisor (Retired)
gbeukeboom
Posts: 2,559
Registered: ‎10-16-2009
My Device: BlackBerry Z10
My Carrier: Bell

Re: How Send Push Notifcation Using C#.Net Code In Blackberry

The admin portal is not a proxy and has no involvement in sending a push.

 

If the credentials used in the app were incorrect then you should receive an HTTP 403 response, but your app is failing before it can even establish the connection making this seem like more of a network/environment issue.

 

Are there any network differences between the server running the PHP code and the server running the C# code?

Garett
@garettBeuk
--
Goodbye everybody!
Please use plain text.