how to send message(text,image,videos) to whatsapp from C# Asp.net Application.
Sending bulk messages programmatically through WhatsApp is definitively against their Terms of Service, and even the author of the (third-party) API posted by andrey.shedko doesn't maintain it or accept any responsibility for it. There's a function within the app to send as many messages as you want to the people you actually know - use that instead.
Within their Legal section:
(iii) you will not attempt to reverse engineer, alter or modify any part of the Service
and
C. You agree not to use or launch any automated system, including without limitation, "robots," "spiders," "offline readers," etc. or "load testers" such as wget, apache bench, mswebstress, httpload, blitz, Xcode Automator, Android Monkey, etc., that accesses the Service in a manner that sends more request messages to the WhatsApp servers in a given period of time than a human can reasonably produce in the same period by using a WhatsApp application
They do not provide a public API, so there's no wiggle room here.
i find perfect solution on This Link.
Following code (C#) I used for sending message-
//Send ( button_click )
string from = "9199********";
string to = txtTo.Text;//Sender Mobile
string msg = txtMessage.Text;
WhatsApp wa = new WhatsApp(from, "BnXk*******B0=", "NickName", true, true);
wa.OnConnectSuccess += () =>
{
MessageBox.Show("Connected to whatsapp...");
wa.OnLoginSuccess += (phoneNumber, data) =>
{
wa.SendMessage(to, msg);
MessageBox.Show("Message Sent...");
};
wa.OnLoginFailed += (data) =>
{
MessageBox.Show("Login Failed : {0}", data);
};
wa.Login();
};
wa.OnConnectFailed += (ex) =>
{
MessageBox.Show("Connection Failed...");
};
wa.Connect();
Related
I am currently working on a C# Windows Form project that requires the user to pay prior to any processing taking place. I am using the Square .Net SDK for payment processing and have successfully managed to get a payment through to the sandbox environment using the Checkout URL generated by the Checkout API. My question is whether there is a simple way to get whether the payment process has been completed. Right now, I am just polling the API with the same order (with identical idempotency keys) and waiting for it to return an error that the order is no longer valid. Here is the backbone of my current code:
var bodyOrderLineItems = new List<CreateOrderRequestLineItem>();
long totalCost = 100;
var charge0 = new Money.Builder().Amount(totalCost).Currency("USD").Build();
bodyOrderLineItems.Add(new CreateOrderRequestLineItem.Builder("1").Name("Incredibly Valuable Product").BasePriceMoney(charge0).Build());
var order = new CreateOrderRequest.Builder()
.ReferenceId("reference_id")
.LineItems(bodyOrderLineItems)
.Build();
var body = new CreateCheckoutRequest.Builder("Test_iKey4", order)
.AskForShippingAddress(false)
.Build();
var checkoutApi = client.CheckoutApi;
try
{
CreateCheckoutResponse result = checkoutApi.CreateCheckout(locationsString, body);
System.Diagnostics.Process.Start(result.Checkout.CheckoutPageUrl);
while (true)
{
System.Threading.Thread.Sleep(5000);
//while payment hasn't gone through
try
{
result = checkoutApi.CreateCheckout(locationsString, body);
}
catch (ApiException e)
{
MessageBox.Show(e.Errors[0].Detail);
break;
}
}
MessageBox.Show("Payment Must Have Gone Through");
}
catch (ApiException e) { MessageBox.Show(e.Errors[0].Detail); };
Is this a valid approach? While this does seem to work, I feel like I am flooding the api with requests. I am pretty inexperienced with the Square API, so any help would be appreciated.
Typically the Checkout API is used within a website, as it includes a parameter redirect_url so that when the payment is complete, the user is redirected back to your side and it includes url parameters such as the transaction id. If you don't have a website, you can instead sign up for webhooks. The PAYMENT_UPDATED webhook will be sent out when a payment has been processed, so you do not need to do polling; just listen for the webhook.
I have an Xamarin.iOS application that is connecting an Azure backend service and I want my service to send notifications to the client applications.
The Microsoft documentation explains how to set up the Notification Hub for different scenario. I think I am getting most of it, however I am not sure I understood the very first part, which is for the iOS application to Retrieve PNS Handle from the Platform Notification Service, as shown in the following picture:
It looks like this is some task that must be performed by the client application alone and then communicate this to the backend service for the registration.
I have a feeling that it happens at the 10th step of this section, when iOS calls the application back on the method RegisteredForRemoteNotifications. In that callback, the application is given a deviceToken:
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
Hub.UnregisterAllAsync (deviceToken, (error) => {
if (error != null)
{
System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
return;
}
NSSet tags = null; // create tags if you want
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) => {
if (errorCallback != null)
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
});
}
Question
Is that deviceToken the PNS Handle that I need to send to the backend service to start the registration process? If not, how am I supposed to contact the PNS to get the Handle?
The information is in the documentation but not in an obvious form for a C# developer.
In Objective-C, the deviceToken is provided by the iOS application, as mentioned by #LucasZ, after it got registered against the PNS.
However I can't just send this deviceToken right away as it will not be accepted by the AppleRegistrationDescription class used in my Service.
It took me a while to get more familiar with Objective-C to figure out that this token was actually transformed before being sent to Azure:
NSSet* tagsSet = tags?tags:[[NSSet alloc] init];
NSString *deviceTokenString = [[token description]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
deviceTokenString = [[deviceTokenString stringByReplacingOccurrencesOfString:#" " withString:#""] uppercaseString];
I have implemented something similar in C#:
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
string pnsHandle = deviceToken.Description
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace(" ", string.Empty)
.ToUpper();
Hub = new SBNotificationHub(Constants.ListenConnectionString, Constants.NotificationHubName);
Hub.UnregisterAllAsync (pnsHandle, (error) =>
{
if (error != null)
{
System.Diagnostics.Debug.WriteLine("Error calling Unregister: {0}", error.ToString());
return;
}
// In my use case, the tags are assigned by the server based on privileges.
NSSet tags = null;
Hub.RegisterNativeAsync(pnsHandle, tags, (errorCallback) =>
{
if (errorCallback != null)
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
});
}
To answer my question, yes, the deviceToken is the PNS Handle but it must be formatted.
The method RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) is to tell the delegate that the app successfully registered with the Push Notification service.
The parameter ‘deviceToken’ is a globally unique token that identifies this device to the Push Notification service.
NSSet tags = null; // create tags if you want
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) =>
{
if (errorCallback != null)
System.Diagnostics.Debug.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
Because you are using Azure, the Hub has send the token to the generate remote notifications in above method. So if you only want to push some thing to all users, you don't need to do something else. If you want to push to specific users, you can register a tag and use it as parameter.
I've got a few devices that interact with an Express app on a local server. For the purposes of a prototype demo I'm trying to make this as simple as possible. Among many other things, my local server interacts with images, and image data in the /uploads folder thusly:
(Express/NodeJS code):
app.route('/uploads')
//Send File to Android
.get( function (req, res) {
var images = fs.readdirSync('./uploads');
console.log(images[images.length-1]);
var imgpath = path.resolve('./uploads/' + images[images.length-1]);
res.sendFile(imgpath);
//res.end('Image List Sent')
})
//Receive image chip data from Android
.post( function (req, res) {
Console.log("insideit");
Console.log(req.body);
res.end('got something?')
});
This server code is receiving requests from C# Android code. The GET command works perfectly, so I will omit that Xamarin/C# code. The POST command from the android app is thus (In C#/Xamarin):
var rxcui = "198840";
string _url = string.Format(#"http://10.1.10.194:3000/uploads", rxcui);
string datastr = "test";
try
{
(new WebClient()).UploadString(_url, datastr);
}
catch
{
Console.WriteLine("Post Upload Error");
}
}
The server sees the post request, but returns 500. It appears that it's not routing properly, because It won't go into my post handling code and print a simple test string. Any thoughts on why the POST command is not being handled appropriately?
Try to replace res.end with res.send(). Something like this
.post( function (req, res) {
Console.log("insideit");
Console.log(req.body);
res.send('got something?');
});
This should work.
i can not send message to specific user by connectionId when I try to send all users like this: context.Clients.All.updateMessages(message) - this code is working.
hare is Hub code:
public void Send(string userToId, string userForId, string message)
{
//Get Recipent (userIdfor) connectionId
var signalrhelper = new HomeController();
string userForconnectionId = signalrhelper.GetConnecionIdByUserId(userForId);
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHubs>();
string messageSenderConnId= signalrhelper.GetConnecionIdByUserId(userToId);
//Call Receiver
context.Clients.Client(userForconnectionId).updateMessages(message);
//Call Sender
context.Clients.Client(messageSenderConnId).updateMessages(message);
}
Hare is My View:
$(function() {
// Declare a proxy to reference the hub.
var notifications = $.connection.chatHubs;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function(data) {
if (window.location.href.indexOf("Messages/DetailMessage?userId") > -1) {
$('#timeline-messages').append('{0}'.Stringformat(data));
} else {
ReplaceUpdateTargetIdToReturnData("Messages/GetMessages", "#header_inbox_bar", "#systemMessage");
}
};
$.connection.hub.start().done(function() {
var myClientId = $.connection.hub.id;
GetConnectionIdToSignalR("Home", "SaveConnectionIdbyUserName", "userId", #Session["UserId"], "hubConnectionId", myClientId);
$('#sendMessageButton').click(function() {
if ($('#sendMessageFiled').val().length > 1) {
// Call the Send method on the hub.
notifications.server.send(#Session["UserId"], myClientId, $('#sendMessageButton').attr("title"), $('#sendMessageFiled').val());
// Clear text box and reset focus for next comment.
$('#sendMessageFiled').val('').focus();
} else {
$('#sendMessageFiled').focus();
}
});
}).fail(function (e) {
alert(e);
});
});
Can anybody Know what's happen ?
By user, I assume you mean an authenticated user? If that is the case, you have to map connections to users first. For instance, a user can have 2 or more signalr connections. So the first step is mapping users to connections, then you can send a message to the user and all his/her connected agents will receive it.
There are several ways to map connections to users, the guide is here: http://www.google.co.uk/url?q=http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections&sa=U&ei=Tjj-VJuPMsPBOZGGgYgH&ved=0CAsQFjAA&usg=AFQjCNFXoGJOm3mzenAJbz46TUq-Lx2bvA
Although this post is already old: I had a similar issue yesterday and it took me hours! I had the connectionIds but no client received a notification. Context.Clients.All.aMethod(...) worked fine, but Context.Clients.Client(theid).aMethod(...) did not work. I finally realized that I stored the connection-ids in the database as an uniqueIdentifier and MS SQL converted the uniqueIdentifier values to uppercase and therefore the connectionids were not valid any more. I converted the connectinIds to lowercase before publishing to my connected clients and then it worked...maybe you experience a similar problem. But your post with an invalid connectionid because of blanks helped my finding the problem.
For my app, I'm using a webview. I have implemented the notifications by following this tutorial :
http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1
In my website I use a js code that check new event added in the db:
function checkNotification()
{
$.ajax({
url: '/checkNewMessages',
type: "GET",
success: function (result)
{
// if new event, then I run the #c code below to tell
// the APN server to send the notif to the device.
}
});
}
To send the notifications I'm using a #c code:
var deviceToken = "2191a536a52445046797a871fe3c4cf...";
var message = "this is a notification.";
var badge = 1;
var password = "blablabla";
var payload = new NotificationPayload(deviceToken, message, badge);
var notificationList = new List<NotificationPayload>() { payload };
var push = new PushNotification(true, "apn_developer_identity.p12", password);
var result = push.SendToApple(notificationList);
And I check this every 10000 milisec
setInterval(checkNotification, 10000);
But this js code will be running only when the user is on the app. What's happen when the app is not running ? The user won't be able to receive the notifications ? I need a script always running in background checking new event on my db. What is the best way to do this ? Thanks for your help.
Push notification are handled by iOS not your app, thus when your server send a push notification to an users app they will just receive it.
Only when you the user opens the app using the notification is it possible to detect the notification used to open the app. You check for the notification used to open the on the
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSDictionary *remoteNotif =[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (remoteNotif) {
/* handle the notification.
}
}
There is not way to monitor push notification in the background.