How to populate dropdownlist using WCF Rest AngularJs - c#

How to populate dropdownlist using WCF Rest Service:
First, this is my code to get service:
service.js
(function (app) {
app.service("GetCategoryService", function ($http) {
this.GetCategory = function () {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetCategory/");
};
});
})(angular.module('entry'));
Entry.Ctrl
(function (app) {
'use strict';
app.controller('entryCtrl', entryCtrl);
entryCtrl.$inject = ['$scope'];
function entryCtrl($scope) {
$scope.pageClass = 'page-entry';
//To Get Category
$scope.Category = function () {
var promiseGet = GetCategoryService.GetCategory();
promiseGet.then(function (pl) { $scope.GetCategory = pl.data },
function (errorPl) {
console.log('Some Error in Getting Records.', errorPl);
});
}
}
})(angular.module('entry'));
This is entry.html
<div class="dropdown">
<select ng-model="Category" ng-options="item.ITEM_TEXT for item in Category"></select>
</div>
WCF Output JSON like:
[{"ITEM_TEXT":"INTERNAL APP"},{"ITEM_TEXT":"INTERNAL IT"}]
I don't know how to passing this to html, what I'm doing like this is not working. please help. thank

Make sure you have set ng-model different from the array name, also inject the service into your controller,
entryCtrl.$inject = ['$scope', 'GetCategoryService'];
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.Category = [{"ITEM_TEXT":"INTERNAL APP"},{"ITEM_TEXT":"INTERNAL IT"}];
}
]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select ng-model="selected" ng-init="selected = Category[0]" ng-options="item.ITEM_TEXT for item in Category"></select>
</body>
</html>

Related

Web Scraping Java Sites with HtmlAgilityPack

Let me start out by saying that I am no pro at web scraping. I can do the basics on most platforms, but that's about it.
I am trying to create the foundation for a web application that can helps users reinforce their language learning by generating additional data, metrics, as well as create new tools for self-testing. The Duolingo website is not offering up any sort of API so my next thought for now is just to scrape https://www.duome.eu/. I wrote a quick little scraper but didn't realize that the site was java. In the following example, it is my wish to collect all of the words from the Words tab that contain anchors:
using System;
using HtmlAgilityPack;
using System.Net.Http;
using System.Text.RegularExpressions;
namespace DuolingoUpdate
{
class Program
{
static void Main(string[] args)
{
string userName = "Podus";
UpdateDuolingoUser(userName);
Console.ReadLine();
}
private static async void UpdateDuolingoUser(string userName)
{
string url = "https://www.duome.eu/" + userName + "/progress/";
// Create the http client connection
HttpClient httpClient = new HttpClient();
var html = await httpClient.GetStringAsync(url);
// Store the html client data in an object
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//var words = htmlDocument.DocumentNode.Descendants("div")
// .Where(node => node.GetAttributeValue("id", "")
// .Equals("words")).ToList();
//var wordList = words[0].Descendants("a")
// .Where(node => node.GetAttributeValue("class", "")
// .Contains("wA")).ToList();
Console.WriteLine(html);
}
}
}
The html object of the above code contains:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="google" value="notranslate">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Duolingo · Podus # duome.eu</title>
<link rel="stylesheet" href="/style.css?1548418871" />
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if("".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
//localStorage.tz = visitortimezone;
//timezone = Date.parse(localStorage.tz);
//timezone = localStorage.tz;
//console.log(timezone);
$.ajax({
type: "GET",
url: "/tz.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
</head>
<body>
<noscript>Click here to adjsut XP charts to your local timezone. </noscript>
<!-- Yandex.Metrika counter --> <script type="text/javascript" > (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter47765476 = new Ya.Metrika({ id:47765476, clickmap:true, trackLinks:true, accurateTrackBounce:true }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script> <noscript><div><img src="https://mc.yandex.ru/watch/47765476" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter -->
</body>
</html>
But if you go to the actual url https://www.duome.eu/Podus/progress/, the site contains a ton of script. So upon inspection the first problem is that I am not getting the html that I see in the browser. The second problem is that if you view source, its nothing like what is in inspect and I don't see anything in source that would lead me to isolate the data from div id="words".
Given my lackluster knowledge of java built web pages, how do I do this, or is it even possible?
You can access dualingo profile data in JSON format via https://www.duolingo.com/users/<username>
eg. https://www.duolingo.com/users/Podus
This should be much easier than trying to scrape the duome profile page manually.

Google map not properly load in web browser control

I have one html file like Map.Html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var address = "Ahmedabad, India" //change the address in order to search the google maps
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
});
var infoWindow = new google.maps.InfoWindow({
content: 'Hello'
});
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
then i load this html file in webbrowser control DocumentText using below code:
using (StreamReader reader = new StreamReader(System.Windows.Forms.Application.StartupPath + "\\Map.html"))
{
_mapHTML = reader.ReadToEnd();
}
webBrowser1.DocumentText = _mapHTML;
but map not load properly.
zoom in/out, Map/Satellite option, Marker are showing but one white layer on map display.
SOLVED -- for me at least.
For some reason, the Webbrowser control is defaulting to a bad version (experimental?). I changed my initialization script to specify the current 3.3 version and everything is back to normal.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.3"></script>

ASP.Net WebAPI 500 (Internal Server Error)

I have followed the tutorial located here:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
However, the main difference is I am using a 3rd party library to get a list of objects which I would like to return to the client.
Here is my index.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Routes</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
</head>
<body>
<div>
<h2>All Routes</h2>
<ul id="routes" />
</div>
<script>
var uri = '../api/MH_Route_Selection';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#routes'));
});
});
});
</script>
</body>
</html>
My controller file:
namespace LMVeKanban.Controllers
{
public class MH_Route_SelectionController : ApiController
{
//GET ROUTES METHOD FOR URI: /api/MH_Route_Selection
[HttpGet]
public IHttpActionResult GetRouteList()
{
var routeManager = new LmvRouteManager(1);
List<Route> routes = routeManager.GetRoutes();
return Ok(Json(routes));
}
}
Everything works fine, the controller gets called and the return value routes, looks like: http://imageshack.com/a/img661/5648/ZQ59Rt.jpg
After the controller passes the list back, I get a 500 error from the server with no clue where it went wrong.
EDIT: Watching the Ok(routes) value shows that it has successfully converted the object:
EDIT 2: I have tried the following which also returns a 500 error in the same manner as the previous attempt
public HttpResponseMessage GetRouteList()
{
var routeManager = new LmvRouteManager(1);
List<Route> routes = routeManager.GetRoutes();
return Request.CreateResponse(HttpStatusCode.OK, routes);
}

bing map does not load

Im doing a web application in C# and ASP.NET MVC4.
Im having a problem with loading a map on one of my view pages...
I have the map on my Details page and the you go from Index page to Details page.
This is some of my code:
<div id='myMap' style="position:relative; width:400px; height:400px;">
</div>
<div>
<input type="button" value="createWalkingRoute" onclick="createDirections();" />
</div>
<div id='directionsItinerary'> </div>
#section scripts{
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'mykey' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createWalkingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to walking
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.walking });
var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle, WA' });
directionsManager.addWaypoint(seattleWaypoint);
var redmondWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond, WA', location: new Microsoft.Maps.Location(47.678561, -122.130993) });
directionsManager.addWaypoint(redmondWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createWalkingRoute });
}
else {
createWalkingRoute();
}
}
getMap();
</script>
}
When you go first go on the Details page the map doesn't load. However if the page is then refreshed, then the map loads after. So to me this is some sort of loading problem. But after trying for few hours Im absolutely stuck.
Can anyone help? thanks
put the getMap() call into some place where it will be called after the page is loaded, for example the body onload event. If you are using jquery, $(document).ready().

ASP.Net MVC Jquery UI Autocomplete - list not showing up when I debug

I have implemented an autocomplete in my app for zip codes. I am debugging in Firebug and I see in my console that the action is performing and I get a list of zip codes in the list of results, but the actual list is not displaying when I debug.
Here's the action in my Customers controller:
//the autocomplete request sends a parameter 'term' that contains the filter
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
//return raw text, one result on each line
return Content(string.Join("\n", zipCodes));
}
Here's the markup (abbreviated)
<% using (Html.BeginForm("Create", "Customers")) {%>
<input type="text" value="" name="ZipCodeID" id="ZipCodeID" />
<% } %>
and here's the order I load my scripts:
<script type="text/javascript" src="/Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({ source: '<%= Url.Action("FindZipCode", "Customers") %>'});
});
</script>
Anything obvious that I'm missing? Like I say the script is grabbing the list of zip codes, they just won't display on my page when I test.
EDIT: I added an image that shows what I see in firebug - it appears that I get my zip codes back, but just won't display the dropdown.
I also updated my text box so that it's inside of the ui-widget div like so:
<div class="ui-widget">
<input type="text" name="ZipCodeID" id="ZipCodeID" />
</div>
and this is the script that I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete('<%= Url.Action("FindZipCode", "Customers") %>');
});
</script>
I was able to get the autocomplete suggestions working using the following code:
Controller:
public JsonResult FindZipCode(string term)
{
VetClinicDataContext db = new VetClinicDataContext();
var zipCodes = from c in db.ZipCodes
where c.ZipCodeNum.ToString().StartsWith(term)
select new { value = c.ZipCodeID, label = c.ZipCodeNum};
return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
}
Markup:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({
source: '<%= Url.Action("FindZipCode", "Customers") %>',
});
});
</script>
<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>
I had huge problems with autocomplete few months ago when first setting it up. For instance, the simple default wireup like you do it never worked for me. I had to specify everything and also attach the result function to it.
This works 100% but it might not be suitable for you. But I hope it helps. Put both in document.ready() function.
$("#products").autocomplete('<%:Url.Action("GetProducts", "Product") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array(data.length), j;
for (j = 0; j < data.length; j++) {
rows[j] = { data: data[j], value: data[j].Title, result: data[j].Title };
}
return rows;
},
formatItem: function (row, y, n) {
return row.PrettyId + ' - ' + row.Title + ' (' + row.Price + ' €)';
},
width: 820,
minChars: 0,
max: 0,
delay: 50,
cacheLength: 10,
selectFirst: true,
selectOnly: true,
mustMatch: true,
resultsClass: "autocompleteResults"
});
$("#products").result(function (event, data, formatted) {
if (data) {
var item = $("#item_" + data.PrettyId),
edititem = $("#edititem_" + data.PrettyId),
currentQuantity;
// etc...
}
});
Try returning JSON from your controller action:
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
return Json(new { suggestions = zipCodes }, JsonRequestBehavior.AllowGet);
}
Also don't forget to include the default CSS or you might not see the suggestions div appear.

Categories

Resources