示例#1
0
        public void ShouldAddListenerToExisting()
        {
            var source = Tracer.GetSourceFor<Foo>();

            var mock = new TextWriterTraceListener();

            Tracer.AddListener("System.Diagnostics", mock);

            // No other sources should have the listener
            Assert.AreEqual(0,
                (from ts in source.Sources
                 where ts.Name != "System.Diagnostics"
                 from ls in ts.Listeners.OfType<TraceListener>()
                 where ls == mock
                 select ts)
                 .Count());

            Assert.AreEqual(1,
                (from ts in source.Sources
                 where ts.Name == "System.Diagnostics"
                 from ls in ts.Listeners.OfType<TraceListener>()
                 where ls == mock
                 select ls)
                 .Count()
                 );
        }
示例#2
0
文件: test.cs 项目: mono/gert
	static int Main (string [] args)
	{
		if (args.Length != 1) {
			Console.WriteLine ("Please specify action.");
			return 1;
		}

		string basedir = AppDomain.CurrentDomain.BaseDirectory;
		string logfile = Path.Combine (basedir, "debug.log");

		switch (args [0]) {
		case "write":
			TextWriterTraceListener debugLog = new TextWriterTraceListener (logfile);
			Debug.AutoFlush = true;
			Debug.Listeners.Add (debugLog);
			Debug.Write ("OK");
			break;
		case "read":
			using (FileStream fs = new FileStream (Path.Combine (basedir, "debug.log"), FileMode.Open, FileAccess.Read, FileShare.Read)) {
				StreamReader sr = new StreamReader (fs, Encoding.Default, true);
#if ONLY_1_1 && !MONO
				Assert.AreEqual (string.Empty, sr.ReadToEnd (), "#1");
#else
				Assert.AreEqual ("OK", sr.ReadToEnd (), "#1");
#endif
				sr.Close ();
			}
			break;
		}

		return 0;
	}
示例#3
0
		static void Main( string[] args )
		{
			TextWriterTraceListener tr = new TextWriterTraceListener( System.Console.Out );
			Debug.Listeners.Add( tr ); Debug.AutoFlush = true; Debug.IndentSize = 3;
			ConsoleHelper.SetWindowPosition( 1, 10 );

			Console.WriteLine( "\n===== Press [Enter] to start the program..." ); Console.ReadLine();

			Console.WriteLine( "\n===== Registering types for the WCF machinery ..." );
			KTypesWCF.AddType( typeof( CalendarDate ) );
			KTypesWCF.AddType( typeof( ClockTime ) );

			Console.WriteLine( "\n===== Creating the Link object ..." );
			dynamic package = new DeepObject(); // Or use null if you don't need it
			package.Login = "******";
			package.Password = "******";
			package.NowDate = new CalendarDate( DateTime.Now );
			package.NowTime = new ClockTime( DateTime.Now );
			var endpoint = "Service_OnTcp_Endpoint"; // Use the endpoint on you App.config file
			var factory = new KFactorySQL(); // Use the appropriate factory
			var link = new KLinkWCF( factory, endpoint, package );

			Console.WriteLine( "\n== Executing your examples ..." );
			Test_Core.Dispatcher( link );

			Console.WriteLine( "\n== Press [Enter] to dispose the link ..." ); Console.ReadLine();
			link.Dispose();
			
			Console.WriteLine( "\n===== Press [Enter] to terminate program..." ); Console.ReadLine();
		}
 public void TestFlush()
 {
     using (var target = new TextWriterTraceListener(_stream))
     {
         target.Write(TestMessage);
         target.Flush();
     }
 }
        public void TestWrite()
        {
            using (var target = new TextWriterTraceListener(_stream))
            {
                target.Write(TestMessage);
            }

            Assert.Contains(TestMessage, File.ReadAllText(_fileName));
        }
        public void TestWriteAfterDisposeShouldNotThrow()
        {
            var target = new TextWriterTraceListener(_stream);
            target.Dispose();

            target.WriteLine(TestMessage);
            target.Write(TestMessage);
            target.Flush();
        }
示例#7
0
 public void TestConstructorWithStream()
 {
     string expectedName = string.Empty;
     using (var target = new TextWriterTraceListener(FileStream.Null))
     {
         Assert.Equal(expectedName, target.Name);
         Assert.NotNull(target.Writer);
     }
 }
示例#8
0
 public void TestDefaultConstructor()
 {
     string expectedName = string.Empty;
     using (var target = new TextWriterTraceListener())
     {
         Assert.Equal(expectedName, target.Name);
         Assert.Null(target.Writer);
     }
 }
示例#9
0
 public void TestConstructorWithTextWriter()
 {
     string expectedName = string.Empty;
     StreamWriter testWriter = StreamWriter.Null;
     using (var target = new TextWriterTraceListener(testWriter))
     {
         Assert.Equal(expectedName, target.Name);
         Assert.Same(testWriter, target.Writer);
     }
 }
        public void TestWriteLine()
        {
            using (var target = new TextWriterTraceListener(_stream))
            {
                target.WriteLine(TestMessage);
            }

            string expected = TestMessage + Environment.NewLine;
            Assert.Contains(expected, File.ReadAllText(_fileName));
        }
示例#11
0
	public static void Main()
	{
		var server = new WebSocketServer(20080);
		server.OnClientConnected += OnClientConnected;
		Console.WriteLine("Started.");
		var debug_out = new TextWriterTraceListener(Console.Out);
		Trace.Listeners.Add(debug_out);
		Debug.WriteLine("DEBUG");
		server.Run();
	}
示例#12
0
		static void Main( string[] args )
		{
			TextWriterTraceListener tr = new TextWriterTraceListener( System.Console.Out );
			Debug.Listeners.Add( tr ); Debug.AutoFlush = true; Debug.IndentSize = 3;
			ConsoleHelper.SetWindowPosition( 0, 80 );

			Console.WriteLine( "\n===== Press [Enter] to start the tests..." ); Console.ReadLine();
			Test_Direct_SQLServer();
			Console.WriteLine( "\n===== Press [Enter] to terminate program..." ); Console.ReadLine();
		}
 public void TestWriterPropery()
 {
     var testWriter = new StreamWriter(_stream);
     using (var target = new TextWriterTraceListener())
     {
         Assert.Null(target.Writer);
         target.Writer = testWriter;
         Assert.NotNull(target.Writer);
         Assert.Same(testWriter, target.Writer);
     }
 }
示例#14
0
    static void Main(string[] args)
    {
        //comment
        string sProdName = "Widget";
        int iUnitQty = 100;
        double dUnitCost = 1.03;
        Debug.WriteLine("Debug Information-Product Starting ");
        Debug.Indent();
        Debug.WriteLine("The product name is " + sProdName);
        Debug.WriteLine("The available units on hand are" + iUnitQty.ToString());
        Debug.WriteLine("The per unit cost is " + dUnitCost.ToString());

        System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();
        Debug.WriteLine(oxml);

        Debug.WriteLine("The product name is " + sProdName, "Field");
        Debug.WriteLine("The units on hand are" + iUnitQty, "Field");
        Debug.WriteLine("The per unit cost is" + dUnitCost.ToString(), "Field");
        Debug.WriteLine("Total Cost is  " + (iUnitQty * dUnitCost), "Calc");

        Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");
        Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");

        Debug.Assert(dUnitCost > 1, "Message will NOT appear");
        Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost  < 1 is false");

        TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
        Debug.Listeners.Add(tr1);

        TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
        Debug.Listeners.Add(tr2);

        Debug.WriteLine("The product name is " + sProdName);
        Debug.WriteLine("The available units on hand are" + iUnitQty);
        Debug.WriteLine("The per unit cost is " + dUnitCost);
        Debug.Unindent();
        Debug.WriteLine("Debug Information-Product Ending");
        Debug.Flush();

        Trace.WriteLine("Trace Information-Product Starting ");
        Trace.Indent();

        Trace.WriteLine("The product name is " + sProdName);
        Trace.WriteLine("The product name is" + sProdName, "Field");
        Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");
        Trace.Assert(dUnitCost > 1, "Message will NOT appear");

        Trace.Unindent();
        Trace.WriteLine("Trace Information-Product Ending");

        Trace.Flush();

        Console.ReadLine();
    }
 /// <summary>
 /// Redirects all log output to the provided text-writer
 /// </summary>
 public static void Open(TextWriter writer)
 {
     try
     {
         Close();
         _init = 1;
         _textWriter = writer;
         Trace.Listeners.Add(_traceWriter = new TextWriterTraceListener(_textWriter));
     }
     catch (Exception e)
     { Trace.WriteLine(e.ToString(), "CSharpTest.Net.QuickLog.Open()"); }
 }
示例#16
0
		static void Main( string[] args )
		{
			TextWriterTraceListener tr = new TextWriterTraceListener( System.Console.Out );
			Debug.Listeners.Add( tr ); Debug.AutoFlush = true; Debug.IndentSize = 3;
			ConsoleHelper.SetWindowPosition( 1, 32 * 12 + 30 );

			Console.WriteLine( "\n===== Press [Enter] to start the tests..." ); Console.ReadLine();

			Console.WriteLine( "\n===== Registering types for the WCF machinery ..." );
			KTypesWCF.AddType( typeof( CalendarDate ) );
			KTypesWCF.AddType( typeof( ClockTime ) );

			Console.WriteLine( "\n===== Starting the service host ..." );
			ServiceHost host = new ServiceHost( typeof( MyServer ) );
			host.Open();

			Console.WriteLine( "\n===== Press [Enter] to finish the service host ..." ); Console.ReadLine();
			try { host.Close( new TimeSpan( 0, 0, 5 ) ); }
			catch { host.Abort(); throw; }

			Console.WriteLine( "\n===== Press [Enter] to terminate program..." ); Console.ReadLine();
		}
示例#17
0
        public static void Main(string[] args)
        {
            // Create a Service Fabric Runtime
            using (FabricRuntime fabricRuntime = FabricRuntime.Create())
                using (TextWriterTraceListener trace = new TextWriterTraceListener(Path.Combine(FabricRuntime.GetActivationContext().LogDirectory, "out.log")))
                {
                    Trace.AutoFlush = true;
                    Trace.Listeners.Add(trace);

                    try
                    {
                        Trace.WriteLine("Starting Service Host for Pi Service.");

                        fabricRuntime.RegisterServiceType(Service.ServiceTypeName, typeof(Service));

                        Thread.Sleep(Timeout.Infinite);
                        GC.KeepAlive(fabricRuntime);
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(e.Message);
                    }
                }
        }
示例#18
0
        /// <summary>
        /// Truns on tracing.
        /// </summary>
        /// <param name="p_eifEnvironmentInfo">The application's envrionment info.</param>
        /// <param name="p_booForceTrace">Whether to force the trace file to be written.</param>
        private static void EnableTracing(IEnvironmentInfo p_eifEnvironmentInfo, bool p_booForceTrace)
        {
            Trace.AutoFlush = true;
            string strTraceFile = "TraceLog" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            TextWriterTraceListener ttlTraceFile = null;

            if (p_booForceTrace)
            {
                ttlTraceFile = new HeaderlessTextWriterTraceListener(Path.Combine(String.IsNullOrEmpty(p_eifEnvironmentInfo.Settings.TraceLogFolder) ? p_eifEnvironmentInfo.ApplicationPersonalDataFolderPath : p_eifEnvironmentInfo.Settings.TraceLogFolder, strTraceFile));
            }
            else
            {
                ttlTraceFile = new HeaderlessTextWriterTraceListener(new MemoryStream(), Path.Combine(String.IsNullOrEmpty(p_eifEnvironmentInfo.Settings.TraceLogFolder) ? p_eifEnvironmentInfo.ApplicationPersonalDataFolderPath : p_eifEnvironmentInfo.Settings.TraceLogFolder, strTraceFile));
            }
            ttlTraceFile.Name = "DefaultListener";
            Trace.Listeners.Add(ttlTraceFile);
            Trace.TraceInformation("Trace file has been created: " + strTraceFile);

            StringBuilder stbStatus = new StringBuilder();

            stbStatus.AppendFormat("Mod Manager Version: {0}{1}", Assembly.GetExecutingAssembly().GetName().Version, p_eifEnvironmentInfo.IsMonoMode ? "(mono)" : "").AppendLine();
            stbStatus.AppendFormat("OS version: {0}", Environment.OSVersion.ToString()).AppendLine();

            stbStatus.AppendLine("Installed .NET Versions:");
            RegistryKey rkyIinstalledVersions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");

            string[] strVersionNames = rkyIinstalledVersions.GetSubKeyNames();
            foreach (string strFrameworkVersion in strVersionNames)
            {
                string strSP = rkyIinstalledVersions.OpenSubKey(strFrameworkVersion).GetValue("SP", 0).ToString();
                stbStatus.AppendFormat("\t{0} SP {1}", strFrameworkVersion, strSP).AppendLine();
            }

            stbStatus.AppendFormat("Tracing is forced: {0}", p_booForceTrace).AppendLine();
            Trace.TraceInformation(stbStatus.ToString());
        }
示例#19
0
        static void Main(string[] args)
        {
            try
            {
                Trace.Listeners.Clear();
                TextWriterTraceListener twtl = new TextWriterTraceListener(Program.logName);
                twtl.Name = "TextLogger";
                twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;

                ConsoleTraceListener ctl = new ConsoleTraceListener(false);
                ctl.TraceOutputOptions = TraceOptions.DateTime;

                Trace.Listeners.Add(twtl);
                Trace.Listeners.Add(ctl);
                Trace.AutoFlush = true;


                ThreadStart clipboardThreadStart = new ThreadStart(BootClipboard);
                Thread      clipboardThread      = new Thread(clipboardThreadStart);
                clipboardThread.Start();
                HookProc callback     = CallbackFunction;
                var      module       = Process.GetCurrentProcess().MainModule.ModuleName;
                var      moduleHandle = GetModuleHandle(module);
                var      hook         = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, callback, moduleHandle, 0);

                while (true)
                {
                    PeekMessage(IntPtr.Zero, IntPtr.Zero, 0x100, 0x109, 0);
                    System.Threading.Thread.Sleep(5);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Exception: {0}", ex);
            }
        }
示例#20
0
        public static ClusterBuilder ConfigureLogging(ClusterBuilder builder)
        {
            var environmentVariable = Environment.GetEnvironmentVariable("MONGO_LOGGING");

            if (environmentVariable == null)
            {
                return(builder);
            }

            SourceLevels defaultLevel;

            if (!Enum.TryParse <SourceLevels>(environmentVariable, ignoreCase: true, result: out defaultLevel))
            {
                return(builder);
            }

            __traceSource = new TraceSource("mongodb-tests", defaultLevel);
            __traceSource.Listeners.Clear(); // remove the default listener
            var listener = new TextWriterTraceListener(Console.Out);

            listener.TraceOutputOptions = TraceOptions.DateTime;
            __traceSource.Listeners.Add(listener);
            return(builder.TraceWith(__traceSource));
        }
示例#21
0
        public void LogWarningZeroParams2()
        {
            // Arrange
            StringWriter            sw = null;
            StringBuilder           sb = new StringBuilder();
            TextWriterTraceListener stringTraceListener = null;

            // Act
            using (sw = new StringWriter(sb))
                using (stringTraceListener = new TextWriterTraceListener(sw))
                {
                    // Setup - add trace listener
                    Trace.Listeners.Add(stringTraceListener);

                    logger.LogWarning("Hello world");

                    // Clean up - remove trace listener
                    Trace.Listeners.Remove(stringTraceListener);
                }


            // Assert
            Assert.AreEqual("Warning|0|TraceLoggerTests|Hello world\r\n", sw.ToString());
        }
示例#22
0
        public void LogWarningWithParams1()
        {
            // Arrange
            StringWriter            sw = null;
            StringBuilder           sb = new StringBuilder();
            TextWriterTraceListener stringTraceListener = null;

            // Act
            using (sw = new StringWriter(sb))
                using (stringTraceListener = new TextWriterTraceListener(sw))
                {
                    // Setup - add trace listener
                    Trace.Listeners.Add(stringTraceListener);

                    logger.Log(LogLevel.Warning, "Hello world {0}", DateTime.MaxValue.ToString("s"));

                    // Clean up - remove trace listener
                    Trace.Listeners.Remove(stringTraceListener);
                }


            // Assert
            Assert.AreEqual("Warning|0|TraceLoggerTests|Hello world 9999-12-31T23:59:59\r\n", sw.ToString());
        }
示例#23
0
        private static void DateTimeTest2(
            string dateTimeFormat
            )
        {
#if !NET_STANDARD_20 && !NET_STANDARD_21
            TraceListener listener = new ConsoleTraceListener();
#else
            TraceListener listener = new TextWriterTraceListener(Console.Out);
#endif

            Trace.Listeners.Add(listener);
            Environment.SetEnvironmentVariable("SQLite_ForceLogPrepare", "1");

            if (dateTimeFormat != null)
            {
                Environment.SetEnvironmentVariable(
                    "AppendManifestToken_SQLiteProviderManifest",
                    String.Format(";DateTimeFormat={0};", dateTimeFormat));
            }

            using (northwindEFEntities db = new northwindEFEntities())
            {
                db.Orders.Where(i => i.OrderDate <
                                new DateTime(1997, 1, 1, 0, 0, 0, DateTimeKind.Local)).Count();
            }

            if (dateTimeFormat != null)
            {
                Environment.SetEnvironmentVariable(
                    "AppendManifestToken_SQLiteProviderManifest",
                    null);
            }

            Environment.SetEnvironmentVariable("SQLite_ForceLogPrepare", null);
            Trace.Listeners.Remove(listener);
        }
示例#24
0
        static void Main(string[] args)
        {
            using (new ExceptionRecorder("TreeHugger"))
            {
                string traceConfig  = ConfigurationManager.AppSettings["Trace"];
                bool   traceEnabled = true;

                if (!bool.TryParse(traceConfig, out traceEnabled) || traceEnabled)
                {
                    string traceFileName = Path.GetTempPath();
                    string timestamp     = DateTime.Now.ToString("s", CultureInfo.InvariantCulture).Replace(':', '.');
                    traceFileName = Path.Combine(traceFileName, "TreeHugger.Trace." + timestamp + ".txt");
                    TextWriterTraceListener listener = new TextWriterTraceListener(traceFileName);
                    Trace.Listeners.Add(listener);
                    Trace.AutoFlush = true;
                }

                Trace.WriteLine("Session started " + DateTime.Now.ToString());

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
        }
示例#25
0
        /// <summary>
        /// Initializes a new log
        /// </summary>
        /// <param name="appName">Name of the application</param>
        public static string Initialize(string appName)
        {
            if (!Convert.ToBoolean(Settings.Default.Trace, CultureInfo.InvariantCulture))
            {
                return(string.Empty);
            }

            // This is going in a "ThoughtWorks" folder under the directory that serves as a
            // common repository for application-specific data that is used by the current, non-roaming user.
            var dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) +
                      "\\ThoughtWorks\\";

            var di = new DirectoryInfo(dir);

            di.Create();

            FilePath = string.Format("{0}{1}{2}{3}", dir, (string.IsNullOrEmpty(appName) ? string.Empty : appName), DateTime.Now.Ticks, ".log");
            _fs      = new FileStream(FilePath, FileMode.Append);
            Log      = new TextWriterTraceListener(_fs);
            Trace.Listeners.Add(Log);
            Log.IndentSize = 4;
            Log.WriteLine(string.Format("{0}*** Log opened at {1} ***", FilePath, DateTime.Now.ToLongTimeString()));
            return(FilePath);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LogFileTraceListener" /> class.
 /// </summary>
 /// <param name="logfile">The logfile.</param>
 /// <remarks></remarks>
 public LogFileTraceListener(string logfile) : base(logfile)
 {
     listener = new TextWriterTraceListener(logfile);
 }
示例#27
0
 public MyTextWriterTraceListener(string Path, com.lokkju.iphonefs.DriveControlServer form)
 {
     Output = new TextWriterTraceListener(Path);
     Form   = form;
 }
示例#28
0
        public void LogExceptionToFile(Exception ex)
        {
            string logDirectory = LogPath + @"\" + DateTime.Today.ToString("yyyyMMdd");
            string filePath     = string.Empty;

            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
                filePath = logDirectory + @"\EXCEPTION.0.log";
            }
            else
            {
                string[] filePaths = Directory.GetFiles(logDirectory, "*.log");
                if (filePaths.Length == 0)
                {
                    filePath = logDirectory + @"\EXCEPTION.0.log";
                }
                else
                {
                    List <string> fileList = new List <string>();
                    foreach (string fPath in filePaths)
                    {
                        FileInfo file  = new FileInfo(fPath);
                        string[] parts = file.Name.Split('.');
                        if (parts[0].ToUpper() == LogFileType.EXCEPTION.ToString())
                        {
                            fileList.Add(fPath);
                        }
                    }

                    int    lastestIndex    = int.MinValue;
                    string lastestFilePath = "";
                    if (fileList.Count <= 0)
                    {
                        filePath = logDirectory + @"\EXCEPTION.0.log";
                    }
                    else
                    {
                        foreach (string fPath in fileList)
                        {
                            FileInfo file  = new FileInfo(fPath);
                            string[] parts = file.Name.Split('.'); //fPath.Split('.');
                            if (Convert.ToInt32(parts[1]) >= lastestIndex)
                            {
                                lastestIndex    = Convert.ToInt32(parts[1]);
                                lastestFilePath = fPath;
                            }
                        }
                        filePath = lastestFilePath;
                    }

                    if (File.Exists(filePath))
                    {
                        FileInfo lastestFile = new FileInfo(filePath);
                        // check if file size be larger than 5MB then create new one
                        if (((lastestFile.Length / 1024f) / 1024f) > 5)
                        {
                            lastestIndex++;
                            filePath = logDirectory + @"\" + LogFileType.EXCEPTION + "." + lastestIndex + ".log";
                        }
                    }
                }
            }

            string logMessage = string.Concat(new object[] { ex.Message, Environment.NewLine,
                                                             ex.Source, Environment.NewLine,
                                                             ex.StackTrace,
                                                             ex.TargetSite,
                                                             ex.InnerException });

            logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage;
            TextWriterTraceListener listener = new TextWriterTraceListener(filePath);

            listener.WriteLine(logMessage);
            listener.Flush();
            listener.Close();
        }
示例#29
0
        private static async void MainSequence()
        {
            //**init**
            _playerMoveSetsBuffer      = new Models.PlayersCurrentMoveDataModel();
            _playerMoveSetsBuffer.Blue = new List <Models.PlayersCurrentMoveDataModel.MoveSet>();
            _playerMoveSetsBuffer.Red  = new List <Models.PlayersCurrentMoveDataModel.MoveSet>();
            await HttpGet("http://bounce22.azurewebsites.net/home/clear");

            //**Patch debug into console**
            var writer = new TextWriterTraceListener(Console.Out);

            Debug.Listeners.Add(writer);

            //**get handle**
            AppHandle = FindWindow("SSFIVAE", "SSFIVAE");
            //IntPtr calculatorHandle = FindWindow("Notepad", "Untitled - Notepad");
            if (AppHandle == IntPtr.Zero)
            {
                Debug.WriteLine("Handle not found");
            }

            while (true)
            {
                string dataString = await HttpGet("http://bounce22.azurewebsites.net/home/");

                var responses = JsonConvert.DeserializeObject <List <String> >(dataString);
                if (dataString != "[]")
                {
                    await HttpGet("http://bounce22.azurewebsites.net/home/clear");

                    foreach (string response in responses)
                    {
                        var movesConverted = new Models.PlayersCurrentMoveDataModel.MoveSet();
                        movesConverted.Moves = new List <Models.PlayersCurrentMoveDataModel.MoveSet.Move>();
                        string[] moves = response.Split(',');
                        if (moves[0].ToLower().Contains("left"))
                        {
                            foreach (string move in moves)
                            {
                                try
                                {
                                    movesConverted.Moves.Add(
                                        new Models.PlayersCurrentMoveDataModel.MoveSet.Move
                                    {
                                        hasBeenExecuted = false,
                                        Keypresses      = new List <string>
                                        {
                                            KvPs.Blue[move.Trim().ToUpper()]
                                        }
                                    });
                                }
                                catch (Exception)
                                {
                                }
                            }
                            _playerMoveSetsBuffer.Blue.Add(movesConverted);
                        }
                        else
                        {
                            foreach (string move in moves)
                            {
                                try
                                {
                                    movesConverted.Moves.Add(
                                        new Models.PlayersCurrentMoveDataModel.MoveSet.Move
                                    {
                                        hasBeenExecuted = false,
                                        Keypresses      = new List <string>
                                        {
                                            KvPs.Red[move.Trim().ToUpper()]
                                        }
                                    });
                                }
                                catch (Exception)
                                {
                                }
                            }
                            _playerMoveSetsBuffer.Red.Add(movesConverted);
                        }
                    }
                }


                if (_playerMoveSetsBuffer.Blue.Count > MinResponses && _playerMoveSetsBuffer.Red.Count > MinResponses)
                {
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("**FIGHT**                    ");
                    var keypressBufferBlue   = new List <string>();
                    var keypressBufferRed    = new List <string>();
                    var keypressBufferMashed = new List <string>();

                    Models.PlayersCurrentMoveDataModel.MoveSet currentMoveSetBlue =
                        _playerMoveSetsBuffer.Blue.ElementAt(rnd.Next(1, _playerMoveSetsBuffer.Blue.Count()));
                    Models.PlayersCurrentMoveDataModel.MoveSet currentMoveSetRed =
                        _playerMoveSetsBuffer.Red.ElementAt(rnd.Next(1, _playerMoveSetsBuffer.Blue.Count()));
                    foreach (Models.PlayersCurrentMoveDataModel.MoveSet.Move Move in currentMoveSetBlue.Moves)
                    {
                        foreach (string key in Move.Keypresses)
                        {
                            keypressBufferBlue.Add(key);
                        }
                    }
                    foreach (Models.PlayersCurrentMoveDataModel.MoveSet.Move Move in currentMoveSetRed.Moves)
                    {
                        foreach (string key in Move.Keypresses)
                        {
                            keypressBufferRed.Add(key);
                        }
                    }
                    try
                    {
                        //who needs linq merges?

                        #region mash

                        keypressBufferMashed.Add(keypressBufferBlue[0]);
                        keypressBufferMashed.Add(keypressBufferRed[0]);
                        keypressBufferMashed.Add(keypressBufferBlue[1]);
                        keypressBufferMashed.Add(keypressBufferRed[1]);
                        keypressBufferMashed.Add(keypressBufferBlue[2]);
                        keypressBufferMashed.Add(keypressBufferRed[2]);
                        keypressBufferMashed.Add(keypressBufferBlue[3]);
                        keypressBufferMashed.Add(keypressBufferRed[3]);
                        keypressBufferMashed.Add(keypressBufferBlue[4]);
                        keypressBufferMashed.Add(keypressBufferRed[4]);
                        keypressBufferMashed.Add(keypressBufferBlue[5]);
                        keypressBufferMashed.Add(keypressBufferRed[5]);
                        keypressBufferMashed.Add(keypressBufferBlue[6]);
                        keypressBufferMashed.Add(keypressBufferRed[6]);
                        keypressBufferMashed.Add(keypressBufferBlue[7]);
                        keypressBufferMashed.Add(keypressBufferRed[7]);
                        keypressBufferMashed.Add(keypressBufferBlue[8]);
                        keypressBufferMashed.Add(keypressBufferRed[8]);
                        keypressBufferMashed.Add(keypressBufferBlue[9]);
                        keypressBufferMashed.Add(keypressBufferRed[9]);
                        keypressBufferMashed.Add(keypressBufferBlue[10]);
                        keypressBufferMashed.Add(keypressBufferRed[10]);
                        keypressBufferMashed.Add(keypressBufferBlue[11]);
                        keypressBufferMashed.Add(keypressBufferRed[11]);
                        keypressBufferMashed.Add(keypressBufferBlue[12]);
                        keypressBufferMashed.Add(keypressBufferRed[12]);
                        keypressBufferMashed.Add(keypressBufferBlue[13]);
                        keypressBufferMashed.Add(keypressBufferRed[13]);
                        keypressBufferMashed.Add(keypressBufferBlue[14]);
                        keypressBufferMashed.Add(keypressBufferRed[14]);
                        keypressBufferMashed.Add(keypressBufferBlue[15]);
                        keypressBufferMashed.Add(keypressBufferRed[15]);
                        keypressBufferMashed.Add(keypressBufferBlue[16]);
                        keypressBufferMashed.Add(keypressBufferRed[16]);
                        keypressBufferMashed.Add(keypressBufferBlue[17]);
                        keypressBufferMashed.Add(keypressBufferRed[17]);

                        #endregion
                    }
                    catch (Exception)
                    {
                    }
                    EnterKeys(keypressBufferMashed);
                    //_playerMoveSetsBuffer = new Models.PlayersCurrentMoveDataModel();
                    //_playerMoveSetsBuffer.Blue = new List<Models.PlayersCurrentMoveDataModel.MoveSet>();
                    //_playerMoveSetsBuffer.Red = new List<Models.PlayersCurrentMoveDataModel.MoveSet>();
                }
                else
                {
                    Console.SetCursorPosition(0, 0);
                    Console.WriteLine("**Response quota not met**");
                }
                Console.SetCursorPosition(0, 2);
                Console.WriteLine("Move Sequences in buffer:");
                Console.WriteLine("   LEFT: " + _playerMoveSetsBuffer.Blue.Count);
                Console.WriteLine("   RIGHT: " + _playerMoveSetsBuffer.Red.Count);
            }
        }
示例#30
0
        static void Main(string[] args)
        {
            Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Verbose;
            CassandraLogWriter      LogWriter = new CassandraLogWriter();
            TextWriterTraceListener twtl      = new TextWriterTraceListener(LogWriter);

            Trace.Listeners.Add(twtl);


            Console.WriteLine("Connecting, setting keyspace and creating Tables..");
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");

            Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1").Build();

            using (var session = cluster.Connect())
            {
                var keyspaceName = "test" + Guid.NewGuid().ToString("N");

                try
                {
                    session.ChangeKeyspace(keyspaceName);
                }
                catch (InvalidQueryException)
                {
                    session.CreateKeyspaceIfNotExists(keyspaceName);
                    session.ChangeKeyspace(keyspaceName);
                }

                LogWriter.GetContext(new CassandraLogContext(session));

                TwitterContext twitterContext = new TwitterContext(session);

                var TweetsTable         = twitterContext.GetTable <Tweet>();
                var AuthorsTable        = twitterContext.GetTable <Author>();
                var FollowedTweetsTable = twitterContext.GetTable <FollowedTweet>();
                var StatisticsTable     = twitterContext.GetTable <Statistics>();

                Console.WriteLine("Done!");

                //Adding authors and their followers to the Authors table:
                Console.WriteLine("Adding authors and their followers to the Authors table..");
                int               AuthorsNo       = 50;
                List <Author>     authorsLocal    = new List <Author>();
                List <Statistics> statisticsLocal = new List <Statistics>();
                List <string>     authorsID       = new List <string>();

                for (int i = 0; i < AuthorsNo; i++)
                {
                    var author_ID = "Author" + i.ToString();
                    var authorEnt = new Author()
                    {
                        author_id = author_ID, followers = authorsID.Where(aut => aut != author_ID).ToList()
                    };
                    AuthorsTable.AddNew(authorEnt);
                    AuthorsTable.EnableQueryTracing(authorEnt);
                    authorsLocal.Add(authorEnt);
                    authorsID.Add(authorEnt.author_id);

                    //We will also add current author to the Statistics table:
                    var statEnt = new Statistics()
                    {
                        author_id = author_ID
                    };
                    StatisticsTable.Attach(statEnt, EntityUpdateMode.ModifiedOnly, EntityTrackingMode.KeepAttachedAfterSave);

                    //And increment number of followers for current author, also in Statistics table:
                    authorEnt.followers.ForEach(folo => statEnt.followers_count += 1);
                    statisticsLocal.Add(statEnt);
                }
                twitterContext.SaveChanges(SaveChangesMode.Batch);
                var traces = AuthorsTable.RetriveAllQueryTraces();
                foreach (var trace in traces)
                {
                    Console.WriteLine("coordinator was {0}", trace.Coordinator);
                }
                Console.WriteLine("Done!");


                //Now every author will add a single tweet:
                Console.WriteLine("Now authors are writing their tweets..");
                List <Tweet>         tweetsLocal         = new List <Tweet>();
                List <FollowedTweet> followedTweetsLocal = new List <FollowedTweet>();
                foreach (var auth in authorsID)
                {
                    var tweetEnt = new Tweet()
                    {
                        tweet_id = Guid.NewGuid(), author_id = auth, body = "Hello world! My name is " + auth + (DateTime.Now.Second % 2 == 0 ? "." : ""), date = DateTimeOffset.Now
                    };
                    TweetsTable.AddNew(tweetEnt);
                    tweetsLocal.Add(tweetEnt);

                    //We will update our statistics table
                    statisticsLocal.First(stat => stat.author_id == auth).tweets_count += 1;

                    //We also have to add this tweet to "FollowedTweet" table, so every user who follows that author, will get this tweet on his/her own wall!
                    FollowedTweet followedTweetEnt = null;
                    Author        author           = AuthorsTable.FirstOrDefault(a => a.author_id == auth).Execute();
                    if (author != default(Author) && author.followers != null)
                    {
                        foreach (var follower in author.followers)
                        {
                            followedTweetEnt = new FollowedTweet()
                            {
                                user_id = follower, author_id = tweetEnt.author_id, body = tweetEnt.body, date = tweetEnt.date, tweet_id = tweetEnt.tweet_id
                            };
                            FollowedTweetsTable.AddNew(followedTweetEnt);
                            followedTweetsLocal.Add(followedTweetEnt);
                        }
                    }
                }
                twitterContext.SaveChanges(SaveChangesMode.Batch);
                Console.WriteLine("Done!");
                string separator = Environment.NewLine + "───────────────────────────────────────────────────────────────────────" + Environment.NewLine;

                Console.WriteLine(separator);

                //To display users that follows "Author8":
                Console.WriteLine("\"Author8\" is followed by:" + Environment.NewLine);
                try
                {
                    Author Author8 = AuthorsTable.First(aut => aut.author_id == "Author8").Execute();
                    Author8.displayFollowers();
                }
                catch (InvalidOperationException)
                {
                    Console.WriteLine("\"Author8\" does not exist in database!");
                }


                //To display all of user "Author15" tweets:
                Console.WriteLine(separator + "All tweets posted by Author15:" + Environment.NewLine);
                foreach (Tweet tweet in (from twt in TweetsTable where twt.author_id == "Author15" select twt).Execute())
                {
                    tweet.display();
                }


                //To display all tweets from users that "Author45" follows:
                string author_id = "Author45";
                Console.WriteLine(separator + string.Format("All tweets posted by users that \"{0}\" follows:", author_id) + Environment.NewLine);

                // At first we will check if specified above author_id is present in database:
                Author specifiedAuthor = (from aut in AuthorsTable where aut.author_id == author_id select aut).FirstOrDefault().Execute(); // it's another possible way of using First/FirstOrDefault method

                if (specifiedAuthor != default(Author))
                {
                    var followedTweets = (from t in FollowedTweetsTable where t.user_id == author_id select t).Execute().ToList();

                    if (followedTweets.Count() > 0)
                    {
                        foreach (var foloTwt in followedTweets)
                        {
                            foloTwt.display();
                        }
                    }
                    else
                    {
                        Console.WriteLine(string.Format("There is no tweets from users that {0} follows.", author_id));
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("Nothing to display because specified author: \"{0}\" does not exist!", author_id));
                }


                //Let's check all of authors punctuation in their tweets, or at least, if they end their tweets with full stop, exclamation or question mark:
                List <string> authorsWithPunctuationProblems = new List <string>();

                //To check it, we can use anonymous class because we are interested only in author_id and body of the tweet
                var slimmedTweets = (from twt in TweetsTable select new { twt.author_id, twt.body }).Execute();
                foreach (var slimTwt in slimmedTweets)
                {
                    if (!(slimTwt.body.EndsWith(".") || slimTwt.body.EndsWith("!") || slimTwt.body.EndsWith("?")))
                    {
                        if (!authorsWithPunctuationProblems.Contains(slimTwt.author_id))
                        {
                            authorsWithPunctuationProblems.Add(slimTwt.author_id);
                        }
                    }
                }


                // Now we can check how many of all authors have this problem..
                float proportion = (float)authorsWithPunctuationProblems.Count() / AuthorsTable.Count().Execute() * 100;
                Console.WriteLine(separator + string.Format("{0}% of all authors doesn't end tweet with punctuation mark!", proportion) + Environment.NewLine);

                if (authorsWithPunctuationProblems.Count > 0)
                {
                    // This time I will help them, and update these tweets with a full stop..
                    foreach (var tweet in TweetsTable.Where(x => authorsWithPunctuationProblems.Contains(x.author_id)).Execute())
                    {
                        TweetsTable.Attach(tweet);
                        tweetsLocal.Where(twt => twt.tweet_id == tweet.tweet_id).First().body += ".";
                        tweet.body += ".";
                    }
                    twitterContext.SaveChanges(SaveChangesMode.Batch);
                }

                //Statistics before deletion of tweets:
                Console.WriteLine(separator + "Before deletion of all tweets our \"Statistics\" table looks like:" + Environment.NewLine);
                StatisticsTable.DisplayTable();


                //Deleting all tweets from "Tweet" table
                foreach (var ent in tweetsLocal)
                {
                    TweetsTable.Delete(ent);

                    var statEnt = statisticsLocal.FirstOrDefault(auth => auth.author_id == ent.author_id);
                    if (statEnt != default(Statistics))
                    {
                        statEnt.tweets_count -= 1;
                    }
                }
                twitterContext.SaveChanges(SaveChangesMode.Batch);

                //Statistics after deletion of tweets:
                Console.WriteLine("After deletion of all tweets our \"Statistics\" table looks like:");
                StatisticsTable.DisplayTable();

                //Logs:
                Console.WriteLine(separator + "Number of received logs: " + LogWriter.LogsTable.Count().Execute());
                foreach (var log in LogWriter.LogsTable.Execute())
                {
                    log.display();
                }

                LogWriter.StopWritingToDB();

                Console.WriteLine(separator + "Deleting keyspace: \"" + keyspaceName + "\"");
                session.DeleteKeyspaceIfExists(keyspaceName);
            }
            Console.WriteLine("Done! Press any key to exit..");
            Console.ReadKey();
        }
示例#31
0
        private async void CompileClick(object sender, RoutedEventArgs e)
        {
            // Logger Setup
            string folder = "Compiler";

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            string logPath = Path.Combine(folder, "ScriptCompiler.log");

            using (var logStream = File.Create(logPath))
            {
                // Create the logger and the exception collector. They are used for debugging.
                var traceListener      = new TextWriterTraceListener(logStream);
                var logger             = new ScriptCompilerLogger(traceListener);
                var exceptionCollector = new ParsingExceptionCollector();
                logger.Information($"Attempting to compile: {_scriptFile.Name}, Time: {DateTime.Now}");
                try
                {
                    // Get the script file.
                    string hsc = txtScript.Text;

                    // Measure the time it took to compile the scripts.
                    var stopWatch = Stopwatch.StartNew();

                    // Compile the scripts.
                    ScriptData compileData = await Task.Run(() => CompileScripts(hsc, _progress, logger, exceptionCollector));

                    stopWatch.Stop();
                    var    timeSpan           = stopWatch.Elapsed;
                    string compilationMessage = $"The scripts were successfully compiled in {Math.Round(timeSpan.TotalSeconds, 3)} seconds.";
                    logger.Information(compilationMessage);

                    // Show the message box.
                    var saveResult = MetroMessageBox.Show("Scripts Compiled", compilationMessage
                                                          + "\nWARNING: This compiler is not 100% accurate and could corrupt the map in rare cases. Making a backup before proceeding is advisable."
                                                          + "\n\nDo you want to save the changes to the file?", MetroMessageBox.MessageBoxButtons.YesNo);
                    if (saveResult == MetroMessageBox.MessageBoxResult.Yes)
                    {
                        //TODO: Move this to its own function.
                        await Task.Run(() =>
                        {
                            using (IStream stream = _streamManager.OpenReadWrite())
                            {
                                _scriptFile.SaveScripts(compileData, stream, _progress);
                                _cashefile.SaveChanges(stream);
                            }
                        });

                        RefreshMeta();
                        StatusUpdater.Update("Scripts saved");
                    }
                }
                // Handle Parsing Errors.
                catch (OperationCanceledException opEx)
                {
                    if (exceptionCollector.ContainsExceptions)
                    {
                        HandleParsingErrors(opEx, exceptionCollector, logger);
                    }
                    else
                    {
                        MetroMessageBox.Show("Operation Canceled", opEx.Message);
                    }
                }
                // Handle Compiler Errors.
                catch (CompilerException compEx)
                {
                    HandleCompilerErrors(compEx, logger);
                }
                finally
                {
                    logger.Flush();
                    ResetProgressBar();
                }
            }
        }
示例#32
0
        private void InitializeXibo()
        {
            Thread.CurrentThread.Name = "UI Thread";

            // Default the XmdsConnection
            ApplicationSettings.Default.XmdsLastConnection = DateTime.MinValue;

            // Override the default size if necessary
            if (ApplicationSettings.Default.SizeX != 0)
            {
                _clientSize   = new Size((int)ApplicationSettings.Default.SizeX, (int)ApplicationSettings.Default.SizeY);
                Size          = _clientSize;
                WindowState   = FormWindowState.Normal;
                Location      = new Point((int)ApplicationSettings.Default.OffsetX, (int)ApplicationSettings.Default.OffsetY);
                StartPosition = FormStartPosition.Manual;
            }
            else
            {
                _clientSize = SystemInformation.PrimaryMonitorSize;
                ApplicationSettings.Default.SizeX = _clientSize.Width;
                ApplicationSettings.Default.SizeY = _clientSize.Height;
            }

            // Show in taskbar
            ShowInTaskbar = ApplicationSettings.Default.ShowInTaskbar;

            // Setup the proxy information
            OptionForm.SetGlobalProxy();

            _statLog = new StatLog();

            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
            this.Shown       += new EventHandler(MainForm_Shown);

            // Create the info form
            _clientInfoForm = new ClientInfo();
            _clientInfoForm.Hide();

            // Add a message filter to listen for the i key
            Application.AddMessageFilter(KeyStore.Instance);

            // Define the hotkey
            Keys key;

            try
            {
                key = (Keys)Enum.Parse(typeof(Keys), ApplicationSettings.Default.ClientInformationKeyCode.ToUpper());
            }
            catch
            {
                // Default back to I
                key = Keys.I;
            }

            KeyStore.Instance.AddKeyDefinition("ClientInfo", key, ((ApplicationSettings.Default.ClientInfomationCtrlKey) ? Keys.Control : Keys.None));

            // Register a handler for the key event
            KeyStore.Instance.KeyPress += Instance_KeyPress;

            // Trace listener for Client Info
            ClientInfoTraceListener clientInfoTraceListener = new ClientInfoTraceListener(_clientInfoForm);

            clientInfoTraceListener.Name = "ClientInfo TraceListener";
            Trace.Listeners.Add(clientInfoTraceListener);

            // Log to disk?
            if (!string.IsNullOrEmpty(ApplicationSettings.Default.LogToDiskLocation))
            {
                TextWriterTraceListener listener = new TextWriterTraceListener(ApplicationSettings.Default.LogToDiskLocation);
                Trace.Listeners.Add(listener);
            }

            Trace.WriteLine(new LogMessage("MainForm", "Client Initialised"), LogType.Info.ToString());
        }
示例#33
0
    public static void InitializeSiteCollection()
    {
#if DEBUG
        TestSiteCollUri = new Uri("http://spsites/sites/" + TestContext.Parameters["TestSiteCollectionName"]);
        return; // Uncommented when debugging LDAPCP code from unit tests
#endif

        logFileListener = new TextWriterTraceListener(TestContext.Parameters["TestLogFileName"]);
        Trace.Listeners.Add(logFileListener);
        Trace.AutoFlush = true;
        Trace.TraceInformation($"{DateTime.Now.ToString("s")} Start integration tests of {ClaimsProviderName} {FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(typeof(ldapcp.LDAPCP)).Location).FileVersion}.");
        Trace.WriteLine($"{DateTime.Now.ToString("s")} DataFile_AllAccounts_Search: {DataFile_AllAccounts_Search}");
        Trace.WriteLine($"{DateTime.Now.ToString("s")} DataFile_AllAccounts_Validate: {DataFile_AllAccounts_Validate}");
        Trace.WriteLine($"{DateTime.Now.ToString("s")} TestSiteCollectionName: {TestContext.Parameters["TestSiteCollectionName"]}");
        if (SPTrust == null)
        {
            Trace.TraceError($"{DateTime.Now.ToString("s")} SPTrust: is null");
        }
        else
        {
            Trace.WriteLine($"{DateTime.Now.ToString("s")} SPTrust: {SPTrust.Name}");
        }

        LDAPCPConfig config = LDAPCPConfig.GetConfiguration(UnitTestsHelper.ClaimsProviderConfigName, UnitTestsHelper.SPTrust.Name);
        if (config == null)
        {
            LDAPCPConfig.CreateConfiguration(ClaimsProviderConstants.CONFIG_ID, ClaimsProviderConstants.CONFIG_NAME, SPTrust.Name);
        }

        var service         = SPFarm.Local.Services.GetValue <SPWebService>(String.Empty);
        SPWebApplication wa = service.WebApplications.FirstOrDefault();
        if (wa != null)
        {
            Trace.WriteLine($"{DateTime.Now.ToString("s")} Web application {wa.Name} found.");
            SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
            string     encodedClaim         = claimMgr.EncodeClaim(TrustedGroup);
            SPUserInfo userInfo             = new SPUserInfo {
                LoginName = encodedClaim, Name = TrustedGroupToAdd_ClaimValue
            };

            // The root site may not exist, but it must be present for tests to run
            Uri rootWebAppUri = wa.GetResponseUri(0);
            if (!SPSite.Exists(rootWebAppUri))
            {
                Trace.WriteLine($"{DateTime.Now.ToString("s")} Creating root site collection {rootWebAppUri.AbsoluteUri}...");
                SPSite spSite = wa.Sites.Add(rootWebAppUri.AbsoluteUri, "root", "root", 1033, "STS#1", FarmAdmin, String.Empty, String.Empty);
                spSite.RootWeb.CreateDefaultAssociatedGroups(FarmAdmin, FarmAdmin, spSite.RootWeb.Title);

                SPGroup membersGroup = spSite.RootWeb.AssociatedMemberGroup;
                membersGroup.AddUser(userInfo.LoginName, userInfo.Email, userInfo.Name, userInfo.Notes);
                spSite.Dispose();
            }

            if (!Uri.TryCreate(rootWebAppUri, TestSiteRelativePath, out TestSiteCollUri))
            {
                Trace.TraceError($"{DateTime.Now.ToString("s")} Unable to generate Uri of test site collection from Web application Uri {rootWebAppUri.AbsolutePath} and relative path {TestSiteRelativePath}.");
            }

            if (!SPSite.Exists(TestSiteCollUri))
            {
                Trace.WriteLine($"{DateTime.Now.ToString("s")} Creating site collection {TestSiteCollUri.AbsoluteUri}...");
                SPSite spSite = wa.Sites.Add(TestSiteCollUri.AbsoluteUri, ClaimsProviderName, ClaimsProviderName, 1033, "STS#1", FarmAdmin, String.Empty, String.Empty);
                spSite.RootWeb.CreateDefaultAssociatedGroups(FarmAdmin, FarmAdmin, spSite.RootWeb.Title);

                SPGroup membersGroup = spSite.RootWeb.AssociatedMemberGroup;
                membersGroup.AddUser(userInfo.LoginName, userInfo.Email, userInfo.Name, userInfo.Notes);
                spSite.Dispose();
            }
            else
            {
                using (SPSite spSite = new SPSite(TestSiteCollUri.AbsoluteUri))
                {
                    SPGroup membersGroup = spSite.RootWeb.AssociatedMemberGroup;
                    membersGroup.AddUser(userInfo.LoginName, userInfo.Email, userInfo.Name, userInfo.Notes);
                }
            }
        }
        else
        {
            Trace.TraceError($"{DateTime.Now.ToString("s")} Web application was NOT found.");
        }
    }
        /// <summary>
        /// Adds the console, debugger, file, or host listener if requested.
        /// </summary>
        internal void AddTraceListenersToSources(Collection <PSTraceSource> matchingSources)
        {
            if (DebuggerListener)
            {
                if (_defaultListener == null)
                {
                    _defaultListener =
                        new DefaultTraceListener();

                    // Note, this is not meant to be localized.
                    _defaultListener.Name = "Debug";
                }

                AddListenerToSources(matchingSources, _defaultListener);
            }

            if (PSHostListener)
            {
                if (_hostListener == null)
                {
                    ((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue;
                    _hostListener = new PSHostTraceListener(this);

                    // Note, this is not meant to be localized.
                    _hostListener.Name = "Host";
                }

                AddListenerToSources(matchingSources, _hostListener);
            }

            if (FileListener != null)
            {
                if (_fileListeners == null)
                {
                    _fileListeners = new Collection <TextWriterTraceListener>();
                    FileStreams    = new Collection <FileStream>();

                    Exception error = null;

                    try
                    {
                        Collection <string> resolvedPaths = new Collection <string>();
                        try
                        {
                            // Resolve the file path
                            ProviderInfo provider = null;
                            resolvedPaths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(FileListener, out provider);

                            // We can only export aliases to the file system
                            if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
                            {
                                throw
                                    new PSNotSupportedException(
                                        StringUtil.Format(TraceCommandStrings.TraceFileOnly,
                                                          FileListener,
                                                          provider.FullName));
                            }
                        }
                        catch (ItemNotFoundException)
                        {
                            // Since the file wasn't found, just make a provider-qualified path out if it
                            // and use that.

                            PSDriveInfo  driveInfo = null;
                            ProviderInfo provider  = null;
                            string       path      =
                                this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                                    FileListener,
                                    new CmdletProviderContext(this.Context),
                                    out provider,
                                    out driveInfo);

                            // We can only export aliases to the file system
                            if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
                            {
                                throw
                                    new PSNotSupportedException(
                                        StringUtil.Format(TraceCommandStrings.TraceFileOnly,
                                                          FileListener,
                                                          provider.FullName));
                            }

                            resolvedPaths.Add(path);
                        }

                        if (resolvedPaths.Count > 1)
                        {
                            throw
                                new PSNotSupportedException(StringUtil.Format(TraceCommandStrings.TraceSingleFileOnly, FileListener));
                        }

                        string resolvedPath = resolvedPaths[0];

                        Exception fileOpenError = null;
                        try
                        {
                            if (ForceWrite && System.IO.File.Exists(resolvedPath))
                            {
                                // remove readonly attributes on the file
                                System.IO.FileInfo fInfo = new System.IO.FileInfo(resolvedPath);
                                if (fInfo != null)
                                {
                                    // Save some disk write time by checking whether file is readonly..
                                    if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                                    {
                                        // Make sure the file is not read only
                                        fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                                    }
                                }
                            }

                            // Trace commands always append..So there is no need to set overwrite with force..
                            FileStream fileStream = new FileStream(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                            FileStreams.Add(fileStream);

                            // Open the file stream

                            TextWriterTraceListener fileListener =
                                new TextWriterTraceListener(fileStream, resolvedPath);

                            fileListener.Name = FileListener;

                            _fileListeners.Add(fileListener);
                        }
                        catch (IOException ioException)
                        {
                            fileOpenError = ioException;
                        }
                        catch (SecurityException securityException)
                        {
                            fileOpenError = securityException;
                        }
                        catch (UnauthorizedAccessException unauthorized)
                        {
                            fileOpenError = unauthorized;
                        }

                        if (fileOpenError != null)
                        {
                            ErrorRecord errorRecord =
                                new ErrorRecord(
                                    fileOpenError,
                                    "FileListenerPathResolutionFailed",
                                    ErrorCategory.OpenError,
                                    resolvedPath);

                            WriteError(errorRecord);
                        }
                    }
                    catch (ProviderNotFoundException providerNotFound)
                    {
                        error = providerNotFound;
                    }
                    catch (System.Management.Automation.DriveNotFoundException driveNotFound)
                    {
                        error = driveNotFound;
                    }
                    catch (NotSupportedException notSupported)
                    {
                        error = notSupported;
                    }

                    if (error != null)
                    {
                        ErrorRecord errorRecord =
                            new ErrorRecord(
                                error,
                                "FileListenerPathResolutionFailed",
                                ErrorCategory.InvalidArgument,
                                FileListener);

                        WriteError(errorRecord);
                    }
                }

                foreach (TraceListener listener in _fileListeners)
                {
                    AddListenerToSources(matchingSources, listener);
                }
            }
        }
示例#35
0
        public static void Main(string[] args)
        {
            string sProdName = "Widget";
            int    iUnitQty  = 100;
            double dUnitCost = 1.03;

            Debug.WriteLine("Debug Information-Product Starting ");
            Debug.Indent();
            Debug.WriteLine("The product name is " + sProdName);
            Debug.WriteLine("The available units on hand are" + iUnitQty.ToString());
            Debug.WriteLine("The per unit cost is " + dUnitCost.ToString());

            System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();
            Debug.WriteLine(oxml);

            Debug.WriteLine("The product name is " + sProdName, "Field");
            Debug.WriteLine("The units on hand are" + iUnitQty, "Field");
            Debug.WriteLine("The per unit cost is" + dUnitCost.ToString(), "Field");
            Debug.WriteLine("Total Cost is  " + (iUnitQty * dUnitCost), "Calc");

            Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");
            Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");

            Debug.Assert(dUnitCost > 1, "Message will NOT appear");
            Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost  < 1 is false");

            var tr1 = new TextWriterTraceListener(Console.Out);

            Debug.Listeners.Add(tr1);

            var tr2 = new TextWriterTraceListener(File.CreateText("Output.txt"));

            Debug.Listeners.Add(tr2);


            Debug.WriteLine("The product name is " + sProdName);
            Debug.WriteLine("The available units on hand are" + iUnitQty);
            Debug.WriteLine("The per unit cost is " + dUnitCost);
            Debug.Unindent();
            Debug.WriteLine("Debug Information-Product Ending");
            Debug.Flush();

            Trace.WriteLine("Trace Information-Product Starting ");
            Trace.Indent();

            Trace.WriteLine("The product name is " + sProdName);
            Trace.WriteLine("The product name is" + sProdName, "Field");
            Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");
            Trace.Assert(dUnitCost > 1, "Message will NOT appear");


            Trace.WriteLine("Trace Information-Product Ending");

            Trace.Flush();

            Console.ReadLine();

            /*
             *  You can use the Trace and the Debug classes separately or together in the same application.
             *  In a Debug Solution Configuration project, both Trace and Debug output are active.
             *  The project generates output from both of these classes to all Listener objects. However,
             *  a Release Solution Configuration project only generates output from a Trace class.
             *  The Release Solution Configuration project ignores any Debug class method invocations.
             */
        }
 /// <summary>
 /// Allows you to close/open the writer
 /// </summary>
 public static void Close()
 {
     if (_traceWriter != null)
     {
         try
         {
             Trace.Listeners.Remove(_traceWriter);
             _traceWriter.Dispose();
         }
         catch { }
         finally
         {
             _textWriter = null;
             _traceWriter = null;
         }
     }
 }
示例#37
0
        public void ShouldRemoveListenerFromExisting()
        {
            var mock = new TextWriterTraceListener();

            Tracer.AddListener("System.Diagnostics", mock);

            // Creation happens after adding now.
            var source = Tracer.GetSourceFor<Foo>();

            var count = (from ts in source.Sources
                         where ts.Name == "System.Diagnostics"
                         from ls in ts.Listeners.OfType<TraceListener>()
                         where ls == mock
                         select ls)
                 .Count();

            // No other sources should have the listener
            Assert.AreEqual(1,
                (from ts in source.Sources
                 where ts.Name == "System.Diagnostics"
                 from ls in ts.Listeners.OfType<TraceListener>()
                 where ls == mock
                 select ls)
                 .Count()
                 );

            Tracer.RemoveListener("System.Diagnostics", mock);

            // No one should have the listener
            Assert.AreEqual(0,
                (from ts in source.Sources
                 where ts.Name == "System.Diagnostics"
                 from ls in ts.Listeners.OfType<TraceListener>()
                 where ls == mock
                 select ls)
                 .Count()
                 );
        }
示例#38
0
    // This script should actually be moved to the main thing, honestly. And various
    // things should be edited to reflect that. Use anim.GetBoneTransform instead
    void Start()
    {
        anim = GetComponent<Animator>();
        decapitate = GetComponent<NoHead>();
        // set up listener
        string filename = @"./output.txt";
        FileStream traceLog;
        if (logging)
        {
            traceLog = new FileStream(filename, FileMode.OpenOrCreate);
            listener = new TextWriterTraceListener(traceLog);
        }

        headTransform = anim.GetBoneTransform(HumanBodyBones.Head);
        neckTransform = anim.GetBoneTransform(HumanBodyBones.Neck);
        spineTransform = anim.GetBoneTransform(HumanBodyBones.Spine);
        cameraRigTransform = headTransform.Find("CameraRig");
        cameraTransform = cameraRigTransform.Find("Camera");

        initHeadRot = headTransform.localRotation.eulerAngles;
    }
示例#39
0
 /// <summary>
 /// Derived method to initialize trace listener to write text data
 /// </summary>
 /// <param name="traceSource">Trace source that holds a set of handlers</param>
 /// <param name="filterLevels">The level of trace message filtered by trace listener</param>
 /// <param name="traceOptions">Trace data options that has to be written in the trace output</param>
 /// <param name="traceListener">Trace listener object associated with the trace source</param>
 public override void InitListener(out TraceListener traceListener)
 {
     traceListener = new TextWriterTraceListener(this.GetStreamWriter());
 }
示例#40
0
        public static void Main(string[] args)
        {
            int  exitCode   = 0;
            bool errorFound = false;
            //RMArgs xtargs = new RMArgs(args);
            RMArgs    xtargs;
            XmlWriter xw = null;
            TextWriterTraceListener twtl = null;
            StringBuilder           sb;

#if TRACE
            Trace.AutoFlush = true;
            twtl            = new TextWriterTraceListener(Console.Out, LISTENER_NAME);
            Trace.Listeners.Add(twtl);
#endif
            xtargs = new RMArgs(args);
            if (args.Length < 1)
            {
                Console.Error.WriteLine("no args");
                showUsage(Console.Out);
                exitCode = 3;
            }
            else
            {
                if (xtargs.showHelp)
                {
                    Console.Error.WriteLine("help requested");
                    showUsage(Console.Out);
                }
                else
                {
                    if (string.IsNullOrEmpty(xtargs.inputFile))
                    {
                        errorFound |= true;
                        Console.Error.WriteLine("input-file not specified.");
                        exitCode = 3;
                    }
                    if (errorFound)
                    {
                        showUsage(Console.Error);
                    }
                    else
                    {
                        sb = new  StringBuilder();
                        xw = XmlWriter.Create(sb, settings);
                        //xw=XmlWriter.Create()
                        if (string.IsNullOrEmpty(xtargs.outputFile))
                        {
                            settings.CloseOutput = false;
                            //xw = XmlWriter.Create(Console.Out, settings);
                        }
                        //else {
                        //    ////settings.CloseOutput = true;
                        //    //xw = XmlWriter.Create(xtargs.outputFile, settings);
                        //}
                        try {
                            writePackage(xw, xtargs);
                            xw.Flush();
                            if (!string.IsNullOrEmpty(xtargs.outputFile))
                            {
                                File.WriteAllText(xtargs.outputFile, sb.ToString());
                            }
                            else
                            {
                                Console.Out.WriteLine(sb.ToString());
                            }
                            if (xtargs.verbose)
                            {
                                Trace.WriteLine("[VERBOSE] " + "wrote output to " +
                                                (string.IsNullOrEmpty(xtargs.outputFile) ?
                                                 "<stdout>" :
                                                 xtargs.outputFile));
                            }
                            ;
                        } catch (Exception ex) {
                            MiniLogger.log(MethodBase.GetCurrentMethod(), ex);
                            exitCode = 1;
                        } finally {
                            if (xw != null)
                            {
                                xw.Close();
                                xw.Dispose();
                                xw = null;
                            }
                        }
                    }
                }
                //KC      Trace.WriteLine("here");
            }
#if TRACE
            if (twtl != null)
            {
                Trace.Flush();
                Trace.Listeners.Remove(LISTENER_NAME);
            }
#endif
            Environment.Exit(exitCode);
        }
示例#41
0
        /************************************************************************
         * Constructor
         *
         * *********************************************************************/

        private Logger()
        {
            m_NoClients = 0;
            m_levellist = new Dictionary <string, ErrorLevel> ();

            /* Make sure LogCtl can write to the event log using "LogCtl" as the event source
             * ------------------------------------------------------------------------------
             * Vista makes this difficult, and we need to add some messy code to deal with this.
             * Throw an exception if we can't set up the event source */

            EnsureEventSourceExists();

            try
            {
                using (RegistryKey logkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\SWI\\LogCtl", false))
                {
                    m_Filename = logkey.GetValue("LogFile").ToString();
                    using (RegistryKey rk = logkey.OpenSubKey("LogLevel"))
                    {
                        foreach (string s in rk.GetValueNames())
                        {
                            if (string.IsNullOrEmpty(s))
                            {
                                m_defaultlevel = Trans(rk.GetValue(s).ToString());
                            }
                            else
                            {
                                m_levellist.Add(s, Trans(rk.GetValue(s).ToString()));
                            }
                        }
                    }
                    try
                    {
                        m_bIfTrace = ((int)logkey.GetValue("IfTrace")) != 0;

                        TextWriterTraceListener tw = new TextWriterTraceListener(logkey.GetValue("TraceFile").ToString());
                        System.Diagnostics.Trace.Listeners.Add(tw);
                        System.Diagnostics.Trace.AutoFlush = true;
                        System.Diagnostics.Trace.WriteLine("Logger() built.");
                    }
                    catch (Exception)
                    {
                        EmergencyMessage(EventLogEntryType.Warning, "Missing TraceFile in registry");
                    }
                    try
                    {
                        m_bIfUseFixedFormatting = ((int)logkey.GetValue("IfUseFixedFormatting")) != 0;
                        string   FixedFormatting = logkey.GetValue("FixedFormatting").ToString();
                        string[] ar = FixedFormatting.Split(new char[] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
                        if (ar.GetUpperBound(0) != 5)
                        {
                            EmergencyMessage(EventLogEntryType.Warning, "The FixedFormatting registry entry is not specifying 6 column widths as expected.");
                            m_bIfUseFixedFormatting = false;
                        }
                        for (int i = 0; i < 6; i++)
                        {
                            m_ColumnWidths[i] = int.Parse(ar[i]);
                        }
                    }
                    catch (Exception)
                    {
                        EmergencyMessage(EventLogEntryType.Warning, "IfUseFixedFormatting or FixedFormatting registry entries");
                    }
                }
            }
            catch (Exception)
            {
                /* Possibly this is the first time LogCtl has ever been used
                 * ---------------------------------------------------------
                 * so create some default settings */

                try
                {
                    using (RegistryKey logkey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\SWI\\LogCtl"))
                    {
                        logkey.SetValue("LogFile", "C:\\Logs\\log.log");
                        using (RegistryKey rk = logkey.CreateSubKey("LogLevel"))
                        {
                            rk.SetValue("", "INF");
                        }
                        logkey.SetValue("IfTrace", 0);
                        logkey.SetValue("TraceFile", "C:\\Logs\\trace.log");
                        logkey.SetValue("RenameEventName", "Global\\STE LogCtl-Rename");
                        logkey.SetValue("IfUseFixedFormatting", 0);
                        logkey.SetValue("FixedFormatting", "20 12 5 4 13 26");
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    throw new Exception("LogCtl could not read or write initialization settings. Please run as administrator and try again.");
                }
                catch (Exception e)
                {
                    throw new Exception(string.Format("Unexpected exception encountered in LogCtl. {0}", e.Message));
                }
            }

            /* Prepare m_RenameEvent
             * ---------------------
             * add retries, Sept 17, 2009 -- B.Muth */

            int retries = 0;

TryAgain:

            try
            {
                using (RegistryKey logkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\SWI\\LogCtl", false))
                {
                    string RenameEventName;


                    RenameEventName = logkey.GetValue("RenameEventName").ToString();

                    EventWaitHandleSecurity sec = new EventWaitHandleSecurity();
                    //EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule ("Everyone",
                    //                                                                EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize,
                    //                                                                AccessControlType.Allow);
                    //EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule (new SecurityIdentifier ("S-1-1-0"), EventWaitHandleRights.FullControl, AccessControlType.Allow);
                    // change from 'Everyone' to 'Users'
                    EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(new SecurityIdentifier("S-1-5-32-545"), EventWaitHandleRights.FullControl, AccessControlType.Allow);
                    sec.AddAccessRule(rule);
                    bool bCreated;

                    try
                    {
                        m_RenameEvent = new EventWaitHandle(true, EventResetMode.ManualReset, RenameEventName, out bCreated, sec);
                    }
                    catch (Exception e)
                    {
                        EmergencyMessage(EventLogEntryType.Error, string.Format("EventWaitHandle() failed in an attempt to create the RenameEventname. {0}", e.Message));
                        if (++retries < 10)
                        {
                            Thread.Sleep(500);
                            goto TryAgain;
                        }
                        m_RenameEvent = null;
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("RenameEventName registry entry is missing, or other exception encoutered. Please check the Application Event log.");
            }
        }
示例#42
0
        //Create a Method to calculate Mileage
        public void  GetAnswer()
        {
            //Create 3 variables to work with
            Decimal Mileage = 0, Distance = 0, Gallons = 0;

            try
            {
                //Add code to set these values from the UI
                Distance = Convert.ToDecimal(txtDistance.Text);
                Gallons  = Convert.ToDecimal(txtGallons.Text);

                //Check for zeros
                if (Distance == 0)
                {
                    //Cause an Exception to be Thrown
                    throw new MyCustomException();
                }

                Mileage = Distance / Gallons;
            }
            catch (DivideByZeroException ex)
            {
                //Catch Divide by Zero errors and use the object from Microsoft's
                //DivideByZeroException Class to show a Message
                MessageBox.Show(ex.Message);
            }
            catch (MyCustomException ex)
            {
                //Catch all MyCustomException errors,
                //Use the Object to show a Custom error Message
                //MessageBox.Show(ex.Message); <-- This line is no longer needed

                //Step 1: Create the TraceListener Objects
                TextWriterTraceListener objTWCon  = new TextWriterTraceListener(Console.Out);
                TextWriterTraceListener objTWFile = new TextWriterTraceListener("c:\\Trace.log");
                EventLogTraceListener   objEL     = new EventLogTraceListener("Mileage Calculator");

                //Step 2: Add the Objects to the Listeners collection
                Debug.Listeners.Add(objTWFile);
                Debug.Listeners.Add(objTWCon);
                Debug.Listeners.Add(objEL);

                //Step 3: Set the system to automatic mode
                Debug.AutoFlush = true;

                //Step 4: Set the message you want to send
                string strMessage;
                strMessage  = "======( Trace Info: " + DateTime.Now + " )======" + "\n";
                strMessage += ex.Message + "\n";
                strMessage += ex.ToString();

                //Step 5: Send the message to all of the listeners, including the default
                Debug.WriteLine(strMessage);

                //Step 6: Close the file in the file version and clear all the Listeners
                objTWFile.Close();
                Debug.Listeners.Clear();
            }
            catch
            {
                //Catch any other type of Exception
                MessageBox.Show("There was an Error");
            }
            finally
            {
                //Put code here that you want to always run
                MessageBox.Show("Inside Finally");
            } //End Try-Catch Block

            MessageBox.Show(Mileage.ToString(), "Answer");
        } //end of GetAnswer
示例#43
0
 protected Tracing(string filename)
 {
     listener        = new TextWriterTraceListener(filename, TraceListenerName);
     verbositySwitch = new System.Diagnostics.TraceSwitch(SwitchName, "0-Off, 1-Errors, 2-Warnings, 3-Info, 4-Verbose", "1");
 }
示例#44
0
        static void Main(string[] args)
        {
            TextWriterTraceListener trac = new TextWriterTraceListener(System.Console.Out);

            Debug.Listeners.Add(trac);

            FileInfo file         = new FileInfo("input.txt");
            bool     isFileExists = false;

            if (file.Exists)
            {
                isFileExists = true;
                Trace.WriteLine("файл input.txt найден");
            }

            if (!isFileExists)
            {
                StreamWriter tmp = new StreamWriter("input.txt");
                tmp.Close();
                Trace.WriteLine("файл input.txt был создан");
            }


            StreamReader reader = new StreamReader("input.txt");

            uint n = 0;

            if (!uint.TryParse(reader.ReadLine(), out n))
            {
                //Console.WriteLine("no values!");
                Trace.WriteLine("no values in input");
                Console.ReadKey();
                return;
            }

            List <Software> soft = new List <Software>(Convert.ToInt32(n));

            Software[] softSer = new Software[n];
            try
            {
                for (int i = 0; i < n; i++)
                {
                    string info = reader.ReadLine();

                    string[] measures = info.Split(',');
                    if (measures.Length == 2)
                    {
                        soft.Add(new FreeSoft(measures[0], measures[1]));
                        softSer[i] = new FreeSoft(measures[0], measures[1]);
                    }
                    else if (measures.Length == 4)
                    {
                        soft.Add(new SharewareSoft(measures[0], measures[1], Convert.ToDateTime(measures[2]), int.Parse(measures[3])));
                        softSer[i] = new SharewareSoft(measures[0], measures[1], Convert.ToDateTime(measures[2]), int.Parse(measures[3]));
                    }
                    else
                    {
                        soft.Add(new CommercialSoft(measures[0], measures[1], Convert.ToDateTime(measures[2]), int.Parse(measures[3]), float.Parse(measures[4])));
                        softSer[i] = new CommercialSoft(measures[0], measures[1], Convert.ToDateTime(measures[2]), int.Parse(measures[3]), float.Parse(measures[4]));
                    }
                }

                Console.WriteLine("Информация о програмном обеспечении");
                foreach (Software animal in softSer)
                {
                    animal.displayInfo();
                }
                reader.Close();

                XmlSerializer formatter = new XmlSerializer(typeof(Software[]));
                using (FileStream fs = new FileStream("Software.xml", FileMode.OpenOrCreate))
                {
                    formatter.Serialize(fs, softSer);
                    Trace.WriteLine("Объект сериализован");
                    //Console.WriteLine("Объект сериализован");
                }



                findListOfSoftware(soft);
                Console.ReadLine();
            }
            catch
            { //Console.WriteLine("ошибка при чтении данных");
                System.Diagnostics.Trace.WriteLine("ошибка при чтении данных");
            }

            Console.ReadKey();
        }
示例#45
0
        private bool RunTest(MethodInfo method)
        {
            foreach (var deploy in method.GetCustomAttributes <DeploymentItemAttribute>(true))
            {
                var depPath = Path.Combine(startDirectory, deploy.Path);
                if (File.Exists(depPath))
                {
                    var outPath = Path.Combine(startDirectory, deploy.OutputDirectory, new FileInfo(deploy.Path).Name);
                    if (!File.Exists(outPath))
                    {
                        File.Copy(depPath, outPath);
                    }
                }
                if (Directory.Exists(depPath))
                {
                    if (!Directory.Exists(deploy.OutputDirectory))
                    {
                        CopyDirectory(depPath, deploy.OutputDirectory);
                    }
                }
            }
            foreach (var deploy in method.ReflectedType.GetCustomAttributes <DeploymentItemAttribute>(true))
            {
                var depPath = Path.Combine(startDirectory, deploy.Path);
                if (File.Exists(depPath))
                {
                    var outPath = Path.Combine(startDirectory, deploy.OutputDirectory, new FileInfo(deploy.Path).Name);
                    if (!File.Exists(outPath))
                    {
                        File.Copy(depPath, outPath);
                    }
                }
                if (Directory.Exists(depPath))
                {
                    if (!Directory.Exists(deploy.OutputDirectory))
                    {
                        CopyDirectory(depPath, deploy.OutputDirectory);
                    }
                }
            }
            var curDir = Directory.GetCurrentDirectory();
            var tracer = new TextWriterTraceListener(Path.Combine(testDirectory, "Results", method.Name + ".txt"));

            Trace.Listeners.Add(tracer);
            bool passed = false;

            try
            {
                var instance = method.ReflectedType.GetConstructor(new Type[0]).Invoke(new object[0]);
                foreach (var initializer in method.ReflectedType
                         .GetMethods().Where(x => x.GetCustomAttributes <TestInitializeAttribute>(true).Count() > 0))
                {
                    initializer.Invoke(instance, new object[0]);
                }
                try
                {
                    method.Invoke(instance, new object[0]);
                    passed = true;
                }
                finally
                {
                    foreach (var cleanup in method.ReflectedType
                             .GetMethods().Where(x => x.GetCustomAttributes <TestCleanupAttribute>(true).Count() > 0))
                    {
                        cleanup.Invoke(instance, new object[0]);
                    }
                }
            }
            catch (TargetInvocationException e)
            {
                Console.WriteLine("Exception thrown: ");
                Console.WriteLine(e.InnerException.ToString());
                Trace.WriteLine("--- Test Results:");
                Trace.WriteLine("Exception thrown: ");
                Trace.WriteLine(e.InnerException.ToString());
                passed = false;
            }
            Trace.WriteLine("Test " + (passed ? "Passed" : "Failed"));
            Trace.Listeners.Remove(tracer);
            tracer.Close();
            Directory.SetCurrentDirectory(curDir);
            return(passed);
        }
示例#46
0
        public void LogToFile(LogFileType logType, string logMessage)
        {
            string logDirectory = LogPath + @"\" + DateTime.Today.ToString("yyyyMMdd");
            string filePath     = string.Empty;

            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
                switch (logType)
                {
                case LogFileType.TRACE:
                    filePath = logDirectory + @"\TRACE.0.log";
                    break;

                case LogFileType.MESSAGE:
                    filePath = logDirectory + @"\MESSAGE.0.log";
                    break;

                case LogFileType.EXCEPTION:
                    filePath = logDirectory + @"\EXCEPTION.0.log";
                    break;

                default:
                    filePath = logDirectory + @"\TRACE.0.log";
                    break;
                }
            }
            else
            {
                string[] filePaths = Directory.GetFiles(logDirectory, "*.log");
                if (filePaths.Length == 0)
                {
                    switch (logType)
                    {
                    case LogFileType.TRACE:
                        filePath = logDirectory + @"\TRACE.0.log";
                        break;

                    case LogFileType.MESSAGE:
                        filePath = logDirectory + @"\MESSAGE.0.log";
                        break;

                    case LogFileType.EXCEPTION:
                        filePath = logDirectory + @"\EXCEPTION.0.log";
                        break;

                    default:
                        filePath = logDirectory + @"\TRACE.0.log";
                        break;
                    }
                }
                else
                {
                    List <string> fileList = new List <string>();
                    foreach (string fPath in filePaths)
                    {
                        FileInfo file  = new FileInfo(fPath);
                        string[] parts = file.Name.Split('.');
                        if (parts[0].ToUpper() == logType.ToString().ToUpper())
                        {
                            fileList.Add(fPath);
                        }
                    }

                    int    lastestIndex    = int.MinValue;
                    string lastestFilePath = "";
                    if (fileList.Count <= 0)
                    {
                        filePath = logDirectory + @"\" + logType.ToString().ToUpper() + ".0.log";
                    }
                    else
                    {
                        foreach (string fPath in fileList)
                        {
                            FileInfo file  = new FileInfo(fPath);
                            string[] parts = file.Name.Split('.'); //fPath.Split('.');
                            if (Convert.ToInt32(parts[1]) >= lastestIndex)
                            {
                                lastestIndex    = Convert.ToInt32(parts[1]);
                                lastestFilePath = fPath;
                            }
                        }

                        filePath = lastestFilePath;
                    }

                    if (File.Exists(filePath))
                    {
                        FileInfo lastestFile = new FileInfo(filePath);
                        // check if file size be larger than 5MB then create new one
                        if (((lastestFile.Length / 1024f) / 1024f) > 5)
                        {
                            lastestIndex++;
                            filePath = logDirectory + @"\" + logType.ToString().ToUpper() + "." + lastestIndex + ".log";
                        }
                    }
                }
            }

            logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage;
            TextWriterTraceListener listener = new TextWriterTraceListener(filePath);

            listener.WriteLine(logMessage);
            listener.Flush();
            listener.Close();
        }
示例#47
0
文件: Program.cs 项目: nima1367/PC
        private static void Main(string[] args)
        {
            MainWindow window = null;
            var        thread = new Thread(() =>
            {
                window     = new MainWindow();
                var writer = new TextWriterTraceListener(System.Console.Out);
                Debug.Listeners.Add(writer);
                Console.WriteLine("Enter the input directory:");
                var inptDir = Console.ReadLine();
                while (inptDir == null || !inptDir.Any())
                {
                    Console.WriteLine("I need a valid input directory. Simply copy and paste the address of the location of the tessellated model plus the file name:");
                    inptDir = Console.ReadLine();
                }
                TessellatedSolid ts = null;
                var s = File.OpenRead(inptDir);
                ts    = IO.Open(s, inptDir, false)[0];
                TesselationToPrimitives.Run(ts);
                var cc = 0;
                foreach (var f in ts.Faces)
                {
                    cc++;
                    //var c = Colors.Red;
                    Point3DCollection vOrder = new Point3DCollection();
                    if (f.Edges[0].OwnedFace == f)
                    {
                        vOrder.Add(new Point3D(f.Edges[0].From.Position[0], f.Edges[0].From.Position[1], f.Edges[0].From.Position[2]));
                        vOrder.Add(new Point3D(f.Edges[0].To.Position[0], f.Edges[0].To.Position[1], f.Edges[0].To.Position[2]));
                    }
                    else
                    {
                        vOrder.Add(new Point3D(f.Edges[0].To.Position[0], f.Edges[0].To.Position[1], f.Edges[0].To.Position[2]));
                        vOrder.Add(new Point3D(f.Edges[0].From.Position[0], f.Edges[0].From.Position[1], f.Edges[0].From.Position[2]));
                    }
                    if (f.Edges[1].From == f.Edges[0].From || f.Edges[1].From == f.Edges[0].To)
                    {
                        vOrder.Add(new Point3D(f.Edges[1].To.Position[0], f.Edges[1].To.Position[1], f.Edges[1].To.Position[2]));
                    }
                    else
                    {
                        vOrder.Add(new Point3D(f.Edges[1].From.Position[0], f.Edges[1].From.Position[1], f.Edges[1].From.Position[2]));
                    }
                    var c = new System.Windows.Media.Color {
                        A = f.Color.A, B = f.Color.B, G = f.Color.G, R = f.Color.R
                    };
                    window.view1.Children.Add(new ModelVisual3D
                    {
                        Content =
                            new GeometryModel3D
                        {
                            Geometry = new MeshGeometry3D
                            {
                                Positions       = vOrder,
                                TriangleIndices = new Int32Collection(new int[] { 0, 1, 2 }),
                                Normals         = new Vector3DCollection(new[] { new Vector3D(f.Normal[0], f.Normal[1], f.Normal[2]) })
                            },
                            Material = new DiffuseMaterial(new SolidColorBrush(c))
                        }
                    });
                }
                window.view1.ZoomExtentsWhenLoaded = true;
                window.ShowDialog();
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
示例#48
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            if (ProductType.MEP != app.Application.Product)
            {
                message = "Please run this command in Revit MEP.";
                return(Result.Failed);
            }

            //SelElementSet sel = uidoc.Selection.Elements; // 2014

            ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); // 2015

            //if( 0 == sel.Size ) // 2014

            if (0 == ids.Count) // 2015
            {
                message = "Please select some rectangular ducts.";
                return(Result.Failed);
            }

            // set up log file:

            string log = Assembly.GetExecutingAssembly().Location
                         + "." + DateTime.Now.ToString("yyyyMMdd")
                         + ".log";

            if (File.Exists(log))
            {
                File.Delete(log);
            }

            TraceListener listener
                = new TextWriterTraceListener(log);

            Trace.Listeners.Add(listener);

            try
            {
                Trace.WriteLine("Begin");

                // loop over all selected ducts:

                //foreach( Duct duct in sel ) // 2014

                foreach (ElementId id in ids) // 2015
                {
                    Duct duct = doc.GetElement(id) as Duct;

                    if (null == duct)
                    {
                        Trace.TraceError("The selection is not a duct!");
                    }
                    else
                    {
                        // process each duct:

                        Trace.WriteLine("========================");
                        Trace.WriteLine("Duct: Id = " + duct.Id.IntegerValue);

                        AnalyseDuct(duct);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            finally
            {
                Trace.Flush();
                listener.Close();
                Trace.Close();
                Trace.Listeners.Remove(listener);
            }
            return(Result.Failed);
        }
        public TobiLoggerFacade()
        {
#if (DEBUG)
            //PresentationTraceSources.SetTraceLevel(obj, PresentationTraceLevel.High)
#endif
            PresentationTraceSources.ResourceDictionarySource.Listeners.Add(new LoggerFacadeTraceListener(this));
            PresentationTraceSources.ResourceDictionarySource.Switch.Level = SourceLevels.All;

            PresentationTraceSources.DataBindingSource.Listeners.Add(new LoggerFacadeTraceListener(this));
            PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;

#if (false && DEBUG) // not very useful (misses the TAB control)
            PresentationTraceSources.DataBindingSource.Listeners.Add(new BindingErrorAdornerTraceListener(false));
#endif

            PresentationTraceSources.DependencyPropertySource.Listeners.Add(new LoggerFacadeTraceListener(this));
            PresentationTraceSources.DependencyPropertySource.Switch.Level = SourceLevels.All;

            PresentationTraceSources.DocumentsSource.Listeners.Add(new LoggerFacadeTraceListener(this));
            PresentationTraceSources.DocumentsSource.Switch.Level = SourceLevels.All;

            PresentationTraceSources.MarkupSource.Listeners.Add(new LoggerFacadeTraceListener(this));
            PresentationTraceSources.MarkupSource.Switch.Level = SourceLevels.All;

            PresentationTraceSources.NameScopeSource.Listeners.Add(new LoggerFacadeTraceListener(this));
            PresentationTraceSources.NameScopeSource.Switch.Level = SourceLevels.All;

            //StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
            //standardOutput.AutoFlush = true;
            //Console.SetOut(standardOutput);

            //StreamWriter standardErr = new StreamWriter(Console.OpenStandardError());
            //standardErr.AutoFlush = true;
            //Console.SetError(standardErr);

            //if (File.Exists(ApplicationConstants.LOG_FILE_PATH))
            //{
            //    // Remark: the following logging messages go to the System.Out, and that's it (not to any file target). We initialize file redirect later on (see below).

            //    Console.WriteLine("Deleting log file [" + ApplicationConstants.LOG_FILE_PATH + "]...");
            //    File.Delete(ApplicationConstants.LOG_FILE_PATH);
            //    Console.WriteLine("File deleted [" + ApplicationConstants.LOG_FILE_PATH + "].");

            //    Thread.Sleep(100);
            //}

#if (BITFACTORY)
            Debug.Listeners.Add(new BitFactoryLoggerTraceListener(this));
            Trace.Listeners.Add(new BitFactoryLoggerTraceListener(this));

            m_Logger = new CompositeLogger();

            Logger consoleLogger = TextWriterLogger.NewConsoleLogger();
            m_Logger.AddLogger("console", consoleLogger);

            consoleLogger.Formatter = new BitFactoryLoggerLogEntryFormatter();
#endif


#if (BITFACTORY)
            Logger fileLogger = new FileLogger(UserInterfaceStrings.LOG_FILE_PATH);
            m_Logger.AddLogger("file", fileLogger);

            fileLogger.Formatter = new BitFactoryLoggerLogEntryFormatter();
#else
            // Remark: we could set DiagnosticsConfiguration.LogFileName
            // and benefit from DefaultTraceListener's built-in support for output to log file,
            // but unfortunately the WriteToLogFile() method opens and closes the file
            // for each Write operation, which obviously is a massive performance bottleneck.

            //m_FileWriter = File.CreateText(UserInterfaceStrings.LOG_FILE_PATH);
            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(ApplicationConstants.LOG_FILE_PATH, FileMode.Create, FileAccess.Write,
                                            FileShare.Read);
            }
            catch (Exception ex)
            {
                MessageBox.Show("1) Press the OK button (the file explorer will open to the file location: [" + ApplicationConstants.LOG_FILE_PATH + "]).\n\n2) Then delete [" + ApplicationConstants.LOG_FILE_NAME + "].\n\n3) Then launch Tobi again.");
                //MessageBox.Show(ex.Message);

                string dir = Path.GetDirectoryName(ApplicationConstants.LOG_FILE_PATH); // Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

                // Shell.ExecuteShellProcess()
                var process = new Process
                {
                    StartInfo =
                    {
                        FileName               = dir,
                        RedirectStandardError  = false, // We can't redirect messages when shell-execute
                        RedirectStandardOutput = false, // We can't redirect messages when shell-execute
                        UseShellExecute        = true,
                        WindowStyle            = ProcessWindowStyle.Normal,
                        Arguments              = ""
                    }
                };
                process.Start();

                throw ex;
            }

#if (false && DEBUG) // We want clickable code line numbers in the debugger output window, but we don't want to spam the log file with this info.
            m_FileWriter = new CodeLocationTextWriter(new StreamWriter(fileStream));
#else
            m_FileWriter = new StreamWriter(fileStream)
            {
                AutoFlush = true
            };
#endif

            var listener = new TextWriterTraceListener(m_FileWriter)
            {
                //                TraceOutputOptions = TraceOptions.DateTime
                //                                     | TraceOptions.LogicalOperationStack
                //                                     | TraceOptions.Timestamp
                //#if (DEBUG)
                // | TraceOptions.Callstack
                //#endif
            };

            // Works for DEBUG too, no need for a second set of listeners
            Trace.Listeners.Add(listener);

            //TODO: this is a massive hack as we needed to change "internal" to "public" in the MEF source code !! (how else to do this though ?)
            TraceSourceTraceWriter.Source.Listeners.Add(listener);

#if (DEBUG)
            var systemOut = new CodeLocationTextWriter(Console.Out);
#else
            var systemOut = Console.Out;
#endif
            //Trace.Listeners.Add(new TextWriterTraceListener(systemOut));


#if (DEBUG)
            var systemErr = new CodeLocationTextWriter(Console.Error);
#else
            var systemErr = Console.Error;
#endif
            //Trace.Listeners.Add(new TextWriterTraceListener(systemErr));


            var compositeOut = new CompositeTextWriter(new[] { m_FileWriter, systemOut });
            Console.SetOut(compositeOut);

            var compositeErr = new CompositeTextWriter(new[] { m_FileWriter, systemErr });
            Console.SetError(compositeErr);
#endif
        }
示例#50
0
        public void TestConstructorWithStreamAndName(string testName)
        {
            StreamWriter testWriter = StreamWriter.Null;

            using (var target = new TextWriterTraceListener(testWriter, testName))
            {
                Assert.Equal(testName, target.Name);
                Assert.Same(testWriter, target.Writer);
            }

            using (var target = new TextWriterTraceListener(FileStream.Null, testName))
            {
                Assert.Equal(testName, target.Name);
                Assert.NotNull(target.Writer);
            }
        }