Esempio n. 1
0
        //INSERTAR USUARIO EMPLEADO
        public int insertarUsuarioE(string username, string contrasena, string rol, int ci)
        {
            NpgsqlConnection conn = DAOUsuario.getInstanceDAO();

            conn.Open();

            String sql = "INSERT INTO \"Usuario\" (\"COD\",\"Nombre\", \"Contrasena\", \"FK-RolU\", \"FK-EmpleadoU\") " +
                         "VALUES ((SELECT NEXTVAL('seq')),'" + username + "', '" + contrasena + "', " + rol + ", " + ci + ")";
            NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);

            try
            {
                int resp = cmd.ExecuteNonQuery(); //CONTROLAR EXCEPTION DE UNIQUE
                conn.Close();
                return(resp);
            }
            catch (Exception e)
            {
                System.Diagnostics.TextWriterTraceListener writer = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
                System.Diagnostics.Debug.Listeners.Add(writer);
                System.Diagnostics.Debug.WriteLine(e.ToString());
                conn.Close();
                return(0);
            }
        }
Esempio n. 2
0
        //VBox outerBox;
//		PropertyGrid propertyGrid;

        public EditorProcess()          //: base ()
        {
                        #if TRACE
            System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
            System.Diagnostics.Trace.Listeners.Add(listener);
                        #endif
        }
Esempio n. 3
0
		public EditorProcess ()
		{
			#if TRACE
				System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener (System.Console.Out);
				System.Diagnostics.Trace.Listeners.Add (listener);
			#endif
		}
Esempio n. 4
0
        //AUDITORIA DEL SISTEMA
        public int insertarAccion(int codU, int codAcc, string fecha, string accion)
        {
            NpgsqlConnection conn = DAOUsuario.getInstanceDAO();

            conn.Open();

            String sql = "INSERT INTO \"Accion-Usuario\" (\"codUsuario\", \"codAccion\", \"Fecha\", \"Descripcion\") " +
                         "VALUES (" + codU + ", " + codAcc + ", TO_TIMESTAMP('" + fecha + "', 'DD-MM-YYYY HH24:MI:SS'), '" + accion + "');";
            NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);

            try
            {
                int resp = cmd.ExecuteNonQuery(); //CONTROLAR EXCEPTION DE UNIQUE
                conn.Close();
                return(resp);
            }
            catch (Exception e)
            {
                System.Diagnostics.TextWriterTraceListener writer = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
                System.Diagnostics.Debug.Listeners.Add(writer);
                System.Diagnostics.Debug.WriteLine(e.ToString());
                conn.Close();
                return(0);
            }
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            System.Diagnostics.TextWriterTraceListener log_writer = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
            System.Diagnostics.Trace.Listeners.Add(log_writer);
            Console.BufferHeight = Int16.MaxValue - 1;

            EVI_D70 camera = new EVI_D70("COM4");

            camera.maximum_pan_angle = EVI_D70.pan_position.create_from_degrees(90);
            camera.minimum_pan_angle = EVI_D70.pan_position.create_from_degrees(-90);
            camera.maximum_tilt_angle = EVI_D70.tilt_position.create_from_degrees(45);
            camera.minimum_tilt_angle = EVI_D70.tilt_position.create_from_degrees(-20);
            camera.maximum_zoom_ratio = EVI_D70.zoom_position.create_from_ratio(2.5);

            camera.pid_pan_tilt_speed = 6;
            camera.pid_target_pan_position.degrees = -80;
            camera.pid_target_tilt_position.degrees = 0;
            camera.pid_control = true;
            //System.Threading.Thread.Sleep(1000);
            //camera.pid_target_pan_position.degrees = 80;
            //camera.pid_target_tilt_position.degrees = 0;
            //System.Threading.Thread.Sleep(1000);
            //camera.pid_control = false;

            while (true)
            { }

            System.Threading.Thread.Sleep(1000);
            camera.Dispose();
            //System.Threading.Thread.Sleep(2500);

            Console.WriteLine("luke is a fairy");
        }
Esempio n. 6
0
 void InitTraceListener()
 {
     string traceFile = Server.MapPath("~") + "/nietoyosten.log";
     System.IO.FileStream traceLog =
         new System.IO.FileStream(traceFile, System.IO.FileMode.OpenOrCreate);
     System.Diagnostics.TextWriterTraceListener listener =
         new System.Diagnostics.TextWriterTraceListener(traceLog);
     System.Diagnostics.Trace.Listeners.Add(listener);
 }
Esempio n. 7
0
 // static constructor
 static ChassisLog()
 {
     // Creates the text file that the trace listener will write to
     // Creates the new trace listener.
     try
     {
     # if TRACE_LOG
         cmLogTraceFile = new System.IO.FileStream(traceLogFilePath, System.IO.FileMode.Append);
         ChassisManagerTraceLog = new System.Diagnostics.TextWriterTraceListener(cmLogTraceFile);
     # endif
     }
Esempio n. 8
0
        // static constructor
        static ChassisLog()
        {
            // Creates the text file that the trace listener will write to
            // Creates the new trace listener.
            try
            {
# if TRACE_LOG
                cmLogTraceFile         = new System.IO.FileStream(traceLogFilePath, System.IO.FileMode.Append);
                ChassisManagerTraceLog = new System.Diagnostics.TextWriterTraceListener(cmLogTraceFile);
# endif
            }
        // Application Level Events

        #region Application_Start sender, eventArgs (virtual)
        public virtual void Application_Start(object sender, EventArgs e)
        {
            string logfilename = GetLogFileName();

            if (logfilename != null)
            {
                _listener = new System.Diagnostics.TextWriterTraceListener(logfilename);
                System.Diagnostics.Debug.Listeners.Add(_listener);
            }
            System.Diagnostics.Debug.AutoFlush = true;
            System.Diagnostics.Debug.Print("Application started");
        }
Esempio n. 10
0
    public static SARAH GetInstance() {
      if (sarah == null) {
        sarah = new SARAH();

        var path = "bootlog.txt";
        if (File.Exists(path)) {
          File.Delete(path);
        }
        var bootlog = new System.Diagnostics.TextWriterTraceListener(File.CreateText(path));
        System.Diagnostics.Debug.Listeners.Add(bootlog);

        sarah.Log("==========================================");
      }
      return sarah;
    }
Esempio n. 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName">file name</param>
        /// <param name="isDelete">if it is false then append to file, true to recreate the file</param>
        public TracerLogger(string fileName, bool isDelete)
        {
            if (isDelete)
            {
                FileInfo f = new FileInfo(fileName);

                if (f.Exists)
                {
                    f.Delete();
                }
            }

            System.Diagnostics.TextWriterTraceListener s = new System.Diagnostics.TextWriterTraceListener(fileName);
            System.Diagnostics.Trace.Listeners.Add(s);
            System.Diagnostics.Trace.AutoFlush = true;
        }
Esempio n. 12
0
        public void NoErrorIsLoggedIfWeDontRequireAReceiver()
        {
            GameObject       go   = new GameObject();
            MessageComponent comp = new MessageComponent();

            go.AddComponent(comp);
            MemoryStream ms = new MemoryStream();

            System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener(ms);
            System.Diagnostics.Debug.Listeners.Clear();
            System.Diagnostics.Debug.Listeners.Add(listener);

            go.SendMessage("NonExisting", 42, SendMessageOptions.DontRequireReceiver);

            listener.Flush();
            Assert.That(ms.Position, Is.EqualTo(0));
        }
Esempio n. 13
0
        public static SARAH GetInstance()
        {
            if (sarah == null)
            {
                sarah = new SARAH();

                var path = "bootlog.txt";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                var bootlog = new System.Diagnostics.TextWriterTraceListener(File.CreateText(path));
                System.Diagnostics.Debug.Listeners.Add(bootlog);

                sarah.Log("==========================================");
            }
            return(sarah);
        }
        public void BadHashWarning()
        {
            var old = Diagnostics.ConcurrentHashtableSwitch;

            Diagnostics.ConcurrentHashtableSwitch = new System.Diagnostics.TraceSwitch("ReplacedSwitch", "", "Warning");
            Diagnostics.TypeBadHashReportMap      = new Dictionary <Type, bool>();

            try
            {
                var writer     = new StringWriter();
                var myListener = new System.Diagnostics.TextWriterTraceListener(writer);

                System.Diagnostics.Trace.Listeners.Add(myListener);

                try
                {
                    var dictionary = new ConcurrentDictionary <BadHashObject, int>();

                    for (int i = 0; i < 1000; ++i)
                    {
                        dictionary.Add(new BadHashObject(), i);
                    }

                    System.Threading.Thread.Sleep(1000);

                    myListener.Flush();
                }
                finally
                { System.Diagnostics.Trace.Listeners.Remove(myListener); }

                writer.Close();

                var result = writer.ToString();

                Assert.IsFalse(String.IsNullOrEmpty(result), "Bad hash not reported");
            }
            finally
            {
                Diagnostics.ConcurrentHashtableSwitch = old;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Initializes a new instance of the DebugInformation class
        /// </summary>
        /// <param name="theOutputFilePath">The path of the output file to receive the debug output</param>
        /// <param name="enableDebugInformation">Boolean flag that indicates whether to enable the debug information</param>
        /// <param name="enableInformationEvents">Boolean flag that indicates whether to include information events in the debug information</param>
        /// <param name="redirectDebugInformationToOutput">Boolean flag that indicates whether to redirect debug information to the output window</param>
        public DebugInformation(string theOutputFilePath, bool enableDebugInformation, bool enableInformationEvents, bool redirectDebugInformationToOutput)
        {
            // Delete any existing output files with the selected name to ape the clearing of all text from the output window
            if (System.IO.File.Exists(
                    theOutputFilePath))
            {
                // Reset the attributes of the existing output file to ensure that it can be deleted
                System.IO.File.SetAttributes(
                    theOutputFilePath,
                    System.IO.FileAttributes.Normal);

                // Then delete the existing output file
                System.IO.File.Delete(
                    theOutputFilePath);
            }

            this.theOutputFilePath = theOutputFilePath;

            this.enableDebugInformation = enableDebugInformation;

            this.enableInformationEvents = enableInformationEvents;

            if (enableDebugInformation)
            {
                this.theOutputWindowListener =
                    new System.Diagnostics.TextWriterTraceListener(theOutputFilePath);

                // Unless instructed otherwise, remove the output window from the list of listeners to debug output as all text will go to the output file
                if (enableDebugInformation &&
                    !redirectDebugInformationToOutput)
                {
                    System.Diagnostics.Debug.Listeners.Clear();
                }

                // Redirect any text added to the output window to the output file
                System.Diagnostics.Trace.Listeners.Add(
                    this.theOutputWindowListener);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Helper function that creates the log file and attaches it
        /// </summary>
        /// <param name="path">The path to place the log file</param>
        private void SetupLogFileHelper(string path)
        {
            if (path != m_LogPath)
            {
                m_LogPath = path;

                // Cleanup
                this.DetachLogger();

                // Create the FileDebugWriter
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                // Create the log file without locking it and turning off buffering
                // NOTE: Stupid FileStream doesn't allow us to get rid of the buffering
                // completely, so even with buffer size set to 1 it still uses an 8-byte buffer
                Stream myDebugFile = new FileStream(path + "\\DEBUG_" + System.Environment.MachineName + "_" + System.DateTime.Now.Ticks.ToString() + ".log", FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 1);
                this.FileDebugWriter = new System.Diagnostics.TextWriterTraceListener(myDebugFile);
                this.AttachLogger();
            }
        }
        static void Main(string[] args)
        {
            System.Diagnostics.TextWriterTraceListener writer = new
   System.Diagnostics.TextWriterTraceListener(System.Console.Out);
            System.Diagnostics.Debug.Listeners.Add(writer);

            JdwpParameters parameters = null;
            int pid = 0;
            for (int i = 0; i < args.Length; i++)
            {
                String str = args[i];
                Console.Out.WriteLine(str);
                Console.Out.Flush();
                if (str.StartsWith("-Xrunjdwp") || str.StartsWith("-agentlib:jdwp"))
                {
                    parameters = new JdwpParameters();
                    parameters.Parse(str);

                }
                if (str.StartsWith("-pid:"))
                {
                    pid = Int32.Parse(str.Substring(5, str.Length - 5));
                }
            }
            if (parameters != null && pid != 0)
            {
                JdwpConnection conn = new JdwpConnection(parameters);
                conn.Connect();
                Console.Error.WriteLine("Started");
                TargetVM target = new TargetVM(pid, new JdwpEventHandler(conn));
                JdwpHandler handler = new JdwpHandler(conn, target);
                handler.Run();
                //System.Threading.Thread.Sleep(5000);
            }
            else
            {
                Environment.Exit(3);
            }
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            System.Diagnostics.TextWriterTraceListener writer = new
                                                                System.Diagnostics.TextWriterTraceListener(System.Console.Out);
            System.Diagnostics.Debug.Listeners.Add(writer);

            JdwpParameters parameters = null;
            int            pid        = 0;

            for (int i = 0; i < args.Length; i++)
            {
                String str = args[i];
                Console.Out.WriteLine(str);
                Console.Out.Flush();
                if (str.StartsWith("-Xrunjdwp") || str.StartsWith("-agentlib:jdwp"))
                {
                    parameters = new JdwpParameters();
                    parameters.Parse(str);
                }
                if (str.StartsWith("-pid:"))
                {
                    pid = Int32.Parse(str.Substring(5, str.Length - 5));
                }
            }
            if (parameters != null && pid != 0)
            {
                JdwpConnection conn = new JdwpConnection(parameters);
                conn.Connect();
                Console.Error.WriteLine("Started");
                TargetVM    target  = new TargetVM(pid, new JdwpEventHandler(conn));
                JdwpHandler handler = new JdwpHandler(conn, target);
                handler.Run();
                //System.Threading.Thread.Sleep(5000);
            }
            else
            {
                Environment.Exit(3);
            }
        }
Esempio n. 19
0
        private static void ConnectOrThrow(
            ABB.Vtrin.cDataLoader dataloader,
            string rtdbHost,
            string rtdbUsername,
            string rtdbPassword)
        {
            // Set up a memory stream to catch exceptions
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                var listener = new System.Diagnostics.TextWriterTraceListener(memoryStream, "connectlistener");
                System.Diagnostics.Trace.Listeners.Add(listener);

                // Set connection options
                dataloader.ConnectOptions =
                    ABB.Vtrin.cDataLoader.cConnectOptions.AcceptNewServerKeys
                    | ABB.Vtrin.cDataLoader.cConnectOptions.AcceptServerKeyChanges;

                // Initialize the database driver
                RTDBDriver = dataloader.Connect(
                    rtdbHost,
                    rtdbUsername,
                    rtdbPassword,
                    false);

                // Unbind the connect listener
                System.Diagnostics.Trace.Listeners.Remove("connectlistener");

                // Case: driver is null, something went wrong
                // > throw an error
                if (RTDBDriver == null)
                {
                    // Read stack trace from the memorystream buffer
                    string msg = System.Text.Encoding.UTF8.GetString(memoryStream.GetBuffer());
                    throw new System.ApplicationException(msg);
                }
            }
        }
Esempio n. 20
0
        private static void AddListener()
        {
            try
            {
                if (!Directory.Exists(Application.StartupPath + "\\Trace"))
                {
                    Directory.CreateDirectory(Application.StartupPath + "\\Trace");
                }

                if (!Directory.Exists(Application.StartupPath + "\\Trace\\" + DateTime.Now.ToString("MM")))
                {
                    Directory.CreateDirectory(Application.StartupPath + "\\Trace\\" + DateTime.Now.ToString("MM"));
                }

                if (Directory.Exists(Application.StartupPath + "\\Trace\\" + DateTime.Now.AddMonths(1).ToString("MM")))
                {
                    Directory.Delete(Application.StartupPath + "\\Trace\\" + DateTime.Now.AddMonths(1).ToString("MM"), true);
                }

                traceName = Application.StartupPath + "\\Trace\\" + DateTime.Now.ToString("MM") + "\\" + DateTime.Now.ToString("dd_TRACE") + ".log";

                System.IO.StreamWriter writer = new System.IO.StreamWriter(traceName, true, System.Text.Encoding.GetEncoding("windows-1254"));

                System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener(writer);

                System.Diagnostics.Trace.Listeners.Add(listener);

                System.Diagnostics.Trace.AutoFlush = true;

                System.Diagnostics.Trace.WriteLine("-> " + DateTime.Now.ToString() + "\tBaşladı");
            }
            catch
            {
                ;
            }
        }
Esempio n. 21
0
        public static void Initialize()
        {
            var name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

            var listenerDtl = new System.Diagnostics.DefaultTraceListener
            {
                LogFileName = "TraceLog_" + name + "_" + DateTime.Now.ToString("yyyMMdd") + ".txt"
            };

            System.Diagnostics.Trace.Listeners.Add(listenerDtl);

            var listenerTwtl = new System.Diagnostics.TextWriterTraceListener();

            listenerTwtl.Writer = Console.Out;
            //listenerTwtl.Writer = new System.IO.StreamWriter(name + ".txt", true, Encoding.UTF8);
            System.Diagnostics.Trace.Listeners.Add(listenerTwtl);

            //var listenerEltl = new System.Diagnostics.EventLogTraceListener();
            //System.Diagnostics.Trace.Listeners.Add(listenerEltl);

            //listenerEltl.EventLog = new System.Diagnostics.EventLog(name, Environment.MachineName, name);
            //var listenerEptl = new System.Diagnostics.Eventing.EventProviderTraceListener("{89185535-C194-48D9-82FB-0B01F7147461}", name);
            //System.Diagnostics.Trace.Listeners.Add(listenerEptl);
        }
Esempio n. 22
0
        //Buscando USUARIO CLIENTE
        public int buscandoUsuarioC(string username, string contrasena)
        {
            NpgsqlConnection conn = DAOUsuario.getInstanceDAO();

            conn.Open();

            string sql = "SELECT \"Nombre\", \"Contrasena\", \"FK-ClienteU\" " +
                         "FROM \"Usuario\" WHERE \"Nombre\" = '" + username + "' AND " +
                         "\"FK-EmpleadoU\" is NULL";
            NpgsqlCommand    cmd = new NpgsqlCommand(sql, conn);
            NpgsqlDataReader dr  = cmd.ExecuteReader();
            int compData         = 0;

            try {
                while (dr.Read())
                {
                    System.Diagnostics.Debug.WriteLine("connection established");
                    System.Diagnostics.TextWriterTraceListener writer = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
                    System.Diagnostics.Debug.Listeners.Add(writer);
                    if (String.Equals(dr[1].ToString(), contrasena))
                    {
                        compData = 1;
                    }
                }
            }
            catch (Exception e)
            {
                compData = 0;
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
            dr.Close();

            conn.Close();

            return(compData);
        }
Esempio n. 23
0
        static bool RunTestSuite(string directoryName, string suiteName, StreamReader instream, VccOptions commandLineOptions)
        {
            var startTime = DateTime.UtcNow;

            System.Diagnostics.Debug.Listeners.Remove("Default");
            var           errorHandler    = new CciErrorHandler(commandLineOptions);
            StringBuilder source          = null;
            StringBuilder expectedOutput  = null;
            StringBuilder actualOutput    = null;
            int           errors          = 0;
            int           testCaseCount   = 0;
            var           WhiteSpaceChars = " \r\n\t".ToCharArray();

            try {
                int line = 1;

                while (!instream.EndOfStream)
                {
                    var l = instream.ReadLine(); // strips Unix or Dos line ending
                    line++;

                    source = new StringBuilder();
                    List <string> compilerParameters;
                    if (l.StartsWith("`") || l.StartsWith("//`"))
                    {
                        string optionString = l.Substring(l.IndexOf('`') + 1);
                        compilerParameters = optionString.Split(WhiteSpaceChars, StringSplitOptions.RemoveEmptyEntries).ToList();
                    }
                    else
                    {
                        compilerParameters = new List <string>();
                        source.Append(l);
                        source.Append("\r\n");
                    }

                    while (!instream.EndOfStream)
                    {
                        l = instream.ReadLine();
                        line++;
                        if (l == "`" || l == "/*`")
                        {
                            break;
                        }
                        source.Append(l);
                        source.Append("\r\n");
                    }

                    if (instream.EndOfStream)
                    {
                        Logger.Instance.Error("The last test case in the suite has not been provided with expected output");
                        errors++;
                        break;
                    }

                    int errLine = line;
                    expectedOutput = new StringBuilder();
                    while (!instream.EndOfStream)
                    {
                        l = instream.ReadLine();
                        line++;
                        if (l == "`" || l == "`*/")
                        {
                            break;
                        }
                        expectedOutput.Append(l);
                        expectedOutput.Append("\r\n");
                    }

                    if (l != "`" && l != "`*/")
                    {
                        Logger.Instance.Error("The last test case in the suite has been provided with incomplete expected output");
                        errors++;
                        break;
                    }

                    actualOutput = new StringBuilder();
                    TextWriter savedOut = Console.Out;
                    Console.SetOut(new StringWriter(actualOutput));
                    System.Diagnostics.TextWriterTraceListener myWriter = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
                    System.Diagnostics.Debug.Listeners.Add(myWriter);

                    ++testCaseCount;
                    string suiteNameWithoutExt = Path.GetFileNameWithoutExtension(suiteName);
                    string fileNameWithoutExt;

                    if (commandLineOptions.OutputDir != null)
                    {
                        fileNameWithoutExt = commandLineOptions.OutputDir;
                    }
                    else
                    {
                        fileNameWithoutExt = directoryName;
                    }

                    fileNameWithoutExt += Path.DirectorySeparatorChar + suiteNameWithoutExt + vccSplitSuffix + testCaseCount + "_" + System.Diagnostics.Process.GetCurrentProcess().Id;
                    currentTestcaseName = Path.GetFileName(string.Format("{0}.{1:00}", suiteNameWithoutExt, testCaseCount));

                    try {
                        int returnCode = RunTest(errorHandler, suiteNameWithoutExt, fileNameWithoutExt, source.ToString(), commandLineOptions, compilerParameters);
                        if (returnCode < 0)
                        {
                            actualOutput.Append("Non zero return code: " + returnCode);
                        }
                    } catch (System.Reflection.TargetInvocationException e) {
                        actualOutput.Append(e.InnerException);
                    } catch (Exception e) {
                        actualOutput.Append(e);
                    }

                    Logger.Instance.ResetReportedErrors();
                    Console.SetOut(savedOut);
                    System.Diagnostics.Debug.Listeners.Remove(myWriter);
                    Regex  rx = new Regex(@"[a-zA-Z]:\\.*?\\(.*)" + vccSplitSuffix + @"[0-9_]*.c\(");
                    string actualOutputRepl = rx.Replace(actualOutput.ToString(), "testcase(");
                    actualOutputRepl = actualOutputRepl.Trim();

                    var expected = expectedOutput.ToString().Trim();
                    if (!expected.Equals(actualOutputRepl))
                    {
                        ReportError(suiteName, source, expected, actualOutputRepl, errLine, errors++ == 0);
                    }
                }
                instream.Close();
                var runtime = DateTime.UtcNow.Subtract(startTime).TotalSeconds;
                if (errors == 0)
                {
                    Logger.Instance.Log("{0} passed [{1:0.00}]", suiteName, runtime);
                }
                else
                {
                    Logger.Instance.NewLine();
                    Logger.Instance.Error("{0} had {1} failure(s) [{2:0.00}]", suiteName, errors, runtime);
                }
            } catch {
                var expected = expectedOutput == null ? "<none>" : expectedOutput.ToString().Trim();
                ReportError(suiteName, source, expected, actualOutput.ToString(), -1, true);
            }
            return(errors == 0);
        }
Esempio n. 24
0
        static void Main()
        {
            #if TRACE
                System.Diagnostics.TextWriterTraceListener listener
                    = new System.Diagnostics.TextWriterTraceListener (System.Console.Out);
                System.Diagnostics.Trace.Listeners.Add (listener);
            #endif

            Application.Init ();

            #region Packing and layout

            Window window = new Window ("AspNetEdit Host Sample");
            window.SetDefaultSize (1000, 700);
            window.DeleteEvent += new DeleteEventHandler (window_DeleteEvent);

            VBox outerBox = new VBox ();
            window.Add (outerBox);

            HPaned leftBox = new HPaned ();
            outerBox.PackEnd (leftBox, true, true, 0);
            HPaned rightBox = new HPaned ();
            leftBox.Add2 (rightBox);

            geckoFrame = new Frame ();
            geckoFrame.Shadow = ShadowType.In;
            rightBox.Pack1 (geckoFrame, true, false);

            #endregion

            #region Toolbar

            // * Save/Open

            Toolbar buttons = new Toolbar ();
            outerBox.PackStart (buttons, false, false, 0);

            ToolButton saveButton = new ToolButton (Stock.Save);
            buttons.Add (saveButton);
            saveButton.Clicked += new EventHandler (saveButton_Clicked);

            ToolButton openButton = new ToolButton(Stock.Open);
            buttons.Add(openButton);
            openButton.Clicked += new EventHandler(openButton_Clicked);

            buttons.Add (new SeparatorToolItem());

            // * Clipboard

            ToolButton undoButton = new ToolButton (Stock.Undo);
            buttons.Add (undoButton);
            undoButton.Clicked +=new EventHandler (undoButton_Clicked);

            ToolButton redoButton = new ToolButton (Stock.Redo);
            buttons.Add (redoButton);
            redoButton.Clicked += new EventHandler (redoButton_Clicked);

            ToolButton cutButton = new ToolButton (Stock.Cut);
            buttons.Add (cutButton);
            cutButton.Clicked += new EventHandler (cutButton_Clicked);

            ToolButton copyButton = new ToolButton (Stock.Copy);
            buttons.Add (copyButton);
            copyButton.Clicked += new EventHandler (copyButton_Clicked);

            ToolButton pasteButton = new ToolButton (Stock.Paste);
            buttons.Add (pasteButton);
            pasteButton.Clicked += new EventHandler (pasteButton_Clicked);

            buttons.Add (new SeparatorToolItem());

            // * Text style

            ToolButton boldButton = new ToolButton (Stock.Bold);
            buttons.Add (boldButton);
            boldButton.Clicked += new EventHandler (boldButton_Clicked);

            ToolButton italicButton = new ToolButton (Stock.Italic);
            buttons.Add (italicButton);
            italicButton.Clicked += new EventHandler (italicButton_Clicked);

            ToolButton underlineButton = new ToolButton (Stock.Underline);
            buttons.Add (underlineButton);
            underlineButton.Clicked += new EventHandler (underlineButton_Clicked);

            ToolButton indentButton = new ToolButton (Stock.Indent);
            buttons.Add (indentButton);
            indentButton.Clicked += new EventHandler (indentButton_Clicked);

            ToolButton unindentButton = new ToolButton (Stock.Unindent);
            buttons.Add (unindentButton);
            unindentButton.Clicked += new EventHandler (unindentButton_Clicked);

            buttons.Add (new SeparatorToolItem());

            // * Toolbox

            ToolButton toolboxAddButton = new ToolButton (Stock.Add);
            buttons.Add (toolboxAddButton);
            toolboxAddButton.Clicked += new EventHandler (toolboxAddButton_Clicked);

            #endregion

            #region Designer services and host

            //set up the services
            ServiceContainer services = new ServiceContainer ();
            services.AddService (typeof (INameCreationService), new NameCreationService ());
            services.AddService (typeof (ISelectionService), new SelectionService ());
            services.AddService (typeof (IEventBindingService), new EventBindingService (window));
            services.AddService (typeof (ITypeResolutionService), new TypeResolutionService ());
            ExtenderListService extListServ = new AspNetEdit.Editor.ComponentModel.ExtenderListService ();
            services.AddService (typeof (IExtenderListService), extListServ);
            services.AddService (typeof (IExtenderProviderService), extListServ);
            services.AddService (typeof (ITypeDescriptorFilterService), new TypeDescriptorFilterService ());
            toolboxService = new ToolboxService ();
            services.AddService (typeof (IToolboxService), toolboxService);

            //create our host
            host = new DesignerHost(services);
            host.NewFile();
            host.Activate();

            #endregion

            #region Designer UI and panels

            IRootDesigner rootDesigner = (IRootDesigner) host.GetDesigner (host.RootComponent);
            RootDesignerView designerView = (RootDesignerView) rootDesigner.GetView (ViewTechnology.Passthrough);
            geckoFrame.Add (designerView);

            PropertyGrid p = new PropertyGrid (services);
            p.WidthRequest = 200;
            rightBox.Pack2 (p, false, false);

            Toolbox toolbox = new Toolbox (services);
            leftBox.Pack1 (toolbox, false, false);
            toolboxService.PopulateFromAssembly (System.Reflection.Assembly.GetAssembly (typeof (System.Web.UI.Control)));
            toolboxService.AddToolboxItem (new TextToolboxItem ("<table><tr><td></td><td></td></tr><tr><td></td><td></td></tr></table>", "Table"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<div style=\"width: 100px; height: 100px;\"></div>", "Div"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<hr />", "Horizontal Rule"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<select><option></option></select>", "Select"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<img src=\"\" />", "Image"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<textarea cols=\"20\" rows=\"2\"></textarea>", "Textarea"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"hidden\" />", "Input [Hidden]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"radio\" />", "Input [Radio]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"checkbox\" />", "Input [Checkbox]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"password\" />", "Input [Password]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"file\" />", "Input [File]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"text\" />", "Input [Text]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"submit\" value=\"submit\" />", "Input [Submit]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"reset\" value=\"reset\" />", "Input [Reset]"), "Html");
            toolboxService.AddToolboxItem (new TextToolboxItem ("<input type=\"button\" value=\"button\" />", "Input [Button]"), "Html");
            toolbox.Refresh ();

            #endregion

            window.ShowAll ();
            Application.Run ();
        }
Esempio n. 25
0
        static bool RunTestSuite(string directoryName, string suiteName, StreamReader instream, VccOptions commandLineOptions)
        {
            var startTime = DateTime.UtcNow;
              System.Diagnostics.Debug.Listeners.Remove("Default");
              var errorHandler = new CciErrorHandler(commandLineOptions);
              StringBuilder source = null;
              StringBuilder expectedOutput = null;
              StringBuilder actualOutput = null;
            int errors = 0;
              int testCaseCount = 0;
              var WhiteSpaceChars = " \r\n\t".ToCharArray();

              try {
            int line = 1;

            while (!instream.EndOfStream) {
              var l = instream.ReadLine(); // strips Unix or Dos line ending
              line++;

              source = new StringBuilder();
            List<string> compilerParameters;
            if (l.StartsWith("`") || l.StartsWith("//`")) {
            string optionString = l.Substring(l.IndexOf('`') + 1);
            compilerParameters = optionString.Split(WhiteSpaceChars, StringSplitOptions.RemoveEmptyEntries).ToList();
              } else {
            compilerParameters = new List<string>();
            source.Append(l);
            source.Append("\r\n");
              }

              while (!instream.EndOfStream) {
            l = instream.ReadLine();
            line++;
            if (l == "`" || l == "/*`")
              break;
            source.Append(l);
            source.Append("\r\n");
              }

              if (instream.EndOfStream) {
            Logger.Instance.Error("The last test case in the suite has not been provided with expected output");
            errors++;
            break;
              }

              int errLine = line;
              expectedOutput = new StringBuilder();
              while (!instream.EndOfStream) {
            l = instream.ReadLine();
            line++;
            if (l == "`" || l == "`*/")
              break;
            expectedOutput.Append(l);
            expectedOutput.Append("\r\n");
              }

              if (l != "`" && l != "`*/") {
            Logger.Instance.Error("The last test case in the suite has been provided with incomplete expected output");
            errors++;
            break;
              }

              actualOutput = new StringBuilder();
              TextWriter savedOut = Console.Out;
              Console.SetOut(new StringWriter(actualOutput));
              System.Diagnostics.TextWriterTraceListener myWriter = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
              System.Diagnostics.Debug.Listeners.Add(myWriter);

              ++testCaseCount;
              string suiteNameWithoutExt = Path.GetFileNameWithoutExtension(suiteName);
              string fileNameWithoutExt;

              if (commandLineOptions.OutputDir != null)
              {
              fileNameWithoutExt = commandLineOptions.OutputDir;
              }
              else
              {
              fileNameWithoutExt = directoryName;
              }

              fileNameWithoutExt += Path.DirectorySeparatorChar + suiteNameWithoutExt + vccSplitSuffix + testCaseCount + "_" + System.Diagnostics.Process.GetCurrentProcess().Id;
              currentTestcaseName = Path.GetFileName(string.Format("{0}.{1:00}", suiteNameWithoutExt, testCaseCount));

              try {
            int returnCode = RunTest(errorHandler, suiteNameWithoutExt, fileNameWithoutExt, source.ToString(), commandLineOptions, compilerParameters);
            if (returnCode < 0)
              actualOutput.Append("Non zero return code: " + returnCode);
              } catch (System.Reflection.TargetInvocationException e) {
            actualOutput.Append(e.InnerException);
              } catch (Exception e) {
            actualOutput.Append(e);
              }

              Logger.Instance.ResetReportedErrors();
              Console.SetOut(savedOut);
              System.Diagnostics.Debug.Listeners.Remove(myWriter);
              Regex rx = new Regex(@"[a-zA-Z]:\\.*?\\(.*)" + vccSplitSuffix + @"[0-9_]*.c\(");
              string actualOutputRepl = rx.Replace(actualOutput.ToString(), "testcase(");
              actualOutputRepl = actualOutputRepl.Trim();

              var expected = expectedOutput.ToString().Trim();
              if (!expected.Equals(actualOutputRepl)) {
            ReportError(suiteName, source, expected, actualOutputRepl, errLine, errors++ == 0);
              }

            }
            instream.Close();
            var runtime = DateTime.UtcNow.Subtract(startTime).TotalSeconds;
            if (errors == 0)
              Logger.Instance.Log("{0} passed [{1:0.00}]", suiteName, runtime);
            else {
              Logger.Instance.NewLine();
              Logger.Instance.Error("{0} had {1} failure(s) [{2:0.00}]", suiteName, errors, runtime);
            }
              } catch {
            var expected = expectedOutput == null ? "<none>" : expectedOutput.ToString().Trim();
            ReportError(suiteName, source, expected, actualOutput.ToString(), -1, true);
              }
              return errors == 0;
        }
Esempio n. 26
0
 public static void RunSuite(string suiteName, TextReader instream) {
   System.Diagnostics.Debug.Listeners.Remove("Default");
   HostEnvironment hostEnvironment = new HostEnvironment();
   hostEnvironment.Errors += HandleErrors;
   StringBuilder source = null;
   StringBuilder expectedOutput = null;
   StringBuilder actualOutput = null;
   List<string> suiteParameters = new List<string>();
   List<string> compilerParameters = null;
   List<string> testCaseParameters = null;
   int errors = 0;
   try {
     int ch = instream.Read();
     int line = 1;
     while (ch >= 0) {
       compilerParameters = new List<string>(suiteParameters);
       bool skipTest = false;
       if (ch == '`') {
         ch = instream.Read();
         bool parametersAreForEntireSuite = false;
         if (ch == '`') {
           parametersAreForEntireSuite = true;
           ch = instream.Read();
         }
         while (ch == '/') {
           //compiler parameters
           StringBuilder cParam = new StringBuilder();
           do {
             cParam.Append((char)ch);
             ch = instream.Read();
           } while (ch != '/' && ch != 0 && ch != 10 && ch != 13);
           for (int i = cParam.Length-1; i >= 0; i--) {
             if (!Char.IsWhiteSpace(cParam[i])) break;
             cParam.Length = i;
           }
           string cp = cParam.ToString();
           compilerParameters.Add(cp);
         }
         if (parametersAreForEntireSuite)
           suiteParameters.AddRange(compilerParameters);
         if (ch == 13) ch = instream.Read();
         if (ch == 10) {
           line++;
           ch = instream.Read();
           if (parametersAreForEntireSuite && ch == '`') continue;
         }
       }
       if (ch == ':') {
         ch = instream.Read();
         while (ch == '=') {
           //test case parameters
           StringBuilder tcParam = new StringBuilder();
           ch = instream.Read(); //discard =
           while (ch != '=' && ch != 0 && ch != 10 && ch != 13) {
             tcParam.Append((char)ch);
             ch = instream.Read();
           }
           for (int i = tcParam.Length-1; i >= 0; i--) {
             if (!Char.IsWhiteSpace(tcParam[i])) break;
             tcParam.Length = i;
           }
           if (testCaseParameters == null) testCaseParameters = new List<string>();
           testCaseParameters.Add(tcParam.ToString());
         }
         if (ch == 13) ch = instream.Read();
         if (ch == 10) {
           ch = instream.Read();
           line++;
         }
       }
       source = new StringBuilder();
       while (ch >= 0 && ch != '`') {
         source.Append((char)ch);
         ch = instream.Read();
         if (ch == 10) line++;
       }
       if (ch < 0) {
         Console.WriteLine("The last test case in the suite has not been provided with expected output");
         errors++;
         break;
       }
       ch = instream.Read();
       if (ch == 13) ch = instream.Read();
       if (ch == 10) {
         line++;
         ch = instream.Read();
       }
       int errLine = line;
       expectedOutput = new StringBuilder();
       while (ch >= 0 && ch != '`') {
         expectedOutput.Append((char)ch);
         ch = instream.Read();
         if (ch == 10) line++;
       }
       if (expectedOutput.Length > 0 && expectedOutput[expectedOutput.Length-1] == 10)
         expectedOutput.Length -= 1;
       if (expectedOutput.Length > 0 && expectedOutput[expectedOutput.Length-1] == 13)
         expectedOutput.Length -= 1;
       ch = instream.Read();
       if (ch == 13) ch = instream.Read();
       if (ch == 10) {
         ch = instream.Read();
         line++;
       }
       if (skipTest) continue;
       actualOutput = new StringBuilder();
       TextWriter savedOut = Console.Out;
       Console.SetOut(new StringWriter(actualOutput));
       System.Diagnostics.TextWriterTraceListener myWriter = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
       System.Diagnostics.Debug.Listeners.Add(myWriter);
       try {
         RunTest(hostEnvironment, Path.GetFileNameWithoutExtension(suiteName), source.ToString(), actualOutput, compilerParameters, testCaseParameters);
       } catch (Exception e) {
         actualOutput.Append(e.Message);
       }
       compilerParameters = null;
       testCaseParameters = null;
       Console.SetOut(savedOut);
       System.Diagnostics.Debug.Listeners.Remove(myWriter);
       if (actualOutput.Length > 0 && actualOutput[actualOutput.Length - 1] == 10)
         actualOutput.Length -= 1;
       if (actualOutput.Length > 0 && actualOutput[actualOutput.Length - 1] == 13)
         actualOutput.Length -= 1;
       if (!expectedOutput.ToString().Equals(actualOutput.ToString())) {
         if (errors++ == 0) Console.WriteLine(suiteName+" failed\n");
         Console.WriteLine("source({0}):", errLine);
         if (source != null)
           Console.WriteLine(source);
         Console.WriteLine("actual output:");
         Console.WriteLine(actualOutput);
         Console.WriteLine("expected output:");
         if (expectedOutput != null)
           Console.WriteLine(expectedOutput);
       }
     }
     instream.Close();
     if (errors == 0)
       Console.WriteLine(suiteName+" passed");
     else {
       Console.WriteLine();
       Console.WriteLine(suiteName+" had "+errors+ (errors > 1 ? " failures" : " failure"));
     }
   } catch {
     Console.WriteLine(suiteName+" failed\n");
     Console.WriteLine("source:");
     if (source != null)
       Console.WriteLine(source);
     Console.WriteLine("actual output:");
     Console.WriteLine(actualOutput);
     Console.WriteLine("expected output:");
     if (expectedOutput != null)
       Console.WriteLine(expectedOutput);
   }
 }
Esempio n. 27
0
 public Logger()
 {
     System.Diagnostics.TextWriterTraceListener listener = new System.Diagnostics.TextWriterTraceListener("nico_download.log", "LogFile");
     this.log.Listeners.Add(listener);
 }
Esempio n. 28
0
        public static bool RunTestSuite(string suiteName, StreamReader instream)
        {
            System.Diagnostics.Debug.Listeners.Remove("Default");
            HostEnvironment hostEnvironment = new HostEnvironment();

            hostEnvironment.Errors += hostEnvironment.HandleErrors;
            StringBuilder source             = null;
            StringBuilder expectedOutput     = null;
            StringBuilder actualOutput       = null;
            List <string> suiteParameters    = new List <string>();
            List <string> compilerParameters = null;
            List <string> testCaseParameters = null;
            int           errors             = 0;

            try {
                int ch   = instream.Read();
                int line = 1;
                while (ch >= 0)
                {
                    compilerParameters = new List <string>(suiteParameters);
                    bool skipTest = false;
                    if (ch == '`')
                    {
                        ch = instream.Read();
                        bool parametersAreForEntireSuite = false;
                        if (ch == '`')
                        {
                            parametersAreForEntireSuite = true;
                            ch = instream.Read();
                        }
                        while (ch == '/')
                        {
                            //compiler parameters
                            StringBuilder cParam = new StringBuilder();
                            do
                            {
                                cParam.Append((char)ch);
                                ch = instream.Read();
                            } while (ch != '/' && ch != 0 && ch != 10 && ch != 13);
                            for (int i = cParam.Length - 1; i >= 0; i--)
                            {
                                if (!Char.IsWhiteSpace(cParam[i]))
                                {
                                    break;
                                }
                                cParam.Length = i;
                            }
                            string cp = cParam.ToString();
                            compilerParameters.Add(cp);
                        }
                        if (parametersAreForEntireSuite)
                        {
                            suiteParameters.AddRange(compilerParameters);
                        }
                        if (ch == 13)
                        {
                            ch = instream.Read();
                        }
                        if (ch == 10)
                        {
                            line++;
                            ch = instream.Read();
                            if (parametersAreForEntireSuite && ch == '`')
                            {
                                continue;
                            }
                        }
                    }
                    if (ch == ':')
                    {
                        ch = instream.Read();
                        while (ch == '=')
                        {
                            //test case parameters
                            StringBuilder tcParam = new StringBuilder();
                            ch = instream.Read(); //discard =
                            while (ch != '=' && ch != 0 && ch != 10 && ch != 13)
                            {
                                tcParam.Append((char)ch);
                                ch = instream.Read();
                            }
                            for (int i = tcParam.Length - 1; i >= 0; i--)
                            {
                                if (!Char.IsWhiteSpace(tcParam[i]))
                                {
                                    break;
                                }
                                tcParam.Length = i;
                            }
                            if (testCaseParameters == null)
                            {
                                testCaseParameters = new List <string>();
                            }
                            testCaseParameters.Add(tcParam.ToString());
                        }
                        if (ch == 13)
                        {
                            ch = instream.Read();
                        }
                        if (ch == 10)
                        {
                            ch = instream.Read();
                            line++;
                        }
                    }
                    source = new StringBuilder();
                    while (ch >= 0 && ch != '`')
                    {
                        source.Append((char)ch);
                        ch = instream.Read();
                        if (ch == 10)
                        {
                            line++;
                        }
                    }
                    if (ch < 0)
                    {
                        Console.WriteLine("The last test case in the suite has not been provided with expected output");
                        errors++;
                        break;
                    }
                    ch = instream.Read();
                    if (ch == 13)
                    {
                        ch = instream.Read();
                    }
                    if (ch == 10)
                    {
                        line++;
                        ch = instream.Read();
                    }
                    int errLine = line;
                    expectedOutput = new StringBuilder();
                    while (ch >= 0 && ch != '`')
                    {
                        expectedOutput.Append((char)ch);
                        ch = instream.Read();
                        if (ch == 10)
                        {
                            line++;
                        }
                    }
                    if (expectedOutput.Length > 0 && expectedOutput[expectedOutput.Length - 1] == 10)
                    {
                        expectedOutput.Length -= 1;
                    }
                    if (expectedOutput.Length > 0 && expectedOutput[expectedOutput.Length - 1] == 13)
                    {
                        expectedOutput.Length -= 1;
                    }
                    ch = instream.Read();
                    if (ch == 13)
                    {
                        ch = instream.Read();
                    }
                    if (ch == 10)
                    {
                        ch = instream.Read();
                        line++;
                    }
                    if (skipTest)
                    {
                        continue;
                    }
                    actualOutput = new StringBuilder();
                    TextWriter savedOut = Console.Out;
                    Console.SetOut(new StringWriter(actualOutput));
                    System.Diagnostics.TextWriterTraceListener myWriter = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
                    System.Diagnostics.Debug.Listeners.Add(myWriter);
                    try {
                        int returnCode = RunTest(hostEnvironment, Path.GetFileNameWithoutExtension(suiteName), source.ToString(), actualOutput, compilerParameters, testCaseParameters);
                        if (returnCode != 0)
                        {
                            actualOutput.Append("Non zero return code: " + returnCode);
                        }
                    } catch (System.Reflection.TargetInvocationException e) {
                        actualOutput.Append(e.InnerException.Message);
                    } catch (Exception e) {
                        actualOutput.Append(e.Message);
                    }
                    compilerParameters = null;
                    testCaseParameters = null;
                    Console.SetOut(savedOut);
                    System.Diagnostics.Debug.Listeners.Remove(myWriter);
                    if (actualOutput.Length > 0 && actualOutput[actualOutput.Length - 1] == 10)
                    {
                        actualOutput.Length -= 1;
                    }
                    if (actualOutput.Length > 0 && actualOutput[actualOutput.Length - 1] == 13)
                    {
                        actualOutput.Length -= 1;
                    }
                    if (!expectedOutput.ToString().Equals(actualOutput.ToString()))
                    {
                        if (errors++ == 0)
                        {
                            Console.WriteLine(suiteName + " failed\n");
                        }
                        Console.WriteLine("source({0}):", errLine);
                        if (source != null)
                        {
                            Console.WriteLine(source);
                        }
                        Console.WriteLine("actual output:");
                        Console.WriteLine(actualOutput);
                        Console.WriteLine("expected output:");
                        if (expectedOutput != null)
                        {
                            Console.WriteLine(expectedOutput);
                        }
                    }
                }
                instream.Close();
                if (errors == 0)
                {
                    Console.WriteLine(suiteName + " passed");
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine(suiteName + " had " + errors + (errors > 1 ? " failures" : " failure"));
                }
            } catch {
                Console.WriteLine(suiteName + " failed\n");
                Console.WriteLine("source:");
                if (source != null)
                {
                    Console.WriteLine(source);
                }
                Console.WriteLine("actual output:");
                Console.WriteLine(actualOutput);
                Console.WriteLine("expected output:");
                if (expectedOutput != null)
                {
                    Console.WriteLine(expectedOutput);
                }
            }
            return(errors == 0);
        }
Esempio n. 29
0
        static void Main()
        {
                        #if TRACE
            System.Diagnostics.TextWriterTraceListener listener
                = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
            System.Diagnostics.Trace.Listeners.Add(listener);
                        #endif

            Application.Init();

            #region Packing and layout

            Window window = new Window("AspNetEdit Host Sample");
            window.SetDefaultSize(1000, 700);
            window.DeleteEvent += new DeleteEventHandler(window_DeleteEvent);

            VBox outerBox = new VBox();
            window.Add(outerBox);

            HPaned leftBox = new HPaned();
            outerBox.PackEnd(leftBox, true, true, 0);
            HPaned rightBox = new HPaned();
            leftBox.Add2(rightBox);

            geckoFrame        = new Frame();
            geckoFrame.Shadow = ShadowType.In;
            rightBox.Pack1(geckoFrame, true, false);

            #endregion

            #region Toolbar

            // * Save/Open

            Toolbar buttons = new Toolbar();
            outerBox.PackStart(buttons, false, false, 0);

            ToolButton saveButton = new ToolButton(Stock.Save);
            buttons.Add(saveButton);
            saveButton.Clicked += new EventHandler(saveButton_Clicked);

            ToolButton openButton = new ToolButton(Stock.Open);
            buttons.Add(openButton);
            openButton.Clicked += new EventHandler(openButton_Clicked);

            buttons.Add(new SeparatorToolItem());

            // * Clipboard

            ToolButton undoButton = new ToolButton(Stock.Undo);
            buttons.Add(undoButton);
            undoButton.Clicked += new EventHandler(undoButton_Clicked);

            ToolButton redoButton = new ToolButton(Stock.Redo);
            buttons.Add(redoButton);
            redoButton.Clicked += new EventHandler(redoButton_Clicked);

            ToolButton cutButton = new ToolButton(Stock.Cut);
            buttons.Add(cutButton);
            cutButton.Clicked += new EventHandler(cutButton_Clicked);

            ToolButton copyButton = new ToolButton(Stock.Copy);
            buttons.Add(copyButton);
            copyButton.Clicked += new EventHandler(copyButton_Clicked);

            ToolButton pasteButton = new ToolButton(Stock.Paste);
            buttons.Add(pasteButton);
            pasteButton.Clicked += new EventHandler(pasteButton_Clicked);

            buttons.Add(new SeparatorToolItem());

            // * Text style

            ToolButton boldButton = new ToolButton(Stock.Bold);
            buttons.Add(boldButton);
            boldButton.Clicked += new EventHandler(boldButton_Clicked);

            ToolButton italicButton = new ToolButton(Stock.Italic);
            buttons.Add(italicButton);
            italicButton.Clicked += new EventHandler(italicButton_Clicked);

            ToolButton underlineButton = new ToolButton(Stock.Underline);
            buttons.Add(underlineButton);
            underlineButton.Clicked += new EventHandler(underlineButton_Clicked);

            ToolButton indentButton = new ToolButton(Stock.Indent);
            buttons.Add(indentButton);
            indentButton.Clicked += new EventHandler(indentButton_Clicked);

            ToolButton unindentButton = new ToolButton(Stock.Unindent);
            buttons.Add(unindentButton);
            unindentButton.Clicked += new EventHandler(unindentButton_Clicked);

            buttons.Add(new SeparatorToolItem());

            // * Toolbox

            ToolButton toolboxAddButton = new ToolButton(Stock.Add);
            buttons.Add(toolboxAddButton);
            toolboxAddButton.Clicked += new EventHandler(toolboxAddButton_Clicked);

            #endregion

            #region Designer services and host

            //set up the services
            ServiceContainer services = new ServiceContainer();
            services.AddService(typeof(INameCreationService), new NameCreationService());
            services.AddService(typeof(ISelectionService), new SelectionService());
            services.AddService(typeof(IEventBindingService), new EventBindingService(window));
            services.AddService(typeof(ITypeResolutionService), new TypeResolutionService());
            ExtenderListService extListServ = new AspNetEdit.Editor.ComponentModel.ExtenderListService();
            services.AddService(typeof(IExtenderListService), extListServ);
            services.AddService(typeof(IExtenderProviderService), extListServ);
            services.AddService(typeof(ITypeDescriptorFilterService), new TypeDescriptorFilterService());
            toolboxService = new ToolboxService();
            services.AddService(typeof(IToolboxService), toolboxService);

            //create our host
            host = new DesignerHost(services);
            host.NewFile();
            host.Activate();

            #endregion

            #region Designer UI and panels

            IRootDesigner    rootDesigner = (IRootDesigner)host.GetDesigner(host.RootComponent);
            RootDesignerView designerView = (RootDesignerView)rootDesigner.GetView(ViewTechnology.Passthrough);
            geckoFrame.Add(designerView);

            PropertyGrid p = new PropertyGrid(services);
            p.WidthRequest = 200;
            rightBox.Pack2(p, false, false);

            Toolbox toolbox = new Toolbox(services);
            leftBox.Pack1(toolbox, false, false);
            toolboxService.PopulateFromAssembly(System.Reflection.Assembly.GetAssembly(typeof(System.Web.UI.Control)));
            toolboxService.AddToolboxItem(new TextToolboxItem("<table><tr><td></td><td></td></tr><tr><td></td><td></td></tr></table>", "Table"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<div style=\"width: 100px; height: 100px;\"></div>", "Div"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<hr />", "Horizontal Rule"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<select><option></option></select>", "Select"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<img src=\"\" />", "Image"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<textarea cols=\"20\" rows=\"2\"></textarea>", "Textarea"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"hidden\" />", "Input [Hidden]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"radio\" />", "Input [Radio]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"checkbox\" />", "Input [Checkbox]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"password\" />", "Input [Password]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"file\" />", "Input [File]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"text\" />", "Input [Text]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"submit\" value=\"submit\" />", "Input [Submit]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"reset\" value=\"reset\" />", "Input [Reset]"), "Html");
            toolboxService.AddToolboxItem(new TextToolboxItem("<input type=\"button\" value=\"button\" />", "Input [Button]"), "Html");
            toolbox.Refresh();

            #endregion

            window.ShowAll();
            Application.Run();
        }
Esempio n. 30
0
        private async Task Run()
        {

            // Values are available here
            if (_options.Verbose)
            {
                var writer = new System.Diagnostics.TextWriterTraceListener(System.Console.Out);
                System.Diagnostics.Debug.Listeners.Add(writer);
            }


            // event loop
            var events = (from evt in _traceSource.GetEvents().ObserveOn(TaskPoolScheduler.Default)
                          // transition to task pool immediately to not block the trace
                          where null != evt
                          let permissions = evt.BuildPermissions()
                          from permission in permissions
                          select permission)
                .SubscribeOn(TaskPoolScheduler.Default);


            var statementsBag = new ConcurrentBag<Task<IAccessStatement>>();

            var subscription = events.Do(s => Console.WriteLine(s.BuildSqlCommand()))
                                     .GroupBy(s => s.BuildSqlCommand())
                                     .Select(grp => grp.FirstAsync().ToTask())
                                     .Subscribe(statementsBag.Add);
            using (subscription)
            {
                while (!_loopComplete)
                {
                    Thread.Sleep(250);
                    if (Console.KeyAvailable)
                    {
                        var key = Console.ReadKey();
                        if (key.Key == ConsoleKey.Escape)
                        {
                            _loopComplete = true;
                        }
                    }
                }

                // closing using block will dispose of subscription
            }


            // open file and write output
            if (!string.IsNullOrEmpty(_options.OutputFile))
            {

                var statements = new List<IAccessStatement>();
                foreach (var task in statementsBag)
                {
                    statements.Add(await task);
                }

                var ordered = statements.Where(s => !(s is UnimplementedAccessStatement))
                                       .OrderBy(s => s.Database)
                                       .ThenBy(s => null != s.Principals ? s.Principals.Select(p => p.Name).FirstOrDefault() : "")
                                       .ThenBy(s => null != s.SecurableObject ? s.SecurableObject.ObjectOwner : "")
                                       .ThenBy(s => null != s.SecurableObject ? s.SecurableObject.ObjectName : "")
                                       .ThenBy(s => null != s.Permissions ? s.Permissions.Select(p => p.Permission).FirstOrDefault() : "");


                var unimplemented = statements.Where(s => s is UnimplementedAccessStatement);

                using (var fstm = File.Open(_options.OutputFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                using (var writeBuff = new StreamWriter(fstm))
                {
                    String lastDb = null;
                    foreach (var accessStatement in ordered)
                    {
                        if (lastDb != accessStatement.Database)
                        {
                            // don't need these at the top
                            if (null != lastDb)
                            {
                                writeBuff.WriteLine("GO");
                                writeBuff.WriteLine();
                            }

                            writeBuff.WriteLine("-- Database " + accessStatement.Database);
                            writeBuff.WriteLine("USE [{0}]", accessStatement.Database);
                            writeBuff.WriteLine("GO");
                            writeBuff.WriteLine();
                            lastDb = accessStatement.Database;
                        }

                        writeBuff.WriteLine(accessStatement.BuildSqlCommand());
                    }

                    writeBuff.WriteLine();
                    writeBuff.WriteLine();

                    foreach (var accessStatement in unimplemented)
                    {
                        writeBuff.WriteLine("These types have not yet been implemented.");
                        // TODO: Need verbose version to dump the original generated statements
                        writeBuff.WriteLine(accessStatement.BuildSqlCommand());
                    }
                }
            }


            Console.WriteLine("Exiting");
        }
Esempio n. 31
0
        /// <summary>
        /// Performs an install of a database
        /// </summary>
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            var commandParams = GetCommandLineParameters();

            var paramUICount = 0;
            var setup        = new InstallSetup();

            if (commandParams.Count > 0)
            {
                if (commandParams.ContainsKey(PARAMKEYS_SHOWSQL))
                {
                    if (commandParams[PARAMKEYS_SHOWSQL].ToLower() == "true" || commandParams[PARAMKEYS_SHOWSQL].ToLower() == "1" || commandParams[PARAMKEYS_SHOWSQL].ToLower() == string.Empty)
                    {
                        setup.ShowSql = true;
                    }
                    else if (commandParams[PARAMKEYS_SHOWSQL].ToLower() == "false" || commandParams[PARAMKEYS_SHOWSQL].ToLower() == "0")
                    {
                        setup.ShowSql = false;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_SHOWSQL + " parameter must be set to 'true or false'.");
                    }
                    paramUICount++;
                }

                if (commandParams.Any(x => PARAMKEYS_TRAN.Contains(x.Key)))
                {
                    setup.UseTransaction = GetSetting(commandParams, PARAMKEYS_TRAN, true);
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_SKIPNORMALIZE))
                {
                    setup.SkipNormalize = true;
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_HASH))
                {
                    if (commandParams[PARAMKEYS_HASH].ToLower() == "true" || commandParams[PARAMKEYS_HASH].ToLower() == "1" || commandParams[PARAMKEYS_HASH].ToLower() == string.Empty)
                    {
                        setup.UseHash = true;
                    }
                    else if (commandParams[PARAMKEYS_HASH].ToLower() == "false" || commandParams[PARAMKEYS_HASH].ToLower() == "0")
                    {
                        setup.UseHash = false;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_HASH + " parameter must be set to 'true or false'.");
                    }
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_CHECKONLY))
                {
                    setup.CheckOnly = true;
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_QUIET))
                {
                    setup.SuppressUI = true;
                    paramUICount++;
                }

                //Setup trace if need be. If showing SQL then auto trace on
                if (commandParams.ContainsKey(PARAMKEYS_TRACE) || setup.ShowSql)
                {
                    var trc = new System.Diagnostics.TextWriterTraceListener(Console.Out);
                    System.Diagnostics.Debug.Listeners.Add(trc);
                    paramUICount++;
                }

                if (commandParams.ContainsKey(PARAMKEYS_VERSIONWARN))
                {
                    if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "all")
                    {
                        setup.AcceptVersionWarningsChangedScripts = true;
                        setup.AcceptVersionWarningsNewScripts     = true;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "none")
                    {
                        setup.AcceptVersionWarningsChangedScripts = false;
                        setup.AcceptVersionWarningsNewScripts     = false;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "new")
                    {
                        setup.AcceptVersionWarningsNewScripts = true;
                    }
                    else if (commandParams[PARAMKEYS_VERSIONWARN].ToLower() == "changed")
                    {
                        setup.AcceptVersionWarningsChangedScripts = true;
                    }
                    else
                    {
                        throw new Exception("The /" + PARAMKEYS_VERSIONWARN + " parameter must be set to 'all, none, new, or changed'.");
                    }
                    paramUICount++;
                }

                if (GetSetting(commandParams, PARAMKEYS_HELP, false))
                {
                    ShowHelp();
                    return;
                }

                //Try to drop database
                if (commandParams.Any(x => PARAMKEYS_DROP.Contains(x.Key)))
                {
                    var masterConnectionString = GetSetting(commandParams, PARAMKEYS_MASTERDB, string.Empty);
                    var dbname = commandParams.Where(x => PARAMKEYS_NEWNAME.Contains(x.Key)).Select(x => x.Value).FirstOrDefault();
                    if (commandParams.Count == 3 && !string.IsNullOrEmpty(masterConnectionString))
                    {
                        if (!DropDatabase(dbname, masterConnectionString))
                        {
                            throw new Exception("The database '" + dbname + "' could not dropped.");
                        }
                        System.Diagnostics.Debug.WriteLine("Database successfully dropped.");
                        return;
                    }
                    throw new Exception("Invalid drop database configuration.");
                }

                setup.ConnectionString       = GetSetting(commandParams, PARAMKEYS_APPDB, string.Empty);
                setup.MasterConnectionString = GetSetting(commandParams, PARAMKEYS_MASTERDB, string.Empty);
                if (GetSetting(commandParams, PARAMKEYS_UPGRADE, setup.IsUpgrade))
                {
                    setup.InstallStatus = InstallStatusConstants.Upgrade;
                }
                if (commandParams.Any(x => PARAMKEYS_CREATE.Contains(x.Key)))
                {
                    setup.InstallStatus = InstallStatusConstants.Create;
                }

                if (commandParams.Any(x => PARAMKEYS_UPGRADE.Contains(x.Key)) && commandParams.Any(x => PARAMKEYS_CREATE.Contains(x.Key)))
                {
                    throw new Exception("You cannot specify both the create and update action.");
                }
                if (commandParams.Count(x => PARAMKEYS_NEWNAME.Contains(x.Key)) > 1)
                {
                    throw new Exception("The new database name was specified more than once.");
                }
                if (commandParams.Count(x => PARAMKEYS_MASTERDB.Contains(x.Key)) > 1)
                {
                    throw new Exception("The master database connection string was specified more than once.");
                }
                if (commandParams.Count(x => PARAMKEYS_APPDB.Contains(x.Key)) > 1)
                {
                    throw new Exception("The connection string was specified more than once.");
                }

                //Determine if calling as a script generator
                if (commandParams.ContainsKey(PARAMKEYS_SCRIPT))
                {
                    var scriptAction = commandParams[PARAMKEYS_SCRIPT].ToLower();
                    switch (scriptAction)
                    {
                    case "versioned":
                    case "unversioned":
                    case "create":
                        break;

                    default:
                        throw new Exception("The script action must be 'create', 'versioned', or 'unversioned'.");
                    }

                    if (!commandParams.ContainsKey(PARAMKEYS_SCRIPTFILE))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter must be set for script generation.");
                    }

                    var dumpFile = commandParams[PARAMKEYS_SCRIPTFILE];
                    if (!IsValidFileName(dumpFile))
                    {
                        throw new Exception("The '" + PARAMKEYS_SCRIPTFILE + "' parameter is not valid.");
                    }

                    var fileCreate = true;
                    if (commandParams.ContainsKey(PARAMKEYS_SCRIPTFILEACTION) && (commandParams[PARAMKEYS_SCRIPTFILEACTION] + string.Empty) == "append")
                    {
                        fileCreate = false;
                    }

                    if (File.Exists(dumpFile) && fileCreate)
                    {
                        File.Delete(dumpFile);
                        System.Threading.Thread.Sleep(500);
                    }

                    switch (scriptAction)
                    {
                    case "versioned":
                        if (commandParams.ContainsKey(PARAMKEYS_DBVERSION))
                        {
                            if (!GeneratedVersion.IsValid(commandParams[PARAMKEYS_DBVERSION]))
                            {
                                throw new Exception("The '" + PARAMKEYS_DBVERSION + "' parameter is not valid.");
                            }

                            setup.Version = new GeneratedVersion(commandParams[PARAMKEYS_DBVERSION]);
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(setup.ConnectionString))
                            {
                                throw new Exception("Generation of versioned scripts requires a '" + PARAMKEYS_DBVERSION + "' parameter or valid connection string.");
                            }
                            else
                            {
                                var s = new nHydrateSetting();
                                s.Load(setup.ConnectionString);
                                setup.Version = new GeneratedVersion(s.dbVersion);
                            }
                        }

                        setup.InstallStatus = InstallStatusConstants.Upgrade;
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;

                    case "unversioned":
                        setup.InstallStatus = InstallStatusConstants.Upgrade;
                        setup.Version       = UpgradeInstaller._def_Version;
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;

                    case "create":
                        setup.InstallStatus = InstallStatusConstants.Create;
                        setup.Version       = new GeneratedVersion(-1, -1, -1, -1, -1);
                        File.AppendAllText(dumpFile, UpgradeInstaller.GetScript(setup));
                        break;
                    }

                    return;
                }

                //If we processed all parameters and they were UI then we need to show UI
                if ((paramUICount < commandParams.Count) || setup.SuppressUI)
                {
                    setup.NewDatabaseName = commandParams.Where(x => PARAMKEYS_NEWNAME.Contains(x.Key)).Select(x => x.Value).FirstOrDefault();
                    Install(setup);
                    return;
                }
            }

            UIInstall(setup);
        }
Esempio n. 32
0
        /// <summary>
        /// Helper function that creates the log file and attaches it
        /// </summary>
        /// <param name="path">The path to place the log file</param>
        private void SetupLogFileHelper( string path )
        {
            if( path != m_LogPath ) {
                m_LogPath = path;

                // Cleanup
                this.DetachLogger();

                // Create the FileDebugWriter
                if( !Directory.Exists( path ) )
                    Directory.CreateDirectory( path );
                // Create the log file without locking it and turning off buffering
                // NOTE: Stupid FileStream doesn't allow us to get rid of the buffering
                // completely, so even with buffer size set to 1 it still uses an 8-byte buffer
                Stream myDebugFile = new FileStream( path + "\\DEBUG_" + System.Environment.MachineName + "_" + System.DateTime.Now.Ticks.ToString() + ".log", FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 1 );
                this.FileDebugWriter = new System.Diagnostics.TextWriterTraceListener( myDebugFile );
                this.AttachLogger();
            }
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            DirectoryInfo d  = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            DirectoryInfo md = new DirectoryInfo(d.FullName + "\\Migrations");

            if (args.Length == 0)
            {
                Console.WriteLine("USAGE: Migrator.exe <target> [[to:<version>|tag:<tag>]|[up[:<steps>]|down[:<steps>]]] [trace:<true|false>]");
                return;
            }

            string target = args[0];
            ConnectionStringSettings cstr = ConfigurationManager.ConnectionStrings[target.Trim()];
            string resolvedTarget         = (cstr == null)?null:cstr.ConnectionString;

            if (resolvedTarget == null)
            {
                Console.WriteLine("\"" + target + "\" is not a valid target.");
                return;
            }

            string version  = null;
            string tag      = null;
            string provider = null;
            bool   trace    = false;

            for (int i = 1; i < args.Length; i++)
            {
                string[] parts = args[i].Split(':');
                if (parts.Length != 2 && parts[0] != "up" && parts[0] != "down" && parts[0] != "trace")
                {
                    Console.WriteLine("Invalid argument: \"" + args[i] + "\"");
                    return;
                }

                // parse specific arguments
                switch (parts[0])
                {
                case "to":
                    version = parts[1];
                    break;

                case "tag":
                    tag = parts[1];
                    break;

                case "p":
                    provider = parts[1];
                    break;

                case "trace":
                    trace = true;
                    break;

                case "up":
                    version = "+";
                    if (parts.Length > 1)
                    {
                        version += parts[1].Trim();
                    }
                    break;

                case "down":
                    version = "-";
                    if (parts.Length > 1)
                    {
                        version += parts[1].Trim();
                    }
                    break;

                default:
                    Console.WriteLine("Invalid command: \"" + parts[0] + ":\"");
                    return;
                }
                if (tag != null)
                {
                    version = null;
                }
            }

            // TODO: resolve other providers
            if (provider == null)
            {
                provider = MigSharp.ProviderNames.SqlServer2008;
            }

            System.IO.FileStream fs = null;
            if (trace)
            {
                string logfile = md.FullName + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".log";
                if (File.Exists(logfile))
                {
                    File.Delete(logfile);
                }
                fs = new FileStream(logfile, FileMode.CreateNew);
                System.Diagnostics.TextWriterTraceListener tl = new System.Diagnostics.TextWriterTraceListener(fs);
                System.Diagnostics.Trace.AutoFlush = true;
                System.Diagnostics.Trace.Listeners.Add(tl);
            }

            int cnt = 0;

            if (md.Exists)
            {
                string iMigration  = typeof(MigSharp.IMigration).FullName;
                string iRMigration = typeof(MigSharp.IReversibleMigration).FullName;

                foreach (FileInfo assem in md.GetFiles("*.dll"))
                {
                    Assembly a = Assembly.LoadFile(assem.FullName);

                    List <MigrationMeta> migs = new List <MigrationMeta>();
                    foreach (Type t in a.GetTypes())
                    {
                        if (t.GetInterface(iMigration) != null || t.GetInterface(iRMigration) != null)
                        {
                            MigrationMeta nm = new MigrationMeta();
                            nm.migrationClass = t.FullName;
                            nm.version        = Int64.Parse(t.Name.Replace("Migration", ""));

                            object[] attr = t.GetCustomAttributes(true);
                            foreach (object cAttr in attr)
                            {
                                if (cAttr is MigSharp.MigrationExportAttribute)
                                {
                                    MigSharp.MigrationExportAttribute mEa = (MigSharp.MigrationExportAttribute)cAttr;
                                    nm.tag    = mEa.Tag;
                                    nm.module = mEa.ModuleName;
                                    break;
                                }
                            }
                            migs.Add(nm);
                        }
                    }
                    if (migs.Count > 0)
                    {
                        migs.Sort();
                    }

                    // resolve version from Tag attribute
                    if (tag != null && version == null)
                    {
                        foreach (MigrationMeta mm in migs)
                        {
                            if (mm.tag != null && mm.tag == tag)
                            {
                                version = mm.version.ToString();
                                break;
                            }
                        }
                        if (version == null && tag != null)
                        {
                            Console.WriteLine("\"" + tag + "\" is not a valid tag.");
                            return;
                        }
                    }

                    // resolve version for incrementals
                    if (version != null && (version.StartsWith("+") || version.StartsWith("-")))
                    {
                        long current = 0;
                        int  dir     = (version.Substring(0, 1) == "+") ? 1 : -1;
                        version = (version.Remove(0, 1) == "") ? "1" : version.Remove(0, 1);
                        int offset = int.Parse(version) * dir;
                        version = null;
                        DbConnection dbc = null;
                        try
                        {
                            // load version table and determine current version
                            DbProviderFactory dbp = DbProviderFactories.GetFactory("System.Data.SqlClient");
                            dbc = dbp.CreateConnection();
                            dbc.ConnectionString = resolvedTarget;
                            dbc.Open();

                            DbCommand cmd = dbc.CreateCommand();
                            cmd.CommandText = "select 1 from sys.tables where name='MigSharp'";
                            object res = cmd.ExecuteScalar();
                            if (res != null)
                            {
                                cmd.CommandText = "select top 1 timestamp, module, tag from MigSharp order by timestamp desc";
                                DbDataReader dr = cmd.ExecuteReader();
                                while (dr.Read())
                                {
                                    current = dr.GetInt64(0);
                                }
                                dbc.Close();
                            }
                        }
                        catch (Exception exp)
                        {
                            if (dbc != null && dbc.State != ConnectionState.Closed)
                            {
                                dbc.Close();
                            }
                            LogMsg(exp, "Could not gather version info from target db!");
                            return;
                        }

                        int idx = offset - 1;
                        if (current > 0)
                        {
                            foreach (MigrationMeta mm in migs)
                            {
                                idx++;
                                if (mm.version == current)
                                {
                                    break;
                                }
                            }
                        }
                        if (idx < 0)
                        {
                            version = "0";
                        }
                        else
                        {
                            if (idx > migs.Count - 1)
                            {
                                idx = migs.Count - 1;
                            }
                            version = migs[idx].version.ToString();
                        }
                    }

                    // Start migration
                    Console.WriteLine("Starting Migration target:" + target + " version:" + (string)((version == null)?"latest":version) + " trace:" + trace.ToString() + " ...");
                    MigSharp.Migrator m = null;
                    MigSharp.MigrationOptions.SetSqlTraceLevel(System.Diagnostics.SourceLevels.All);
                    m = new MigSharp.Migrator(resolvedTarget, provider);

                    try
                    {
                        if (version == null)
                        {
                            m.MigrateAll(a);
                        }
                        else
                        {
                            m.MigrateTo(a, Convert.ToInt64(version));
                        }
                    }
                    catch (Exception exp)
                    {
                        LogMsg(exp, null);
                        return;
                    }
                    cnt++;

                    if (fs != null && trace)
                    {
                        System.Diagnostics.Trace.Flush();
                        fs.Close();
                    }
                }
            }
            if (cnt == 0)
            {
                Console.WriteLine("No valid Migrations found.");
            }
            else
            {
                Console.WriteLine("Migrations completed.");
            }
        }