Notification message sent thru pinpoint does not reach the Mobile - android-push-notification

Based on the link I tried tried working and here is the code I tried out
public static void SendNotification2(String appid, String pinpointEndpointId){
try {
GetEndpointRequest getEndpointRequest = new GetEndpointRequest()
.withApplicationId(appid)
.withEndpointId(pinpointEndpointId);
AmazonPinpoint pinpoint = AmazonPinpointClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
GetEndpointResult endpointResult = pinpoint.getEndpoint(getEndpointRequest);
EndpointResponse endpointResponse = endpointResult.getEndpointResponse();
Map<String, String> data = new HashMap<String, String>();
data.put("message", "test");
DirectMessageConfiguration directMessageConfiguration =
new DirectMessageConfiguration().withGCMMessage(new GCMMessage().withData(data).withSilentPush(true));
AddressConfiguration addressConfiguration = new AddressConfiguration().withChannelType(ChannelType.GCM);
MessageRequest messageRequest = new MessageRequest().withMessageConfiguration(directMessageConfiguration)
.addAddressesEntry(endpointResponse.getAddress(), addressConfiguration);
SendMessagesRequest sendMessagesRequest = new SendMessagesRequest()
.withApplicationId(appid)
.withMessageRequest(messageRequest);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code executes successfully without any error/exception but i do not see the notification.
However when i post the message from "Direct Messaging" section of pinpoint with the Endpoint Id I am able to see the notification in mobile.
Also using Amazon CLI the Notification message is delivered:
aws --region="us-east-1" pinpoint send-messages --application-id 1fd19ca6fa944a79bdd91beddb4b4f7e --message-request "{\"Context\":{},\"MessageConfiguration\":{\"DefaultMessage\":{\"Body\":\"Test from default message\",\"Substitutions\":{}},\"DefaultPushNotificationMessage\":{},\"APNSMessage\":{},\"GCMMessage\":{\"Data\":{\"message\":\"test\"},\"SilentPush\":true},\"BaiduMessage\":{},\"ADMMessage\":{},\"SMSMessage\":{}},\"Addresses\":{\"cltaa5owuOU:APA91bFOBUB5YRi_Ac6teNmuu19aoFDAByOeoVbqLmY1Yp6cZEp_aueunDU1ZPB6H50GKBfuxu300z-El_sEjxo72crYKnklI-wboxXDk180JICrif0c7R-fR4xFOm5WsQOGUJZPFLG6\":{\"ChannelType\":\"GCM\"}},\"Endpoints\":{}}
Any help will be appreciated.
Thanks

Related

Xamarin.Forms Consume Rest Service

I'm new to Xamarin and developing native apps in general (I have made html5 apps in the past).
I have started on a Xamarin.Forms project and I'm trying to contact a REST like API (need to GET an URL which will return a json array).
Normally from C# I would use RestSharp and perform this call using the RestClient.
I'm not having any luck installing that package from Xamarin Studio though, but I have got the Microsoft HTTP Libraries installed.
I'm pretty sure this is a very trivial task to perform, I just haven't been able to adapt the samples I have found online to work for me.
Anyone who could post how this is done please (remember I'm new to this so don't expect me to understand everything that is different from say a normal console app)?
It is easy with HTTP Client and JSON.NET here is a example of a GET:
public async Task<List<Appointment>> GetDayAppointments(DateTime day)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
//Your url.
string resourceUri = ApiBaseAddress;
HttpResponseMessage result = await client.GetAsync (resourceUri, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try {
return GetDayAppointmentsList(result);
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
} else {
if(TokenExpired(result)){
App.SessionExpired = true;
App.ShowLogin();
}
return null;
}
return null;
}
private List<Appointment> GetDayAppointmentsList(HttpResponseMessage result){
string content = result.Content.ReadAsStringAsync ().Result;
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["citas"];
List<Appointment> AppoinmentsList = new List<Appointment> ();
foreach (var jObj in jarray) {
Appointment newApt = new Appointment ();
newApt.Guid = (int)jObj ["id"];
newApt.PatientId = (string)jObj ["paciente"];
newApt.Name = (string)jObj ["nombre"];
newApt.FatherLstName = (string)jObj ["paterno"];
newApt.MotherLstName = (string)jObj ["materno"];
string strStart = (string)jObj ["horaIni"];
TimeSpan start;
TimeSpan.TryParse (strStart, out start);
newApt.StartDate = start;
string strEnd = (string)jObj ["horaFin"];
TimeSpan end;
TimeSpan.TryParse (strEnd, out end);
newApt.EndDate = end;
AppoinmentsList.Add (newApt);
}
return AppoinmentsList;
}
I use System.Net.WebClient and our asp.net WebAPI interface:
public string GetData(Uri uri)
{//uri like "https://webapi.main.cz/api/root"
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
//You can set webClient.Headers there
webClient.Encoding = System.Text.Encoding.UTF8;
ret = webClient.DownloadString(uri));//Test some data received
//In ret you can have JSON string
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
4
public string SendData(Uri uri, byte[] data)
{//uri like https://webapi.main.cz/api/PostCheckLicence/
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.Accept] = "application/octet-stream";
webClient.Headers[HttpRequestHeader.ContentType] = "text/bytes";
webClient.Encoding = System.Text.Encoding.ASCII;
byte[] result = webClient.UploadData(uri, data);
ret = Encoding.ASCII.GetString(result);
if (ret.Contains("\"ResultWebApi\":\"OK"))
{//In ret you can have JSON string
}
else
{
}
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
x
I've some examples in my Github repo. Just grab the classes there and give them a try. The API is really easy to use:
await new Request<T>()
.SetHttpMethod(HttpMethod.[Post|Put|Get|Delete].Method) //Obligatory
.SetEndpoint("http://www.yourserver.com/profilepic/") //Obligatory
.SetJsonPayload(someJsonObject) //Optional if you're using Get or Delete, Obligatory if you're using Put or Post
.OnSuccess((serverResponse) => {
//Optional action triggered when you have a succesful 200 response from the server
//serverResponse is of type T
})
.OnNoInternetConnection(() =>
{
// Optional action triggered when you try to make a request without internet connetion
})
.OnRequestStarted(() =>
{
// Optional action triggered always as soon as we start making the request i.e. very useful when
// We want to start an UI related action such as showing a ProgressBar or a Spinner.
})
.OnRequestCompleted(() =>
{
// Optional action triggered always when a request finishes, no matter if it finished successufully or
// It failed. It's useful for when you need to finish some UI related action such as hiding a ProgressBar or
// a Spinner.
})
.OnError((exception) =>
{
// Optional action triggered always when something went wrong it can be caused by a server-side error, for
// example a internal server error or for something in the callbacks, for example a NullPointerException.
})
.OnHttpError((httpErrorStatus) =>
{
// Optional action triggered when something when sending a request, for example, the server returned a internal
// server error, a bad request error, an unauthorize error, etc. The httpErrorStatus variable is the error code.
})
.OnBadRequest(() =>
{
// Optional action triggered when the server returned a bad request error.
})
.OnUnauthorize(() =>
{
// Optional action triggered when the server returned an unauthorize error.
})
.OnInternalServerError(() =>
{
// Optional action triggered when the server returned an internal server error.
})
//AND THERE'S A LOT MORE OF CALLBACKS THAT YOU CAN HOOK OF, CHECK THE REQUEST CLASS TO MORE INFO.
.Start();
And there's a couple of examples.
For all my Xamarin Forms app I use Tiny.RestClient.
It's easy to get it and easy to use it.
You have to download this nuget.
And after it just very easy to use it :
var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
var cities = client.
GetRequest("City").
AddQueryParameter("id", 2).
AddQueryParameter("country", "France").
ExecuteAsync<City>> ();
Hopes that helps.

Using Smack: login("foo", "bar") gives "Not connected to server" exception

I´m so sorry about this noob question, in my application I use a button to send a friend request, the other person accept it and it works fine, my problem is, when I want to delete a contact I got FATAL EXCEPTION: main java.lang.IllegalStateException: Not connected to server.
The error is in this line
connection.login("113", "AA");
This is my code, I dont have any idea if this code works :(, can someone help me please?
ConnectionConfiguration connConfig = new ConnectionConfiguration(
"xxx.xxx.x.xx", 5222, "xxx.xxx.x.xx");
XMPPConnection connection = new XMPPConnection(connConfig);
SharedPreferences phoneNo3 = this.getSharedPreferences("phonef", MODE_PRIVATE);
String username = phoneNo3.getString("phonef", "");
SharedPreferences conts = this.getSharedPreferences("contrass", MODE_PRIVATE);
String passwords = conts.getString("contrass", "");
try {
connection.login("113", "AA");
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
RosterPacket.Item item = new RosterPacket.Item("laboral#xxx.xxx.x.xx", null);
item.setItemType(RosterPacket.ItemType.remove);
packet.addRosterItem(item);
connection.sendPacket(packet);
} catch (XMPPException ex) {
Log.e("XMPPClient", "[SettingsDialog] Failed to log in as " + username);
connection.disconnect();
}
You need to call connect() before login(String, String).

Getting the relevant error message using .net SDK

I'm using Facebook ads api SDK for .net (http://www.nuget.org/packages/Facebook/6.4.2) and when I catch an error, the message is always the same general error in the exception message object:
(FacebookApiException - #100) Invalid parameter
It happens since I moved to the versioned calls (v2.2) - before that I used the unversioned calls and it was fine. For example, this is how I get the error (using regular try catch in c#):
try
{
FacebookClient facebookClient = new FacebookClient();
facebookClient.AccessToken = "<YOUR_ACCESS_TOKEN>"
Dictionary<string, object> parameters = new Dictionary<string, object>();
string name = Guid.NewGuid().ToString();
parameters.Add("name", name);
parameters.Add("conversion_specs", "");
parameters.Add("campaign_id", "6024570447800");
parameters.Add("creative", "{\"creative_id\":\"6024570452200\"}");
parameters.Add("redownload", "false");
parameters.Add("tracking_specs", "");
parameters.Add("view_tags", "[]");
var result = facebookClient.Post("v2.2/act_107893676040337/adgroups", parameters) as IDictionary<string, object>;
}
catch (Exception ex)
{
FacebookApiException fbEx = ex as FacebookApiException;
string errorMsg = fbEx.Message;
}
It happens because Facebook changed the return error object and added 2 new fields: error_user_title, error_user_msg.
Is there a way to access these fields in the FacebookApiException object ?
How can I extract the relevant error message?
I dived into this issue and it's not a Facebook problem. The problem is in the third party SDK.
I contacted the development team, they aware of this issue and fixed it in the last beta version.

java api to get a file content for enterprise github

I tried so hard for a simple line of code that read a file content from enterprise github with oauth token, but could not find a example of such.
I tried https://github.com/jcabi/jcabi-github, but it does not support enterprise github?(maybe I am wrong)
Now i am trying egit:
GitHubClient client = new GitHubClient("enterprise url");
GitHubRequest request = new GitHubRequest();
request.setUri("/readme");
GitHubResponse response = client.get(request);
Then what? I only saw a getBody, maybe I need to parse it with some kinda json library? It has to be simpler..I am expecting something like: repo.get(url).getContent()
Finally figure out by reading source code..
GitHubClient client = new GitHubClient(YOURENTERPRICEURL);
client.setOAuth2Token(token);
// first use token service
RepositoryService repoService = new RepositoryService(client);
try {
Repository repo = repoService.getRepository(USER, REPONAME);
// now contents service
ContentsService contentService = new ContentsService(client);
List<RepositoryContents> test = contentService.getContents(repo, YOURFILENAME);
List<RepositoryContents> contentList = contentService.getContents(repo);
for(RepositoryContents content : test){
String fileConent = content.getContent();
String valueDecoded= new String(Base64.decodeBase64(fileConent.getBytes() ));
System.out.println(valueDecoded);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

I am trying to update status to twitter using twitter4j but it does not work

I succeeded to get every credentials(Oauth_token,Oauth_verifier).
With it, I tried to post a text to twitter account, but it always fail with error message "No authentication challenges found"
I found some solution like
"Check the time zone automatically",
"import latest twitter4j library" etc..
but after check it, still not work.
Is there anyone can show me the way.
code is like below
public static void updateStatus(final String pOauth_token,final String pOauth_verifier) {
new Thread() {
public void run() {
Looper.prepare();
try {
TwitterFactory factory = new TwitterFactory();
AccessToken accessToken = new AccessToken(pOauth_token,pOauth_verifier);
Twitter twitter = factory.getInstance();
twitter.setOAuthConsumer(Cdef.consumerKey, Cdef.consumerSecret);
twitter.setOAuthAccessToken(accessToken);
if (twitter.getAuthorization().isEnabled()) {
Log.e("btnTwSend","인증값을 셋팅하였고 API를 호출합니다.");
Status status = twitter.updateStatus(Cdef.sendText + " #" + String.valueOf(System.currentTimeMillis()));
Log.e("btnTwSend","status:" + status.getText());
}
} catch (Exception e) {
Log.e("btnTwSend",e.toString());
}
};
}.start();
}
"No authentication challenges found"
I think you are missing Access token secret in your code. That is why you are getting this exception.
Try following :
ConfigurationBuilder configurationBuilder;
Configuration configuration;
// Set the proper configuration parameters
configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
configurationBuilder
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access token
configurationBuilder.setOAuthAccessToken(ACCESS_TOKEN);
// Access token secret
configurationBuilder
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
// Get the configuration object based on the params
configuration = configurationBuilder.build();
// Pass it to twitter factory to get the proprt twitter instance.
twitterFactory = new TwitterFactory(configuration);
twitter = twitterFactory.getInstance();
// use this instance to update
twitter.updateStatus("Your status");
I finally found the reason.
I thought parameter named 'oauth_token' , 'oauth_verifier' is member of accesstoken,
but it was not true.
I just had to pass one more way to get correct key.
and this way needs 'oauth_token' , 'oauth_verifier' to get accesstoken.
This code must add one more code below:
mAccessToken = mTwitter.getOAuthAccessToken(REQUEST_TOKEN,OAUTH_VERIFIER);