How to properly forward/redirect calls with pjsua2 - pjsua2

I can't find info on the net how to forward a call with pjsua2.
Currently Im trying with the xfer method but Im getting:
../src/pjsip-ua/sip_inv.c:3942: inv_on_state_null: Assertion `!"Unexpected transaction type"' failed.
There is no information about this error.
This is my code Im trying:
void MyAccount::onIncomingCall(OnIncomingCallParam &iprm)
{
MyCall *call = new MyCall(*this, iprm.callId);
...
calls.push_back(call);
...
QString fwd_to = fwd(QString::fromStdString(ci.remoteUri));
if(fwd_to != "NO_FWD")
{
info+="*** Xfer Call: ";
info+=QString::fromStdString(ci.remoteUri);
info+=" [";
info+=QString::fromStdString(ci.stateText);
info+="]\n";
infoChanged=true;
CallOpParam prm1;
prm1.statusCode = (pjsip_status_code)200;
call->answer(prm1);
pj_thread_sleep(2000);
CallOpParam prm2(true);
call->xfer(fwd_to.toStdString(), prm2);
}
else
{
// standart incoming
...
}
}
fwd is my own function which search a database if it needs to forward the call

I did something like this and works, dont know if some other way exist:
(answering with no media, setting flag and in other thread xfering call to fwd_to string)
if(fwd_to != "NO_FWD")
{
CallOpParam prm1;
prm1.statusCode = (pjsip_status_code)200;
call->answer(prm1);
call->fwd_to = fwd_to;
call->fwd=true;
}
FwdThread *fwd_thread = new FwdThread();
fwd_thread->start();
void FwdThread::run()
{
static pj_thread_desc s_desc;
static pj_thread_t *s_thread;
pj_thread_register("FwdThread", s_desc, &s_thread);
loop();
}
void FwdThread::loop()
{
while(1)
{
for(auto &call : pjt->v_calls)
{
if(call->fwd && call->answered)
{
call->fwd=false;
CallOpParam prm2(true);
call->xfer(call->fwd_to.toStdString(), prm2);
}
}
if(pjt->Stop)
break;
pj_thread_sleep(500);
}
}

Related

Respond from Volley library comes in twice

I am trying to figure out why a response from the Volley library comes in twice (and it is not always the same response that is doubled).
This is the result, a pie chart:
As we can see the total income and the total spending comes in twice (and if I debug it, it is never 4 GET calls, it is always at least 6 GET calls, although only 4 methods are executed).
Here is my code where I am trying to execute 4 GET requests.
public void initialize() {
getOutputFromDatabase(StaticFields.INCOME);
getOutputFromDatabase(StaticFields.EXPENSE);
getOutputFromDatabase(StaticFields.SAVINGS);
getOutputFromDatabase(StaticFields.FOOD);
}
private void getOutputFromDatabase(String incomeOrExpenseOrSavingsOrFood) {
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(this);
// REST URL
String url = null;
if(incomeOrExpenseOrSavingsOrFood.equals("income")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_INCOME;
} else if (incomeOrExpenseOrSavingsOrFood.equals("expense")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_EXPENSE;
} else if (incomeOrExpenseOrSavingsOrFood.equals("savings")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_SAVINGS;
} else if (incomeOrExpenseOrSavingsOrFood.equals("food")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_FOOD;
}
//String Request initialized
StringRequest mStringRequest = new StringRequest(Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
JSONObject locs = obj.getJSONObject("incomeexpense");
JSONArray recs = locs.getJSONArray("Total income");
String repl = recs.getString(0);
if(incomeOrExpenseOrSavingsOrFood.equals("income") && repl.equals("null")) {
totalIncome.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("income") && !repl.equals("null")){
totalIncome.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total income",
Float.parseFloat(repl),
Color.parseColor("#99CC00")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("expense") && repl.equals("null")) {
totalExpense.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("expense") && !repl.equals("null")) {
totalExpense.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total spending",
Float.parseFloat(repl),
Color.parseColor("#FF4444")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("savings") && repl.equals("null")) {
totalSavings.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("savings") && !repl.equals("null")) {
totalSavings.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total savings",
Float.parseFloat(repl),
Color.parseColor("#33B5E5")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("food") && repl.equals("null")) {
totalFood.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("food") && !repl.equals("null")) {
totalFood.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Food/day",
Float.parseFloat(repl),
Color.parseColor("#FFBB33")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Error :" + error.toString());
}
});
mStringRequest.setShouldCache(false);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
mStringRequest.setRetryPolicy(retryPolicy);
mRequestQueue.add(mStringRequest);
// To animate the pie chart
pieChart.startAnimation();
}
Maybe someone know what I am doing wrong here?
I tried different things like
disabling the cache
setting a policy
but nothing worked so far.
I found my error.
The problem is that I am calling my methods where we can find the REST API calls in onResume again.
I had in my mind that onResume is called when someone comes back to his Activity, but I was wrong.
This is my right onResume now.
#Override
protected void onResume() {
super.onResume();
// pieChart.clearChart();
loadSharedPreferences(StaticFields.SP_PORT);
loadSharedPreferences(StaticFields.SP_INTERNET_ADDRESS);
loadSharedPreferences(StaticFields.SP_PERSON);
// getOutputFromDatabase(StaticFields.INCOME);
// getOutputFromDatabase(StaticFields.EXPENSE);
// getOutputFromDatabase(StaticFields.SAVINGS);
// getOutputFromDatabase(StaticFields.FOOD);
// To animate the pie chart
pieChart.startAnimation();
resetEditText();
}

How to setting firebase remote config for unity?

lets to the point, so i want to make some configuration with my game to show Ads but I avoid to update game version too much, because of that I choose firebase remote config with this I can update setting/configuration without update the game version.
there is document for this but not very clear for newbie like me, you can check it here https://firebase.google.com/docs/remote-config/use-config-unity
I already make the script like on doc, but I don't understand how its work on show data because error string format, which is what I know on this firebase console is int format
the script like this :
public static _FirebaseRemoteConfig instance;
private void Awake()
{
instance = this;
}
Firebase.DependencyStatus dependencyStatus = Firebase.DependencyStatus.UnavailableOther;
// Use this for initialization
void Start()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
public void InitializeFirebase()
{
System.Collections.Generic.Dictionary<string, object> defaults =
new System.Collections.Generic.Dictionary<string, object>();
defaults.Add("config_test_string", "default local string");
defaults.Add("config_test_int", 1);
defaults.Add("config_test_float", 1.0);
defaults.Add("config_test_bool", false);
Firebase.RemoteConfig.FirebaseRemoteConfig.SetDefaults(defaults);
Debug.Log("Remote config ready!");
}
public void FetchFireBase()
{
FetchDataAsync();
}
public void ShowData()
{
Debug.Log("maxCountToShowAdmob: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.GetValue("MaxCountShowIntersitialAds").LongValue);
}
// Start a fetch request.
public Task FetchDataAsync()
{
Debug.Log("Fetching data...");
System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync(
TimeSpan.Zero);
return fetchTask.ContinueWith(FetchComplete);
}
void FetchComplete(Task fetchTask)
{
if (fetchTask.IsCanceled)
{
Debug.Log("Fetch canceled.");
}
else if (fetchTask.IsFaulted)
{
Debug.Log("Fetch encountered an error.");
}
else if (fetchTask.IsCompleted)
{
Debug.Log("Fetch completed successfully!");
}
var info = Firebase.RemoteConfig.FirebaseRemoteConfig.Info;
switch (info.LastFetchStatus)
{
case Firebase.RemoteConfig.LastFetchStatus.Success:
Firebase.RemoteConfig.FirebaseRemoteConfig.ActivateFetched();
Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).",
info.FetchTime));
break;
case Firebase.RemoteConfig.LastFetchStatus.Failure:
switch (info.LastFetchFailureReason)
{
case Firebase.RemoteConfig.FetchFailureReason.Error:
Debug.Log("Fetch failed for unknown reason");
break;
case Firebase.RemoteConfig.FetchFailureReason.Throttled:
Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
break;
}
break;
case Firebase.RemoteConfig.LastFetchStatus.Pending:
Debug.Log("Latest Fetch call still pending.");
break;
}
}

How to invoke unit test a Print Event handler in c#

I have below method which will get invoked when I call Print() method. I need to unit test the same. Is there any suggestions on how to do this?
internal PrintRemovalController(IApplicationContextHelper applicationContextHelper)
{
_applicationContextHelper = applicationContextHelper;
using (PrintDocument)
_printDocument.PrintPage += PrintDocument_PrintPage;
}
public void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
Font printFont = null;
try
{
PrintDetails pd;
do
{
pd = _printLines[_printPosition];
printFont = new Font("Courier New", 11, pd.Style);
if (pd.Text != "PAGE~~END")
e.Graphics.DrawString(pd.Text, printFont, Brushes.Black, pd.XPos, d.YPos);
_printPosition++;
}
while (pd.Text != "PAGE~~END");
e.HasMorePages = _printPosition < _printLines.Count;
}
finally
{
if (printFont != null)
printFont.Dispose();
}
}

addautomtioneventhandler on web pages

I'm trying to add an automation event handler for a ui button. I've tested on desktop applications and it's working but I've a problem with buttons in web pages.In fact I can invoke them with InvokePattern.Invoke() but I don't see the handler working after that!
this is my code :
if ((wantedElement != null))
{
element = wantedElement;
buttonEvent = new AutomationEventHandler(close_event);
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, element,TreeScope.Element,buttonEvent );
object pattern;
if (wantedElement.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))
{
InvokePattern invokePattern = (InvokePattern)pattern;
invokePattern.Invoke();
}
}
...
private static void close_event(object sender, AutomationEventArgs e)
{
AutomationElement sourceElement;
try
{
sourceElement = sender as AutomationElement;
Console.WriteLine("button try");
}
catch (ElementNotAvailableException)
{
return;
}
if (e.EventId == InvokePattern.InvokedEvent)
{
// TODO Add handling code.
Console.WriteLine("button invoked");
}
else
{
// TODO Handle any other events that have been subscribed to.
Console.WriteLine("button event");
}
}

Is EntityReference.Load checking for EntityReference.IsLoaded?

Hi I was wondering if EntityReference.Load method includes
If Not ref.IsLoaded Then ref.Load()
My question is basically:
Dim person = Context.Persons.FirstOrDefault
person.AddressReference.Load()
person.AddressReference.Load() 'Does it do anything?
It does Load again. I verified this by Profiler and it shown two queries. Default merge option is MergeOption.AppendOnly and it doesn't prevent from querying again. Code from Reflector:
public override void Load(MergeOption mergeOption)
{
base.CheckOwnerNull();
ObjectQuery<TEntity> query = base.ValidateLoad<TEntity>(mergeOption, "EntityReference");
base._suppressEvents = true;
try
{
List<TEntity> collection = new List<TEntity>(RelatedEnd.GetResults<TEntity>(query));
if (collection.Count > 1)
{
throw EntityUtil.MoreThanExpectedRelatedEntitiesFound();
}
if (collection.Count == 0)
{
if (base.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)
{
throw EntityUtil.LessThanExpectedRelatedEntitiesFound();
}
if ((mergeOption == MergeOption.OverwriteChanges) || (mergeOption == MergeOption.PreserveChanges))
{
EntityKey entityKey = ObjectStateManager.FindKeyOnEntityWithRelationships(base.Owner);
EntityUtil.CheckEntityKeyNull(entityKey);
ObjectStateManager.RemoveRelationships(base.ObjectContext, mergeOption, (AssociationSet) base.RelationshipSet, entityKey, (AssociationEndMember) base.FromEndProperty);
}
base._isLoaded = true;
}
else
{
base.Merge<TEntity>(collection, mergeOption, true);
}
}
finally
{
base._suppressEvents = false;
}
this.OnAssociationChanged(CollectionChangeAction.Refresh, null);
}
Just for reference for anyone else finding the accepted answer, here is the extension method I created for my current project.
using System.Data.Objects.DataClasses;
namespace ProjectName
{
public static class EntityFrameworkExtensions
{
public static void EnsureLoaded<TEntity>(this EntityReference<TEntity> reference)
where TEntity : class, IEntityWithRelationships
{
if (!reference.IsLoaded)
reference.Load();
}
}
}
And usage:
Patient patient = // get patient
patient.ClinicReference.EnsureLoaded();
patient.Clinic.DoStuff();