chikka api (Receiving SMS) - laravel-5

I have a problem in receiving a SMS from chikka API. I have tried the code posted in their documentation here's the code:
try
{
$message_type = $_POST["message_type"];
}
catch (Exception $e)
{
echo "Error";
exit(0);
}
if (strtoupper($message_type) == "INCOMING")
{
try
{
$message = $_POST["message"];
$mobile_number = $_POST["mobile_number"];
$shortcode = $_POST["shortcode"];
$timestamp = $_POST["timestamp"];
$request_id = $_POST["request_id"];
echo "Accepted";
exit(0);
}
catch (Exception $e)
{
echo "Error";
exit(0);
}
}
else
{
echo "Error";
exit(0);
}
but it only returns error. And I am working on how to process the message sent by the API but it doesn't work. I am new to this API.

Related

Laravel Exception

I want to create Customs Exceptions, and I want to catch and manage them in the controller. But I can't do it.
For example
use Exception;
class MyException extends Exception
{
}
in the controller
public function myFuncion($request){
try{
exceptFunction();
} catch(MyException $e){
repairIt();
}
}
private function exceptFunction(){
throw new MyException('f*ck');
}
The problem here is the code in catch is never executed! Always Laravel send me to the handler! I want to catch and manage the exception by my way in the controller!
I hope you can help (and teach) me.
Thanks
Nicolas
class CajaMovimientoController {
public function anular(AnularCajaMovimientoRequest $request) {
...
if ($movimiento->isIngreso()) {
try {
$this->checkSaldo($movimiento->apertura_id, $movimiento->valores, false);
} catch (Exception $e) {
dd("catch");
return redirect()->back()->with('mensajes', $e->getMessage());
}
dd("anular ingreso");
} else {
$this->checkSaldo($movimiento->apertura_id, $movimiento->valores, true);
dd("anular egreso");
}
}
private function checkSaldo($sessionId, $valores, $ingreso) {
$cajaApertura = CajaApertura::find($sessionId);
$sft = 0;
$sch = 0;
$monto = 0;
foreach ($valores as $valor) {
$monto = $monto + floatval($valor->monto);
if ($valor->cheque_id != null) {
$sch = $sch + floatval($valor->monto);
} else {
$sft = $sft + floatval($valor->monto);
}
}
if (!$ingreso) {
if ($sft > $cajaApertura->efectivo) {
throw new CajaSaldoException('No puede egresar mas efectivo del que posee');
// return redirect()->back()->with('mensajes', 'No puede egresar mas efectivo del que posee');
}
if ($sch > $cajaApertura->cheque) {
throw new CajaSaldoException('No puede egresar mas cheques del que posee');
// return redirect()->back()->with('mensajes', 'No puede egresar mas cheques del que posee');
}
}
for ($i = 0; $i < count($valores); $i++) {
//protected $fillable = ['id','movimiento_id', 'cheque_id', 'monto'
if ($valores[$i]->cheque_id != null) {
$cheque = Cheque::find($valores[$i]->cheque_id);
if ($cheque->caja_id != $cajaApertura->caja_id) {
throw new CajaSaldoException('No puede deshacer. Cheque no está en caja');
}
if ($ingreso) {
if ($cheque->estado != 2) {
throw new CajaSaldoException('No puede reingresar cheque');
}
} else {
if ($cheque->estado != 1) {
throw new CajaSaldoException('No puede egresar cheque');
}
}
}
}
}
}
My Exception Class
namespace Prestamos\Exceptions;
use Exception;
class CajaSaldoException extends Exception
{
//
}
Whenever you want to catch an exception, make sure you are referencing the correct exception in the catch block.
So either, you would reference the FQCN of the class like this
try {
} catch(\App\Exceptions\CustomException $exception) {
}
Or, you would add your use statement at the top of your class
use App\Exceptions\CustomException;
try {
} catch(CustomException $exception) {
}
In your particular case, what is happening is, you are trying to catch a \App\Exceptions\CustomException without adding the use statements.
try {
} catch(CustomException $exception) {
}
What happens in this case is, your code block is looking to catch a App\Http\Controllers\CajaMovimientoController\CustomException exception.
Since it can't find it, the exception is then handled by Laravel as a general exception. Read more about namespaces.

Xamarin(PCL) - Signal R - System.InvalidOperationExceptionConnection started reconnecting before invocation result was received

I am getting System.InvalidOperationExceptionConnection started reconnecting before invocation result was received exception sometimes with Signal R chat, i am using Signal R client in PCL of Xamarin Project
Here is Chat service class-
public class ChatService : IChatService
{
private IHubProxy _hubProxy;
private HubConnection _hubConnection;
private readonly IMobileServiceClient _mobileClient;
private readonly IInsightsService _insightsService;
private readonly IChatMessageRepository _chatRepository;
public ChatService(IMobileServiceClient mobileClient, IInsightsService insightsService, IChatMessageRepository chatRepository)
{
_insightsService = insightsService;
_mobileClient = mobileClient;
_chatRepository = chatRepository;
}
public event EventHandler<ChatMessage> MessageReceived;
public async Task Connect(bool dismissCurrentConnection = false)
{
try
{
if (!CrossConnectivity.Current.IsConnected)
{
return;
}
// Always create a new connection to avoid SignalR close event delays
if (_hubConnection != null)
{
if (!dismissCurrentConnection)
{
return;
}
_hubConnection.StateChanged -= OnConnectionStateChangedHandler;
_hubConnection.Reconnected -= OnReconnectedHandler;
// DON´T call connection.Dispose() or it may block for 20 seconds
_hubConnection = null;
_hubProxy = null;
}
_hubConnection = new HubConnection(Identifiers.Environment.ChatUrl);
// connection.TransportConnectTimeout = TimeSpan.FromSeconds(5);
_hubConnection.TraceWriter = new DebugTextWriter("SignalR");
_hubConnection.TraceLevel = TraceLevels.All;
_hubConnection.StateChanged += OnConnectionStateChangedHandler;
_hubConnection.Reconnected += OnReconnectedHandler;
if (_mobileClient.CurrentUser == null)
throw new Exception("MobileClient.CurrentUser null. You have to login to Azure Mobile Service first.");
_hubConnection.Headers[HttpHeaders.XZumoAuth] = _mobileClient.CurrentUser.MobileServiceAuthenticationToken;
_hubProxy = _hubConnection.CreateHubProxy(Identifiers.ChatHubName);
_hubProxy.On<ChatMessage>("addMessage", message =>
{
MessageReceived?.Invoke(this, message);
});
if (_hubConnection.State == ConnectionState.Disconnected)
{
await _hubConnection.Start();
}
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
private async void OnConnectionStateChangedHandler(StateChange change)
{
if (_mobileClient?.CurrentUser != null && change.NewState == ConnectionState.Disconnected && CrossConnectivity.Current.IsConnected)
{
// SignalR doesn´t do anything after disconnected state, so we need to manually reconnect
await Connect(true);
}
}
private void OnReconnectedHandler()
{
Debug.WriteLine("[SignalR] SignalR Reconnected to Hub: {0}", Identifiers.ChatHubName);
}
public async Task SendMessage(ChatMessage message)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
await Connect(true);
}
await _hubProxy.Invoke("Send", message);
}
catch (Exception ex)
{
try
{
await _chatRepository.InsertAsync(message);
}
catch (Exception ex2)
{
_insightsService.ReportException(ex);
_insightsService.ReportException(ex2);
throw ex;
}
}
}
public async Task JoinChatRoom(string chatRoomId)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
await Connect(true);
}
await _hubProxy.Invoke("JoinChatRoom", chatRoomId);
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
public async Task LeaveChatRoom(string chatRoomId)
{
try
{
if (_hubConnection.State == ConnectionState.Disconnected)
{
await Connect(true);
}
await _hubProxy.Invoke("LeaveChatRoom", chatRoomId);
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
public void Disconnect()
{
try
{
if (_hubConnection != null && _hubConnection.State != ConnectionState.Disconnected)
_hubConnection.Stop();
}
catch (Exception ex)
{
_insightsService.ReportException(ex);
}
}
}
How can i prevent and catch this exception? this is not always though

How can I input a email and let me register only if it contains # and .com

How do I validate an email address?
An address should have a "# " and end ".com "
Here's the code I used:
public void email(){
String a = "qwertyuiopasdfghjklzxcqwertyuiopasdfghjklzxcvbnmvbnmqwertyuiopasdfghjklzxcvbnm#qwertyuiopasdfghjklzxcvbnmqwertyuiopaqwertyuiopasdfghjklzxcvbnmsdfghjklzxcvbnm.com";
String b = JOptionPane.showInputDialog("Enter email");
try{
if(!b.contains(a)){
throw new Error("Incorrect");
}else{
System.out.println("Correct");
}
} catch (Error e){
System.out.println(""+e);
}
}
I think this might help you. From: What is the best Java email address validation method?
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}

issue in getting token id in android

I know that there are lot of questions about this but I couldn't figure out the solution from those questions.
I am getting null in a token from GCM. many people have done this using class, but I am doing
this in background thread in same class. It returns null in regId.
OnCreate
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
Log.e(TAG, "registering in background");
registerInBackground();
} else {
Log.e(TAG, "Notification Token : " + regid);
user.setNotificationToken(regid);
}
} else {
MyLog.i(TAG, "No valid Google Play Services APK found.");
}
RegisterInBackgroud() if device is not registered before.
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Log.e(TAG, "doing in background");
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
if(gcm != null)
{
Log.e(TAG, "GCM is not null");
}
regid = gcm.register(SENDER_ID);
Log.e(TAG, "token id:" + regid);
msg = "Device registered, registration ID=" + regid;
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
I tried to log it bug it display null in regId. what could be the problem in this ?
Some how my app id was not working. Recreating app on google console generated a new id which i used in my project and it started working.

Refactor nested IF statement for clarity [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to refactor this mumbo jumbo of a method to make it more readible, it has way to many nested IF's for my liking.
How would you refactor this?
public static void HandleUploadedFile(string filename)
{
try
{
if(IsValidFileFormat(filename)
{
int folderID = GetFolderIDFromFilename(filename);
if(folderID > 0)
{
if(HasNoViruses(filename)
{
if(VerifyFileSize(filename)
{
// file is OK
MoveToSafeFolder(filename);
}
else
{
DeleteFile(filename);
LogError("file size invalid");
}
}
else
{
DeleteFile(filename);
LogError("failed virus test");
}
}
else
{
DeleteFile(filename);
LogError("invalid folder ID");
}
}
else
{
DeleteFile(filename);
LogError("invalid file format");
}
}
catch (Exception ex)
{
LogError("unknown error", ex.Message);
}
finally
{
// do some things
}
}
I would reverse the conditions in the test to if bad then deleteAndLog as the example below. This prevent nesting and puts the action near the test.
try{
if(IsValidFileFormat(filename) == false){
DeleteFile(filename);
LogError("invalid file format");
return;
}
int folderID = GetFolderIDFromFilename(filename);
if(folderID <= 0){
DeleteFile(filename);
LogError("invalid folder ID");
return;
}
...
}...
Guard clauses.
For each condition, negate it, change the else block into the then block, and return.
Thus
if(IsValidFileFormat(filename)
{
// then
}
else
{
// else
}
Becomes:
if(!IsValidFileFormat(filename)
{
// else
return;
}
// then
If you are not against using exceptions, you could handle the checks without nesting.
Warning, air code ahead:
public static void HandleUploadedFile(string filename)
{
try
{
int folderID = GetFolderIDFromFilename(filename);
if (folderID == 0)
throw new InvalidFolderException("invalid folder ID");
if (!IsValidFileFormat(filename))
throw new InvalidFileException("invalid file format!");
if (!HasNoViruses(filename))
throw new VirusFoundException("failed virus test!");
if (!VerifyFileSize(filename))
throw new InvalidFileSizeException("file size invalid");
// file is OK
MoveToSafeFolder(filename);
}
catch (Exception ex)
{
DeleteFile(filename);
LogError(ex.message);
}
finally
{
// do some things
}
}
One possible approach is to have single if statements that check for when the condition isn't true. Have a return for each one of these checks. This turns your method into a sequence of 'if' blocks instead of a nest.
There's not a lot to refactor here, as you keep the 3 tests separately due to the fact that the error messages relate to the test performed. You could opt for having the test methods report back the error to log so you don't have them in the if/else tree, which could make things simpler abit as you then could simply test for an error and log it + delete the file.
In David Waters reply, I don't like the repeated DeleteFile LogError pattern. I would either write a helper method called DeleteFileAndLog(string file, string error) or I would write the code like this:
public static void HandleUploadedFile(string filename)
{
try
{
string errorMessage = TestForInvalidFile(filename);
if (errorMessage != null)
{
LogError(errorMessage);
DeleteFile(filename);
}
else
{
MoveToSafeFolder(filename);
}
}
catch (Exception err)
{
LogError(err.Message);
DeleteFile(filename);
}
finally { /* */ }
}
private static string TestForInvalidFile(filename)
{
if (!IsValidFormat(filename))
return "invalid file format.";
if (!IsValidFolder(filename))
return "invalid folder.";
if (!IsVirusFree(filename))
return "has viruses";
if (!IsValidSize(filename))
return "invalid size.";
// ... etc ...
return null;
}
It's the elses above that throw my eye. Here's an alternative, inside the try {}
You can make this even shorter by returning after MoveToSafeFolder (Even though you're returning the finally block will be executed.) Then you don't need to assign an empty string to errorMessage, and you don't need to check is errorString empty before deleting the file and logging the message). I didn't do it here because many find early returns offensive, and I'd agree in this instance, since having the finally block execute after the return is unintuitive for many people.
Hope this helps
string errorMessage = "invalid file format";
if (IsValidFileFormat(filename))
{
errorMessage = "invalid folder ID";
int folderID = GetFolderIDFromFilename(filename);
if (folderID > 0)
{
errorMessage = "failed virus test";
if (HasNoViruses(filename))
{
errorMessage = "file size invalid";
if (VerifyFileSize(filename))
{
// file is OK
MoveToSafeFolder(filename);
errorMessage = "";
}
}
}
}
if (!string.IsNullOrEmpty(errorMessage))
{
DeleteFile(filename);
LogError(errorMessage);
}
I would to something like this:
public enum FileStates {
MoveToSafeFolder = 1,
InvalidFileSize = 2,
FailedVirusTest = 3,
InvalidFolderID = 4,
InvalidFileFormat = 5,
}
public static void HandleUploadedFile(string filename) {
try {
switch (Handledoc(filename)) {
case FileStates.FailedVirusTest:
deletefile(filename);
logerror("Virus");
break;
case FileStates.InvalidFileFormat:
deletefile(filename);
logerror("Invalid File format");
break;
case FileStates.InvalidFileSize:
deletefile(filename);
logerror("Invalid File Size");
break;
case FileStates.InvalidFolderID:
deletefile(filename);
logerror("Invalid Folder ID");
break;
case FileStates.MoveToSafeFolder:
MoveToSafeFolder(filename);
break;
}
}
catch (Exception ex) {
logerror("unknown error", ex.Message);
}
}
private static FileStates Handledoc(string filename) {
if (isvalidfileformat(filename)) {
return FileStates.InvalidFileFormat;
}
if ((getfolderidfromfilename(filename) <= 0)) {
return FileStates.InvalidFolderID;
}
if ((HasNoViruses(filename) == false)) {
return FileStates.FailedVirusTest;
}
if ((VerifyFileSize(filename) == false)) {
return FileStates.InvalidFileSize;
}
return FileStates.MoveToSafeFolder;
}
How about this?
public static void HandleUploadedFile(string filename)
{
try
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return; }
// --------------------------------------------------------
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
or, even better, ... this:
public static void HandleUploadedFile(string filename)
{
try
{
if(ValidateUploadedFile(filename))
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private bool ValidateUploadedFile(string fileName)
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return false; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return false; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return false; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return false; }
// ---------------------------------------------------------------
return true;
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
NOTE: You shouldn't be catching and swallowing generic Exception without rethrowing it...

Resources