I'm running a titanium iOS application, it works as expected on the simulator and also on the device when I run it from appcelerator studio, however when I package the app for adhoc distribution and install it on my iPhone device via iTunes it just gets stuck on the splash screen.
Also I can not debug because it is adhoc distribution. The only thing I noticed using alerts is that it runs through alloy.js but never gets to index.js
Any help would be appreciated.
edit: these are my index and alloy files.
index.js
// Arguments passed into this controller can be accessed via the `$.args` object directly or:
var args = $.args;
var webServices = require("webService");
var TAG = "[loginActivity.js] : ";
var fb = Alloy.Globals.Facebook;
var win = $.window;
var core = require("core");
var network = require("NETWORK");
sessionStatus = Ti.App.Properties.getBool('session');
console.log("session estatus "+sessionStatus);
if(!sessionStatus)
Ti.App.Properties.setBool('session', false);
sessionStatus = Ti.App.Properties.getBool('session');
console.log("session estatus "+sessionStatus);
Ti.App.session=sessionStatus;
manageLogin();
Ti.App.addEventListener('resumed',function(e){
//check if login is still valid
console.log("hola");
manageLogin(); //I just reuse my login logic on resume
});
function manageLogin(){
if(Ti.App.session==false){
// require("core").openLogin;
console.log("abro login");
openLogin();
}else{
console.log("abro main");
Ti.App.User_id= Ti.App.Properties.getInt('User_id');
//Ti.App.profIm =Ti.App.Properties.getObject('image');
require("core").openMainActivity();
}
}
function openLogin(){
console.log("First attempt to use geolocation services.");
var hasLocationPermissions = Ti.Geolocation.hasLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE);
Ti.API.info('Ti.Geolocation.hasLocationPermissions', hasLocationPermissions);
if (hasLocationPermissions) {
console.log("GPS permissions granted.");
open();
} else {
console.log("Second attempt");
Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE, function(e) {
if (e.success) {
// $.index.open();
open();
} else {
console.log("Something happened during second attempt");
if (OS_ANDROID) {
//alert('You denied permission for now, forever or the dialog did not show at all because you denied it forever earlier.');
var activity = Titanium.Android.currentActivity;
activity.finish();
open();
}
// We already check AUTHORIZATION_DENIED earlier so we can be sure it was denied now and not before
Ti.UI.createAlertDialog({
title : 'You denied permission.',
// We also end up here if the NSLocationAlwaysUsageDescription is missing from tiapp.xml in which case e.error will say so
message : e.error
}).show();
}
});
}
}
function open(e) {
var nextWin = core.createWindow({
controllerName : "loginActivity"
});
if (OS_ANDROID) {
nextWin.fbProxy = Alloy.Globals.Facebook.createActivityWorker({lifecycleContainer: nextWin});
}
nextWin.addEventListener("postlayout", function checkGPS(e){
nextWin.removeEventListener("postlayout", checkGPS);
if(Ti.Geolocation.getLocationServicesEnabled() === false) {
if(OS_ANDROID){
var alertDlg = Titanium.UI.createAlertDialog({
title:'GPS apagado',
message:'El GPS está apagado. Enciéndelo en ajustes.',
buttonNames: ['No encender el gps', 'Abrir ajustes']
});
alertDlg.cancel = 0;
alertDlg.addEventListener('click', function(e){
if(!e.cancel) {
//open up the settings page
var settingsIntent = Titanium.Android.createIntent({
action: 'android.settings.LOCATION_SOURCE_SETTINGS'
});
Titanium.Android.currentActivity.startActivity(settingsIntent);
}
});
alertDlg.show();
}
else {
alert("No se detecta tu ubicación, te recomendamos encender el GPS antes de iniciar la aplicación.");
}
}
});
nextWin.open();
}
and alloy.js
(function(){
var ACS = require('ti.cloud'),
env = Ti.App.deployType.toLowerCase() === 'production' ? 'production' : 'development',
username = Ti.App.Properties.getString('acs-username-'+env),
password = Ti.App.Properties.getString('acs-password-'+env);
// if not configured, just return
if (!env || !username || !password) { return; }
/**
* Appcelerator Cloud (ACS) Admin User Login Logic
*
* fires login.success with the user as argument on success
* fires login.failed with the result as argument on error
*/
ACS.Users.login({
login:username,
password:password,
}, function(result){
Ti.API.info("Yes, logged in.");
if (env==='development') {
Ti.API.info('ACS Login Results for environment `'+env+'`:');
Ti.API.info(result);
}
if (result && result.success && result.users && result.users.length){
Ti.App.fireEvent('login.success',result.users[0],env);
} else {
Ti.App.fireEvent('login.failed',result,env);
}
});
})();
Alloy.Globals.Facebook = require('facebook');
var T = function (name) {
return require('T/' + name);
};
T('trimethyl');
var Notifications = T('notifications');
Notifications.onReceived = function(e) {
console.log("onreceived "+JSON.stringify(e));
alert(e.data);
};
Notifications.subscribe();
console.log("token "+Notifications.getRemoteDeviceUUID());
For future references.
I had to test step by step, block by block and line by line using a single alert at a time to find out what part of the code was causing the application to crash.
I did find out that 2 separate files were calling each other like require("file2") in file 1 and require("file1") in file 2. Although I don't know why this problem/bug/whatever happened only in distribution ad-hoc mode and not when running the app directly from the computer.
Related
I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/
First I've to explain the scenario:
Kiosk web app with CHROMIUM, showing LOCAL webs. That is, no webserver installed. Chromium is always showing "file:///" pages.
The reason is: sometimes, the computer can be offline (network issues, wifi range...).
Requirement: we want to use google analytics. When computer is ONLINE, the system send http request to GA normally. When OFFLINE, we want to save http request to indexedDB.
Using a worker that executes a job each X seconds, we test the Internet connection. If success, the worker gets the http requests saved into indexedDB and send to Google Analytics.
We've achieved all steps, but one: accesing indexedDB from javascript code inside a Blob.
The reason to use a js Worker inside a Blob is because Chrome don't allow accesing javascript files when the scenario is locally (File:///). This is a small example of a Worker inside a Blob, that access indexedDb each 3 seconds. The example works great in Firefox, for example. But in Chrome, this exception is launched when executing code that access to indexedDb from Blob code:
Unhandled rejection: OpenFailedError: SecurityError Failed to execute
'open' on 'IDBFactory': access to the Indexed Database API is denied
in this context.
<html>
<head>
<title>Example error blob and indexeddb</title>
</head>
<body>
<p>This example demostrate that javascript code inside a Blob can't access indexedDb in Chrome.</p>
<p>Click 'Start WebWorker' to create a Worker inside a Blob. This worker tries to insert some<br>
data into a database created in 'startWorker()' function.</p>
<button type="button" onclick="startWorker()" id="btnStart">
Start WebWorker
</button>
<button type="button" onclick="stopWorker()" id="btnStop">
Stop WebWorker
</button>
<!-- FOR LOGGING INFO PURPOSES -->
<p id="demo"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- TRICK !! Declare this block of type 'javascript/worker' or something non-standard.
Later we can create on the fly javascript executable code
using a Blob (see 'window.onload' function later on this file)
-->
<script id="worker" type="javascript/worker">
var started = false;
var timer;
onmessage = function (event)
{
var orden = event.data.toString();
switch (orden)
{
case 'start':
start();
break;
case 'stop':
stop();
break;
default:
notRecognized(orden);
break;
}
}
function start()
{
if( ! started)
{
timer = setInterval(function(){ job() }, 3000);
started = true;
}
}
function stop()
{
if(started)
{
clearInterval(timer);
started = false;
}
}
//Executed each 3 seconds (see start() )
function job()
{
// Open the database -> ERROR!! Uncaught SecurityError: Failed to execute 'open' on 'IDBFactory':
// access to the Indexed Database API is denied in this context.
var open = indexedDB.open("MyDatabase", 1);
open.onsuccess = function()
{
// Start a new transaction
var db = open.result;
var tx = db.transaction("MyObjectStore", "readwrite");
var store = tx.objectStore("MyObjectStore");
var index = store.index("NameIndex");
// Add some data
store.put({id: 12345, name: {first: "John", last: "Doe"}, age: 42});
store.put({id: 67890, name: {first: "Bob", last: "Smith"}, age: 35});
// Close the db when the transaction is done
tx.oncomplete = function()
{
db.close();
};
}
}//end job()
function notRecognized(orden)
{
var mensaje = 'Comando no reconocido';
selt.postMessage(mensaje + ': ' + orden);
}
</script>
<script type="text/javascript">
var myWorker;
var workerStarted = false;
//Al cargar la pagina, se llama al onload, que carga el WebWorker
window.onload = function () {
var blob = new Blob([ document.querySelector('#worker').textContent ], {type : 'text/javascript'});
myWorker = new Worker(window.URL.createObjectURL(blob));
myWorker.onmessage = function (event)
{
document.getElementById("demo").textContent = event.data; //cambiamos el texto del <p>
console.log("Got: " + event.data + "\n");
};
myWorker.onerror = function (error)
{
document.getElementById("demo").textContent = "Worker error: " + error.message;
console.log("Worker error: " + error.message + "\n");
throw error;
};
};//e onload
//click en botón iniciar, mandamos 'start' al worker
function startWorker()
{
if(workerStarted)
{
document.getElementById("demo").textContent = "Worker yet started !";
return;
}
//Create the DataBase
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
// Open (or create) the database
var open = indexedDB.open("MyDatabase", 1);
// Create the schema
open.onupgradeneeded = function() {
var db = open.result;
var store = db.createObjectStore("MyObjectStore", {keyPath: "id"});
var index = store.createIndex("NameIndex", ["name.last", "name.first"]);
};
workerStarted = true;
//Start Worker
myWorker.postMessage('start');
}
//click en botón parar, mandamos 'stop' al worker
function stopWorker() {
myWorker.postMessage('stop');
}
</script>
</body>
</html>
Following scenario/my solution consists of the following:
Project one: (SELF HOST) I have a SignalR console application which handles the logic including the authentication process ( queries database with EF ). Project two: (CLIENT) I have an ASP.Net web application with an AngularJS client.
So far I can talk to the hub just fine. The problem is, I cannot seem to get the authentication to work. I've tried a bunch of things I've found but none of them worked. Most of them didn't even apply to my problem..
Currently I've stripped my project back to the basics and I have the following code:
Startup class:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
My hub:
[HubName("systemHub")]
public class systemHub : Hub
{
public void Authenticate(String pLogin, String pPassword)
{
User curUser = new AuthManager().Authenticate(pLogin, pPassword);
//this is where I'd want to send the auth cookie or whatever and contact the "loginCallback" function in my client
}
[Authorize]
public void Hello(String pMessage)
{
Clients.All.callbackFunc(pMessage);
}
}
Js client:
hinagApp.controller('hinagController', function ($scope) {
$(document).ready(function () {
var conURL = 'http://localhost:8080/signalr';
$.getScript(conURL + '/hubs', function () {
$.connection.hub.url = conURL;
var lHub = $.connection.systemHub;
lHub.client.callbackFunc = function(pM){
alert(pM);
}
lHub.client.loginCallback = function (pSuccess) {
if (pSuccess) {
//if logged in
lHub.server.hello("test");
}
else {
alert("fail");
}
}
$('#loginbutton').click(function () {
lHub.server.authenticate($('#input_login').val(), $('#input_pass').val());
});
$.connection.hub.start();
});
})
});
I recently ran into a similar problem. If I understand you right, you want to do the authentication on your signalr server application. Signalr can accept standard webrequests just fine.
Set the authenticationtype to cookies:
CookieAuthenticationOptions lOptions = new CookieAuthenticationOptions()
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
LoginPath = new PathString("/Auth/Login"),
LogoutPath = new PathString("/Auth/Logout"),
};
app.UseCookieAuthentication(lOptions);
If user wants to login, set the claims you'd like to use
var lForm = await context.Request.ReadFormAsync();
if (!String.IsNullOrEmpty(lForm["input_login"]) && !String.IsNullOrEmpty(lForm["input_pass"]))
{
//Benutzer authentifizieren
var lAuthenticatedUser = new UserManager().Authenticate(lForm["input_login"], lForm["input_pass"]);
if (lAuthenticatedUser != null)
{
//Existiert der Nutzer legen wir die Claims an
ClaimsIdentity lIdentity = new ClaimsIdentity(lOptions.AuthenticationType);
lIdentity.AddClaim(new Claim(ClaimTypes.Name, lAuthenticatedUser.Username));
lIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, lAuthenticatedUser.InternalUserId.ToString()));
lIdentity.AddClaim(new Claim(ClaimTypes.SerialNumber, context.Request.RemoteIpAddress));
//Und zum Schluss einloggen
context.Authentication.SignIn(lIdentity);
//Und auf die Spieleseite weiterleiten
context.Response.Redirect(BLL._Configuration.HinagGameURL);
}
}
If you want to serve the login page you can do it like this (_Authpage is your page as String, for example)
else if (context.Request.Path.Value == "/Auth/")
{
if (context.Authentication.User != null)
context.Response.Redirect(BLL._Configuration.HinagGameURL);
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(_Authpage);
}
If the user needs anything else ( such as additional style files in your authpage )
else
{
await next();
}
All of this belongs in your Startup.
In Startup.cs you need to add forms authentication middleware (probably you need to tune it a bit):
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
});
https://msdn.microsoft.com/en-us/library/microsoft.owin.security.cookies.cookieauthenticationoptions(v=vs.113).aspx
You kind screwed up Angular with that code. Try this one:
hinagApp
.controller('hinagController', function ($scope, $http) {
var conURL = 'http://localhost:8080/signalr';
var lHub = $.connection.systemHub;
lHub.client.callbackFunc = function(pM){
alert(pM);
}
lHub.client.loginCallback = function (pSuccess) {
if (pSuccess) {
//if logged in
lHub.server.hello("test");
}
else {
alert("fail");
}
}
$http
.get(conURL + '/hubs')
.then(function(response) {
$.connection.hub.url = conURL;
$('#loginbutton').click(function () {
lHub.server.authenticate($('#input_login').val(), $('#input_pass').val());
});
$.connection.hub.start();
});
});
to check if page is published using server side code i should use this snippet:
PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
foreach (PublishingPage page in pages)
{
if(!page.ListItem.File.Level == SPFileLevel.Published)
return;
// logic
}
How could i do the same but using Javascript in SharePoint?
According to SP.Publishing.PublishingWeb Methods the method GetPublishingPages is not supported in JSOM API.
But you could consider the following example to determine whether page is published or not using JSOM API
function getPublishingPages(success,error)
{
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(function() {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
getPublishingPages(printPagesInfo,logError);
});
function printPagesInfo(pages)
{
pages.get_data().forEach(function(item){
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
console.log(String.format('Page {0} is {1}', file.get_name(),pageStatus));
});
}
function logError(sender,args){
console.log('An error occured: ' + args.get_message());
}
I have a project with Blackberry Web Work, and this is my first time for mobile programming.
I want to create cache database using window.openDatabase
But something is strange, I put alert after to show this database, but it didnot show anything.
I also put alert before and after this function, only show alert before this function
I try to put try catch error, but it still not show error message.
Need your help
Thx
Here is my simple code :
$(document).ready(function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
alert("prepare to open database");
var db = openDatabase(shortName, version, displayName, maxSize);
alert("open Database");
// You should have a database instance in db.
}
} catch (e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error " + e + ".");
}
return;
}
alert("Database is: " + db);
});
Your issue seems to be related to the positioning of your try/catch statements. I rearranged your sample code and it is working:
$(document).ready(function () {
if (!window.openDatabase) {
alert('not supported');
} else {
try {
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
alert("prepare to open database");
var db = openDatabase(shortName, version, displayName, maxSize);
alert("open Database");
// You should have a database instance in db.
} catch (e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error: " + e + ".");
}
return;
}
alert("Database is: " + db);
}
});
Keep in mind that openDatabase is not supported on all browsers. FireFox and IE will give you the 'not supported' alert, and Chrome and Safari will display the remaining alerts.
Here is the JSFIDDLE link to test the modified code http://jsfiddle.net/sdarya/0pkvLfpv/