Is there any way to message on whatsapp without opening the application - whatsapp

I've been searching for the solution to send the message on whatsapp from the Application or via REST-APIs without opening it.
As I have mentioned below the code will validate for the Whatsapp-type installed in device and then it will send it to user but in this case it launch the whatsapp.
private void launchWhatsapp(String msg) {
try {
boolean installed2 = obj.appInstalledOrNot("com.whatsapp.w4b");
if (installed2) try {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setPackage("com.whatsapp.w4b");
String url = "https://api.whatsapp.com/send?" +
"phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
"&text=" + msg;
sendIntent.setData(Uri.parse(url));
if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
startActivityForResult(sendIntent, 104);
}
} catch (Exception e) {
e.printStackTrace();
}
else {
boolean installed = obj.appInstalledOrNot("com.whatsapp");
if (installed) {
Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.setAction(Intent.ACTION_VIEW);
sendIntent.setPackage("com.whatsapp");
String url = "https://api.whatsapp.com/send?" +
"phone=" + PhoneNumberUtils.stripSeparators(Cust_Phone_Code + " " + getIntent().getStringExtra("Cust_Mob")) +
"&text=" + msg;
sendIntent.setData(Uri.parse(url));
if (sendIntent.resolveActivity(this.getPackageManager()) != null) {
startActivityForResult(sendIntent, 104);
}
} else {
Toast.makeText(InvoiceReport.this, "Whatsapp not available", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
//Log.e("Error", "ERROR_OPEN_MESSANGER"+e.toString());
}
}
I am expecting if anyone click on the browser on send message then this redirect to whatsapp application.

Related

Using Dispatcher with thread

I have a list of rtf strings that are needed to convert to html. I am using a richtextbox control to convert rtf to html. My problem is this
The solution should also work but how do i implement this solution in my code?
public string ConvertRtfToHtml(string rtfText)
{
try
{
var thread = new Thread(ConvertRtfInSTAThread);
var threadData = new ConvertRtfThreadData { RtfText = rtfText };
thread.SetApartmentState(ApartmentState.STA);
thread.Start(threadData);
try
{
thread.Join();
}
catch(ThreadStateException e){
logger.Error("ThreadStateException " + e.Message);
}
catch (ThreadInterruptedException e) {
logger.Error("ThreadInterruptedException " + e.Message);
}
return threadData.HtmlText;
}
catch (Exception e){
logger.Error("ConvertRtfToHtml: " + e.InnerException.Message);
return "Error";
}
}
private void ConvertRtfInSTAThread(object rtf)
{
MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter();
var threadData = rtf as ConvertRtfThreadData;
try
{
threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
}
catch(Exception e){
logger.Error("ConvertRtfInSTAThread: " + e.Message);
}
}
this markupconverter.convertrtftohtml uses richtextbox control.
Where do i fit the Dispatcher in above code?
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
Dispatcher.Run();
I used it as follows
private void ConvertRtfInSTAThread(object rtf)
{
MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter();
var threadData = rtf as ConvertRtfThreadData;
try
{
threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText);
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
Dispatcher.Run();
}
catch(Exception e){
logger.Error("ConvertRtfInSTAThread: " + e.Message);
}
}

Renci.SshNet : "server response does not contain ssh protocol identification"

I'm working with the Renci SSH.Net library on a WPF application and I'm having an issue with using the SFTP client. When the user tries to connect to download some files from the SFTP server he gets the message shown below:
Server response does not contain ssh protocol identification
It doesn't appear to be something specific with the server as I'm able to connect and download the files just fine on my development desktop and a secondary laptop. The same application is able to connect over SSH and run commands without issue, it's just the SFTP connection that appears to be the problem. I'm looking for a little guidance as to where to begin troubleshooting this.
Code for SFTP shown below:
void DownloadPlogs()
{
try
{
SftpClient SFTP;
if (GV.UseCustomPort && GV.CustomPort > 0 && GV.CustomPort < 65535)
{
SFTP = new SftpClient(GV.IpAddress, GV.CustomPort, GV.Username, GV.Password);
}
else
{
SFTP = new SftpClient(GV.IpAddress, 22, GV.Username, "");
}
SFTP.Connect();
DownloadDirectory(SFTP, "/PLOG", Directory.GetCurrentDirectory() + #"\PLOG");
ZipFile.CreateFromDirectory("PLOG", String.Format("{0} - {1} PLOGS.zip", GV.IpAddress, DateTime.Now.ToString("yyyyMMddHHmmss")));
Directory.Delete(Directory.GetCurrentDirectory() + #"\PLOG", true);
SFTP.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Getting PLOGS");
}
}
void DownloadDirectory(SftpClient Client, string Source, string Destination)
{
var Files = Client.ListDirectory(Source);
foreach (var File in Files)
{
if (!File.IsDirectory && !File.IsSymbolicLink)
{
DownloadFile(Client, File, Destination);
}
else if (File.IsSymbolicLink)
{
//Ignore
}
else if (File.Name != "." && File.Name != "..")
{
var Dir = Directory.CreateDirectory(System.IO.Path.Combine(Destination, File.Name));
DownloadDirectory(Client, File.FullName, Dir.FullName);
}
}
}
void DownloadFile(SftpClient Client, Renci.SshNet.Sftp.SftpFile File, string Directory)
{
using (Stream FileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(Directory, File.Name)))
{
Client.DownloadFile(File.FullName, FileStream);
}
}
Code for SSH below:
public SshConnection(string Host, int Port, string Username, string Password)
{
myClient = new SshClient(Host, Port, Username, Password);
myClient.KeepAliveInterval = new TimeSpan(0, 0, 5);
myClient.HostKeyReceived += myClient_HostKeyReceived;
myClient.ErrorOccurred += myClient_ErrorOccurred;
}
void myClient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message, "SSH Error Occurred");
}
void myClient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
{
e.CanTrust = true;
}
public async void Connect()
{
Task T = new Task(() =>
{
try
{
myClient.Connect();
}
catch (System.Net.Sockets.SocketException)
{
MessageBox.Show("Invalid IP Address or Hostname", "SSH Connection Error");
}
catch (Renci.SshNet.Common.SshAuthenticationException ex)
{
MessageBox.Show(ex.Message, "SSH Authentication Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
MessageBox.Show(ex.GetType().ToString());
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
});
T.Start();
await T;
if (T.IsCompleted)
{
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
}
public void Disconnect()
{
try
{
myClient.Disconnect();
OnConnection(this, new ConnectEventArgs(myClient.IsConnected));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
public void SendData(string Data)
{
try
{
if (Data.EndsWith("\r\n"))
{
RunCommandAsync(Data, SshCommandRx);
}
else
{
RunCommandAsync(String.Format("{0}\r\n",Data), SshCommandRx);
}
//SshCommand Command = myClient.RunCommand(Data);
//OnDataReceived(this, new DataEventArgs(Command.Result));
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
private async void RunCommandAsync(String Data, SshCommandCallback Callback)
{
Task<SshCommand> T = new Task<SshCommand>(() =>
{
try
{
SshCommand Command = myClient.RunCommand(Data);
return Command;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
return null;
}
});
T.Start();
await T;
if (T.IsCompleted)
{
Callback(this, T.Result);
}
}
private void SshCommandRx(SshConnection C, SshCommand Command)
{
if (Command != null)
{
string Rx = Command.Result;
//if (Rx.StartsWith(Command.CommandText))
//{
// Rx = Rx.Remove(0, Command.CommandText.Length);
//}
while (Rx.EndsWith("\r\n\r\n") == false)
{
Rx += "\r\n";
}
OnDataReceived(this, new DataEventArgs(Rx));
}
}
I solve it for my self only with connections retrying attempts. Didn't find what exactly the issue is, but have this connection issue many times.
Example:
int attempts = 0;
do
{
try
{
client.Connect();
}
catch (Renci.SshNet.Common.SshConnectionException e)
{
attempts++;
}
} while (attempts < _connectiontRetryAttempts && !client.IsConnected);
I experienced the same odd error message when attempting to connect to a SFTP server while using the SSH.NET library in a program on the server. The problem did not appear while testing from my development machine.
The solution was to have our server team add the IP address of the server into the hosts.allow file on the SFTP Linux server.

SMACK API In Band registration fails with forbidden error

I am using SMACK API's AccountManager class but failed to successfully create a new account. supportsAccountCreation() returns true.
The createAccount method fails with the following error.
D/SMACK: SENT (0): <iq to='xmpp.jp' id='e740L-48' type='set'><query xmlns='jabber:iq:register'><username>MY_NEW_USER</username><password>**********************</password></query></iq>
D/SMACK: RECV (0): <iq from='xmpp.jp' id='e740L-48' type='error'><query xmlns='jabber:iq:register'><username>MY_NEW_USER</username><password>*****************</password></query><error code='403' type='auth'><forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
W/System.err: org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: forbidden - auth
W/System.err: at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232)
W/System.err: at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:213)
W/System.err: at org.jivesoftware.smackx.iqregister.AccountManager.createAccount(AccountManager.java:272)
W/System.err: at org.jivesoftware.smackx.iqregister.AccountManager.createAccount(AccountManager.java:244)
..
D/SMACK: SENT (0): <auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='SCRAM-SHA-1'>*****************************************</auth>
D/SMACK: RECV (0): <failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><not-authorized/></failure>
UPDATE: Code added here
API v4.1.5
private void initialiseConnection() {
Log.d("xmpp", "Initialising connection");
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(getServer());
config.setHost(getServer());
config.setPort(getPort());
config.setDebuggerEnabled(true);
config.setSendPresence(true);
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
connection.addConnectionListener(new XMPPConnectionStateHandler(this));
connection.addConnectionListener(new XMPPAccountLoginHandler(this));
connection.addConnectionListener(new XMPPOfflineMessageHandler(this));
connection.addConnectionListener(new XMPPPingMessageHandler(this));
connection.addConnectionListener(new XMPPReconnectionHandler(this));
connection.addConnectionListener(new XMPPPresenceHandler(this));
connection.addConnectionListener(new XMPPDeliveryReceiptHandler(this));
}
public void connect(final String caller) {
if (ConnectionManagerHelper.hasDataConnection(context)){
Log.d(TAG, "Data connection fine");
} else {
Log.d(TAG, "Data connection not avaiable");
}
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected()) return false;
isconnecting = true;
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
connected = true;
notifyConnectionEstablishedEvent();
} catch (IOException e) {
Log.e(TAG, "(" + caller + ")" + " IOException: " + e.getMessage());
notifyConnectionFailureEvent();
} catch (final SmackException e) {
Log.e(TAG, "(" + caller + ")" + " SMACKException: " + e.getMessage());
notifyConnectionFailureEvent();
} catch (final XMPPException e) {
Log.e(TAG, "(" + caller + ")" + " XMPPException: " + e.getMessage());
notifyConnectionFailureEvent();
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login() {
try {
connection.addAsyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
Log.d(TAG, packet.toXML().toString());
notifyMessageStatusReceivedEvent(packet);
}
}, new StanzaFilter() {
#Override
public boolean accept(Stanza stanza) {
return true;
}
});
Log.d(TAG, "Attempting to login as " + loginUser);
connection.login(loginUser, passwordUser);
notifyConnectionConnectedEvent();
} catch (SmackException.AlreadyLoggedInException e){
Log.d(TAG, "Already logged on to chat server");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
//if first login failed, try to create an account and then login
Log.d(TAG, "Login failed. Trying to create a new account.");
register();
}
}
public void register(){
Log.d(TAG, "Attempting to register");
try {
AccountManager accountManager = AccountManager.getInstance(connection);
if (accountManager.supportsAccountCreation()){
Log.d(TAG, "Server supports remote registration");
accountManager.sensitiveOperationOverInsecureConnection(true);
Log.d(TAG, "Sending registration request");
HashMap<String, String> attributes = new HashMap<>();
attributes.put("email", "test#gmail.com");
accountManager.createAccount(loginUser, passwordUser, attributes);
} else {
Log.w(TAG, "Server does not support remote registrations");
}
} catch (XMPPException | SmackException e) {
e.printStackTrace();
}
}
I have spent 3 days already googl-ing and stackoverflow-ing.
Has someone seen and fixed this already?
You have to set access rules for registering new user. I have attached here the complete access rules. You can add this by clicking raw in access rules.
[{access,announce,[{allow,[{acl,admin}]}]},
{access,c2s,[{deny,[{acl,blocked}]},{allow,[all]}]},
{access,c2s_shaper,[{none,[{acl,admin}]},{normal,[all]}]},
{access,configure,[{allow,[{acl,admin}]}]},
{access,local,[{allow,[{acl,local}]}]},
{access,max_user_offline_messages,[{5000,[{acl,admin}]},{100,[all]}]},
{access,max_user_sessions,[{10,[all]}]},
{access,mod_register,[{access_from,register_from},{access,register}]},
{access,register,[{allow,[{acl,local}]}]},
{access,muc_create,[{allow,[{acl,local}]}]},
{access,pubsub_createnode,[{allow,[{acl,local}]}]},
{access,register,[{allow,[all]}]},
{access,register_from,[{allow,[all]}]},
{access,s2s_shaper,[{fast,[all]}]},
{access,trusted_network,[{allow,[{acl,loopback}]}]}]
The below code worked for me,
AccountManager accountManager = AccountManager.getInstance(connection);
try {
if (accountManager.supportsAccountCreation()) {
accountManager.sensitiveOperationOverInsecureConnection(true);
accountManager.createAccount("name", "password");
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}

How I can link between JADE agent with the OPC

How I can link between Agent and OPC? Because when I add the Agent code, JAVA cannot connect the OPC. Thank you
public class G2P extends Agent{
//Agent initializations
protected void setup() {
// Printout a welcome message
System.out.println("G2-agent "+getAID().getName()+" is ready.");
}
public static void main(String[] args) throws Exception {
// create connection information
final ConnectionInformation ci = new ConnectionInformation();
ci.setHost("");
ci.setDomain("");
ci.setUser("");
ci.setPassword("");
ci.setClsid("F8582CF2-88FB-11D0-B850-00C0F0104305");
final String itemId1 = "....";
// create a new server
final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
try {
// connect to server
server.connect();
// add sync access, poll every 500 ms
final AccessBase access = new SyncAccess(server, 500);
access.addItem(itemId1, new DataCallback() {
#Override
public void changed(Item item, ItemState state) {
// also dump value
try {
if (state.getValue().getType() == JIVariant.VT_UI4) {
System.out.println("<<< " + state + " / value = " + state.getValue().getObjectAsUnsigned().getValue());
} else {
System.out.println("<<< " + state + " / value = " + state.getValue().getObject());
}
} catch (JIException e) {
e.printStackTrace();
}
}
});
// Add a new group
final Group group = server.addGroup("test");
// Add a new item to the group
final Item item = group.addItem(itemId1);
// start reading
access.bind();
// add a thread for writing a value every 3 seconds
ScheduledExecutorService writeThread = Executors.newSingleThreadScheduledExecutor();
final AtomicInteger i = new AtomicInteger(0);
writeThread.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
final JIVariant value = new JIVariant(i.incrementAndGet());
try {
System.out.println(">>> " + "writing value " + i.get());
item.write(value);
} catch (JIException e) {
e.printStackTrace();
}
}
}, 5, 3, TimeUnit.SECONDS);
// wait a little bit
Thread.sleep(20 * 1000);
writeThread.shutdownNow();
// stop reading
access.unbind();
} catch (final JIException e) {
System.out.println(String.format("%08X: %s", e.getErrorCode(), server.getErrorMessage(e.getErrorCode())));
}
}
}

NullReferenceException was unhandledby user code

I am making a registration page and while using an input tag to upload image of the user, it is giving an error while running the website: "NullReferenceException was unhandledby user code". Please help me to sort this out. The method which is giving error is:
protected void Button2_Click(object sender, EventArgs e)
{
var path = "Memberimg";
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Memberimg") + "\\" + fn;
if ((f1.PostedFile != null) && (f1.PostedFile.ContentLength > 0))
{
try
{
f1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}
You are referring to f1.PostedFile before checking to see if it is null, in the line with:
string fn = System.IO.Path.GetFileName(f1.PostedFile.FileName);