C# Razor and JavaScript? - javascript

I need to check a boolean value coming from my .NET viewmodel in my JavaScript. If the user isn't signed in meaning my boolean of IsAnonymous would be true, I need to fire off two JavaScript functions. If it's false, I don't want to call the functions. I need to do this because one of the functions calls an ApplicationUser object which doesn't exist if the person using the website isn't signed in. And therefore, it throws a Null Reference Exception.
I've tried this code in my script tag at the bottom of my razor page, but the addBookmark function gets called even if Model.IsAnonymous returns true. Since addBookmark requires an ApplicationUser object, I'm throwing an error.
if (!#Model.IsAnonymous) {
if ($('.bookmark-btn').hasClass('bookmark-story-btn')) {
addBookmark();
} else {
removeBookmark();
}
}

Just do it at your View!
#if (!Model.IsAnonymous)
{
<script>
if ($('.bookmark-btn').hasClass('bookmark-story-btn')) {
addBookmark();
} else {
removeBookmark();
}
</script>
}

Related

How to optimize a parameter validation in Javascript

I have one very interesting question.
We know that we should check every parameter in a function.
So we want to check : if param exists, if type is correct, if it is contain some property in case of JSON type etc. and it should be done in every function.
actually how we can optimize and and avoid a tons of conditional if-else?
I tried to do something like that, but I don't know if it's good. Because it just throws an error and stops a program. But I don't know how it can be done better. I thought that es7 decorators will help me but it isn't because I can't use it for the properties checking because it works only with classes and methods.
export function isExists(param) {
if (param) {
return true;
}
throw new TypeError("Param should exists. Please check it.");
}
export function isJsonObject(itemToTest) {
if (itemToTest) {
return ~Object.prototype.toString.call(itemToTest).search(/Object/);
}
throw new TypeError("itemToTest should exists if you want to test it. Please check it.");
}
export function isOwnPropertyExist(objToTest, propName) {
isExists(objToTest); // Here i want to continue a program workflow or it will be broken if my checking won't have success
isExists(prop);
isJsonObject(objToTest);
if (objToTest.hasOwnProperty(propName)) {
return true;
}
throw new TypeError("objToTest should exists and contains a property with name ");
}
Thanks for any help! This question is tormenting me a more than 2 years.
P.S. I don't want to use Typescript (I just want to know, how do you resolve this moment)

Telling JS when AS's ExternalInterface is ready

SOLVED: I should have added more detail. Even though the External Interface was set up the NetConnection/NetStream objects were not connected to the server. As a result, I couldn't make any calls thru. A very important detail I left out, apologies.
I know that it's proper to have Flash call back to JavaScript when External Interface is ready so I make the call. The JS method gets called correctly but I am unable to then trigger a successful call back to the Flash file. I have to manually set a 1-second timeout to get it to work and I don't understand why. If the External Interface is ready then I should be able to call back to Flash right away, right?
By the way, I'm using SWFObject.embedSWF() to place the Flash file on the page. I've given the file an id and name attributes.
Here's my flash code:
private function init():void // onCreationComplete handler
{
this.setupExternalInterface();
}
private function setupExternalInterface():void
{
if (ExternalInterface.available)
{
ExternalInterface.call("swfIsReady");
ExternalInterface.addCallback("call", makeACall);
}
}
And here's the JSP page:
function swfIsReady(){
setTimeout(flexCall,1000);
}
function flexCall(){
var theApp = getFlexApp(attributes.name);
theApp.call();
}
function getFlexApp(appName)
{
if (navigator.appName.indexOf ("Microsoft") !=-1)
{
return window[appName];
}
else
{
return document[appName];
}
}
This is the only way it works. I thought I could just remove the timeout and call flexCall() directly.
I think you have two little problems in your code :
The first problem is using the call() method which is used in JavaScript to invoke a function.
Try this (I'm not sure that's working but to more see the problem) :
swf_obj.call.call();
but the solution is simply to use another name of your callback function :
swf_obj.make_call();
The second one, is calling ExternalInterface.addCallback() after ExternalInterface.call() which you can just inverse their order to get it working.
So your code can be like this for example :
ActionScript :
private function init(event:FlexEvent):void
{
setupExternalInterface();
}
private function setupExternalInterface():void
{
if (ExternalInterface.available)
{
ExternalInterface.addCallback("make_call", makeACall);
ExternalInterface.call("swfIsReady");
}
}
JavaScript :
function swfIsReady()
{
var swf_obj= swfobject.getObjectById(attributes.name);
if (swf_obj) {
swf_obj.make_call();
}
}
Hope that can help.

PEG.js: how to use prompt?

I'm creating a C++ parser with PEG.js, and I need to be able to use cin. With the after-match JS, when I use prompt(), the (alternate) online version throws an error of 'Parse Error: prompt is not defined'. I am trying to use the initializer to create a function to replicate prompt (probably not optimized, I was just trying it as a solution). However, when I do this, it still gives me the error. I have tried using window.prompt as well, but again, it does not work. Here's an example of what I'm doing:
{
function cin() {
window.prompt("");
}
function changeVar(variable, newValue) {
if(typeof variable === typeof newValue) {
variable = newValue;
} else if(typeof variable === 'undefined') {
alert("You can't assign a value to a variable if the variable isn't declared yet!");
} else {
alert("Bad assignment. In C++, a variable *must* have the same type *all the time*.");
}
}
}
stdin =
whitespace* "std::cin" whitespace* ">>" whitespace* varToBeChanged:[a-zA-Z_]+ ";" whitespace*
{ changeVar(varToBeChanged, cin('')); return varToBeChanged; }
whitespace =
space:[ \t]
{ return space; }
and then in the parser testing field:
std::cin >> variable;
Thank you for looking. I have tried Googling this and SO-searching this but I haven't found any results.
Also, here is the main piece of code, for all the (current) extra information anyone needs. I am having some problems with this as well, but I'll try to figure them out on my own before I post another question.
If you are using http://peg.arcanis.fr/, then the parser code is executed inside of a Web Worker - which has no access to any UI like the window or the DOM. The error "undefined variable" means literally that there is no window or prompt declared.
If you paste your code into http://pegjs.majda.cz/online, it is executed in the web page environment and works flawlessly.

Is it possible to access as3 custom properties from javascript?

I have the following property defined in my webcam as3 webcam class
public function get paused():Boolean
{
return (cam == null);
}
public function set paused(p:Boolean):void
{
if(p){picture.draw(vid,flip);cam = null;}
else cam = Camera.getCamera();
vid.attachCamera(cam);
}
Is it possible to access this from javascript? When I had it as a simple function it worked with:
ExternalInterface.addCallback("paused", paused);
But that wont compile after I changed it to properties.
"Error: Implicit coercion of a value of type Boolean to an unrelated type Function."
I'm an actionscript newbie so maybe there's something obvious I'm missing.
addCallback() only accepts a function, so you'll need to create meaningful functions that set and get the value without the use of the get and set keywords:
function getPaused():Boolean
{
return paused;
}
function setPaused(value:Boolean):void
{
paused = value;
}
ExternalInterface.addCallback("getPaused", getPaused);
ExternalInterface.addCallback("setPaused", setPaused);

Conditionally invoking JavaScript from a bean

How do I conditionally invoke JavaScript from a bean in JSF 2?
I have a class that uses PrimeFaces which uploads user files to a particular folder, but if the user attempts to upload a file with the same name as one that is already present, I want JavaScript in this case to open up a box on the screen asking the user if he wants to overwrite the old file, or cancel the operation. If no file with that name is present, then JavaScript is not called.
I know how to test that a folder has a particular file in it, it is just that I need to know how to invoke JavaScript conditionally.
I would most appreciate any advice on this.
I have looked at variopus resources online, but still cannot get the application to work correctly. basically, this is what I have done, in an included xhtml page I have the following code for the file upload:
<p:fileUpload id="fileUpload" fileUploadListener="#{filters.upload}"
allowTypes="#{filters.uploadTypes}" invalidFileMessage="#{filters.uploadBadType}"
sizeLimit="#{filters.uploadSize}" invalidSizeMessag="#{filters.uploadBadSize}"
update="fileUpload fileTable uploadMessage" description="Select Text File"
disabled="#{filters.disableFileUploadButton}"/>
<!--- Then further in the same file is this: -->
<p:remoteCommand name="remoteCommandOverwrite" actionListender="#{filters.execOverwrite}"/>
The parent xhtml page that includes the above I have the foolowing JavaScript:
<script type="text/javascript">
function popupConfirm() {
var overwrite = confirm('Warning: This will overwrite the existing file - Do you confirm this?');
if (overwrite) remoteCommandOverwrite([{name: overwrite, value: true}]);
}
</script>
In my bean I have the following code in three methods:
public void upload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
overwrite = false;
// Do what you want with the file
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
// Initialization etc.
File file = new File(uploadFull + fileName);
if (file.exists()) {
RequestContext.getCurrentInstance().execute("popupConfirm()");
// Then test to see if overwrite is true or false, and act accordingly
}
// Then I am supposed to get the value of overwrite here:
public void execOverwrite() {
System.out.println("### execOverwrite() ###");
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> map = context.getExternalContext().getRequestParameterMap();
String soverwrite = (String) map.get("overwrite");
if (soverwrite.equals("true")) {
overwrite = true;
System.out.println("overwrite: true");
}
}
What I am trying to do is first to invoke conditionally the JavaScript function popupConfirm(). On clicking the "Upload" button that is invoked if the codition is true, which is what I want. This is then supposed to call
That works and brings up the confirm() box, but the is never called, so the method execOverwrite() in my bean is also never called, and I cannot pick up the return value and pass it to the code inside the method copyFile(). What is going wrong?
I put this problem on the back burner for about a week, and have just got back to it. I got it to work, and can pass a value back to the bean, but somehow I need to resume execution from the place where JavaScript is called.
To sumarize, my JavaScript contains the following code:
<script type="text/javascript">
function popupConfirm() {
var overwrite = confirm('Warning: This will overwrite the existing file - Do you confirm this?');
if (overwrite) remoteCommandOverwrite([{name: 'overwrite', value: 'true'}]);
}
</script>
And in the xhtml code I have:
<p:fileUpload id="fileUpload" fileUploadListener="#{filters.upload}" ...../>
<!-- Other code -->
<p:remoteCommand name="remoteCommandOverwrite" actionListener="#{filters.execOverwrite}"/>
Then on clicking the file upload button after clicking the choose file button, the code in the JavaScript, as listed above, is executed:
RequestContext.getCurrentInstance().execute("popupConfirm()");
Then on clicking "OK" in the dialog box, this method in the same bean is called:
public void execOverwrite() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> map = context.getExternalContext().getRequestParameterMap();
String soverwrite = map.get("overwrite");
if (soverwrite.equals("true")) {
overwrite = true; }
}
}
where the flag "overwrite" will eventually be tested to see if it is true.
Using various print statements I check that this works. However, the code does not resume executing after encountering the statement: RequestContext.getCurrentInstance().execute("popupConfirm()"); regardless of whether I enter "OK" or "Cancel" in the dialog, which is what i want it to do. It looks as if a callback of some type is required, and would most appreciate some ideas.
According to your tag, you are using PrimeFaces, so there is an easy way to invoke a javascript function from a server side event managed bean method when the browser has completed processing the server response. PrimeFaces gives you a utility class called RequestContext.
public void doActionListenerMethod() {
if (!isValid()) {
RequestContext.getCurrentInstance().execute("MyJSObject.doClientSideStuff()");
}
}
The following will execute the string argument as a Javascript when JSF has finished rendering on the client.

Categories