Monday, February 29, 2016
object.defineProperty(cat, 'name', (enumerable: false))
JavaScript call apply
Call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
var obj = {
num: 2
};
var addToThis = function(a) {
return this.num + a;
};
addToThis.call(obj,3);
the obj is passed to addToThis function which has "num" property. a is passed when call is made.
Apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
var addToThis = function(a, b, c) {
return this.num + a + b+ c;
};
console.log(addToThis.apply(obj, arr);
the obj is passed to addToThis function which has "num" property. arguments is passed in an array when apply is made
JavaScript Bind
var a = {name:"bob"};
var b = {name: "john"};
function showName(){return this.name;};
showName.bind(a)();
showName.bind(b)();
Ex 2
function add(x,y){
return x + y;
}
var plus1 = add.bind(null,1);
console.log(plus1(5));
Friday, February 26, 2016
connect to mongoDB from node.js
add to project folder a new folder data, and create database.js
//database.js
(function (database) {
var mongodb = require("mongodb");
var mongoURL = "mongodb://localhost:27017/theBoard";
var theDB = null;
database.getDB = function (next) {
if (!theDB) {
//connect to the database
mongodb.MongoClient.connect(mongoURL, function (err, db) {
if (err) {
next(err, null);
} else {
theDB = {
db: db
}
next(null, theDB)
}
});
}
else {
next(null, theDB);
}
};
})(module.exports);
start mongo command and list details
http://localhost:28017/
http://localhost:28017/local/
http://localhost:28017/theBoard/
you need to last "/" to get it to work
http://localhost:28017/theBoard/notes/
control shift P
control shift M
udemy dan wahlin
Mongo DB download
Thursday, February 25, 2016
Variadic function
--lowMessage, highMessage, number = ...
lowMessage, highMessage, number = ...
function getRandomNumber(maxValue)
math.randomseed(os.time())
math.random()
return math.random(maxValue)
end
function handleGuesses(lowMessage, highMessage, number)
--lowMessage, highMessage, number = ...
local guesses = {}
while answer ~= number do
local answer = io.read("*n")
guesses[#guesses+1] = answer
if answer < number then
print(lowMessage)
elseif answer > number then
print(highMessage)
else
break
end
print "Guess again"
end
return guesses
end
local number = getRandomNumber(100)
print "Guess a number"
local guesses = handleGuesses("Too low", "Too high", number)
print "You got it"
print "Here are your guesses"
for i,v in ipairs(guesses) do
print(i, v)
end
Lua function
function getRandomNumber(maxValue)
print "Guess number"
math.randomseed(os.time())
math.random()
return math.random(maxValue)
end
number= getRandomNumber(100)
print(number)
while answer ~= number do
answer = io.read("*n")
if answer < number then
print("too low")
elseif answer > number then
print ("too high")
else
print "got it"
end
end
print(number)
print(answer)
Lua chunk of code
>> showing waiting for more code
lua scripting
https://code.google.com/archive/p/luaforwindows/downloads
northwind sql sample database install for SQL express 2012
Wednesday, February 24, 2016
grunt-cli nodmon
npm install grunt-cli -g
install node mon
npm install grunt-nodemon -save-dev
add gruntfile.js to root of project
// gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
nodemon: {
all: {
script: 'server.js',
options: {
watchedExtensions: ['js']
}
}
},
});
grunt.loadNpmTasks('grunt-nodemon');
grunt.registerTask('default', ['nodemon']);
};
.node js add .bowerrc to project for client side library
Create .bowerrc file (save again with encoding western Europe windows, when create need to create with .bowerrc.txt then rename it).
below will change install directory of BOWER
ex. bower install underscore, it will save to dir below:
{
"directory": "public/lib"
}
node.js public folder static
var http = require('http');
var express = require("express");
var app = express();
var controllers = require("./controllers");
app.set("view engine", "vash");
// set the public static resource folder
app.use(express.static(__dirname + "/public"));
//map the routes
controllers.init(app);
app.get("/api/users", function (req, res) {
res.set("Content-Type", "application/json");
res.send({ name: "Greg", isValid: true, group: "Admin" });
});
var port = process.env.port || 3000;
var server = http.createServer(app);
server.listen(port);
layout.vash
<!DOCTYPE html>
<html>
<head>
<title>@model.title</title>
<link href="/css/site.css" rel="stylesheet" />
</head>
<body>
<div> @html.block('body') </div>
</body>
</html>
node.js error first call back
seed data in Node.js
index.vash
@html.extend('layout', function(model){
@html.block('body', function(model){
<h1>@model.title </h1>
@if (model.error){
<p class="text-error">Error occurred: @model.error</p>
}
@model.categories.forEach(function (category){
<div>
<span>@(category.notes ? category.notes.length:0) -</span>
<a href="#">@category.name</a>
</div>
})
})
})
index.js
(function (data) {
var seedData = require("./seedData");
data.getNoteCategories = function (next) {
next(null, seedData.initialNotes);
};
})(module.exports);
node.js controllers
server.js
var http = require('http');
var express = require("express");
var app = express();
var controllers = require("./controllers");
app.set("view engine", "vash");
//map the routes
controllers.init(app);
app.get("/api/users", function (req, res) {
res.set("Content-Type", "application/json");
res.send({ name: "Greg", isValid: true, group: "Admin" });
});
var port = process.env.port || 3000;
var server = http.createServer(app);
server.listen(port);
Add controllers folder, add index.js, add homeControllers.js
controllers/index.js, it depends on home controller
(function (controllers) {
var homeController = require("./homeController.js");
controllers.init = function (app) {
homeController.init(app);
};
})(module.exports);
controllers/homeController.js
(function (homeController) {
homeController.init = function (app) {
app.get("/", function (req, res) {
res.render("index", { title: "Express+Vash" });
});
};
})(module.exports);
index.vash vash view engine
var http = require('http');
var express = require("express");
var app = express();
app.set("view engine", "vash");
app.get("/", function (req, res) {
res.render("index", { title: "Express+Vash" });
});
app.get("/api/users", function (req, res) {
res.set("Content-Type", "application/json");
res.send({ name: "Greg", isValid: true, group: "Admin" });
});
var port = process.env.port || 3000;
var server = http.createServer(app);
server.listen(port);
index,vash in view folder, VS2015 requires HTML tags to be upper case (see below)
<!DOCTYPE HTML>
<HTML>
<head>
<title>@model.title</title>
</head>
<BODY>
<div>@model.title</div>
</BODY>
</HTML>
Node js express
var http = require('http');
var express = require("express");
var app = express();
app.get("/", function(req, res) {
res.send("<html><body><h1>" + req.url + "</h1></body><html");
});
app.get("/api/users", function (req, res) {
res.set("Content-Type", "application/json");
res.send({ name: "Greg", isValid: true, group: "Admin" });
});
var port = process.env.port || 3000;
var server = http.createServer(app);
server.listen(port);
Node.js http
var http = require('http');
var express = require("express");
var app = express();
var port = process.env.port || 3000;
var server = http.createServer(function (req, res) {
console.log(req.url);
res.write("<html><body><h1>" + req.url + "</h1></body><html>");
res.end();
});
server.listen(port);
npm install uninstall --save
Node JS folder dependencies
console.log('Hello world');
var x = 1;
var y = 2;
console.log(x * y);
var msg = require("./msgs.js");
//console.log(msg.first);
//console.log(msg.second);
//console.log(msg.msg1);
var o = new msg();
console.log(o.first);
var logger = require('./logger/index.js');
logger.log("test logger");
add a new folder logger and default will be the index.js file, also js file extension can be ignored.
index.js
module.exports.log = function (msg){
console.log(msg);
}
exports as constructor
console.log('Hello world');
var x = 1;
var y = 2;
console.log(x * y);
var msg = require("./msgs.js");
//console.log(msg.first);
//console.log(msg.second);
//console.log(msg.msg1);
var o = new msg();
console.log(o.first);
msgs.js as constructor
module.exports =function (){
this.first= "this is a msg";
}
exports function
var x = 1;
var y = 2;
console.log(x * y);
var msg = require("./msgs.js");
//console.log(msg.first);
//console.log(msg.second);
//console.log(msg.msg1);
console.log(msg());
msgs.js
module.exports =function (){
return "this is a msg";
}
exports returns an object to require
console.log('Hello world');
var x = 1;
var y = 2;
console.log(x * y);
var msg = require("./msgs.js");
console.log(msg.first);
msgs.js
exports.first = "first"
Tuesday, February 23, 2016
Open existing node js projects in Visual studio
wiki.shibboleth.net
https://wiki.shibboleth.net/confluence/#all-updates
Monday, February 22, 2016
redis multi exec watch
Visual studio node extension
https://github.com/Microsoft/nodejstools/wiki/io.js-and-ES6-support
https://github.com/Microsoft/nodejstools/wiki/Install-Node.js-and-get-started-with-NTVS
Saturday, February 20, 2016
change out the camel case jason
{
services.AddMvc()
.AddJsonOptions(opt =>
{
opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<WorldContext>();
switch asp.net web site to web api
DNX
dnvm use -r coreclr 1.0.0-rc1-update1
you have to move the directory to the project default directory to execute dnx command
ex.
D:\Projects\Pluralsight\aspnet5\src\aspnet5
Friday, February 19, 2016
Redis book
https://www.quora.com/What-are-the-best-links-books-to-learn-Redis
Thursday, February 18, 2016
Redis tutorial
Get SERVER:NAME
set connections 10
incr connections
del connections
Wednesday, February 17, 2016
DdContext
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<WorldContext>();
In Models\WoldContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace aspnet5.Models
{
public class WorldContext: DbContext
{
public WorldContext()
{
Database.EnsureCreated();
}
public DbSet<Trip> Trips { get; set; }
public DbSet<Stop> Stops { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connString = Startup.Configuration["Data:WorldContextConnection"];
optionsBuilder.UseSqlServer(connString);
base.OnConfiguring(optionsBuilder);
}
}
}
Startup.cs in ASP.NET 5 MVC 6
1. to read from configuration file config.json
2. to add MVC to project.
3. configure MVC route.
4. if debug is for run app in debug mode, so executing the fake service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
using aspnet5.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.PlatformAbstractions;
namespace aspnet5
{
public class Startup
{
public static IConfigurationRoot Configuration;
public Startup(IApplicationEnvironment appEnv )
{
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
#if DEBUG
services.AddScoped<IMailService, DebugMailService>();
#else
services.AddScoped<IMailService, MailService>();
#endif
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
//app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "App", action = "index" }
);
}
);
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
hackerrank. C# factorial
int Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
http://stackoverflow.com/questions/16583665/for-loop-to-calculate-factorials
C# merge two array and sort it - hacker rank test question
{
int[] _a = new int[4] { 3, 5, 6, 11 };
int[] _b = new int[8];
int _a_cnt = 0;
_a_cnt = 4;
_b[0] = 12;
_b[1] = 13;
_b[2] = 9;
_b[3] = 7;
mergeArray(_a, _b, _a_cnt);
}
static void mergeArray(int[] a, int[] b, int M)
{
Array.Copy(a, 0, b, M, M);
Array.Sort(b);
}
}
Tuesday, February 16, 2016
_Layout.cshtml use @RenderSection("Scripts",false)
@RenderSection("Scripts",false)
Add to view
ex.
Contact.cshtml
which injects scripts to the view:
@section Scripts{
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
full _Layout.cshtml below:
@*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
ViewBag.Title = "Home page";
}
<!doctype="html">
<html>
<head>
<title>the world @ViewBag,Title</title>
<meta charset="utf-8" />
<link href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/css/site.css" rel="stylesheet" />
<script src="~/lib/angularjs/angular.min.js"></script>
<script src="~/js/app.js"></script>
<script src="~/js/controller.js"></script>
</head>
<body ng-app="app">
<div id="sidebar">
<img src="~/img/greg.jpg" alt="Greg image" class="headshot" />
<span id="username">greg</span>
<ul class="menu">
<li class="active"><a <a asp-controller="app" asp-action="Index">home</a></li>
<li><a asp-controller="app" asp-action="About">About</a></li>
<li><a <a asp-controller="app" asp-action="Contact">contact</a></li>
</ul>
</div>
<div id="wrapper" class="row">
<div id="main">
<h2>The world</h2>
<p>this web site</p>
@RenderBody()
</div>
<div id="footer">©The World Ltd</div>
</div>
<script type="text/javascript" src="~/js/site.js"></script>
@RenderSection("Scripts",false)
</body>
</html>
~/ start from the root
<link href="~/css/site.css" rel="stylesheet" />
Add MVC to ASP.NET 5
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
add in ConfigureServices, then add to Configure
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
namespace aspnet5
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
//app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
input
ng-repeat
<div ng-controller="controller as vm" class="col-md-6 col-md-offset-3">
<h2>{{vm.name}}</h2>
<table class="table table-responsive table-striped">
<tr ng-repeat="trip in vm.trips">
<td>{{trip.name}}</td>
<td>{{trip.created | date:'shortDate'}}</td>
<td><a href="#" class="btn btn-sm btn-primary">Manage</a></td>
</tr>
</table>
</div>
module
(function () {
'use strict';
angular.module('app', [
// Angular modules
// Custom modules
// 3rd Party Modules
]);
})();
controller
(function () {
'use strict';
angular
.module('app')
.controller('controller', controller);
//controller.$inject = [''];
function controller() {
/* jshint validthis:true */
var vm = this;
vm.name = "greg";
vm.trips = [{
name: "US trip",
created: new Date()
}, {
name: "World trip",
created: new Date()
}];
}
})();
Monday, February 15, 2016
class in li make it active
<ul class="menu">
<li class="active"><a href="#">home</a></li>
<li><a href="#">about</a></li>
<li><a href="#">contact</a></li>
</ul>
css file below: you need . after li
.menu li.active {
font-weight:bold;
}
Sunday, February 14, 2016
Angular JS VS2015 example
Angular JS bare minimal - index,html, module, controller
{
"name": "ASP.NET",
"private": true,
"dependencies": {
"angularjs": "~1.5.0",
"bootstrap": "~3.3.6",
"jquery": "~2.2.0",
"jquery-validation": "~1.14.0",
"jquery-validation-unobtrusive": "~3.2.5",
"underscore": "~1.8.3"
}
}
index.html
<!doctype="html">
<html>
<head>
<title>the world</title>
<script src="lib/angularjs/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controller.js"></script>
</head>
<body ng-app="app">
<h2>The worldf</h2>
<div ng-controller="controller as vm">
{{ vm.name }}
</div>
<p>this web site</p>
</body>
</html>
app.js --- module (difference between module and controller is module is a setter with [])
function () {
'use strict';
//creating module
angular.module('app', []);
})();
controller.js -- controller
(function () {
'use strict';
//getting existing module
angular
.module('app')
.controller('controller', controller);
//controller.$inject = [''];
function controller() {
/* jshint validthis:true */
var vm = this;
vm.name = 'greg';
}
})();
RevillWeb Angular JS tutorial
Visual studio 2015 add index.html
{
app.UseDefaultFiles();
app.UseStaticFiles();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
visual studio 2015 extension
add new file --- use shift F2 to add a new file to project
web essentials 2015
Saturday, February 13, 2016
sublime for AngularJS
Friday, February 12, 2016
Loupe javascript event loop
Webapi in Web browser
Call back stack
If empty, put things in task queue to call stack
Thursday, February 11, 2016
Provider
Only type can be put in app.config
Can set values on service application wide before they can be injected to any part of application.
This.$get is required, must return an object containing all public available methods
Variables attached to 'this' are able to set in app.config
'var' are not
Service vs factory, constant vs value
Factory return an object with methods
Service has to be initiated with new
Constant available during angularjs configuration phase
Value available during run time phase
Wednesday, February 10, 2016
asp,net 5
one time binding - Angular JS 1.3 removed from the $Watch list page 56 AngualrJS for .Net developers in 24 hours, $digest cycle, "dirty list"
<div ng-controller="Order as vm">
<input type="text" ng-model="vm.orderTotal" />
<p>{{ ::vm.orderTotal }}</p>
</div>
Prototypal inheritance - page 53 AngualrJS for .Net developers in 24 hours,
<!-- View without ControllerAs syntax that has nested scopes.-->
<div ng-controller="Order">
<input type="text" ng-model="orderTotal" />
<div ng-if="showDetails">
<input type="text" ng-model="orderTotal" />
</div>
</div>
You can avoid all of that mess by using ControllerAs syntax:
<!-- View with nested scopes, but with ControllerAs.-->
<div ng-controller="Order as vm">
<input type="text" ng-model="vm.orderTotal" />
<div ng-if="showDetails">
<input type="text" ng-model="vm.orderTotal" />
</div>
</div>
Now the two models explicitly share the same scope of the controller’s alias,
vm
, and we’ve tamed the scope craziness.
Tuesday, February 9, 2016
John papa angular js style guide
http://www.johnpapa.net/angular-style-guide/
IIFE immediately invoked function experssion
(function(){
"use strict";
var app = angular.module("musicApp", []);
app.controller('ArtistController', [artistController]);
function artistController() {
var vm = this;
vm.name = 'Foo';
};
}());
define controller as vm to no longer inject $scope
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script src="scripts/angular.js"></script>
<script src="scripts/app.js"></script>
</head>
<body>
<div ng-app="musicApp">
<div ng-controller="ArtistController as vm">
{{vm.name}}
</div>
</div>
</body>
</html>
var app = angular.module("musicApp", []);
app.controller('ArtistController', [artistController]);
function artistController() {
var vm = this;
vm.name = 'Foo';
};
AngualrJS for .Net developers in24 hours hours 5 page 43
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script src="scripts/angular.js"></script>
<script src="scripts/app.js"></script>
</head>
<body>
<div ng-app="musicApp">
<div ng-controller="ArtistController">
{{artist}}
<button ng-click="pumpkins()">Pumpkins</button>
<button ng-click="rise()">Rise</button>
</div>
</div>
</body>
</html>
Angular JS module, controller, $scope
angular.module to construct the module
you will also put dependencies in []
inside module has controller
controller is also on html file (this portion of web page is in my control with my $scope)
$scope send data over to html file using {{xxxx}}
xxxx is inside $scope
display data on web page.
Uncaught Error: [$injector:nomod] Module 'xxxx' is not available!
http://www.johnpapa.net/easy-fix-to-a-common-angular-module-error/
Correct line
angular.module('musicApp',[])
You need to have ",[]" when specify a module
Uncaught Error: [$injector:nomod] Module 'musicApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.9/$injector/nomod?p0=musicApp
angular.js:4470 Uncaught Error: [$injector:modulerr] Failed to instantiate module musicApp due to:
Error: [$injector:nomod] Module 'musicApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.9/$injector/nomod?p0=musicApp
the something in `ng-app="something"` in your html must match the name of your main app module.
I got the same error, but it was because I forgot the angular.module("name", [])
you cant forget the [] or it wont inject and dependencies.
below is the app.js file
angular.module('musicApp',[])
.controller('ArtistController', ['$scope', ArtistController]);
function ArtistController($scope) {
$scope.artist='Foo'
}
below is the index.html file
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script src="scripts/angular.js"></script>
<script src="scripts/app.js"></script>
</head>
<body>
<div ng-app="musicApp">
<div ng-controller="ArtistController">
{{artist}}
</div>
</div>
</body>
</html>
Asp.net 5
https://get.asp.net/
AngularJS and IE
Saturday, February 6, 2016
CORS cross origin request
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works
Web api testing tool
Postman getpostman.com
SoapUI
Swagger.IO
Fiddler
Friday, February 5, 2016
Firebase.com 3 way binding
3 way binding, update database
Thursday, February 4, 2016
Wednesday, February 3, 2016
Knockout js tutorial
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-1