/// <summary>
 ///    Similar to System.String.Format, composes a new MulticulturalString object
 ///    based on a format string and inserts.
 /// </summary>
 /// <remarks>
 ///    If any of the inserts are MulticulturalString objects or IFormattable, then
 ///    those portions of the resulting MulticulturalString will also be rendered
 ///    in a culture-specific way.
 /// </remarks>
 public static MulticulturalString Format(MulticulturalString mcsFmt, params object[] inserts)
 {
     return(new MulticulturalString((ci) =>
     {
         string fmt = mcsFmt.ToCulture(ci);
         object[] cultureSpecificInserts = InsertsToCulture(inserts, ci);
         return String.Format(CultureInfo.CurrentCulture, fmt, cultureSpecificInserts);
     }));
 }
Example #2
0
        protected DbgProviderException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            if (null == info)
            {
                throw new ArgumentNullException("info");
            }

            ErrorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord));
            McsMessage  = (MulticulturalString)info.GetValue("McsMessage", typeof(MulticulturalString));
        }
 /// <summary>
 ///    Similar to System.String.Format, composes a new MulticulturalString object
 ///    based on a format string and inserts.
 /// </summary>
 /// <remarks>
 /// <para>
 ///    If any of the inserts are MulticulturalString objects or IFormattable, then
 ///    those portions of the resulting MulticulturalString will also be rendered
 ///    in a culture-specific way.
 /// </para>
 /// <para>
 ///    The IFormatProvider could be CultureInfo.CurrentCulture, or some other
 ///    settings that control how dates, numbers, currency, etc. are formatted,
 ///    regardless of the language the strings are in.
 /// </para>
 /// </remarks>
 public static MulticulturalString Format(IFormatProvider fmtProvider,
                                          MulticulturalString mcsFmt,
                                          params object[] inserts)
 {
     return(new MulticulturalString((ci) =>
     {
         string fmt = mcsFmt.ToCulture(ci);
         object[] cultureSpecificInserts = InsertsToCulture(inserts, ci);
         return String.Format(fmtProvider, fmt, cultureSpecificInserts);
     }));
 }
Example #4
0
 public override void WriteWarning(MulticulturalString warningText)
 {
     ThrowIfDisposed();
     LogManager.Trace("HoldingPipeline WARNING: {0}", warningText);
     m_q.Add((nextPipe) => nextPipe.WriteWarning(warningText));
 }
Example #5
0
 public void WriteError(MulticulturalString message, string errorId, ErrorCategory errorCategory, object targetObject)
 {
     WriteError(new DbgProviderException(message, errorId, errorCategory, targetObject));
 }
Example #6
0
 public abstract void WriteDebug(MulticulturalString debugText);
Example #7
0
 public static void Trace(MulticulturalString messageFmt, params object[] inserts)
 {
     Trace(Util.McSprintf(messageFmt, inserts));
 }
Example #8
0
 internal DbgProviderException(MulticulturalString mcsMessage, Exception inner, ErrorRecord er)
     : this(mcsMessage.ToString(), inner, er)
 {
     McsMessage = mcsMessage;
 }
Example #9
0
 internal DbgProviderException(MulticulturalString mcsMessage, string errorId, ErrorCategory ec, Exception inner)
     : this(mcsMessage, errorId, ec, inner, null)
 {
 }
        internal void WriteWarning(MulticulturalString warningText)
        {
            LogManager.Trace("{0} WriteWarning: {1}", ProviderId, warningText);

            WriteWarning(warningText, true);
        }
Example #11
0
        // Internal-only stuff:

        public override void WriteWarning(MulticulturalString warningText)
        {
            ThrowIfDisposed();
            LogManager.Trace("WriteWarning: {0}", warningText);
        }
Example #12
0
 public void WriteDebug(MulticulturalString debugTextFormat, params object[] inserts)
 {
     WriteDebug(Util.McSprintf(debugTextFormat, inserts));
 }
Example #13
0
 public void WriteVerbose(MulticulturalString verboseTextFormat, params object[] inserts)
 {
     WriteVerbose(Util.McSprintf(verboseTextFormat, inserts));
 }
Example #14
0
 public void WriteWarning(MulticulturalString warningTextFormat, params object[] inserts)
 {
     WriteWarning(Util.McSprintf(warningTextFormat, inserts));
 }
Example #15
0
        }         // end SaveLogFile()

        // If we make a copy of the trace file before closing the tracing session, the
        // file will be "unfinalized":
        //
        //     * The EndTime field in the header will be incorrect.
        //
        //     * The BuffersWritten field in the header will be incorrect.
        //
        //     * The file size will be the full, pre-allocated amount, even though likely
        //       only a small fraction of it is used.
        //
        // When processing such a trace file on Windows 7, the file will be detected as
        // corrupt. However, improvements in the ProcessTrace function in Win8 will allow
        // these problems to be tolerated. So, when saving a copy of the trace file, we
        // could require that a Win8 machine be used to analyze the trace file... or we
        // could just fix the file header and size.
        //
        // Technically, the structure of an .etl file is not documented, although the
        // constituent structures show up in header files (WMI_BUFFER_HEADER,
        // SYSTEM_TRACE_HEADER, TRACE_LOGFILE_HEADER). So it's possible this stuff could
        // change in Win9.
        private static void _FinalizeTraceFile(string traceFile)
        {
            // N.B. We assume the lock is held (to prevent anyone from tracing while we
            // finalize the copied trace file).
            try
            {
                int err = NativeMethods.ControlTrace(sm_traceHandle,
                                                     null,
                                                     sm_etp,
                                                     EventTraceControl.Query);
                if ((0 != err) && (ERROR_MORE_DATA != err))  // we don't need the additional data
                {
                    // N.B. Not using Util.Fail here, since Util.Fail traces.
                    Debug.Fail(Util.Sprintf("This call should not fail: {0}.", err));
                    throw new Win32Exception(err);
                }

                int cbTraceBufferSize = sm_etp.BufferSize * 1024;             // convert from KB to bytes
                int buffersWritten    = sm_etp.BuffersWritten;
                int cbMaxFileSize     = sm_etp.MaximumFileSize * 1024 * 1024; // convert from MB to bytes

                using (FileStream fileStream = Util.CreateFile(traceFile,
                                                               FileMode.Open,
                                                               FileAccess.ReadWrite,
                                                               FileShare.Read))
                {
                    if (fileStream.Length < 1024)
                    {
                        // Of course this is not a true program invariant (we don't
                        // control the file), but in practice it should never happen.
                        // N.B. Not using Util.Fail here, since Util.Fail traces.
                        Debug.Fail("should not happen");
                        // If the file is corrupt, we'll just leave it as-is. Maybe
                        // something can be salvaged.
                        Trace("Error: trace file \"{0}\" is impossibly short ({1} bytes).", traceFile, fileStream.Length);
                        return;
                    }

                    // I could define all the relevant structures that occur at the
                    // beginning of an .etl file (WMI_BUFFER_HEADER, SYSTEM_TRACE_HEADER,
                    // and TRACE_LOGFILE_HEADER), but I only need to poke two values and
                    // set the file size, so I'm just going to use offsets.

                    // Verify that the buffer size matches.
                    fileStream.Seek(NativeMethods.BytesBeforeTraceLogfileHeader, SeekOrigin.Begin);
                    // We do not dispose of reader because it would also dispose of the
                    // underlying stream, and we're not done with it yet.
                    BinaryReader reader      = new BinaryReader(fileStream);
                    int          fileBufSize = reader.ReadInt32();
                    if (fileBufSize != cbTraceBufferSize)
                    {
                        // Of course this is not a true program invariant (we don't
                        // control the file), but in practice it should never happen.
                        // N.B. Not using Util.Fail here, since Util.Fail traces.
                        Debug.Fail("should not happen");
                        // If the file is corrupt, we'll just leave it as-is. Maybe
                        // something can be salvaged.
                        Trace("Error: trace file \"{0}\" buffer size does not match ControlTrace output ({1} vs {2}).", traceFile, fileBufSize, cbTraceBufferSize);
                        return;
                    }

                    fileStream.Seek(NativeMethods.BytesBeforeTraceLogfileHeader +
                                    NativeMethods.OffsetOfTraceLogFileHeaderEndTime,
                                    SeekOrigin.Begin);
                    // We do not dispose of writer because it would also dispose of the
                    // underlying stream, and we're not done with it yet.
                    BinaryWriter writer = new BinaryWriter(fileStream);

                    // Not sure why they don't use UTC.
                    writer.Write(DateTime.Now.ToFileTime());

                    fileStream.Seek(NativeMethods.BytesBeforeTraceLogfileHeader +
                                    NativeMethods.OffsetOfTraceLogFileHeaderBuffersWritten,
                                    SeekOrigin.Begin);
                    writer.Write(buffersWritten);

                    fileStream.SetLength(Math.Min(buffersWritten * cbTraceBufferSize, cbMaxFileSize));
                } // end using( fileStream )
            }
            catch (Win32Exception w32e)
            {
                MulticulturalString mcsErrMsg = Util.McSprintf(Resources.ErrMsgTraceFailureFmt,
                                                               traceFile,
                                                               Util.GetExceptionMessages(w32e));
                Exception e2 = Util.TryConvertWin32ExceptionToIOException(w32e, mcsErrMsg);
                if (null != e2)
                {
                    throw e2;
                }
                else
                {
                    throw;
                }
            }
        } // end _FinalizeTraceFile()
Example #16
0
        private static void _StartTracing(EventProvider ep)
        {
            try
            {
                // N.B. Not using Util.Assert here, since Util.Assert traces.
                Debug.Assert(!String.IsNullOrEmpty(sm_logFile), "Must have a log file to start tracing.");
                sm_maxLogFileSizeMB = RegistryUtils.GetRegValue("MaxTraceFileSizeMB", 8, (v) => Math.Max(1, v));
                // If we are doing "low-priority" tracing, let's use a smaller file. And for
                // testing logging, we'll make it so we can wrap around a little quicker
                if (sm_useLowPriFile ||
                    !String.IsNullOrEmpty(Environment.GetEnvironmentVariable("_DBGSHELL_TEST_MIN_TRACE_FILE_SIZE")))
                {
                    sm_maxLogFileSizeMB = 1;
                }
                int    bufSizeKb  = 0;
                string bufSizeStr = Environment.GetEnvironmentVariable("_DBGSHELL_TEST_BUF_SIZE");
                if (!String.IsNullOrEmpty(bufSizeStr))
                {
                    if (Int32.TryParse(bufSizeStr, out bufSizeKb))
                    {
                        if (bufSizeKb < 0)
                        {
                            // N.B. Not using Util.Fail here, since Util.Fail traces.
                            Debug.Fail("need a value >= 0");
                            bufSizeKb = 0;
                        }
                    }
                }

                int    bufsPerProc    = 0;
                string bufsPerProcStr = Environment.GetEnvironmentVariable("_DBGSHELL_TEST_BUFS_PER_PROC");
                if (!String.IsNullOrEmpty(bufsPerProcStr))
                {
                    if (Int32.TryParse(bufsPerProcStr, out bufsPerProc))
                    {
                        if (bufsPerProc < 0)
                        {
                            // N.B. Not using Util.Fail here, since Util.Fail traces.
                            Debug.Fail("need a value >= 0");
                            bufsPerProc = 0;
                        }
                    }
                }

                sm_etp = new EventTraceProperties(DbgProviderEtwProviderGuid, sm_logFile, sm_maxLogFileSizeMB, bufSizeKb, bufsPerProc);

                int err = NativeMethods.StartTrace(out sm_traceHandle, "Microsoft.DbgProvider.TraceSession", sm_etp);
                if (0 != err)
                {
                    var e = new Win32Exception(err);
                    e.Data["sm_logFile"] = sm_logFile;
                    throw e;
                }

                Guid tmp = DbgProviderEtwProviderGuid;
                err = NativeMethods.EnableTraceEx2(sm_traceHandle,
                                                   ref tmp,
                                                   ControlCode.ENABLE_PROVIDER,
                                                   TraceLevel.Verbose,
                                                   0,  // matchAnyKeyword
                                                   0,  // matchAllKeyword
                                                   0,  // timeout, zero means trace async
                                                   IntPtr.Zero);
                if (0 != err)
                {
                    throw new Win32Exception(err);
                }

                FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
                lock (sm_syncRoot)
                    if (!sm_shuttingDown)
                    {
                        // Can't call Trace directly because this code is called in the code path that
                        // lazily initializes the sm_eventProvider field.
                        ep.WriteMessageEvent("==========================================================");
                        ep.WriteMessageEvent(Util.Sprintf("DbgProvider version {0}", fvi.FileVersion));
                        ep.WriteMessageEvent(Util.Sprintf("CurrentCulture/CurrentUICulture: {0} / {1}", CultureInfo.CurrentCulture.Name, CultureInfo.CurrentUICulture.Name));
                        ep.WriteMessageEvent(Util.Sprintf("Process ID: {0} (0x{0:x4})", NativeMethods.GetCurrentProcessId()));
                        ep.WriteMessageEvent(Util.Sprintf("Process command line: {0}", Environment.CommandLine));
                        ep.WriteMessageEvent(Util.Sprintf("User type: {0}, interactive: {1}",
                                                          _GetUserType(),
                                                          Environment.UserInteractive));
                        ep.WriteMessageEvent(Util.Sprintf("Current machine: {0}", Environment.MachineName));
                        Flush();
                    }
            }
            catch (Win32Exception w32e)
            {
                MulticulturalString mcsErrMsg = Util.McSprintf(Resources.ErrMsgTraceFailureFmt,
                                                               sm_logFile,
                                                               Util.GetExceptionMessages(w32e));
                Exception e2 = Util.TryConvertWin32ExceptionToIOException(w32e, mcsErrMsg);
                if (null != e2)
                {
                    throw e2;
                }
                else
                {
                    throw;
                }
            }
        } // end _StartTracing()
Example #17
0
 public override void WriteVerbose(MulticulturalString verboseText)
 {
     ThrowIfDisposed();
     LogManager.Trace("HoldingPipeline VERBOSE: {0}", verboseText);
     m_q.Add((nextPipe) => nextPipe.WriteVerbose(verboseText));
 }
Example #18
0
 public override void WriteDebug(MulticulturalString debugText)
 {
     ThrowIfDisposed();
     LogManager.Trace("HoldingPipeline DEBUG: {0}", debugText);
     m_q.Add((nextPipe) => nextPipe.WriteDebug(debugText));
 }
Example #19
0
 public override void WriteVerbose(MulticulturalString verboseText)
 {
     ThrowIfDisposed();
     LogManager.Trace("WriteVerbose: {0}", verboseText);
 }
        internal void WriteVerbose(MulticulturalString verboseText)
        {
            LogManager.Trace("{0} WriteVerbose: {1}", ProviderId, verboseText);

            WriteVerbose(verboseText, true);
        }
Example #21
0
 public override void WriteDebug(MulticulturalString debugText)
 {
     ThrowIfDisposed();
     LogManager.Trace("WriteDebug: {0}", debugText);
 }
Example #22
0
 internal DbgProviderException(MulticulturalString mcsMessage, string errorId, ErrorCategory ec, object targetObject)
     : this(mcsMessage.ToString(), errorId, ec, targetObject)
 {
     McsMessage = mcsMessage;
 }
Example #23
0
 public abstract void WriteVerbose(MulticulturalString verboseText);
Example #24
0
 public abstract void WriteWarning(MulticulturalString warningText);
Example #25
0
        } // end _WriteToEventProvider()

        public static void Trace(MulticulturalString message)
        {
            Trace(message.ToCulture(CultureInfo.InvariantCulture));
        }