CXCallDirectoryProvider in Callkit is not called - callkit

I'm trying to build a caller id for iOS application based on the example of Hotline. I have done the following steps:
Install the hotline app.
Enable the Call blocking and identification in settings.
Register the ProviderDelegate and CallManager in AppDelegate
My CallDirectoryHandler as follows:
class CallDirectoryHandler: CXCallDirectoryProvider {
override func beginRequest(with context: CXCallDirectoryExtensionContext) {
print("CallDirectoryHandler beginRequest is called")
context.delegate = self
// Check whether this is an "incremental" data request. If so, only provide the set of phone number blocking
// and identification entries which have been added or removed since the last time this extension's data was loaded.
// But the extension must still be prepared to provide the full set of data at any time, so add all blocking
// and identification phone numbers if the request is not incremental.
if context.isIncremental {
addOrRemoveIncrementalBlockingPhoneNumbers(to: context)
addOrRemoveIncrementalIdentificationPhoneNumbers(to: context)
} else {
addAllBlockingPhoneNumbers(to: context)
addAllIdentificationPhoneNumbers(to: context)
}
context.completeRequest()
}
}
I use another phone to call my iPhone. However, the app does not print anything.
What steps did I miss ?
Thanks

Related

Embarcadero C++ : How to notify user if new update is available?

I am beginner in Embarcadero C++, If my application is developed in Embarcadero C++ and installed in client machine then how my application notify user if new update is available? If user clicked on yes button then it will first download the application then install it.
Please let me know if anybody have any Idea.
Here is how I check if new version of program is available on the server, using
Indy Client component TIdHTTP.
Let's say you have uploaded a new version of your application. Besides installation or zip file containing you application, upload a one line text file (applicationBuildData.txt) which contains build value (integer), delimiter (;) and optionally some other data (version number, program name, etc...). For example:
20170215; ProgamName rel. 1.2.
This is the only line in applicationBuildData.txt file. Here is the code sample (I've modified my original code a bit):
void __fastcall TfrmDialog::Button1Click(TObject *Sender)
{
TIdHTTP *IdHTTP1 = new TIdHTTP(this);
// let's say this is current app build (on user's side)
int currAppBuild = 20170101;
int prodBuildNew = 0;
UnicodeString prodVersionNew;
UnicodeString version_str;
try {
// get content of applicationBuildData.txt into string
version_str = IdHTTP1->Get("http://www.your-site.com/applicationBuildData.txt");
prodBuildNew = StrToInt(version_str.SubString(1, version_str.Pos(";") - 1).Trim());
prodVersionNew = version_str.SubString(version_str.Pos(";") + 1, 100).Trim();
}
catch (...)
{
prodBuildNew = 0;
prodVersionNew = "???";
}
if (prodBuildNew == 0) {
// ...faild to get data from server...
// display message
}
else if (prodBuildNew > currAppBuild) {
// new version is available
// display message
}
else {
// application version is up to date
// display message
}
delete IdHTTP1;
}
In this example, current build number is smaller then uploaded build number and it will indicate user that new version is available.
Note: currAppBuild is usually some global constant, or global variable that presents build version. After new version on the server is detected, you can either download installation/zip or simply display message and let the user go to your site and download new version manually.
Edit: How to download the file to your local disk using TIdHTTP component, check the following video:
https://www.youtube.com/watch?v=fcN8K3R4iZE

MVC5 AntiForgeryToken - how to handle "The provided anti-forgery token was meant for user "", but the current user is "xxx"." exception?

I want to protect our login actions by AntiforgeryToken attribute - I know why the exception from the topic occurs, however I can't seem to find any good solution for it.
Let say we have the following situations:
It's 8:00 AM, application users are coming to work, they sit down and starting the login process - right now it is very possible that some of the users will get the same ValidationToken. After the first one logs in - all other will see the above exception (or some other custom exception screen) when they attempt to login.
Some user logged in, then accidentally pressed the "back" button and attempted to log in again - while this is more unlikely, it can happen, and I don't want users to see exceptions when it does.
So the question is simple - how to prevent the above situations, or how to handle them so that users won't notice anything. I have tried the following:
Setting the AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; in Application_Start in Global.asax - it didn't fix the problem, I still get the same exception
Setting the [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")] on the method with [ValidateAntiForgeryToken] attribute - again, no luck there
Right now I was thinking to manually validate the token in action body, catch the error, and check if attempt was made by anonymous user:
public ActionResult SomeAction()
{
try
{
AntiForgery.Validate();
}
catch(HttpAntiForgeryException ex)
{
if(String.IsNullOrEmpty(HttpContext.User.Identity.Name))
{
throw;
}
}
//Rest of action body here
//..
//..
}
The above seems to prevent the errors - but is it safe? What alternatives are there?
Thanks in advance.
Best regards.
EDIT:
The final "solution" was to disable token validation on login form - there may be a better way to handle it, but it seems that all solutions I found, were ugly workarounds similar to mine proposed above.
Since there is no way to know how "safe" those alternatives are (if they are safe at all), we decided to do disable token validation on login.
Try setting (in global.cs):
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
This will add the name identifier to your token,
As for the double login issue try to use a script to document the date and time of the original submit to stop a second submit with the same token.
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
So we know one thing; users like the back button and have a habit of the double click, this is a big issue with AntiforgeryToken.
But depending on what your application does there are ways to limit their compulsion to do so. The simplest of which is to do your best to try and make the visitor not feel like they need to “rewind” their request to alter it.
Ensure that form error messaging is clear and concise to ensure the
user knows what is wrong. Contexual errors give bonus points.
Always maintain form state between form submissions. Apart from
passwords or credit card numbers, there’s no excuse thanks the to MVC
form helpers. #Html.LabelFor(x => x.FirstName)
If forms are spread across tabs or hidden divs such as those used in
SPA frameworks like Angular or ember.js, be smart and show the
controller layouts or form that the errors actually originated from in
the form submission when displaying the error. Don’t just direct them
to the home controller or first tab.
“What’s going on?” - Keeping the user informed
When a AntiForgeryToken doesn’t validate your website will throw an Exception of type System.Web.Mvc.HttpAntiForgeryException.
If you’ve set up correctly you’ve got friendly errors turned on and this will mean your error page will not show an Exception and show a nice error page that tells them what is up.
You can make this a little easier by at least giving the user a more informative page targeted at these exceptions by catching the HttpAntiForgeryException.
private void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpAntiForgeryException)
{
Response.Clear();
Server.ClearError(); //make sure you log the exception first
Response.Redirect("/error/antiforgery", true);
}
}
and your /error/antiforgery view can tell them Sorry you have tried to submit the same information twice
Another Idea is to log the error and return the user to the login screen:
Create a HandleAntiforgeryTokenErrorAttribute class that Overrides the OnException method.
HandleAntiforgeryTokenErrorAttribute.cs:
public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { action = "Login", controller = "Account" }));
}
}
Global Filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new HandleAntiforgeryTokenErrorAttribute()
{ ExceptionType = typeof(HttpAntiForgeryException) }
);
}
}
I would also use a few tools to record all your information as login is critical part of your application
NLog for general logging and emails on critical application exceptions (including web exceptions).
Elmah for filtering and email of web exceptions.
EDIT:
Also you may want to look at a jQuery plugin called SafeForm. Link
EDIT:
I have seen allot of debate on this and everyone's views on the subject have valid points, How i look at it is (Taken from owasp.org)
Cross-Site Request Forgery (CSRF) is an attack that forces an end user
to execute unwanted actions on a web application in which they're
currently authenticated, CSRF attacks specifically target state-changing requests, not theft of data. The anti-forgery token is
specific to 'who is logged on'. So once you login, then go back, the
old token is no longer valid
Now i also use authorized IP addresses for login to allot of my applications with 2 factor authorization if the users IP address changes, so if Cross-Site Request Forgery was in play the user wouldn't match the IP address and request 2 factor authorization. almost like the way a security router would work. but if you want to keep it on your login page i don't see a problem as long as you have your friendly error pages set up people will not get upset as they will see they did something wrong.
I just wanted to add to the pool pro's answer - regarding the Filter part - that one must be careful since that will override all the exceptions about AntiforgeryToken, and if you (like myself) have this token validation on other parts of your application you might consider adding some validation to the filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new HandleAntiforgeryTokenErrorAttribute() { ExceptionType = typeof(HttpAntiForgeryException) });
}
}
public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
string actionName = filterContext.Controller.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = filterContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
if (actionName.ToLower() == "login" && controllerName.ToLower() == "account")
{
//Handle Error
//In here you handle the error, either by logging, adding notifications, etc...
//Handle Exception
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { action = "Login", controller = "Account" }));
}
else
{
base.OnException(filterContext);
}
}
}
Note that I separate the cases where this exception is thrown on the Account/Login method, from all the other mehtods where a [ValidateAntiForgeryToken] might be used.

Windows Phone app not receiving push notification from Parse.com

I have followed this tutorial on setting up Parse push notification in a Windows Phone app. This is my code:
public App() {
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached) {
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
// Initialize the Parse client with your Application ID and .NET Key found on
// your Parse dashboard
ParseClient.Initialize("grpTmrClet8K35yeXg2HQKK8wl59VeC9ijH0I0dn", "os8EfSFq9maPBtDJ91Mq0xnWme8fLANhttTPAqKu");
// After calling ParseClient.Initialize():
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("testchannel");
};
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private async void Application_Launching(object sender, LaunchingEventArgs e) {
await ParseAnalytics.TrackAppOpenedAsync();
}
When I send a push notification from the Parse dashboard it doesn't get received. I have tried running both on the emulator (Windows Phone 8.0) and device (8.1), with app in foreground, background and closed with the same negative result.
When I use a channel like "testchannel" above and use the segment options, the channel name appears in the dropdown list of options indicating that the app is at least connecting Parse, but it just wont receive the notifications.
Hope someone can help me identify what I am missing. Thanks in advance.
If you are developing a Windows Phone 8.1 app, make sure you've enabled toast notification in the manifest file.
I don't quite understand everything about Parse just yet, but this is what works for me.
In App.xaml.cs:
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("wSjuNTbtjVLRaedXvOoaf9S5cTbkuQohTulNZ2vS", "nWZMhXRet9Wotlgikb9aUdKf5GFtRiMvduw7w68z");
}
We subscribe and enable analytics OnLaunched:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
//Generated codes go here
await ParsePush.SubscribeAsync("testchannel");
await ParseAnalytics.TrackAppOpenedAsync();
That would simply do the trick. You should modify the code according to your needs. Hope this helps.

How can I pass data between two Chrome apps?

I have created two Chrome apps and I want to pass some data (string format) from one Chrome app to another Chrome app. Appreciate if someone can help me with showing the correct way of doing this?
It's an RTFM question.
From Messaging documentation (note that it mentions extensions, but it works for apps):
In addition to sending messages between different components in your extension, you can use the messaging API to communicate with other extensions. This lets you expose a public API that other extensions can take advantage of.
You need to send messages using chrome.runtime.sendMessage (using app ID) and receive them using chrome.runtime.onMessageExternal event. If required, long-lived connections can also be established.
// App 1
var app2id = "abcdefghijklmnoabcdefhijklmnoab2";
chrome.runtime.onMessageExternal.addListener(
// This should fire even if the app is not running, as long as it is
// included in the event page (background script)
function(request, sender, sendResponse) {
if(sender.id == app2id && request.data) {
// Use data passed
// Pass an answer with sendResponse() if needed
}
}
);
// App 2
var app1id = "abcdefghijklmnoabcdefhijklmnoab1";
chrome.runtime.sendMessage(app1id, {data: /* some data */},
function(response) {
if(response) {
// Installed and responded
} else {
// Could not connect; not installed
// Maybe inspect chrome.runtime.lastError
}
}
);

Push Notification not received by windows phone app : Parse

I have followed all the steps given in the documentation to register for a push notification from the Parse website. (All the steps in the sense I downloaded the default project and added event handler to handle the incoming toast notification).
ParseClient.Initialize("x0uNa3Q164SVGKbH4mxZJaxWxsuYtslB5tVPj893",
"cXFv9RQAoray9xFdwdcZCHXrrkrM6KNd0WyN194H");
this.Startup += async (sender, args) =>
{
// This optional line tracks statistics around app opens, including push effectiveness:
ParseAnalytics.TrackAppOpens(RootFrame);
// By convention, the empty string is considered a "Broadcast" channel
// Note that we had to add "async" to the definition to use the await keyword
await ParsePush.SubscribeAsync("");
};
ParsePush.ToastNotificationReceived += ParsePushOnToastNotificationReceived;
and the handler
private void ParsePushOnToastNotificationReceived(object sender,
NotificationEventArgs notificationEventArgs)
{
var s = new ShellToast();
s.Content = notificationEventArgs.Collection.Values.First();
s.Title = "My Toast";
s.Show();
}
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
await ParseAnalytics.TrackAppOpenedAsync();
}
When I run the app in the emulator it registers the app and I can verify it in my dashboard. But as soon as I send push notification from the website number of registered devices will be shown as 0 and the app doesnt receive the notification.
One thing to mention is this behavior is not consistent. Sometimes the app does receive the notification. Can anyone mention the reason for this or any other point I am missing?
One thing to note is that ShellToast.Show() should only be used from background task. If you call it when an app is in the foreground, toast won't be shown. http://msdn.microsoft.com/en-US/library/windowsphone/develop/microsoft.phone.shell.shelltoast.show(v=vs.105).aspx
So, be sure your app is not in the foreground when you expect to see toast notification.
Firstly you will be shown toast notification only if the foreground app is not running. If your app is running when you receive push notification you have to do like:
void ParsePushOnToastNotificationReceived(object sender,
NotificationEventArgs notificationEventArgs)
{
Deployment.Current.Dispatcher.BeginInvoke(()=>{
// do anything
MessageBox.Show("got notification");
});
}
If your app is not running the os will handle the notification properly, you dont have to do anything.