示例#1
0
        static void Main(string[] args)
        {
            CommandLineArgs parsedArgs = new CommandLineArgs();
            bool ok = CommandLine.Parser.Default.ParseArguments(args, parsedArgs);

            if (!ok)
            {
                HelpText help = HelpText.AutoBuild(parsedArgs);
                throw new Exception(string.Format("Invalid command line args: {0}", help.ToString()));
            }

            if (parsedArgs.TopOfHour)
            {
                //wait until the top of the hour to start
                TimeSpan ts = TimeUntilNextHour();
                Console.WriteLine("waiting for " + ts);
                Thread.Sleep(ts);
            }

            MainService service = GetService(parsedArgs.Username, parsedArgs.Password);
            PreCacher cacher = new PreCacher(service);

            while (true)
            {
                //cache the last hour of changes
                DateTime now = DateTime.Now;
                DateTime start = GetDateTimeToHour(now.AddHours(-1));
                DateTime end = GetDateTimeToHour(now);
                cacher.CacheData(parsedArgs.VendorID, parsedArgs.JobID, start, end);

                //wait until the top of the next hour
                Thread.Sleep(TimeUntilNextHour());
                //Thread.Sleep(parsedArgs.RepeatMin * 60 * 1000);
            }
        }
        public ViewLabels()
        {
            _labelTemplateManager = FirstFloor.ModernUI.App.App.Container.GetInstance<ILabelTemplateManager>();
            _labelManager = FirstFloor.ModernUI.App.App.Container.GetInstance<ILabelManager>();
            _bitmapGenerator = FirstFloor.ModernUI.App.App.Container.GetInstance<IBitmapGenerator>();
            _fileManager = FirstFloor.ModernUI.App.App.Container.GetInstance<IFileManager>();

            _labelLocation = new CommandLineArgs()["location"];
            LabelImages = new ObservableCollection<DisplayLabel>();
     
            InitializeComponent();

            DataContext = this;

            var configDirectory = $@"{AppDomain.CurrentDomain.BaseDirectory}\Config\";
            if (_fileManager.CheckDirectoryExists(configDirectory))
            {
                _fsWatcher = new FileSystemWatcher
                {
                    NotifyFilter = NotifyFilters.LastWrite,
                    Path = configDirectory,
                    Filter = "labels.json",
                    EnableRaisingEvents = true
                };
                _fsWatcher.Changed += FsWatcherOnChanged;

                GetImages();
            }
            else
            {
                ModernDialog.ShowMessage($"An error occurred. The '{configDirectory}' directory could not be found.", "Error", MessageBoxButton.OK, Window.GetWindow(this));

            }
            
        }
        private void Run()
        {
            var parsedArgs = new CommandLineArgs();

            try
            {
                if (!Parser.ParseArgumentsWithUsage(this.args, parsedArgs))
                {
                    throw new ArgumentException("** CommandLine.Parser **");
                }

                // analyze the file...
                this.DumpIffFile(parsedArgs);
            }
            catch (Exception ex)
            {
                // Report it?
                if (!(ex is ArgumentException && ex.Message == "** CommandLine.Parser **"))
                {
                    Console.WriteLine("EXCEPTION: {0}", ex.Message);
                }

                // auto-pause on exceptions if we're debugging.
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    parsedArgs.PauseBeforeExiting = true;
                }
            }
            finally
            {
                if (parsedArgs.PauseBeforeExiting)
                {
                    WaitToExit();
                }
            }
        }
示例#4
0
文件: mp7.cs 项目: EtaPi/potw_7
        private static void PrintMaze( MazeSegment[,] maze, CommandLineArgs args )
        {
            Console.WriteLine();

            Console.Write( "   " );

            for ( var x = 0; x < args.Columns; x++ )
            {
                Console.Write( " _" );
            }

            Console.WriteLine();

            for ( var y = 0; y < args.Rows; y++ )
            {
                Console.Write( "   " );

                for ( var x = 0; x < args.Columns; x++ )
                {
                    var segment = maze[x, y];

                    if ( x == 0 )
                    {
                        Console.Write( '|' );
                    }

                    Console.Write( ( segment.Bottom ) ? '_' : ' ' );
                    Console.Write( ( segment.Right ) ? '|' : ' ' );
                }

                Console.WriteLine();
            }
        }
示例#5
0
文件: mp7.cs 项目: EtaPi/potw_7
        private static CommandLineArgs ParseCommandLine( string[] args )
        {
            var results = new CommandLineArgs
            {
                Rows = 4,
                Columns = 4,
            };

            for ( var i = 0; i < args.Length; i++ )
            {
                switch ( args[i].ToLower() )
                {
                    case "-r":
                    case "-rows":
                        results.Rows = ProcessIntCommandLineArg( args, ++i );
                        break;

                    case "-c":
                    case "-cols":
                    case "-columns":
                        results.Columns = ProcessIntCommandLineArg( args, ++i );
                        break;

                    case "-d":
                    case "-disp":
                    case "-display":

                        results.DisplayMode = true;
                        results.MazeId = ProcessULongCommandLineArg( args, ++i );

                        break;

                    case "-p":
                    case "-prog":
                    case "-progress":
                    case "-progressbar":
                        results.ShowProgressBar = true;
                        break;

                    case "-l":
                    case "-list":
                        results.ListMode = true;
                        break;

                    default:
                        ExitShowUsage();
                        break;
                }
            }

            return results;
        }
        static void Main()
        {
            var parameters = new CommandLineArgs(Environment.GetCommandLineArgs());

            if (!Debugger.IsAttached &&
                parameters.ContainsKey(DebugArgumentTitle) &&
                parameters[DebugArgumentTitle] == "True") {
                Debugger.Launch();
                Debugger.Break();
            }

            if (parameters.Count == 0) return;

            // Check privileges
            var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) throw new UnauthorizedAccessException("Couldn't get administrator privileges");

            if (!parameters.ContainsKey(ActionArgumentTitle)) return;

            switch (parameters[ActionArgumentTitle]) {
                case ActionArgumentCreate: {
                    LinkType type;
                    if (!parameters.ContainsKey(CreateLinkPathArgumentTitle) ||
                        !parameters.ContainsKey(CreateDestinationArgumentTitle) ||
                        !parameters.ContainsKey(CreateLinkTypeArgumentTitle) ||
                        !Enum.TryParse(parameters[CreateLinkTypeArgumentTitle], out type)) {
                            return;
                    }
                    var linkPath = parameters[CreateLinkPathArgumentTitle];

                    if(Directory.Exists(linkPath))
                        Directory.Delete(linkPath, true);
                    else if(File.Exists(linkPath))
                        File.Delete(linkPath);

                    var success = CreateSymbolicLink(parameters[CreateLinkPathArgumentTitle], parameters[CreateDestinationArgumentTitle], type);
                    if (!success) {
                        var error = Marshal.GetLastWin32Error();
                        #if DEBUG
                            Debugger.Break();
                        #endif
                    }
                    break;
                }
            }
        }
示例#7
0
        public IDisposable Play(MediaStreamInfo mediaStreamInfo, IPlaybackController playbackController)
        {
            //fix url
            var url = new Uri(mediaStreamInfo.url);

            if (url == null || !url.IsAbsoluteUri)
            {
                throw new Exception("Invalid playback url");
            }
            if (mediaStreamInfo.transport != MediaStreamInfo.Transport.Http)
            {
                if (String.Compare(url.Scheme, "rtsp", true) != 0)
                {
                    throw new Exception("Invalid playback url");
                }
            }
            else if (String.Compare(url.Scheme, "rtsp", true) != 0)
            {
                int defPort;
                if (String.Compare(url.Scheme, Uri.UriSchemeHttp, true) == 0)
                {
                    defPort = 80;
                }
                else if (String.Compare(url.Scheme, Uri.UriSchemeHttps, true) == 0)
                {
                    defPort = 443;
                }
                else
                {
                    throw new Exception("Invalid playback url");
                }
                var ub = new UriBuilder(url);
                ub.Scheme = "rtsp";
                if (ub.Port == -1)
                {
                    ub.Port = defPort;
                }
                url             = ub.Uri;
                mediaStreamInfo = new MediaStreamInfo(url.ToString(), mediaStreamInfo.transport, mediaStreamInfo.userNameToken);
            }

            var disposable = new SingleAssignmentDisposable();

            playerTask.mediaStreamInfo    = mediaStreamInfo;
            playerTask.playbackController = playbackController;
            if (playerHost != null)
            {
                playerHost.Dispose();
                RemotingServices.Disconnect(playerHost);
                playerHost = null;
            }

            playerHost = new PlayerHost(playerTask);
            RemotingServices.Marshal(playerHost);
            var ipcChannel        = AppHosting.SetupChannel();
            var hostControllerUri = RemotingServices.GetObjectUri(playerHost);
            var hostControllerUrl = ipcChannel.GetUrlsForUri(hostControllerUri).First();

            //start player host process
            var hostProcessArgs = new CommandLineArgs();
            var t = Uri.EscapeDataString(hostControllerUrl);

            hostProcessArgs.Add("controller-url", new List <string> {
                hostControllerUrl
            });

            var pi = new ProcessStartInfo()
            {
                FileName        = Assembly.GetExecutingAssembly().Location,
                UseShellExecute = false,
                Arguments       = String.Join(" ", hostProcessArgs.Format()),
            };

            pi.EnvironmentVariables["PATH"] = String.Join("; ", Bootstrapper.specialFolders.dlls.Select(sfd => sfd.directory.FullName).Append(pi.EnvironmentVariables["PATH"]));

            StartHostProcess(pi);
            return(Disposable.Create(() => {
                Dispose();
            }));
        }
示例#8
0
		public IDisposable Play(MediaStreamInfo mediaStreamInfo, IPlaybackController playbackController) {
			//fix url
			var url = new Uri(mediaStreamInfo.url);
			if (url == null || !url.IsAbsoluteUri) {
				throw new Exception("Invalid playback url");
			}
			if (mediaStreamInfo.transport != MediaStreamInfo.Transport.Http) {
				if (String.Compare(url.Scheme, "rtsp", true) != 0) {
					throw new Exception("Invalid playback url");
				}
			} else if (String.Compare(url.Scheme, "rtsp", true) != 0) {
				int defPort;
				if (String.Compare(url.Scheme, Uri.UriSchemeHttp, true) == 0) {
					defPort = 80;
				} else if (String.Compare(url.Scheme, Uri.UriSchemeHttps, true) == 0) {
					defPort = 443;
				} else {
					throw new Exception("Invalid playback url");
				}
				var ub = new UriBuilder(url);
				ub.Scheme = "rtsp";
				if (ub.Port == -1) {
					ub.Port = defPort;
				}
				url = ub.Uri;
				mediaStreamInfo = new MediaStreamInfo(url.ToString(), mediaStreamInfo.transport, mediaStreamInfo.userNameToken);
			}

			var disposable = new SingleAssignmentDisposable();
			playerTask.mediaStreamInfo = mediaStreamInfo;
			playerTask.playbackController = playbackController;
			if (playerHost != null) {
				playerHost.Dispose();
				RemotingServices.Disconnect(playerHost);
				playerHost = null;
			}

			playerHost = new PlayerHost(playerTask);
			RemotingServices.Marshal(playerHost);
			var ipcChannel = AppHosting.SetupChannel();
			var hostControllerUri = RemotingServices.GetObjectUri(playerHost);
			var hostControllerUrl = ipcChannel.GetUrlsForUri(hostControllerUri).First();

			//start player host process
			var hostProcessArgs = new CommandLineArgs();
			var t = Uri.EscapeDataString(hostControllerUrl);
			hostProcessArgs.Add("controller-url", new List<string> { hostControllerUrl });

			var pi = new ProcessStartInfo() {
				FileName = Assembly.GetExecutingAssembly().Location,
				UseShellExecute = false,
				Arguments = String.Join(" ", hostProcessArgs.Format()),
			};
			pi.EnvironmentVariables["PATH"] = String.Join("; ", Bootstrapper.specialFolders.dlls.Select(sfd => sfd.directory.FullName).Append(pi.EnvironmentVariables["PATH"]));

			StartHostProcess(pi);
			return Disposable.Create(() => {
				Dispose();
			});
		}
示例#9
0
        public void HandleCommandLineActions(CommandLineArgs commandLineArgs)
        {
        	Log.InsideMethod();
        	
            Boolean connectToConsole = commandLineArgs.Console;
            this.fullScreenSwitch.FullScreen = commandLineArgs.Fullscreen;

            if (commandLineArgs.HasUrlDefined)
                this.QuickConnect(commandLineArgs.UrlServer, commandLineArgs.UrlPort, connectToConsole, commandLineArgs.ProtcolName, commandLineArgs.UrlServer, commandLineArgs.UseDbFavorite);
            else if (commandLineArgs.HasMachineDefined)
                this.QuickConnect(commandLineArgs.MachineName, commandLineArgs.Port, connectToConsole, commandLineArgs.ProtcolName, null, commandLineArgs.UseDbFavorite);
            else
                this.ConnectToFavorites(commandLineArgs, connectToConsole);
        }
示例#10
0
        private void DumpIffFile(CommandLineArgs commandLine)
        {
            // header info...
            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine("IffDump v0.1");
            Console.WriteLine("----------------------------------------------------------------------");
            Console.WriteLine();

            Console.WriteLine("Getting IFF information from {0}...", commandLine.InputFile);

            using (IffReader reader = new IffReader(commandLine.InputFile))
            {
                foreach (var chunk in reader.GetChunks(0))
                {
                    this.HandleIffInfo(chunk, reader);
                }

                // show extracted resources...
                Console.WriteLine();
                Console.WriteLine("metadata - {0}", this.metadata.DocumentElement.Name);
                Console.WriteLine(
                    "resources - {0}, {1}, {2}, {3}",
                    this.pictResources == null ? "--" : this.pictResources.Count.ToString(),
                    this.sndResources == null ? "--" : this.sndResources.Count.ToString(),
                    this.dataResources == null ? "--" : this.dataResources.Count.ToString(),
                    this.execResources == null ? "--" : this.execResources.Count.ToString());

                if (!this.coverImage.HasValue)
                {
                    Console.WriteLine("file has no cover art");
                }
                else
                {
                    uint artOffset;
                    if (this.pictResources == null || !this.pictResources.TryGetValue(this.coverImage.Value, out artOffset))
                    {
                        Console.WriteLine("could not find cover art resource (pict {0})", this.coverImage.Value);
                    }
                    else
                    {
                        var artTypeId = reader.ReadTypeId(artOffset);
                        var artLength = reader.ReadUint();
                        Console.WriteLine("cover art is {0} resource at offset 0x{1:x8}, length 0x{2:x8}", artTypeId, artOffset, artLength);
                        using (var stream = new MemoryStream(reader.ReadBytes(artLength)))
                        {
                            var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                            var frame = decoder.Frames[0];
                            Console.WriteLine("cover art is {0}x{1}", frame.PixelWidth, frame.PixelHeight);
                        }
                    }
                }
            }
        }
示例#11
0
        /// <summary>
        /// Processes the command line
        /// </summary>
        /// <param name="args"></param>
        private static void ProcessCommandLine(CommandLineArgs commandLineArgs)
        {
            // Perform some validation
            if (commandLineArgs.mExport)
            {
                ImporterExporter exporter = new ImporterExporter();

                // We need a valid project specified
                if (!System.IO.File.Exists(commandLineArgs.mProject))
                {
                    System.Console.WriteLine("Invalid or no project specified.");
                    return;
                }

                // Open the project
                GUIProject.CurrentProject = GUIProject.Load(commandLineArgs.mProject);

                // We need a valid platform specified
                Platform targetPlatform = null;
                foreach (Platform platform in GUIProject.CurrentProject.Platforms)
                {
                    if (platform.Name == commandLineArgs.mPlatform)
                    {
                        targetPlatform = platform;
                        break;
                    }
                }

                if (targetPlatform == null)
                {
                    System.Console.WriteLine("Invalid or no platform specified");
                    return;
                }

                // See if we have an output directory override
                string outputDir = targetPlatform.OutputDirectory;
                if (commandLineArgs.mOutputDir != "")
                {
                    outputDir = commandLineArgs.mOutputDir;
                    targetPlatform.OutputDirectory = outputDir;
                }

                // Determine the output directory.  If it's not rooted, we need to construct
                // the rooted path
                string projectDir = System.IO.Path.GetDirectoryName(commandLineArgs.mProject);
                if (!System.IO.Path.IsPathRooted(outputDir))
                    outputDir = projectDir + "\\" + outputDir;

                // Create the output directory and verify that it exists
                System.IO.Directory.CreateDirectory(outputDir);
                if (!System.IO.Directory.Exists(outputDir))
                {
                    System.Console.WriteLine("Invalid output directory for platform " + targetPlatform.Name + " : " + outputDir);
                    return;
                }

                ArrayList itemsToExport = ImporterExporter.GetItemsToExport(GUIProject.CurrentProject.Entries);
                List<Platform> platforms = new List<Platform>(new Platform[] { targetPlatform });

                // Finally, export.
                foreach (object item in itemsToExport)
                {
                    System.Console.Write("Exporting.. %s : " + item.ToString());
                    bool bSuccess = exporter.Export(item, platforms);
                    System.Console.WriteLine(bSuccess ? " success" : " FAILED");
                }
            }
        }
示例#12
0
        static void Main(string[] args)
        {
            LoadPlugins();

            CommandLineArgs cmdArgs = new CommandLineArgs(args);

            if (cmdArgs.mExport)
            {
                ProcessCommandLine(cmdArgs);
            }
            else
            {
            #if !(DEBUG)
                try
                {
            #endif
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new OtterEditorMainForm(cmdArgs.mProject));
            #if !(DEBUG)
                }
                catch (Exception e)
                {
                    ReportBugForm reportBugForm = new ReportBugForm(e);
                    reportBugForm.ShowDialog();
                }
            #endif
            }
        }
示例#13
0
        private static CommandLineArgs ParseCommandline(string[] cmdLineArgs)
        {
            CommandLineArgs commandline = new CommandLineArgs();

            Parser.ParseArguments(cmdLineArgs, commandline);

            if (!string.IsNullOrEmpty(commandline.Config))
            {
                Log.Info(string.Format("Loading configuration file at {0}", commandline.Config));
                Settings.ConfigurationFileLocation = commandline.Config;
            }

            if (!string.IsNullOrEmpty(commandline.Cred))
            {
                Log.Info(string.Format("Loading password safe at {0}", commandline.Cred));
                Configuration.Files.Credentials.StoredCredentials.ConfigurationFileLocation = commandline.Cred;
            }

            return commandline;
        }
示例#14
0
        private static void RunMainForm(CommandLineArgs commandLine)
        {
            try
            {
                SingleInstanceApplication.Instance.Start(mainForm);
                mainForm.HandleCommandLineActions(commandLine);
                Application.Run(mainForm);
            }
            catch (Exception exc)
            {
				Log.Fatal("The main form has thrown an exception.", exc);
            }
        }
示例#15
0
        private static void StartMainForm(CommandLineArgs commandLine)
        {
            try
            {
            	RunMainForm(commandLine);
            }
            catch (Exception exc)
            {
				Log.Fatal("The main form has thrown an exception.", exc);
            }
        }
示例#16
0
文件: mp7.cs 项目: EtaPi/potw_7
        private static bool ValidateMaze( MazeSegment[,] maze, CommandLineArgs args )
        {
            var visits = 0;
            var queue = new Queue<MazeSegment>();

            queue.Enqueue( maze[0, 0].Mark( -1 ) );

            while ( true )
            {
                if ( queue.Count == 0 )
                {
                    break;
                }

                var segment = queue.Dequeue();

                visits += 1;

                if ( segment.IsClosed )
                {
                    break;
                }

                if ( !segment.Top && maze[segment.X, segment.Y - 1].ID != segment.ParentID )
                {
                    if ( maze[segment.X, segment.Y - 1].Visited )
                    {
                        break;
                    }

                    queue.Enqueue( maze[segment.X, segment.Y - 1].Mark( segment.ID ) );
                }

                if ( !segment.Right && maze[segment.X + 1, segment.Y].ID != segment.ParentID )
                {
                    if ( maze[segment.X + 1, segment.Y].Visited )
                    {
                        break;
                    }

                    queue.Enqueue( maze[segment.X + 1, segment.Y].Mark( segment.ID ) );
                }

                if ( !segment.Bottom && maze[segment.X, segment.Y + 1].ID != segment.ParentID )
                {
                    if ( maze[segment.X, segment.Y + 1].Visited )
                    {
                        break;
                    }

                    queue.Enqueue( maze[segment.X, segment.Y + 1].Mark( segment.ID ) );
                }

                if ( !segment.Left && maze[segment.X - 1, segment.Y].ID != segment.ParentID )
                {
                    if ( maze[segment.X - 1, segment.Y].Visited )
                    {
                        break;
                    }

                    queue.Enqueue( maze[segment.X - 1, segment.Y].Mark( segment.ID ) );
                }
            }

            return visits == ( args.Columns * args.Rows );
        }
示例#17
0
 public TimerCommand(CommandLineArgs arguments, TextWriter outputStream)
 {
     this.arguments = arguments;
     OutputStream = outputStream;
 }
        public void MainScenario()
        {
            CommandLineArgs args = new CommandLineArgs();
            args.AddArgs(new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i" });

            // parse args
            foreach (var arg in args)
            {
                switch (arg.OriginalValue)
                {
                    case "a":
                    case "c":
                    case "d":
                    case "h":
                    case "i":
                        args.ProcessCurrentArgLater();
                        break;
                }
            }

            Assert.False(args.Empty);

            // wave 2
            int n = 0;
            foreach (var arg in args)
            {
                switch (arg.OriginalValue)
                {
                    case "a":
                    case "i":
                        n++;
                        break;
                    case "c":
                    case "d":
                    case "h":
                        args.ProcessCurrentArgLater();
                        n++;
                        break;
                    default:
                        Assert.True(false);
                        break;
                }
            }

            Assert.Equal(5, n);
            Assert.False(args.Empty);

            foreach (var arg in args)
            {
                switch (arg.OriginalValue)
                {
                    case "c":
                    case "d":
                    case "h":
                        args.ProcessCurrentArgLater();
                        break;
                }
            }

            Assert.False(args.Empty);

            foreach (var arg in args)
            {
                args.ProcessCurrentArgLater();

                switch (arg.OriginalValue)
                {
                    case "c":
                        Assert.Equal("d", args.PeekNext()?.OriginalValue);
                        break;
                    case "d":
                        Assert.Equal("h", args.PeekNext()?.OriginalValue);
                        break;
                    case "h":
                        Assert.Equal(null, args.PeekNext());
                        break;
                }
            }

            Assert.False(args.Empty);

            foreach (var arg in args)
            {
                args.ProcessCurrentArgLater();
                switch (arg.OriginalValue)
                {
                    case "c":
                    case "d":
                    case "h":
                        if (args.Skip())
                        {
                            args.ProcessCurrentArgLater();
                        }
                        break;
                }
            }

            Assert.False(args.Empty);

            args.AddArgs(new string[] { "j", "k" });

            bool firstIteration = true;
            foreach (var arg in args)
            {
                Assert.True(firstIteration);
                args.ProcessCurrentArgLater();
                args.ForceNextWave();
                firstIteration = false;
            }

            Assert.False(args.Empty);

            // wave 3
            Assert.True((from arg in args select arg.OriginalValue).SequenceEqual(new string[] { "c", "d", "h", "j", "k" }));
            Assert.True(args.Empty);

            // finished
            Assert.True((from arg in args select arg.OriginalValue).SequenceEqual(new string[0]));
            Assert.True(args.Empty);
        }
示例#19
0
        private void ConnectToFavorites(CommandLineArgs commandLineArgs, bool connectToConsole)
        {
        	Log.InsideMethod();
        	
        	if (this.favsList1 != null)
	            if (commandLineArgs.Favorites.Length > 0)
	                foreach (String favoriteName in commandLineArgs.Favorites)
	                    this.Connect(favoriteName, connectToConsole, false, favsList1.SaveInDB, waitForEnd: true);
        }
示例#20
0
 public TimerCommand(CommandLineArgs arguments)
 {
     this.arguments = arguments;
 }
示例#21
0
        public deviMobile(string[] arg)
        {
            // Parse the command line arguments. See CommandLine.cs.
            CommandLineArgs args = new CommandLineArgs(arg);
            // Set various options if they're specified.
            string gridfile = "Grids.txt";
            if (args["gridfile"] != null)
            {
                gridfile = args["gridfile"];
            }
            // Read in the grids. Loop through the space-separated file, adding them to the dictionary.
            // Since there's no way of maintaining order, we also store the default separately.

            Console.WriteLine("[MAIN] Reading grids from " + gridfile);
            string[] grids = File.ReadAllLines(gridfile);
            LoginServers = new Dictionary<string, string>();
            bool defaulted = false;
            foreach (string grid in grids)
            {
                string[] split = new string[1];
                split[0] = " ";
                string[] griddata = grid.Trim().Split(split, 2, StringSplitOptions.RemoveEmptyEntries);
                LoginServers.Add(griddata[1], griddata[0]);
                if (!defaulted)
                {
                    DefaultLoginServer = griddata[1];
                    defaulted = true;
                }
                Console.WriteLine("[MAIN] Grids loaded " + griddata[1] + " (" + griddata[0] + ")");
            }
            Console.WriteLine("[MAIN] Default grid: " + DEFAULT_LOGIN_SERVER);

            // More fun option setting.
            if (args["root"] != null)
            {
                StaticRoot = args["root"];
            }
            if(!StaticRoot.EndsWith("/"))
            {
                StaticRoot += "/";
            }
            Console.WriteLine("[MAIN] Static root: " + STATIC_ROOT);
            if (args["texturecache"] != null)
            {
                TextureCache = args["texturecache"];
            }
            // TextureCache must end with a forward slash. Make sure it does.
            if (!TextureCache.EndsWith("/"))
            {
                TextureCache += "/";
            }
            if(args["texturebucket"] != null)
            {
                TextureBucket = args["texturebucket"];
            }
            if(args["textureroot"] != null)
            {
                TextureRoot = args["textureroot"];
            }
            if (args["mac"] != null)
            {
                MacAddress = args["mac"];
            }
            Console.WriteLine("[MAIN] Using MAC address: " + MAC_ADDRESS);
            if (args["id0"] != null)
            {
                Id0 = args["id0"];
            }
            Console.WriteLine("[MAIN] Using id0: " + (ID0 == "" ? "[blank]" : ID0));
            if (args["banlist"] != null)
            {
                BanList = args["banlist"];
            }
            if(BanList != "")
            {
                Console.WriteLine("[MAIN] Using banlist at " + BanList);
                if (args["banupdate"] != null)
                {
                    BanUpdateTime = double.Parse(args["banupdate"]);
                }
                if(BanUpdateTime > 0.0)
                {
                    Console.WriteLine("[MAIN] Updating the banlist every " + BanUpdateTime + " seconds.");
                }
                else
                {
                    Console.WriteLine("[MAIN] Banlist updating disabled.");
                }
            }
            else
            {
                Console.WriteLine("[MAIN] Not using ban list.");
            }
            HandleContentEncoding = (args["doencoding"] != null);
            Console.WriteLine("[MAIN] Handling content encoding: " + (HANDLE_CONTENT_ENCODING ? "Yes" : "No"));
            if(args["spamdebug"] != null)
            {
                DebugMode = true;
                Settings.LOG_LEVEL = Helpers.LogLevel.Debug;
            }
            else if(args["debug"] != null)
            {
                DebugMode = true;
                Settings.LOG_LEVEL = Helpers.LogLevel.Info;
            }
            else
            {
                Settings.LOG_LEVEL = Helpers.LogLevel.Error;
            }
            Console.WriteLine("[MAIN] Debug mode: " + (DEBUG_MODE ? "On" : "Off"));
            // Create an empty dictionary for the users. This is defined as public further up.
            Users = new Dictionary<Guid, User>();

            // Make a web server!
            HttpWebServer webserver = new HttpWebServer((args["port"]!=null)?int.Parse(args["port"]):8080);
            try
            {
                // If the "private" CLI argument was specified, make it private by making us only
                // listen to the loopback address (127.0.0.0)
                if (args["private"] != null)
                {
                    webserver.LocalAddress = System.Net.IPAddress.Loopback;
                    Console.WriteLine("[MAIN] Using private mode.");
                }
            }
            catch
            {
                // If we can't make it private, oh well.
            }

            // Make sure we have a usable texture cache, create it if not.
            // If we're using S3, this is just used for conversions. If we're using
            // our own texture system, we store textures here for client use.
            Console.WriteLine("[MAIN] Checking texture cache...");
            if (!Directory.Exists(TEXTURE_CACHE))
            {
                Console.WriteLine("[MAIN] Not found; Attempting to create texture cache...");
                try
                {
                    Directory.CreateDirectory(TEXTURE_CACHE);
                    Console.WriteLine("[MAIN] Created texture cache.");
                }
                catch
                {
                    Console.WriteLine("[MAIN] Failed to create texture cache at " + TEXTURE_CACHE + "; aborting.");
                    return;
                }
            }

            // Grab the S3 details off the command line if available.
            S3Config = new Affirma.ThreeSharp.ThreeSharpConfig();
            S3Config.AwsAccessKeyID = (args["s3key"] == null) ? AccessKey : args["s3key"];
            S3Config.AwsSecretAccessKey = (args["s3secret"] == null) ? PrivateAccessKey : args["s3secret"];
            // Check that, if we're using S3, we have enough information to do so.
            if(TextureBucket != "" && (S3Config.AwsAccessKeyID == "" || S3Config.AwsSecretAccessKey == "" || TextureRoot == ""))
            {
                Console.WriteLine("[MAIN] Error: To use S3 you must set s3key, s3secret, texturebucket and textureroot");
                return;
            }
            UseS3 = (TextureBucket != ""); // We're using S3 if TextureBucket is not blank.
            if (UseS3)
            {
                Console.WriteLine("[MAIN] Texture root: " + TEXTURE_ROOT);
                Console.WriteLine("[MAIN] Using Amazon S3 for textures:");
                Console.WriteLine("\tBucket: " + TEXTURE_BUCKET);
                Console.WriteLine("\tAccess key: " + S3Config.AwsAccessKeyID);
                Console.WriteLine("\tSecret: ".PadRight(S3Config.AwsSecretAccessKey.Length + 10, '*'));
            }
            else
            {
                TextureRoot = "textures/"; // Set the texture root to ourselves if not using S3.
                Console.WriteLine("[MAIN] Using internal server for textures:");
                Console.WriteLine("\tTexture root: " + TEXTURE_ROOT);
            }

            Console.WriteLine("[MAIN] Setting up pages...");
            // Set up the root.
            VirtualDirectory root = new VirtualDirectory();
            webserver.Root = root;
            #region Dynamic file setup
            // Create the virtual files, passing most of them (except index.html and differentorigin.kat,
            // as they don't need to deal with SL) the Users dictionary. Users is a reference object,
            // so changes are reflected in all the pages. The same goes for individual User objects.
            root.AddFile(new Html.MainPage("index.html", root, Users));
            //root.AddFile(new Html.Proxy("differentorigin.kat", root));
            root.AddFile(new Html.MakeFile("make.d", root));
            //root.AddFile(new Html.iPhone("iphone.kat", root));
            root.AddFile("robots.txt");
            // textures/ is only used if we aren't using S3 for textures.
            if(!UseS3)
            {
                root.AddDirectory(new DriveDirectory("textures", deviMobile.TEXTURE_CACHE, root));
            }
            // API stuff.
            VirtualDirectory api = new VirtualDirectory("api", root);
            root.AddDirectory(api);
            api.AddFile(new Html.BasicStats("stats", api, Users));
            api.AddFile(new Html.CreateSession("new", api, Users));
            api.AddFile(new Html.SendMessage("send", api, Users));
            api.AddFile(new Html.EventQueue("events", api, Users));
            api.AddFile(new Html.Logout("logout", api, Users));
            api.AddFile(new Html.Connect("login", api, Users));
            api.AddFile(new Html.LoginDetails("details", api, Users));

            // Core
            VirtualDirectory core = new VirtualDirectory("core", root);
            root.AddDirectory(core);
            core.AddFile(new Html.Exit("exit", core, Users));

            #endregion
            Console.WriteLine("[MAIN] Loading banlist...");
            BannedUsers = new BanList(); // Create BanList.

            Console.WriteLine("[MAIN] Starting server...");

            // Start the webserver.
            webserver.Start();
            // Set a timer to call timecheck() every five seconds to check for timed out sessions.
            System.Timers.Timer timer = new System.Timers.Timer(5000);
            timer.AutoReset = true;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timecheck);
            timer.Start();
            // Sleep forever. Note that this means nothing after this line ever gets executed.
            // We do this because no more processing takes place in this thread.
            //string cmd = Console.ReadLine();
            //if (cmd == "exit") Environment.Exit(1);
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            // We never get past this point, so all code past here has been deleted for now.
        }
示例#22
0
        static void Main(string[] args)
        {
            CommandLineArgs cmdArgs = new CommandLineArgs(args);
            try
            {
                using (ChannelFactory<IIncinerateService> clientFactory = new ChannelFactory<IIncinerateService>())
                {

                    NamedPipeTransportBindingElement transport = new NamedPipeTransportBindingElement();
                    CustomBinding binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), transport);
                    clientFactory.Endpoint.Binding = binding;
                    clientFactory.Endpoint.Address = new EndpointAddress("net.pipe://IncinerateService/incinerate");
                    IIncinerateService customersProxy = clientFactory.CreateChannel();
                    if (cmdArgs.GetAgents)
                    {
                        IList<AgentInfo> lines = customersProxy.GetAgents();
                        StringBuilder sb = new StringBuilder();
                        foreach (AgentInfo line in lines)
                        {
                            sb.AppendLine(line.Name + ": " + line.Status);
                        }
                        Console.WriteLine(sb.ToString());
                    }
                    else if (cmdArgs.ProcessIDs != null && cmdArgs.AgentName != null)
                    {
                        string[] splitted = cmdArgs.ProcessIDs.Split(',');
                        IList<int> pids = new List<int>();
                        foreach (string pidStr in splitted)
                        {
                            pids.Add(Int32.Parse(pidStr));
                        }
                        customersProxy.AddLearningAgent(pids, cmdArgs.AgentName);
                    }
                    else if (cmdArgs.Watched != null
                        && cmdArgs.StrategyRed != null && cmdArgs.StrategyYellow != null
                        && cmdArgs.P1 != null && cmdArgs.P2 != null)
                    {
                        customersProxy.Watch(cmdArgs.Watched,
                            cmdArgs.StrategyRed, cmdArgs.StrategyYellow,
                            Double.Parse(cmdArgs.P1), Double.Parse(cmdArgs.P2));
                    }
                    else if (cmdArgs.Stop != null)
                    {
                        customersProxy.Stop();
                    }
                    else
                    {
                        cmdArgs.PrintUsage();
                    }
                    clientFactory.Close();
                }
            }
            catch (CommunicationObjectFaultedException ex)
            {
                Console.WriteLine("Service is not working");
            }
            catch (FormatException ex)
            {
                Console.WriteLine("Illegal agruments");
            }
            catch (EndpointNotFoundException ex)
            {
                Console.WriteLine("Service is not running");
            }
            catch (CommunicationException ex)
            {
                Console.WriteLine("Can not connect to service");
            }
        }
示例#23
0
        static void Main(string[] args)
        {
            parsedArgs = new CommandLineArgs();
            bool ok = CommandLine.Parser.Default.ParseArguments(args, parsedArgs);

            if (!ok)
            {
                HelpText help = HelpText.AutoBuild(parsedArgs);
                throw new Exception(string.Format("Invalid command line args: {0}", help.ToString()));
            }

            List<Pipe> pipes = CreatePipes();
            List<long> pipeIDs = pipes.Select(p => p.PipeID).ToList();
            CreateCalibrationImages();
            List<Weld> welds = CreateWelds(pipeIDs);
            List<Load> loads = CreateLoads(pipeIDs);
            List<ReferenceDocument> refDocs = CreateReferenceDocuments(pipes, welds, loads);
            OutputInsertStatements(pipes, welds, loads, refDocs);
            OutputSqlScript();

            Console.WriteLine("done, press a key");
            Console.ReadKey();
        }
示例#24
0
文件: mp7.cs 项目: EtaPi/potw_7
        private static void BuildWalls( MazeSegment[,] maze, CommandLineArgs args, ulong mazeId )
        {
            for ( var y = 0; y < args.Rows; y++ )
            {
                for ( var x = 0; x < args.Columns; x++ )
                {
                    var segment = maze[x, y];

                    for ( var i = 0; i < 4; i++ )
                    {
                        if ( segment.Factors[i] > 0 )
                        {
                            segment.Values[i] = ( mazeId & segment.Factors[i] ) == segment.Factors[i];
                        }
                        else
                        {
                            segment.Values[i] = true;
                        }
                    }
                }
            }
        }
示例#25
0
文件: mp7.cs 项目: EtaPi/potw_7
        private static MazeSegment[,] CreateMaze( CommandLineArgs args )
        {
            var results = new MazeSegment[args.Columns, args.Rows];
            var id = 0;
            var factor = 1UL;

            for ( var y = 0; y < args.Rows; y++ )
            {
                for ( var x = 0; x < args.Columns; x++ )
                {
                    results[x, y] = new MazeSegment( ++id, x, y );

                    //Left
                    if ( x > 0 )
                    {
                        results[x, y].LeftFactor = results[x - 1, y].RightFactor;
                    }

                    //Top
                    if ( y > 0 )
                    {
                        results[x, y].TopFactor = results[x, y - 1].BottomFactor;
                    }

                    //Bottom
                    if ( y < args.Rows - 1 )
                    {
                        results[x, y].BottomFactor = factor;

                        factor *= 2;
                    }

                    //Right
                    if ( x < args.Columns - 1 )
                    {
                        results[x, y].RightFactor = factor;

                        factor *= 2;
                    }

                    results[x, y].Commit();
                }
            }

            return results;
        }
示例#26
0
        static void Main(string[] args)
        {
            try
            {
                //Setup error handling for unmanaged exceptions
                AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
                Application.ThreadException += Application_ThreadException;
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

                //Setup the default args
                CommandLineArgs extenderArgs = new CommandLineArgs();
                extenderArgs.autoStart = false;
                extenderArgs.worldName = "";
                extenderArgs.instanceName = "";
                extenderArgs.noGUI = false;
                extenderArgs.noConsole = false;
                extenderArgs.debug = false;
                extenderArgs.gamePath = "";

                //Process the args
                foreach (string arg in args)
                {
                    if (arg.Split('=').Length > 1)
                    {
                        string argName = arg.Split('=')[0];
                        string argValue = arg.Split('=')[1];

                        Console.WriteLine("Name-Value Arg: name='" + argName + "' value='" + argValue + "'");

                        if (argName.ToLower().Equals("instance"))
                        {
                            extenderArgs.instanceName = argValue;
                        }
                        if (argName.ToLower().Equals("gamepath"))
                        {
                            extenderArgs.gamePath = argValue;
                        }
                    }
                    else
                    {
                        if (arg.ToLower().Equals("autostart"))
                        {
                            extenderArgs.autoStart = true;
                        }
                        if (arg.ToLower().Equals("nogui"))
                        {
                            extenderArgs.noGUI = true;

                            //Implies autostart
                            extenderArgs.autoStart = true;
                        }
                        if (arg.ToLower().Equals("noconsole"))
                        {
                            extenderArgs.noGUI = true;

                            //Implies nogui and autostart
                            extenderArgs.noGUI = true;
                            extenderArgs.autoStart = true;
                        }
                        if (arg.ToLower().Equals("debug"))
                        {
                            extenderArgs.debug = true;
                        }
                    }
                }

                m_server = new Server(extenderArgs);
                if (extenderArgs.autoStart)
                {
                    m_server.StartServer();
                }

                if (!extenderArgs.noGUI)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    m_serverExtenderForm = new SEServerExtender(m_server);
                    Application.Run(m_serverExtenderForm);
                }
            }
            catch (AutoException eEx)
            {
                Console.WriteLine("AutoException - " + eEx.AdditionnalInfo + "\n\r" + eEx.GetDebugString());
                MessageBox.Show(eEx.AdditionnalInfo + "\n\r" + eEx.GetDebugString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TargetInvocationException ex)
            {
                Console.WriteLine("TargetInvocationException - " + ex.ToString() + "\n\r" + ex.InnerException.ToString());
                MessageBox.Show(ex.ToString() + "\n\r" + ex.InnerException.ToString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception - " + ex.ToString());
                MessageBox.Show(ex.ToString(), @"SEServerExtender", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }