Saturday, May 19, 2018

JQuery

Basic syntax is :$(selector).action()
- A $ sign to define/access JQuery
- A(selector) to "query (or find)" HTML elements
- A jQuery action() to be performed on the elements(s)

examples:
$(this).hide() - hides the current element.
$("p').hide() - hides all <p> elements
$(".test").hide()  hides all elements with class ="test"
$("#test").hid() hides all elements with id = "test"

Are you familiar with CSS selector?
jQuery uses CSS syntax to select elements. You will learn more about he selector syntax in the next chapter of this tutorial.

The Document Ready Event
$(document).ready(function ()
{
}

This is to prevent any jQuery code from running before the document is finished loading  (is ready).

More Examples of jQuery Selectors

SyntaxDescriptionExample
$("*")Selects all elementsTry it
$(this)Selects the current HTML elementTry it
$("p.intro")Selects all <p> elements with class="intro"Try it
$("p:first")Selects the first <p> elementTry it
$("ul li:first")Selects the first <li> element of the first <ul>Try it
$("ul li:first-child")Selects the first <li> element of every <ul>Try it
$("[href]")Selects all elements with an href attributeTry it
$("a[target='_blank']")Selects all <a> elements with a target attribute value equal to "_blank"Try it
$("a[target!='_blank']")Selects all <a> elements with a target attribute value NOT equal to "_blank"Try it
$(":button")Selects all <button> elements and <input> elements of type="button"Try it
$("tr:even")Selects all even <tr> elementsTry it
$("tr:odd")Selects all odd <tr> elementsTry it
Use our jQuery Selector Tester to demonstrate the different selectors.

functions In a Separate File
If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, you can put your jQury functions in a separate .js file.
When we demonstrate jQuery in this tutorial, the functions are added directly into teh <head> section. However, sometimes it is preferable to place them in a separate file, like (use the src attribute to refer to the .js file).

ASP.NET MVC6 default debugging launch URL

refer to https://stackoverflow.com/questions/30002050/asp-net-mvc-6-default-debugging-launch-url

Q: When using the new Visual Studio 2015 RC ASP.NET 5.0 Web API template the default debugging start up URL is somehow set to api/values. Where is this default configured and how do I change it?

Ans:
    here was very little documentation that I could find regarding where this start up URL was declared. There is a brief mention of it in this blog post on MSDN. I eventually stumbled upon it in the launchSettings.json file under the Properties node of the project as shown below:
enter image description here
Here are the contents of this file:
{
  "profiles": {
    "IIS Express": {
      "commandName" : "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables" : {
        "ASPNET_ENV": "Development"
      }
    }
  }
}
You can change the launchURL to your desired default route.

Sunday, May 13, 2018

JavaScript JSON

What is JSON?

    • JSON stands for JavaScript Object Notation
    • JSON is lightweight data interchange format
    • JSON is language independent *
    • JSON is "self-describing" and easy to understand
    * The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

    JSON Example

    This JSON syntax defines an employees object: an array of 3 employee records (objects):

    JSON Example

    {
    "employees":[
        {"firstName":"John""lastName":"Doe"}, 
        {"firstName":"Anna""lastName":"Smith"},
        {"firstName":"Peter""lastName":"Jones"}
    ]
    }

    The JSON Format Evaluates to JavaScript Objects

    The JSON format is syntactically identical to the code for creating JavaScript objects.
    Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

    JSON Syntax Rules

    • Data is in name/value pairs
    • Data is separated by commas
    • Curly braces hold objects
    • Square brackets hold arrays

Converting a JSON Text to a JavaScript Object

A common use of JSON is to read data from a web server, and display the data in a web page.
For simplicity, this can be demonstrated using a string as input.
First, create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
var obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>


JS Reserved Words

avaScript Objects, Properties, and Methods

You should also avoid using the name of JavaScript built-in objects, properties, and methods:
ArrayDateevalfunction
hasOwnPropertyInfinityisFiniteisNaN
isPrototypeOflengthMathNaN
nameNumberObjectprototype
StringtoStringundefinedvalueOf

Java Reserved Words

JavaScript is often used together with Java. You should avoid using some Java objects and properties as JavaScript identifiers:
getClassjavaJavaArrayjavaClass
JavaObjectJavaPackage

Other Reserved Words

JavaScript can be used as the programming language in many applications.
You should also avoid using the name of HTML and Window objects and properties:
alertallanchoranchors
areaassignblurbutton
checkboxclearIntervalclearTimeoutclientInformation
closeclosedconfirmconstructor
cryptodecodeURIdecodeURIComponentdefaultStatus
documentelementelementsembed
embedsencodeURIencodeURIComponentescape
eventfileUploadfocusform
formsframeinnerHeightinnerWidth
layerlayerslinklocation
mimeTypesnavigatenavigatorframes
frameRatehiddenhistoryimage
imagesoffscreenBufferingopenopener
optionouterHeightouterWidthpackages
pageXOffsetpageYOffsetparentparseFloat
parseIntpasswordpkcs11plugin
promptpropertyIsEnumradioreset
screenXscreenYscrollsecure
selectselfsetIntervalsetTimeout
statussubmittainttext
textareatopunescapeuntaint
window

HTML Event Handlers

In addition you should avoid using the name of all HTML event handlers.
Examples:
onbluronclickonerroronfocus
onkeydownonkeypressonkeyuponmouseover
onloadonmouseuponmousedownonsubmit

JavaScript Style Guide and Coding Conventions

Always use the same coding conventions for all your JavaScript projects.

JavaScript Coding Conventions
Coding conventions are style guidelines for programming. They typically cover:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and princiles
Coding conventions secure quality:
  • Improves code readability
  • Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.


Never Declare Number, String, or Boolean Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.
Declaring these types as objects, slows down execution speed, and products nasty side effects:


Use === Comparison

The == comparison operator always converts (to matching types) before comparison.
The === operator forces comparison of values and type:

Example

0 == "";        // true1 == "1";       // true1 == true;      // true
0 === "";       // false1 === "1";      // false1 === true;     // false
Try it Yourself »

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.
Undefined values can break your code. It is a good habit to assign default values to arguments.

Example

function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }
}
Try it Yourself »
Read more about function parameters and arguments at Function Parameters

Avoid Using eval()
The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.
Because it allows arbitrary code to be run, it also represents a security problem.

JavaScript Debugging

Errors can (will) happen, every time you write some new computer code.

JavaScript Debuggers

Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.
Built-in debuggers can be turned on and off, forcing errors to be reported to the user.
With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine variables while the code is executing.
Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your browser with the F12 key, and select "Console" in the debugger menu.

The console.log() Method

If your browser supports debugging, you can use console.log() to display JavaScript values in the debugger window:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>

</body>
</html>
Try it Yourself »
Tip: Read more about the console.log() method in our JavaScript Console Reference.

Setting Breakpoints

In the debugger window, you can set breakpoints in the JavaScript code.
At each breakpoint, JavaScript will stop executing, and let you examine JavaScript values.
After examining values, you can resume the execution of code (typically with a play button).

Major Browsers' Debugging Tools

Normally, you activate debugging in your browser with F12, and select "Console" in the debugger menu.
Otherwise follow these steps:

Chrome

  • Open the browser.
  • From the menu, select tools.
  • From tools, choose developer tools.
  • Finally, select Console.

Firefox Firebug

  • Open the browser.
  • Go to the web page:
    http://www.getfirebug.com
  • Follow the instructions how to:
    install Firebug

Internet Explorer

  • Open the browser.
  • From the menu, select tools.
  • From tools, choose developer tools.
  • Finally, select Console.

Opera

  • Open the browser.
  • Go to the webpage:
    http://dev.opera.com
  • Follow the instructions how to:
    add a Developer Console button to your toolbar.

Safari Firebug

  • Open the browser.
  • Go to the webpage:
    http://safari-extensions.apple.com
  • Follow the instructions how to:
    install Firebug Lite.

Safari Develop Menu

  • Go to Safari, Preferences, Advanced in the main menu.
  • Check "Enable Show Develop menu in menu bar".
  • When the new option "Develop" appears in the menu:
    Choose "Show Error Console".

Did You Know?

Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs.
The first known computer bug was a real bug (an insect) stuck in the electronics.