I am wanting to add application insights sdk into a blazor web assembly project. I came across multiple articles such as Application Insights for web pages and stackoverflow that has the exact thing I am looking for. However, after adding the snippet of code from the microsoft link and using connectionString over instrumentationKey to the index.html page and injecting IJSRuntime in order to call JavaScript methods from .NET code then calling Application Inisghts methods... when running the application at the top of the home page I will see #inject IJSRuntime _jsRuntime.
Am I not properly setting up the injecting? Also, do I need to add these lines of code into each razor component (page folder) or just having it in the index.html will cover everything from the start to end no matter what I click and what page is rendered?
Index.html
#inject IJSRuntime _jsRuntime
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
!function (T, l, y) { var S = T.location, k = "script", D = "connectionString", C = "ingestionendpoint", I = "disableExceptionTracking", E = "ai.device.", b = "toLowerCase", w = "crossOrigin", N = "POST", e = "appInsightsSDK", t = y.name || "appInsights"; (y.name || T[e]) && (T[e] = t); var n = T[t] || function (d) { var g = !1, f = !1, m = { initialize: !0, queue: [], sv: "5", version: 2, config: d }; function v(e, t) { var n = {}, a = "Browser"; return n[E + "id"] = a[b](), n[E + "type"] = a, n["ai.operation.name"] = S && S.pathname || "_unknown_", n["ai.internal.sdkVersion"] = "javascript:snippet_" + (m.sv || m.version), { time: function () { var e = new Date; function t(e) { var t = "" + e; return 1 === t.length && (t = "0" + t), t } return e.getUTCFullYear() + "-" + t(1 + e.getUTCMonth()) + "-" + t(e.getUTCDate()) + "T" + t(e.getUTCHours()) + ":" + t(e.getUTCMinutes()) + ":" + t(e.getUTCSeconds()) + "." + ((e.getUTCMilliseconds() / 1e3).toFixed(3) + "").slice(2, 5) + "Z" }(), iKey: e, name: "Microsoft.ApplicationInsights." + e.replace(/-/g, "") + "." + t, sampleRate: 100, tags: n, data: { baseData: { ver: 2 } } } } var h = d.url || y.src; if (h) { function a(e) { var t, n, a, i, r, o, s, c, u, p, l; g = !0, m.queue = [], f || (f = !0, t = h, s = function () { var e = {}, t = d.connectionString; if (t) for (var n = t.split(";"), a = 0; a < n.length; a++) { var i = n[a].split("="); 2 === i.length && (e[i[0][b]()] = i[1]) } if (!e[C]) { var r = e.endpointsuffix, o = r ? e.location : null; e[C] = "https://" + (o ? o + "." : "") + "dc." + (r || "services.visualstudio.com") } return e }(), c = s[D] || d[D] || "", u = s[C], p = u ? u + "/v2/track" : d.endpointUrl, (l = []).push((n = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)", a = t, i = p, (o = (r = v(c, "Exception")).data).baseType = "ExceptionData", o.baseData.exceptions = [{ typeName: "SDKLoadFailed", message: n.replace(/\./g, "-"), hasFullStack: !1, stack: n + "\nSnippet failed to load [" + a + "] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: " + (S && S.pathname || "_unknown_") + "\nEndpoint: " + i, parsedStack: [] }], r)), l.push(function (e, t, n, a) { var i = v(c, "Message"), r = i.data; r.baseType = "MessageData"; var o = r.baseData; return o.message = 'AI (Internal): 99 message:"' + ("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) (" + n + ")").replace(/\"/g, "") + '"', o.properties = { endpoint: a }, i }(0, 0, t, p)), function (e, t) { if (JSON) { var n = T.fetch; if (n && !y.useXhr) n(t, { method: N, body: JSON.stringify(e), mode: "cors" }); else if (XMLHttpRequest) { var a = new XMLHttpRequest; a.open(N, t), a.setRequestHeader("Content-type", "application/json"), a.send(JSON.stringify(e)) } } }(l, p)) } function i(e, t) { f || setTimeout(function () { !t && m.core || a() }, 500) } var e = function () { var n = l.createElement(k); n.src = h; var e = y[w]; return !e && "" !== e || "undefined" == n[w] || (n[w] = e), n.onload = i, n.onerror = a, n.onreadystatechange = function (e, t) { "loaded" !== n.readyState && "complete" !== n.readyState || i(0, t) }, n }(); y.ld < 0 ? l.getElementsByTagName("head")[0].appendChild(e) : setTimeout(function () { l.getElementsByTagName(k)[0].parentNode.appendChild(e) }, y.ld || 0) } try { m.cookie = l.cookie } catch (p) { } function t(e) { for (; e.length;)!function (t) { m[t] = function () { var e = arguments; g || m.queue.push(function () { m[t].apply(m, e) }) } }(e.pop()) } var n = "track", r = "TrackPage", o = "TrackEvent"; t([n + "Event", n + "PageView", n + "Exception", n + "Trace", n + "DependencyData", n + "Metric", n + "PageViewPerformance", "start" + r, "stop" + r, "start" + o, "stop" + o, "addTelemetryInitializer", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush"]), m.SeverityLevel = { Verbose: 0, Information: 1, Warning: 2, Error: 3, Critical: 4 }; var s = (d.extensionConfig || {}).ApplicationInsightsAnalytics || {}; if (!0 !== d[I] && !0 !== s[I]) { var c = "onerror"; t(["_" + c]); var u = T[c]; T[c] = function (e, t, n, a, i) { var r = u && u(e, t, n, a, i); return !0 !== r && m["_" + c]({ message: e, url: t, lineNumber: n, columnNumber: a, error: i }), r }, d.autoExceptionInstrumented = !0 } return m }(y.cfg); function a() { y.onInit && y.onInit(n) } (T[t] = n).queue && 0 === n.queue.length ? (n.queue.push(a), n.trackPageView({})) : a() }(window, document, {
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: { // Application Insights Configuration
connectionString: "CONNECTIONSTRING_KEY_GOES_HERE"
/* ...Other Configuration Options... */
}
});
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorWeb</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorWeb.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
await _jsRuntime.InvokeVoidAsync("appInsights.trackPageView");
</html>
Injecting the Application Insights for Blazor web applications. Steps to be followed
Add BlazorApplicationInsights
Nuget
dotnet add package BlazorApplicationInsights
Add call to Program.cs
builder.Services.AddBlazorApplicationInsights();
Add using statement to _Imports.razor
#using BlazorApplicationInsights;
Add component to App.razor
<ApplicationInsightsComponent />
Add Application Insights JS to head in index.html
Source
Set 'ld: -1' so that the page will be blocked until the JS is loaded and enter your instrumentationKey
Add the Source like below screenshot
Add JS Interop to the bottom of body in index.html
I can see the Track Event button which I was used.
Also, I can see the custom Event in Application Insights.
Refer here
I have an array which return data in size like 3,6,9,12,15.. (multiplication of 3)
DataTable dt = new DataTable();
string GridData = ViewState["ShowItem"].ToString();
string[] FilterData = GridData.Split('^');
Above array return data like..
FilterData [0] = "Pizza"; (Item)
FilterData [1] = "2$"; (Price)
FilterData [2] = "2"; (Quantity)
FilterData [3] = "Burger";
FilterData [4] = "5$";
FilterData [5] = "1";
FilterData [6] = "Cesa";
FilterData [7] = "7$";
FilterData [8] = "3";
now I want to enter above data as column wise in database like:
Item Price Quantity Total(Price*Quantity)
now I want to run a loop that add data of particular field like:
for (int nIndex = 0; nIndex < FilterData.Length; nIndex++)
{
DataRow drow = dt.NewRow();
drow["ProductItem"] = FilterData[nIndex].ToString(); (Add all Item)
drow["Cost"] = FilterData[nIndex].ToString(); (Add all Cost)
drow["Quantity"] = FilterData[nIndex].ToString(); (Add all Quantity)
double Total= Convert.ToDouble(FilterData[nIndex].ToString()) * Convert.ToInt32(FilterData[nIndex].ToString()); (Add all cost*Quantity)
drow["Total"] = Total;
dt.Rows.Add(drow);
}
So can anybody help me how could I run the loop so it add data to particular column like:
Item Price Quantity Total(Price*Quantity)
Pizza 2 2 4
Burger 5 1 5
Cesa 7 3 21
You need to increment nIndex by 3 each time, access each member by it's offset from nIndex:
for (int nIndex = 0; nIndex < FilterData.Length; nIndex += 3)
{
DataRow drow = dt.NewRow();
drow["ProductItem"] = FilterData[nIndex]; // Item
var cost = FilterData[nIndex + 1]; // Cost
var qty = FilterData[nIndex + 2]; // Quantity
drow["Cost"] = cost;
drow["Quantity"] = qty;
double Total =
Convert.ToDouble(cost.Remove(cost.Length - 1)) * // remove $
Convert.ToInt32(qty); // Total
drow["Total"] = Total;
dt.Rows.Add(drow);
}
i'm trying to retrieve AAPL financials and i'm getting the following error
> library(quantmod)
> f <- get(getFinancials('APPL'))
Error in thead[x]:thead[x + 1] : NA/NaN argument
In addition: Warning message:
In readLines(tmp) :
incomplete final line found on 'C:\Users\myuser\AppData\Local\Temp\Rtmpgrg0Uq\fileafc7f52710a'
i've tried to load the entire NQ100 and got the same error message for these stocks as well
> symbols
[1] "ADBE" "APOL" "AAPL" "AMAT" "ADSK" "ADP" "BBBY" "BMC" "CA" "CERN" "CSCO" "COST" "DELL" "DTV" "DLTR" "ERTS" "ESRX" "FFIV" "FLEX" "GRMN" "GMCR" "HSIC" "ILMN"
[24] "INFY" "INTC" "INTU" "JOYG" "KLAC" "LRCX" "LLTC" "MRVL" "MXIM" "MCHP" "MU" "MSFT" "NTAP" "NWSA" "NVDA" "ORCL" "PAYX" "QCOM" "RIMM" "ROST" "SNDK" "STX" "SHLD"
[47] "SPLS" "SBUX" "SYMC" "URBN" "VOD" "WFM" "XLNX"
all other stocks work fine
this is the text from the file fileafc7f52710a specified in the error message
<!DOCTYPE html><html><head><script>(function(){(function(){function d(a){this.t={};this.tick=function(a,c,b){b=void 0!=b?b:(new Date).getTime();this.t[a]=[b,c]};this.tick("start",null,a)}var a=new d;window.jstiming={Timer:d,load:a};if(window.performance&&window.performance.timing){var a=window.performance.timing,c=window.jstiming.load,b=a.navigationStart,a=a.responseStart;0<b&&a>=b&&(c.tick("_wtsrt",void 0,b),c.tick("wtsrt_","_wtsrt",a),c.tick("tbsd_","wtsrt_"))}try{a=null,window.chrome&&window.chrome.csi&&(a=Math.floor(window.chrome.csi().pageT),
c&&0<b&&(c.tick("_tbnd",void 0,window.chrome.csi().startE),c.tick("tbnd_","_tbnd",b))),null==a&&window.gtbExternal&&(a=window.gtbExternal.pageT()),null==a&&window.external&&(a=window.external.pageT,c&&0<b&&(c.tick("_tbnd",void 0,window.external.startE),c.tick("tbnd_","_tbnd",b))),a&&(window.jstiming.pt=a)}catch(e){}})();})();
</script><title>Financial Statements for APPELL PETE CORP - Google Finance</title><meta name="Description" content="Get the detailed quarterly/annual income statement, cashflow statement, and balance sheet for APPELL PETE CORP (PINK:APPL). See revenue, expenses, profit, cash, assets, liabilities, shareholder’s equity and more for the lastest fiscal quarter/year for APPELL PETE CORP (PINK:APPL) on Google Finance."><meta http-equiv="X-UA-Compatible" content="IE=10"><link rel="stylesheet" type="text/css" href="/finance/f/finance_us-3578168175.css"><link rel="stylesheet" type="text/css" href="/finance/_/ss/a/ver=1b0b1eb0rwwhe/am=!xiAxGGlQxoffym1L/bf=/r=O"><link rel="icon" type="image/vnd.microsoft.icon" href="/finance/favicon.ico"><style>#gbar,#guser{font-size:13px;padding-right:8px;padding-top:4px !important;}#gbar{padding-left:8px;height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}#media all{.gb1{height:22;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}</style><script></script><script>
function _rpt() {}
function _tck() {}
</script></head><body><div class=fjfe-bodywrapper><div id=fjfe-real-body class=g-doc><input type="text" name="hist_state" id="hist_state" style="display:none;"><iframe id="hist_frame" name="hist_frame" class=invfr tabindex="-1"></iframe><iframe src="/finance/_/js/a/b/rt=h/ver=t5fUYABu0to.en_US./sv=1/am=!xiAxGGlQxoffym1L/d=0" class=invfr tabindex="-1"></iframe><div id=gbar><nobr><a class=gb1 href="http://www.google.com/webhp?hl=en&tab=ew">Search</a> <a class=gb1 href="http://www.google.com/imghp?hl=en&tab=ei">Images</a> <a class=gb1 href="http://maps.google.com/maps?hl=en&tab=el">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=e8">Play</a> <a class=gb1 href="http://www.youtube.com/?tab=e1">YouTube</a> <a class=gb1 href="http://news.google.com/nwshp?hl=en&tab=en">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=em">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=eo">Drive</a> <a class=gb1 style="text-decoration:none" href="http://www.google.com/intl/en/options/"><u>More</u> »</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.com/support/finance?hl=en" class=gb4>Help</a> | <a target=_top id=gb_70 href="https://www.google.com/accounts/ServiceLogin?service=finance&passive=1209600&continue=http://www.google.com/finance?fstype%3Dii%26q%3DAPPL&followup=http://www.google.com/finance?fstype%3Dii%26q%3DAPPL" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div><div id=fjfe-click-wrapper><script>
(function() {
var l = window.location;
var q = l.search ? l.search.substr(1) : '';
var h = l.hash ? l.hash.substr(1) : '';
var p = '/finance';
var ss = 'stockscreener';
var conn = window.history && window.history.pushState ? '/' : '#';
if (l.pathname == p + '/' + ss) {
if (h) l.href = p + conn + ss + '?' + q + '&' + h;
} else if (l.pathname != p && h) {
l.href = p + l.hash;
}
if (h) {
document.getElementById('fjfe-click-wrapper').style.display = 'none';
}
})();
</script><div id=gf-head class="g-section g-tpl-75-25 g-split"><div class="g-unit g-first"><div class=fjfe-logo><img src="/finance/f/logo_us-115376669.gif" alt="Google Finance"></div><div id=gf-search class=fjfe-search><form method="get" action="/finance" autocomplete="off"><input class=fjfe-searchbox-input name=q type=text tabindex=1 value="PINK:APPL"></input><span class=fjfe-searchbox-button-wrapper><span class=fjfe-searchbox-button-wrapper2><input class=fjfe-searchbox-button type=submit tabindex=2 value="Get quotes"></input></span></span><input type=hidden name="ei" value="OudPUfCPNIeowAPQtQE"></input></form></div></div><div class="g-unit fjfe-promo"><div id="ad2-target" class="id-ad2-target"></div></div></div><div class=elastic><div id=app class="g-section g-tpl-left-11p4em"><div class="g-unit g-first"><div id=gf-nav><div class=fjfe-nav-nav><ul class=fjfe-nav id=navmenu><li class=fjfe-nav-item><div>Markets</div><li class=fjfe-nav-item><div>News</div><li class=fjfe-nav-item><div>Portfolios</div></ul></div><div class="fjfe-recentquotes fjfe-recentquotes-noquote"><h4>Recent Quotes <span class="fjfe-recentquotes-duration">(2 hours)</span></h4><div class=fjfe-recentquotes-noquote-notification>You have no recent quotes</div><div class=fjfe-recentquotes-quotes><div class="fjfe-toggle fjfe-toggle-button"><span class=fjfe-chg-toggle>chg</span> | <span class=fjfe-perc-toggle>%</span></div><div class=fjfe-table-div><table class=fjfe-recentquotes-table id=rq width=100%></table></div></div></div></div><script>var _cleardot = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
var google = google || {};
google.finance = google.finance || {};
google.finance.gce =false;</script><script src="/finance/f/sfe-opt-2862241303.js"></script><script>
_regOnLoad = function(f) {
if (document.readyState == 'complete') {
f && f();
} else {
// Window.attachEvent() for IE8 and below compatability.
var addEventFunction = window.attachEvent ||
window.addEventListener || function(ignored, f) { f(); };
var event = window.attachEvent ? 'onload' : 'load';
f && addEventFunction(event, f);
}
};
google.finance.renderRecentQuotes = function() {};
</script></div><div class=g-unit id=gf-viewc><div class=fjfe-content></div></div></div></div></div><div id=gf-foot><div class=fjfe-footer-links>Google Finance Beta available in: Hong Kong - Canada - U.S. - China - U.K.</div><p class=fjfe-footer-disclaimer>Information is provided "as is" and solely for informational purposes, not for trading purposes or advice, and may be delayed.<br>To see all exchange delays, please see disclaimer.</p><div class=fjfe-footer-links>©2013 Google - Google Home - Blog - Help - Report a Problem - Privacy Policy - Terms of Service</div></div></div></div><script>var googlefinance = {i: ["f.b.id","",,500,"",0,,["f.b.cf","t5fUYABu0to.en_US.",0]
,[]
,0,[["c388b5b8","true",2]
]
,"OudPUfCPNIeowAPQtQE","www.google.com"]
}; GF_domReady = 1;</script></body></html>
I've been trying to get the "Count" for my "Value" field in my query expression. In my code it suppose to create a list of checkboxes and beside the checkboxes is a count of how many items are in the list(checkbox).
Could someone show me how to get the count for the items of my field Value this is a checbox filtering system I'm making.I've just started learning linq and lambda exressions.
Code in C# ASP.NET
var dept = Page.RouteData.Values["department"];
var department = (from d in db.Departments where d.Name.Replace(" ", "-") == dept select new {d.Id, d.Name}).FirstOrDefault();
var query = (from p in db.Products
join f in db.ProductFilters on p.Id equals f.ProductId into filters
from x in filters.Where(x => x.Product.DepartmentId == department.Id)
select new { x.Id, x.Name, x.Value }).ToList();
var brand = query.Where(x => x.Name == "Brand").OrderBy(x => x.Value);
var price = query.Where(x => x.Name == "Price").OrderBy(x => x.Value);
var brandAndPrice = brand.Concat(price);
var labelBrandAndPrice = (from f in brandAndPrice select new { f.Name }).Distinct().OrderBy(x => x.Name);
//var otherFilters = query.Except(brandAndPrice);
StringBuilder sb = new StringBuilder();
sb.Append("<div class=\"Filters\">");
foreach (var label in labelBrandAndPrice)
{
sb.Append("<span>" + label.Name + "</span><br />");
sb.Append("<div class=\"ProdFilters\">");
// Below is where I wanted to do distinct expression and groupby but it didn't work
var BrandPriceCollection = brandAndPrice.Where(x => x.Name == label.Name).Distinct().ToList();
foreach (var bp in BrandPriceCollection)
{
//Here i want to write out the count for the field Value
sb.Append("<input type=\"checkbox\" id=\"" + bp.Value + "\" /><span>" + bp.Value + "(" + "Count" + ")" + "</span><br />");
}
sb.Append("</div>");
}
sb.Append("</div>");
var BrandPriceCollection = brandAndPrice.Where(x => x.Name == label.Name).Distinct().ToList();
var groupings = BrandPriceCollection.GroupBy(x => x.Value);
foreach (var g in groupings)
{
//Here i want to write out the count for the field Value
sb.Append("<input type=\"checkbox\" id=\"" + g.Key + "\" /><span>" + g.Key + "(" + g.Count() + ")" + "</span><br />");
}
GroupBy returns your data in the structure like Dictionary, with value you are grouping on in Key property and the collection of elements inside, so you can just Count() it. Note that groupings is the collection of collections now.
I have code:
api_result = '{"response":[{"uid":1969258,"first_name":"Walle","last_name":"Woo"}]}';
var myobj:Object = JSON.decode(api_result);
So, how I can get uid, first_name and last_name from "response" array?
var UID:Object = myobj.response[0].uid;
var firstName:Object = myobj.response[0].first_name;
var lastName:Object = myobj.response[0].last_name;