diff --git a/CSharp/capability-botToWeb/.gitattributes b/CSharp/capability-botToWeb/.gitattributes deleted file mode 100644 index 1ff0c42304..0000000000 --- a/CSharp/capability-botToWeb/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/CSharp/capability-botToWeb/.gitignore b/CSharp/capability-botToWeb/.gitignore deleted file mode 100644 index 1c9a181a44..0000000000 --- a/CSharp/capability-botToWeb/.gitignore +++ /dev/null @@ -1,242 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -[Xx]64/ -[Xx]86/ -[Bb]uild/ -bld/ -[Bb]in/ -[Oo]bj/ - -# Visual Studio 2015 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# DNX -project.lock.json -artifacts/ - -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml - -# TODO: Un-comment the next line if you do not want to checkin -# your web deploy settings because they may include unencrypted -# passwords -#*.pubxml -*.publishproj - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/packages/* -# except build/, which is used as an MSBuild target. -!**/packages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/packages/repositories.config -# NuGet v3's project.json files produces more ignoreable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directory -AppPackages/ -BundleArtifacts/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -[Ss]tyle[Cc]op.* -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.pfx -*.publishsettings -node_modules/ -orleans.codegen.cs - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm - -# SQL Server files -*.mdf -*.ldf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# LightSwitch generated files -GeneratedArtifacts/ -ModelManifest.xml - -# Paket dependency manager -.paket/paket.exe - -# FAKE - F# Make -.fake/ diff --git a/CSharp/capability-botToWeb/Bot/App_Start/WebApiConfig.cs b/CSharp/capability-botToWeb/Bot/App_Start/WebApiConfig.cs deleted file mode 100644 index 2b0216ce73..0000000000 --- a/CSharp/capability-botToWeb/Bot/App_Start/WebApiConfig.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web.Http; - -namespace Bot -{ - public static class WebApiConfig - { - public static void Register(HttpConfiguration config) - { - // Json settings - config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; - config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; - JsonConvert.DefaultSettings = () => new JsonSerializerSettings() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - Formatting = Newtonsoft.Json.Formatting.Indented, - NullValueHandling = NullValueHandling.Ignore, - }; - - // Web API configuration and services - - // Web API routes - config.MapHttpAttributeRoutes(); - - config.Routes.MapHttpRoute( - name: "DefaultApi", - routeTemplate: "api/{controller}/{id}", - defaults: new { id = RouteParameter.Optional } - ); - } - } -} diff --git a/CSharp/capability-botToWeb/Bot/Bot.csproj b/CSharp/capability-botToWeb/Bot/Bot.csproj deleted file mode 100644 index 89907e983c..0000000000 --- a/CSharp/capability-botToWeb/Bot/Bot.csproj +++ /dev/null @@ -1,284 +0,0 @@ - - - - - Debug - AnyCPU - - - 2.0 - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - Bot - Bot Application1 - v4.6 - true - - - - - - - - - /subscriptions/301c6f74-02a2-4142-b79b-32c04b0b02f7/resourcegroups/IDAHDBBot/providers/microsoft.insights/components/IDAHDBBot - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - - - - ..\packages\Autofac.4.0.0-rc3-309\lib\net451\Autofac.dll - True - - - ..\packages\Braintree.2.64.0\lib\Braintree-2.64.0.dll - True - - - ..\packages\Chronic.Signed.0.3.2\lib\net40\Chronic.dll - True - - - ..\packages\log4net.2.0.5\lib\net45-full\log4net.dll - True - - - ..\packages\Lorem.NET.1.0.6\lib\net40\LoremNET.dll - True - - - ..\packages\Microsoft.ApplicationInsights.Agent.Intercept.1.2.1\lib\net45\Microsoft.AI.Agent.Intercept.dll - True - - - ..\packages\Microsoft.ApplicationInsights.DependencyCollector.2.1.0\lib\net45\Microsoft.AI.DependencyCollector.dll - True - - - ..\packages\Microsoft.ApplicationInsights.PerfCounterCollector.2.1.0\lib\net45\Microsoft.AI.PerfCounterCollector.dll - True - - - ..\packages\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.1.0\lib\net45\Microsoft.AI.ServerTelemetryChannel.dll - True - - - ..\packages\Microsoft.ApplicationInsights.Web.2.1.0\lib\net45\Microsoft.AI.Web.dll - True - - - ..\packages\Microsoft.ApplicationInsights.WindowsServer.2.1.0\lib\net45\Microsoft.AI.WindowsServer.dll - True - - - ..\packages\Microsoft.ApplicationInsights.Log4NetAppender.2.1.0\lib\net45\Microsoft.ApplicationInsights.Log4NetAppender.dll - True - - - ..\packages\Microsoft.Bot.Builder.3.5.3\lib\net46\Microsoft.Bot.Builder.dll - True - - - ..\packages\Microsoft.Bot.Builder.3.5.3\lib\net46\Microsoft.Bot.Builder.Autofac.dll - True - - - ..\packages\Microsoft.Bot.Builder.3.5.3\lib\net46\Microsoft.Bot.Connector.dll - True - - - - ..\packages\Microsoft.Identity.Client.1.0.304142221-alpha\lib\net45\Microsoft.Identity.Client.dll - True - - - ..\packages\Microsoft.Identity.Client.1.0.304142221-alpha\lib\net45\Microsoft.Identity.Client.Platform.dll - True - - - ..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.12.0\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll - True - - - ..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.12.0\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll - True - - - ..\packages\Microsoft.IdentityModel.Logging.1.0.0\lib\net451\Microsoft.IdentityModel.Logging.dll - True - - - ..\packages\Microsoft.IdentityModel.Protocol.Extensions.1.0.2.206221351\lib\net45\Microsoft.IdentityModel.Protocol.Extensions.dll - True - - - ..\packages\Microsoft.IdentityModel.Tokens.5.0.0\lib\net451\Microsoft.IdentityModel.Tokens.dll - True - - - ..\packages\Microsoft.Rest.ClientRuntime.2.3.2\lib\net45\Microsoft.Rest.ClientRuntime.dll - True - - - ..\packages\Microsoft.Win32.Primitives.4.0.1\lib\net46\Microsoft.Win32.Primitives.dll - True - - - ..\packages\Microsoft.WindowsAzure.ConfigurationManager.3.2.1\lib\net40\Microsoft.WindowsAzure.Configuration.dll - True - - - ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll - True - - - ..\packages\PayPal.1.8.0\lib\net451\PayPal.dll - True - - - - - ..\packages\System.Diagnostics.DiagnosticSource.4.0.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\packages\System.IdentityModel.Tokens.Jwt.4.0.2.206221351\lib\net45\System.IdentityModel.Tokens.Jwt.dll - True - - - - - ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - True - - - - - ..\packages\System.Runtime.Serialization.Primitives.4.1.1\lib\net46\System.Runtime.Serialization.Primitives.dll - True - - - ..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net46\System.Security.Cryptography.Algorithms.dll - True - - - ..\packages\System.Security.Cryptography.Encoding.4.0.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net46\System.Security.Cryptography.X509Certificates.dll - True - - - - - - - - - - - - ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - True - - - ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll - True - - - - - - - - - - - - - - Designer - - - - - - - - - - Global.asax - - - - - - - - - - - Web.config - - - Web.config - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - true - - - - - - - - - True - True - 3979 - / - http://localhost:3979/ - False - False - - - False - - - - - - \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Controllers/MessagesController.cs b/CSharp/capability-botToWeb/Bot/Controllers/MessagesController.cs deleted file mode 100644 index 31e80f9c35..0000000000 --- a/CSharp/capability-botToWeb/Bot/Controllers/MessagesController.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Bot.Dialogs; -using Microsoft.Bot.Builder.Dialogs; -using Microsoft.Bot.Connector; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using System.Web.Http; - -namespace Bot -{ - [BotAuthentication] - public class MessagesController : ApiController - { - /// - /// POST: api/Messages - /// Receive a message from a user and reply to it - /// - public async Task Post([FromBody]Activity activity) - { - if (activity.Type == ActivityTypes.Message) - { - await Conversation.SendAsync(activity, () => new PayDialog()); - } - else - { - await HandleSystemMessage(activity); - } - var response = Request.CreateResponse(HttpStatusCode.OK); - return response; - } - - private Task HandleSystemMessage(Activity message) - { - if (message.Type == ActivityTypes.DeleteUserData) - { - // Implement user deletion here - // If we handle user deletion, return a real message - } - else if (message.Type == ActivityTypes.ConversationUpdate) - { - // Handle conversation state changes, like members being added and removed - // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info - // Not available in all channels - } - else if (message.Type == ActivityTypes.ContactRelationUpdate) - { - // Handle add/remove from contact lists - // Activity.From + Activity.Action represent what happened - } - else if (message.Type == ActivityTypes.Typing) - { - // Handle knowing tha the user is typing - } - else if (message.Type == ActivityTypes.Ping) - { - } - - return null; - } - } -} \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Controllers/PaymentController.cs b/CSharp/capability-botToWeb/Bot/Controllers/PaymentController.cs deleted file mode 100644 index bb852a71f0..0000000000 --- a/CSharp/capability-botToWeb/Bot/Controllers/PaymentController.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Microsoft.Bot.Builder.Dialogs; -using PayPal.Api; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; -using System.Web.Http; - -namespace Bot.Controllers -{ - public class PaymentController : ApiController - { - [HttpGet] - // POST api/ - [Route("api/Payment")] - //Example: http://localhost:3979/api/Payment?resume=H4sIAAAAAAAEAEWOUQ6CMAyGmz0YPYHHYCAicAHjiy_KAcqogWSsZOs4nmdzRhLf_n79mv5vAFAxkL8NcEi5MLm5vPD0g3ecCXYJd2nIQZkRnSO7uTRHi8IeVM-ysXNVa30qSlDpYp0Mdd7CMS1GkaXNMssG7chB2kZrncF-Ck8fg9Dw-PtfevUcl9TNsFvJB5SJ3fajxqouh74B-ADTzn_4vgAAAA2&cancel=true&token=EC-01U772690T6522532 - public async Task Payment([FromUri] string resume, [FromUri] string token, [FromUri] string paymentId = null, [FromUri] string PayerID = null, [FromUri] bool cancel = false) - { - //Get resumption cookie - var resumptionCookie = UrlToken.Decode(resume); - var msg = resumptionCookie.GetMessage(); - - if (cancel) - { - msg.Text = "You have canceled your payment, please try again."; - } - else - { - var paymentExecution = new PaymentExecution() { payer_id = PayerID }; - var payment = new Payment() { id = paymentId }; - - // Execute the payment - var executedPayment = payment.Execute(Bot.Utilities.Configuration.GetAPIContext(), paymentExecution); - - if (executedPayment.state.ToLower() == "approved") - { - //GetMessage - msg.Text = "Thanks!"; - } - else - { - msg.Text = "I am sorry your payment was not successful, please try again."; - } - } - await Conversation.ResumeAsync(resumptionCookie, msg); - HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK); - resp.Content = new StringContent(string.Concat(msg.Text, " Please return to the conversation with the bot to continue...")); - return resp; - } - - - } -} \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Dialogs/PayDialog.cs b/CSharp/capability-botToWeb/Bot/Dialogs/PayDialog.cs deleted file mode 100644 index 1334cce43c..0000000000 --- a/CSharp/capability-botToWeb/Bot/Dialogs/PayDialog.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Microsoft.Bot.Builder.Dialogs; -using Microsoft.Bot.Connector; -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -namespace Bot.Dialogs -{ - [Serializable] - public class PayDialog : IDialog - { - private const string NOTICES_STATE_BAG_KEY = @"notices"; - - private static readonly Regex NOTICE_VALIDATOR = new Regex("^[A-Za-z0-9]{10}$", RegexOptions.Compiled); - private static readonly List EXIT_COMMANDS = new List { "start over", "done", "exit", "quit", "reset" }; - -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public async Task StartAsync(IDialogContext context) -#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - { - context.Wait(EnterPaymentAmount); - } - - private async Task EnterPaymentAmount(IDialogContext context, IAwaitable result) - { - await PromptForAmountToPay(context, @"I'd be happy to help you give me money!
-Please enter the amount you wish to pay."); - } - - private async Task PromptForAmountToPay(IDialogContext context, string promptText) - { - // Can't use PromptDialog.Text because we want to drop a ResumptionCookie when we get the user's response. - // This requires IAwaitable - var msg = context.MakeMessage(); - msg.Text = promptText; - - await context.PostAsync(msg); - - context.Wait(PaymentAmountEntered); - } - - private async Task PaymentAmountEntered(IDialogContext context, IAwaitable result) - { - var content = await result; - - double pmtAmount; - if (!double.TryParse(content.Text, out pmtAmount)) - { - await context.PostAsync(@"Sorry, doesn't look like a valid payment amount. Try again!"); - context.Wait(PaymentAmountEntered); - } - else - { - // Drop a resumption cookie we'll pick back up after the user pays on Paypal - var resumption = new ResumptionCookie(content); - context.PrivateConversationData.SetValue("resumption", resumption); - - await context.Forward(new PayFlow(), PaymentComplete, content.Text, System.Threading.CancellationToken.None); - } - } - - private async Task PaymentComplete(IDialogContext context, IAwaitable result) - { - if (await result) - { - BeDone(context); - } - else - { - await PromptForAmountToPay(context, @"Oops! There appears to have been an error processing your payment.
-Enter another amount to try again."); - } - } - - private void BeDone(IDialogContext context, bool result = true) - { - context.ConversationData.RemoveValue(NOTICES_STATE_BAG_KEY); - context.Done(result); - } - } -} \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Dialogs/PayFlow.cs b/CSharp/capability-botToWeb/Bot/Dialogs/PayFlow.cs deleted file mode 100644 index c6dab3e522..0000000000 --- a/CSharp/capability-botToWeb/Bot/Dialogs/PayFlow.cs +++ /dev/null @@ -1,168 +0,0 @@ -using Microsoft.Bot.Builder.Dialogs; -using Microsoft.Bot.Connector; -using PayPal.Api; -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using System.Linq; - -namespace Bot.Dialogs -{ - - - /* - * 1. Bot requests a client token from server in order to initialize the client SDK - * 2. Bot creates a payment order - * - * 3. Once the client SDK is initialized and the customer has submitted payment information, the SDK communicates that information to Braintree, which returns a payment method nonce - * 4 You then send the payment nonce to your server - * 5. Your server code receives the payment method nonce from your client and then uses the server SDK to create a transaction or perform other Braintree functions Credentials - * - * - * - */ - [Serializable] - public class PayFlow : IDialog - { -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public async Task StartAsync(IDialogContext context) -#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - { - context.Wait(InitialMessageReceived); - } - - private async Task InitialMessageReceived(IDialogContext context, IAwaitable result) - { - //1. Your app or web front-end requests a client token from your server in order to initialize the client SDK - var apiContext = Bot.Utilities.Configuration.GetAPIContext(); - //2.Bot creates a payment order - await CreatePayment(apiContext, context, await result); - } - - private async Task CreatePayment(APIContext apiContext, IDialogContext context, string amount) - { - // ###Items - // Items within a transaction. - var itemList = new ItemList() - { - items = new List() - }; - - itemList.items.Add(new Item() - { - name = @"Payment", - currency = @"USD", - price = amount, - quantity = "1" - }); - - //We're only doing one item so this is not really needed, but with multiple items you need to ensure the sum is correct - double totalAmt = itemList.items.Sum( x => Convert.ToDouble(x.price)); - - // ###Payer - // A resource representing a Payer that funds a payment - // Payment Method - // as `paypal` - var payer = new Payer() { payment_method = "paypal" }; - - // ###Redirect URLS - // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment. - var baseURI = System.Configuration.ConfigurationManager.AppSettings["Payment_Redirect_base_URI"]; - ResumptionCookie _resumption = null; - context.PrivateConversationData.TryGetValue("resumption", out _resumption); - var redirectUrl = baseURI + "resume=" + UrlToken.Encode(_resumption); - var redirUrls = new RedirectUrls() - { - cancel_url = redirectUrl + "&cancel=true", - return_url = redirectUrl - }; - - // ###Details - // Let's you specify details of a payment amount. - var details = new Details() - { - subtotal = totalAmt.ToString() - }; - - // ###Amount - // Let's you specify a payment amount. - var totalAmount = new PayPal.Api.Amount() - { - currency = "USD", - total = totalAmt.ToString()// Total must be equal to sum of shipping, tax and subtotal. - //, // Total must be equal to sum of shipping, tax and subtotal. - //details = details - }; - - // ###Transaction - // A transaction defines the contract of a - // payment - what is the payment for and who - // is fulfilling it. - var transactionList = new List(); - - // The Payment creation API requires a list of - // Transaction; add the created `Transaction` - // to a List - transactionList.Add(new PayPal.Api.Transaction() - { - description = "Transaction description.", - invoice_number = GetRandomInvoiceNumber(), - amount = totalAmount, - item_list = itemList - }); - - // ###Payment - // A Payment Resource; create one using - // the above types and intent as `sale` or `authorize` - var payment = new Payment() - { - intent = "sale", - payer = payer, - transactions = transactionList, - redirect_urls = redirUrls - }; - - // Create a payment using a valid APIContext - var createdPayment = payment.Create(apiContext); - // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment. - var links = createdPayment.links.GetEnumerator(); - var urllink = string.Empty; - while (links.MoveNext()) - { - var link = links.Current; - if (link.rel.ToLower().Trim().Equals("approval_url")) - { - urllink = link.href; - break; - } - } - //var msg = context.MakeMessage(); - //msg.TextFormat = TextFormatTypes.Markdown; - //msg.Text = $"Please click [here]({urllink}) to PayPal to approve the payment..."; - await context.PostAsync($"Please click [here]({urllink}) to PayPal to approve the payment..."); - context.Wait(StoreReceiptAndFinish); - - } - - /// - /// Gets a random invoice number to be used with a sample request that requires an invoice number. - /// - /// A random invoice number in the range of 0 to 999999 - private static string GetRandomInvoiceNumber() => new Random().Next(999999).ToString(); - - private async Task StoreReceiptAndFinish(IDialogContext context, IAwaitable result) - { - var receiptNumber = await result; - - // TODO: Validate entered receipt with Paypal - var msg = context.MakeMessage(); - msg.Text = receiptNumber.Text; - - await context.PostAsync(msg, CancellationToken.None); - context.ConversationData.SetValue("receiptNumber", receiptNumber.Text); - context.Done(true); - } - } -} \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Global.asax b/CSharp/capability-botToWeb/Bot/Global.asax deleted file mode 100644 index 5b2f63634e..0000000000 --- a/CSharp/capability-botToWeb/Bot/Global.asax +++ /dev/null @@ -1 +0,0 @@ -<%@ Application Codebehind="Global.asax.cs" Inherits="Bot.WebApiApplication" Language="C#" %> diff --git a/CSharp/capability-botToWeb/Bot/Global.asax.cs b/CSharp/capability-botToWeb/Bot/Global.asax.cs deleted file mode 100644 index af47f41ada..0000000000 --- a/CSharp/capability-botToWeb/Bot/Global.asax.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Web.Http; - -namespace Bot -{ - public class WebApiApplication : System.Web.HttpApplication - { - protected void Application_Start() - { - GlobalConfiguration.Configure(WebApiConfig.Register); - } - } -} diff --git a/CSharp/capability-botToWeb/Bot/Properties/AssemblyInfo.cs b/CSharp/capability-botToWeb/Bot/Properties/AssemblyInfo.cs deleted file mode 100644 index 7ef8a64261..0000000000 --- a/CSharp/capability-botToWeb/Bot/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("PayPalBot")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("PayPalBot")] -[assembly: AssemblyCopyright("Copyright © 2016")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a8ba1066-5695-4d71-abb4-65e5a5e0c3d4")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/CSharp/capability-botToWeb/Bot/Utilities/Configuration.cs b/CSharp/capability-botToWeb/Bot/Utilities/Configuration.cs deleted file mode 100644 index f09992a5ee..0000000000 --- a/CSharp/capability-botToWeb/Bot/Utilities/Configuration.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Collections.Generic; -using PayPal.Api; - -namespace Bot.Utilities -{ - public static class Configuration - { - public readonly static string ClientId; - public readonly static string ClientSecret; - - // Static constructor for setting the readonly static members. - static Configuration() - { - var config = GetConfig(); - ClientId = config["clientId"]; - ClientSecret = config["clientSecret"]; - } - - // Create the configuration map that contains mode and other optional configuration details. - public static Dictionary GetConfig() => ConfigManager.Instance.GetProperties(); - - // Create accessToken - private static string GetAccessToken() - { - // ###AccessToken - // Retrieve the access token from - // OAuthTokenCredential by passing in - // ClientID and ClientSecret - // It is not mandatory to generate Access Token on a per call basis. - // Typically the access token can be generated once and - // reused within the expiry window - string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken(); - return accessToken; - } - - // Returns APIContext object - public static APIContext GetAPIContext(string accessToken = "") - { - // ### Api Context - // Pass in a `APIContext` object to authenticate - // the call and to send a unique request id - // (that ensures idempotency). The SDK generates - // a request id if you do not pass one explicitly. - var apiContext = new APIContext(string.IsNullOrEmpty(accessToken) ? GetAccessToken() : accessToken); - apiContext.Config = GetConfig(); - - // Use this variant if you want to pass in a request id - // that is meaningful in your application, ideally - // a order id. - // String requestId = Long.toString(System.nanoTime(); - // APIContext apiContext = new APIContext(GetAccessToken(), requestId )); - - return apiContext; - } - - } -} - \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Web.Debug.config b/CSharp/capability-botToWeb/Bot/Web.Debug.config deleted file mode 100644 index 2e302f9f95..0000000000 --- a/CSharp/capability-botToWeb/Bot/Web.Debug.config +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Web.Release.config b/CSharp/capability-botToWeb/Bot/Web.Release.config deleted file mode 100644 index c35844462b..0000000000 --- a/CSharp/capability-botToWeb/Bot/Web.Release.config +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/Web.config b/CSharp/capability-botToWeb/Bot/Web.config deleted file mode 100644 index b9a8953cdc..0000000000 --- a/CSharp/capability-botToWeb/Bot/Web.config +++ /dev/null @@ -1,117 +0,0 @@ - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/CSharp/capability-botToWeb/Bot/default.htm b/CSharp/capability-botToWeb/Bot/default.htm deleted file mode 100644 index f5b046d607..0000000000 --- a/CSharp/capability-botToWeb/Bot/default.htm +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/packages.config b/CSharp/capability-botToWeb/Bot/packages.config deleted file mode 100644 index bed76df44d..0000000000 --- a/CSharp/capability-botToWeb/Bot/packages.config +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CSharp/capability-botToWeb/Bot/scripts/ai.0.22.19-build00125.js b/CSharp/capability-botToWeb/Bot/scripts/ai.0.22.19-build00125.js deleted file mode 100644 index e02b33ba13..0000000000 --- a/CSharp/capability-botToWeb/Bot/scripts/ai.0.22.19-build00125.js +++ /dev/null @@ -1,3859 +0,0 @@ -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - (function (LoggingSeverity) { - LoggingSeverity[LoggingSeverity["CRITICAL"] = 0] = "CRITICAL"; - LoggingSeverity[LoggingSeverity["WARNING"] = 1] = "WARNING"; - })(ApplicationInsights.LoggingSeverity || (ApplicationInsights.LoggingSeverity = {})); - var LoggingSeverity = ApplicationInsights.LoggingSeverity; - (function (_InternalMessageId) { - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserDoesNotSupportLocalStorage"] = 0] = "NONUSRACT_BrowserDoesNotSupportLocalStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserCannotReadLocalStorage"] = 1] = "NONUSRACT_BrowserCannotReadLocalStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserCannotReadSessionStorage"] = 2] = "NONUSRACT_BrowserCannotReadSessionStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserCannotWriteLocalStorage"] = 3] = "NONUSRACT_BrowserCannotWriteLocalStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserCannotWriteSessionStorage"] = 4] = "NONUSRACT_BrowserCannotWriteSessionStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserFailedRemovalFromLocalStorage"] = 5] = "NONUSRACT_BrowserFailedRemovalFromLocalStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_BrowserFailedRemovalFromSessionStorage"] = 6] = "NONUSRACT_BrowserFailedRemovalFromSessionStorage"; - _InternalMessageId[_InternalMessageId["NONUSRACT_CannotSendEmptyTelemetry"] = 7] = "NONUSRACT_CannotSendEmptyTelemetry"; - _InternalMessageId[_InternalMessageId["NONUSRACT_ClientPerformanceMathError"] = 8] = "NONUSRACT_ClientPerformanceMathError"; - _InternalMessageId[_InternalMessageId["NONUSRACT_ErrorParsingAISessionCookie"] = 9] = "NONUSRACT_ErrorParsingAISessionCookie"; - _InternalMessageId[_InternalMessageId["NONUSRACT_ErrorPVCalc"] = 10] = "NONUSRACT_ErrorPVCalc"; - _InternalMessageId[_InternalMessageId["NONUSRACT_ExceptionWhileLoggingError"] = 11] = "NONUSRACT_ExceptionWhileLoggingError"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedAddingTelemetryToBuffer"] = 12] = "NONUSRACT_FailedAddingTelemetryToBuffer"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedMonitorAjaxAbort"] = 13] = "NONUSRACT_FailedMonitorAjaxAbort"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedMonitorAjaxDur"] = 14] = "NONUSRACT_FailedMonitorAjaxDur"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedMonitorAjaxOpen"] = 15] = "NONUSRACT_FailedMonitorAjaxOpen"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedMonitorAjaxRSC"] = 16] = "NONUSRACT_FailedMonitorAjaxRSC"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedMonitorAjaxSend"] = 17] = "NONUSRACT_FailedMonitorAjaxSend"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedToAddHandlerForOnBeforeUnload"] = 18] = "NONUSRACT_FailedToAddHandlerForOnBeforeUnload"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedToSendQueuedTelemetry"] = 19] = "NONUSRACT_FailedToSendQueuedTelemetry"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailedToReportDataLoss"] = 20] = "NONUSRACT_FailedToReportDataLoss"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FlushFailed"] = 21] = "NONUSRACT_FlushFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_MessageLimitPerPVExceeded"] = 22] = "NONUSRACT_MessageLimitPerPVExceeded"; - _InternalMessageId[_InternalMessageId["NONUSRACT_MissingRequiredFieldSpecification"] = 23] = "NONUSRACT_MissingRequiredFieldSpecification"; - _InternalMessageId[_InternalMessageId["NONUSRACT_NavigationTimingNotSupported"] = 24] = "NONUSRACT_NavigationTimingNotSupported"; - _InternalMessageId[_InternalMessageId["NONUSRACT_OnError"] = 25] = "NONUSRACT_OnError"; - _InternalMessageId[_InternalMessageId["NONUSRACT_SessionRenewalDateIsZero"] = 26] = "NONUSRACT_SessionRenewalDateIsZero"; - _InternalMessageId[_InternalMessageId["NONUSRACT_SenderNotInitialized"] = 27] = "NONUSRACT_SenderNotInitialized"; - _InternalMessageId[_InternalMessageId["NONUSRACT_StartTrackEventFailed"] = 28] = "NONUSRACT_StartTrackEventFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_StopTrackEventFailed"] = 29] = "NONUSRACT_StopTrackEventFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_StartTrackFailed"] = 30] = "NONUSRACT_StartTrackFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_StopTrackFailed"] = 31] = "NONUSRACT_StopTrackFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TelemetrySampledAndNotSent"] = 32] = "NONUSRACT_TelemetrySampledAndNotSent"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TrackEventFailed"] = 33] = "NONUSRACT_TrackEventFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TrackExceptionFailed"] = 34] = "NONUSRACT_TrackExceptionFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TrackMetricFailed"] = 35] = "NONUSRACT_TrackMetricFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TrackPVFailed"] = 36] = "NONUSRACT_TrackPVFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TrackPVFailedCalc"] = 37] = "NONUSRACT_TrackPVFailedCalc"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TrackTraceFailed"] = 38] = "NONUSRACT_TrackTraceFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_TransmissionFailed"] = 39] = "NONUSRACT_TransmissionFailed"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailToSetStorageBuffer"] = 40] = "NONUSRACT_FailToSetStorageBuffer"; - _InternalMessageId[_InternalMessageId["NONUSRACT_FailToRestoreStorageBuffer"] = 41] = "NONUSRACT_FailToRestoreStorageBuffer"; - _InternalMessageId[_InternalMessageId["USRACT_CannotSerializeObject"] = 42] = "USRACT_CannotSerializeObject"; - _InternalMessageId[_InternalMessageId["USRACT_CannotSerializeObjectNonSerializable"] = 43] = "USRACT_CannotSerializeObjectNonSerializable"; - _InternalMessageId[_InternalMessageId["USRACT_CircularReferenceDetected"] = 44] = "USRACT_CircularReferenceDetected"; - _InternalMessageId[_InternalMessageId["USRACT_ClearAuthContextFailed"] = 45] = "USRACT_ClearAuthContextFailed"; - _InternalMessageId[_InternalMessageId["USRACT_ExceptionTruncated"] = 46] = "USRACT_ExceptionTruncated"; - _InternalMessageId[_InternalMessageId["USRACT_IllegalCharsInName"] = 47] = "USRACT_IllegalCharsInName"; - _InternalMessageId[_InternalMessageId["USRACT_ItemNotInArray"] = 48] = "USRACT_ItemNotInArray"; - _InternalMessageId[_InternalMessageId["USRACT_MaxAjaxPerPVExceeded"] = 49] = "USRACT_MaxAjaxPerPVExceeded"; - _InternalMessageId[_InternalMessageId["USRACT_MessageTruncated"] = 50] = "USRACT_MessageTruncated"; - _InternalMessageId[_InternalMessageId["USRACT_NameTooLong"] = 51] = "USRACT_NameTooLong"; - _InternalMessageId[_InternalMessageId["USRACT_SampleRateOutOfRange"] = 52] = "USRACT_SampleRateOutOfRange"; - _InternalMessageId[_InternalMessageId["USRACT_SetAuthContextFailed"] = 53] = "USRACT_SetAuthContextFailed"; - _InternalMessageId[_InternalMessageId["USRACT_SetAuthContextFailedAccountName"] = 54] = "USRACT_SetAuthContextFailedAccountName"; - _InternalMessageId[_InternalMessageId["USRACT_StringValueTooLong"] = 55] = "USRACT_StringValueTooLong"; - _InternalMessageId[_InternalMessageId["USRACT_StartCalledMoreThanOnce"] = 56] = "USRACT_StartCalledMoreThanOnce"; - _InternalMessageId[_InternalMessageId["USRACT_StopCalledWithoutStart"] = 57] = "USRACT_StopCalledWithoutStart"; - _InternalMessageId[_InternalMessageId["USRACT_TelemetryInitializerFailed"] = 58] = "USRACT_TelemetryInitializerFailed"; - _InternalMessageId[_InternalMessageId["USRACT_TrackArgumentsNotSpecified"] = 59] = "USRACT_TrackArgumentsNotSpecified"; - _InternalMessageId[_InternalMessageId["USRACT_UrlTooLong"] = 60] = "USRACT_UrlTooLong"; - })(ApplicationInsights._InternalMessageId || (ApplicationInsights._InternalMessageId = {})); - var _InternalMessageId = ApplicationInsights._InternalMessageId; - var _InternalLogMessage = (function () { - function _InternalLogMessage(msgId, msg, properties) { - this.message = _InternalMessageId[msgId].toString(); - this.messageId = msgId; - var diagnosticText = (msg ? " message:" + _InternalLogMessage.sanitizeDiagnosticText(msg) : "") + - (properties ? " props:" + _InternalLogMessage.sanitizeDiagnosticText(JSON.stringify(properties)) : ""); - this.message += diagnosticText; - } - _InternalLogMessage.sanitizeDiagnosticText = function (text) { - return "\"" + text.replace(/\"/g, "") + "\""; - }; - return _InternalLogMessage; - })(); - ApplicationInsights._InternalLogMessage = _InternalLogMessage; - var _InternalLogging = (function () { - function _InternalLogging() { - } - _InternalLogging.throwInternalNonUserActionable = function (severity, message) { - if (this.enableDebugExceptions()) { - throw message; - } - else { - if (typeof (message) !== "undefined" && !!message) { - if (typeof (message.message) !== "undefined") { - message.message = this.AiNonUserActionablePrefix + message.message; - if (this.verboseLogging()) { - this.warnToConsole(message.message); - } - this.logInternalMessage(severity, message); - } - } - } - }; - _InternalLogging.throwInternalUserActionable = function (severity, message) { - if (this.enableDebugExceptions()) { - throw message; - } - else { - if (typeof (message) !== "undefined" && !!message) { - if (typeof (message.message) !== "undefined") { - message.message = this.AiUserActionablePrefix + message.message; - this.warnToConsole(message.message); - this.logInternalMessage(severity, message); - } - } - } - }; - _InternalLogging.warnToConsole = function (message) { - if (typeof console !== "undefined" && !!console) { - if (typeof console.warn === "function") { - console.warn(message); - } - else if (typeof console.log === "function") { - console.log(message); - } - } - }; - _InternalLogging.resetInternalMessageCount = function () { - this._messageCount = 0; - }; - _InternalLogging.clearInternalMessageLoggedTypes = function () { - if (ApplicationInsights.Util.canUseSessionStorage()) { - var sessionStorageKeys = ApplicationInsights.Util.getSessionStorageKeys(); - for (var i = 0; i < sessionStorageKeys.length; i++) { - if (sessionStorageKeys[i].indexOf(_InternalLogging.AIInternalMessagePrefix) === 0) { - ApplicationInsights.Util.removeSessionStorage(sessionStorageKeys[i]); - } - } - } - }; - _InternalLogging.setMaxInternalMessageLimit = function (limit) { - if (!limit) { - throw new Error('limit cannot be undefined.'); - } - this.MAX_INTERNAL_MESSAGE_LIMIT = limit; - }; - _InternalLogging.logInternalMessage = function (severity, message) { - if (this._areInternalMessagesThrottled()) { - return; - } - var logMessage = true; - if (ApplicationInsights.Util.canUseSessionStorage()) { - var storageMessageKey = _InternalLogging.AIInternalMessagePrefix + _InternalMessageId[message.messageId]; - var internalMessageTypeLogRecord = ApplicationInsights.Util.getSessionStorage(storageMessageKey); - if (internalMessageTypeLogRecord) { - logMessage = false; - } - else { - ApplicationInsights.Util.setSessionStorage(storageMessageKey, "1"); - } - } - if (logMessage) { - if (this.verboseLogging() || severity === LoggingSeverity.CRITICAL) { - this.queue.push(message); - this._messageCount++; - } - if (this._messageCount == this.MAX_INTERNAL_MESSAGE_LIMIT) { - var throttleLimitMessage = "Internal events throttle limit per PageView reached for this app."; - var throttleMessage = new _InternalLogMessage(_InternalMessageId.NONUSRACT_MessageLimitPerPVExceeded, throttleLimitMessage); - this.queue.push(throttleMessage); - this.warnToConsole(throttleLimitMessage); - } - } - }; - _InternalLogging._areInternalMessagesThrottled = function () { - return this._messageCount >= this.MAX_INTERNAL_MESSAGE_LIMIT; - }; - _InternalLogging.AiUserActionablePrefix = "AI: "; - _InternalLogging.AIInternalMessagePrefix = "AITR_"; - _InternalLogging.AiNonUserActionablePrefix = "AI (Internal): "; - _InternalLogging.enableDebugExceptions = function () { return false; }; - _InternalLogging.verboseLogging = function () { return false; }; - _InternalLogging.queue = []; - _InternalLogging.MAX_INTERNAL_MESSAGE_LIMIT = 25; - _InternalLogging._messageCount = 0; - return _InternalLogging; - })(); - ApplicationInsights._InternalLogging = _InternalLogging; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var StorageType; - (function (StorageType) { - StorageType[StorageType["LocalStorage"] = 0] = "LocalStorage"; - StorageType[StorageType["SessionStorage"] = 1] = "SessionStorage"; - })(StorageType || (StorageType = {})); - var Util = (function () { - function Util() { - } - Util._getLocalStorageObject = function () { - return Util._getVerifiedStorageObject(StorageType.LocalStorage); - }; - Util._getVerifiedStorageObject = function (storageType) { - var storage = null; - var fail; - var uid; - try { - uid = new Date; - storage = storageType === StorageType.LocalStorage ? window.localStorage : window.sessionStorage; - storage.setItem(uid, uid); - fail = storage.getItem(uid) != uid; - storage.removeItem(uid); - if (fail) { - storage = null; - } - } - catch (exception) { - storage = null; - } - return storage; - }; - Util.canUseLocalStorage = function () { - return !!Util._getLocalStorageObject(); - }; - Util.getStorage = function (name) { - var storage = Util._getLocalStorageObject(); - if (storage !== null) { - try { - return storage.getItem(name); - } - catch (e) { - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserCannotReadLocalStorage, "Browser failed read of local storage. " + Util.getExceptionName(e), { exception: Util.dump(e) }); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, message); - } - } - return null; - }; - Util.setStorage = function (name, data) { - var storage = Util._getLocalStorageObject(); - if (storage !== null) { - try { - storage.setItem(name, data); - return true; - } - catch (e) { - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserCannotWriteLocalStorage, "Browser failed write to local storage. " + Util.getExceptionName(e), { exception: Util.dump(e) }); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, message); - } - } - return false; - }; - Util.removeStorage = function (name) { - var storage = Util._getLocalStorageObject(); - if (storage !== null) { - try { - storage.removeItem(name); - return true; - } - catch (e) { - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserFailedRemovalFromLocalStorage, "Browser failed removal of local storage item. " + Util.getExceptionName(e), { exception: Util.dump(e) }); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, message); - } - } - return false; - }; - Util._getSessionStorageObject = function () { - return Util._getVerifiedStorageObject(StorageType.SessionStorage); - }; - Util.canUseSessionStorage = function () { - return !!Util._getSessionStorageObject(); - }; - Util.getSessionStorageKeys = function () { - var keys = []; - if (Util.canUseSessionStorage()) { - for (var key in window.sessionStorage) { - keys.push(key); - } - } - return keys; - }; - Util.getSessionStorage = function (name) { - var storage = Util._getSessionStorageObject(); - if (storage !== null) { - try { - return storage.getItem(name); - } - catch (e) { - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserCannotReadSessionStorage, "Browser failed read of session storage. " + Util.getExceptionName(e), { exception: Util.dump(e) }); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, message); - } - } - return null; - }; - Util.setSessionStorage = function (name, data) { - var storage = Util._getSessionStorageObject(); - if (storage !== null) { - try { - storage.setItem(name, data); - return true; - } - catch (e) { - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserCannotWriteSessionStorage, "Browser failed write to session storage. " + Util.getExceptionName(e), { exception: Util.dump(e) }); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, message); - } - } - return false; - }; - Util.removeSessionStorage = function (name) { - var storage = Util._getSessionStorageObject(); - if (storage !== null) { - try { - storage.removeItem(name); - return true; - } - catch (e) { - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserFailedRemovalFromSessionStorage, "Browser failed removal of session storage item. " + Util.getExceptionName(e), { exception: Util.dump(e) }); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, message); - } - } - return false; - }; - Util.setCookie = function (name, value, domain) { - var domainAttrib = ""; - if (domain) { - domainAttrib = ";domain=" + domain; - } - Util.document.cookie = name + "=" + value + domainAttrib + ";path=/"; - }; - Util.stringToBoolOrDefault = function (str) { - if (!str) { - return false; - } - return str.toString().toLowerCase() === "true"; - }; - Util.getCookie = function (name) { - var value = ""; - if (name && name.length) { - var cookieName = name + "="; - var cookies = Util.document.cookie.split(";"); - for (var i = 0; i < cookies.length; i++) { - var cookie = cookies[i]; - cookie = Util.trim(cookie); - if (cookie && cookie.indexOf(cookieName) === 0) { - value = cookie.substring(cookieName.length, cookies[i].length); - break; - } - } - } - return value; - }; - Util.deleteCookie = function (name) { - Util.document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;"; - }; - Util.trim = function (str) { - if (typeof str !== "string") - return str; - return str.replace(/^\s+|\s+$/g, ""); - }; - Util.newId = function () { - var base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - var result = ""; - var random = Math.random() * 1073741824; - while (random > 0) { - var char = base64chars.charAt(random % 64); - result += char; - random = Math.floor(random / 64); - } - return result; - }; - Util.isArray = function (obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - Util.isError = function (obj) { - return Object.prototype.toString.call(obj) === "[object Error]"; - }; - Util.isDate = function (obj) { - return Object.prototype.toString.call(obj) === "[object Date]"; - }; - Util.toISOStringForIE8 = function (date) { - if (Util.isDate(date)) { - if (Date.prototype.toISOString) { - return date.toISOString(); - } - else { - function pad(number) { - var r = String(number); - if (r.length === 1) { - r = "0" + r; - } - return r; - } - return date.getUTCFullYear() - + "-" + pad(date.getUTCMonth() + 1) - + "-" + pad(date.getUTCDate()) - + "T" + pad(date.getUTCHours()) - + ":" + pad(date.getUTCMinutes()) - + ":" + pad(date.getUTCSeconds()) - + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) - + "Z"; - } - } - }; - Util.getIEVersion = function (userAgentStr) { - if (userAgentStr === void 0) { userAgentStr = null; } - var myNav = userAgentStr ? userAgentStr.toLowerCase() : navigator.userAgent.toLowerCase(); - return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : null; - }; - Util.msToTimeSpan = function (totalms) { - if (isNaN(totalms) || totalms < 0) { - totalms = 0; - } - var ms = "" + totalms % 1000; - var sec = "" + Math.floor(totalms / 1000) % 60; - var min = "" + Math.floor(totalms / (1000 * 60)) % 60; - var hour = "" + Math.floor(totalms / (1000 * 60 * 60)) % 24; - ms = ms.length === 1 ? "00" + ms : ms.length === 2 ? "0" + ms : ms; - sec = sec.length < 2 ? "0" + sec : sec; - min = min.length < 2 ? "0" + min : min; - hour = hour.length < 2 ? "0" + hour : hour; - return hour + ":" + min + ":" + sec + "." + ms; - }; - Util.isCrossOriginError = function (message, url, lineNumber, columnNumber, error) { - return (message === "Script error." || message === "Script error") && error === null; - }; - Util.dump = function (object) { - var objectTypeDump = Object.prototype.toString.call(object); - var propertyValueDump = JSON.stringify(object); - if (objectTypeDump === "[object Error]") { - propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'"; - } - return objectTypeDump + propertyValueDump; - }; - Util.getExceptionName = function (object) { - var objectTypeDump = Object.prototype.toString.call(object); - if (objectTypeDump === "[object Error]") { - return object.name; - } - return ""; - }; - Util.addEventHandler = function (eventName, callback) { - if (!window || typeof eventName !== 'string' || typeof callback !== 'function') { - return false; - } - var verbEventName = 'on' + eventName; - if (window.addEventListener) { - window.addEventListener(eventName, callback, false); - } - else if (window["attachEvent"]) { - window["attachEvent"].call(verbEventName, callback); - } - else { - return false; - } - return true; - }; - Util.document = typeof document !== "undefined" ? document : {}; - Util.NotSpecified = "not_specified"; - return Util; - })(); - ApplicationInsights.Util = Util; - var UrlHelper = (function () { - function UrlHelper() { - } - UrlHelper.parseUrl = function (url) { - if (!UrlHelper.htmlAnchorElement) { - UrlHelper.htmlAnchorElement = !!UrlHelper.document.createElement ? UrlHelper.document.createElement('a') : {}; - } - UrlHelper.htmlAnchorElement.href = url; - return UrlHelper.htmlAnchorElement; - }; - UrlHelper.getAbsoluteUrl = function (url) { - var result; - var a = UrlHelper.parseUrl(url); - if (a) { - result = a.href; - } - return result; - }; - UrlHelper.getPathName = function (url) { - var result; - var a = UrlHelper.parseUrl(url); - if (a) { - result = a.pathname; - } - return result; - }; - UrlHelper.document = typeof document !== "undefined" ? document : {}; - return UrlHelper; - })(); - ApplicationInsights.UrlHelper = UrlHelper; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var extensions = (function () { - function extensions() { - } - extensions.IsNullOrUndefined = function (obj) { - return typeof (obj) === "undefined" || obj === null; - }; - return extensions; - })(); - ApplicationInsights.extensions = extensions; - var stringUtils = (function () { - function stringUtils() { - } - stringUtils.GetLength = function (strObject) { - var res = 0; - if (!extensions.IsNullOrUndefined(strObject)) { - var stringified = ""; - try { - stringified = strObject.toString(); - } - catch (ex) { - } - res = stringified.length; - res = isNaN(res) ? 0 : res; - } - return res; - }; - return stringUtils; - })(); - ApplicationInsights.stringUtils = stringUtils; - var dateTime = (function () { - function dateTime() { - } - dateTime.Now = (window.performance && window.performance.now) ? - function () { - return performance.now(); - } - : - function () { - return new Date().getTime(); - }; - dateTime.GetDuration = function (start, end) { - var result = null; - if (start !== 0 && end !== 0 && !extensions.IsNullOrUndefined(start) && !extensions.IsNullOrUndefined(end)) { - result = end - start; - } - return result; - }; - return dateTime; - })(); - ApplicationInsights.dateTime = dateTime; - var EventHelper = (function () { - function EventHelper() { - } - EventHelper.AttachEvent = function (obj, eventNameWithoutOn, handlerRef) { - var result = false; - if (!extensions.IsNullOrUndefined(obj)) { - if (!extensions.IsNullOrUndefined(obj.attachEvent)) { - obj.attachEvent("on" + eventNameWithoutOn, handlerRef); - result = true; - } - else { - if (!extensions.IsNullOrUndefined(obj.addEventListener)) { - obj.addEventListener(eventNameWithoutOn, handlerRef, false); - result = true; - } - } - } - return result; - }; - EventHelper.DetachEvent = function (obj, eventNameWithoutOn, handlerRef) { - if (!extensions.IsNullOrUndefined(obj)) { - if (!extensions.IsNullOrUndefined(obj.detachEvent)) { - obj.detachEvent("on" + eventNameWithoutOn, handlerRef); - } - else { - if (!extensions.IsNullOrUndefined(obj.removeEventListener)) { - obj.removeEventListener(eventNameWithoutOn, handlerRef, false); - } - } - } - }; - return EventHelper; - })(); - ApplicationInsights.EventHelper = EventHelper; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var XHRMonitoringState = (function () { - function XHRMonitoringState() { - this.openDone = false; - this.setRequestHeaderDone = false; - this.sendDone = false; - this.abortDone = false; - this.onreadystatechangeCallbackAttached = false; - } - return XHRMonitoringState; - })(); - ApplicationInsights.XHRMonitoringState = XHRMonitoringState; - var ajaxRecord = (function () { - function ajaxRecord(id) { - this.completed = false; - this.requestHeadersSize = null; - this.ttfb = null; - this.responseReceivingDuration = null; - this.callbackDuration = null; - this.ajaxTotalDuration = null; - this.aborted = null; - this.pageUrl = null; - this.requestUrl = null; - this.requestSize = 0; - this.method = null; - this.status = null; - this.requestSentTime = null; - this.responseStartedTime = null; - this.responseFinishedTime = null; - this.callbackFinishedTime = null; - this.endTime = null; - this.originalOnreadystatechage = null; - this.xhrMonitoringState = new XHRMonitoringState(); - this.clientFailure = 0; - this.CalculateMetrics = function () { - var self = this; - self.ajaxTotalDuration = ApplicationInsights.dateTime.GetDuration(self.requestSentTime, self.responseFinishedTime); - }; - this.id = id; - } - ajaxRecord.prototype.getAbsoluteUrl = function () { - return this.requestUrl ? ApplicationInsights.UrlHelper.getAbsoluteUrl(this.requestUrl) : null; - }; - ajaxRecord.prototype.getPathName = function () { - return this.requestUrl ? ApplicationInsights.UrlHelper.getPathName(this.requestUrl) : null; - }; - return ajaxRecord; - })(); - ApplicationInsights.ajaxRecord = ajaxRecord; - ; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -; -/// -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var AjaxMonitor = (function () { - function AjaxMonitor(appInsights) { - this.currentWindowHost = window.location.host; - this.appInsights = appInsights; - this.initialized = false; - this.Init(); - } - AjaxMonitor.prototype.Init = function () { - if (this.supportsMonitoring()) { - this.instrumentOpen(); - this.instrumentSend(); - this.instrumentAbort(); - this.initialized = true; - } - }; - AjaxMonitor.prototype.isMonitoredInstance = function (xhr, excludeAjaxDataValidation) { - return this.initialized - && (excludeAjaxDataValidation === true || !ApplicationInsights.extensions.IsNullOrUndefined(xhr.ajaxData)) - && xhr[AjaxMonitor.DisabledPropertyName] !== true; - }; - AjaxMonitor.prototype.supportsMonitoring = function () { - var result = false; - if (!ApplicationInsights.extensions.IsNullOrUndefined(XMLHttpRequest)) { - result = true; - } - return result; - }; - AjaxMonitor.prototype.instrumentOpen = function () { - var originalOpen = XMLHttpRequest.prototype.open; - var ajaxMonitorInstance = this; - XMLHttpRequest.prototype.open = function (method, url, async) { - try { - if (ajaxMonitorInstance.isMonitoredInstance(this, true) && - (!this.ajaxData || - !this.ajaxData.xhrMonitoringState.openDone)) { - ajaxMonitorInstance.openHandler(this, method, url, async); - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedMonitorAjaxOpen, "Failed to monitor XMLHttpRequest.open, monitoring data for this ajax call may be incorrect.", { - ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(this), - exception: Microsoft.ApplicationInsights.Util.dump(e) - })); - } - return originalOpen.apply(this, arguments); - }; - }; - AjaxMonitor.prototype.openHandler = function (xhr, method, url, async) { - var ajaxData = new ApplicationInsights.ajaxRecord(ApplicationInsights.Util.newId()); - ajaxData.method = method; - ajaxData.requestUrl = url; - ajaxData.xhrMonitoringState.openDone = true; - xhr.ajaxData = ajaxData; - this.attachToOnReadyStateChange(xhr); - }; - AjaxMonitor.getFailedAjaxDiagnosticsMessage = function (xhr) { - var result = ""; - try { - if (!ApplicationInsights.extensions.IsNullOrUndefined(xhr) && - !ApplicationInsights.extensions.IsNullOrUndefined(xhr.ajaxData) && - !ApplicationInsights.extensions.IsNullOrUndefined(xhr.ajaxData.requestUrl)) { - result += "(url: '" + xhr.ajaxData.requestUrl + "')"; - } - } - catch (e) { } - return result; - }; - AjaxMonitor.prototype.instrumentSend = function () { - var originalSend = XMLHttpRequest.prototype.send; - var ajaxMonitorInstance = this; - XMLHttpRequest.prototype.send = function (content) { - try { - if (ajaxMonitorInstance.isMonitoredInstance(this) && !this.ajaxData.xhrMonitoringState.sendDone) { - ajaxMonitorInstance.sendHandler(this, content); - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedMonitorAjaxSend, "Failed to monitor XMLHttpRequest, monitoring data for this ajax call may be incorrect.", { - ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(this), - exception: Microsoft.ApplicationInsights.Util.dump(e) - })); - } - return originalSend.apply(this, arguments); - }; - }; - AjaxMonitor.prototype.sendHandler = function (xhr, content) { - xhr.ajaxData.requestSentTime = ApplicationInsights.dateTime.Now(); - if (!this.appInsights.config.disableCorrelationHeaders && (ApplicationInsights.UrlHelper.parseUrl(xhr.ajaxData.getAbsoluteUrl()).host == this.currentWindowHost)) { - xhr.setRequestHeader("x-ms-request-id", xhr.ajaxData.id); - } - xhr.ajaxData.xhrMonitoringState.sendDone = true; - }; - AjaxMonitor.prototype.instrumentAbort = function () { - var originalAbort = XMLHttpRequest.prototype.abort; - var ajaxMonitorInstance = this; - XMLHttpRequest.prototype.abort = function () { - try { - if (ajaxMonitorInstance.isMonitoredInstance(this) && !this.ajaxData.xhrMonitoringState.abortDone) { - this.ajaxData.aborted = 1; - this.ajaxData.xhrMonitoringState.abortDone = true; - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedMonitorAjaxAbort, "Failed to monitor XMLHttpRequest.abort, monitoring data for this ajax call may be incorrect.", { - ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(this), - exception: Microsoft.ApplicationInsights.Util.dump(e) - })); - } - return originalAbort.apply(this, arguments); - }; - }; - AjaxMonitor.prototype.attachToOnReadyStateChange = function (xhr) { - var ajaxMonitorInstance = this; - xhr.ajaxData.xhrMonitoringState.onreadystatechangeCallbackAttached = ApplicationInsights.EventHelper.AttachEvent(xhr, "readystatechange", function () { - try { - if (ajaxMonitorInstance.isMonitoredInstance(xhr)) { - if (xhr.readyState === 4) { - ajaxMonitorInstance.onAjaxComplete(xhr); - } - } - } - catch (e) { - var exceptionText = Microsoft.ApplicationInsights.Util.dump(e); - if (!exceptionText || exceptionText.toLowerCase().indexOf("c00c023f") == -1) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedMonitorAjaxRSC, "Failed to monitor XMLHttpRequest 'readystatechange' event handler, monitoring data for this ajax call may be incorrect.", { - ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr), - exception: Microsoft.ApplicationInsights.Util.dump(e) - })); - } - } - }); - }; - AjaxMonitor.prototype.onAjaxComplete = function (xhr) { - xhr.ajaxData.responseFinishedTime = ApplicationInsights.dateTime.Now(); - xhr.ajaxData.status = xhr.status; - xhr.ajaxData.CalculateMetrics(); - if (xhr.ajaxData.ajaxTotalDuration < 0) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedMonitorAjaxDur, "Failed to calculate the duration of the ajax call, monitoring data for this ajax call won't be sent.", { - ajaxDiagnosticsMessage: AjaxMonitor.getFailedAjaxDiagnosticsMessage(xhr), - requestSentTime: xhr.ajaxData.requestSentTime, - responseFinishedTime: xhr.ajaxData.responseFinishedTime - })); - } - else { - this.appInsights.trackAjax(xhr.ajaxData.id, xhr.ajaxData.getAbsoluteUrl(), xhr.ajaxData.getPathName(), xhr.ajaxData.ajaxTotalDuration, (+(xhr.ajaxData.status)) >= 200 && (+(xhr.ajaxData.status)) < 400, +xhr.ajaxData.status, xhr.ajaxData.method); - xhr.ajaxData = null; - } - }; - AjaxMonitor.instrumentedByAppInsightsName = "InstrumentedByAppInsights"; - AjaxMonitor.DisabledPropertyName = "Microsoft_ApplicationInsights_BypassAjaxInstrumentation"; - return AjaxMonitor; - })(); - ApplicationInsights.AjaxMonitor = AjaxMonitor; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var HashCodeScoreGenerator = (function () { - function HashCodeScoreGenerator() { - } - HashCodeScoreGenerator.prototype.getHashCodeScore = function (key) { - var score = this.getHashCode(key) / HashCodeScoreGenerator.INT_MAX_VALUE; - return score * 100; - }; - HashCodeScoreGenerator.prototype.getHashCode = function (input) { - if (input == "") { - return 0; - } - while (input.length < HashCodeScoreGenerator.MIN_INPUT_LENGTH) { - input = input.concat(input); - } - var hash = 5381; - for (var i = 0; i < input.length; ++i) { - hash = ((hash << 5) + hash) + input.charCodeAt(i); - hash = hash & hash; - } - return Math.abs(hash); - }; - HashCodeScoreGenerator.INT_MAX_VALUE = 2147483647; - HashCodeScoreGenerator.MIN_INPUT_LENGTH = 8; - return HashCodeScoreGenerator; - })(); - ApplicationInsights.HashCodeScoreGenerator = HashCodeScoreGenerator; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - (function (FieldType) { - FieldType[FieldType["Default"] = 0] = "Default"; - FieldType[FieldType["Required"] = 1] = "Required"; - FieldType[FieldType["Array"] = 2] = "Array"; - FieldType[FieldType["Hidden"] = 4] = "Hidden"; - })(ApplicationInsights.FieldType || (ApplicationInsights.FieldType = {})); - var FieldType = ApplicationInsights.FieldType; - ; - var Serializer = (function () { - function Serializer() { - } - Serializer.serialize = function (input) { - var output = Serializer._serializeObject(input, "root"); - return JSON.stringify(output); - }; - Serializer._serializeObject = function (source, name) { - var circularReferenceCheck = "__aiCircularRefCheck"; - var output = {}; - if (!source) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_CannotSerializeObject, "cannot serialize object because it is null or undefined", { name: name })); - return output; - } - if (source[circularReferenceCheck]) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_CircularReferenceDetected, "Circular reference detected while serializing object", { name: name })); - return output; - } - if (!source.aiDataContract) { - if (name === "measurements") { - output = Serializer._serializeStringMap(source, "number", name); - } - else if (name === "properties") { - output = Serializer._serializeStringMap(source, "string", name); - } - else if (name === "tags") { - output = Serializer._serializeStringMap(source, "string", name); - } - else if (ApplicationInsights.Util.isArray(source)) { - output = Serializer._serializeArray(source, name); - } - else { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_CannotSerializeObjectNonSerializable, "Attempting to serialize an object which does not implement ISerializable", { name: name })); - try { - JSON.stringify(source); - output = source; - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, e && typeof e.toString === 'function' ? e.toString() : "Error serializing object"); - } - } - return output; - } - source[circularReferenceCheck] = true; - for (var field in source.aiDataContract) { - var contract = source.aiDataContract[field]; - var isRequired = (typeof contract === "function") ? (contract() & FieldType.Required) : (contract & FieldType.Required); - var isHidden = (typeof contract === "function") ? (contract() & FieldType.Hidden) : (contract & FieldType.Hidden); - var isArray = contract & FieldType.Array; - var isPresent = source[field] !== undefined; - var isObject = typeof source[field] === "object" && source[field] !== null; - if (isRequired && !isPresent && !isArray) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_MissingRequiredFieldSpecification, "Missing required field specification. The field is required but not present on source", { field: field, name: name })); - continue; - } - if (isHidden) { - continue; - } - var value; - if (isObject) { - if (isArray) { - value = Serializer._serializeArray(source[field], field); - } - else { - value = Serializer._serializeObject(source[field], field); - } - } - else { - value = source[field]; - } - if (value !== undefined) { - output[field] = value; - } - } - delete source[circularReferenceCheck]; - return output; - }; - Serializer._serializeArray = function (sources, name) { - var output = undefined; - if (!!sources) { - if (!ApplicationInsights.Util.isArray(sources)) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_ItemNotInArray, "This field was specified as an array in the contract but the item is not an array.\r\n", { name: name })); - } - else { - output = []; - for (var i = 0; i < sources.length; i++) { - var source = sources[i]; - var item = Serializer._serializeObject(source, name + "[" + i + "]"); - output.push(item); - } - } - } - return output; - }; - Serializer._serializeStringMap = function (map, expectedType, name) { - var output = undefined; - if (map) { - output = {}; - for (var field in map) { - var value = map[field]; - if (expectedType === "string") { - if (value === undefined) { - output[field] = "undefined"; - } - else if (value === null) { - output[field] = "null"; - } - else if (!value.toString) { - output[field] = "invalid field: toString() is not defined."; - } - else { - output[field] = value.toString(); - } - } - else if (expectedType === "number") { - if (value === undefined) { - output[field] = "undefined"; - } - else if (value === null) { - output[field] = "null"; - } - else { - var num = parseFloat(value); - if (isNaN(num)) { - output[field] = "NaN"; - } - else { - output[field] = num; - } - } - } - else { - output[field] = "invalid field: " + name + " is of unknown type."; - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, output[field]); - } - } - } - return output; - }; - return Serializer; - })(); - ApplicationInsights.Serializer = Serializer; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Base = (function () { - function Base() { - } - return Base; - })(); - Telemetry.Base = Base; - })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Envelope = (function () { - function Envelope() { - this.ver = 1; - this.sampleRate = 100.0; - this.tags = {}; - } - return Envelope; - })(); - Telemetry.Envelope = Envelope; - })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -var __extends = (this && this.__extends) || function (d, b) { - for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - var Common; - (function (Common) { - "use strict"; - var Envelope = (function (_super) { - __extends(Envelope, _super); - function Envelope(data, name) { - var _this = this; - _super.call(this); - this.name = Common.DataSanitizer.sanitizeString(name) || ApplicationInsights.Util.NotSpecified; - this.data = data; - this.time = ApplicationInsights.Util.toISOStringForIE8(new Date()); - this.aiDataContract = { - time: ApplicationInsights.FieldType.Required, - iKey: ApplicationInsights.FieldType.Required, - name: ApplicationInsights.FieldType.Required, - sampleRate: function () { - return (_this.sampleRate == 100) ? ApplicationInsights.FieldType.Hidden : ApplicationInsights.FieldType.Required; - }, - tags: ApplicationInsights.FieldType.Required, - data: ApplicationInsights.FieldType.Required, - }; - } - return Envelope; - })(Microsoft.Telemetry.Envelope); - Common.Envelope = Envelope; - })(Common = Telemetry.Common || (Telemetry.Common = {})); - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - var Common; - (function (Common) { - "use strict"; - var Base = (function (_super) { - __extends(Base, _super); - function Base() { - _super.apply(this, arguments); - this.aiDataContract = {}; - } - return Base; - })(Microsoft.Telemetry.Base); - Common.Base = Base; - })(Common = Telemetry.Common || (Telemetry.Common = {})); - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var AI; -(function (AI) { - "use strict"; - var ContextTagKeys = (function () { - function ContextTagKeys() { - this.applicationVersion = "ai.application.ver"; - this.applicationBuild = "ai.application.build"; - this.applicationTypeId = "ai.application.typeId"; - this.applicationId = "ai.application.applicationId"; - this.deviceId = "ai.device.id"; - this.deviceIp = "ai.device.ip"; - this.deviceLanguage = "ai.device.language"; - this.deviceLocale = "ai.device.locale"; - this.deviceModel = "ai.device.model"; - this.deviceNetwork = "ai.device.network"; - this.deviceNetworkName = "ai.device.networkName"; - this.deviceOEMName = "ai.device.oemName"; - this.deviceOS = "ai.device.os"; - this.deviceOSVersion = "ai.device.osVersion"; - this.deviceRoleInstance = "ai.device.roleInstance"; - this.deviceRoleName = "ai.device.roleName"; - this.deviceScreenResolution = "ai.device.screenResolution"; - this.deviceType = "ai.device.type"; - this.deviceMachineName = "ai.device.machineName"; - this.deviceVMName = "ai.device.vmName"; - this.locationIp = "ai.location.ip"; - this.operationId = "ai.operation.id"; - this.operationName = "ai.operation.name"; - this.operationParentId = "ai.operation.parentId"; - this.operationRootId = "ai.operation.rootId"; - this.operationSyntheticSource = "ai.operation.syntheticSource"; - this.operationIsSynthetic = "ai.operation.isSynthetic"; - this.operationCorrelationVector = "ai.operation.correlationVector"; - this.sessionId = "ai.session.id"; - this.sessionIsFirst = "ai.session.isFirst"; - this.sessionIsNew = "ai.session.isNew"; - this.userAccountAcquisitionDate = "ai.user.accountAcquisitionDate"; - this.userAccountId = "ai.user.accountId"; - this.userAgent = "ai.user.userAgent"; - this.userId = "ai.user.id"; - this.userStoreRegion = "ai.user.storeRegion"; - this.userAuthUserId = "ai.user.authUserId"; - this.userAnonymousUserAcquisitionDate = "ai.user.anonUserAcquisitionDate"; - this.userAuthenticatedUserAcquisitionDate = "ai.user.authUserAcquisitionDate"; - this.sampleRate = "ai.sample.sampleRate"; - this.cloudName = "ai.cloud.name"; - this.cloudRoleVer = "ai.cloud.roleVer"; - this.cloudEnvironment = "ai.cloud.environment"; - this.cloudLocation = "ai.cloud.location"; - this.cloudDeploymentUnit = "ai.cloud.deploymentUnit"; - this.serverDeviceOS = "ai.serverDevice.os"; - this.serverDeviceOSVer = "ai.serverDevice.osVer"; - this.internalSdkVersion = "ai.internal.sdkVersion"; - this.internalAgentVersion = "ai.internal.agentVersion"; - this.internalDataCollectorReceivedTime = "ai.internal.dataCollectorReceivedTime"; - this.internalProfileId = "ai.internal.profileId"; - this.internalProfileClassId = "ai.internal.profileClassId"; - this.internalAccountId = "ai.internal.accountId"; - this.internalApplicationName = "ai.internal.applicationName"; - this.internalInstrumentationKey = "ai.internal.instrumentationKey"; - this.internalTelemetryItemId = "ai.internal.telemetryItemId"; - this.internalApplicationType = "ai.internal.applicationType"; - this.internalRequestSource = "ai.internal.requestSource"; - this.internalFlowType = "ai.internal.flowType"; - this.internalIsAudit = "ai.internal.isAudit"; - this.internalTrackingSourceId = "ai.internal.trackingSourceId"; - this.internalTrackingType = "ai.internal.trackingType"; - this.internalIsDiagnosticExample = "ai.internal.isDiagnosticExample"; - } - return ContextTagKeys; - })(); - AI.ContextTagKeys = ContextTagKeys; -})(AI || (AI = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Application = (function () { - function Application() { - } - return Application; - })(); - Context.Application = Application; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Device = (function () { - function Device() { - this.id = "browser"; - this.type = "Browser"; - } - return Device; - })(); - Context.Device = Device; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Internal = (function () { - function Internal() { - this.sdkVersion = "javascript:" + ApplicationInsights.Version; - } - return Internal; - })(); - Context.Internal = Internal; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Location = (function () { - function Location() { - } - return Location; - })(); - Context.Location = Location; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Operation = (function () { - function Operation() { - this.id = ApplicationInsights.Util.newId(); - if (window && window.location && window.location.pathname) { - this.name = window.location.pathname; - } - } - return Operation; - })(); - Context.Operation = Operation; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var SamplingScoreGenerator = (function () { - function SamplingScoreGenerator() { - this.hashCodeGeneragor = new ApplicationInsights.HashCodeScoreGenerator(); - } - SamplingScoreGenerator.prototype.getSamplingScore = function (envelope) { - var tagKeys = new AI.ContextTagKeys(); - var score = 0; - if (envelope.tags[tagKeys.userId]) { - score = this.hashCodeGeneragor.getHashCodeScore(envelope.tags[tagKeys.userId]); - } - else if (envelope.tags[tagKeys.operationId]) { - score = this.hashCodeGeneragor.getHashCodeScore(envelope.tags[tagKeys.operationId]); - } - else { - score = Math.random(); - } - return score; - }; - return SamplingScoreGenerator; - })(); - ApplicationInsights.SamplingScoreGenerator = SamplingScoreGenerator; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Sample = (function () { - function Sample(sampleRate) { - this.INT_MAX_VALUE = 2147483647; - if (sampleRate > 100 || sampleRate < 0) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_SampleRateOutOfRange, "Sampling rate is out of range (0..100). Sampling will be disabled, you may be sending too much data which may affect your AI service level.", { samplingRate: sampleRate })); - this.sampleRate = 100; - } - this.sampleRate = sampleRate; - this.samplingScoreGenerator = new ApplicationInsights.SamplingScoreGenerator(); - } - Sample.prototype.isSampledIn = function (envelope) { - if (this.sampleRate == 100) - return true; - var score = this.samplingScoreGenerator.getSamplingScore(envelope); - return score < this.sampleRate; - }; - return Sample; - })(); - Context.Sample = Sample; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var AI; -(function (AI) { - "use strict"; - (function (SessionState) { - SessionState[SessionState["Start"] = 0] = "Start"; - SessionState[SessionState["End"] = 1] = "End"; - })(AI.SessionState || (AI.SessionState = {})); - var SessionState = AI.SessionState; -})(AI || (AI = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var Session = (function () { - function Session() { - } - return Session; - })(); - Context.Session = Session; - var _SessionManager = (function () { - function _SessionManager(config) { - if (!config) { - config = {}; - } - if (!(typeof config.sessionExpirationMs === "function")) { - config.sessionExpirationMs = function () { return _SessionManager.acquisitionSpan; }; - } - if (!(typeof config.sessionRenewalMs === "function")) { - config.sessionRenewalMs = function () { return _SessionManager.renewalSpan; }; - } - this.config = config; - this.automaticSession = new Session(); - } - _SessionManager.prototype.update = function () { - if (!this.automaticSession.id) { - this.initializeAutomaticSession(); - } - var now = +new Date; - var acquisitionExpired = now - this.automaticSession.acquisitionDate > this.config.sessionExpirationMs(); - var renewalExpired = now - this.automaticSession.renewalDate > this.config.sessionRenewalMs(); - if (acquisitionExpired || renewalExpired) { - this.automaticSession.isFirst = undefined; - this.renew(); - } - else { - this.automaticSession.renewalDate = +new Date; - this.setCookie(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate); - } - }; - _SessionManager.prototype.backup = function () { - this.setStorage(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate); - }; - _SessionManager.prototype.initializeAutomaticSession = function () { - var cookie = ApplicationInsights.Util.getCookie('ai_session'); - if (cookie && typeof cookie.split === "function") { - this.initializeAutomaticSessionWithData(cookie); - } - else { - var storage = ApplicationInsights.Util.getStorage('ai_session'); - if (storage) { - this.initializeAutomaticSessionWithData(storage); - } - } - if (!this.automaticSession.id) { - this.automaticSession.isFirst = true; - this.renew(); - } - }; - _SessionManager.prototype.initializeAutomaticSessionWithData = function (sessionData) { - var params = sessionData.split("|"); - if (params.length > 0) { - this.automaticSession.id = params[0]; - } - try { - if (params.length > 1) { - var acq = +params[1]; - this.automaticSession.acquisitionDate = +new Date(acq); - this.automaticSession.acquisitionDate = this.automaticSession.acquisitionDate > 0 ? this.automaticSession.acquisitionDate : 0; - } - if (params.length > 2) { - var renewal = +params[2]; - this.automaticSession.renewalDate = +new Date(renewal); - this.automaticSession.renewalDate = this.automaticSession.renewalDate > 0 ? this.automaticSession.renewalDate : 0; - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_ErrorParsingAISessionCookie, "Error parsing ai_session cookie, session will be reset: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - if (this.automaticSession.renewalDate == 0) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_SessionRenewalDateIsZero, "AI session renewal date is 0, session will be reset.")); - } - }; - _SessionManager.prototype.renew = function () { - var now = +new Date; - this.automaticSession.id = ApplicationInsights.Util.newId(); - this.automaticSession.acquisitionDate = now; - this.automaticSession.renewalDate = now; - this.setCookie(this.automaticSession.id, this.automaticSession.acquisitionDate, this.automaticSession.renewalDate); - if (!ApplicationInsights.Util.canUseLocalStorage()) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_BrowserDoesNotSupportLocalStorage, "Browser does not support local storage. Session durations will be inaccurate.")); - } - }; - _SessionManager.prototype.setCookie = function (guid, acq, renewal) { - var acquisitionExpiry = acq + this.config.sessionExpirationMs(); - var renewalExpiry = renewal + this.config.sessionRenewalMs(); - var cookieExpiry = new Date(); - var cookie = [guid, acq, renewal]; - if (acquisitionExpiry < renewalExpiry) { - cookieExpiry.setTime(acquisitionExpiry); - } - else { - cookieExpiry.setTime(renewalExpiry); - } - var cookieDomnain = this.config.cookieDomain ? this.config.cookieDomain() : null; - ApplicationInsights.Util.setCookie('ai_session', cookie.join('|') + ';expires=' + cookieExpiry.toUTCString(), cookieDomnain); - }; - _SessionManager.prototype.setStorage = function (guid, acq, renewal) { - ApplicationInsights.Util.setStorage('ai_session', [guid, acq, renewal].join('|')); - }; - _SessionManager.acquisitionSpan = 86400000; - _SessionManager.renewalSpan = 1800000; - return _SessionManager; - })(); - Context._SessionManager = _SessionManager; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Context; - (function (Context) { - "use strict"; - var User = (function () { - function User(config) { - var cookie = ApplicationInsights.Util.getCookie(User.userCookieName); - if (cookie) { - var params = cookie.split(User.cookieSeparator); - if (params.length > 0) { - this.id = params[0]; - } - } - this.config = config; - if (!this.id) { - this.id = ApplicationInsights.Util.newId(); - var date = new Date(); - var acqStr = ApplicationInsights.Util.toISOStringForIE8(date); - this.accountAcquisitionDate = acqStr; - date.setTime(date.getTime() + 31536000000); - var newCookie = [this.id, acqStr]; - var cookieDomain = this.config.cookieDomain ? this.config.cookieDomain() : undefined; - ApplicationInsights.Util.setCookie(User.userCookieName, newCookie.join(User.cookieSeparator) + ';expires=' + date.toUTCString(), cookieDomain); - ApplicationInsights.Util.removeStorage('ai_session'); - } - this.accountId = config.accountId ? config.accountId() : undefined; - var authCookie = ApplicationInsights.Util.getCookie(User.authUserCookieName); - if (authCookie) { - authCookie = decodeURI(authCookie); - var authCookieString = authCookie.split(User.cookieSeparator); - if (authCookieString[0]) { - this.authenticatedId = authCookieString[0]; - } - if (authCookieString.length > 1 && authCookieString[1]) { - this.accountId = authCookieString[1]; - } - } - } - User.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId) { - var isInvalidInput = !this.validateUserInput(authenticatedUserId) || (accountId && !this.validateUserInput(accountId)); - if (isInvalidInput) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_SetAuthContextFailedAccountName, "Setting auth user context failed. " + - "User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars.")); - return; - } - this.authenticatedId = authenticatedUserId; - var authCookie = this.authenticatedId; - if (accountId) { - this.accountId = accountId; - authCookie = [this.authenticatedId, this.accountId].join(User.cookieSeparator); - } - ApplicationInsights.Util.setCookie(User.authUserCookieName, encodeURI(authCookie), this.config.cookieDomain()); - }; - User.prototype.clearAuthenticatedUserContext = function () { - this.authenticatedId = null; - this.accountId = null; - ApplicationInsights.Util.deleteCookie(User.authUserCookieName); - }; - User.prototype.validateUserInput = function (id) { - if (typeof id !== 'string' || - !id || - id.match(/,|;|=| |\|/)) { - return false; - } - return true; - }; - User.cookieSeparator = '|'; - User.userCookieName = 'ai_user'; - User.authUserCookieName = 'ai_authUser'; - return User; - })(); - Context.User = User; - })(Context = ApplicationInsights.Context || (ApplicationInsights.Context = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var DataLossAnalyzer = (function () { - function DataLossAnalyzer() { - } - DataLossAnalyzer.reset = function () { - if (DataLossAnalyzer.isEnabled()) { - ApplicationInsights.Util.setSessionStorage(DataLossAnalyzer.ITEMS_QUEUED_KEY, "0"); - DataLossAnalyzer.itemsRestoredFromSessionBuffer = 0; - } - }; - DataLossAnalyzer.isEnabled = function () { - return DataLossAnalyzer.enabled && - DataLossAnalyzer.appInsights != null && - DataLossAnalyzer.appInsights.context._sender._XMLHttpRequestSupported && - ApplicationInsights.Util.canUseSessionStorage(); - }; - DataLossAnalyzer.getIssuesReported = function () { - var result = (!DataLossAnalyzer.isEnabled() || isNaN(+ApplicationInsights.Util.getSessionStorage(DataLossAnalyzer.ISSUES_REPORTED_KEY))) ? - 0 : - +ApplicationInsights.Util.getSessionStorage(DataLossAnalyzer.ISSUES_REPORTED_KEY); - return result; - }; - DataLossAnalyzer.incrementItemsQueued = function () { - try { - if (DataLossAnalyzer.isEnabled()) { - var itemsQueued = DataLossAnalyzer.getNumberOfLostItems(); - ++itemsQueued; - ApplicationInsights.Util.setSessionStorage(DataLossAnalyzer.ITEMS_QUEUED_KEY, itemsQueued.toString()); - } - } - catch (e) { } - }; - DataLossAnalyzer.decrementItemsQueued = function (countOfItemsSentSuccessfully) { - try { - if (DataLossAnalyzer.isEnabled()) { - var itemsQueued = DataLossAnalyzer.getNumberOfLostItems(); - itemsQueued -= countOfItemsSentSuccessfully; - if (itemsQueued < 0) - itemsQueued = 0; - ApplicationInsights.Util.setSessionStorage(DataLossAnalyzer.ITEMS_QUEUED_KEY, itemsQueued.toString()); - } - } - catch (e) { } - }; - DataLossAnalyzer.getNumberOfLostItems = function () { - var result = 0; - try { - if (DataLossAnalyzer.isEnabled()) { - result = isNaN(+ApplicationInsights.Util.getSessionStorage(DataLossAnalyzer.ITEMS_QUEUED_KEY)) ? - 0 : - +ApplicationInsights.Util.getSessionStorage(DataLossAnalyzer.ITEMS_QUEUED_KEY); - } - } - catch (e) { - result = 0; - } - return result; - }; - DataLossAnalyzer.reportLostItems = function () { - try { - if (DataLossAnalyzer.isEnabled() && - DataLossAnalyzer.getIssuesReported() < DataLossAnalyzer.LIMIT_PER_SESSION && - DataLossAnalyzer.getNumberOfLostItems() > 0) { - var lostItems = DataLossAnalyzer.getNumberOfLostItems() - DataLossAnalyzer.itemsRestoredFromSessionBuffer; - DataLossAnalyzer.appInsights.trackTrace("AI (Internal): Internal report DATALOSS:\"" + lostItems + "\"", null); - DataLossAnalyzer.appInsights.flush(); - var issuesReported = DataLossAnalyzer.getIssuesReported(); - ++issuesReported; - ApplicationInsights.Util.setSessionStorage(DataLossAnalyzer.ISSUES_REPORTED_KEY, issuesReported.toString()); - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedToReportDataLoss, "Failed to report data loss: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - finally { - try { - DataLossAnalyzer.reset(); - } - catch (e) { } - } - }; - DataLossAnalyzer.enabled = false; - DataLossAnalyzer.itemsRestoredFromSessionBuffer = 0; - DataLossAnalyzer.LIMIT_PER_SESSION = 10; - DataLossAnalyzer.ITEMS_QUEUED_KEY = "AI_itemsQueued"; - DataLossAnalyzer.ISSUES_REPORTED_KEY = "AI_lossIssuesReported"; - return DataLossAnalyzer; - })(); - ApplicationInsights.DataLossAnalyzer = DataLossAnalyzer; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var ArraySendBuffer = (function () { - function ArraySendBuffer(config) { - this._config = config; - this._buffer = []; - } - ArraySendBuffer.prototype.enqueue = function (payload) { - this._buffer.push(payload); - }; - ArraySendBuffer.prototype.count = function () { - return this._buffer.length; - }; - ArraySendBuffer.prototype.clear = function () { - this._buffer.length = 0; - }; - ArraySendBuffer.prototype.getItems = function () { - return this._buffer.slice(0); - }; - ArraySendBuffer.prototype.batchPayloads = function (payload) { - if (payload && payload.length > 0) { - var batch = this._config.emitLineDelimitedJson() ? - payload.join("\n") : - "[" + payload.join(",") + "]"; - return batch; - } - return null; - }; - ArraySendBuffer.prototype.markAsSent = function (payload) { - this.clear(); - }; - ArraySendBuffer.prototype.clearSent = function (payload) { - this.clear(); - }; - return ArraySendBuffer; - })(); - ApplicationInsights.ArraySendBuffer = ArraySendBuffer; - var SessionStorageSendBuffer = (function () { - function SessionStorageSendBuffer(config) { - this._config = config; - var bufferItems = this.getBuffer(SessionStorageSendBuffer.BUFFER_KEY); - var notDeliveredItems = this.getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY); - this._buffer = bufferItems.concat(notDeliveredItems); - ApplicationInsights.DataLossAnalyzer.itemsRestoredFromSessionBuffer = this._buffer.length; - this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, this._buffer); - this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, []); - } - SessionStorageSendBuffer.prototype.enqueue = function (payload) { - this._buffer.push(payload); - this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, this._buffer); - }; - SessionStorageSendBuffer.prototype.count = function () { - return this._buffer.length; - }; - SessionStorageSendBuffer.prototype.clear = function () { - this._buffer.length = 0; - this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, []); - this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, []); - }; - SessionStorageSendBuffer.prototype.getItems = function () { - return this._buffer.slice(0); - }; - SessionStorageSendBuffer.prototype.batchPayloads = function (payload) { - if (payload && payload.length > 0) { - var batch = this._config.emitLineDelimitedJson() ? - payload.join("\n") : - "[" + payload.join(",") + "]"; - return batch; - } - return null; - }; - SessionStorageSendBuffer.prototype.markAsSent = function (payload) { - var sentElements = this.getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY); - sentElements = sentElements.concat(payload); - this._buffer = this.removePayloadsFromBuffer(payload, this._buffer); - this.setBuffer(SessionStorageSendBuffer.BUFFER_KEY, this._buffer); - this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, sentElements); - }; - SessionStorageSendBuffer.prototype.clearSent = function (payload) { - var sentElements = this.getBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY); - sentElements = this.removePayloadsFromBuffer(payload, sentElements); - this.setBuffer(SessionStorageSendBuffer.SENT_BUFFER_KEY, sentElements); - }; - SessionStorageSendBuffer.prototype.removePayloadsFromBuffer = function (payloads, buffer) { - var remaining = []; - for (var i in buffer) { - var contains = false; - for (var j in payloads) { - if (payloads[j] === buffer[i]) { - contains = true; - break; - } - } - if (!contains) { - remaining.push(buffer[i]); - } - } - ; - return remaining; - }; - SessionStorageSendBuffer.prototype.getBuffer = function (key) { - try { - var bufferJson = ApplicationInsights.Util.getSessionStorage(key); - if (bufferJson) { - var buffer = JSON.parse(bufferJson); - if (buffer) { - return buffer; - } - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailToRestoreStorageBuffer, " storage key: " + key + ", " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - return []; - }; - SessionStorageSendBuffer.prototype.setBuffer = function (key, buffer) { - try { - var bufferJson = JSON.stringify(buffer); - ApplicationInsights.Util.setSessionStorage(key, bufferJson); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailToSetStorageBuffer, " storage key: " + key + ", " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - SessionStorageSendBuffer.BUFFER_KEY = "AI_buffer"; - SessionStorageSendBuffer.SENT_BUFFER_KEY = "AI_sentBuffer"; - return SessionStorageSendBuffer; - })(); - ApplicationInsights.SessionStorageSendBuffer = SessionStorageSendBuffer; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -; -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var Sender = (function () { - function Sender(config) { - this._XMLHttpRequestSupported = false; - this._lastSend = 0; - this._config = config; - this._sender = null; - this._buffer = (ApplicationInsights.Util.canUseSessionStorage() && this._config.enableSessionStorageBuffer()) - ? new ApplicationInsights.SessionStorageSendBuffer(config) : new ApplicationInsights.ArraySendBuffer(config); - if (typeof XMLHttpRequest != "undefined") { - var testXhr = new XMLHttpRequest(); - if ("withCredentials" in testXhr) { - this._sender = this._xhrSender; - this._XMLHttpRequestSupported = true; - } - else if (typeof XDomainRequest !== "undefined") { - this._sender = this._xdrSender; - } - } - } - Sender.prototype.send = function (envelope) { - var _this = this; - try { - if (this._config.disableTelemetry()) { - return; - } - if (!envelope) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_CannotSendEmptyTelemetry, "Cannot send empty telemetry")); - return; - } - if (!this._sender) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_SenderNotInitialized, "Sender was not initialized")); - return; - } - var payload = ApplicationInsights.Serializer.serialize(envelope); - var bufferPayload = this._buffer.getItems(); - var batch = this._buffer.batchPayloads(bufferPayload); - if (batch && (batch.length + payload.length > this._config.maxBatchSizeInBytes())) { - this.triggerSend(); - } - this._buffer.enqueue(payload); - if (!this._timeoutHandle) { - this._timeoutHandle = setTimeout(function () { - _this._timeoutHandle = null; - _this.triggerSend(); - }, this._config.maxBatchInterval()); - } - ApplicationInsights.DataLossAnalyzer.incrementItemsQueued(); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedAddingTelemetryToBuffer, "Failed adding telemetry to the sender's buffer, some telemetry will be lost: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - Sender.prototype._getSizeInBytes = function (list) { - var size = 0; - if (list && list.length) { - for (var i = 0; i < list.length; i++) { - var item = list[i]; - if (item && item.length) { - size += item.length; - } - } - } - return size; - }; - Sender.prototype.triggerSend = function (async) { - var isAsync = true; - if (typeof async === 'boolean') { - isAsync = async; - } - try { - if (!this._config.disableTelemetry()) { - if (this._buffer.count() > 0) { - var payload = this._buffer.getItems(); - this._sender(payload, isAsync); - } - this._lastSend = +new Date; - } - else { - this._buffer.clear(); - } - clearTimeout(this._timeoutHandle); - this._timeoutHandle = null; - } - catch (e) { - if (!ApplicationInsights.Util.getIEVersion() || ApplicationInsights.Util.getIEVersion() > 9) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TransmissionFailed, "Telemetry transmission failed, some telemetry will be lost: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - } - }; - Sender.prototype._xhrSender = function (payload, isAsync) { - var _this = this; - var xhr = new XMLHttpRequest(); - xhr[ApplicationInsights.AjaxMonitor.DisabledPropertyName] = true; - xhr.open("POST", this._config.endpointUrl(), isAsync); - xhr.setRequestHeader("Content-type", "application/json"); - xhr.onreadystatechange = function () { return _this._xhrReadyStateChange(xhr, payload, payload.length); }; - xhr.onerror = function (event) { return _this._onError(payload, xhr.responseText || xhr.response || "", event); }; - var batch = this._buffer.batchPayloads(payload); - xhr.send(batch); - this._buffer.markAsSent(payload); - }; - Sender.prototype._xdrSender = function (payload, isAsync) { - var _this = this; - var xdr = new XDomainRequest(); - xdr.onload = function () { return _this._xdrOnLoad(xdr, payload); }; - xdr.onerror = function (event) { return _this._onError(payload, xdr.responseText || "", event); }; - xdr.open('POST', this._config.endpointUrl()); - var batch = this._buffer.batchPayloads(payload); - xdr.send(batch); - this._buffer.markAsSent(payload); - }; - Sender.prototype._xhrReadyStateChange = function (xhr, payload, countOfItemsInPayload) { - if (xhr.readyState === 4) { - if ((xhr.status < 200 || xhr.status >= 300) && xhr.status !== 0) { - this._onError(payload, xhr.responseText || xhr.response || ""); - } - else { - this._onSuccess(payload, countOfItemsInPayload); - } - } - }; - Sender.prototype._xdrOnLoad = function (xdr, payload) { - if (xdr && (xdr.responseText + "" === "200" || xdr.responseText === "")) { - this._onSuccess(payload, 0); - } - else { - this._onError(payload, xdr && xdr.responseText || ""); - } - }; - Sender.prototype._onError = function (payload, message, event) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_OnError, "Failed to send telemetry.", { message: message })); - this._buffer.clearSent(payload); - }; - Sender.prototype._onSuccess = function (payload, countOfItemsInPayload) { - ApplicationInsights.DataLossAnalyzer.decrementItemsQueued(countOfItemsInPayload); - this._buffer.clearSent(payload); - }; - return Sender; - })(); - ApplicationInsights.Sender = Sender; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var SplitTest = (function () { - function SplitTest() { - this.hashCodeGeneragor = new ApplicationInsights.HashCodeScoreGenerator(); - } - SplitTest.prototype.isEnabled = function (key, percentEnabled) { - return this.hashCodeGeneragor.getHashCodeScore(key) < percentEnabled; - }; - return SplitTest; - })(); - ApplicationInsights.SplitTest = SplitTest; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Domain = (function () { - function Domain() { - } - return Domain; - })(); - Telemetry.Domain = Domain; - })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {})); -})(Microsoft || (Microsoft = {})); -var AI; -(function (AI) { - "use strict"; - (function (SeverityLevel) { - SeverityLevel[SeverityLevel["Verbose"] = 0] = "Verbose"; - SeverityLevel[SeverityLevel["Information"] = 1] = "Information"; - SeverityLevel[SeverityLevel["Warning"] = 2] = "Warning"; - SeverityLevel[SeverityLevel["Error"] = 3] = "Error"; - SeverityLevel[SeverityLevel["Critical"] = 4] = "Critical"; - })(AI.SeverityLevel || (AI.SeverityLevel = {})); - var SeverityLevel = AI.SeverityLevel; -})(AI || (AI = {})); -/// -/// -var AI; -(function (AI) { - "use strict"; - var MessageData = (function (_super) { - __extends(MessageData, _super); - function MessageData() { - _super.call(this); - this.ver = 2; - this.properties = {}; - _super.call(this); - } - return MessageData; - })(Microsoft.Telemetry.Domain); - AI.MessageData = MessageData; -})(AI || (AI = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - var Common; - (function (Common) { - "use strict"; - var DataSanitizer = (function () { - function DataSanitizer() { - } - DataSanitizer.sanitizeKeyAndAddUniqueness = function (key, map) { - var origLength = key.length; - var field = DataSanitizer.sanitizeKey(key); - if (field.length !== origLength) { - var i = 0; - var uniqueField = field; - while (map[uniqueField] !== undefined) { - i++; - uniqueField = field.substring(0, DataSanitizer.MAX_NAME_LENGTH - 3) + DataSanitizer.padNumber(i); - } - field = uniqueField; - } - return field; - }; - DataSanitizer.sanitizeKey = function (name) { - if (name) { - name = ApplicationInsights.Util.trim(name.toString()); - if (name.search(/[^0-9a-zA-Z-._()\/ ]/g) >= 0) { - name = name.replace(/[^0-9a-zA-Z-._()\/ ]/g, "_"); - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_IllegalCharsInName, "name contains illegal characters. Illegal characters have been replaced with '_'.", { newName: name })); - } - if (name.length > DataSanitizer.MAX_NAME_LENGTH) { - name = name.substring(0, DataSanitizer.MAX_NAME_LENGTH); - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_NameTooLong, "name is too long. It has been truncated to " + DataSanitizer.MAX_NAME_LENGTH + " characters.", { name: name })); - } - } - return name; - }; - DataSanitizer.sanitizeString = function (value) { - if (value) { - value = ApplicationInsights.Util.trim(value); - if (value.toString().length > DataSanitizer.MAX_STRING_LENGTH) { - value = value.toString().substring(0, DataSanitizer.MAX_STRING_LENGTH); - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_StringValueTooLong, "string value is too long. It has been truncated to " + DataSanitizer.MAX_STRING_LENGTH + " characters.", { value: value })); - } - } - return value; - }; - DataSanitizer.sanitizeUrl = function (url) { - if (url) { - url = ApplicationInsights.Util.trim(url); - if (url.length > DataSanitizer.MAX_URL_LENGTH) { - url = url.substring(0, DataSanitizer.MAX_URL_LENGTH); - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_UrlTooLong, "url is too long, it has been trucated to " + DataSanitizer.MAX_URL_LENGTH + " characters.", { url: url })); - } - } - return url; - }; - DataSanitizer.sanitizeMessage = function (message) { - if (message) { - if (message.length > DataSanitizer.MAX_MESSAGE_LENGTH) { - message = message.substring(0, DataSanitizer.MAX_MESSAGE_LENGTH); - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_MessageTruncated, "message is too long, it has been trucated to " + DataSanitizer.MAX_MESSAGE_LENGTH + " characters.", { message: message })); - } - } - return message; - }; - DataSanitizer.sanitizeException = function (exception) { - if (exception) { - if (exception.length > DataSanitizer.MAX_EXCEPTION_LENGTH) { - exception = exception.substring(0, DataSanitizer.MAX_EXCEPTION_LENGTH); - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_ExceptionTruncated, "exception is too long, it has been trucated to " + DataSanitizer.MAX_EXCEPTION_LENGTH + " characters.", { exception: exception })); - } - } - return exception; - }; - DataSanitizer.sanitizeProperties = function (properties) { - if (properties) { - var tempProps = {}; - for (var prop in properties) { - var value = DataSanitizer.sanitizeString(properties[prop]); - prop = DataSanitizer.sanitizeKeyAndAddUniqueness(prop, tempProps); - tempProps[prop] = value; - } - properties = tempProps; - } - return properties; - }; - DataSanitizer.sanitizeMeasurements = function (measurements) { - if (measurements) { - var tempMeasurements = {}; - for (var measure in measurements) { - var value = measurements[measure]; - measure = DataSanitizer.sanitizeKeyAndAddUniqueness(measure, tempMeasurements); - tempMeasurements[measure] = value; - } - measurements = tempMeasurements; - } - return measurements; - }; - DataSanitizer.padNumber = function (num) { - var s = "00" + num; - return s.substr(s.length - 3); - }; - DataSanitizer.MAX_NAME_LENGTH = 150; - DataSanitizer.MAX_STRING_LENGTH = 1024; - DataSanitizer.MAX_URL_LENGTH = 2048; - DataSanitizer.MAX_MESSAGE_LENGTH = 32768; - DataSanitizer.MAX_EXCEPTION_LENGTH = 32768; - return DataSanitizer; - })(); - Common.DataSanitizer = DataSanitizer; - })(Common = Telemetry.Common || (Telemetry.Common = {})); - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Trace = (function (_super) { - __extends(Trace, _super); - function Trace(message, properties) { - _super.call(this); - this.aiDataContract = { - ver: ApplicationInsights.FieldType.Required, - message: ApplicationInsights.FieldType.Required, - severityLevel: ApplicationInsights.FieldType.Default, - measurements: ApplicationInsights.FieldType.Default, - properties: ApplicationInsights.FieldType.Default - }; - message = message || ApplicationInsights.Util.NotSpecified; - this.message = Telemetry.Common.DataSanitizer.sanitizeMessage(message); - this.properties = Telemetry.Common.DataSanitizer.sanitizeProperties(properties); - } - Trace.envelopeType = "Microsoft.ApplicationInsights.{0}.Message"; - Trace.dataType = "MessageData"; - return Trace; - })(AI.MessageData); - Telemetry.Trace = Trace; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var AI; -(function (AI) { - "use strict"; - var EventData = (function (_super) { - __extends(EventData, _super); - function EventData() { - _super.call(this); - this.ver = 2; - this.properties = {}; - this.measurements = {}; - _super.call(this); - } - return EventData; - })(Microsoft.Telemetry.Domain); - AI.EventData = EventData; -})(AI || (AI = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Event = (function (_super) { - __extends(Event, _super); - function Event(name, properties, measurements) { - _super.call(this); - this.aiDataContract = { - ver: ApplicationInsights.FieldType.Required, - name: ApplicationInsights.FieldType.Required, - properties: ApplicationInsights.FieldType.Default, - measurements: ApplicationInsights.FieldType.Default, - }; - this.name = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(name) || ApplicationInsights.Util.NotSpecified; - this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties); - this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements); - } - Event.envelopeType = "Microsoft.ApplicationInsights.{0}.Event"; - Event.dataType = "EventData"; - return Event; - })(AI.EventData); - Telemetry.Event = Event; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var AI; -(function (AI) { - "use strict"; - var ExceptionDetails = (function () { - function ExceptionDetails() { - this.hasFullStack = true; - this.parsedStack = []; - } - return ExceptionDetails; - })(); - AI.ExceptionDetails = ExceptionDetails; -})(AI || (AI = {})); -/// -/// -/// -var AI; -(function (AI) { - "use strict"; - var ExceptionData = (function (_super) { - __extends(ExceptionData, _super); - function ExceptionData() { - _super.call(this); - this.ver = 2; - this.exceptions = []; - this.properties = {}; - this.measurements = {}; - _super.call(this); - } - return ExceptionData; - })(Microsoft.Telemetry.Domain); - AI.ExceptionData = ExceptionData; -})(AI || (AI = {})); -var AI; -(function (AI) { - "use strict"; - var StackFrame = (function () { - function StackFrame() { - } - return StackFrame; - })(); - AI.StackFrame = StackFrame; -})(AI || (AI = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Exception = (function (_super) { - __extends(Exception, _super); - function Exception(exception, handledAt, properties, measurements, severityLevel) { - _super.call(this); - this.aiDataContract = { - ver: ApplicationInsights.FieldType.Required, - handledAt: ApplicationInsights.FieldType.Required, - exceptions: ApplicationInsights.FieldType.Required, - severityLevel: ApplicationInsights.FieldType.Default, - properties: ApplicationInsights.FieldType.Default, - measurements: ApplicationInsights.FieldType.Default, - }; - this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties); - this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements); - this.handledAt = handledAt || "unhandled"; - this.exceptions = [new _ExceptionDetails(exception)]; - if (severityLevel) { - this.severityLevel = severityLevel; - } - } - Exception.CreateSimpleException = function (message, typeName, assembly, fileName, details, line, handledAt) { - return { - handledAt: handledAt || "unhandled", - exceptions: [ - { - hasFullStack: true, - message: message, - stack: details, - typeName: typeName, - parsedStack: [ - { - level: 0, - assembly: assembly, - fileName: fileName, - line: line, - method: "unknown" - } - ] - } - ] - }; - }; - Exception.envelopeType = "Microsoft.ApplicationInsights.{0}.Exception"; - Exception.dataType = "ExceptionData"; - return Exception; - })(AI.ExceptionData); - Telemetry.Exception = Exception; - var _ExceptionDetails = (function (_super) { - __extends(_ExceptionDetails, _super); - function _ExceptionDetails(exception) { - _super.call(this); - this.aiDataContract = { - id: ApplicationInsights.FieldType.Default, - outerId: ApplicationInsights.FieldType.Default, - typeName: ApplicationInsights.FieldType.Required, - message: ApplicationInsights.FieldType.Required, - hasFullStack: ApplicationInsights.FieldType.Default, - stack: ApplicationInsights.FieldType.Default, - parsedStack: ApplicationInsights.FieldType.Array, - }; - this.typeName = Telemetry.Common.DataSanitizer.sanitizeString(exception.name) || ApplicationInsights.Util.NotSpecified; - this.message = Telemetry.Common.DataSanitizer.sanitizeMessage(exception.message) || ApplicationInsights.Util.NotSpecified; - var stack = exception["stack"]; - this.parsedStack = this.parseStack(stack); - this.stack = Telemetry.Common.DataSanitizer.sanitizeException(stack); - this.hasFullStack = ApplicationInsights.Util.isArray(this.parsedStack) && this.parsedStack.length > 0; - } - _ExceptionDetails.prototype.parseStack = function (stack) { - var parsedStack = undefined; - if (typeof stack === "string") { - var frames = stack.split('\n'); - parsedStack = []; - var level = 0; - var totalSizeInBytes = 0; - for (var i = 0; i <= frames.length; i++) { - var frame = frames[i]; - if (_StackFrame.regex.test(frame)) { - var parsedFrame = new _StackFrame(frames[i], level++); - totalSizeInBytes += parsedFrame.sizeInBytes; - parsedStack.push(parsedFrame); - } - } - var exceptionParsedStackThreshold = 32 * 1024; - if (totalSizeInBytes > exceptionParsedStackThreshold) { - var left = 0; - var right = parsedStack.length - 1; - var size = 0; - var acceptedLeft = left; - var acceptedRight = right; - while (left < right) { - var lSize = parsedStack[left].sizeInBytes; - var rSize = parsedStack[right].sizeInBytes; - size += lSize + rSize; - if (size > exceptionParsedStackThreshold) { - var howMany = acceptedRight - acceptedLeft + 1; - parsedStack.splice(acceptedLeft, howMany); - break; - } - acceptedLeft = left; - acceptedRight = right; - left++; - right--; - } - } - } - return parsedStack; - }; - return _ExceptionDetails; - })(AI.ExceptionDetails); - var _StackFrame = (function (_super) { - __extends(_StackFrame, _super); - function _StackFrame(frame, level) { - _super.call(this); - this.sizeInBytes = 0; - this.aiDataContract = { - level: ApplicationInsights.FieldType.Required, - method: ApplicationInsights.FieldType.Required, - assembly: ApplicationInsights.FieldType.Default, - fileName: ApplicationInsights.FieldType.Default, - line: ApplicationInsights.FieldType.Default, - }; - this.level = level; - this.method = ""; - this.assembly = ApplicationInsights.Util.trim(frame); - var matches = frame.match(_StackFrame.regex); - if (matches && matches.length >= 5) { - this.method = ApplicationInsights.Util.trim(matches[2]) || this.method; - this.fileName = ApplicationInsights.Util.trim(matches[4]); - this.line = parseInt(matches[5]) || 0; - } - this.sizeInBytes += this.method.length; - this.sizeInBytes += this.fileName.length; - this.sizeInBytes += this.assembly.length; - this.sizeInBytes += _StackFrame.baseSize; - this.sizeInBytes += this.level.toString().length; - this.sizeInBytes += this.line.toString().length; - } - _StackFrame.regex = /^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/; - _StackFrame.baseSize = 58; - return _StackFrame; - })(AI.StackFrame); - Telemetry._StackFrame = _StackFrame; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var AI; -(function (AI) { - "use strict"; - var MetricData = (function (_super) { - __extends(MetricData, _super); - function MetricData() { - _super.call(this); - this.ver = 2; - this.metrics = []; - this.properties = {}; - _super.call(this); - } - return MetricData; - })(Microsoft.Telemetry.Domain); - AI.MetricData = MetricData; -})(AI || (AI = {})); -var AI; -(function (AI) { - "use strict"; - (function (DataPointType) { - DataPointType[DataPointType["Measurement"] = 0] = "Measurement"; - DataPointType[DataPointType["Aggregation"] = 1] = "Aggregation"; - })(AI.DataPointType || (AI.DataPointType = {})); - var DataPointType = AI.DataPointType; -})(AI || (AI = {})); -/// -var AI; -(function (AI) { - "use strict"; - var DataPoint = (function () { - function DataPoint() { - this.kind = AI.DataPointType.Measurement; - } - return DataPoint; - })(); - AI.DataPoint = DataPoint; -})(AI || (AI = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - var Common; - (function (Common) { - "use strict"; - var DataPoint = (function (_super) { - __extends(DataPoint, _super); - function DataPoint() { - _super.apply(this, arguments); - this.aiDataContract = { - name: ApplicationInsights.FieldType.Required, - kind: ApplicationInsights.FieldType.Default, - value: ApplicationInsights.FieldType.Required, - count: ApplicationInsights.FieldType.Default, - min: ApplicationInsights.FieldType.Default, - max: ApplicationInsights.FieldType.Default, - stdDev: ApplicationInsights.FieldType.Default - }; - } - return DataPoint; - })(AI.DataPoint); - Common.DataPoint = DataPoint; - })(Common = Telemetry.Common || (Telemetry.Common = {})); - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Metric = (function (_super) { - __extends(Metric, _super); - function Metric(name, value, count, min, max, properties) { - _super.call(this); - this.aiDataContract = { - ver: ApplicationInsights.FieldType.Required, - metrics: ApplicationInsights.FieldType.Required, - properties: ApplicationInsights.FieldType.Default, - }; - var dataPoint = new Microsoft.ApplicationInsights.Telemetry.Common.DataPoint(); - dataPoint.count = count > 0 ? count : undefined; - dataPoint.max = isNaN(max) || max === null ? undefined : max; - dataPoint.min = isNaN(min) || min === null ? undefined : min; - dataPoint.name = Telemetry.Common.DataSanitizer.sanitizeString(name) || ApplicationInsights.Util.NotSpecified; - dataPoint.value = value; - this.metrics = [dataPoint]; - this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties); - } - Metric.envelopeType = "Microsoft.ApplicationInsights.{0}.Metric"; - Metric.dataType = "MetricData"; - return Metric; - })(AI.MetricData); - Telemetry.Metric = Metric; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var AI; -(function (AI) { - "use strict"; - var PageViewData = (function (_super) { - __extends(PageViewData, _super); - function PageViewData() { - _super.call(this); - this.ver = 2; - this.properties = {}; - this.measurements = {}; - _super.call(this); - } - return PageViewData; - })(AI.EventData); - AI.PageViewData = PageViewData; -})(AI || (AI = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var PageView = (function (_super) { - __extends(PageView, _super); - function PageView(name, url, durationMs, properties, measurements) { - _super.call(this); - this.aiDataContract = { - ver: ApplicationInsights.FieldType.Required, - name: ApplicationInsights.FieldType.Default, - url: ApplicationInsights.FieldType.Default, - duration: ApplicationInsights.FieldType.Default, - properties: ApplicationInsights.FieldType.Default, - measurements: ApplicationInsights.FieldType.Default, - }; - this.url = Telemetry.Common.DataSanitizer.sanitizeUrl(url); - this.name = Telemetry.Common.DataSanitizer.sanitizeString(name) || ApplicationInsights.Util.NotSpecified; - if (!isNaN(durationMs)) { - this.duration = ApplicationInsights.Util.msToTimeSpan(durationMs); - } - this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties); - this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements); - } - PageView.envelopeType = "Microsoft.ApplicationInsights.{0}.Pageview"; - PageView.dataType = "PageviewData"; - return PageView; - })(AI.PageViewData); - Telemetry.PageView = PageView; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var AI; -(function (AI) { - "use strict"; - var PageViewPerfData = (function (_super) { - __extends(PageViewPerfData, _super); - function PageViewPerfData() { - _super.call(this); - this.ver = 2; - this.properties = {}; - this.measurements = {}; - _super.call(this); - } - return PageViewPerfData; - })(AI.PageViewData); - AI.PageViewPerfData = PageViewPerfData; -})(AI || (AI = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var PageViewPerformance = (function (_super) { - __extends(PageViewPerformance, _super); - function PageViewPerformance(name, url, unused, properties, measurements) { - _super.call(this); - this.aiDataContract = { - ver: ApplicationInsights.FieldType.Required, - name: ApplicationInsights.FieldType.Default, - url: ApplicationInsights.FieldType.Default, - duration: ApplicationInsights.FieldType.Default, - perfTotal: ApplicationInsights.FieldType.Default, - networkConnect: ApplicationInsights.FieldType.Default, - sentRequest: ApplicationInsights.FieldType.Default, - receivedResponse: ApplicationInsights.FieldType.Default, - domProcessing: ApplicationInsights.FieldType.Default, - properties: ApplicationInsights.FieldType.Default, - measurements: ApplicationInsights.FieldType.Default - }; - this.isValid = false; - var timing = PageViewPerformance.getPerformanceTiming(); - if (timing) { - var total = PageViewPerformance.getDuration(timing.navigationStart, timing.loadEventEnd); - var network = PageViewPerformance.getDuration(timing.navigationStart, timing.connectEnd); - var request = PageViewPerformance.getDuration(timing.requestStart, timing.responseStart); - var response = PageViewPerformance.getDuration(timing.responseStart, timing.responseEnd); - var dom = PageViewPerformance.getDuration(timing.responseEnd, timing.loadEventEnd); - if (total == 0) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_ErrorPVCalc, "error calculating page view performance.", { total: total, network: network, request: request, response: response, dom: dom })); - } - else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_ClientPerformanceMathError, "client performance math error.", { total: total, network: network, request: request, response: response, dom: dom })); - } - else { - this.durationMs = total; - this.perfTotal = this.duration = ApplicationInsights.Util.msToTimeSpan(total); - this.networkConnect = ApplicationInsights.Util.msToTimeSpan(network); - this.sentRequest = ApplicationInsights.Util.msToTimeSpan(request); - this.receivedResponse = ApplicationInsights.Util.msToTimeSpan(response); - this.domProcessing = ApplicationInsights.Util.msToTimeSpan(dom); - this.isValid = true; - } - } - this.url = Telemetry.Common.DataSanitizer.sanitizeUrl(url); - this.name = Telemetry.Common.DataSanitizer.sanitizeString(name) || ApplicationInsights.Util.NotSpecified; - this.properties = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(properties); - this.measurements = ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(measurements); - } - PageViewPerformance.prototype.getIsValid = function () { - return this.isValid; - }; - PageViewPerformance.prototype.getDurationMs = function () { - return this.durationMs; - }; - PageViewPerformance.getPerformanceTiming = function () { - if (typeof window != "undefined" && window.performance && window.performance.timing) { - return window.performance.timing; - } - return null; - }; - PageViewPerformance.isPerformanceTimingSupported = function () { - return typeof window != "undefined" && window.performance && window.performance.timing; - }; - PageViewPerformance.isPerformanceTimingDataReady = function () { - var timing = window.performance.timing; - return timing.domainLookupStart > 0 - && timing.navigationStart > 0 - && timing.responseStart > 0 - && timing.requestStart > 0 - && timing.loadEventEnd > 0 - && timing.responseEnd > 0 - && timing.connectEnd > 0 - && timing.domLoading > 0; - }; - PageViewPerformance.getDuration = function (start, end) { - var duration = 0; - if (!(isNaN(start) || isNaN(end))) { - duration = Math.max(end - start, 0); - } - return duration; - }; - PageViewPerformance.envelopeType = "Microsoft.ApplicationInsights.{0}.PageviewPerformance"; - PageViewPerformance.dataType = "PageviewPerformanceData"; - return PageViewPerformance; - })(AI.PageViewPerfData); - Telemetry.PageViewPerformance = PageViewPerformance; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var TelemetryContext = (function () { - function TelemetryContext(config) { - this._config = config; - this._sender = new ApplicationInsights.Sender(config); - if (typeof window !== 'undefined') { - this._sessionManager = new ApplicationInsights.Context._SessionManager(config); - this.application = new ApplicationInsights.Context.Application(); - this.device = new ApplicationInsights.Context.Device(); - this.internal = new ApplicationInsights.Context.Internal(); - this.location = new ApplicationInsights.Context.Location(); - this.user = new ApplicationInsights.Context.User(config); - this.operation = new ApplicationInsights.Context.Operation(); - this.session = new ApplicationInsights.Context.Session(); - this.sample = new ApplicationInsights.Context.Sample(config.sampleRate()); - } - } - TelemetryContext.prototype.addTelemetryInitializer = function (telemetryInitializer) { - this.telemetryInitializers = this.telemetryInitializers || []; - this.telemetryInitializers.push(telemetryInitializer); - }; - TelemetryContext.prototype.track = function (envelope) { - if (!envelope) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_TrackArgumentsNotSpecified, "cannot call .track() with a null or undefined argument")); - } - else { - if (envelope.name === ApplicationInsights.Telemetry.PageView.envelopeType) { - ApplicationInsights._InternalLogging.resetInternalMessageCount(); - } - if (this.session) { - if (typeof this.session.id !== "string") { - this._sessionManager.update(); - } - } - this._track(envelope); - } - return envelope; - }; - TelemetryContext.prototype._track = function (envelope) { - if (this.session) { - if (typeof this.session.id === "string") { - this._applySessionContext(envelope, this.session); - } - else { - this._applySessionContext(envelope, this._sessionManager.automaticSession); - } - } - this._applyApplicationContext(envelope, this.application); - this._applyDeviceContext(envelope, this.device); - this._applyInternalContext(envelope, this.internal); - this._applyLocationContext(envelope, this.location); - this._applySampleContext(envelope, this.sample); - this._applyUserContext(envelope, this.user); - this._applyOperationContext(envelope, this.operation); - envelope.iKey = this._config.instrumentationKey(); - var doNotSendItem = false; - try { - this.telemetryInitializers = this.telemetryInitializers || []; - var telemetryInitializersCount = this.telemetryInitializers.length; - for (var i = 0; i < telemetryInitializersCount; ++i) { - var telemetryInitializer = this.telemetryInitializers[i]; - if (telemetryInitializer) { - if (telemetryInitializer.apply(null, [envelope]) === false) { - doNotSendItem = true; - break; - } - } - } - } - catch (e) { - doNotSendItem = true; - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - if (!doNotSendItem) { - if (envelope.name === ApplicationInsights.Telemetry.Metric.envelopeType || - this.sample.isSampledIn(envelope)) { - var iKeyNoDashes = this._config.instrumentationKey().replace(/-/g, ""); - envelope.name = envelope.name.replace("{0}", iKeyNoDashes); - this._sender.send(envelope); - } - else { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TelemetrySampledAndNotSent, "Telemetry is sampled and not sent to the AI service.", { SampleRate: this.sample.sampleRate })); - } - } - return envelope; - }; - TelemetryContext.prototype._applyApplicationContext = function (envelope, appContext) { - if (appContext) { - var tagKeys = new AI.ContextTagKeys(); - if (typeof appContext.ver === "string") { - envelope.tags[tagKeys.applicationVersion] = appContext.ver; - } - if (typeof appContext.build === "string") { - envelope.tags[tagKeys.applicationBuild] = appContext.build; - } - } - }; - TelemetryContext.prototype._applyDeviceContext = function (envelope, deviceContext) { - var tagKeys = new AI.ContextTagKeys(); - if (deviceContext) { - if (typeof deviceContext.id === "string") { - envelope.tags[tagKeys.deviceId] = deviceContext.id; - } - if (typeof deviceContext.ip === "string") { - envelope.tags[tagKeys.deviceIp] = deviceContext.ip; - } - if (typeof deviceContext.language === "string") { - envelope.tags[tagKeys.deviceLanguage] = deviceContext.language; - } - if (typeof deviceContext.locale === "string") { - envelope.tags[tagKeys.deviceLocale] = deviceContext.locale; - } - if (typeof deviceContext.model === "string") { - envelope.tags[tagKeys.deviceModel] = deviceContext.model; - } - if (typeof deviceContext.network !== "undefined") { - envelope.tags[tagKeys.deviceNetwork] = deviceContext.network; - } - if (typeof deviceContext.oemName === "string") { - envelope.tags[tagKeys.deviceOEMName] = deviceContext.oemName; - } - if (typeof deviceContext.os === "string") { - envelope.tags[tagKeys.deviceOS] = deviceContext.os; - } - if (typeof deviceContext.osversion === "string") { - envelope.tags[tagKeys.deviceOSVersion] = deviceContext.osversion; - } - if (typeof deviceContext.resolution === "string") { - envelope.tags[tagKeys.deviceScreenResolution] = deviceContext.resolution; - } - if (typeof deviceContext.type === "string") { - envelope.tags[tagKeys.deviceType] = deviceContext.type; - } - } - }; - TelemetryContext.prototype._applyInternalContext = function (envelope, internalContext) { - if (internalContext) { - var tagKeys = new AI.ContextTagKeys(); - if (typeof internalContext.agentVersion === "string") { - envelope.tags[tagKeys.internalAgentVersion] = internalContext.agentVersion; - } - if (typeof internalContext.sdkVersion === "string") { - envelope.tags[tagKeys.internalSdkVersion] = internalContext.sdkVersion; - } - } - }; - TelemetryContext.prototype._applyLocationContext = function (envelope, locationContext) { - if (locationContext) { - var tagKeys = new AI.ContextTagKeys(); - if (typeof locationContext.ip === "string") { - envelope.tags[tagKeys.locationIp] = locationContext.ip; - } - } - }; - TelemetryContext.prototype._applyOperationContext = function (envelope, operationContext) { - if (operationContext) { - var tagKeys = new AI.ContextTagKeys(); - if (typeof operationContext.id === "string") { - envelope.tags[tagKeys.operationId] = operationContext.id; - } - if (typeof operationContext.name === "string") { - envelope.tags[tagKeys.operationName] = operationContext.name; - } - if (typeof operationContext.parentId === "string") { - envelope.tags[tagKeys.operationParentId] = operationContext.parentId; - } - if (typeof operationContext.rootId === "string") { - envelope.tags[tagKeys.operationRootId] = operationContext.rootId; - } - if (typeof operationContext.syntheticSource === "string") { - envelope.tags[tagKeys.operationSyntheticSource] = operationContext.syntheticSource; - } - } - }; - TelemetryContext.prototype._applySampleContext = function (envelope, sampleContext) { - if (sampleContext) { - envelope.sampleRate = sampleContext.sampleRate; - } - }; - TelemetryContext.prototype._applySessionContext = function (envelope, sessionContext) { - if (sessionContext) { - var tagKeys = new AI.ContextTagKeys(); - if (typeof sessionContext.id === "string") { - envelope.tags[tagKeys.sessionId] = sessionContext.id; - } - if (typeof sessionContext.isFirst !== "undefined") { - envelope.tags[tagKeys.sessionIsFirst] = sessionContext.isFirst; - } - } - }; - TelemetryContext.prototype._applyUserContext = function (envelope, userContext) { - if (userContext) { - var tagKeys = new AI.ContextTagKeys(); - if (typeof userContext.accountId === "string") { - envelope.tags[tagKeys.userAccountId] = userContext.accountId; - } - if (typeof userContext.agent === "string") { - envelope.tags[tagKeys.userAgent] = userContext.agent; - } - if (typeof userContext.id === "string") { - envelope.tags[tagKeys.userId] = userContext.id; - } - if (typeof userContext.authenticatedId === "string") { - envelope.tags[tagKeys.userAuthUserId] = userContext.authenticatedId; - } - if (typeof userContext.storeRegion === "string") { - envelope.tags[tagKeys.userStoreRegion] = userContext.storeRegion; - } - } - }; - return TelemetryContext; - })(); - ApplicationInsights.TelemetryContext = TelemetryContext; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var Data = (function (_super) { - __extends(Data, _super); - function Data() { - _super.call(this); - } - return Data; - })(Microsoft.Telemetry.Base); - Telemetry.Data = Data; - })(Telemetry = Microsoft.Telemetry || (Microsoft.Telemetry = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - var Common; - (function (Common) { - "use strict"; - var Data = (function (_super) { - __extends(Data, _super); - function Data(type, data) { - _super.call(this); - this.aiDataContract = { - baseType: ApplicationInsights.FieldType.Required, - baseData: ApplicationInsights.FieldType.Required - }; - this.baseType = type; - this.baseData = data; - } - return Data; - })(Microsoft.Telemetry.Data); - Common.Data = Data; - })(Common = Telemetry.Common || (Telemetry.Common = {})); - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var PageViewManager = (function () { - function PageViewManager(appInsights, overridePageViewDuration) { - this.pageViewPerformanceSent = false; - this.overridePageViewDuration = false; - this.overridePageViewDuration = overridePageViewDuration; - this.appInsights = appInsights; - } - PageViewManager.prototype.trackPageView = function (name, url, properties, measurements, duration) { - var _this = this; - if (typeof name !== "string") { - name = window.document && window.document.title || ""; - } - if (typeof url !== "string") { - url = window.location && window.location.href || ""; - } - var pageViewSent = false; - var customDuration = 0; - if (Telemetry.PageViewPerformance.isPerformanceTimingSupported()) { - var start = Telemetry.PageViewPerformance.getPerformanceTiming().navigationStart; - customDuration = Telemetry.PageViewPerformance.getDuration(start, +new Date); - } - else { - this.appInsights.sendPageViewInternal(name, url, !isNaN(duration) ? duration : 0, properties, measurements); - this.appInsights.flush(); - pageViewSent = true; - } - if (this.overridePageViewDuration || !isNaN(duration)) { - this.appInsights.sendPageViewInternal(name, url, !isNaN(duration) ? duration : customDuration, properties, measurements); - this.appInsights.flush(); - pageViewSent = true; - } - var maxDurationLimit = 60000; - if (!Telemetry.PageViewPerformance.isPerformanceTimingSupported()) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_NavigationTimingNotSupported, "trackPageView: navigation timing API used for calculation of page duration is not supported in this browser. This page view will be collected without duration and timing info.")); - return; - } - var handle = setInterval(function () { - try { - if (Telemetry.PageViewPerformance.isPerformanceTimingDataReady()) { - clearInterval(handle); - var pageViewPerformance = new Telemetry.PageViewPerformance(name, url, null, properties, measurements); - if (!pageViewPerformance.getIsValid() && !pageViewSent) { - _this.appInsights.sendPageViewInternal(name, url, customDuration, properties, measurements); - _this.appInsights.flush(); - } - else { - if (!pageViewSent) { - _this.appInsights.sendPageViewInternal(name, url, pageViewPerformance.getDurationMs(), properties, measurements); - } - if (!_this.pageViewPerformanceSent) { - _this.appInsights.sendPageViewPerformanceInternal(pageViewPerformance); - _this.pageViewPerformanceSent = true; - } - _this.appInsights.flush(); - } - } - else if (Telemetry.PageViewPerformance.getDuration(start, +new Date) > maxDurationLimit) { - clearInterval(handle); - if (!pageViewSent) { - _this.appInsights.sendPageViewInternal(name, url, maxDurationLimit, properties, measurements); - _this.appInsights.flush(); - } - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TrackPVFailedCalc, "trackPageView failed on page load calculation: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }, 100); - }; - return PageViewManager; - })(); - Telemetry.PageViewManager = PageViewManager; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var PageVisitTimeManager = (function () { - function PageVisitTimeManager(pageVisitTimeTrackingHandler) { - this.prevPageVisitDataKeyName = "prevPageVisitData"; - this.pageVisitTimeTrackingHandler = pageVisitTimeTrackingHandler; - } - PageVisitTimeManager.prototype.trackPreviousPageVisit = function (currentPageName, currentPageUrl) { - try { - var prevPageVisitTimeData = this.restartPageVisitTimer(currentPageName, currentPageUrl); - if (prevPageVisitTimeData) { - this.pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime); - } - } - catch (e) { - ApplicationInsights._InternalLogging.warnToConsole("Auto track page visit time failed, metric will not be collected: " + ApplicationInsights.Util.dump(e)); - } - }; - PageVisitTimeManager.prototype.restartPageVisitTimer = function (pageName, pageUrl) { - try { - var prevPageVisitData = this.stopPageVisitTimer(); - this.startPageVisitTimer(pageName, pageUrl); - return prevPageVisitData; - } - catch (e) { - ApplicationInsights._InternalLogging.warnToConsole("Call to restart failed: " + ApplicationInsights.Util.dump(e)); - return null; - } - }; - PageVisitTimeManager.prototype.startPageVisitTimer = function (pageName, pageUrl) { - try { - if (ApplicationInsights.Util.canUseSessionStorage()) { - if (ApplicationInsights.Util.getSessionStorage(this.prevPageVisitDataKeyName) != null) { - throw new Error("Cannot call startPageVisit consecutively without first calling stopPageVisit"); - } - var currPageVisitData = new PageVisitData(pageName, pageUrl); - var currPageVisitDataStr = JSON.stringify(currPageVisitData); - ApplicationInsights.Util.setSessionStorage(this.prevPageVisitDataKeyName, currPageVisitDataStr); - } - } - catch (e) { - ApplicationInsights._InternalLogging.warnToConsole("Call to start failed: " + ApplicationInsights.Util.dump(e)); - } - }; - PageVisitTimeManager.prototype.stopPageVisitTimer = function () { - try { - if (ApplicationInsights.Util.canUseSessionStorage()) { - var pageVisitEndTime = Date.now(); - var pageVisitDataJsonStr = ApplicationInsights.Util.getSessionStorage(this.prevPageVisitDataKeyName); - if (pageVisitDataJsonStr) { - var prevPageVisitData = JSON.parse(pageVisitDataJsonStr); - prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData.pageVisitStartTime; - ApplicationInsights.Util.removeSessionStorage(this.prevPageVisitDataKeyName); - return prevPageVisitData; - } - else { - return null; - } - } - return null; - } - catch (e) { - ApplicationInsights._InternalLogging.warnToConsole("Stop page visit timer failed: " + ApplicationInsights.Util.dump(e)); - return null; - } - }; - return PageVisitTimeManager; - })(); - Telemetry.PageVisitTimeManager = PageVisitTimeManager; - var PageVisitData = (function () { - function PageVisitData(pageName, pageUrl) { - this.pageVisitStartTime = Date.now(); - this.pageName = pageName; - this.pageUrl = pageUrl; - } - return PageVisitData; - })(); - Telemetry.PageVisitData = PageVisitData; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var AI; -(function (AI) { - "use strict"; - (function (DependencyKind) { - DependencyKind[DependencyKind["SQL"] = 0] = "SQL"; - DependencyKind[DependencyKind["Http"] = 1] = "Http"; - DependencyKind[DependencyKind["Other"] = 2] = "Other"; - })(AI.DependencyKind || (AI.DependencyKind = {})); - var DependencyKind = AI.DependencyKind; -})(AI || (AI = {})); -var AI; -(function (AI) { - "use strict"; - (function (DependencySourceType) { - DependencySourceType[DependencySourceType["Undefined"] = 0] = "Undefined"; - DependencySourceType[DependencySourceType["Aic"] = 1] = "Aic"; - DependencySourceType[DependencySourceType["Apmc"] = 2] = "Apmc"; - })(AI.DependencySourceType || (AI.DependencySourceType = {})); - var DependencySourceType = AI.DependencySourceType; -})(AI || (AI = {})); -/// -/// -/// -/// -var AI; -(function (AI) { - "use strict"; - var RemoteDependencyData = (function (_super) { - __extends(RemoteDependencyData, _super); - function RemoteDependencyData() { - _super.call(this); - this.ver = 2; - this.kind = AI.DataPointType.Aggregation; - this.dependencyKind = AI.DependencyKind.Other; - this.success = true; - this.dependencySource = AI.DependencySourceType.Apmc; - this.properties = {}; - _super.call(this); - } - return RemoteDependencyData; - })(Microsoft.Telemetry.Domain); - AI.RemoteDependencyData = RemoteDependencyData; -})(AI || (AI = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - var Telemetry; - (function (Telemetry) { - "use strict"; - var RemoteDependencyData = (function (_super) { - __extends(RemoteDependencyData, _super); - function RemoteDependencyData(id, absoluteUrl, commandName, value, success, resultCode, method) { - _super.call(this); - this.aiDataContract = { - id: ApplicationInsights.FieldType.Required, - ver: ApplicationInsights.FieldType.Required, - name: ApplicationInsights.FieldType.Default, - kind: ApplicationInsights.FieldType.Required, - value: ApplicationInsights.FieldType.Default, - count: ApplicationInsights.FieldType.Default, - min: ApplicationInsights.FieldType.Default, - max: ApplicationInsights.FieldType.Default, - stdDev: ApplicationInsights.FieldType.Default, - dependencyKind: ApplicationInsights.FieldType.Default, - success: ApplicationInsights.FieldType.Default, - async: ApplicationInsights.FieldType.Default, - dependencySource: ApplicationInsights.FieldType.Default, - commandName: ApplicationInsights.FieldType.Default, - dependencyTypeName: ApplicationInsights.FieldType.Default, - properties: ApplicationInsights.FieldType.Default, - resultCode: ApplicationInsights.FieldType.Default - }; - this.id = id; - this.name = this.formatDependencyName(method, absoluteUrl); - this.commandName = Telemetry.Common.DataSanitizer.sanitizeUrl(commandName); - this.value = value; - this.success = success; - this.resultCode = resultCode + ""; - this.dependencyKind = AI.DependencyKind.Http; - this.dependencyTypeName = "Ajax"; - } - RemoteDependencyData.prototype.formatDependencyName = function (method, absoluteUrl) { - if (method) { - return method.toUpperCase() + " " + absoluteUrl; - } - else { - return absoluteUrl; - } - }; - RemoteDependencyData.envelopeType = "Microsoft.ApplicationInsights.{0}.RemoteDependency"; - RemoteDependencyData.dataType = "RemoteDependencyData"; - return RemoteDependencyData; - })(AI.RemoteDependencyData); - Telemetry.RemoteDependencyData = RemoteDependencyData; - })(Telemetry = ApplicationInsights.Telemetry || (ApplicationInsights.Telemetry = {})); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - ApplicationInsights.Version = "0.22.19"; - var AppInsights = (function () { - function AppInsights(config) { - var _this = this; - this._trackAjaxAttempts = 0; - this.config = config || {}; - var defaults = AppInsights.defaultConfig; - if (defaults !== undefined) { - for (var field in defaults) { - if (this.config[field] === undefined) { - this.config[field] = defaults[field]; - } - } - } - ApplicationInsights._InternalLogging.verboseLogging = function () { return _this.config.verboseLogging; }; - ApplicationInsights._InternalLogging.enableDebugExceptions = function () { return _this.config.enableDebug; }; - var configGetters = { - instrumentationKey: function () { return _this.config.instrumentationKey; }, - accountId: function () { return _this.config.accountId; }, - sessionRenewalMs: function () { return _this.config.sessionRenewalMs; }, - sessionExpirationMs: function () { return _this.config.sessionExpirationMs; }, - endpointUrl: function () { return _this.config.endpointUrl; }, - emitLineDelimitedJson: function () { return _this.config.emitLineDelimitedJson; }, - maxBatchSizeInBytes: function () { return _this.config.maxBatchSizeInBytes; }, - maxBatchInterval: function () { return _this.config.maxBatchInterval; }, - disableTelemetry: function () { return _this.config.disableTelemetry; }, - sampleRate: function () { return _this.config.samplingPercentage; }, - cookieDomain: function () { return _this.config.cookieDomain; }, - enableSessionStorageBuffer: function () { return _this.config.enableSessionStorageBuffer; } - }; - var enableExperiment = new ApplicationInsights.SplitTest().isEnabled(this.config.instrumentationKey, 5); - this.config.enableSessionStorageBuffer = enableExperiment; - this.context = new ApplicationInsights.TelemetryContext(configGetters); - ApplicationInsights.DataLossAnalyzer.appInsights = this; - ApplicationInsights.DataLossAnalyzer.enabled = enableExperiment; - ApplicationInsights.DataLossAnalyzer.reportLostItems(); - this._pageViewManager = new Microsoft.ApplicationInsights.Telemetry.PageViewManager(this, this.config.overridePageViewDuration); - this._eventTracking = new Timing("trackEvent"); - this._eventTracking.action = function (name, url, duration, properties, measurements) { - if (!measurements) { - measurements = { duration: duration }; - } - else { - if (isNaN(measurements["duration"])) { - measurements["duration"] = duration; - } - } - var event = new ApplicationInsights.Telemetry.Event(name, properties, measurements); - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Event.dataType, event); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Event.envelopeType); - _this.context.track(envelope); - }; - this._pageTracking = new Timing("trackPageView"); - this._pageTracking.action = function (name, url, duration, properties, measurements) { - _this.sendPageViewInternal(name, url, duration, properties, measurements); - }; - this._pageVisitTimeManager = new ApplicationInsights.Telemetry.PageVisitTimeManager(function (pageName, pageUrl, pageVisitTime) { return _this.trackPageVisitTime(pageName, pageUrl, pageVisitTime); }); - if (!this.config.disableAjaxTracking) { - new Microsoft.ApplicationInsights.AjaxMonitor(this); - } - } - AppInsights.prototype.sendPageViewInternal = function (name, url, duration, properties, measurements) { - var pageView = new ApplicationInsights.Telemetry.PageView(name, url, duration, properties, measurements); - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.PageView.dataType, pageView); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.PageView.envelopeType); - this.context.track(envelope); - this._trackAjaxAttempts = 0; - }; - AppInsights.prototype.sendPageViewPerformanceInternal = function (pageViewPerformance) { - var pageViewPerformanceData = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerformance); - var pageViewPerformanceEnvelope = new ApplicationInsights.Telemetry.Common.Envelope(pageViewPerformanceData, ApplicationInsights.Telemetry.PageViewPerformance.envelopeType); - this.context.track(pageViewPerformanceEnvelope); - }; - AppInsights.prototype.startTrackPage = function (name) { - try { - if (typeof name !== "string") { - name = window.document && window.document.title || ""; - } - this._pageTracking.start(name); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_StartTrackFailed, "startTrackPage failed, page view may not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.stopTrackPage = function (name, url, properties, measurements) { - try { - if (typeof name !== "string") { - name = window.document && window.document.title || ""; - } - if (typeof url !== "string") { - url = window.location && window.location.href || ""; - } - this._pageTracking.stop(name, url, properties, measurements); - if (this.config.autoTrackPageVisitTime) { - this._pageVisitTimeManager.trackPreviousPageVisit(name, url); - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_StopTrackFailed, "stopTrackPage failed, page view will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.trackPageView = function (name, url, properties, measurements, duration) { - try { - this._pageViewManager.trackPageView(name, url, properties, measurements, duration); - if (this.config.autoTrackPageVisitTime) { - this._pageVisitTimeManager.trackPreviousPageVisit(name, url); - } - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TrackPVFailed, "trackPageView failed, page view will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.startTrackEvent = function (name) { - try { - this._eventTracking.start(name); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_StartTrackEventFailed, "startTrackEvent failed, event will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.stopTrackEvent = function (name, properties, measurements) { - try { - this._eventTracking.stop(name, undefined, properties, measurements); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_StopTrackEventFailed, "stopTrackEvent failed, event will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.trackEvent = function (name, properties, measurements) { - try { - var eventTelemetry = new ApplicationInsights.Telemetry.Event(name, properties, measurements); - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Event.dataType, eventTelemetry); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Event.envelopeType); - this.context.track(envelope); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TrackEventFailed, "trackEvent failed, event will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.trackAjax = function (id, absoluteUrl, pathName, totalTime, success, resultCode, method) { - if (this.config.maxAjaxCallsPerView === -1 || - this._trackAjaxAttempts < this.config.maxAjaxCallsPerView) { - var dependency = new ApplicationInsights.Telemetry.RemoteDependencyData(id, absoluteUrl, pathName, totalTime, success, resultCode, method); - var dependencyData = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.RemoteDependencyData.dataType, dependency); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(dependencyData, ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType); - this.context.track(envelope); - } - else if (this._trackAjaxAttempts === this.config.maxAjaxCallsPerView) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_MaxAjaxPerPVExceeded, "Maximum ajax per page view limit reached, ajax monitoring is paused until the next trackPageView(). In order to increase the limit set the maxAjaxCallsPerView configuration parameter.")); - } - ++this._trackAjaxAttempts; - }; - AppInsights.prototype.trackException = function (exception, handledAt, properties, measurements, severityLevel) { - try { - if (!ApplicationInsights.Util.isError(exception)) { - try { - throw new Error(exception); - } - catch (error) { - exception = error; - } - } - var exceptionTelemetry = new ApplicationInsights.Telemetry.Exception(exception, handledAt, properties, measurements, severityLevel); - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Exception.dataType, exceptionTelemetry); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Exception.envelopeType); - this.context.track(envelope); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TrackExceptionFailed, "trackException failed, exception will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.trackMetric = function (name, average, sampleCount, min, max, properties) { - try { - var telemetry = new ApplicationInsights.Telemetry.Metric(name, average, sampleCount, min, max, properties); - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Metric.dataType, telemetry); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Metric.envelopeType); - this.context.track(envelope); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TrackMetricFailed, "trackMetric failed, metric will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.trackTrace = function (message, properties) { - try { - var telemetry = new ApplicationInsights.Telemetry.Trace(message, properties); - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Trace.dataType, telemetry); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Trace.envelopeType); - this.context.track(envelope); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_TrackTraceFailed, "trackTrace failed, trace will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.trackPageVisitTime = function (pageName, pageUrl, pageVisitTime) { - var properties = { PageName: pageName, PageUrl: pageUrl }; - this.trackMetric("PageVisitTime", pageVisitTime, 1, pageVisitTime, pageVisitTime, properties); - }; - AppInsights.prototype.flush = function () { - try { - this.context._sender.triggerSend(); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FlushFailed, "flush failed, telemetry will not be collected: " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.setAuthenticatedUserContext = function (authenticatedUserId, accountId) { - try { - this.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_SetAuthContextFailed, "Setting auth user context failed. " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.clearAuthenticatedUserContext = function () { - try { - this.context.user.clearAuthenticatedUserContext(); - } - catch (e) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_SetAuthContextFailed, "Clearing auth user context failed. " + ApplicationInsights.Util.getExceptionName(e), { exception: ApplicationInsights.Util.dump(e) })); - } - }; - AppInsights.prototype.SendCORSException = function (properties) { - var exceptionData = Microsoft.ApplicationInsights.Telemetry.Exception.CreateSimpleException("Script error.", "Error", "unknown", "unknown", "The browser's same-origin policy prevents us from getting the details of this exception.The exception occurred in a script loaded from an origin different than the web page.For cross- domain error reporting you can use crossorigin attribute together with appropriate CORS HTTP headers.For more information please see http://www.w3.org/TR/cors/.", 0, null); - exceptionData.properties = properties; - var data = new ApplicationInsights.Telemetry.Common.Data(ApplicationInsights.Telemetry.Exception.dataType, exceptionData); - var envelope = new ApplicationInsights.Telemetry.Common.Envelope(data, ApplicationInsights.Telemetry.Exception.envelopeType); - this.context.track(envelope); - }; - AppInsights.prototype._onerror = function (message, url, lineNumber, columnNumber, error) { - try { - var properties = { url: url ? url : document.URL }; - if (ApplicationInsights.Util.isCrossOriginError(message, url, lineNumber, columnNumber, error)) { - this.SendCORSException(properties); - } - else { - if (!ApplicationInsights.Util.isError(error)) { - var stack = "window.onerror@" + properties.url + ":" + lineNumber + ":" + (columnNumber || 0); - error = new Error(message); - error["stack"] = stack; - } - this.trackException(error, null, properties); - } - } - catch (exception) { - var errorString = error ? (error.name + ", " + error.message) : "null"; - var exceptionDump = ApplicationInsights.Util.dump(exception); - ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_ExceptionWhileLoggingError, "_onerror threw exception while logging error, error will not be collected: " + ApplicationInsights.Util.getExceptionName(exception), { exception: exceptionDump, errorString: errorString })); - } - }; - return AppInsights; - })(); - ApplicationInsights.AppInsights = AppInsights; - var Timing = (function () { - function Timing(name) { - this._name = name; - this._events = {}; - } - Timing.prototype.start = function (name) { - if (typeof this._events[name] !== "undefined") { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_StartCalledMoreThanOnce, "start was called more than once for this event without calling stop.", { name: this._name, key: name })); - } - this._events[name] = +new Date; - }; - Timing.prototype.stop = function (name, url, properties, measurements) { - var start = this._events[name]; - if (isNaN(start)) { - ApplicationInsights._InternalLogging.throwInternalUserActionable(ApplicationInsights.LoggingSeverity.WARNING, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.USRACT_StopCalledWithoutStart, "stop was called without a corresponding start.", { name: this._name, key: name })); - } - else { - var end = +new Date; - var duration = ApplicationInsights.Telemetry.PageViewPerformance.getDuration(start, end); - this.action(name, url, duration, properties, measurements); - } - delete this._events[name]; - this._events[name] = undefined; - }; - return Timing; - })(); - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - var Initialization = (function () { - function Initialization(snippet) { - snippet.queue = snippet.queue || []; - var config = snippet.config || {}; - if (config && !config.instrumentationKey) { - config = snippet; - if (config["iKey"]) { - Microsoft.ApplicationInsights.Version = "0.10.0.0"; - config.instrumentationKey = config["iKey"]; - } - else if (config["applicationInsightsId"]) { - Microsoft.ApplicationInsights.Version = "0.7.2.0"; - config.instrumentationKey = config["applicationInsightsId"]; - } - else { - throw new Error("Cannot load Application Insights SDK, no instrumentationKey was provided."); - } - } - config = Initialization.getDefaultConfig(config); - this.snippet = snippet; - this.config = config; - } - Initialization.prototype.loadAppInsights = function () { - var appInsights = new Microsoft.ApplicationInsights.AppInsights(this.config); - if (this.config["iKey"]) { - var originalTrackPageView = appInsights.trackPageView; - appInsights.trackPageView = function (pagePath, properties, measurements) { - originalTrackPageView.apply(appInsights, [null, pagePath, properties, measurements]); - }; - } - var legacyPageView = "logPageView"; - if (typeof this.snippet[legacyPageView] === "function") { - appInsights[legacyPageView] = function (pagePath, properties, measurements) { - appInsights.trackPageView(null, pagePath, properties, measurements); - }; - } - var legacyEvent = "logEvent"; - if (typeof this.snippet[legacyEvent] === "function") { - appInsights[legacyEvent] = function (name, properties, measurements) { - appInsights.trackEvent(name, properties, measurements); - }; - } - return appInsights; - }; - Initialization.prototype.emptyQueue = function () { - try { - if (Microsoft.ApplicationInsights.Util.isArray(this.snippet.queue)) { - var length = this.snippet.queue.length; - for (var i = 0; i < length; i++) { - var call = this.snippet.queue[i]; - call(); - } - this.snippet.queue = undefined; - delete this.snippet.queue; - } - } - catch (exception) { - var properties = {}; - if (exception && typeof exception.toString === "function") { - properties.exception = exception.toString(); - } - var message = new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedToSendQueuedTelemetry, "Failed to send queued telemetry", properties); - Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(ApplicationInsights.LoggingSeverity.WARNING, message); - } - }; - Initialization.prototype.pollInteralLogs = function (appInsightsInstance) { - return setInterval(function () { - var queue = Microsoft.ApplicationInsights._InternalLogging.queue; - var length = queue.length; - for (var i = 0; i < length; i++) { - appInsightsInstance.trackTrace(queue[i].message); - } - queue.length = 0; - }, this.config.diagnosticLogInterval); - }; - Initialization.prototype.addHousekeepingBeforeUnload = function (appInsightsInstance) { - // Add callback to push events when the user navigates away - if (!appInsightsInstance.config.disableFlushOnBeforeUnload && ('onbeforeunload' in window)) { - var performHousekeeping = function () { - appInsightsInstance.context._sender.triggerSend(); - appInsightsInstance.context._sessionManager.backup(); - }; - if (!Microsoft.ApplicationInsights.Util.addEventHandler('beforeunload', performHousekeeping)) { - Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, new ApplicationInsights._InternalLogMessage(ApplicationInsights._InternalMessageId.NONUSRACT_FailedToAddHandlerForOnBeforeUnload, 'Could not add handler for beforeunload')); - } - } - }; - Initialization.getDefaultConfig = function (config) { - if (!config) { - config = {}; - } - config.endpointUrl = config.endpointUrl || "//dc.services.visualstudio.com/v2/track"; - config.sessionRenewalMs = 30 * 60 * 1000; - config.sessionExpirationMs = 24 * 60 * 60 * 1000; - config.maxBatchSizeInBytes = config.maxBatchSizeInBytes > 0 ? config.maxBatchSizeInBytes : 1000000; - config.maxBatchInterval = !isNaN(config.maxBatchInterval) ? config.maxBatchInterval : 15000; - config.enableDebug = ApplicationInsights.Util.stringToBoolOrDefault(config.enableDebug); - config.disableExceptionTracking = (config.disableExceptionTracking !== undefined && config.disableExceptionTracking !== null) ? - ApplicationInsights.Util.stringToBoolOrDefault(config.disableExceptionTracking) : - false; - config.disableTelemetry = ApplicationInsights.Util.stringToBoolOrDefault(config.disableTelemetry); - config.verboseLogging = ApplicationInsights.Util.stringToBoolOrDefault(config.verboseLogging); - config.emitLineDelimitedJson = ApplicationInsights.Util.stringToBoolOrDefault(config.emitLineDelimitedJson); - config.diagnosticLogInterval = config.diagnosticLogInterval || 10000; - config.autoTrackPageVisitTime = ApplicationInsights.Util.stringToBoolOrDefault(config.autoTrackPageVisitTime); - if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) { - config.samplingPercentage = 100; - } - config.disableAjaxTracking = (config.disableAjaxTracking !== undefined && config.disableAjaxTracking !== null) ? - ApplicationInsights.Util.stringToBoolOrDefault(config.disableAjaxTracking) : - false; - config.maxAjaxCallsPerView = !isNaN(config.maxAjaxCallsPerView) ? config.maxAjaxCallsPerView : 500; - config.disableCorrelationHeaders = (config.disableCorrelationHeaders !== undefined && config.disableCorrelationHeaders !== null) ? - ApplicationInsights.Util.stringToBoolOrDefault(config.disableCorrelationHeaders) : - true; - config.disableFlushOnBeforeUnload = (config.disableFlushOnBeforeUnload !== undefined && config.disableFlushOnBeforeUnload !== null) ? - ApplicationInsights.Util.stringToBoolOrDefault(config.disableFlushOnBeforeUnload) : - false; - config.enableSessionStorageBuffer = (config.enableSessionStorageBuffer !== undefined && config.enableSessionStorageBuffer !== null) ? - ApplicationInsights.Util.stringToBoolOrDefault(config.enableSessionStorageBuffer) : - false; - return config; - }; - return Initialization; - })(); - ApplicationInsights.Initialization = Initialization; - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var Microsoft; -(function (Microsoft) { - var ApplicationInsights; - (function (ApplicationInsights) { - "use strict"; - try { - if (typeof window !== "undefined" && typeof JSON !== "undefined") { - var aiName = "appInsights"; - if (window[aiName] === undefined) { - Microsoft.ApplicationInsights.AppInsights.defaultConfig = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(); - } - else { - var snippet = window[aiName] || {}; - var init = new Microsoft.ApplicationInsights.Initialization(snippet); - var appInsightsLocal = init.loadAppInsights(); - for (var field in appInsightsLocal) { - snippet[field] = appInsightsLocal[field]; - } - init.emptyQueue(); - init.pollInteralLogs(appInsightsLocal); - init.addHousekeepingBeforeUnload(appInsightsLocal); - } - } - } - catch (e) { - Microsoft.ApplicationInsights._InternalLogging.warnToConsole('Failed to initialize AppInsights JS SDK: ' + e.message); - } - })(ApplicationInsights = Microsoft.ApplicationInsights || (Microsoft.ApplicationInsights = {})); -})(Microsoft || (Microsoft = {})); -/// -var AI; -(function (AI) { - "use strict"; - var AjaxCallData = (function (_super) { - __extends(AjaxCallData, _super); - function AjaxCallData() { - _super.call(this); - this.ver = 2; - this.properties = {}; - this.measurements = {}; - _super.call(this); - } - return AjaxCallData; - })(AI.PageViewData); - AI.AjaxCallData = AjaxCallData; -})(AI || (AI = {})); -/// -var AI; -(function (AI) { - "use strict"; - var RequestData = (function (_super) { - __extends(RequestData, _super); - function RequestData() { - _super.call(this); - this.ver = 2; - this.properties = {}; - this.measurements = {}; - _super.call(this); - } - return RequestData; - })(Microsoft.Telemetry.Domain); - AI.RequestData = RequestData; -})(AI || (AI = {})); -/// -/// -var AI; -(function (AI) { - "use strict"; - var SessionStateData = (function (_super) { - __extends(SessionStateData, _super); - function SessionStateData() { - _super.call(this); - this.ver = 2; - this.state = AI.SessionState.Start; - _super.call(this); - } - return SessionStateData; - })(Microsoft.Telemetry.Domain); - AI.SessionStateData = SessionStateData; -})(AI || (AI = {})); -var AI; -(function (AI) { - "use strict"; - (function (TestResult) { - TestResult[TestResult["Pass"] = 0] = "Pass"; - TestResult[TestResult["Fail"] = 1] = "Fail"; - })(AI.TestResult || (AI.TestResult = {})); - var TestResult = AI.TestResult; -})(AI || (AI = {})); diff --git a/CSharp/capability-botToWeb/Bot/scripts/ai.0.22.19-build00125.min.js b/CSharp/capability-botToWeb/Bot/scripts/ai.0.22.19-build00125.min.js deleted file mode 100644 index 88b4ac92d0..0000000000 --- a/CSharp/capability-botToWeb/Bot/scripts/ai.0.22.19-build00125.min.js +++ /dev/null @@ -1 +0,0 @@ -var __extends,Microsoft,AI;(function(n){var t;(function(n){var r,t,i,u;(function(n){n[n.CRITICAL=0]="CRITICAL";n[n.WARNING=1]="WARNING"})(n.LoggingSeverity||(n.LoggingSeverity={}));r=n.LoggingSeverity,function(n){n[n.NONUSRACT_BrowserDoesNotSupportLocalStorage=0]="NONUSRACT_BrowserDoesNotSupportLocalStorage";n[n.NONUSRACT_BrowserCannotReadLocalStorage=1]="NONUSRACT_BrowserCannotReadLocalStorage";n[n.NONUSRACT_BrowserCannotReadSessionStorage=2]="NONUSRACT_BrowserCannotReadSessionStorage";n[n.NONUSRACT_BrowserCannotWriteLocalStorage=3]="NONUSRACT_BrowserCannotWriteLocalStorage";n[n.NONUSRACT_BrowserCannotWriteSessionStorage=4]="NONUSRACT_BrowserCannotWriteSessionStorage";n[n.NONUSRACT_BrowserFailedRemovalFromLocalStorage=5]="NONUSRACT_BrowserFailedRemovalFromLocalStorage";n[n.NONUSRACT_BrowserFailedRemovalFromSessionStorage=6]="NONUSRACT_BrowserFailedRemovalFromSessionStorage";n[n.NONUSRACT_CannotSendEmptyTelemetry=7]="NONUSRACT_CannotSendEmptyTelemetry";n[n.NONUSRACT_ClientPerformanceMathError=8]="NONUSRACT_ClientPerformanceMathError";n[n.NONUSRACT_ErrorParsingAISessionCookie=9]="NONUSRACT_ErrorParsingAISessionCookie";n[n.NONUSRACT_ErrorPVCalc=10]="NONUSRACT_ErrorPVCalc";n[n.NONUSRACT_ExceptionWhileLoggingError=11]="NONUSRACT_ExceptionWhileLoggingError";n[n.NONUSRACT_FailedAddingTelemetryToBuffer=12]="NONUSRACT_FailedAddingTelemetryToBuffer";n[n.NONUSRACT_FailedMonitorAjaxAbort=13]="NONUSRACT_FailedMonitorAjaxAbort";n[n.NONUSRACT_FailedMonitorAjaxDur=14]="NONUSRACT_FailedMonitorAjaxDur";n[n.NONUSRACT_FailedMonitorAjaxOpen=15]="NONUSRACT_FailedMonitorAjaxOpen";n[n.NONUSRACT_FailedMonitorAjaxRSC=16]="NONUSRACT_FailedMonitorAjaxRSC";n[n.NONUSRACT_FailedMonitorAjaxSend=17]="NONUSRACT_FailedMonitorAjaxSend";n[n.NONUSRACT_FailedToAddHandlerForOnBeforeUnload=18]="NONUSRACT_FailedToAddHandlerForOnBeforeUnload";n[n.NONUSRACT_FailedToSendQueuedTelemetry=19]="NONUSRACT_FailedToSendQueuedTelemetry";n[n.NONUSRACT_FailedToReportDataLoss=20]="NONUSRACT_FailedToReportDataLoss";n[n.NONUSRACT_FlushFailed=21]="NONUSRACT_FlushFailed";n[n.NONUSRACT_MessageLimitPerPVExceeded=22]="NONUSRACT_MessageLimitPerPVExceeded";n[n.NONUSRACT_MissingRequiredFieldSpecification=23]="NONUSRACT_MissingRequiredFieldSpecification";n[n.NONUSRACT_NavigationTimingNotSupported=24]="NONUSRACT_NavigationTimingNotSupported";n[n.NONUSRACT_OnError=25]="NONUSRACT_OnError";n[n.NONUSRACT_SessionRenewalDateIsZero=26]="NONUSRACT_SessionRenewalDateIsZero";n[n.NONUSRACT_SenderNotInitialized=27]="NONUSRACT_SenderNotInitialized";n[n.NONUSRACT_StartTrackEventFailed=28]="NONUSRACT_StartTrackEventFailed";n[n.NONUSRACT_StopTrackEventFailed=29]="NONUSRACT_StopTrackEventFailed";n[n.NONUSRACT_StartTrackFailed=30]="NONUSRACT_StartTrackFailed";n[n.NONUSRACT_StopTrackFailed=31]="NONUSRACT_StopTrackFailed";n[n.NONUSRACT_TelemetrySampledAndNotSent=32]="NONUSRACT_TelemetrySampledAndNotSent";n[n.NONUSRACT_TrackEventFailed=33]="NONUSRACT_TrackEventFailed";n[n.NONUSRACT_TrackExceptionFailed=34]="NONUSRACT_TrackExceptionFailed";n[n.NONUSRACT_TrackMetricFailed=35]="NONUSRACT_TrackMetricFailed";n[n.NONUSRACT_TrackPVFailed=36]="NONUSRACT_TrackPVFailed";n[n.NONUSRACT_TrackPVFailedCalc=37]="NONUSRACT_TrackPVFailedCalc";n[n.NONUSRACT_TrackTraceFailed=38]="NONUSRACT_TrackTraceFailed";n[n.NONUSRACT_TransmissionFailed=39]="NONUSRACT_TransmissionFailed";n[n.NONUSRACT_FailToSetStorageBuffer=40]="NONUSRACT_FailToSetStorageBuffer";n[n.NONUSRACT_FailToRestoreStorageBuffer=41]="NONUSRACT_FailToRestoreStorageBuffer";n[n.USRACT_CannotSerializeObject=42]="USRACT_CannotSerializeObject";n[n.USRACT_CannotSerializeObjectNonSerializable=43]="USRACT_CannotSerializeObjectNonSerializable";n[n.USRACT_CircularReferenceDetected=44]="USRACT_CircularReferenceDetected";n[n.USRACT_ClearAuthContextFailed=45]="USRACT_ClearAuthContextFailed";n[n.USRACT_ExceptionTruncated=46]="USRACT_ExceptionTruncated";n[n.USRACT_IllegalCharsInName=47]="USRACT_IllegalCharsInName";n[n.USRACT_ItemNotInArray=48]="USRACT_ItemNotInArray";n[n.USRACT_MaxAjaxPerPVExceeded=49]="USRACT_MaxAjaxPerPVExceeded";n[n.USRACT_MessageTruncated=50]="USRACT_MessageTruncated";n[n.USRACT_NameTooLong=51]="USRACT_NameTooLong";n[n.USRACT_SampleRateOutOfRange=52]="USRACT_SampleRateOutOfRange";n[n.USRACT_SetAuthContextFailed=53]="USRACT_SetAuthContextFailed";n[n.USRACT_SetAuthContextFailedAccountName=54]="USRACT_SetAuthContextFailedAccountName";n[n.USRACT_StringValueTooLong=55]="USRACT_StringValueTooLong";n[n.USRACT_StartCalledMoreThanOnce=56]="USRACT_StartCalledMoreThanOnce";n[n.USRACT_StopCalledWithoutStart=57]="USRACT_StopCalledWithoutStart";n[n.USRACT_TelemetryInitializerFailed=58]="USRACT_TelemetryInitializerFailed";n[n.USRACT_TrackArgumentsNotSpecified=59]="USRACT_TrackArgumentsNotSpecified";n[n.USRACT_UrlTooLong=60]="USRACT_UrlTooLong"}(n._InternalMessageId||(n._InternalMessageId={}));t=n._InternalMessageId;i=function(){function n(i,r,u){this.message=t[i].toString();this.messageId=i;var f=(r?" message:"+n.sanitizeDiagnosticText(r):"")+(u?" props:"+n.sanitizeDiagnosticText(JSON.stringify(u)):"");this.message+=f}return n.sanitizeDiagnosticText=function(n){return'"'+n.replace(/\"/g,"")+'"'},n}();n._InternalLogMessage=i;u=function(){function u(){}return u.throwInternalNonUserActionable=function(n,t){if(this.enableDebugExceptions())throw t;else typeof t=="undefined"||!t||typeof t.message!="undefined"&&(t.message=this.AiNonUserActionablePrefix+t.message,this.verboseLogging()&&this.warnToConsole(t.message),this.logInternalMessage(n,t))},u.throwInternalUserActionable=function(n,t){if(this.enableDebugExceptions())throw t;else typeof t=="undefined"||!t||typeof t.message!="undefined"&&(t.message=this.AiUserActionablePrefix+t.message,this.warnToConsole(t.message),this.logInternalMessage(n,t))},u.warnToConsole=function(n){typeof console=="undefined"||!console||(typeof console.warn=="function"?console.warn(n):typeof console.log=="function"&&console.log(n))},u.resetInternalMessageCount=function(){this._messageCount=0},u.clearInternalMessageLoggedTypes=function(){var i,t;if(n.Util.canUseSessionStorage())for(i=n.Util.getSessionStorageKeys(),t=0;t=this.MAX_INTERNAL_MESSAGE_LIMIT},u.AiUserActionablePrefix="AI: ",u.AIInternalMessagePrefix="AITR_",u.AiNonUserActionablePrefix="AI (Internal): ",u.enableDebugExceptions=function(){return!1},u.verboseLogging=function(){return!1},u.queue=[],u.MAX_INTERNAL_MESSAGE_LIMIT=25,u._messageCount=0,u}();n._InternalLogging=u})(t=n.ApplicationInsights||(n.ApplicationInsights={}))})(Microsoft||(Microsoft={})),function(n){var t;(function(n){var t,i,r;(function(n){n[n.LocalStorage=0]="LocalStorage";n[n.SessionStorage=1]="SessionStorage"})(t||(t={}));i=function(){function i(){}return i._getLocalStorageObject=function(){return i._getVerifiedStorageObject(t.LocalStorage)},i._getVerifiedStorageObject=function(n){var i=null,u,r;try{r=new Date;i=n===t.LocalStorage?window.localStorage:window.sessionStorage;i.setItem(r,r);u=i.getItem(r)!=r;i.removeItem(r);u&&(i=null)}catch(f){i=null}return i},i.canUseLocalStorage=function(){return!!i._getLocalStorageObject()},i.getStorage=function(t){var r=i._getLocalStorageObject(),f;if(r!==null)try{return r.getItem(t)}catch(u){f=new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserCannotReadLocalStorage,"Browser failed read of local storage. "+i.getExceptionName(u),{exception:i.dump(u)});n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,f)}return null},i.setStorage=function(t,r){var u=i._getLocalStorageObject(),e;if(u!==null)try{return u.setItem(t,r),!0}catch(f){e=new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserCannotWriteLocalStorage,"Browser failed write to local storage. "+i.getExceptionName(f),{exception:i.dump(f)});n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,e)}return!1},i.removeStorage=function(t){var r=i._getLocalStorageObject(),f;if(r!==null)try{return r.removeItem(t),!0}catch(u){f=new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserFailedRemovalFromLocalStorage,"Browser failed removal of local storage item. "+i.getExceptionName(u),{exception:i.dump(u)});n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,f)}return!1},i._getSessionStorageObject=function(){return i._getVerifiedStorageObject(t.SessionStorage)},i.canUseSessionStorage=function(){return!!i._getSessionStorageObject()},i.getSessionStorageKeys=function(){var n=[],t;if(i.canUseSessionStorage())for(t in window.sessionStorage)n.push(t);return n},i.getSessionStorage=function(t){var r=i._getSessionStorageObject(),f;if(r!==null)try{return r.getItem(t)}catch(u){f=new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserCannotReadSessionStorage,"Browser failed read of session storage. "+i.getExceptionName(u),{exception:i.dump(u)});n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,f)}return null},i.setSessionStorage=function(t,r){var u=i._getSessionStorageObject(),e;if(u!==null)try{return u.setItem(t,r),!0}catch(f){e=new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserCannotWriteSessionStorage,"Browser failed write to session storage. "+i.getExceptionName(f),{exception:i.dump(f)});n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,e)}return!1},i.removeSessionStorage=function(t){var r=i._getSessionStorageObject(),f;if(r!==null)try{return r.removeItem(t),!0}catch(u){f=new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserFailedRemovalFromSessionStorage,"Browser failed removal of session storage item. "+i.getExceptionName(u),{exception:i.dump(u)});n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,f)}return!1},i.setCookie=function(n,t,r){var u="";r&&(u=";domain="+r);i.document.cookie=n+"="+t+u+";path=/"},i.stringToBoolOrDefault=function(n){return n?n.toString().toLowerCase()==="true":!1},i.getCookie=function(n){var e="",f,u,r,t;if(n&&n.length)for(f=n+"=",u=i.document.cookie.split(";"),r=0;r0;)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(n%64),t+=i,n=Math.floor(n/64);return t},i.isArray=function(n){return Object.prototype.toString.call(n)==="[object Array]"},i.isError=function(n){return Object.prototype.toString.call(n)==="[object Error]"},i.isDate=function(n){return Object.prototype.toString.call(n)==="[object Date]"},i.toISOStringForIE8=function(n){if(i.isDate(n)){function t(n){var t=String(n);return t.length===1&&(t="0"+t),t}return Date.prototype.toISOString?n.toISOString():n.getUTCFullYear()+"-"+t(n.getUTCMonth()+1)+"-"+t(n.getUTCDate())+"T"+t(n.getUTCHours())+":"+t(n.getUTCMinutes())+":"+t(n.getUTCSeconds())+"."+String((n.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}},i.getIEVersion=function(n){n===void 0&&(n=null);var t=n?n.toLowerCase():navigator.userAgent.toLowerCase();return t.indexOf("msie")!=-1?parseInt(t.split("msie")[1]):null},i.msToTimeSpan=function(n){(isNaN(n)||n<0)&&(n=0);var t=""+n%1e3,i=""+Math.floor(n/1e3)%60,r=""+Math.floor(n/6e4)%60,u=""+Math.floor(n/36e5)%24;return t=t.length===1?"00"+t:t.length===2?"0"+t:t,i=i.length<2?"0"+i:i,r=r.length<2?"0"+r:r,u=u.length<2?"0"+u:u,u+":"+r+":"+i+"."+t},i.isCrossOriginError=function(n,t,i,r,u){return(n==="Script error."||n==="Script error")&&u===null},i.dump=function(n){var t=Object.prototype.toString.call(n),i=JSON.stringify(n);return t==="[object Error]"&&(i="{ stack: '"+n.stack+"', message: '"+n.message+"', name: '"+n.name+"'"),t+i},i.getExceptionName=function(n){var t=Object.prototype.toString.call(n);return t==="[object Error]"?n.name:""},i.addEventHandler=function(n,t){if(!window||typeof n!="string"||typeof t!="function")return!1;var i="on"+n;if(window.addEventListener)window.addEventListener(n,t,!1);else if(window.attachEvent)window.attachEvent.call(i,t);else return!1;return!0},i.document=typeof document!="undefined"?document:{},i.NotSpecified="not_specified",i}();n.Util=i;r=function(){function n(){}return n.parseUrl=function(t){return n.htmlAnchorElement||(n.htmlAnchorElement=!n.document.createElement?{}:n.document.createElement("a")),n.htmlAnchorElement.href=t,n.htmlAnchorElement},n.getAbsoluteUrl=function(t){var i,r=n.parseUrl(t);return r&&(i=r.href),i},n.getPathName=function(t){var i,r=n.parseUrl(t);return r&&(i=r.pathname),i},n.document=typeof document!="undefined"?document:{},n}();n.UrlHelper=r})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function n(){}return n.IsNullOrUndefined=function(n){return typeof n=="undefined"||n===null},n}(),i,r,u;n.extensions=t;i=function(){function n(){}return n.GetLength=function(n){var i=0,r;if(!t.IsNullOrUndefined(n)){r="";try{r=n.toString()}catch(u){}i=r.length;i=isNaN(i)?0:i}return i},n}();n.stringUtils=i;r=function(){function n(){}return n.Now=window.performance&&window.performance.now?function(){return performance.now()}:function(){return(new Date).getTime()},n.GetDuration=function(n,i){var r=null;return n===0||i===0||t.IsNullOrUndefined(n)||t.IsNullOrUndefined(i)||(r=i-n),r},n}();n.dateTime=r;u=function(){function n(){}return n.AttachEvent=function(n,i,r){var u=!1;return t.IsNullOrUndefined(n)||(t.IsNullOrUndefined(n.attachEvent)?t.IsNullOrUndefined(n.addEventListener)||(n.addEventListener(i,r,!1),u=!0):(n.attachEvent("on"+i,r),u=!0)),u},n.DetachEvent=function(n,i,r){t.IsNullOrUndefined(n)||(t.IsNullOrUndefined(n.detachEvent)?t.IsNullOrUndefined(n.removeEventListener)||n.removeEventListener(i,r,!1):n.detachEvent("on"+i,r))},n}();n.EventHelper=u})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function n(){this.openDone=!1;this.setRequestHeaderDone=!1;this.sendDone=!1;this.abortDone=!1;this.onreadystatechangeCallbackAttached=!1}return n}(),i;n.XHRMonitoringState=t;i=function(){function i(i){this.completed=!1;this.requestHeadersSize=null;this.ttfb=null;this.responseReceivingDuration=null;this.callbackDuration=null;this.ajaxTotalDuration=null;this.aborted=null;this.pageUrl=null;this.requestUrl=null;this.requestSize=0;this.method=null;this.status=null;this.requestSentTime=null;this.responseStartedTime=null;this.responseFinishedTime=null;this.callbackFinishedTime=null;this.endTime=null;this.originalOnreadystatechage=null;this.xhrMonitoringState=new t;this.clientFailure=0;this.CalculateMetrics=function(){var t=this;t.ajaxTotalDuration=n.dateTime.GetDuration(t.requestSentTime,t.responseFinishedTime)};this.id=i}return i.prototype.getAbsoluteUrl=function(){return this.requestUrl?n.UrlHelper.getAbsoluteUrl(this.requestUrl):null},i.prototype.getPathName=function(){return this.requestUrl?n.UrlHelper.getPathName(this.requestUrl):null},i}();n.ajaxRecord=i})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(t){"use strict";var i=function(){function i(n){this.currentWindowHost=window.location.host;this.appInsights=n;this.initialized=!1;this.Init()}return i.prototype.Init=function(){this.supportsMonitoring()&&(this.instrumentOpen(),this.instrumentSend(),this.instrumentAbort(),this.initialized=!0)},i.prototype.isMonitoredInstance=function(n,r){return this.initialized&&(r===!0||!t.extensions.IsNullOrUndefined(n.ajaxData))&&n[i.DisabledPropertyName]!==!0},i.prototype.supportsMonitoring=function(){var n=!1;return t.extensions.IsNullOrUndefined(XMLHttpRequest)||(n=!0),n},i.prototype.instrumentOpen=function(){var u=XMLHttpRequest.prototype.open,r=this;XMLHttpRequest.prototype.open=function(f,e,o){try{!r.isMonitoredInstance(this,!0)||this.ajaxData&&this.ajaxData.xhrMonitoringState.openDone||r.openHandler(this,f,e,o)}catch(s){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_FailedMonitorAjaxOpen,"Failed to monitor XMLHttpRequest.open, monitoring data for this ajax call may be incorrect.",{ajaxDiagnosticsMessage:i.getFailedAjaxDiagnosticsMessage(this),exception:n.ApplicationInsights.Util.dump(s)}))}return u.apply(this,arguments)}},i.prototype.openHandler=function(n,i,r){var u=new t.ajaxRecord(t.Util.newId());u.method=i;u.requestUrl=r;u.xhrMonitoringState.openDone=!0;n.ajaxData=u;this.attachToOnReadyStateChange(n)},i.getFailedAjaxDiagnosticsMessage=function(n){var i="";try{t.extensions.IsNullOrUndefined(n)||t.extensions.IsNullOrUndefined(n.ajaxData)||t.extensions.IsNullOrUndefined(n.ajaxData.requestUrl)||(i+="(url: '"+n.ajaxData.requestUrl+"')")}catch(r){}return i},i.prototype.instrumentSend=function(){var u=XMLHttpRequest.prototype.send,r=this;XMLHttpRequest.prototype.send=function(f){try{r.isMonitoredInstance(this)&&!this.ajaxData.xhrMonitoringState.sendDone&&r.sendHandler(this,f)}catch(e){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_FailedMonitorAjaxSend,"Failed to monitor XMLHttpRequest, monitoring data for this ajax call may be incorrect.",{ajaxDiagnosticsMessage:i.getFailedAjaxDiagnosticsMessage(this),exception:n.ApplicationInsights.Util.dump(e)}))}return u.apply(this,arguments)}},i.prototype.sendHandler=function(n){n.ajaxData.requestSentTime=t.dateTime.Now();this.appInsights.config.disableCorrelationHeaders||t.UrlHelper.parseUrl(n.ajaxData.getAbsoluteUrl()).host!=this.currentWindowHost||n.setRequestHeader("x-ms-request-id",n.ajaxData.id);n.ajaxData.xhrMonitoringState.sendDone=!0},i.prototype.instrumentAbort=function(){var r=XMLHttpRequest.prototype.abort,u=this;XMLHttpRequest.prototype.abort=function(){try{u.isMonitoredInstance(this)&&!this.ajaxData.xhrMonitoringState.abortDone&&(this.ajaxData.aborted=1,this.ajaxData.xhrMonitoringState.abortDone=!0)}catch(f){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_FailedMonitorAjaxAbort,"Failed to monitor XMLHttpRequest.abort, monitoring data for this ajax call may be incorrect.",{ajaxDiagnosticsMessage:i.getFailedAjaxDiagnosticsMessage(this),exception:n.ApplicationInsights.Util.dump(f)}))}return r.apply(this,arguments)}},i.prototype.attachToOnReadyStateChange=function(r){var u=this;r.ajaxData.xhrMonitoringState.onreadystatechangeCallbackAttached=t.EventHelper.AttachEvent(r,"readystatechange",function(){try{if(u.isMonitoredInstance(r)&&r.readyState===4)u.onAjaxComplete(r)}catch(f){var e=n.ApplicationInsights.Util.dump(f);e&&e.toLowerCase().indexOf("c00c023f")!=-1||t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_FailedMonitorAjaxRSC,"Failed to monitor XMLHttpRequest 'readystatechange' event handler, monitoring data for this ajax call may be incorrect.",{ajaxDiagnosticsMessage:i.getFailedAjaxDiagnosticsMessage(r),exception:n.ApplicationInsights.Util.dump(f)}))}})},i.prototype.onAjaxComplete=function(n){n.ajaxData.responseFinishedTime=t.dateTime.Now();n.ajaxData.status=n.status;n.ajaxData.CalculateMetrics();n.ajaxData.ajaxTotalDuration<0?t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.WARNING,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_FailedMonitorAjaxDur,"Failed to calculate the duration of the ajax call, monitoring data for this ajax call won't be sent.",{ajaxDiagnosticsMessage:i.getFailedAjaxDiagnosticsMessage(n),requestSentTime:n.ajaxData.requestSentTime,responseFinishedTime:n.ajaxData.responseFinishedTime})):(this.appInsights.trackAjax(n.ajaxData.id,n.ajaxData.getAbsoluteUrl(),n.ajaxData.getPathName(),n.ajaxData.ajaxTotalDuration,+n.ajaxData.status>=200&&+n.ajaxData.status<400,+n.ajaxData.status,n.ajaxData.method),n.ajaxData=null)},i.instrumentedByAppInsightsName="InstrumentedByAppInsights",i.DisabledPropertyName="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",i}();t.AjaxMonitor=i})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){var t=function(){function n(){}return n.prototype.getHashCodeScore=function(t){var i=this.getHashCode(t)/n.INT_MAX_VALUE;return i*100},n.prototype.getHashCode=function(t){var i,r;if(t=="")return 0;while(t.length100||t<0)&&(n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_SampleRateOutOfRange,"Sampling rate is out of range (0..100). Sampling will be disabled, you may be sending too much data which may affect your AI service level.",{samplingRate:t})),this.sampleRate=100);this.sampleRate=t;this.samplingScoreGenerator=new n.SamplingScoreGenerator}return t.prototype.isSampledIn=function(n){if(this.sampleRate==100)return!0;var t=this.samplingScoreGenerator.getSamplingScore(n);return tthis.config.sessionExpirationMs(),i=n-this.automaticSession.renewalDate>this.config.sessionRenewalMs();t||i?(this.automaticSession.isFirst=undefined,this.renew()):(this.automaticSession.renewalDate=+new Date,this.setCookie(this.automaticSession.id,this.automaticSession.acquisitionDate,this.automaticSession.renewalDate))},t.prototype.backup=function(){this.setStorage(this.automaticSession.id,this.automaticSession.acquisitionDate,this.automaticSession.renewalDate)},t.prototype.initializeAutomaticSession=function(){var t=n.Util.getCookie("ai_session"),i;t&&typeof t.split=="function"?this.initializeAutomaticSessionWithData(t):(i=n.Util.getStorage("ai_session"),i&&this.initializeAutomaticSessionWithData(i));this.automaticSession.id||(this.automaticSession.isFirst=!0,this.renew())},t.prototype.initializeAutomaticSessionWithData=function(t){var i=t.split("|"),r,u;i.length>0&&(this.automaticSession.id=i[0]);try{i.length>1&&(r=+i[1],this.automaticSession.acquisitionDate=+new Date(r),this.automaticSession.acquisitionDate=this.automaticSession.acquisitionDate>0?this.automaticSession.acquisitionDate:0);i.length>2&&(u=+i[2],this.automaticSession.renewalDate=+new Date(u),this.automaticSession.renewalDate=this.automaticSession.renewalDate>0?this.automaticSession.renewalDate:0)}catch(f){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_ErrorParsingAISessionCookie,"Error parsing ai_session cookie, session will be reset: "+n.Util.getExceptionName(f),{exception:n.Util.dump(f)}))}this.automaticSession.renewalDate==0&&n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_SessionRenewalDateIsZero,"AI session renewal date is 0, session will be reset."))},t.prototype.renew=function(){var t=+new Date;this.automaticSession.id=n.Util.newId();this.automaticSession.acquisitionDate=t;this.automaticSession.renewalDate=t;this.setCookie(this.automaticSession.id,this.automaticSession.acquisitionDate,this.automaticSession.renewalDate);n.Util.canUseLocalStorage()||n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_BrowserDoesNotSupportLocalStorage,"Browser does not support local storage. Session durations will be inaccurate."))},t.prototype.setCookie=function(t,i,r){var f=i+this.config.sessionExpirationMs(),e=r+this.config.sessionRenewalMs(),u=new Date,s=[t,i,r],o;f0&&(this.id=e[0]));this.config=i;this.id||(this.id=n.Util.newId(),u=new Date,o=n.Util.toISOStringForIE8(u),this.accountAcquisitionDate=o,u.setTime(u.getTime()+31536e6),h=[this.id,o],c=this.config.cookieDomain?this.config.cookieDomain():undefined,n.Util.setCookie(t.userCookieName,h.join(t.cookieSeparator)+";expires="+u.toUTCString(),c),n.Util.removeStorage("ai_session"));this.accountId=i.accountId?i.accountId():undefined;f=n.Util.getCookie(t.authUserCookieName);f&&(f=decodeURI(f),r=f.split(t.cookieSeparator),r[0]&&(this.authenticatedId=r[0]),r.length>1&&r[1]&&(this.accountId=r[1]))}return t.prototype.setAuthenticatedUserContext=function(i,r){var f=!this.validateUserInput(i)||r&&!this.validateUserInput(r),u;if(f){n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_SetAuthContextFailedAccountName,"Setting auth user context failed. User auth/account id should be of type string, and not contain commas, semi-colons, equal signs, spaces, or vertical-bars."));return}this.authenticatedId=i;u=this.authenticatedId;r&&(this.accountId=r,u=[this.authenticatedId,this.accountId].join(t.cookieSeparator));n.Util.setCookie(t.authUserCookieName,encodeURI(u),this.config.cookieDomain())},t.prototype.clearAuthenticatedUserContext=function(){this.authenticatedId=null;this.accountId=null;n.Util.deleteCookie(t.authUserCookieName)},t.prototype.validateUserInput=function(n){return typeof n!="string"||!n||n.match(/,|;|=| |\|/)?!1:!0},t.cookieSeparator="|",t.userCookieName="ai_user",t.authUserCookieName="ai_authUser",t}();t.User=i})(t=n.Context||(n.Context={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(){}return t.reset=function(){t.isEnabled()&&(n.Util.setSessionStorage(t.ITEMS_QUEUED_KEY,"0"),t.itemsRestoredFromSessionBuffer=0)},t.isEnabled=function(){return t.enabled&&t.appInsights!=null&&t.appInsights.context._sender._XMLHttpRequestSupported&&n.Util.canUseSessionStorage()},t.getIssuesReported=function(){return!t.isEnabled()||isNaN(+n.Util.getSessionStorage(t.ISSUES_REPORTED_KEY))?0:+n.Util.getSessionStorage(t.ISSUES_REPORTED_KEY)},t.incrementItemsQueued=function(){try{if(t.isEnabled()){var i=t.getNumberOfLostItems();++i;n.Util.setSessionStorage(t.ITEMS_QUEUED_KEY,i.toString())}}catch(r){}},t.decrementItemsQueued=function(i){try{if(t.isEnabled()){var r=t.getNumberOfLostItems();r-=i;r<0&&(r=0);n.Util.setSessionStorage(t.ITEMS_QUEUED_KEY,r.toString())}}catch(u){}},t.getNumberOfLostItems=function(){var i=0;try{t.isEnabled()&&(i=isNaN(+n.Util.getSessionStorage(t.ITEMS_QUEUED_KEY))?0:+n.Util.getSessionStorage(t.ITEMS_QUEUED_KEY))}catch(r){i=0}return i},t.reportLostItems=function(){var r,i;try{t.isEnabled()&&t.getIssuesReported()0&&(r=t.getNumberOfLostItems()-t.itemsRestoredFromSessionBuffer,t.appInsights.trackTrace('AI (Internal): Internal report DATALOSS:"'+r+'"',null),t.appInsights.flush(),i=t.getIssuesReported(),++i,n.Util.setSessionStorage(t.ISSUES_REPORTED_KEY,i.toString()))}catch(u){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_FailedToReportDataLoss,"Failed to report data loss: "+n.Util.getExceptionName(u),{exception:n.Util.dump(u)}))}finally{try{t.reset()}catch(u){}}},t.enabled=!1,t.itemsRestoredFromSessionBuffer=0,t.LIMIT_PER_SESSION=10,t.ITEMS_QUEUED_KEY="AI_itemsQueued",t.ISSUES_REPORTED_KEY="AI_lossIssuesReported",t}();n.DataLossAnalyzer=t})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var i=function(){function n(n){this._config=n;this._buffer=[]}return n.prototype.enqueue=function(n){this._buffer.push(n)},n.prototype.count=function(){return this._buffer.length},n.prototype.clear=function(){this._buffer.length=0},n.prototype.getItems=function(){return this._buffer.slice(0)},n.prototype.batchPayloads=function(n){return n&&n.length>0?this._config.emitLineDelimitedJson()?n.join("\n"):"["+n.join(",")+"]":null},n.prototype.markAsSent=function(){this.clear()},n.prototype.clearSent=function(){this.clear()},n}(),t;n.ArraySendBuffer=i;t=function(){function t(i){this._config=i;var r=this.getBuffer(t.BUFFER_KEY),u=this.getBuffer(t.SENT_BUFFER_KEY);this._buffer=r.concat(u);n.DataLossAnalyzer.itemsRestoredFromSessionBuffer=this._buffer.length;this.setBuffer(t.BUFFER_KEY,this._buffer);this.setBuffer(t.SENT_BUFFER_KEY,[])}return t.prototype.enqueue=function(n){this._buffer.push(n);this.setBuffer(t.BUFFER_KEY,this._buffer)},t.prototype.count=function(){return this._buffer.length},t.prototype.clear=function(){this._buffer.length=0;this.setBuffer(t.BUFFER_KEY,[]);this.setBuffer(t.SENT_BUFFER_KEY,[])},t.prototype.getItems=function(){return this._buffer.slice(0)},t.prototype.batchPayloads=function(n){return n&&n.length>0?this._config.emitLineDelimitedJson()?n.join("\n"):"["+n.join(",")+"]":null},t.prototype.markAsSent=function(n){var i=this.getBuffer(t.SENT_BUFFER_KEY);i=i.concat(n);this._buffer=this.removePayloadsFromBuffer(n,this._buffer);this.setBuffer(t.BUFFER_KEY,this._buffer);this.setBuffer(t.SENT_BUFFER_KEY,i)},t.prototype.clearSent=function(n){var i=this.getBuffer(t.SENT_BUFFER_KEY);i=this.removePayloadsFromBuffer(n,i);this.setBuffer(t.SENT_BUFFER_KEY,i)},t.prototype.removePayloadsFromBuffer=function(n,t){var u=[],i,r,f;for(i in t){r=!1;for(f in n)if(n[f]===t[i]){r=!0;break}r||u.push(t[i])}return u},t.prototype.getBuffer=function(t){var i,r;try{if(i=n.Util.getSessionStorage(t),i&&(r=JSON.parse(i),r))return r}catch(u){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_FailToRestoreStorageBuffer," storage key: "+t+", "+n.Util.getExceptionName(u),{exception:n.Util.dump(u)}))}return[]},t.prototype.setBuffer=function(t,i){try{var u=JSON.stringify(i);n.Util.setSessionStorage(t,u)}catch(r){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_FailToSetStorageBuffer," storage key: "+t+", "+n.Util.getExceptionName(r),{exception:n.Util.dump(r)}))}},t.BUFFER_KEY="AI_buffer",t.SENT_BUFFER_KEY="AI_sentBuffer",t}();n.SessionStorageSendBuffer=t})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(t){if(this._XMLHttpRequestSupported=!1,this._lastSend=0,this._config=t,this._sender=null,this._buffer=n.Util.canUseSessionStorage()&&this._config.enableSessionStorageBuffer()?new n.SessionStorageSendBuffer(t):new n.ArraySendBuffer(t),typeof XMLHttpRequest!="undefined"){var i=new XMLHttpRequest;"withCredentials"in i?(this._sender=this._xhrSender,this._XMLHttpRequestSupported=!0):typeof XDomainRequest!="undefined"&&(this._sender=this._xdrSender)}}return t.prototype.send=function(t){var i=this;try{if(this._config.disableTelemetry())return;if(!t){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_CannotSendEmptyTelemetry,"Cannot send empty telemetry"));return}if(!this._sender){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_SenderNotInitialized,"Sender was not initialized"));return}var r=n.Serializer.serialize(t),e=this._buffer.getItems(),u=this._buffer.batchPayloads(e);u&&u.length+r.length>this._config.maxBatchSizeInBytes()&&this.triggerSend();this._buffer.enqueue(r);this._timeoutHandle||(this._timeoutHandle=setTimeout(function(){i._timeoutHandle=null;i.triggerSend()},this._config.maxBatchInterval()));n.DataLossAnalyzer.incrementItemsQueued()}catch(f){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_FailedAddingTelemetryToBuffer,"Failed adding telemetry to the sender's buffer, some telemetry will be lost: "+n.Util.getExceptionName(f),{exception:n.Util.dump(f)}))}},t.prototype._getSizeInBytes=function(n){var r=0,t,i;if(n&&n.length)for(t=0;t0&&(r=this._buffer.getItems(),this._sender(r,i)),this._lastSend=+new Date);clearTimeout(this._timeoutHandle);this._timeoutHandle=null}catch(u){(!n.Util.getIEVersion()||n.Util.getIEVersion()>9)&&n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_TransmissionFailed,"Telemetry transmission failed, some telemetry will be lost: "+n.Util.getExceptionName(u),{exception:n.Util.dump(u)}))}},t.prototype._xhrSender=function(t,i){var u=this,r=new XMLHttpRequest,f;r[n.AjaxMonitor.DisabledPropertyName]=!0;r.open("POST",this._config.endpointUrl(),i);r.setRequestHeader("Content-type","application/json");r.onreadystatechange=function(){return u._xhrReadyStateChange(r,t,t.length)};r.onerror=function(n){return u._onError(t,r.responseText||r.response||"",n)};f=this._buffer.batchPayloads(t);r.send(f);this._buffer.markAsSent(t)},t.prototype._xdrSender=function(n){var i=this,t=new XDomainRequest,r;t.onload=function(){return i._xdrOnLoad(t,n)};t.onerror=function(r){return i._onError(n,t.responseText||"",r)};t.open("POST",this._config.endpointUrl());r=this._buffer.batchPayloads(n);t.send(r);this._buffer.markAsSent(n)},t.prototype._xhrReadyStateChange=function(n,t,i){n.readyState===4&&((n.status<200||n.status>=300)&&n.status!==0?this._onError(t,n.responseText||n.response||""):this._onSuccess(t,i))},t.prototype._xdrOnLoad=function(n,t){n&&(n.responseText+""=="200"||n.responseText==="")?this._onSuccess(t,0):this._onError(t,n&&n.responseText||"")},t.prototype._onError=function(t,i){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_OnError,"Failed to send telemetry.",{message:i}));this._buffer.clearSent(t)},t.prototype._onSuccess=function(t,i){n.DataLossAnalyzer.decrementItemsQueued(i);this._buffer.clearSent(t)},t}();n.Sender=t})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(){this.hashCodeGeneragor=new n.HashCodeScoreGenerator}return t.prototype.isEnabled=function(n,t){return this.hashCodeGeneragor.getHashCodeScore(n)=0&&(i=i.replace(/[^0-9a-zA-Z-._()\/ ]/g,"_"),n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_IllegalCharsInName,"name contains illegal characters. Illegal characters have been replaced with '_'.",{newName:i}))),i.length>t.MAX_NAME_LENGTH&&(i=i.substring(0,t.MAX_NAME_LENGTH),n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_NameTooLong,"name is too long. It has been truncated to "+t.MAX_NAME_LENGTH+" characters.",{name:i})))),i},t.sanitizeString=function(i){return i&&(i=n.Util.trim(i),i.toString().length>t.MAX_STRING_LENGTH&&(i=i.toString().substring(0,t.MAX_STRING_LENGTH),n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_StringValueTooLong,"string value is too long. It has been truncated to "+t.MAX_STRING_LENGTH+" characters.",{value:i})))),i},t.sanitizeUrl=function(i){return i&&(i=n.Util.trim(i),i.length>t.MAX_URL_LENGTH&&(i=i.substring(0,t.MAX_URL_LENGTH),n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_UrlTooLong,"url is too long, it has been trucated to "+t.MAX_URL_LENGTH+" characters.",{url:i})))),i},t.sanitizeMessage=function(i){return i&&i.length>t.MAX_MESSAGE_LENGTH&&(i=i.substring(0,t.MAX_MESSAGE_LENGTH),n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_MessageTruncated,"message is too long, it has been trucated to "+t.MAX_MESSAGE_LENGTH+" characters.",{message:i}))),i},t.sanitizeException=function(i){return i&&i.length>t.MAX_EXCEPTION_LENGTH&&(i=i.substring(0,t.MAX_EXCEPTION_LENGTH),n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.USRACT_ExceptionTruncated,"exception is too long, it has been trucated to "+t.MAX_EXCEPTION_LENGTH+" characters.",{exception:i}))),i},t.sanitizeProperties=function(n){var r,i,u;if(n){r={};for(i in n)u=t.sanitizeString(n[i]),i=t.sanitizeKeyAndAddUniqueness(i,r),r[i]=u;n=r}return n},t.sanitizeMeasurements=function(n){var r,i,u;if(n){r={};for(i in n)u=n[i],i=t.sanitizeKeyAndAddUniqueness(i,r),r[i]=u;n=r}return n},t.padNumber=function(n){var t="00"+n;return t.substr(t.length-3)},t.MAX_NAME_LENGTH=150,t.MAX_STRING_LENGTH=1024,t.MAX_URL_LENGTH=2048,t.MAX_MESSAGE_LENGTH=32768,t.MAX_EXCEPTION_LENGTH=32768,t}();t.DataSanitizer=i})(i=t.Common||(t.Common={}))})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(r,u){i.call(this);this.aiDataContract={ver:n.FieldType.Required,message:n.FieldType.Required,severityLevel:n.FieldType.Default,measurements:n.FieldType.Default,properties:n.FieldType.Default};r=r||n.Util.NotSpecified;this.message=t.Common.DataSanitizer.sanitizeMessage(r);this.properties=t.Common.DataSanitizer.sanitizeProperties(u)}return __extends(r,i),r.envelopeType="Microsoft.ApplicationInsights.{0}.Message",r.dataType="MessageData",r}(AI.MessageData);t.Trace=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.EventData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(t){function i(i,r,u){t.call(this);this.aiDataContract={ver:n.FieldType.Required,name:n.FieldType.Required,properties:n.FieldType.Default,measurements:n.FieldType.Default};this.name=n.Telemetry.Common.DataSanitizer.sanitizeString(i)||n.Util.NotSpecified;this.properties=n.Telemetry.Common.DataSanitizer.sanitizeProperties(r);this.measurements=n.Telemetry.Common.DataSanitizer.sanitizeMeasurements(u)}return __extends(i,t),i.envelopeType="Microsoft.ApplicationInsights.{0}.Event",i.dataType="EventData",i}(AI.EventData);t.Event=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(){function n(){this.hasFullStack=!0;this.parsedStack=[]}return n}();n.ExceptionDetails=t}(AI||(AI={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.exceptions=[];this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.ExceptionData=t}(AI||(AI={})),function(n){"use strict";var t=function(){function n(){}return n}();n.StackFrame=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var u=function(t){function i(i,u,f,e,o){t.call(this);this.aiDataContract={ver:n.FieldType.Required,handledAt:n.FieldType.Required,exceptions:n.FieldType.Required,severityLevel:n.FieldType.Default,properties:n.FieldType.Default,measurements:n.FieldType.Default};this.properties=n.Telemetry.Common.DataSanitizer.sanitizeProperties(f);this.measurements=n.Telemetry.Common.DataSanitizer.sanitizeMeasurements(e);this.handledAt=u||"unhandled";this.exceptions=[new r(i)];o&&(this.severityLevel=o)}return __extends(i,t),i.CreateSimpleException=function(n,t,i,r,u,f,e){return{handledAt:e||"unhandled",exceptions:[{hasFullStack:!0,message:n,stack:u,typeName:t,parsedStack:[{level:0,assembly:i,fileName:r,line:f,method:"unknown"}]}]}},i.envelopeType="Microsoft.ApplicationInsights.{0}.Exception",i.dataType="ExceptionData",i}(AI.ExceptionData),r,i;t.Exception=u;r=function(r){function u(i){r.call(this);this.aiDataContract={id:n.FieldType.Default,outerId:n.FieldType.Default,typeName:n.FieldType.Required,message:n.FieldType.Required,hasFullStack:n.FieldType.Default,stack:n.FieldType.Default,parsedStack:n.FieldType.Array};this.typeName=t.Common.DataSanitizer.sanitizeString(i.name)||n.Util.NotSpecified;this.message=t.Common.DataSanitizer.sanitizeMessage(i.message)||n.Util.NotSpecified;var u=i.stack;this.parsedStack=this.parseStack(u);this.stack=t.Common.DataSanitizer.sanitizeException(u);this.hasFullStack=n.Util.isArray(this.parsedStack)&&this.parsedStack.length>0}return __extends(u,r),u.prototype.parseStack=function(n){var t=undefined,e,l,o,r,a,s,h,p,w,b;if(typeof n=="string"){for(e=n.split("\n"),t=[],l=0,o=0,r=0;r<=e.length;r++)a=e[r],i.regex.test(a)&&(s=new i(e[r],l++),o+=s.sizeInBytes,t.push(s));if(h=32768,o>h)for(var u=0,f=t.length-1,v=0,c=u,y=f;uh){b=y-c+1;t.splice(c,b);break}c=u;y=f;u++;f--}}return t},u}(AI.ExceptionDetails);i=function(t){function i(r,u){t.call(this);this.sizeInBytes=0;this.aiDataContract={level:n.FieldType.Required,method:n.FieldType.Required,assembly:n.FieldType.Default,fileName:n.FieldType.Default,line:n.FieldType.Default};this.level=u;this.method="";this.assembly=n.Util.trim(r);var f=r.match(i.regex);f&&f.length>=5&&(this.method=n.Util.trim(f[2])||this.method,this.fileName=n.Util.trim(f[4]),this.line=parseInt(f[5])||0);this.sizeInBytes+=this.method.length;this.sizeInBytes+=this.fileName.length;this.sizeInBytes+=this.assembly.length;this.sizeInBytes+=i.baseSize;this.sizeInBytes+=this.level.toString().length;this.sizeInBytes+=this.line.toString().length}return __extends(i,t),i.regex=/^([\s]+at)?(.*?)(\@|\s\(|\s)([^\(\@\n]+):([0-9]+):([0-9]+)(\)?)$/,i.baseSize=58,i}(AI.StackFrame);t._StackFrame=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.metrics=[];this.properties={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.MetricData=t}(AI||(AI={})),function(n){"use strict";(function(n){n[n.Measurement=0]="Measurement";n[n.Aggregation=1]="Aggregation"})(n.DataPointType||(n.DataPointType={}));var t=n.DataPointType}(AI||(AI={})),function(n){"use strict";var t=function(){function t(){this.kind=n.DataPointType.Measurement}return t}();n.DataPoint=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){var i;(function(t){"use strict";var i=function(t){function i(){t.apply(this,arguments);this.aiDataContract={name:n.FieldType.Required,kind:n.FieldType.Default,value:n.FieldType.Required,count:n.FieldType.Default,min:n.FieldType.Default,max:n.FieldType.Default,stdDev:n.FieldType.Default}}return __extends(i,t),i}(AI.DataPoint);t.DataPoint=i})(i=t.Common||(t.Common={}))})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(t){var i;(function(i){"use strict";var r=function(r){function u(u,f,e,o,s,h){r.call(this);this.aiDataContract={ver:t.FieldType.Required,metrics:t.FieldType.Required,properties:t.FieldType.Default};var c=new n.ApplicationInsights.Telemetry.Common.DataPoint;c.count=e>0?e:undefined;c.max=isNaN(s)||s===null?undefined:s;c.min=isNaN(o)||o===null?undefined:o;c.name=i.Common.DataSanitizer.sanitizeString(u)||t.Util.NotSpecified;c.value=f;this.metrics=[c];this.properties=t.Telemetry.Common.DataSanitizer.sanitizeProperties(h)}return __extends(u,r),u.envelopeType="Microsoft.ApplicationInsights.{0}.Metric",u.dataType="MetricData",u}(AI.MetricData);i.Metric=r})(i=t.Telemetry||(t.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(n.EventData);n.PageViewData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(r,u,f,e,o){i.call(this);this.aiDataContract={ver:n.FieldType.Required,name:n.FieldType.Default,url:n.FieldType.Default,duration:n.FieldType.Default,properties:n.FieldType.Default,measurements:n.FieldType.Default};this.url=t.Common.DataSanitizer.sanitizeUrl(u);this.name=t.Common.DataSanitizer.sanitizeString(r)||n.Util.NotSpecified;isNaN(f)||(this.duration=n.Util.msToTimeSpan(f));this.properties=n.Telemetry.Common.DataSanitizer.sanitizeProperties(e);this.measurements=n.Telemetry.Common.DataSanitizer.sanitizeMeasurements(o)}return __extends(r,i),r.envelopeType="Microsoft.ApplicationInsights.{0}.Pageview",r.dataType="PageviewData",r}(AI.PageViewData);t.PageView=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(n.PageViewData);n.PageViewPerfData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(u,f,e,o,s){var h;if(i.call(this),this.aiDataContract={ver:n.FieldType.Required,name:n.FieldType.Default,url:n.FieldType.Default,duration:n.FieldType.Default,perfTotal:n.FieldType.Default,networkConnect:n.FieldType.Default,sentRequest:n.FieldType.Default,receivedResponse:n.FieldType.Default,domProcessing:n.FieldType.Default,properties:n.FieldType.Default,measurements:n.FieldType.Default},this.isValid=!1,h=r.getPerformanceTiming(),h){var c=r.getDuration(h.navigationStart,h.loadEventEnd),l=r.getDuration(h.navigationStart,h.connectEnd),a=r.getDuration(h.requestStart,h.responseStart),v=r.getDuration(h.responseStart,h.responseEnd),y=r.getDuration(h.responseEnd,h.loadEventEnd);c==0?n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.WARNING,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_ErrorPVCalc,"error calculating page view performance.",{total:c,network:l,request:a,response:v,dom:y})):c0&&n.navigationStart>0&&n.responseStart>0&&n.requestStart>0&&n.loadEventEnd>0&&n.responseEnd>0&&n.connectEnd>0&&n.domLoading>0},r.getDuration=function(n,t){var i=0;return isNaN(n)||isNaN(t)||(i=Math.max(t-n,0)),i},r.envelopeType="Microsoft.ApplicationInsights.{0}.PageviewPerformance",r.dataType="PageviewPerformanceData",r}(AI.PageViewPerfData);t.PageViewPerformance=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(){"use strict"})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){"use strict";var t=function(){function t(t){this._config=t;this._sender=new n.Sender(t);typeof window!="undefined"&&(this._sessionManager=new n.Context._SessionManager(t),this.application=new n.Context.Application,this.device=new n.Context.Device,this.internal=new n.Context.Internal,this.location=new n.Context.Location,this.user=new n.Context.User(t),this.operation=new n.Context.Operation,this.session=new n.Context.Session,this.sample=new n.Context.Sample(t.sampleRate()))}return t.prototype.addTelemetryInitializer=function(n){this.telemetryInitializers=this.telemetryInitializers||[];this.telemetryInitializers.push(n)},t.prototype.track=function(t){return t?(t.name===n.Telemetry.PageView.envelopeType&&n._InternalLogging.resetInternalMessageCount(),this.session&&typeof this.session.id!="string"&&this._sessionManager.update(),this._track(t)):n._InternalLogging.throwInternalUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.USRACT_TrackArgumentsNotSpecified,"cannot call .track() with a null or undefined argument")),t},t.prototype._track=function(t){var i,f,r,u,o;this.session&&(typeof this.session.id=="string"?this._applySessionContext(t,this.session):this._applySessionContext(t,this._sessionManager.automaticSession));this._applyApplicationContext(t,this.application);this._applyDeviceContext(t,this.device);this._applyInternalContext(t,this.internal);this._applyLocationContext(t,this.location);this._applySampleContext(t,this.sample);this._applyUserContext(t,this.user);this._applyOperationContext(t,this.operation);t.iKey=this._config.instrumentationKey();i=!1;try{for(this.telemetryInitializers=this.telemetryInitializers||[],f=this.telemetryInitializers.length,r=0;rl&&(clearInterval(a),s||(o.appInsights.sendPageViewInternal(i,r,l,u,f),o.appInsights.flush()))}catch(v){n._InternalLogging.throwInternalNonUserActionable(n.LoggingSeverity.CRITICAL,new n._InternalLogMessage(n._InternalMessageId.NONUSRACT_TrackPVFailedCalc,"trackPageView failed on page load calculation: "+n.Util.getExceptionName(v),{exception:n.Util.dump(v)}))}},100)},i}();t.PageViewManager=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(n){var t;(function(t){"use strict";var r=function(){function t(n){this.prevPageVisitDataKeyName="prevPageVisitData";this.pageVisitTimeTrackingHandler=n}return t.prototype.trackPreviousPageVisit=function(t,i){try{var r=this.restartPageVisitTimer(t,i);r&&this.pageVisitTimeTrackingHandler(r.pageName,r.pageUrl,r.pageVisitTime)}catch(u){n._InternalLogging.warnToConsole("Auto track page visit time failed, metric will not be collected: "+n.Util.dump(u))}},t.prototype.restartPageVisitTimer=function(t,i){try{var r=this.stopPageVisitTimer();return this.startPageVisitTimer(t,i),r}catch(u){return n._InternalLogging.warnToConsole("Call to restart failed: "+n.Util.dump(u)),null}},t.prototype.startPageVisitTimer=function(t,r){try{if(n.Util.canUseSessionStorage()){if(n.Util.getSessionStorage(this.prevPageVisitDataKeyName)!=null)throw new Error("Cannot call startPageVisit consecutively without first calling stopPageVisit");var u=new i(t,r),f=JSON.stringify(u);n.Util.setSessionStorage(this.prevPageVisitDataKeyName,f)}}catch(e){n._InternalLogging.warnToConsole("Call to start failed: "+n.Util.dump(e))}},t.prototype.stopPageVisitTimer=function(){var r,i,t;try{return n.Util.canUseSessionStorage()?(r=Date.now(),i=n.Util.getSessionStorage(this.prevPageVisitDataKeyName),i?(t=JSON.parse(i),t.pageVisitTime=r-t.pageVisitStartTime,n.Util.removeSessionStorage(this.prevPageVisitDataKeyName),t):null):null}catch(u){return n._InternalLogging.warnToConsole("Stop page visit timer failed: "+n.Util.dump(u)),null}},t}(),i;t.PageVisitTimeManager=r;i=function(){function n(n,t){this.pageVisitStartTime=Date.now();this.pageName=n;this.pageUrl=t}return n}();t.PageVisitData=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";(function(n){n[n.SQL=0]="SQL";n[n.Http=1]="Http";n[n.Other=2]="Other"})(n.DependencyKind||(n.DependencyKind={}));var t=n.DependencyKind}(AI||(AI={})),function(n){"use strict";(function(n){n[n.Undefined=0]="Undefined";n[n.Aic=1]="Aic";n[n.Apmc=2]="Apmc"})(n.DependencySourceType||(n.DependencySourceType={}));var t=n.DependencySourceType}(AI||(AI={})),function(n){"use strict";var t=function(t){function i(){t.call(this);this.ver=2;this.kind=n.DataPointType.Aggregation;this.dependencyKind=n.DependencyKind.Other;this.success=!0;this.dependencySource=n.DependencySourceType.Apmc;this.properties={};t.call(this)}return __extends(i,t),i}(Microsoft.Telemetry.Domain);n.RemoteDependencyData=t}(AI||(AI={})),function(n){var t;(function(n){var t;(function(t){"use strict";var i=function(i){function r(r,u,f,e,o,s,h){i.call(this);this.aiDataContract={id:n.FieldType.Required,ver:n.FieldType.Required,name:n.FieldType.Default,kind:n.FieldType.Required,value:n.FieldType.Default,count:n.FieldType.Default,min:n.FieldType.Default,max:n.FieldType.Default,stdDev:n.FieldType.Default,dependencyKind:n.FieldType.Default,success:n.FieldType.Default,async:n.FieldType.Default,dependencySource:n.FieldType.Default,commandName:n.FieldType.Default,dependencyTypeName:n.FieldType.Default,properties:n.FieldType.Default,resultCode:n.FieldType.Default};this.id=r;this.name=this.formatDependencyName(h,u);this.commandName=t.Common.DataSanitizer.sanitizeUrl(f);this.value=e;this.success=o;this.resultCode=s+"";this.dependencyKind=AI.DependencyKind.Http;this.dependencyTypeName="Ajax"}return __extends(r,i),r.prototype.formatDependencyName=function(n,t){return n?n.toUpperCase()+" "+t:t},r.envelopeType="Microsoft.ApplicationInsights.{0}.RemoteDependency",r.dataType="RemoteDependencyData",r}(AI.RemoteDependencyData);t.RemoteDependencyData=i})(t=n.Telemetry||(n.Telemetry={}))})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(){"use strict"})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(){"use strict"})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(t){"use strict";var r,i;t.Version="0.22.19";r=function(){function r(u){var f=this,e,o,h,s;if(this._trackAjaxAttempts=0,this.config=u||{},e=r.defaultConfig,e!==undefined)for(o in e)this.config[o]===undefined&&(this.config[o]=e[o]);t._InternalLogging.verboseLogging=function(){return f.config.verboseLogging};t._InternalLogging.enableDebugExceptions=function(){return f.config.enableDebug};h={instrumentationKey:function(){return f.config.instrumentationKey},accountId:function(){return f.config.accountId},sessionRenewalMs:function(){return f.config.sessionRenewalMs},sessionExpirationMs:function(){return f.config.sessionExpirationMs},endpointUrl:function(){return f.config.endpointUrl},emitLineDelimitedJson:function(){return f.config.emitLineDelimitedJson},maxBatchSizeInBytes:function(){return f.config.maxBatchSizeInBytes},maxBatchInterval:function(){return f.config.maxBatchInterval},disableTelemetry:function(){return f.config.disableTelemetry},sampleRate:function(){return f.config.samplingPercentage},cookieDomain:function(){return f.config.cookieDomain},enableSessionStorageBuffer:function(){return f.config.enableSessionStorageBuffer}};s=(new t.SplitTest).isEnabled(this.config.instrumentationKey,5);this.config.enableSessionStorageBuffer=s;this.context=new t.TelemetryContext(h);t.DataLossAnalyzer.appInsights=this;t.DataLossAnalyzer.enabled=s;t.DataLossAnalyzer.reportLostItems();this._pageViewManager=new n.ApplicationInsights.Telemetry.PageViewManager(this,this.config.overridePageViewDuration);this._eventTracking=new i("trackEvent");this._eventTracking.action=function(n,i,r,u,e){e?isNaN(e.duration)&&(e.duration=r):e={duration:r};var o=new t.Telemetry.Event(n,u,e),s=new t.Telemetry.Common.Data(t.Telemetry.Event.dataType,o),h=new t.Telemetry.Common.Envelope(s,t.Telemetry.Event.envelopeType);f.context.track(h)};this._pageTracking=new i("trackPageView");this._pageTracking.action=function(n,t,i,r,u){f.sendPageViewInternal(n,t,i,r,u)};this._pageVisitTimeManager=new t.Telemetry.PageVisitTimeManager(function(n,t,i){return f.trackPageVisitTime(n,t,i)});this.config.disableAjaxTracking||new n.ApplicationInsights.AjaxMonitor(this)}return r.prototype.sendPageViewInternal=function(n,i,r,u,f){var e=new t.Telemetry.PageView(n,i,r,u,f),o=new t.Telemetry.Common.Data(t.Telemetry.PageView.dataType,e),s=new t.Telemetry.Common.Envelope(o,t.Telemetry.PageView.envelopeType);this.context.track(s);this._trackAjaxAttempts=0},r.prototype.sendPageViewPerformanceInternal=function(n){var i=new t.Telemetry.Common.Data(t.Telemetry.PageViewPerformance.dataType,n),r=new t.Telemetry.Common.Envelope(i,t.Telemetry.PageViewPerformance.envelopeType);this.context.track(r)},r.prototype.startTrackPage=function(n){try{typeof n!="string"&&(n=window.document&&window.document.title||"");this._pageTracking.start(n)}catch(i){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_StartTrackFailed,"startTrackPage failed, page view may not be collected: "+t.Util.getExceptionName(i),{exception:t.Util.dump(i)}))}},r.prototype.stopTrackPage=function(n,i,r,u){try{typeof n!="string"&&(n=window.document&&window.document.title||"");typeof i!="string"&&(i=window.location&&window.location.href||"");this._pageTracking.stop(n,i,r,u);this.config.autoTrackPageVisitTime&&this._pageVisitTimeManager.trackPreviousPageVisit(n,i)}catch(f){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_StopTrackFailed,"stopTrackPage failed, page view will not be collected: "+t.Util.getExceptionName(f),{exception:t.Util.dump(f)}))}},r.prototype.trackPageView=function(n,i,r,u,f){try{this._pageViewManager.trackPageView(n,i,r,u,f);this.config.autoTrackPageVisitTime&&this._pageVisitTimeManager.trackPreviousPageVisit(n,i)}catch(e){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_TrackPVFailed,"trackPageView failed, page view will not be collected: "+t.Util.getExceptionName(e),{exception:t.Util.dump(e)}))}},r.prototype.startTrackEvent=function(n){try{this._eventTracking.start(n)}catch(i){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_StartTrackEventFailed,"startTrackEvent failed, event will not be collected: "+t.Util.getExceptionName(i),{exception:t.Util.dump(i)}))}},r.prototype.stopTrackEvent=function(n,i,r){try{this._eventTracking.stop(n,undefined,i,r)}catch(u){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_StopTrackEventFailed,"stopTrackEvent failed, event will not be collected: "+t.Util.getExceptionName(u),{exception:t.Util.dump(u)}))}},r.prototype.trackEvent=function(n,i,r){try{var f=new t.Telemetry.Event(n,i,r),e=new t.Telemetry.Common.Data(t.Telemetry.Event.dataType,f),o=new t.Telemetry.Common.Envelope(e,t.Telemetry.Event.envelopeType);this.context.track(o)}catch(u){t._InternalLogging.throwInternalNonUserActionable(t.LoggingSeverity.CRITICAL,new t._InternalLogMessage(t._InternalMessageId.NONUSRACT_TrackEventFailed,"trackEvent failed, event will not be collected: "+t.Util.getExceptionName(u),{exception:t.Util.dump(u)}))}},r.prototype.trackAjax=function(n,i,r,u,f,e,o){if(this.config.maxAjaxCallsPerView===-1||this._trackAjaxAttempts0?n.maxBatchSizeInBytes:1e6,n.maxBatchInterval=isNaN(n.maxBatchInterval)?15e3:n.maxBatchInterval,n.enableDebug=t.Util.stringToBoolOrDefault(n.enableDebug),n.disableExceptionTracking=n.disableExceptionTracking!==undefined&&n.disableExceptionTracking!==null?t.Util.stringToBoolOrDefault(n.disableExceptionTracking):!1,n.disableTelemetry=t.Util.stringToBoolOrDefault(n.disableTelemetry),n.verboseLogging=t.Util.stringToBoolOrDefault(n.verboseLogging),n.emitLineDelimitedJson=t.Util.stringToBoolOrDefault(n.emitLineDelimitedJson),n.diagnosticLogInterval=n.diagnosticLogInterval||1e4,n.autoTrackPageVisitTime=t.Util.stringToBoolOrDefault(n.autoTrackPageVisitTime),(isNaN(n.samplingPercentage)||n.samplingPercentage<=0||n.samplingPercentage>=100)&&(n.samplingPercentage=100),n.disableAjaxTracking=n.disableAjaxTracking!==undefined&&n.disableAjaxTracking!==null?t.Util.stringToBoolOrDefault(n.disableAjaxTracking):!1,n.maxAjaxCallsPerView=isNaN(n.maxAjaxCallsPerView)?500:n.maxAjaxCallsPerView,n.disableCorrelationHeaders=n.disableCorrelationHeaders!==undefined&&n.disableCorrelationHeaders!==null?t.Util.stringToBoolOrDefault(n.disableCorrelationHeaders):!0,n.disableFlushOnBeforeUnload=n.disableFlushOnBeforeUnload!==undefined&&n.disableFlushOnBeforeUnload!==null?t.Util.stringToBoolOrDefault(n.disableFlushOnBeforeUnload):!1,n.enableSessionStorageBuffer=n.enableSessionStorageBuffer!==undefined&&n.enableSessionStorageBuffer!==null?t.Util.stringToBoolOrDefault(n.enableSessionStorageBuffer):!1,n},i}();t.Initialization=i})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){var t;(function(){"use strict";var r,u;try{if(typeof window!="undefined"&&typeof JSON!="undefined")if(r="appInsights",window[r]===undefined)n.ApplicationInsights.AppInsights.defaultConfig=n.ApplicationInsights.Initialization.getDefaultConfig();else{var f=window[r]||{},t=new n.ApplicationInsights.Initialization(f),i=t.loadAppInsights();for(u in i)f[u]=i[u];t.emptyQueue();t.pollInteralLogs(i);t.addHousekeepingBeforeUnload(i)}}catch(e){n.ApplicationInsights._InternalLogging.warnToConsole("Failed to initialize AppInsights JS SDK: "+e.message)}})(t=n.ApplicationInsights||(n.ApplicationInsights={}))}(Microsoft||(Microsoft={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(n.PageViewData);n.AjaxCallData=t}(AI||(AI={})),function(n){"use strict";var t=function(n){function t(){n.call(this);this.ver=2;this.properties={};this.measurements={};n.call(this)}return __extends(t,n),t}(Microsoft.Telemetry.Domain);n.RequestData=t}(AI||(AI={})),function(n){"use strict";var t=function(t){function i(){t.call(this);this.ver=2;this.state=n.SessionState.Start;t.call(this)}return __extends(i,t),i}(Microsoft.Telemetry.Domain);n.SessionStateData=t}(AI||(AI={})),function(n){"use strict";(function(n){n[n.Pass=0]="Pass";n[n.Fail=1]="Fail"})(n.TestResult||(n.TestResult={}));var t=n.TestResult}(AI||(AI={})) \ No newline at end of file diff --git a/CSharp/capability-botToWeb/CancelPayFlow.png b/CSharp/capability-botToWeb/CancelPayFlow.png deleted file mode 100644 index 36fdc166a4..0000000000 Binary files a/CSharp/capability-botToWeb/CancelPayFlow.png and /dev/null differ diff --git a/CSharp/capability-botToWeb/CancelPayFlowPayPal.png b/CSharp/capability-botToWeb/CancelPayFlowPayPal.png deleted file mode 100644 index a14f0f1a51..0000000000 Binary files a/CSharp/capability-botToWeb/CancelPayFlowPayPal.png and /dev/null differ diff --git a/CSharp/capability-botToWeb/LICENSE b/CSharp/capability-botToWeb/LICENSE deleted file mode 100644 index a28827c2b8..0000000000 --- a/CSharp/capability-botToWeb/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Microsoft - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/CSharp/capability-botToWeb/PaypalBot.sln b/CSharp/capability-botToWeb/PaypalBot.sln deleted file mode 100644 index 3260f4952b..0000000000 --- a/CSharp/capability-botToWeb/PaypalBot.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bot", "Bot\Bot.csproj", "{A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - CodeAnalysis|Any CPU = CodeAnalysis|Any CPU - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A8BA1066-5695-4D71-ABB4-65E5A5E0C3D4}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/CSharp/capability-botToWeb/Readme.md b/CSharp/capability-botToWeb/Readme.md deleted file mode 100644 index 9ec4304c50..0000000000 --- a/CSharp/capability-botToWeb/Readme.md +++ /dev/null @@ -1,53 +0,0 @@ -# PayPal Bot Sample - -A sample bot that forwards the user to complete a PayPal payment and then resumes the conversation. This sample is a simple starting point for more complex PayPal transactions through bots. By redirecting to PayPal and resuming once done we ensure the bot does not handle the financial transaction itself and just facilitates it. - -### Prerequisites - -The minimum prerequisites to run this sample are: -* The latest update of Visual Studio 2015. You can download the community version [here](http://www.visualstudio.com) for free. -* The Bot Framework Emulator. To install the Bot Framework Emulator, download it from [here](https://emulator.botframework.com/). Please refer to [this documentation article](https://github.com/microsoft/botframework-emulator/wiki/Getting-Started) to know more about the Bot Framework Emulator. -* [A PayPal developer account](https://developer.paypal.com/) with: - * A test Business (Merchant) account to be the test seller account and - * A test Personal account to use as the test buyer making a payment. Make sure to include funds in the test Personal account when creating it so you can use those for the test payments. -* A [PayPal REST API app](https://developer.paypal.com/developer/applications) associated with the Business (Merchant) account mentioned above. You won't need a Webhook configured in this PayPal app. Take note of the Client ID, App ID, and Secret when creating the app. - -### Highlights - -The bot instructs the user to click a link to perform a payment on PayPal and points PayPal's completion Url back to a new Controller within the bot (`PaymentController`). - -When the request is sent to `PaymentController`, the bot resumes the conversation using a stored ResumptionCookie for the user on the channel where the payment flow was initiated. It pulls relevant information from the PayPal response to know whether or not payment was successful at PayPal before completing the payment. - -The code uses the [PayPal .NET SDK](https://www.nuget.org/packages/paypal). Before running: -* Update the **PayPal** section in `Web.config` with the values from the PayPal REST API app you created -* Update the **MS_WebHookReceiverSecret_PayPal** setting in the `appSettings` section with the same value as clientSecret from the **PayPal** section - -### Examples - -After starting a conversation with the bot, it'll ask the amount you want to pay. Once a numeric amount is provided, it'll build the link for the user to follow to complete the transaction on the PayPal website. - -#### Success Flow - -On the PayPal website if you log in with the test Personal account you created as part of the pre-requisites you'll be able to complete the payment: -![Success Pay Flow PayPal](SuccessPayFlowPayPal.png) - -And here is the conversation in the Bot Emulator for the successful transaction: -![Success Pay Flow Bot](SuccessPayFlow.png) - -#### Cancellation Flow - -On the PayPal website if the user decides to cancel the transaction it will not complete the payment: -![Cancellation Pay Flow PayPal](CancelPayFlowPayPal.png) - -And here is the conversation in the Bot Emulator for the cancelled transaction: -![Cancellation Pay Flow Bot](CancelPayFlow.png) - -### Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -### Copyright and license - -Code released under [the MIT license](LICENSE) diff --git a/CSharp/capability-botToWeb/SuccessPayFlow.png b/CSharp/capability-botToWeb/SuccessPayFlow.png deleted file mode 100644 index 4c67c66221..0000000000 Binary files a/CSharp/capability-botToWeb/SuccessPayFlow.png and /dev/null differ diff --git a/CSharp/capability-botToWeb/SuccessPayFlowPayPal.png b/CSharp/capability-botToWeb/SuccessPayFlowPayPal.png deleted file mode 100644 index 03a30019e8..0000000000 Binary files a/CSharp/capability-botToWeb/SuccessPayFlowPayPal.png and /dev/null differ diff --git a/Node/capability-botToWeb/2016-10-31-Payments-with-Bot-Framework.md b/Node/capability-botToWeb/2016-10-31-Payments-with-Bot-Framework.md deleted file mode 100644 index e4a24af4ff..0000000000 --- a/Node/capability-botToWeb/2016-10-31-Payments-with-Bot-Framework.md +++ /dev/null @@ -1,401 +0,0 @@ ---- -published: true -layout: post -title: "Integrating Payments with Bots" -author: "Bhargav Nookala" -author-link: "http://bhargavsbox.com" -author-image: "images/authorsthumbnail/BhargavNookala.jpg" -author-twitter: "http://twitter.com/bhargav" -image: "images/2016-10-31-Payments-with-Bot-Framework/title.png" -thumbnail: "images/2016-10-31-Payments-with-Bot-Framework/title_thumbnail.png" -date: 2016-10-31 10:00:00 -tags: bots Microsoft framework node SDK PayPal -color: "blue" -excerpt: "Integrating payment service providers with the Microsoft Bot Framework." -coderesource: "https://github.com/bnookala/node-paymentbot" -attributions: - - text: 'PayPal Payments API documentation' - url: 'https://developer.paypal.com/docs/api/payments/' - - text: 'PayPal Node SDK' - url: 'https://github.com/paypal/PayPal-node-SDK' - ---- - -# Background - -At a recent collaboration with a customer, we learned about a few integrations they had wanted to build for Bots running with the Microsoft Bot Framework. One such integration was with a payments service provider, like PayPal. We had created an example of this integration with the C# SDK for Bot Framework, but no such example existed for the Node SDK. As such, I'd like to demonstrate how straightforward it is to build a PayPal integration for bots made using Bot Framework's Node SDK. - -## Set up an application - -You will need to register the bot application with PayPal to generate the requisite keys to access the Paypal APIs. After logging into PayPal, [go to the developer center page to create an application](https://developer.paypal.com/developer/applications/create). Copy the **Client ID** and the **Client Secret** (the **Client Secret** will be hidden from you until you select 'Show' with your cursor). - -We additionally need to [create a test user](https://developer.paypal.com/developer/accounts/create) to use with the PayPal sandbox. When testing in the **sandbox** environment, you can use this test account, which doesn't require adding a credit card or funding the account. - -## Setup Node and grab the sample - -The following steps assume you have Node.js, npm, and a Bot Framework Emulator installed on your computer. To install Node and npm, visit [the Node download page](https://nodejs.org/en/download/) and select 'Current.' At the time of writing, the current iteration of Node is version 6.7.0, but any version that is 4.x or above should work. We do not recommend lower versions as the semantics of some keywords have changed between versions. - -The cross platform Bot Framework Emulator is [available to download here](https://docs.botframework.com/en-us/tools/bot-framework-emulator/). - -From here on, we'll reference and discuss the code available [on Github](https://github.com/bnookala/node-paymentbot). Using `git`, clone the repository onto your computer in your terminal of choice: `git clone https://github.com/bnookala/node-paymentbot`, `cd` into this directory and run `npm install` to download the module dependencies. - -## Running the sample - -1. `cd` into the `node-paymentbot` directory -2. `npm install` to install the module dependencies -3. Set the `PAYPAL_CLIENT_ID`, `PAYPAL_CLIENT_SECRET`, and `PAYPAL_CLIENT_MODE` environment variables in your terminal to the copied **Client ID** from PayPal, the copied **Client Secret** from PayPal, and **"sandbox"** respectively. You can optionally set the `PORT` environment variable to customize which port the application is bound to, but it will default to 3978. -4. run `node app.js`, note the URL that it writes the console, i.e., `restify listening to http://[::]:3978` -5. To configure the Bot Framework Emulator, start the emulator application, and enter the bot messaging endpoint. For a locally running bot it should be: `http://localhost:3978/api/messages` -6. Start interacting with the bot! - -# Building a payment flow from scratch - -PayPal offers many APIs and products for creating and executing payments between users and businesses. To keep our integration straightforward, we'll focus on one relatively simple flow, which involves user approval of payment before we're able to execute and receive a payment. The full flow is described [in PayPal's documentation](https://developer.paypal.com/docs/integration/web/accept-paypal-payment/) in detail, but we'll be using [PayPal's Node SDK](https://github.com/paypal/PayPal-node-SDK) to remove some of the boilerplate in creating and executing the payments. - - -## Integrating PayPal into a Bot - -To use the PayPal Node SDK, we must require it as a module, and configure it with the **Client ID** and **Client Secret** variables we generated from the PayPal dashboard earlier. PayPal also provides a sandbox environment for testing transactions. We'll use this environment here to test payments. In practice, when deploying to a production service, you'll likely want to use different credentials. One popular way to achieve this bucketed approach to deployment is through the underlying system's environment variables. This way, your code can be environment-agnostic, and you won't need to keep your **Client ID** and **Client Secret** variables in your code. When configured, the `paypal` module will be able to create and execute payments and transactions: - - - - -To set up our bot, we'll need to create an instance of a `ChatConnector` and an instance of a `UniversalBot`. We'll also need to create an HTTP server, for the `ChatConnector` instance to listen on. A `ChatConnector` allows our Bot to listen and respond on multiple types of messaging channels. Bot Framework currently supports numerous [popular messaging channels](https://docs.botframework.com/en-us/faq/#what-channels-does-the-bot-framework-currently-support), and is consistently adding more. We'll use the `UniversalBot` instance to define our bot's logic (i.e. how it should respond and react when a user performs an action): - - - - -This setup is great, but our bot doesn't do anything yet; we haven't defined any logic for it. Let's step back and define a use case for this bot: a city government charges a resident for their parking fine and the resident logs on to complete that payment. This example is straightforward enough that we can build it using a single dialog combined with a waterfalled conversation. For more background on dialogs and conversation, please [read the related section of the Bot Framework documentation](https://docs.botframework.com/en-us/node/builder/guides/core-concepts/#collecting-input). A stubbed out example is as follows: - - - - -Now, our bot will be able to respond to conversation. Let's test it in the bot framework emulator: - -![UI of Microsoft Bot Framework Channel Emulator. Bot tells user they have one outstanding fine for a parking fine violation, and asks 'what would you like to do?' with option to pay fine or cancel.]({{site.baseurl}}/images/2016-10-31-Payments-with-Bot-Framework/emulator.png) - -Our bot can now recognize that we want to pay our fine, but it does not yet know how to process that fine. [Line 24](https://gist.github.com/bnookala/a8c8c352e4c6180e822655fa311aa204#file-bot_dialog_stubbing-js-L24) of the above gist describes a "TODO": creating a payment and asking the user to approve it. This point is the first step in our two-step approval/execution flow for collecting payment from a user. Let's create a function, `createAndSendPayment`, that can create the payment using the PayPal Node SDK, and provide a link that the user can go to the approve the payment. We'll use the function `paypal.payment.create` that the Paypal Node SDK offers to create this payment. The first argument to this function is a JSON object, and the second is a callback that is executed upon success or failure. The schema of the JSON object defines the payment that the user will approve, and includes the name, description, amount, and URLs that PayPal will redirect to on approval or cancellation. The full schema of the JSON object that PayPal requires for payment creation is [described in their documentation](https://developer.paypal.com/docs/api/payments/#payment_create_request). The code as follows describes a function that builds our payment JSON, and one that takes this built JSON, creates a payment and asks the user to approve it: - - - - -The callback ([starting at Line 44](https://gist.github.com/bnookala/a8c8c352e4c6180e822655fa311aa204#file-payment_json_ex-js-L44-L59)) passed as the second parameter looks through the `payment` object received as an argument and searches for an `approval_url` property, which can be presented to the user. The user must visit this URL and approve the payment before we can continue and execute the payment. We use a Bot Framework built-in, `builder.Prompts.text`, to display the approval URL to the user. - -With the user having visited the URL and approved a payment, we must now execute the payment. To do that, we must create a `redirect_url` and provide that in the JSON object for payment creation. PayPal will then redirect our user to this endpoint, which will be hosted by us on the HTTP server we had set up earlier. Soon, we'll use this endpoint to perform the payment execution. Our code now has a endpoint ([lines 3 through 6](https://gist.github.com/bnookala/a8c8c352e4c6180e822655fa311aa204#file-redirect_ex-js-L3-L6)) that PayPal will redirect to: - - - - -To execute an approved payment, we use the `paypal.payment.execute` function provided by PayPal's Node SDK. This function takes three arguments: a payment ID, a JSON blob with [a few fields describing the payment to be executed](https://developer.paypal.com/docs/api/payments/#payment_execute_request), and a callback that is run on success or fail. When PayPal redirects to our endpoint, it modifies the query parameters of the redirect URL, adding a `paymentId` and a `PayerID`. These parameters must be used to execute the payment, with `paymentId` corresponding to the first argument of `paypal.payment.execute`, and `PayerID` corresponding to a field within the JSON blob: - - - - -We now have the full payment flow, except the very last step which involves informing the user (via the bot, and on the user's native messaging channel) that their payment has been successfully processed. Since we're no longer operating within the context of the bot, but rather within the context of the HTTP server, we'll have to get creative. - -We'll need to modify our code a bit and build up an `Address`, a Bot Framework model that identifies the channel and user with which a message is associated. These properties are all encoded on the `session.message` object normally, and can thus be re-encoded as query arguments in the `return_url` of the approval step. PayPal does not strip these parameters, so they get returned again when the user is redirected to the `approvalComplete` endpoint. When the payment is executed, we can pass these parameters along and create a message to be sent to the user, even in the context of the HTTP Server, without an active `session` object. - - - - -[Line 8](https://gist.github.com/bnookala/a8c8c352e4c6180e822655fa311aa204#file-redirect_bot_message_ex-js-L8) identifies the `Address` of the message to be encoded into the `return_url`. When the payment is executed, [lines 34-35](https://gist.github.com/bnookala/a8c8c352e4c6180e822655fa311aa204#file-redirect_bot_message_ex-js-L34-L35) pull these same encoded parameters out of the query string, and pass it along to a new function, `respondToUser`, which uses the address to build up a `builder.Message`. All messages that pass through the Bot Framework are represented internally through this model. Thus, we can create a response here, and send it along to our bot at [line 53](https://gist.github.com/bnookala/a8c8c352e4c6180e822655fa311aa204#file-redirect_bot_message_ex-js-L53). Our complete interaction now looks like this: - -![Animated GIF of complete interaction with Microsoft Bot Framework Channel Emulator and PayPal]({{site.baseurl}}/images/2016-10-31-Payments-with-Bot-Framework/complete_flow.gif) - - -## Conclusion - -The code highlighted above consists mostly of snippets and examples that intend to illustrate how we implemented payments with Bot Framework. A working code example is [available on GitHub](https://github.com/bnookala/node-paymentbot). - -Through this tutorial, I've identified a common third party service integration, PayPal, and integrated it with a Bot built on Bot Framework's Node SDK. I've also demonstrated that Bot Framework is a flexible tool for integrating conversation into your platform and can coexist with many popular existing integrations. diff --git a/Node/capability-botToWeb/LICENSE b/Node/capability-botToWeb/LICENSE deleted file mode 100644 index 32b2375ba4..0000000000 --- a/Node/capability-botToWeb/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Bhargav Nookala - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/Node/capability-botToWeb/README.md b/Node/capability-botToWeb/README.md deleted file mode 100644 index f2470f6073..0000000000 --- a/Node/capability-botToWeb/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# node-paymentbot - -![An animation that shows the paypal integration in use](complete_flow.gif) - -## Description - -A sample bot that demonstrates an integration between Bot Framework and PayPal - -## Setup - -1. Download and install a Bot Framework emulator, as this bot can be run locally: https://docs.botframework.com/en-us/tools/bot-framework-emulator/ - -2. Create a PayPal account, and then create an application. You can do that here: https://developer.paypal.com/developer/applications/create. -After creating the application, grab the **Client ID** and **Client Secret** from the application dashboard. These will be used to allow the bot to connect to PayPal. - -3. Create a PayPal sandbox test user here: https://developer.paypal.com/developer/accounts/. This is only needed if you use the PayPal "sandbox" environment to test payments. -You can change the environment PayPal will create payments on by changing the `PAYPAL_CLIENT_MODE` environment variable to "live". - -4. Export these environment variables: **PAYPAL_CLIENT_MODE**, **PAYPAL_CLIENT_ID**, **PAYPAL_CLIENT_SECRET**. - -5. Export bot credentials into environment variables: **MICROSOFT_APP_ID**, **MICROSOFT_APP_PASSWORD** (Get them from https://dev.botframework.com) - -For Mac OS/Linux: - -``` -export PAYPAL_CLIENT_MODE="sandbox" -PAYPAL_CLIENT_ID="YOUR CLIENT ID FROM PAYPAL" -PAYPAL_CLIENT_SECRET="YOUR CLIENT SECRET FROM PAYPAL" -MICROSOFT_APP_ID="YOUR BOT APP ID" -MICROSOFT_APP_PASSWORD="YOUT BOT APP PASSWORD" -``` - -For Windows using PowerShell: - -``` -$env:PAYPAL_CLIENT_MODE = "sandbox" -$env:PAYPAL_CLIENT_ID = "YOUR CLIENT ID FROM PAYPAL" -$env:PAYPAL_CLIENT_SECRET = "YOUR CLIENT SECRET FROM PAYPAL" -$env:MICROSOFT_APP_ID = "YOUR BOT APP ID" -$env:MICROSOFT_APP_PASSWORD = "YOUT BOT APP PASSWORD" -``` - -## Installation - -Assuming that you've installed a version of Node 6: - -1. `git clone http://github.com/bnookala/node-paymentbot` -2. `cd node-paymentbot` -3. `npm install` -4. `node app.js` -5. Start up the emulator, verify the 'Bot URL' field is the same as the URL written to your console by the application. -6. Done! :tada: - -## License -**MIT**. See LICENSE file. - -## Questions? -[Tweet at me!](https://twitter.com/bhargav) \ No newline at end of file diff --git a/Node/capability-botToWeb/app.js b/Node/capability-botToWeb/app.js deleted file mode 100644 index 0fbd379ffb..0000000000 --- a/Node/capability-botToWeb/app.js +++ /dev/null @@ -1,238 +0,0 @@ -'use strict'; - -// Node Requires -const url = require('url'); - -// Third party modules -const restify = require('restify'); -const builder = require('botbuilder'); -const paypal = require('paypal-rest-sdk'); - -// Configure the paypal module with a client id and client secret that you -// generate from https://developer.paypal.com/ -paypal.configure({ - 'mode': process.env.PAYPAL_CLIENT_MODE, - 'client_id': process.env.PAYPAL_CLIENT_ID, - 'client_secret': process.env.PAYPAL_CLIENT_SECRET -}); - -// A connector connects a bot on bot framework to various messaging services that a bot -// can talk to. -let connector = new builder.ChatConnector({ - appId: process.env.MICROSOFT_APP_ID, - appPassword: process.env.MICROSOFT_APP_PASSWORD -}); - -// A bot listens and reacts to messages that the connector picks up on. -let bot = new builder.UniversalBot(connector, function (session, args) { - session.beginDialog('listFines'); -}); - -// Simple two step dialog to list 'fines' that a user has received, and allow -// a user to 'pay' them. -bot.dialog('listFines', [ - function (session, args) { - console.log('List Fines Dialog'); - session.send('You have 1 outstanding fine:'); - - session.send('Parking Fine Violation'); - builder.Prompts.choice(session, "What would you like to do?", ["Pay fine", "Cancel"]); - }, - function (session, results, next) { - let choice = results.response; - - if (choice.entity === 'Cancel') { - return; - } - - // Starts the payment flow. - createAndSendPayment(session); - }, -]); - -// We're using restify here to set up an HTTP server, and create some callbacks that Paypal will hit. -let server = restify.createServer(); -server.use(restify.queryParser()); - -server.listen(process.env.PORT || process.env.port || 3978, function () { - console.log('%s listening to %s', server.name, server.url); -}); - -// This is a callback that Paypal hits when a user approves a transaction for completion. -server.get('approvalComplete', function (req, res, next) { - console.log('User approved transaction'); - executePayment(req.params); - res.end('Executing your transaction - you may close this browser tab.'); -}); - -// This is a callback that Paypal hits when a user cancels a transaction for completion. -server.get('cancelPayment', function (req, res, next) { - console.log('User cancelled transaction'); - cancelledPayment(req.params); - res.end('Canceling your transaction - you may close this browser tab.'); -}); - -// Messages are posted to this endpoint. We ask the connector to listen at this endpoint -// for new messages. -server.post('/api/messages', connector.listen()); - -/** - * This function creates and returns an object that is passed through to the PayPal Node SDK - * to create a payment that a user must manually approve. - * - * See https://developer.paypal.com/docs/api/payments/#payment_create_request for a description of * the fields. - */ -function createPaymentJson(returnUrl, cancelUrl) { - return { - "intent": "sale", - "payer": { - "payment_method": "paypal" - }, - "redirect_urls": { - "return_url": returnUrl, - "cancel_url": cancelUrl - }, - "transactions": [{ - "item_list": { - "items": [{ - "name": "Fine", - "sku": "ParkingFine", - "price": "1.00", - "currency": "USD", - "quantity": 1 - }] - }, - "amount": { - "currency": "USD", - "total": "1.00" - }, - "description": "This is your fine. Please pay it :3" - }] - }; -} - -/** - * This function creates and returns an object that is passed through to the PayPal Node SDK - * to execute an authorized payment. - * - * See https://developer.paypal.com/docs/api/payments/#payment_execute_request for a description of * the fields. - */ -function executePaymentJson(payerId) { - return { - "payer_id": payerId, - "transactions": [{ - "amount": { - "currency": "USD", - "total": "1.00" - } - }] - }; -} - -/** - * Generates a URL that Paypal will redirect to on approval or cancellation - * of the payment by the user. - */ -function createUrl(path, address) { - console.log('Creating URL for path: ' + path); - - // The address passed in is an Object that defines the context - // of the conversation - the user, the channel, the http endpoint the bot - // exists on, and so on. We encode this information into the return URL - // to be parsed out by our approval completion endpoint. - let addressEncoded = encodeURIComponent(JSON.stringify(address)); - - // This object encodes the endpoint that PayPal redirects to when - // a user approves the transaction. - let urlObject = { - protocol: 'http', - hostname: process.env.HOST || 'localhost', - port: process.env.PORT || process.env.port || 3978, - pathname: path, - query: { addressEncoded } - } - - return url.format(urlObject); -} - -/** - * Creates a payment on paypal that a user must approve. - */ -function createAndSendPayment(session) { - console.log('Creating Payment'); - - let returnUrl = createUrl('approvalComplete', session.message.address); - let cancelUrl = createUrl('cancelPayment', session.message.address); - let paymentJson = createPaymentJson(returnUrl, cancelUrl); - - paypal.payment.create(paymentJson, function (error, payment) { - if (error) { - console.log(error); - throw error; - } else { - // The SDK returns a payment object when the payment is successfully created. - // This object has a few properties, described at length here: - // https://developer.paypal.com/docs/api/payments/#payment_create_response - // We're looking for the 'approval_url' property, which the user must go to - // to approve the transaction before we can actively execute the transaction. - for (var index = 0; index < payment.links.length; index++) { - if (payment.links[index].rel === 'approval_url') { - session.send("Please pay your fine: " + payment.links[index].href); - } - } - } - }); -}; - -/** - * When a payment is approved by the user, we can go ahead and execute it. - */ -function executePayment(parameters) { - console.log('Executing an Approved Payment'); - - // Appended to the URL by PayPal during the approval step. - let paymentId = parameters.paymentId; - let payerId = parameters.PayerID; - - // Generate the sample payment execution JSON that paypal requires: - let paymentJson = executePaymentJson(payerId); - - // Grab the encoded address object, URL decode it, and parse it back into a JSON object. - let addressEncoded = decodeURIComponent(parameters.addressEncoded); - let address = JSON.parse(addressEncoded); - - // Finally, execute the payment, and tell the user that we got their payment. - paypal.payment.execute(paymentId, paymentJson, function (error, payment) { - if (error) { - console.log(error.response); - throw error; - } else { - console.log('Payment Executed Successfully'); - respondToUserSuccess(payment, address); - } - }); -} - -/** - * This function completes the payment dialog by creating a message, binding an address to it, - * and sending it. - */ -function respondToUserSuccess(payment, address) { - let message = new builder.Message().address(address).text('Thanks for your payment!'); - - bot.send(message.toMessage()); -} - -/** - * If a user chooses to cancel the payment (on the PayPal approval dialog), we should - * back via the bot. - */ -function cancelledPayment(parameters) { - console.log('Cancelled a payment'); - - let addressEncoded = decodeURIComponent(parameters.addressEncoded); - let address = JSON.parse(addressEncoded); - let message = new builder.Message().address(address).text('Cancelled your payment.'); - - bot.send(message.toMessage()); -} \ No newline at end of file diff --git a/Node/capability-botToWeb/complete_flow.gif b/Node/capability-botToWeb/complete_flow.gif deleted file mode 100644 index 20c9e2016e..0000000000 Binary files a/Node/capability-botToWeb/complete_flow.gif and /dev/null differ diff --git a/Node/capability-botToWeb/index.html b/Node/capability-botToWeb/index.html deleted file mode 100644 index c42c37a13b..0000000000 --- a/Node/capability-botToWeb/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/Node/capability-botToWeb/package.json b/Node/capability-botToWeb/package.json deleted file mode 100644 index 962040011a..0000000000 --- a/Node/capability-botToWeb/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "node-paymentbot", - "version": "1.0.0", - "description": "An example of a bot that pays people", - "main": "app.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/bnookala/node-paymentbot.git" - }, - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/bnookala/node-paymentbot/issues" - }, - "homepage": "https://github.com/bnookala/node-paymentbot#readme", - "dependencies": { - "botbuilder": "^3.7.0", - "paypal-rest-sdk": "^1.6.9", - "restify": "^4.1.1" - } -}