How can I correlate frontend and backend using App Insights? - azure

I am having an ASP.NET Core Razor application, where I am using the JavaScript AppInsights component for the ckient-side (configured in _Layout.cshtml) and the nuget package for the server-side.
Unfortunately, I am not able to correlate page views on the client-side to requests on the server-side. Also, the application map is not getting drawn correctly, no matter what I try. As you can see, they are "disconnected".
I have tried the following settings on the front end without luck. Any idea?
disableFetchTracking: false,
enableCorsCorrelation: true,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true,

I figured it out. The documentation only lists XMLHttpRequest calls under the auto-collected dependency items for JavaScript.
So that implies I have to change views like this
// MySite.cshtml
#page
#model ...
#{
ViewData["Title"] = "My Site";
}
<h1>#ViewData["Title"]</h1>
<form method="post" class="mt-1">
<button class="btn btn-primary">Do something</button>
<input type="hidden" name="id" value="doSomething" />
</form>
// MySite.cshtml.cs
public class MySiteModel : PageModel
{
// ...
public void OnPost(string id)
{
// ...
}
}
To views that make use of AJAX, e.g like so
// MySite.cshtml
#page
#model ...
#{
ViewData["Title"] = "Exceptions";
}
<h1>#ViewData["Title"]</h1>
<button class="btn btn-primary" id="doSomething">Do Something</button>
#section scripts
{
<script>
$(document).click(e => {
var id = e.target.id;
if (id == "doSomething") {
$.ajax({
url: '?handler=DoSomething
});
}
});
</script>
}
// MySite.cshtml.cs
public MySiteModel : PageModel
{
...
public void OnGetDoSomething()
{
...
}
}
And now everything looks as it should

Related

signalr2 asp.net ,vc5 how to set different css styles for messages that sent and received?

I use ASP.NET MVC 5 and SignalR 2 .
I have one chat page in one view,
and one chat page in another partialview,
i have different style for sent message and received message.
how to set this styles to messages that sent and received ?
all letters in internet is chat in one view.so not have different style.
i use this link : https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc
thanks :)
#{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
You need a flag according which you can different between messages from and to server. And you need also some css to mark different messages.
Sample:
chat.client.addNewMessageToPage = function (name, message, fromServer) {
// Add the message to the page.
if(fromServer){
$('#discussion').append('<li class="messageFromServer">strong>'+htmlEncode(name)+'</strong>: '+htmlEncode(message) + '</li>');
}
else{
$('#discussion').append('<li class="messageToServer"><strong>'+htmlEncode(name)+'</strong>: '+htmlEncode(message)+'</li>');
}
};
Sample css:
.messageFromServer{
color:purple
}
.messageToServer{
color:red
(You can test css stuff on fiddler:
https://jsfiddle.net/ugrf0jea/7/)
Your hub:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Mark the message, that this is from other client. Only call methode "addNewMessageToPage" with this params on other clients(not on caller)
Clients.Others.addNewMessageToPage(name, message, false);
// Mark message that this is from current client. Only call method addNewMessageToPage" on caller cliebt
Clients.Caller.addNewMessageToPage(name, message, false);
}
}

Can't get to Liferay's (Spring Portlet MVC's) controller from JS by doing the following:

Here's the JSP from where my Javascript function is being called:
JSP code
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="continueTour" onclick="showTutorial()">Take a Quick Tour</button>
Skip Tour
</div>
Here's the Javascript function from where I need to render another JSP, and hence need to get to the Render method in the controller. Notice the 'simulate' method that I'm calling to simulate the click of the hyperlink (!Not sure if this is right or not!):
Javascript Code showTutorial() method:
function showTutorial(){
launchTutorial();
}
function launchTutorial(){
var enjoyhint_instance = new EnjoyHint({
onEnd: function(){
AUI().use('liferay-portlet-url', function(A) {
var plid = Liferay.ThemeDisplay.getPlid();
var url=Liferay.PortletURL.createRenderURL();
/*url.setPortletId(plid);*/
url.setPortletName(Liferay.ThemeDisplay.getp)
url.setParameter('render','redirectToEmpInfo');
alert(url);
A.one(document.createElement('a')).attr('href',url).simulate('click');
});
}
});
var enjoyhint_script_steps = [
{
"next #newAuthorizationActive": 'To create an authorization form'
}
];
enjoyhint_instance.set(enjoyhint_script_steps);
enjoyhint_instance.run();
}
Here's the controller method which I've written to catch the render request from the Javascript.
Controller Method (Not getting to this method)
#RenderMapping(params = "render=redirectToEmpInfo")
protected ModelAndView redirectToEmpInfoForAuthTour(ModelMap map, RenderRequest renderRequest, RenderResponse response) {
LiferayPortal.logInfo(_log, "Inside the render method for Emp Info");
return null;
/*return new ModelAndView("emailsuccess", map);*/
}
You add this code in head of jsp:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%# taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<liferay-theme:defineObjects/>
<portlet:defineObjects />
Also in you code:
var plid = Liferay.ThemeDisplay.getPlid();
var url=Liferay.PortletURL.createRenderURL();
/*url.setPortletId(plid);*/
url.setPortletName(Liferay.ThemeDisplay.getp)
url.setParameter('render','redirectToEmpInfo');
alert(url);
Replace, similar to this:
var plid = Liferay.ThemeDisplay.getPlid();
var url = Liferay.PortletURL.createRenderURL();
url.setPortletId('<%=themeDisplay.getPortletDisplay().getId() %>');
url.setParameter('render', 'redirectToEmpInfo');
alert(url);

AJAX File upload on LIferay: unable to match parameters

I'm trying to write a Liferay portlet that sends a file upload over AJAX to a JSONWS endpoint, but I keep getting the following errors in the logfile:
DEBUG [http-bio-8080-exec-70][JSONWebServiceActionsManagerImpl:121] Request JSON web service action with path /document/upload-file and method POST for //document-portlet
DEBUG [http-bio-8080-exec-70][JSONWebServiceActionsManagerImpl:455] Found 1 JSON web service actions with path /document-portlet/document/upload-file in for //document-portlet
DEBUG [http-bio-8080-exec-70][JSONWebServiceActionsManagerImpl:501] Unable to match parameters to a JSON web service action with path /document-portlet/document/upload-file for //document-portlet
ERROR [http-bio-8080-exec-70][JSONWebServiceServiceAction:97] No JSON web service action associated with path /document/upload-file and method POST for //document-portlet
Following a couple of tutorials, my JSONWS implementation looks like this:
class DocumentServiceImpl extends DocumentServiceBaseImpl {
#JSONWebService(method="POST")
public String uploadFile(File content) {
// ...
}
}
And here's my client-side code:
<aui:form name="files" enctype="multipart/form-data">
<aui:input type="file" name="content" label="File" />
<aui:button type="submit" name="btnUploadFile" value="Upload file" />
</aui:form>
<script>
AUI().use(
'aui-io-request',
function(A) {
var btnUploadFile = A.one("#<portlet:namespace />btnUploadFile");
btnUploadFile.on("click",
function(event) {
event.preventDefault();
var myForm = A.one("#<portlet:namespace/>files");
var ajaxURL = "http://localhost:8080/api/jsonws/document-portlet.document/upload-file";
var configs = {
method : 'POST',
form : {
id : myForm,
upload : true
},
sync : true,
on : {
complete : function() {
// ...
}
}
};
A.io.request(ajaxURL, configs);
}
)
}
);
</script>
It looks to me like Liferay discovers the uploadFile method, but it can't match the signature of the request to the parameters of the method. How do I match parameters for a multipart/form-data request? Or am I going about this the wrong way?

Multiple Layouts in Ember.js?

Coming from a Rails background, you can have multiple Layouts - for say, anonymous user pages and then authenticated pages.
Is this possible with Ember?
I've tried declaring a new templateName in my UsersRouter, with no avail.
I've also checked this guide: http://emberjs.com/guides/views/adding-layouts-to-views/
But it doesn't seem to be working :/
You can use {{render}} inside an if helper to show different layouts.
For instance if you have an ApplicationController that has login and logout action handlers, and a corresponding `loggedIn' property.
App.ApplicationController = Ember.Controller.extend({
loggedIn: false,
login: function() {
this.set('loggedIn', true);
},
logout: function() {
this.set('loggedIn', false);
}
});
The you can bind to the loggedIn property inside the application template like so.
<script type='text/x-handlebars' data-template-name='application'>
<button {{action login }}>Login</button>
<button {{action logout }}>Logout</button>
{{#if loggedIn}}
{{render 'user'}}
{{else}}
{{render 'guest'}}
{{/if}}
</script>
Where user and guest are corresponding templates.
<script type='text/x-handlebars' data-template-name='user'>
<h1>User layout</h1>
<div class='box user'>
{{outlet}}
</div>
</script>
<script type='text/x-handlebars' data-template-name='guest'>
<h1>Guest layout</h1>
<div class='box guest'>
{{outlet}}
</div>
</script>
Here's a working jsbin.
Edit: To not use the application route based on some static criteria or loaded via model hooks, you can override the renderTemplate method of the ApplicationRoute.
App.ApplicationRoute = Ember.Route.extend({
renderTemplate: function() {
var loggedIn = false;
if (loggedIn) {
this.render('user');
} else {
this.render('guest');
}
}
});

Geolocation JSF

Does anyone have an example of sending a geolocation from a mobile phone to a JSF backing bean?
Would like to get the customers address using geolocation? (Will need to convert from geolocation co-ordinates to a drop down list of nearby roads).
Thanks,
D
Not sure if this will help u get started...
This pulls GPS Geolocation Data from Mobile Devices into a Form...
Then do whatever with it from there...
<script type="text/javascript">
function getLocationConstant()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(onGeoSuccess,onGeoError);
} else {
alert("Your browser or device doesn't support Geolocation");
}
}
// If we have a successful location update
function onGeoSuccess(event)
{
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
}
// If something has gone wrong with the geolocation request
function onGeoError(event)
{
alert("Error code " + event.code + ". " + event.message);
}
</script>
<cfform action="gps2.cfm" method="post">
Latitude: <input type="text" id="Latitude" name="Latitude" value="">
<br><br>
Longitude: <input type="text" id="Longitude" name="Longitude" value="">
<br><br>
<input type="button" value="Get Location" onclick="getLocationConstant()"/>
<br><br>
<input type="submit" value="Add GPS Location" class=small>
</cfform>
View this links please:
https://developers.google.com/maps/documentation/javascript/examples/map-geolocation - Google Developers
https://goo.gl/TD7aiq - JsFiddle
JS:
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
Using the Javascript you can get the co-ordinates and you can set the backend variable using document.getElementById("id")) in javascript.
Example:
<h:inputText value="{myBean.latitude}" id="latitudeID" />
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.getElementById("formName:latitudeID").value=position.coords.latitude; /* this will set the value in variable */
}
</script>
</body>
</html>

Resources