A challenge with onclick occured while combining MVC4, SignalR, knockoutJS - asp.net-mvc-4

I have a simple MVC4 app where however I want to combine knockoutJS and SignalR and I got a challenge which seems to be caused by the fact that I'm trying to assign 2 onclick events on the same button: using knockoutJS and signalR. Please let me know what's wrong here. Below is the code.
This is my viewModel:
var viewModel = {
searchString: ko.observable("Monique"),
search: function () {
$.ajax({
url: "#Url.Action("Search")",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
$('#info').append(result.message);
}
});
},
searchClient: function () {
//do sth
},
showAll: function () {
//do sth
}
};
ko.applyBindings(viewModel);
And this part is related to signalR:
This is my hub on a server:
[HubName("send")]
public class DataHub: Hub
{
public void Send(string text)
{
Clients.All.addMessage(text);
}
}
and this is a signalR js part:
$(function () {
var hub = $.connection.send;
hub.client.addMessage = function (text) {
alert(text);
$('#info').append(text);
};
$.connection.hub.start().done(function () {
$('#btnServer').click(function () {
alert('btn server clicked');
hub.server.send("something");
});
});
});
So as you can see, knockoutJS has onclick event processing here search: function () { }
and in signalR I also have $('#btnServer').click(function() {.
And as a result, what is related to knockoutJS works but the part related to signalR does not work...

In that function where you bind click event using knockout, return true. By default, Knockout will prevent the click event from taking any default action.

Related

Net Core and JQuery autocomplete

Im having some real problems getting JQuery autocomplete to work in Net Core.
here is my client side script :
<script>
$(document).ready(function () {
$('#txtSystemUserDisplayName').autocomplete({
change: function (event, ui) {
if (!ui.item) {
$('#txtSystemUserDisplayName').val("");
}
},
source: function (request, response) {
$.ajax({
url: "#(Url.Action("SearchEmployeesAJAX", "Home" ))",
// data: "{ 'term': '" + request.term.replace(/'/gi, "\\'") + "'}",
data: { term: 'fumanchu' },
dataType: "json", type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var x = Array.prototype.slice.call(data);
response($.map(x, function (item) {
return {
label: item.employeeDisplayName,
}
}))
}, error: function (response) { alert(response.responseText); }, failure: function (response) { alert(response.responseText); }
});
},
select: function (e, i) {
$("#hfSystemUserDisplayName").val(i.item.label);
},
minLength: 1
});
});
Now when i start typing , the autocomplete fires but the param in the controller method is NULL , no matter what i do. it doesnt matter what i call the 'term' in the data object of the request. And yes i am making sure that the controller method parameter is named the same . eg
public JsonResult SearchEmployeesAJAX(String term) {
as you can see ive even commented it out and hardcoded a string in there, still null.
it DOES work if I set the string as part of the URL eg:
url: "#(Url.Action("SearchEmployeesAJAX", "Home", new {#term="blahblahblah" }
This is how I have always done autocompletes in the past on .Net Framework, and never had an issue. Is there something different about Net Core that im not aware of, maybe something different about how requests are formed?
Any help would be appreciated.
Ok so if anyone else is also having this problem, it appears that you cant use the Url.Action helper anymore and still have the parameter not be null.
You will need to use a raw string as the url instead, which seemed to solve this.

ReferenceError: data is not defined in angular 6

Im calling a service from one of my component, via the assignGirdle function. While this service is being executed, I get the above error, but when I check in the network tab and click on the API call, in response in can see the data.
Note girdleNew is of type any. Also this function I'm calling on ngOnInit()
assignGirdle() {
this.diamondSearchService.getDistinctValues()
.subscribe((data) => {
this.girdleNew = data;
}, error => {
this.alertify.error(error);
});
}
The service:
getDistinctValues() {
return this.authHttp
.get(this.baseUrl + 'distinct/girdle')
.map(response => response.json())
.catch(this.handleError);
}
Check if you have imported service in your component. Below is my data service import.
import { DataService } from '../data.service';
Create object of the same in your component:
constructor(public data: DataService) { }
In my component I have called this getUser() method which is defined in DataService.
this.data.getUser(email).subscribe( data => {
if(data.length > 0){
console.log(data);
}
});
Below is my service:
getUser(email){
// definition
}
This works for me.

How to pull data from SqlDataAdapter and store it in a JsonStore collection in MobileFirst

I have a SqlDataAdapter and I want to store it in a JsonStore collection in MobileFirst and Display it in table form. I have tried using Load() method but its not working.
this is my resultSetCollection.js file
;(function () {
WL.JSONStore.init({
resultSet : {
searchFields: {"EMP_NAME":"string","EMP_ID":"integer"}
}
}, {
// password : 'PleaseChangeThisPassword'
})
.then(function () {
return WL.Client.invokeProcedure({
adapter : 'EmployeeList',
procedure : 'getEmployeeLists',
parameters : []
});
})
.then(function (responseFromAdapter) {
alert('responseFromAdapter:' + JSON.stringify(responseFromAdapter.invocationResult.resultSet));
var accessor = WL.JSONStore.get('resultSet');
var data=responseFromAdapter.invocationResult.resultSet;
var changeOptions = {
replaceCriteria : ['EMP_ID', 'EMP_NAME'],
addNew : true,
markDirty : false
};
return accessor.change(data, changeOptions);
})
.then(function (response) {
console.log(response);
//Here I want to retrieve the collection and display it in a table
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).error(errObj);
});
}());
An adapter procedure request from a client application will have a response object in its success and failure callbacks. So lets assume that the request was successfull and data was returned from the backend server.
Lets also assume you have a JSONStore initialized and properly setup with a collection. You then only need to get the collection and add data to it.
The below example takes the full response from an HTTP adapter request and puts it as-is into a collection. You will of course need to create a better setup for your specific scenario...
Note that the code is not optimised and performance or with 100% proper logic. It's just a demonstration flow.
Tested in MobileFirst Platform Foundation 7.0.0.00.
main.js:
var collectionName = 'mydata';
var collections = {
mydata : {
searchFields : {data: 'string'},
}
};
function wlCommonInit(){
WL.JSONStore.init(collections).then(
function() {
var resourceRequest = new WLResourceRequest("/adapters/myadapter/getStories", WLResourceRequest.GET);
resourceRequest.send().then(resourceRequestSuccess, resourceRequestFailure);
}
);
}
function resourceRequestSuccess(response) {
WL.JSONStore.get(collectionName).add(response).then(
function(){
WL.Logger.info("successfully added response to collection");
displayDataFromCollection();
},
function() {
alert("failed adding response to collection");
}
);
}
function resourceRequestFailure() {
alert ("failure");
}
If you then like to fetch the data from the JSONStore and display it in the HTML, you could do something like this:
// get a specific item from the stored response and display it in a table
function displayDataFromCollection() {
WL.JSONStore.get(collectionName).findAll().then(
function(result) {
$("#mytable").append("<tr><td>" + result[0].json.responseJSON.rss.channel.title + "</td></tr>");
},
function() {
alert ("unable to display collection");
}
);
}
The index.html looks like this:
<table id="mytable">
</table>

Sencha Touch 2, before filter on the router, to check for user's auth state

I am developing a Sencha Touch 2 app with user authentication.
I use a token for authentication.
The logic.
Check is a token exists in local storage:
var tokenStore = Ext.getStore('TokenStore'),
token = tokenStore.getAt(0).get('token');
If there is a token, check if it's valid.
I am doing a read from a model which is connected to my API which, returns success or fail - depending on the token - if it's valid or not.
TestApp.model.CheckAuthModel.load(1, {
scope: this,
success: function(record) {
// Here, I know the token is valid
},
failure: function() {
console.log('failure');
},
callback: function(record) {
console.log('callback');
console.log();
}
});
And here is the router, which handles the logic for the views:
Ext.define("TestApp.controller.Router", {
extend: "Ext.app.Controller",
config: {
refs: {
HomeView: 'HomeView',
LoginView: 'LoginView',
ProductsView: 'ProductsView',
ProductsViewTwo: 'ProductsViewTwo'
},
routes: {
'': 'home',
'home' : 'home',
'login' : 'login',
'products' : 'products',
'testingtwo' : 'testingtwo'
}
},
home: function () {
console.log('TestApp.controller.Router home function');
var initialItem = Ext.Viewport.getActiveItem(),
comp = this.getHomeView();
if (comp === undefined) comp = Ext.create('TestApp.view.HomeView');
Ext.Viewport.animateActiveItem(comp, {
type: 'slide',
listeners: {
animationend: function() {
initialItem.destroy();
}
}
});
},
login: function () {
var initialItem = Ext.Viewport.getActiveItem(),
comp = this.getLoginView();
if (comp === undefined) comp = Ext.create('TestApp.view.LoginView');
Ext.Viewport.animateActiveItem(comp, {
type: 'slide',
listeners: {
animationend: function() {
initialItem.destroy();
}
}
});
},
products: function () {
var initialItem = Ext.Viewport.getActiveItem(),
comp = this.getProductsView();
if (comp === undefined) comp = Ext.create('TestApp.view.ProductsView');
Ext.Viewport.animateActiveItem(comp, {
type: 'slide',
listeners: {
animationend: function(){
initialItem.destroy();
}
}
});
},
testingtwo: function () {
var initialItem = Ext.Viewport.getActiveItem(),
comp = this.getProductsViewTwo();
if (comp === undefined) comp = Ext.create('TestApp.view.ProductsViewTwo');
Ext.Viewport.animateActiveItem(comp, {
type: 'slide',
listeners: {
animationend: function(){
initialItem.destroy();
}
}
});
},
launch: function() {
console.log('TestApp.controller.Router launch!');
}
});
Now, how can I link the router with the check auth model callback?
I want to know the auth state when the app reaches the router.
In other MVC frameworks, I could do a before filter, on the router, check for auth and handle the routes accordingly.
Can i do this in Sencha Touch 2?
Any ideas?
Hi I think this section in the documentation is exactly what you need:
before : Object
Provides a mapping of Controller functions to filter functions that are run before them when dispatched to from a route. These are usually used to run pre-processing functions like authentication before a certain function is executed. They are only called when dispatching from a route. Example usage:
Ext.define('MyApp.controller.Products', {
config: {
before: {
editProduct: 'authenticate'
},
routes: {
'product/edit/:id': 'editProduct'
}
},
//this is not directly because our before filter is called first
editProduct: function() {
//... performs the product editing logic
},
//this is run before editProduct
authenticate: function(action) {
MyApp.authenticate({
success: function() {
action.resume();
},
failure: function() {
Ext.Msg.alert('Not Logged In', "You can't do that, you're not logged in");
}
});
}
});
http://docs.sencha.com/touch/2.3.1/#!/api/Ext.app.Controller-cfg-before
Of course, it's still up to you to decide whether you should check every time or should cache the auth result for sometime.
Updated to answer comment below
Honestly, i am not sure how they was going to declare that static method Authenticate in Sencha (you would be able to do it normally through Javascript i think, i.e.: prototype).
But there are other better options to solve just that Authenticate function:
Just create a singleton class that handle utility stuffs.
http://docs.sencha.com/touch/2.3.1/#!/api/Ext.Class-cfg-singleton
If you really want to use MyApp, you can declare within the Ext.app.Application (in app.js). Then call it from the global instance MyApp.app.some_function(). I wouldn't exactly recommend this method because you change app.js, that might bring problem if you upgrade sencha touch.
You could implemented auth check in application's launch function or in your auth controller's init function and based on the response redirect the to appropriate url. Something like this:
TestApp.model.CheckAuthModel.load(1, {
scope: this,
success: function(record) {
this.redirectTo("home/");
},
failure: function() {
this.redirectTo("login/");
console.log('failure');
},
callback: function(record) {
console.log('callback');
console.log();
}
});

Phonegap windows 8 App, with camera functionality, navigate.camera.getPicture() call back function is never called when deployed

We have made a Win8 app using phonegap.
The application also has a reference to a Windows runtime component used to perform some asyc task.
The application has a camera feature, where in the camera is invoked, picture taken and then the picture is displayed on the screen in the success call back function. Everything works perfectly when running directly from visual studio express. The problem arises when we create a package of the application and deploy it using either metro sideloader or powershell. The camera success callback function is never called.
The code for calling the camera is something like this:
CameraService = function() {
var that = {};
that.invokecamera = function(callback) {
try {
GLOBALS.callback = callback;
if (GLOBALS.Ready) {
navigator.camera.getPicture(that.onSuccess, GLOBALS.ThrowException, {
quality : 50,
saveToPhotoAlbum : true,
destinationType : Camera.DestinationType.FILE_URI
});
}
} catch (err) {
alert(err);
} finally {
}
}
that.onSuccess=function(imageURI) {
GLOBALS.ImagePath = imageURI;
GLOBALS.callback(imageURI);
}
return that;
}
Ok, So i figured out the issue mentioned here:
issue with installed app
To fix this i, as mentioned in the link replaced
Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
With
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
In the cordova.js file. I am using cordova 2.4.0.
A more elaborated exmple
Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (file) {
file.openAsync(Windows.Storage.FileAccessMode.readWrite).done(function (fileStream) {
Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(_stream, fileStream).done(function () {
var _imageUrl = URL.createObjectURL(file);
successCallback(_imageUrl);
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });
});
Becomes
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (file) {
file.openAsync(Windows.Storage.FileAccessMode.readWrite).done(function (fileStream) {
Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(_stream, fileStream).done(function () {
var _imageUrl = URL.createObjectURL(file);
successCallback(_imageUrl);
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });
}, function () { errorCallback("Resize picture error."); });