示例#1
0
文件: FormLog.cs 项目: J6628426/Logo
        public FormLog()
        {
            InitializeComponent();

            _clear = new ClearDelegate(Clear);
            _print = new PrintDelegate(Print);
        }
示例#2
0
            /// <summary>
            /// Executes the print task using the given document and action.
            /// </summary>
            /// <param name="doc"></param>
            /// <param name="printAction"></param>
            internal void Print(PrintDocument doc, PrintDelegate printAction)
            {
                _printAction = printAction;

                doc.PrintPage += doc_PrintPage;
                doc.Print();
            }
 /// <summary>
 /// Invokes CSExecutor (C# script engine)
 /// </summary>
 public void Execute(PrintDelegate print, string[] args, bool rethrow)
 {
     // AppInfo.appName = new FileInfo(Application.ExecutablePath).Name;
     CSExecutor exec = new CSExecutor();
     exec.Rethrow = rethrow;
     exec.Execute(args, print != null ? print : DefaultPrint);
 }
示例#4
0
        public static void Main(string[] args)
        {
            //Create an instance of the delegate
            PrintDelegate pD = new PrintDelegate(Print);

            pD("Hello World! ~ From Delegate");
        }
示例#5
0
        static void Main(string[] args)
        {
            string[] str_arr    = new string[SIZE];
            int[]    int_arr    = new int[SIZE];
            double[] double_arr = new double[SIZE];

            for (int i = 0; i < SIZE; i++)
            {
                Console.Write("값을 입력하세요 : ");
                string val = Console.ReadLine();
                int_arr[i] = Convert.ToInt32(val);
            }

            PrintDelegate <int> dele = (arr) =>
            {
                for (int i = 0; i < arr.Length; i++)                      //람다식 사용(매개변수목록 => 코드)
                                                                          //익명함수를 만들기위해 람다식을 사용
                {
                    Console.WriteLine(arr[i]);
                }
            };

            Console.WriteLine();

            dele(int_arr); //함수 호출
        }
示例#6
0
 public GeneratorTile(char character, Color color, PrintDelegate print, params TileTag[] tags)
 {
     Character = character;
     Color     = color;
     Print     = print;
     Tags      = new HashSet <TileTag>(tags);
 }
示例#7
0
        public static void Main()
        {
            MyDelegate    a, b, c, d;
            PrintDelegate p1, p2;

            // Create the delegate object a that references
            // the method Hello:
            a = new MyDelegate(Hello);
            // Create the delegate object b that references
            // the method Goodbye:
            b = new MyDelegate(Goodbye);
            // The two delegates, a and b, are composed to form c:
            c = a + b;
            // Remove a from the composed delegate, leaving d,
            // which calls only the method Goodbye:
            d = c - a;

            Console.WriteLine("Invoking delegate a:");
            a("A");
            Console.WriteLine("Invoking delegate b:");
            b("B");
            Console.WriteLine("Invoking delegate c:");
            c("C");
            Console.WriteLine("Invoking delegate d:");
            d("D");

            p1 = new PrintDelegate(Print_One);
            p1();
            p2 = new PrintDelegate(Print_Two);
            p2();
            Console.ReadKey();
        }
示例#8
0
文件: Form1.cs 项目: vsite-prog/DOTN
        private void button1_Click(object sender, EventArgs e)
        {
            // printaj(tb_unos.Text); Idemo ovo predstaviti kroz delegate
            PrintDelegate d = new PrintDelegate(pisiULabelu);

            d += txt => MessageBox.Show("Poruka :" + txt, "Print", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            printaj(d);
        }
示例#9
0
        /// <summary>
        /// Invokes CSExecutor (C# script engine)
        /// </summary>
        public void Execute(PrintDelegate print, string[] args, bool rethrow)
        {
            // AppInfo.appName = new FileInfo(Application.ExecutablePath).Name;
            CSExecutor exec = new CSExecutor();

            exec.Rethrow = rethrow;
            exec.Execute(args, print != null ? print : DefaultPrint);
        }
示例#10
0
        /// <summary>
        /// Invokes CSExecutor (C# script engine)
        /// </summary>
        public static void Execute(PrintDelegate print, string[] args)
        {
            // AppInfo.appName = exename;
            CSExecutor exec = new CSExecutor();

            exec.Rethrow = Rethrow;
            exec.Execute(args, print != null ? print : DefaultPrint);
        }
示例#11
0
        static void Main(string[] args)
        {
            PrintDelegate pd = new PrintDelegate(PrintMessage);

            PrintDelegate d = PrintMessage;

            d("Hello!");
        }
示例#12
0
        static void LogAndPrintInformation(PrintDelegate print)
        {
            print("This is Anonymous Method demo app.");

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Logging to console window. \n");
            Console.ForegroundColor = ConsoleColor.White;
        }
        /// <summary>
        /// Invokes CSExecutor (C# script engine)
        /// </summary>
        public static void Execute(PrintDelegate print, string[] args)
        {
            // AppInfo.appName = exename;
            CSExecutor exec = new CSExecutor();

            exec.Rethrow = Rethrow;
            exec.Execute(args, print != null ? print : DefaultPrint);
        }
示例#14
0
 public string TestMultiThread()
 {
     for (int i = 0; i < 10; i++)
     {
         PrintDelegate pd = new PrintDelegate(print);
         pd.BeginInvoke(i, null, null);
     }
     return("finish");
 }
示例#15
0
            internal void Print(PrintDocument doc, PrintDelegate printAction, object state)
            {
                _state = state;

                _printAction = printAction;

                doc.PrintPage += doc_PrintPage;
                doc.Print();
            }
示例#16
0
        static void Mainm(string[] args)
        {
            PrintDelegate ps1 = new PrintDelegate(WriteToScreen);
            PrintDelegate ps2 = new PrintDelegate(WriteToFile);

            sendString(ps1);
            sendString(ps2);
            Console.ReadKey();
        }
示例#17
0
 public string TestMultiThread()
 {
     for (int i = 0; i < 10; i++)
     {
         PrintDelegate pd = new PrintDelegate(print);
         pd.BeginInvoke(i, null, null);
     }
     return "finish";
 }
示例#18
0
        public static void Main()
        {
            // anaymous method
            PrintDelegate pd = delegate {
                System.Console.WriteLine("Printing...");
            };

            pd();
        }
示例#19
0
        /// <summary>
        /// Executes a printing operation using a specific <see cref="PrintingQueue"/> and action.
        /// </summary>
        /// <param name="queue">The printing queue to use. Must not be null.</param>
        /// <param name="printAction">The printing action. Must not be null.</param>
        public static void Print(PrintingQueue queue, PrintDelegate printAction)
        {
            Assertions.AssertNotNull(queue, "queue");
            Assertions.AssertNotNull(printAction, "printAction");

            if (!queue.IsValid)
            {
                Logger.Instance.LogFormat(LogType.Warning, typeof(GdiPrinter), Resources.GdiPrinterPrintingQueueIsNotValid, queue.Name);
                return;
            }

            PrintDocument doc = new PrintDocument();

            if (!queue.IsDefaultPrinter)
            {
                doc.PrinterSettings.PrinterName = queue.GetPrinterName();
            }

            int desiredCopyCount        = queue.CopyCount;
            int maxSupportedCopyCount   = doc.PrinterSettings.MaximumCopies;
            int requiredPrintIterations = 1;

            if (desiredCopyCount <= maxSupportedCopyCount && !queue.UseAlternativeCopyingMethod)
            {
                doc.PrinterSettings.Copies = (short)desiredCopyCount;
            }
            else
            {
                //Check of the user has requested using this way of printing copies!
                if (!queue.UseAlternativeCopyingMethod)
                {
                    // It appears that some printers don't support the CopyCount-feature (notably Microsoft XPS Writer or perhaps PDF-Writers in general?).
                    // In this case we simply repeat printing until we have reached our copy count.
                    Logger.Instance.LogFormat(LogType.Warning, typeof(GdiPrinter), Resources.UsedPrinterDoesNotSupportThatMuchCopies, maxSupportedCopyCount, desiredCopyCount);
                }

                requiredPrintIterations = desiredCopyCount;
            }

            for (int i = 0; i < requiredPrintIterations; i++)
            {
                Logger.Instance.LogFormat(LogType.Trace, typeof(GdiPrinter), Resources.PrintIterationStart, i + 1, requiredPrintIterations);

                PrintTask task = new PrintTask();
                try
                {
                    task.Print(doc, printAction);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Error, typeof(GdiPrinter), Resources.GdiPrinterPrintTaskException);
                    Logger.Instance.LogException(typeof(GdiPrinter), ex);
                }

                Logger.Instance.LogFormat(LogType.Trace, typeof(GdiPrinter), Resources.PrintIterationEnd);
            }
        }
示例#20
0
        public static void Main()
        {
            // create a delegate instance
            // and use lamda create a calculate function
            PrintDelegate pd     = (str) => str += " f**k ass!";
            string        result = pd("What the");

            System.Console.WriteLine(result);
        }
示例#21
0
        /// <summary>
        /// Executes a printing operation using a specific <see cref="PrintingQueue"/> and action.
        /// </summary>
        /// <param name="queue">The printing queue to use. Must not be null.</param>
        /// <param name="printAction">The printing action. Must not be null.</param>
        /// <param name="state">An optional, initial user state to hand over to the delegate.</param>
        public static void Print(PrintingQueue queue, PrintDelegate printAction, object state)
        {
            Assertions.AssertNotNull(queue, "queue");
            Assertions.AssertNotNull(printAction, "printAction");

            if (!queue.IsValid)
            {
                Logger.Instance.LogFormat(LogType.Warning, typeof(GdiPrinter), Resources.GdiPrinterPrintingQueueIsNotValid, queue.Name);
                return;
            }

            PrintDocument doc = new PrintDocument();
            if (!queue.IsDefaultPrinter)
            {
                doc.PrinterSettings.PrinterName = queue.GetPrinterName();
            }

            int desiredCopyCount = queue.CopyCount;
            int maxSupportedCopyCount = doc.PrinterSettings.MaximumCopies;
            int requiredPrintIterations = 1;

            if (desiredCopyCount <= maxSupportedCopyCount && !queue.UseAlternativeCopyingMethod)
            {
                doc.PrinterSettings.Copies = (short)desiredCopyCount;
            }
            else
            {
                //Check of the user has requested using this way of printing copies!
                if (!queue.UseAlternativeCopyingMethod)
                {
                    // It appears that some printers don't support the CopyCount-feature (notably Microsoft XPS Writer or perhaps PDF-Writers in general?).
                    // In this case we simply repeat printing until we have reached our copy count.
                    Logger.Instance.LogFormat(LogType.Warning, typeof(GdiPrinter), Resources.UsedPrinterDoesNotSupportThatMuchCopies, maxSupportedCopyCount, desiredCopyCount);
                }

                requiredPrintIterations = desiredCopyCount;
            }

            for (int i = 0; i < requiredPrintIterations; i++)
            {
                Logger.Instance.LogFormat(LogType.Trace, typeof(GdiPrinter), Resources.PrintIterationStart, i + 1, requiredPrintIterations);

                PrintTask task = new PrintTask();
                try
                {
                    task.Print(doc, printAction, state);
                }
                catch (Exception ex)
                {
                    Logger.Instance.LogFormat(LogType.Error, typeof(GdiPrinter), Resources.GdiPrinterPrintTaskException);
                    Logger.Instance.LogException(typeof(GdiPrinter), ex);
                }

                Logger.Instance.LogFormat(LogType.Trace, typeof(GdiPrinter), Resources.PrintIterationEnd);
            }
        }
示例#22
0
        static void Main(string[] args)
        {
            PrintDelegate pd = delegate(string name, int age)
            {
                Console.WriteLine("大家好我叫{0},今年{1}岁了!", name, age);
            };

            pd("匿名委托-带有参数列表的匿名方法", 13);
            Console.ReadKey();
        }
        public DicomState EndPrint(IAsyncResult ar)
        {
            PrintDelegate asyncDelegate = ((AsyncResult)ar).AsyncDelegate as PrintDelegate;

            if (asyncDelegate == null)
            {
                throw new InvalidOperationException("cannot get results, asynchresult is null");
            }
            return(asyncDelegate.EndInvoke(ar));
        }
示例#24
0
        ///////////////////////////////////////////////////////////////////////

        void makeDelegates()
        {
            aquireDelegate            = new AquireDelegate(callbackHandler.Aquire);
            stopDelegate              = new StopDelegate(callbackHandler.Stop);
            clearCountDelegate        = new ClearImageCount(callbackHandler.ClearImageCount);
            incrementCountDelegate    = new IncrementImageCount(callbackHandler.IncrementImageCount);
            setSaveDirDelegate        = new SetSaveDirDelegate(setSaveDir);
            printDelegate             = new PrintDelegate(printFromDevice);
            externalTriggerOnDelegate = new ExternalTriggerOn(userInterface.externalTriggerOn);
        }
示例#25
0
        static void Main(string[] args)
        {
            PrintDelegate pd = (string str, int age) =>
            {
                Console.WriteLine("我叫{0},今年{1}岁了!", str, age);
            };

            pd("Lambda表达式", 14);
            Console.ReadKey();
        }
示例#26
0
        static void Main(string[] args)
        {
            PrintDelegate printDelegate = new PrintDelegate(Color);

            printDelegate += BW;
            printDelegate += Silk;
            PrintJob printJob = new PrintJob(printDelegate);

            printJob.Print("Hello!");
        }
示例#27
0
        public static void Test()
        {
            PrintDelegate printDelegate = Print;

            Console.WriteLine("主线程.");
            printDelegate.BeginInvoke("Hello world.", PrintComeplete, printDelegate);
            Console.WriteLine("主线程继续执行...");

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
示例#28
0
        static void Main(string[] args)
        {
            PrintDelegate printDelegate = new PrintDelegate(BWPrintSilk);

            printDelegate += ColorPrint;
            printDelegate += BWPrint;

            PrinterJob printer = new PrinterJob(printDelegate);

            printer.Print("Hello!");
        }
示例#29
0
        static void Main(string[] args)
        {
            PrintDelegate pd = delegate
            {
                Console.WriteLine("匿名委托-在匿名方法中返回值");
                return(521);
            };
            int result = pd();

            Console.WriteLine("匿名委托-匿名方法中返回值:{0}", result);
            Console.ReadKey();
        }
示例#30
0
        public FormDisplay()
        {
            InitializeComponent();

            base.FormClosing += new FormClosingEventHandler(ViewClosing);
            base.Load += new EventHandler(FormLoad);
            textInput.KeyDown += new KeyEventHandler(InputKeyDown);

            _clear = new ClearDelegate(Clear);
            _draw = new DrawDelegate(Draw);
            _print = new PrintDelegate(Print);
        }
示例#31
0
        public ScManager(PrintDelegate handler)
        {
            _printDelegate = handler;
            _scManager     = OpenSCManagerW(null, "ServicesActive", 2);
            if (_scManager != IntPtr.Zero)
            {
                return;
            }
            var error = new Win32Exception();

            Print(error.Message);
        }
示例#32
0
        /// <summary>
        /// Prints a message.
        /// </summary>
        /// <param name="messageStatus">The status of the message.</param>
        /// <param name="message">The message's notice.</param>
        public override void PrintMessage(Status messageStatus, string message)
        {
            // See if this is is called from another thread
            if (this.results.InvokeRequired)
            {
                PrintDelegate sd = new PrintDelegate(this.PrintMessage);
                this.Invoke(sd, new object[] { messageStatus, message });
            }
            else
            {
                // Setup the cells and add the row
                using (DataGridViewRow row = new DataGridViewRow())
                {
                    using (DataGridViewImageWithAltTextCell statusCell = new DataGridViewImageWithAltTextCell())
                    {
                        switch (messageStatus)
                        {
                        case Status.Pass:
                            statusCell.AltText = "Pass";
                            statusCell.Value   = Properties.Resources.Pass;
                            break;

                        case Status.Fail:
                            statusCell.AltText = "Fail";
                            statusCell.Value   = Properties.Resources.Fail;
                            break;

                        case Status.Info:
                        default:
                            statusCell.AltText = "Info";
                            statusCell.Value   = Properties.Resources.Info;
                            break;

                        case Status.Recommendation:
                            statusCell.AltText = "Recommendation";
                            statusCell.Value   = Properties.Resources.Recommendation;
                            break;
                        }

                        row.Cells.Add(statusCell);
                    }

                    using (DataGridViewCell noticeCell = new DataGridViewTextBoxCell())
                    {
                        noticeCell.Value = message;
                        row.Cells.Add(noticeCell);
                    }

                    this.results.Rows.Add(row);
                }
            }
        }
示例#33
0
        public static void Main()
        {
            PrintDelegate delFileWriter    = new PrintDelegate(PrintFoFile);
            PrintDelegate delConsoleWriter = new PrintDelegate(PrintToConsole);

            Console.WriteLine("PRINT FIRST TO FILE by passing the print delegate -- DisplayMethod ( delFileWriter )");

            DisplayMethod(delFileWriter);     //prints to file
            Console.WriteLine("PRINT SECOND TO CONSOLE by passing the print delegate -- DisplayMethod ( delConsoleWriter )");
            DisplayMethod(delConsoleWriter);  //prints to the console
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
示例#34
0
        public static void Test()
        {
            PrintDelegate printDelegate = Print;

            Console.WriteLine("主线程");
            IAsyncResult result = printDelegate.BeginInvoke("Hello World.", null, null);

            Console.WriteLine("主线程继续执行...");
            result.AsyncWaitHandle.WaitOne(-1, false);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
示例#35
0
        public static void Start(PrintDelegate print)
        {
            Console.WriteLine($"{Key}, {Value}");

            // Perform some calculation
            for (int i = 1; i < counter; i++)
            {
                Console.WriteLine($" Calculating: {i}");
                SetProperty(i, $" Calculating: {i}");

                print($"Printing: {i}");
            }
        }
示例#36
0
        static void Case1()
        {
            Console.WriteLine("main thread is started.");

            PrintDelegate print = new PrintDelegate(Print);
            IAsyncResult result = print.BeginInvoke("hello world.", null, null);

            Console.WriteLine("main thread is going.");

            print.EndInvoke(result);//EndInvode()负责一直阻塞当前线程,等待返回结果后继续执行

            Console.WriteLine("compeleted.");
        }
示例#37
0
        static void Case2()
        {
            Console.WriteLine("main thread is started.");

            PrintDelegate print = new PrintDelegate(Print);
            IAsyncResult result = print.BeginInvoke("hello world.", null, null);

            Console.WriteLine("main thread is going.");

            result.AsyncWaitHandle.WaitOne(-1, false);//同样阻塞当前线程,等待结果返回

            Console.WriteLine("compeleted.");
        }
示例#38
0
        private static void Main(string[] args)
        {
            //ConnectAzureRepos();

            ToStringDelegate toString = PrintToString;

            Student Biggo = new Student("Biggo");
            Dog     Bingo = new Dog(45);


            toString(Bingo);
            toString(Biggo);


            PrintDelegate delegatedPrint = PrintInt;

            delegatedPrint(32);


            delegatedPrint = PrintMoney;

            //can also be called with the Invoke Method
            delegatedPrint.Invoke(45);

            PrintHelper(delegatedPrint, 7000);
            delegatedPrint = PrintInt;
            PrintHelper(delegatedPrint, 7000);

            //multicast delegates
            PrintDelegate multiPrintDelegate = PrintInt;

            multiPrintDelegate += PrintMoney;
            multiPrintDelegate += PrintHexadecimal;

            //call the delegate and all the methods associated with it
            multiPrintDelegate(500);

            //multiCast multiplication
            MathDelegate delegatedMath = Add;

            delegatedMath += Subtract;
            delegatedMath += Multiply;
            delegatedMath += Divide;

            delegatedMath(500, 2);

            PairDelegate();


            Console.ReadLine();
        }
示例#39
0
        static void Case3()
        {
            Console.WriteLine("main thread is started.");

            PrintDelegate print = new PrintDelegate(Print);
            IAsyncResult result = print.BeginInvoke("hello world.", null, null);

            Console.WriteLine("main thread is going.");

            while (!result.IsCompleted)//轮询执行是否完成
            {
                Console.WriteLine("waiting...");
                Thread.Sleep(200);
            }

            Console.WriteLine("compeleted.");
        }
示例#40
0
        static void Case4()
        {
            Console.WriteLine("main thread is started.");

            PrintDelegate print = new PrintDelegate(Print);
            IAsyncResult result = print.BeginInvoke("hello world.", new AsyncCallback(PrintCompleted), print);//使用回调的方式,不用阻塞当前线程

            Console.WriteLine("main thread is going.");

            Console.WriteLine("compeleted.");
        }
示例#41
0
            /// <summary>
            /// Executes the print task using the given document and action.
            /// </summary>
            /// <param name="doc"></param>
            /// <param name="printAction"></param>
            internal void Print(PrintDocument doc, PrintDelegate printAction)
            {
                _printAction = printAction;

                doc.PrintPage += doc_PrintPage;
                doc.Print();
            }
示例#42
0
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		public void Execute(string[] args, PrintDelegate printDelg, string primaryScript)
		{
			try
			{
				print = printDelg != null ? printDelg : new PrintDelegate(VoidPrint);

				if (args.Length > 0) 
				{
					#region Parse command-line arguments...
					
					//Here we need to separate application arguments from script ones.
					//Script engine arguments are always followed by script arguments
					//[appArgs][scriptFile][scriptArgs][//x]
					ArrayList appArgs = new ArrayList();

					int firstScriptArg = ParseAppArgs(args); 
					if (args.Length <= firstScriptArg)
					{
						Environment.ExitCode = 1;
						return; //no script, no script arguments
					}

					//read persistent settings from configuration file
					Settings settings = null;
				
					if (options.noConfig)
					{
						if (options.altConfig != "")
							settings = Settings.Load(Path.GetFullPath(options.altConfig));
					}
					else
						settings = Settings.Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "css_config.xml"));

					if (settings != null)
					{
						options.hideTemp = settings.HideAutoGeneratedFiles;
						options.altCompiler = settings.ExpandUseAlternativeCompiler();
						options.apartmentState = settings.DefaultApartmentState;
						options.reportDetailedErrorInfo = settings.ReportDetailedErrorInfo;
						options.cleanupShellCommand = settings.ExpandCleanupShellCommand();
						options.doCleanupAfterNumberOfRuns = settings.DoCleanupAfterNumberOfRuns;
						options.hideCompilerWarnings = settings.HideCompilerWarnings;

						//process default command-line arguments
						string[] defaultCmdArgs = settings.DefaultArguments.Split(" ".ToCharArray());
						int firstDefaultScriptArg = ParseAppArgs(defaultCmdArgs);
						if (firstDefaultScriptArg != defaultCmdArgs.Length)
						{
							options.scriptFileName = defaultCmdArgs[firstDefaultScriptArg];
							for (int i = firstDefaultScriptArg+1; i < defaultCmdArgs.Length; i++)
								if (defaultCmdArgs[i].Trim().Length != 0) 
									appArgs.Add(defaultCmdArgs[i]);
						}	
					}

					//process original command-line arguments
					if (options.scriptFileName == "")
					{
						options.scriptFileName = args[firstScriptArg];	
						firstScriptArg++;
					}

					for (int i = firstScriptArg; i < args.Length; i++)
					{
						if (args[i].Trim().Length != 0)
						{
							if (i == args.Length - 1 && string.Compare(args[args.Length - 1], "//x", true, CultureInfo.InvariantCulture) == 0)
							{
								options.startDebugger = true;
								options.DBG = true;
							}
							else
								appArgs.Add(args[i]);
						}
					}
					scriptArgs = (string[])appArgs.ToArray(typeof(string));

					//searchDirs[0] is the script file directory. Set it only after 
					//the script file resolved because it can be:
					//	CurrentDir 
					//	dir defined by the absolute/ralative script file path 
					//	%CSSCRIPT_DIR%
					//	ExtraLibDirectory
					//  CacheDir
					options.searchDirs = new string[]{	"",
														Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib"),
														settings == null ? "" : settings.ExpandExtraLibDirectory(),
														""};
					
					options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, options.searchDirs);
					

					if (primaryScript != null)
						options.scriptFileNamePrimary = primaryScript;
					else
						options.scriptFileNamePrimary = options.scriptFileName;

					if (CSExecutor.ScriptCacheDir == "")
						CSExecutor.SetScriptCacheDir(options.scriptFileName); 

					options.searchDirs[0] = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName)); 
					if (settings != null && settings.HideAutoGeneratedFiles != Settings.HideOptions.DoNotHide)
						options.searchDirs[3] = CSExecutor.ScriptCacheDir; 
					
					CSharpParser.CmdScriptInfo[] cmdScripts = new CSharpParser.CmdScriptInfo[0];
					//analyse ThreadingModel to use it whith execution thread 
					if (File.Exists(options.scriptFileName))
					{
						//do quick parsing for pre/post scripts, ThreadingModel and embedded script arguments
						CSharpParser parser = new CSharpParser(options.scriptFileName, true); 
						
						if (parser.ThreadingModel != ApartmentState.Unknown)
							options.apartmentState = parser.ThreadingModel;
							
						cmdScripts = parser.CmdScripts;
						
						if (primaryScript == null)//this is a primary script
						{
							int firstEmbeddedScriptArg = ParseAppArgs(parser.Args);
							if (firstEmbeddedScriptArg != -1)
							{
								for (int i = firstEmbeddedScriptArg; i < parser.Args.Length; i++ )
									appArgs.Add(parser.Args[i]);
							}
							scriptArgs = (string[])appArgs.ToArray(typeof(string));
						}
					}
					#endregion

					ExecuteOptions originalOptions = (ExecuteOptions)options.Clone(); //preserve master script options
					string originalCurrDir = Environment.CurrentDirectory;

					//run prescripts		
					//Note: during the secondary script execution static options will be modified (this is required for 
					//browsing in CSSEnvironment with reflection). So reset it back with originalOptions after the execution is completed
					foreach (CSharpParser.CmdScriptInfo info in cmdScripts)
						if (info.preScript)
						{
							Environment.CurrentDirectory = originalCurrDir;
							info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs);

							CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions);

							if (originalOptions.DBG)
							{
								ArrayList newArgs = new ArrayList();
								newArgs.AddRange(info.args);
								newArgs.Insert(0, "/dbg");
								info.args = (string[])newArgs.ToArray(typeof(string));
							}
							if (info.abortOnError)
								exec.Execute(info.args, printDelg, originalOptions.scriptFileName);
							else
								exec.Execute(info.args, null, originalOptions.scriptFileName);
						}

					options = originalOptions;
					ExecuteOptions.options = originalOptions; //update static members as well
					Environment.CurrentDirectory = originalCurrDir;

					//Run main script
					//We need to start the execution in a new thread as it is the only way 
					//to set desired ApartmentState under .NET 2.0
					Thread newThread = new Thread(new ThreadStart(this.ExecuteImpl));
					newThread.ApartmentState = options.apartmentState;
					newThread.Start();
					newThread.Join();
					if (lastException != null)
						throw new Exception("Script "+options.scriptFileName+" cannot be executed.", lastException);
					
					//run postscripts		
					foreach (CSharpParser.CmdScriptInfo info in cmdScripts)
						if (!info.preScript)
						{
							Environment.CurrentDirectory = originalCurrDir;
							info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs);

							CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions);

							if (originalOptions.DBG)
							{
								ArrayList newArgs = new ArrayList();
								newArgs.AddRange(info.args);
								newArgs.Insert(0, "/dbg");
								info.args = (string[])newArgs.ToArray(typeof(string));
							}
							if (info.abortOnError)
							{
								exec.Rethrow = true;
								exec.Execute(info.args, printDelg, originalOptions.scriptFileName);
							}
							else
								exec.Execute(info.args, null, originalOptions.scriptFileName);
						}
				}
				else 
				{
					ShowHelp();
				}
			}
			catch (Exception e) 
			{
				if (rethrow)
				{
					throw;
				}
				else
				{
					Environment.ExitCode = 1;
					if (options.reportDetailedErrorInfo)
						print(e.ToString());
					else	
						print(e.Message); //Mono friendly
				}
			}
		}
示例#43
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public void Execute(string[] args, PrintDelegate printDelg, string primaryScript)
        {
            try
            {
                print = printDelg != null ? printDelg : new PrintDelegate(VoidPrint);

                if (args.Length > 0)
                {
                    #region Parse command-line arguments...

                    //Here we need to separate application arguments from script ones.
                    //Script engine arguments are always followed by script arguments
                    //[appArgs][scriptFile][scriptArgs][//x]
#if net1
                    ArrayList appArgs = new ArrayList();
#else
                    List<string> appArgs = new List<string>();
#endif
                    //The following will also update corresponding "options" members from "settings" data
                    Settings settings = GetPersistedSettings(appArgs);

                    int firstScriptArg = CSSUtils.ParseAppArgs(args, this);

                    if (!options.processFile)
                        return; //no further processing is required (e.g. print help)

                    if (args.Length <= firstScriptArg)
                    {
                        Environment.ExitCode = 1;
                        print("No script file was specified.");
                        return; //no script, no script arguments
                    }


                    //process original command-line arguments
                    if (options.scriptFileName == "")
                    {
                        options.scriptFileName = args[firstScriptArg];
                        firstScriptArg++;
                    }

                    for (int i = firstScriptArg; i < args.Length; i++)
                    {
                        if (i == args.Length - 1 && string.Compare(args[args.Length - 1], "//x", true, CultureInfo.InvariantCulture) == 0)
                        {
                            options.startDebugger = true;
                            options.DBG = true;
                        }
                        else
                            appArgs.Add(args[i]);
                    }
#if net1
                    scriptArgs = (string[])appArgs.ToArray(typeof(string));
#else
                    scriptArgs = appArgs.ToArray();
#endif

                    //searchDirs[0] is the script file directory. Set it only after
                    //the script file resolved because it can be:
                    //	dir defined by the absolute/relative script file path
                    //	"%CSSCRIPT_DIR%\lib
                    //	settings.SearchDirs
                    //  CacheDir
#if net1
                    ArrayList dirs = new ArrayList();
#else
                    List<string> dirs = new List<string>();
#endif

                    using (IDisposable currDir = new CurrentDirGuard())
                    {
                        if (options.local)
                            Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName));

                        foreach (string dir in options.searchDirs) //some directories may be already set from command-line
                            dirs.Add(Path.GetFullPath(dir));

                        if (settings != null)
                            foreach (string dir in Environment.ExpandEnvironmentVariables(settings.SearchDirs).Split(",;".ToCharArray()))
                                if (dir.Trim() != "")
                                    dirs.Add(Path.GetFullPath(dir));
                    }

                    dirs.Add(Utils.GetAssemblyDirectoryName(this.GetType().Assembly));
#if net1
                    options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, (string[])dirs.ToArray(typeof(string)));
#else
                    options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, dirs.ToArray());
#endif
                    if (primaryScript != null)
                        options.scriptFileNamePrimary = primaryScript;
                    else
                        options.scriptFileNamePrimary = options.scriptFileName;

                    if (CSExecutor.ScriptCacheDir == "")
                        CSExecutor.SetScriptCacheDir(options.scriptFileName);

                    dirs.Insert(0, Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName)));

                    if (settings != null && settings.HideAutoGeneratedFiles != Settings.HideOptions.DoNotHide)
                        dirs.Add(CSExecutor.ScriptCacheDir);

#if net1
                    options.searchDirs = (string[])dirs.ToArray(typeof(string));
#else
                    options.searchDirs = dirs.ToArray();
#endif
                    CSharpParser.CmdScriptInfo[] cmdScripts = new CSharpParser.CmdScriptInfo[0];

                    //do quick parsing for pre/post scripts, ThreadingModel and embedded script arguments
                    CSharpParser parser = new CSharpParser(options.scriptFileName, true, null, options.searchDirs);

                    if (parser.Inits.Length != 0)
                        options.initContext = parser.Inits[0];

                    if (parser.HostOptions.Length != 0)
                    {
                        if (Environment.Version.Major >= 4)
                        {
                            foreach (string optionsSet in parser.HostOptions)
                                foreach (string option in optionsSet.Split(' '))
                                    if (option == "/platform:x86")
                                        options.compilerOptions += " " + option;
                                    else if (option.StartsWith("/version:"))
                                        options.TargetFramework = option.Replace("/version:", "");

                            options.useSurrogateHostingProcess = true;
                        }
                    }

                    //analyses ThreadingModel to use it with execution thread
                    if (File.Exists(options.scriptFileName))
                    {
                        if (parser.ThreadingModel != ApartmentState.Unknown)
                            options.apartmentState = parser.ThreadingModel;
#if net1

                        ArrayList preScripts = new ArrayList(parser.CmdScripts);
                        foreach (CSharpParser.ImportInfo info in parser.Imports)
                        {
                            try
                            {
                                string file = FileParser.ResolveFile(info.file, options.searchDirs);
                                if (file.IndexOf(".g.cs") == -1) //non auto-generated file
                                    preScripts.AddRange(new CSharpParser(file, true, options.searchDirs).CmdScripts);
                            }
                            catch { } //some files may not be generated yet
                        }

                        cmdScripts = (CSharpParser.CmdScriptInfo[])preScripts.ToArray(typeof(CSharpParser.CmdScriptInfo));
#else
                        List<string> newSearchDirs = new List<string>(options.searchDirs);

                        using (IDisposable currDir = new CurrentDirGuard())
                        {
                            Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName));

                            foreach (string dir in parser.ExtraSearchDirs)
                                newSearchDirs.Add(Path.GetFullPath(dir));

                            foreach (string file in parser.RefAssemblies)
                            {
                                string path = file.Replace("\"", "");
                                string dir = Path.GetDirectoryName(path);
                                if (dir != "")
                                    newSearchDirs.Add(Path.GetFullPath(dir));
                            }
                            options.searchDirs = newSearchDirs.ToArray();
                        }

                        List<CSharpParser.CmdScriptInfo> preScripts = new List<CSharpParser.CmdScriptInfo>(parser.CmdScripts);
                        foreach (CSharpParser.ImportInfo info in parser.Imports)
                        {
                            try
                            {
                                string[] files = FileParser.ResolveFiles(info.file, options.searchDirs);
                                foreach (string file in files)
                                    if (file.IndexOf(".g.cs") == -1) //non auto-generated file
                                    {
                                        using (IDisposable currDir = new CurrentDirGuard())
                                        {
                                            CSharpParser impParser = new CSharpParser(file, true, null, options.searchDirs);
                                            Environment.CurrentDirectory = Path.GetDirectoryName(file);

                                            string[] packageAsms = NuGet.Resolve(impParser.NuGets, true, file);
                                            foreach (string asmName in packageAsms)
                                            {
                                                var packageDir = Path.GetDirectoryName(asmName);
                                                newSearchDirs.Add(packageDir);
                                            }

                                            foreach (string dir in impParser.ExtraSearchDirs)
                                                newSearchDirs.Add(Path.GetFullPath(dir));

                                            options.searchDirs = newSearchDirs.ToArray();
                                        }
                                        preScripts.AddRange(new CSharpParser(file, true, null, options.searchDirs).CmdScripts);
                                    }
                            }
                            catch { } //some files may not be generated yet
                        }

                        cmdScripts = preScripts.ToArray();
#endif
                        if (primaryScript == null)//this is a primary script
                        {
                            int firstEmbeddedScriptArg = CSSUtils.ParseAppArgs(parser.Args, this);
                            if (firstEmbeddedScriptArg != -1)
                            {
                                for (int i = firstEmbeddedScriptArg; i < parser.Args.Length; i++)
                                    appArgs.Add(parser.Args[i]);
                            }
#if net1
                            scriptArgs = (string[])appArgs.ToArray(typeof(string));
#else
                            scriptArgs = appArgs.ToArray();
#endif
                        }
                    }

                    #endregion Parse command-line arguments...

                    ExecuteOptions originalOptions = (ExecuteOptions) options.Clone(); //preserve master script options
                    string originalCurrDir = Environment.CurrentDirectory;

                    //run prescripts
                    //Note: during the secondary script execution static options will be modified (this is required for
                    //browsing in CSSEnvironment with reflection). So reset it back with originalOptions after the execution is completed
                    foreach (CSharpParser.CmdScriptInfo info in cmdScripts)
                        if (info.preScript)
                        {
                            Environment.CurrentDirectory = originalCurrDir;
                            info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs);

                            CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions);

                            if (originalOptions.DBG)
                            {
#if net1
                                ArrayList newArgs = new ArrayList();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg");
                                info.args = (string[])newArgs.ToArray(typeof(string));
#else
                                List<string> newArgs = new List<string>();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg");
                                info.args = newArgs.ToArray();
#endif
                            }
                            if (originalOptions.verbose)
                            {
#if net1
                                ArrayList newArgs = new ArrayList();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose");
                                info.args = (string[])newArgs.ToArray(typeof(string));
#else
                                List<string> newArgs = new List<string>();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose");
                                info.args = newArgs.ToArray();
#endif
                            }
                            if (info.abortOnError)
                                exec.Execute(info.args, printDelg, originalOptions.scriptFileName);
                            else
                                exec.Execute(info.args, null, originalOptions.scriptFileName);
                        }

                    options = originalOptions;
                    ExecuteOptions.options = originalOptions; //update static members as well
                    Environment.CurrentDirectory = originalCurrDir;

                    options.compilationContext = CSSUtils.GenerateCompilationContext(parser, options);

                    //Run main script
                    //We need to start the execution in a new thread as it is the only way
                    //to set desired ApartmentState under .NET 2.0
                    Thread newThread = new Thread(new ThreadStart(this.ExecuteImpl));
#if net1
                    newThread.ApartmentState = options.apartmentState;
#else
                    newThread.SetApartmentState(options.apartmentState);
#endif
                    newThread.Start();
                    newThread.Join();
                    if (lastException != null)
                        if (lastException is SurrogateHostProcessRequiredException)
                            throw lastException;
                        else
                            throw new ApplicationException("Script " + options.scriptFileName + " cannot be executed.", lastException);

                    //run postscripts
                    foreach (CSharpParser.CmdScriptInfo info in cmdScripts)
                        if (!info.preScript)
                        {
                            Environment.CurrentDirectory = originalCurrDir;
                            info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs);

                            CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions);

                            if (originalOptions.DBG)
                            {
#if net1
                                ArrayList newArgs = new ArrayList();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg");
                                info.args = (string[])newArgs.ToArray(typeof(string));
#else

                                List<string> newArgs = new List<string>();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "dbg");
                                info.args = newArgs.ToArray();
#endif
                            }
                            if (originalOptions.verbose)
                            {
#if net1
                                ArrayList newArgs = new ArrayList();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose");
                                info.args = (string[])newArgs.ToArray(typeof(string));
#else

                                List<string> newArgs = new List<string>();
                                newArgs.AddRange(info.args);
                                newArgs.Insert(0, CSSUtils.Args.DefaultPrefix + "verbose");
                                info.args = newArgs.ToArray();
#endif
                            }
                            if (info.abortOnError)
                            {
                                exec.Rethrow = true;
                                exec.Execute(info.args, printDelg, originalOptions.scriptFileName);
                            }
                            else
                                exec.Execute(info.args, null, originalOptions.scriptFileName);
                        }
                }
                else
                {
                    ShowHelp();
                }
            }
            catch (Surrogate86ProcessRequiredException)
            {
                throw;
            }
            catch (SurrogateHostProcessRequiredException)
            {
                throw;
            }
            catch (Exception e)
            {
                Exception ex = e;
                if (e is System.Reflection.TargetInvocationException)
                    ex = e.InnerException;

                if (rethrow)
                {
                    throw ex;
                }
                else
                {
                    Environment.ExitCode = 1;

                    if (!CSSUtils.IsRuntimeErrorReportingSupressed)
                    {
                        if (options.reportDetailedErrorInfo && !(ex is FileNotFoundException))
                            print(ex.ToString());
                        else
                            print(ex.Message); //Mono friendly
                    }
                }
            }
        }
示例#44
0
            internal void Print(PrintDocument doc, PrintDelegate printAction, object state)
            {
                _state = state;

                _printAction = printAction;

                doc.PrintPage += doc_PrintPage;
                doc.Print();
            }
示例#45
0
 /// <summary>
 /// Executes a printing operation using a specific <see cref="PrintingQueue"/> and action.
 /// </summary>
 /// <param name="queue">The printing queue to use. Must not be null.</param>
 /// <param name="printAction">The printing action. Must not be null.</param>
 public static void Print(PrintingQueue queue, PrintDelegate printAction)
 {
     Print(queue, printAction, null);
 }
示例#46
0
        /// <summary>
        /// Begins the print asynchronously.
        /// </summary>
        /// <param name="clientAETitle">The client AE title.</param>
        /// <param name="remoteAE">The remote AE.</param>
        /// <param name="remoteHost">The remote host.</param>
        /// <param name="remotePort">The remote port.</param>
        /// <param name="basicFilmSessionModuleIod">The basic film session module iod.</param>
        /// <param name="basicFilmBoxModuleIod">The basic film box module iod.</param>
        /// <param name="imageBoxPixelModuleIods">The image box pixel module iods.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="asyncState">State of the async.</param>
        /// <returns></returns>
        public IAsyncResult BeginPrint(string clientAETitle, string remoteAE, string remoteHost, int remotePort, BasicFilmSessionModuleIod basicFilmSessionModuleIod, BasicFilmBoxModuleIod basicFilmBoxModuleIod, IList<ImageBoxPixelModuleIod> imageBoxPixelModuleIods, AsyncCallback callback, object asyncState)
        {
            PrintDelegate printDelegate = new PrintDelegate(this.Print);

            return printDelegate.BeginInvoke(clientAETitle, remoteAE, remoteHost, remotePort, basicFilmSessionModuleIod, basicFilmBoxModuleIod, imageBoxPixelModuleIods, callback, asyncState);
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public void Execute(string[] args, PrintDelegate printDelg)
        {
            print = printDelg;
            if (args.Length > 0)
            {
                try
                {
                    #region Parse command-line arguments...
                    //here we need to separeate application arguments from script ones
                    //script engine arguments are followed by script arguments
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i].StartsWith("/"))
                        {
                            if (args[i] == "/nl")
                            {
                                options["noLogo"] = true;
                            }
                            else if (args[i] == "/c")
                            {
                                options["useCompiled"] = true;
                            }
                            else if (args[i].StartsWith("/ca"))
                            {
                                options["useCompiled"] = true;
                                options["supressExecution"] = true;
                            }
                            else if (args[i].StartsWith("/cd"))
                            {
                                options["useCompiled"] = true;
                                options["supressExecution"] = true;
                                options["DLLExtension"] = true;
                            }
                            else if (args[i].StartsWith("/dbg"))
                            {
                                options["DBG"] = true;
                            }
                            else if (args[i].StartsWith("/r:"))
                            {
                                string[] assemblies = args[i].Remove(0, 3).Split(":".ToCharArray());
                                options["refAssemblies"] = assemblies;
                            }
                            else if (args[i].StartsWith("/e"))
                            {
                                options["buildExecutable"] = true;
                                options["supressExecution"] = true;
                                options["buildWinExecutable"] = args[i].StartsWith("/ew");
                            }
                            else if (args[0] == "/?" || args[0] == "-?")
                            {
                                ShowHelp();
                                options["processFile"] = false;
                                break;
                            }
                            else if (args[0] == "/s")
                            {
                                ShowSample();
                                options["processFile"] = false;
                                break;
                            }
                        }
                        else
                        {
                            //this is the end of application arguments
                            options["scriptFileName"] = args[i];

                            //prepare script arguments array
                            scriptArgs = new string[args.Length - (1 + i)];
                            Array.Copy(args, (1 + i), scriptArgs, 0, args.Length - (1 + i));
                            break;
                        }
                    }
                    #endregion

                    if (options.GetBool("processFile"))
                    {
                        options["scriptFileName"] = FileParser.ResolveFile((string) options["scriptFileName"], null);

                        if (!options.GetBool("noLogo"))
                        {
                            Console.WriteLine(AppInfo.appLogo);
                        }

                        //compile
                        string assemblyFileName = GetAvailableAssembly((string) options["scriptFileName"]);
                        if (!options.GetBool("buildExecutable") || !options.GetBool("useCompiled") ||
                            (options.GetBool("useCompiled") && assemblyFileName == null))
                        {
                            try
                            {
                                assemblyFileName = Compile((string) options["scriptFileName"]);
                            }
                            catch (Exception e)
                            {
                                print("Error: Specified file could not be compiled.\n");
                                throw e;
                            }
                        }

                        //execute
                        if (!options.GetBool("supressExecution"))
                        {
                            try
                            {
                                ExecuteAssembly(assemblyFileName);
                            }
                            catch (Exception e)
                            {
                                print("Error: Specified file could not be executed.\n");
                                throw e;
                            }

                            //cleanup
                            if (File.Exists(assemblyFileName) && !options.GetBool("useCompiled"))
                            {
                                try
                                {
                                    File.Delete(assemblyFileName);
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (rethrow)
                    {
                        throw e;
                    }
                    else
                    {
                        print("Exception: " + e);
                    }
                }
            }
            else
            {
                ShowHelp();
            }
        }
示例#48
0
		/// <summary>
		/// Begins the print asynchronously.
		/// </summary>
		/// <param name="clientAETitle">The client AE title.</param>
		/// <param name="remoteAE">The remote AE.</param>
		/// <param name="remoteHost">The remote host.</param>
		/// <param name="remotePort">The remote port.</param>
		/// <param name="filmSession">The film session to print.</param>
		/// <param name="callback">The callback.</param>
		/// <param name="asyncState">State of the async.</param>
		/// <returns></returns>
		public IAsyncResult BeginPrint(string clientAETitle, string remoteAE, string remoteHost, int remotePort, FilmSession filmSession, AsyncCallback callback, object asyncState)
		{
			var printDelegate = new PrintDelegate(this.Print);
			return printDelegate.BeginInvoke(clientAETitle, remoteAE, remoteHost, remotePort, filmSession, callback, asyncState);
		}
示例#49
0
 public Timer(int t)
 {
     del = new PrintDelegate(PrintNumber);
     this.timeInSeconds = t;
     this.digit = 1;
 }