Wednesday, June 6, 2012

SharePoint Unified Logging Service from JavaScript


<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test6.aspx.cs" Inherits="test.Layouts.test.test6"
    DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <%--http://msdn.microsoft.com/en-us/library/hh803115--%>
    <script src="/_layouts/LoggingSample/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        // Creates a custom ulslog object
        // with the required properties.
        function ulsObject() {
            this.message = null;
            this.file = null;
            this.line = null;
            this.client = null;
            this.stack = null;
            this.team = null;
            this.originalFile = null;
        }
        // Detecting the browser to create the client information
        // in the required format.
        function getClientInfo() {
            var browserName = '';
            if (jQuery.browser.msie)
                browserName = "Internet Explorer";
            else if (jQuery.browser.mozilla)
                browserName = "Firefox";
            else if (jQuery.browser.safari)
                browserName = "Safari";
            else if (jQuery.browser.opera)
                browserName = "Opera";
            else
                browserName = "Unknown";
            var browserVersion = jQuery.browser.version;
            var browserLanguage = navigator.language;
            if (browserLanguage == undefined) {
                browserLanguage = navigator.userLanguage;
            }
            var client = "<client><browser name='{0}' version='{1}'></browser><language>{2}</language></client>";
            client = String.format(client, browserName, browserVersion, browserLanguage);
            return client;
        }
        // Utility function to assist string formatting.
        String.format = function () {
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "gm");
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        }
        // Creates the callstack in the required format
        // using the caller function definition.
        function getCallStack(functionDef, depth) {
            if (functionDef != null) {
                var signature = '';
                functionDef = functionDef.toString();
                signature = functionDef.substring(0, functionDef.indexOf("{"));
                if (signature.indexOf("function") == 0) {
                    signature = signature.substring(8);
                }
                if (depth == 0) {
                    var stack = "<stack><function depth='0' signature='{0}'>{1}</function></stack>";
                    stack = String.format(stack, signature, functionDef);
                }
                else {
                    var stack = "<stack><function depth='1' signature='{0}'></function></stack>";
                    stack = String.format(stack, signature);
                }
                return stack;
            }
            return "";
        }
        // Creates the SOAP packet required by SendClientScriptErrorReport
        // web method.
        function generateErrorPacket(ulsObj) {
            var soapPacket = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                                       "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
                                       "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                          "<soap:Body>" +
                            "<SendClientScriptErrorReport " +
                              "xmlns=\"http://schemas.microsoft.com/sharepoint/diagnostics/\">" +
                              "<message>{0}</message>" +
                              "<file>{1}</file>" +
                              "<line>{2}</line>" +
                              "<stack>{3}</stack>" +
                              "<client>{4}</client>" +
                              "<team>{5}</team>" +
                              "<originalFile>{6}</originalFile>" +
                            "</SendClientScriptErrorReport>" +
                          "</soap:Body>" +
                        "</soap:Envelope>";

            soapPacket = String.format(soapPacket, encodeXmlString(ulsObj.message), encodeXmlString(ulsObj.file),
                 ulsObj.line, encodeXmlString(ulsObj.stack), encodeXmlString(ulsObj.client),
                 encodeXmlString(ulsObj.team), encodeXmlString(ulsObj.originalFile));
            return soapPacket;
        }
        // Utility function to encode special characters in XML.
        function encodeXmlString(txt) {
            txt = String(txt);
            txt = jQuery.trim(txt);
            txt = txt.replace(/&/g, "&amp;");
            txt = txt.replace(/</g, "&lt;");
            txt = txt.replace(/>/g, "&gt;");
            txt = txt.replace(/'/g, "&apos;");
            txt = txt.replace(/"/g, "&quot;");
            return txt;
        }
        // Function to form the Diagnostics service URL.
        function getWebSvcUrl() {
            var serverurl = location.href;
            if (serverurl.indexOf("?") != -1) {
                serverurl = serverurl.replace(location.search, '');
            }
            var index = serverurl.lastIndexOf("/");
            serverurl = serverurl.substring(0, index - 1);
            serverurl = serverurl.concat('/_vti_bin/diagnostics.asmx');
            return serverurl;
        }
        // Method to post the SOAP packet to the Diagnostic web service.
        function postMessageToULSSvc(soapPacket) {
            $(document).ready(function () {
                $.ajax({
                    url: getWebSvcUrl(),
                    type: "POST",
                    dataType: "xml",
                    data: soapPacket, //soap packet.
                    contentType: "text/xml; charset=\"utf-8\"",
                    success: handleResponse, // Invoke when the web service call is successful.
                    error: handleError// Invoke when the web service call fails.
                });
            });
        }
        // Invoked when the web service call succeeds.
        function handleResponse(data, textStatus, jqXHR) {
            // Custom code...
            alert('Successfully logged trace to ULS');
        }
        // Invoked when the web service call fails.
        function handleError(jqXHR, textStatus, errorThrown) {
            //Custom code...
            alert('Error occurred in executing the web request');
        }
        // Registering the ULS logging function on a global level.
        window.onerror = logErrorToULS;
        // Set default value for teamName.
        var teamName = "Custom SharePoint Application";
        // Further add the logErrorToULS method at the end of the script.
        // Function to log messages to Diagnostic web service.
        // Invoked by the window.onerror message.
        function logErrorToULS(msg, url, linenumber) {
            var ulsObj = new ulsObject();
            ulsObj.message = "Error occurred: " + msg;
            ulsObj.file = url.substring(url.lastIndexOf("/") + 1); // Get the current file name.
            ulsObj.line = linenumber;
            ulsObj.stack = getCallStack(logErrorToULS.caller); // Create error call stack.
            ulsObj.client = getClientInfo(); // Create client information.
            ulsObj.team = teamName; // Declared in the consumer script.
            ulsObj.originalFile = ulsObj.file;
            var soapPacket = generateErrorPacket(ulsObj); // Create the soap packet.
            postMessageToULSSvc(soapPacket); // Post to the web service.
            return true;
        }
        // Function to log message to Diagnostic web service.
        // Specifically invoked by a consumer method.
        function logMessageToULS(message, fileName) {
            if (message != null) {
                var ulsObj = new ulsObject();
                ulsObj.message = message;
                ulsObj.file = fileName;
                ulsObj.line = 0; // We don't know the line, so we set it to zero.
                ulsObj.stack = getCallStack(logMessageToULS.caller);
                ulsObj.client = getClientInfo();
                ulsObj.team = teamName;
                ulsObj.originalFile = ulsObj.file;
                var soapPacket = generateErrorPacket(ulsObj);
                postMessageToULSSvc(soapPacket);
            }
        }
    </script>
    <script type="text/javascript" language="javascript">
        var teamName = "Simple ULS Logging";
        function doWork() {
            unknownFunction();
            alert("unknownFunction");
        }
        function logMessage() {
            logMessageToULS('This is a trace message from CEWP', 'loggingsample.aspx');
            alert("logMessage");
        }
    </script>
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <asp:Button ID="btn1" runat="server" Text="Log Exception" OnClientClick="return doWork();" />
    <asp:Button ID="btn2" runat="server" Text="Log Trance" OnClientClick="return logMessage();" />
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Application Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea"
    runat="server">
    My Application Page
</asp:Content>

No comments:

Post a Comment

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   ...

Popular posts