private void ShowAllDocumentsButton_Click(object sender, EventArgs e)
{
string SearchTerm = SearchInput.Text;
StatusText.Text = "Searching...";
SearchResultsList.Items.Clear();
// we only want to find contentTypes which are checked.
ArrayList contentTypes = new ArrayList();
foreach (CheckBox box in ContentTypePanel.Controls)
{
if (box.Checked)
{
contentTypes.Add(box.Text);
}
}
Task> task =
Task.Run>(async () => await ShowAllAsync(SearchTerm, contentTypes));
DocumentSearchResult theDocs = task.Result;
try
{
foreach (var doc in theDocs.Results.ToArray().OrderBy(n => n.Document.Id))
{
var item = new ListViewItem(doc.Document.Id);
item.SubItems.Add(doc.Document.Title);
item.SubItems.Add((doc.Document.Description));
item.SubItems.Add(doc.Document.Content);
item.SubItems.Add(doc.Document.Tags.Join(","));
item.SubItems.Add(doc.Document.ContentType);
SearchResultsList.Items.Add(item);
}
StatusText.Text = "Search Complete";
SearchResultsCount.Text = $"{SearchResultsList.Items.Count}";
}
catch (Exception ex)
{
MessageBox.Show((ex.Message));
}
}
private async Task> ShowAllAsync(string searchTerm, ArrayList contentTypes)
{
return await Task.Run>(() =>
{
AzureSearchClient client = AzureSearchClient.ForQueries();
SearchParameters searchParams = new SearchParameters { Top = 9999 };
List filters = new List();
foreach (string contentType in contentTypes)
{
filters.Add($"contentType eq '{contentType}'");
}
searchParams.Filter = $"siteId eq {LssEnvironment.CurrentSite.ID}";
if (filters.Any())
searchParams.Filter += $" and {filters.WhereNotNull().Join(" or ")}";
var searchClient = AzureSearchClient.ForQueries();
Microsoft.Azure.Search.Models.DocumentSearchResult theDocs = client.SearchDocuments(searchTerm, searchParams);
return theDocs;
});
}
private async Task CheckSitemapUrlAsync(string theUrl)
{
return await Task.Run
(() =>
{
ResultEntry result = new ResultEntry();
HttpStatusCode resultCode = HttpStatusCode.OK;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(theUrl);
req.Accept = "text/html";
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (CanCheckInternalLinks(theUrl))
{
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
result.Html = reader.ReadToEnd();
}
}
response.Close();
}
catch (Exception ex)
{
resultCode = GetHttpStatusCode(ex);
}
result.Url = theUrl;
result.Status = resultCode;
return result;
});
}
---------------------HTML-------------------
<body ng-app="MyApp" ng-controller="MainCtrl">
<div class="container">
<form role="form">
<div class="formSection">
<h3>Binding a model</h3>
<div class="form-group">
<label >Address:</label>
<input class="form-control" id="address" placeholder="address" ng-model="address">
<button class="btn btn-default" ng-click="onAddressClick()">Go</button>
</div>
</div>
<div class="formSection">
<h3>Read addresses from server JSON file</h3>
<div class="form-group">
<label>Address list:</label>
<button class="btn btn-default" ng-click="onGetAddressesClick()">Go</button>
<ul class="addressList">
</ul>
</div>
</div>
<div class="formSection">
<h3>Read random address from WCF service</h3>
<div class="form-group">
<label >Address:</label>
<label class=" " id="addressRandom" ng-bind= "randomAddress" > </label>
<button class="btn btn-default" ng-click="onGetRandomAddressClick()">Go</button>
</div>
</div>
</form>
</div>
<div class="container">
<h4 class="mapDivTitle"></h4>
<div class='MapDiv'> <div id="map_canvas" ></div> </div>
</div>
</body>
---------------------Script-------------------
var myApp = angular.module('MyApp', ["ngRoute"]);
myApp.controller('MainCtrl', function ($scope, $http) {
$scope.address = "Raleigh,NC";
$scope.JSON = "";
$scope.serviceString = "";
$scope.randomAddress = "";
// Goto address typed in
$scope.onAddressClick = function () {
codeAddress($scope.address);
};
// Goto address typed in
$scope.onGetAddressesClick = function () {
$scope.getJSON();
};
// Get address list from JSON server file
$scope.getJSON = function () {
;
$http.get('data/data.json')
.success(function (data) {
$scope.JSON = data;
// fill up address list.
$('.addressList li').remove();
$.each(data, function (index) {
$.each(data[index], function (key, theAddress) {
var $li = $("<li>" + theAddress.name + "</li>");
$li.attr('address', theAddress.address);
$li.click(function () {
$('.addressList li').removeClass('activeItem');
$(this).addClass('activeItem');
codeAddress($(this).attr('address'));
});
$('.addressList').append($li);
});
});
if ($('.addressList li:first').length > 0)
$('.addressList li:first').click();
})
.error(function (data, status) {
alert('error:' + data + ' ---' + status);
;
}
);
}
$scope.onGetRandomAddressClick = function () {
$scope.callService();
};
// Call WCF Rest service
$scope.callService = function () {
;
$http.get('services/service.svc/json')
.success(function (data) {
codeAddress(data);
$scope.randomAddress = data;
})
.error(function (data, status) {
alert('error:' + data + ' ---' + status);
;
}
);
}
// init google map api...
initializeMap();
// show default address
codeAddress($scope.address);
});
// Custom Directive - Attribute
myApp.directive("blueColor", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
$(element).css('color', 'blue');
}
}
});
// Custom Directive - Element
myApp.directive("customDirective", function () {
return {
restrict: "E",
link: function (scope, element, attrs) {
$(element).css('color', 'red');
}
}
});
// RouteProvider
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/view1/:param', {
templateUrl: 'templates/view1.html',
controller: 'View1Controller'
}).
when('/view2/:param', {
templateUrl: 'templates/view2.html',
controller: 'View2Controller'
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('View1Controller', function ($scope, $routeParams) {
$scope.message = 'This is View 1 Page';
console.log("params(1):" + $routeParams.param);
});
myApp.controller('View2Controller', function ($scope, $routeParams) {
$scope.message = 'This is View 2 Page';
console.log("params(2):" + $routeParams.param);
});
// Google Maps
function initializeMap() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
$('.mapDivTitle').text(results[0].formatted_address);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
---------------------HTML(App)-------------------
<template>
<require from="app.css"></require>
<!--Import map template component class-->
<require from="map"></require>
<!--Main title message from app class-->
<div class="mainContainer">
<div class="container listContainer">
<h3>${message}</h3>
<div class="formSection">
<!--For each address, show a selection item with image-->
<ul class="addressList">
<li repeat.for="address of addressArray" click.trigger="showLocation($event)" data-address=${address.address}> <img src=${address.image} /> <a href="#" class="addressName">${address.name}</a></li>
</ul>
</div>
</div>
<div class="container">
<!--Map template component to show location-->
<map view-model.ref="map"></map>
</div>
</div>
</template>
---------------------Script(App)-------------------
export class App {
constructor() {
this.message = "Select a city...";
this.addressArray = [
{"name":"Fenway Park","address":"Fenway Park, Boston","image":"../aureliasample/src/images/fenway.jpg"},
{"name":"PNC Arena","address":"1400 Edwards Mill Rd, Raleigh, NC 27607","image":"../aureliasample/src/images/pnc.jpg"},
{"name":"Statue of Liberty","address":"Statue of Liberty in New York, USA","image":"../aureliasample/src/images/statue.jpg"},
{"name":"Walt Disney World","address":"Walt Disney World","image":"../aureliasample/src/images/walt.jpg"},
{"name":"Times Square","address":"Times Square","image":"../aureliasample/src/images/times.jpg"},
{"name":"Niagara Falls","address":"Niagara Falls","image":"../aureliasample/src/images/niagara.jpg"}
];
}
attached() {
// once DOM is attached, show default city in map window
var self = this;
setTimeout (function () {
self.map.codeAddress(self.addressArray[0].address);
},500);
}
// User clicked on an address, show location on Map template component
showLocation(event)
{
var $li = $(event.currentTarget);
this.map.codeAddress($li.attr('data-address'));
}
}
---------------------HTML(Map)-------------------
<template ref="mapElement" >
<!--Import map style sheet-->
<require from="map.css"></require>
<div class="container" >
<div ref="title" class="mapDivTitle">${title}</div>
<!--Element which map will be drawn-->
<div class='MapDiv'> <div id="map_canvas"></div> </div>
</div>
</template>
---------------------Script(Map)-------------------
export class Map {
constructor() {
this.self = this;
this.geocoder = undefined;
this.map = undefined;
this.title = "";
}
// once DOM is attached, init the Google Map API
attached() {
this.$element = $(this.mapElement);
this.initializeMap();
}
// Google Maps
initializeMap() {
this.geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
codeAddress(address) {
var self = this;
this.title = address;
this.geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
---------------------HTML-------------------
<body ng-app="MyApp" ng-controller="MainCtrl">
<!--nRoute will handle these options-->
<ul class="mainNav"><li><a href="#/WidgetView1/About" name="group1">Help Tips</a></li><li><a href="#/WidgetView2/About" name="group1">Sticky Notes</a></li></ul>
<div class="container">
<div ng-view></div>
</div>
</body>
---------------------Script-------------------
var myApp = angular.module('MyApp', ["ngRoute"]);
myApp.controller('MainCtrl', function ($scope, $http) {
});
// RouteProvider
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/WidgetView1/:param', {
templateUrl: 'templates/WidgetView1.html',
controller: 'WidgetView1Controller'
}).
when('/WidgetView2/:param', {
templateUrl: 'templates/WidgetView2.html',
controller: 'WidgetView2Controller'
}).
otherwise({
redirectTo: '/'
});
}]);
/* Display the custom JQuery Info Popup widget */
myApp.controller('WidgetView1Controller', function ($scope, $routeParams) {
var Help = $('#HelpTip1');
Help.Ex_HelpTip({
Title: 'Interesting Facts',
Content: '<div><img src="/app/widgets/eagle.png" style="width:64px;" /> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. <a href="http://google.com">Visit our site</a> Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex </div>',
Anchor: $('#Anchor1'),
Location: 'Bottom',
OpenDirection: 'right',
SmallSize: false,
HelpWindowIcon: 'helpreminder.png'
});
Help.show();
});
/* Display the custom JQuery Sticky Note widget */
myApp.controller('WidgetView2Controller', function ($scope, $routeParams) {
var stickNotes = $('#myNotes');
stickNotes.Ex_StickyNote({
Title: 'My Notes',
Content: "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium \n\r\n Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. ",
TimeStamp: ""
});
// show hide notes
$scope.showNotes = function () {
stickNotes.data('Ex_StickyNote').Show(!stickNotes.is(':visible'));
};
var stickAction = $('#myAction');
stickAction.Ex_StickyNote({
Title: 'Action Items',
Content: "Vivamus mauris nibh, accumsan at efficitur a, dignissim eget sem. Nulla ante sem, gravida nec scelerisque at, laoreet ac ipsum. Sed accumsan tortor vitae ante iaculis, a scelerisque velit vehicula. Sed tempor velit est, ut ultrices ante egestas sit amet. Maecenas venenatis, augue ac faucibus maximus, enim lacus faucibus lacus, ut convallis orci massa id erat",
TimeStamp: ""
});
// show hide notes
$scope.showAction = function () {
stickAction.data('Ex_StickyNote').Show(!stickAction.is(':visible'));
};
});
---------------------HTML-------------------
<body ng-app="MyApp" ng-controller="SignalRCtrl as ctrl">
<div class="container sender ">
<span class="sent"> Client sending number </span> <h2 id="theValue">0</h2> <span class="sent"> to server...</span>
<br />
<md-slider-container class="sliderContainer">
<md-slider flex="" min="1" max="500" ng-model="maxValue" aria-label="red" id="red-slider">
</md-slider>
<md-input-container>
<input id="maxValue" flex="" type="number" ng-model="maxValue" aria-label="red" aria-controls="red-slider" value="10">
</md-input-container>
</md-slider-container>
<span class="sliderLabel">Slide to set <strong>maximum</strong> value</span>
</div>
<div class="container receiver">
<h2 class="chartDivTitle">SignalR Data</h2>
<span>Received data from server</span>
<div id='chartDiv'> </div>
</div>
<md-button class="md-primary md-raised demo-dialog-open-button resetChart" ng-click="ctrl.resetChart($event)">
Reset Chart
</md-button>
<!--JQuery -->
<script src="Scripts/jquery-1.6.4.min.js" ></script>
<!--JQ Plot-->
<link href="Scripts/jquery.jqplot.min.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery.jqplot.min.js" type="text/javascript"></script>
<script src="Scripts/jqplot.cursor.min.js" type="text/javascript"></script>
<script src="Scripts/jqplot.dateAxisRenderer.min.js" type="text/javascript"></script>
<script src="Scripts/jqplot.highlighter.min.js" type="text/javascript"></script>
<script src="Scripts/jqplot.trendline.min.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/jqplot.canvasTextRenderer.min.js"></script>
<script type="text/javascript" src="Scripts/jqplot.canvasAxisTickRenderer.min.js"></script>
<script type="text/javascript" src="Scripts/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="Scripts/jqplot.barRenderer.min.js"></script>
<script src="Scripts/jqplot.canvasAxisLabelRenderer.min.js" type="text/javascript"></script>
<!--Angular -->
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/svg-assets-cache.js'></script>
<script src='https://cdn.gitcdn.link/cdn/angular/bower-material/v1.1.1/angular-material.js'></script>
<!--SignalR -->
<script src="Scripts/jquery.signalR-2.0.0.js"></script>
<!--Autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<!-- application js file -->
<script src="app.js"></script>
</body>
---------------------Script-------------------
// Angular init
(function() {
'use strict';
angular.module('MyApp',['ngMaterial'])
.controller('SignalRCtrl', SignalRCtrl);
function SignalRCtrl($mdPanel, $scope) {
this._mdPanel = $mdPanel;
var self = this;
$scope.maxValue = 5;
// this array will hold the data
this.plotData = [0];
this.ThePlotChart = undefined;
var chat = $.connection.chatHub; // Declare a proxy to reference the hub.
// This function will be called each time a value is sent from server..
chat.client.broadcastMessage = function (randomVal) {
$('#theValue').text(randomVal);
if (self.plotData.length > 100)
self.plotData = [0];
// add the data point
self.plotData.push(parseInt(randomVal));
// plot it!
self.ThePlotChart = self.renderChart(self.ThePlotChart, self.plotData);
};
// Start the connection.
$.connection.hub.start().done(function () {
// every 2 seconds, generate a new random value and send to server
setInterval(function () {
var maxValue = $("#maxValue").val();
var randomVal = Math.floor(Math.random() * (maxValue - 1 + 1) + 1);
chat.server.send(randomVal);
}, 2000);
});
// default plot
this.ThePlotChart = this.renderChart(this.ThePlotChart, this.plotData);
}
SignalRCtrl.prototype.resetChart = function () {
this.plotData = [0];
}
/* JQPlot */
SignalRCtrl.prototype.renderChart = function (ThePlotChart, plotData) {
if (ThePlotChart) {
ThePlotChart.destroy();
}
$('#chartDiv').show();
var plot = $.jqplot('chartDiv', [plotData], {
title: {
text: 'SingleR Data',
show: false,
fontSize: '100%',
textColor: 'white'
},
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions: {
angle: -30,
fontSize: '10pt',
textColor: (function () {
return '#333';
})()
}
},
seriesDefaults: {
renderer: $.jqplot.MeterGaugeRenderer,
rendererOptions: {
smooth: true
},
step: true,
markerOptions: { show: false },
trendline: {
show: true,
color: 'lightcoral'
}
},
axes: {
xaxis: {
label: "Index",
pad: 0
},
yaxis: {
label: "Value"
}
}
});
return plot;
}
})();
---------------------HTML-------------------
<div class="header">
<h3> Enter full URL, then click Go button to shorten the url. </h3> <br />
</div>
<div id="mainDiv1" class="contentDiv"></div>
<div id="mainDiv2" class="contentDiv"></div>
<div id="mainDiv3" class="contentDiv"></div>
---------------------Script-------------------
var ShortenComponent = React.createClass({
getInitialState : function () {
;
},
change: function(event){
this.props.url = event.target.value
},
openWindow: function() {
window.open(this.props.shortURL,"_blank");
},
shortenIt: function (longURL) {
var self = this;
var site = React.findDOMNode(this.refs.siteHost);
$(site).fadeIn().removeClass('hidden');
var theUrl = 'http://free.pagepeeker.com/v2/thumbs.php?size=m&url=' + self.props.url;
$(site).find('img').attr('src',theUrl);
gapi.client.load('urlshortener', 'v1', function () {
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': self.props.url
},
'key': "AIzaSyDHG_7HuCu1ESY_dUSOu3Dyqc1wA1dcgB0"
});
var resp = request.execute(function (resp) {
if (resp.error) {
alert("Shorten URL failed." + resp.error.message);
} else {
self.props.shortURL = resp.id;
self.forceUpdate();
$(site).fadeIn().removeClass('hidden');
var theUrl = 'http://free.pagepeeker.com/v2/thumbs.php?size=m&url=' + self.props.url;
$(site).find('img').attr('src',theUrl);
}
});
});
},
render: function() {
return (
<form className="form-horizontal mainDiv">
<label htmlFor="urlName" className="control-label">Enter URL:</label>
<input className="urlValue form-control" id="urlName" name="urlName" placeholder="URL" defaultValue={this.props.url} onChange={this.change} />
<button type="button" className="btn btn-primary btn-sm shortenBtn" onClick={this.shortenIt}>Go</button>
<div className="siteHost hidden" ref="siteHost" onClick={this.openWindow}>
<img src="" />
<a className="shortURL text-success" href="#" >{this.props.shortURL}</a>
</div>
</form>
);
}
});
// Create 3 seperate URL Shortner instances
React.render( <ShortenComponent url="http://huffingtonpost.com"/>, document.getElementById('mainDiv1'));
React.render(<ShortenComponent url="http://dell.com" />, document.getElementById('mainDiv2'));
React.render(<ShortenComponent url="https://amazon.com" />, document.getElementById('mainDiv3'));
---------------------HTML-------------------
<body >
<div class="container">
<form role="form">
<div class="formSection">
<div class="form-group">
<h3 class="title">Show students</h3>
<button class="btn btn-default" data-bind="click:getStudentsClick">Go</button> <br />
<ul class="studentList" data-bind= "foreach : studentsArray">
<li data-bind="click:$root.showStudentClick"> <img data-bind="attr:{src: '../content/images/' + face}" /><div class="studentName" data-bind="text:name"></div></li>
</ul>
<div class="attribute">Images courtesy of <a href="javascript: window.open('http://www.vectoropenstock.com', '_blank');">Vector Open Stock</a></div>
</div>
</div>
<div class="formSection">
</div>
<div class="formSection">
</div>
</form>
</div>
<div class="container">
<h4 class="chartDivTitle"></h4>
<div id='chartDiv'> </div>
</div>
</body>
---------------------Script-------------------
$(document).ready(function () {
// Activates knockout.js
ko.applyBindings(new AppViewModel());
});
/* Knockout */
function AppViewModel() {
// Data
var self = this;
self.studentsArray = ko.observableArray([]);
self.plotChart = undefined;
// show the student grades in chart
self.showStudentClick = function (student,event) {
var plotData = [[null]];
$.each(student.grades, function (i, grades) {
plotData.push([grades.year,grades.grade]);
});
self.plotChart = renderChart(self.plotChart, 'chartDiv', plotData);
$('.chartDivTitle').text(student.name);
$('.studentList li').removeClass('activeItem');
$(event.delegateTarget).addClass('activeItem');
};
// respond to get students (go) button by calling for server side JSON file
self.getStudentsClick = function () {
$.getJSON("data/data.json", function (allData) {
eval("self.studentsArray(" + JSON.stringify(allData.studentsArray) + ");");
$('.attribute').fadeIn();
if ($('.studentList li:first').length > 0)
$('.studentList li:first').click();
});
};
}
/* JQPlot */
function renderChart(ThePlotChart, ChartElement, plotData) {
if (ThePlotChart) {
ThePlotChart.destroy();
}
$('#' + ChartElement).show();
ThePlotChart = $.jqplot(ChartElement, [plotData], {
title: {
text: '',
show: false,
fontSize: '100%',
textColor: 'white'
},
grid: {
background: '#ffffff'
},
series: [{
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barWidth: 30,
varyBarColor: true
}
}],
seriesDefaults: {
trendline: {
show: false
}
},
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer,
tickOptions: {
angle: -30,
fontSize: '10pt',
textColor: (function () {
return '#333';
})()
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
},
yaxis: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
label: 'Grade',
tickOptions: {
fontSize: '10pt',
textColor: (function () {
return '#333';
})()
},
labelOptions: {
textColor: (function () {
return '#333';
})()
}
}
}
});
return ThePlotChart;
}
---------------------HTML-------------------
<body >
<div class="container">
<form role="form">
<div class="formSection">
<h3>What do you want to find?</h3>
<div class="form-group">
<label>Search for:</label>
<input class="form-control" id="searchTerm" placeholder="Search term(s)" data-bind="value:searchTerm"/>
<button class="btn btn-default" data-bind="click:getStoriesClick">Go</button>
<ul class="storiesList" data-bind= "foreach : storiesArray">
<li data-bind="click:$root.showStoryClick"> <div class="imgHost"> <img data-bind="attr:{src: (pagemap != undefined) && (pagemap.cse_thumbnail != undefined) && (pagemap.cse_thumbnail.length > 0) ? pagemap.cse_thumbnail[0].src : '../content/images/noimage.png' }" /> </div> <div class="storyName" data-bind="html:htmlTitle"></div></li>
</ul>
</div>
</div>
<div class="formSection">
</div>
<div class="formSection">
</div>
</form>
</div>
<div class="container">
<h4 class="storyDivTitle"></h4>
<div id='storyDiv'>
<div class="imgHost">
<img />
</div>
<div class="snippet"></div>
<a class="link"></a>
</div>
</div>
</body>
---------------------Script-------------------
// load google api
google.load('search', '1');
$(document).ready(function () {
// Activates knockout.js
ko.applyBindings(new AppViewModel());
});
/* Knockout */
function AppViewModel() {
// Data
var self = this;
self.storiesArray = ko.observableArray([]);
self.searchTerm = "";
// show the story
self.showStoryClick = function (story, event) {
$('#storyDiv .snippet').html(story.htmlSnippet);
var image = (story.pagemap != undefined) && (story.pagemap.cse_image != undefined) && (story.pagemap.cse_image.length > 0) ? story.pagemap.cse_image[0].src : '/content/images/noimage.png'
$('#storyDiv img').attr('src', image);
$('#storyDiv .link').attr('href', "javascript: window.open('" + story.link + "', '_blank');").text(story.displayLink);
$('.storyDivTitle').html(story.htmlTitle);
$('.storiesList li').removeClass('activeItem');
$(event.delegateTarget).addClass('activeItem');
};
// respond to get stories (go) button by calling google api search
self.getStoriesClick = function () {
$('.storiesList li').remove();
GoogleSearch(self.searchTerm, function (results) {
// validate pagemap member
if (results.items != undefined) {
$.each(results.items, function (i, item) {
if (item.pagemap == undefined)
results.items[i].pagemap = new Object();
});
eval("self.storiesArray(" + JSON.stringify(results.items) + ");");
}
});
if ($('.storiesList li:first').length > 0)
$('.storiesList li:first').click();
};
}
// perform a custom google search and return results..
function GoogleSearch(Search, Callback) {
// Search Engine
// All cx=002283654265514449813:-zrrncnpc2i
var Key = "";
var ImageTypeArgs = '';
var cx = "002283654265514449813:-zrrncnpc2i"; // All
var TargetDateRestrict = ''; // wide open
Key = 'AIzaSyBQ2v0XRzvgo-REOXM-H8YlODoV3mzVTRc';
var url = 'https://www.googleapis.com/customsearch/v1?q=' + Search + '&callback=?' + '&cx=' + cx + TargetDateRestrict + ImageTypeArgs;
url = (url + ('&key=' + Key)); // add the api key
url = (url + '&filter=1'); // no duplicates
url = (url + '&start=' + 1); // Start Index
$.getJSON(url, '', ContentFound); // call google.
function ContentFound(response) {
if (response.error) {
alert(response.error.message);
}
Callback(response);
}
}
---------------------HTML-------------------
<body>
<div class="container">
<form role="form">
<div class="formSection">
<div class="form-group">
<h3 class="title">Show Employees</h3>
<button type ="button" class="getEmployeesBtn btn btn-primary">Go</button> <br />
<div id="employeeList-content"></div>
</div>
</div>
</form>
</div>
<div class="container">
<h4 class="gridDivTitle"></h4>
<div class='KendoGrid_Ex' id='theGrid'></div>
</div>
</body>
<!-- Handlebar templates-->
<script id="employeeList-template" type="text/x-handlebars-template">
<ul class="employeeList">
{{#employees}}
<li employeeDetails ="{{json this}}"> <img src = '../content/images/{{face}}' /><div class="employeeName">{{name}}</div></li>
{{/employees}}
</ul>
<div class="attribute">Images courtesy of <a href="javascript: window.open('http://www.vectoropenstock.com', '_blank');">Vector Open Stock</a></div>
</script>
---------------------Script-------------------
$(document).ready(function () {
// init the kendo grid
var grid = $('#theGrid');
var columns = [
{ field: "date", title: "Date", type: 'date', sortable: { allowUnsort: false }, width: "100px", headerAttributes: { style: "font-weight:bold" } },
{
field: "description", title: "Description", sortable: { allowUnsort: false },
headerAttributes: { style: "font-weight:bold" }
},
{
field: "amount", title: "Amount", width: "100px", format: "{0:c}", headerAttributes: { style: "font-weight:bold" }, sortable: { allowUnsort: false }
},
{ field: "notes", title: "Notes", sortable: false, filterable: false, encoded: false, headerAttributes: { style: "font-weight:bold;" } }];
// init the custom JQuery Grid widget (Based upon Kendo UI Grid)
grid.KendoGrid_Ex({
captionText: 'Employee Expenses',
columnSchema: columns,
OnDataBound: function (e) {
// auto select the 1st on in list only if no row is selected
var firstRow = $('.KendoGrid_Ex').find('table tr[role="row"]:eq(1)'); // skips header row
if ((firstRow.length > 0) && ($('.KendoGrid_Ex').find('.grid-row-selected').length == 0)) {
firstRow.click();
}
}
});
// show the employee expenses in grid
$(document).on("click", ".employeeList li", function (item) {
var employee = jQuery.parseJSON ($(item.currentTarget).attr('employeeDetails'));
$('.gridDivTitle').text(employee.name);
var grid = $('.KendoGrid_Ex .gridhost').data("kendoGrid");
grid.dataSource.data(employee.expenses);
$('.employeeList li').removeClass('activeItem');
$(item.currentTarget).addClass('activeItem');
});
// respond to employees (go) button by calling for server side JSON file
$('.getEmployeesBtn').click(function () {
$.getJSON("data/data.json", function (allData) {
// Let's init the Handlebar template and bind to data context
var source = $("#employeeList-template").html();
var template = Handlebars.compile(source);
var theTemplate = template(allData);
$("#employeeList-content").html(theTemplate);
if ($('.employeeList li:first').length > 0) {
$('.employeeList li:first').click();
$('.employeeList').fadeIn();
$('.attribute').fadeIn();
}
});
});
// simple helper to convert object to JSON
Handlebars.registerHelper('json', function (context) {
return JSON.stringify(context);
});
});
---------------------HTML-------------------
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.4.1</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.1/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.4.1/jasmine.css">
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script src="lib/jquery.cookie.js"></script>
<script src="lib/moment.min.js"></script>
<script src="lib/jasmine-2.4.1/jasmine.js"></script>
<script src="lib/jasmine-2.4.1/jasmine-html.js"></script>
<script src="lib/jasmine-2.4.1/boot.js"></script>
<!-- source files to test... -->
<script src="src/utilities.js"></script>
<!-- Jasmine spec files... -->
<script src="spec/UtilitiesSpec.js"></script>
</head>
<body>
</body>
</html>
---------------------Script-------------------
/*
* Jasmine test runner for Utility library functions
* Jasmine version 2.4.1
*/
describe("Utility Library - Helper Functions", function () {
var util = new Utility();
describe("GetuserSession", function () {
it("should return session Id", function () {
$.cookie('SessionId', "ABC", { path: '/' });
var session = util.GetUserSession();
expect(session).toEqual("ABC");
});
});
xdescribe("CopyTextToClipboard", function () {
xit("should copy text into clipboard", function () {
var result = util.copyTextToClipboard("ABC");
expect(result).toBeTruthy();
});
});
describe("FormatJSONDate", function () {
it("should format value to friendly date", function () {
var result = util.FormatJSONDate("05/21/2016");
expect(result).toBeDefined();
});
it("should return Invalid Date when applicable", function () {
var result = util.FormatJSONDate("Junk");
expect(result).toMatch("Invalid Date");
});
});
describe("GetValidationPath", function () {
it("should return full path to validation method ValidateURI", function () {
var result = util.GetValidationPath("ValidateURI");
expect(result).toBeDefined();
});
});
describe("GetImagesPath", function () {
var result;
it("should return full path to image user.png", function () {
result = util.GetImagesPath("user.png");
expect(result).toBeDefined();
});
it("return value should end with image file name", function () {
expect(result).endsWithString(".png");
});
});
describe("ReplaceAllStr", function () {
it("should replace all '#' chars with '*'", function () {
var result = util.replaceAllStr("ABC##D#", "#", "*");
expect(result).toEqual("ABC**D*");
});
});
describe("Encode", function () {
it("should encode string to Base64 format", function () {
var result = util.Encode("ABC");
expect(result).toEqual("QUJD");
});
});
describe("Decode", function () {
it("should decode Base64 string to clear text format", function () {
var result = util.Decode("QUJD");
expect(result).toEqual("ABC");
});
});
describe("Pad", function () {
it("should pad 2 zeros to initial string", function () {
var result = util.Pad("ABC", 5);
expect(result).toEqual("ABC00");
});
});
describe("GetGUID", function () {
var result;
beforeEach(function () {
spyOn(util, 'Pad');
result = util.GetGUID();
});
it("should return a unique Guid format number", function () {
expect(result).toBeDefined();
console.log(result);
});
it("should have called 'Pad' function 5 times", function () {
expect(util.Pad).toHaveBeenCalledTimes(5);
});
});
describe("HighlightJSON", function () {
var json = [{ "_id": "57b1e55863d493321b18f063", "index": 0, "guid": "3859b241-b0e3-47b0-ae1e-b682cafb190a", "isActive": false, "balance": "$3,814.62", "picture": "http://placehold.it/32x32", "age": 33, "eyeColor": "green", "tags": ["Lorem", "ex", "sunt", "qui", "minim", "occaecat", "non"], "friends": [{ "id": 0, "name": "Maude Estrada" }, { "id": 1, "name": "Audrey Parks" }, { "id": 2, "name": "Wendi White" }] }];
var result;
it("should color code / highlight JSON", function () {
result = util.HighlightJSON(json);
expect(result).toBeDefined();
});
it("should return HTML markup code", function () {
var containsSpan = result.indexOf("span") >= 0;
expect(containsSpan).toEqual(true);
});
});
});
// Custom Matcher
beforeEach(function () {
jasmine.addMatchers({
endsWithString: function () {
return {
compare: function (actual, expected) {
return {
pass: actual.indexOf(expected, actual.length - expected.length) !== -1
};
}
};
}
});
});