Пример #1
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var args = value as string;

            if (!string.IsNullOrEmpty(args))
            {
                var argsArr = CommandLineUtils.ParseCommandLine(args);

                var argsVm = new ArgumentVM[argsArr.Length];

                for (int i = 0; i < argsArr.Length; i++)
                {
                    argsVm[i] = new ArgumentVM()
                    {
                        Index = i + 1,
                        Value = argsArr[i]
                    };
                }

                return(argsVm);
            }
            else
            {
                return(null);
            }
        }
 public override Task <ExecutableResult> RunCode(string solutionDirectory, int timeout = Timeout.Infinite)
 {
     return(Task.Run(() =>
     {
         return CommandLineUtils.ExecuteCommand($"{DetectOS.ConsolePromptArgumentStart} dotnet run --project {solutionDirectory}", timeout);
     }));
 }
Пример #3
0
    public static void Reinstall(string apk)
    {
        string cmd = Path.Combine(SDK, "platform-tools/adb");
        var    res = CommandLineUtils.Run(cmd, "install -r " + apk);

        Debug.Log(res);
    }
Пример #4
0
        private static void ResignAPK(string path)
        {
            string res;

            #region zipalign
            string zipalign = Path.Combine(AndroidUtils.BUILD_TOOLS, "zipalign");
            res = CommandLineUtils.Run(zipalign, $"-f -v 4 {path}");
            UnityEngine.Debug.Log(res);
            #endregion

            #region apksigner
            string cmdline = "";
            string indef   = PlayerSettings.applicationIdentifier;
            string pkg     = EnvironmentUtils.Get("pkg_type", JPARAM_PKG_TYPE_INNER);
            if (pkg == JPARAM_PKG_TYPE_AST)//傲世堂用,ebg,v1,v2
            {
                string keystore = Path.GetFullPath("Assets/Editor/Android/android.keystore");
                cmdline = $"-keystore {keystore} -alias ebg -aliaspswd 123456 -pswd 123456 -v1_set true -v2 true {path}";
            }
            else if (pkg.Equals(JPARAM_PKG_TYPE_XKSLHX))           //圣灵幻想,xinkuai,v1
            {
                string keystore = Path.GetFullPath("Assets/Editor/Android/key.keystore");
                cmdline = $"-keystore {keystore} -alias xinyou -aliaspswd xinyou -pswd xinyou -v1_set true -v2 false {path}";
            }
            else//其他,ebg,v1
            {
                string keystore = Path.GetFullPath("Assets/Editor/Android/android.keystore");
                cmdline = $"-keystore {keystore} -alias ebg -aliaspswd 123456 -pswd 123456 -v1_set true -v2 false {path}";
            }
            string apksigner = Path.GetFullPath("Assets/Editor/Android/apksigner.jar");
            res = CommandLineUtils.Run($"java -jar {apksigner}", cmdline);
            UnityEngine.Debug.Log(res);
            #endregion
        }
Пример #5
0
    public static bool HasDevicesConnected()
    {
        string sdk   = SDK;
        var    res   = CommandLineUtils.Run(Path.Combine(sdk, "platform-tools/adb"), "devices");
        var    index = res.IndexOf("List of devices attached");

        if (index >= 0)
        {
            var endl = res.IndexOf('\n', index + 1);
            if (endl >= 0)
            {
                var result  = false;
                var devices = res.Substring(endl + 1).Split('\n');
                foreach (var device in devices)
                {
                    if (device.Contains("device"))
                    {
                        Debug.Log("device: " + device.Split(' ')[0]);
                        result = true;
                    }
                }
                return(result);
            }
        }
        return(false);
    }
Пример #6
0
    public static void Uninstall(string bundleIdentifier)
    {
        string cmd = Path.Combine(SDK, "platform-tools/adb");
        var    res = CommandLineUtils.Run(cmd, "uninstall " + bundleIdentifier);

        Debug.Log(res);
    }
Пример #7
0
    static AndroidUtils()
    {
#if UNITY_ANDROID
#if UNITY_EDITOR_WIN
        SDK = ScanSDKRoot();
        NDK = Path.Combine(SDK, "ndk-bundle");

        string javaPath     = EnvironmentUtils.Get("PROGRAMFILES", "C:\\Program Files") + "\\Java";
        string jdkDirectory = GetJavaInstallationPath();
        var    jdkTrims     = jdkDirectory.TrimEnd(new char[] { '\n' }).Split(new char[] { ' ', '\t', '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
        if (jdkTrims != null && jdkTrims.Length > 0)
        {
            JDK = Path.Combine(javaPath, jdkTrims.Last());
            CommandLineUtils.AddSearchPath(Path.Combine(JDK, "bin"));
        }
#endif

#if UNITY_EDITOR_OSX
        SDK = Path.Combine(EnvironmentUtils.Get("HOME", "/System"), "Library/Android/sdk");
        NDK = Path.Combine(SDK, "ndk-bundle");
        JDK = "/System/Library/Frameworks/JavaVM.framework/Versions/Current";
#endif

        string[] tools = Directory.GetDirectories(Path.Combine(SDK, "build-tools"));
        if (tools != null && tools.Length > 0)
        {
            BUILD_TOOLS = tools[tools.Length - 1];
        }

        Debug.Log("SDK: " + SDK);
        Debug.Log("NDK: " + NDK);
        Debug.Log("JDK: " + JDK);
        Debug.Log("BUILD_TOOLS: " + BUILD_TOOLS);
#endif
    }
Пример #8
0
    // post a local file to a s3
    public static string Put(string file, string path)
    {
        string name = Path.GetFileName(file);

        var key = Path.Combine(BasePath, path);

        Debug.LogFormat("S3 Put: {0} -> {1}:/{2}", name, Bucket, key);

        if (string.IsNullOrEmpty(Bucket))
        {
            return(string.Empty);
        }

        string md5 = CalculateMD5(file);

        string url = "http://" + Bucket + ".s3.amazonaws.com/";

        string args        = string.Format("{0} -F file=@{1} -F key='{2}' -F acl='public-read' -F AWSAccessKeyId='{3}' -F Policy='{4}' -F Signature='{5}' -F Content-MD5='{6}'", url, file, key, AccessKeyId, Policy, Signature, md5);
        var    contentType = MimeUtils.GetMimeType(Path.GetExtension(name));

        if (!string.IsNullOrEmpty(contentType))
        {
            args += (" -F Content-Type=" + contentType);
        }

        Debug.Log("Uploading S3: curl " + args);

        string s3PutResult = CommandLineUtils.Run("curl", args);

        Debug.Log(s3PutResult);

        // return the url
        return(url + key);
    }
Пример #9
0
        static void Main(string[] args)
        {
            var options = new CommandLineOptions();

            string result;

            if (Parser.Default.ParseArguments(args, options))
            {
                if (options.SkipDecoding)
                {
                    result = options.TestValue;
                }
                else
                {
                    result = CommandLineUtils.DecodeText(options.TestValue, false, options.HasRegEx, options.UseEscapeChars);
                }
            }
            else
            {
                result = "Errors in ParseArguments: " + Environment.NewLine;
                if (options.LastParserState.Errors.Count > 0)
                {
                    foreach (var error in options.LastParserState.Errors)
                    {
                        result += error.BadOption.ShortName + ": " + error.ToString() + Environment.NewLine;
                    }
                }
            }

            using (var outfile = new StreamWriter("output.log"))
            {
                outfile.Write(result);
            }
        }
Пример #10
0
        static async Task Main(string[] args)
        {
            CommandLineUtils.ShowUsageIfHelpRequested(
                @"Usage: 
DatabaseBackupUtility [Required: Connection string] [Required: The path of the directory to save the .bak file] [Required if InitialCatalog is not specified in connection string: The name of the database]",
                args);
            var connectionString = args.Length > 0?
                                   args[0] : throw new ArgumentException($"Please pass connection string as first argument");

            var backupDir = args.Length > 1?
                            args[1] : throw new ArgumentException($"Please pass backup directory as the second argument");

            var dbName = args.GetDatabaseName(connectionString, 2);

            Console.WriteLine($"Backing up database {dbName} to directory {backupDir}");
            var dirInfo = new DirectoryInfo(backupDir);

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }

            var backupService = new BackupService(connectionString, dirInfo.FullName);
            await backupService.BackupDatabase(dbName);
        }
Пример #11
0
        /// <summary>
        /// Specific options for ABCDExplorer.
        /// </summary>
        //class Options : CommandLineUtils.CommonOptions
        //{

        //}

        /// <summary>
        /// Loop through a set of ABCD methods and try to dump
        /// some generic and dense info on what it is like.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Options opt = CommandLineUtils.ParseOptions<Options>(args);

            // Setup which pairs of variables we will look at.
            var abcdPairs = new[]
            {
                Tuple.Create("SumCalR_Sum2JTrackPt", JetEventTypeSumCalRPlot, JetEventTypeSum2JTrackPt),
                Tuple.Create("SumCalR_DRToTrackSum", JetEventTypeSumCalRPlot, JetEventDRToTrackSum),
            };

            // Get the background along with the variables we are going to look at for each event.
            var backgrounds = CommandLineUtils.GetRequestedBackground()
                              .AsEventStream();

            // Do a background
            using (var output = new FutureTFile("ABCDExplorer.root"))
            {
                foreach (var vPair in abcdPairs)
                {
                    var dir = output.mkdir(vPair.Item1);

                    // Do something like the sum of logR and the NTrack variable Something dumb...
                    var explorer = new ABCDCutExplorer <EventType>(vPair.Item2, vPair.Item3);

                    // Do the uncorrelated version of the exploration.
                    var info = DoABCDExploration(explorer, backgrounds, dir.mkdir("correlated"));

                    // Next, get the uncorrelated version
                    var unCorVars    = UncorrelateVariables(info.CoVar, JetEventTypeSumCalRPlot, JetEventTypeSum2JTrackPt);
                    var exploreUnCor = new ABCDCutExplorer <EventType>(unCorVars.Item1, unCorVars.Item2);
                    DoABCDExploration(exploreUnCor, backgrounds, dir.mkdir("uncorrelated"));
                }
            }
        }
Пример #12
0
        private static void Main(string[] args)
        {
            ParserResult <FtpOptions> ftpOptionsResult;

            if (args.Length == 1)
            {
                var configOptionsResult = Parser.Default.ParseArguments <ConfigOptions>(args);
                if (configOptionsResult.Errors.Any())
                {
                    return;
                }

                if (!VerifyConfigOptions(configOptionsResult))
                {
                    return;
                }

                var config = CommandLineUtils.CommandLineToArgs(File.ReadAllText(configOptionsResult.Value.ConfigFile));
                ftpOptionsResult = Parser.Default.ParseArguments <FtpOptions>(config);
                if (ftpOptionsResult.Errors.Any())
                {
                    return;
                }
            }
            else
            {
                ftpOptionsResult = Parser.Default.ParseArguments <FtpOptions>(args);
                if (ftpOptionsResult.Errors.Any())
                {
                    return;
                }
            }

            var options = ftpOptionsResult.Value;

            while (true)
            {
                try
                {
                    if (!VerifyFtpOptions(options))
                    {
                        return;
                    }
                    UploadToServer(options);
                }
                catch (FtpCommandException exception)
                {
                    if (exception.Message.Contains("Login"))
                    {
                        Console.WriteLine("Password is incorrect, try again!");
                        options.Password = null;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Пример #13
0
    private void OnGUI()
    {
        string schemaPath    = Path.Combine(Application.dataPath, "../../Source/FlatBuffers/Schema");
        string dataCachePath = Path.Combine(Application.dataPath, "../../Source/FlatBuffers/DataCache");
        string gamePath      = Path.Combine(Application.dataPath, "GM/Scripts/DataCache");

        if (GUILayout.Button("Open Floder"))
        {
            string path = schemaPath.Replace("/", "\\");
            System.Diagnostics.Process.Start("explorer.exe", path);
        }

        GUILayout.BeginHorizontal();
        TableName = EditorGUILayout.TextField("TableName:", TableName);
        GUILayout.EndHorizontal();

        if (GUILayout.Button("Generate"))
        {
            string sourceFile = string.Format("{0}/{1}.fbs", schemaPath, TableName);//生成
            string tempPath   = string.Format("{0}/DataCache", schemaPath);
            CommandLineUtils.Run("flatc", string.Format("-c -b --schema --csharp --gen-onefile -o {0} {1}", tempPath, sourceFile));

            string[] tempFiles = Directory.GetFiles(string.Format("{0}/DataCache", schemaPath));//拷贝至DataCache目录
            foreach (string tempFile in tempFiles)
            {
                string dataCacheFile = string.Format("{0}/{1}", dataCachePath, Path.GetFileName(tempFile));
                File.Copy(tempFile, dataCacheFile, true);
            }
        }

        if (GUILayout.Button("Copy To Client"))
        {
            string gameFile     = string.Format("{0}/{1}.cs", gamePath, TableName);//拷贝至工程内
            string tempGameFile = string.Format("{0}/{1}.cs", dataCachePath, TableName);
            File.Copy(tempGameFile, gameFile, true);
        }

        GUILayout.BeginHorizontal();
        ServerPath = EditorGUILayout.TextField("Server Path:", ServerPath);
        GUILayout.EndHorizontal();

        if (GUILayout.Button("Copy To Server"))
        {
            string targetFile = string.Format("{0}/{1}.bfbs", ServerPath, TableName);
            string sourceFile = string.Format("{0}/{1}.bfbs", dataCachePath, TableName);
            File.Copy(sourceFile, targetFile, true);
        }

        if (GUILayout.Button("Delete Temp"))
        {
            string   targetPath  = string.Format("{0}/DataCache", schemaPath);
            string[] targetFiles = Directory.GetFiles(targetPath);
            foreach (string targetFile in targetFiles)
            {
                File.Delete(targetFile);
            }
            Directory.Delete(targetPath);
        }
    }
Пример #14
0
        public void Converted_endpoint_should_return_sqlapi_endpoint()
        {
            string accountGraphEndpoint = "https://graph-database.gremlin.cosmosdb.azure.com:443/";
            string accountSqlEndpoint   = "https://graph-database.documents.azure.com:443/";

            var result = CommandLineUtils.ConvertToSqlApiEndpoint(accountGraphEndpoint);

            Assert.Equal(accountSqlEndpoint, result);
        }
Пример #15
0
        public string GetCommandLine(Model.Server server, string host)
        {
            if (server.CurrentPlayers == server.MaximumPlayers)
            {
                return("Sorry, the game is already started.");
            }

            return(CommandLineUtils.GetClientLaunchCommand(host, server.Port, server.Mod.CommandLine));
        }
        private string GenCommandLine(string value, bool hasRegEx = false, bool useEscapeChars = false)
        {
            value = CommandLineUtils.EncodeText(value, hasRegEx, useEscapeChars);

            return(String.Format(" {0}{1}--testVal \"{2}\" --someFlag",
                                 hasRegEx ? "--hasRegEx " : "",
                                 useEscapeChars ? "--useEscapeChars " : "",
                                 value
                                 ));
        }
Пример #17
0
    private void UploadDataToUWA()
    {
#if UNITY_EDITOR_WIN
        string command = Application.dataPath.Replace("Assets", "UwaDataUploader/UwaDataUploader.exe");
#else
        string command = "mono " + Application.dataPath.Replace("Assets", "UwaDataUploader/UwaDataUploader.exe");
#endif
        string args = Application.dataPath.Replace("Assets", "UwaScan");
        CommandLineUtils.Run(command, args);
    }
Пример #18
0
    public static void LaunchGameAndroid()
    {
        Debug.Log("LaunchGameAndroid");

        string adb = Path.Combine(SDK, "platform-tools/adb");

        CommandLineUtils.Run(adb, "shell am force-stop " + PlayerSettings.applicationIdentifier);
        string res = CommandLineUtils.Run(adb, "shell am start " + PlayerSettings.applicationIdentifier + "/com.unity3d.player.UnityPlayerNativeActivity");

        Debug.Log(res);
    }
Пример #19
0
        public void Parsed_connection_string_should_return_all_tuples()
        {
            string accountEndpoint = "https://graph-database.gremlin.cosmosdb.azure.com:443/";
            string accountKey      = "FakeKeyU8WB0cNFR0QvWT0jBouMnIqYuavySbwmYK3Ur2xvNBuVhAv3HHnrxhYBNf3dO2Kugbw==";
            string database        = "db001";
            string collection      = "col003";


            var result = CommandLineUtils.ParseCosmosDbConnectionString("AccountEndpoint=https://graph-database.gremlin.cosmosdb.azure.com:443/;AccountKey=FakeKeyU8WB0cNFR0QvWT0jBouMnIqYuavySbwmYK3Ur2xvNBuVhAv3HHnrxhYBNf3dO2Kugbw==;ApiKind=Gremlin;Database=db001;Collection=col003");

            Assert.Equal(result.accountEndpoint, accountEndpoint);
            Assert.Equal(result.accountKey, accountKey);
            Assert.Equal(result.database, database);
            Assert.Equal(result.collection, collection);
        }
        public async override Task <ExecutableResult> RunTests(string solutionDirectory, int timeout = Timeout.Infinite)
        {
            ExecutableResult res = await Task.Run(() =>
            {
                return(CommandLineUtils.ExecuteCommand($"{DetectOS.ConsolePromptArgumentStart} dotnet test {solutionDirectory}", timeout));
            });

            if (!res.WasError)
            {
                int idx = res.RawResult.LastIndexOf("Microsoft");
                res.RawResult = res.RawResult.Substring(idx);
            }

            return(res);
        }
Пример #21
0
        public override Task <ExecutableResult> RunTests(string solutionDirectory, int timeout)
        {
            return(Task.Run(() =>
            {
                Console.WriteLine("sd:" + solutionDirectory);
                ExecutableResult res = CommandLineUtils
                                       .ExecuteCommand($"{DetectOS.ConsolePromptArgumentStart} " + @"""" + $"dotnet test {solutionDirectory}" + @"""", timeout);
                if (!res.WasError)
                {
                    int idx = res.RawResult.LastIndexOf("Microsoft");
                    res.RawResult = res.RawResult.Substring(idx);
                }

                return res;
            }));
        }
Пример #22
0
        static void Main(string[] args)
        {
            // Parse the command parameters
            var opt = CommandLineUtils.ParseOptions <Options>(args);

            libDataAccess.Files.JobVersionNumber = opt.JobVersion;
            libDataAccess.Files.JobName          = opt.JobName;

            // Next, for each dataset, write out the files.
            foreach (var ds in opt.Datasets)
            {
                WriteLine($"Looking at {ds}.");
                GenerateExtrapolationMCFiles(ds);
            }

            FutureConsole.DumpToCout();
        }
        public IActionResult Index(PrivateViewModel request)
        {
            StartServerResponse viewModel;

            try
            {
                if (!ModelState.IsValid)
                {
                    throw new WebInterfaceException("Something went off the rails.");
                }

                if (_torCheckService.IsTorExit(HttpContext.Connection.RemoteIpAddress))
                {
                    throw new WebInterfaceException("Requesting private servers through Tor is not allowed.");
                }

                if (!_rateLimiterService.IsRequestAllowed(HttpContext.Connection.RemoteIpAddress))
                {
                    throw new WebInterfaceException("Sorry, you have requested too many servers recently, you need to wait some time.");
                }

                string tempFolderName = "";
                if ((request.FormFile?.Length ?? 0) > 0)
                {
                    tempFolderName = _customMapService.StoreTempCustomMap(request.FormFile);
                }

                var    spawnedServer = _privateServerService.SpawnNewPrivateServer(request.Players + 1, request.ModName, tempFolderName ?? "");
                string commandLine   = CommandLineUtils.GetClientLaunchCommand(HttpContext.Request.Host.Host,
                                                                               spawnedServer.Port,
                                                                               spawnedServer.Mod.CommandLine);

                viewModel = new StartServerResponse(spawnedServer.Port, commandLine);
            }
            catch (WebInterfaceException ex)
            {
                viewModel = new StartServerResponse(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                viewModel = new StartServerResponse("Internal server error.");
            }

            return(View("Result", viewModel));
        }
        public static void Main(string[] args)
        {
            IGui gui = new Gui();

            try
            {
                // Show test UI when given no arguments
                if (args.Length == 0)
                {
                    gui.ShowWindow(() => new Tester());
                }
                else
                {
                    var prompts    = new AuthenticationPrompts(gui);
                    var resultDict = new Dictionary <string, string>();

                    if (StringComparer.OrdinalIgnoreCase.Equals(args[0], "userpass"))
                    {
                        string username = CommandLineUtils.GetParameter(args, "--username");
                        if (prompts.ShowCredentialsPrompt(ref username, out string password))
                        {
                            resultDict["username"] = username;
                            resultDict["password"] = password;
                        }
                        else
                        {
                            throw new OperationCanceledException("authentication prompt was canceled");
                        }
                    }
                    else if (StringComparer.OrdinalIgnoreCase.Equals(args[0], "oauth"))
                    {
                        if (!prompts.ShowOAuthPrompt())
                        {
                            throw new OperationCanceledException("authentication prompt was canceled");
                        }

                        resultDict["continue"] = "1";
                    }
                    else
                    {
                        throw new Exception($"unknown argument '{args[0]}'");
                    }

                    Console.Out.WriteDictionary(resultDict);
                }
Пример #25
0
        static void Main(string[] args)
        {
            CommandLineUtils.ApplyValuesFromcommandLine(args);
            var targetSiteUrl = ConfigurationManager.AppSettings.Get("targetSiteUrl");

            using (ClientContext context = new ClientContext(targetSiteUrl))
            {
                //context.RequestTimeout = Timeout.Infinite;
                var username        = ConfigurationManager.AppSettings.Get("sharePointUserName");
                var password        = ConfigurationManager.AppSettings.Get("sharePointPassword");
                var securedPassword = new SecureString();
                if (string.IsNullOrEmpty(password))
                {
                    securedPassword = GetConsoleSecurePassword();
                }
                else
                {
                    foreach (var c in password.ToCharArray())
                    {
                        securedPassword.AppendChar(c);
                    }
                }
                context.Credentials = new SharePointOnlineCredentials(username, securedPassword);

                NintexApiSettings.ApiKey             = ConfigurationManager.AppSettings.Get("nintexApiKey");
                NintexApiSettings.WebServiceUrl      = ConfigurationManager.AppSettings.Get("nintexServiceUrl");
                NintexApiSettings.HttpRequestTimeout = TimeSpan.Parse(ConfigurationManager.AppSettings["nintexApiTimeout"]);


                context.Load(context.Web, x => x.Title, x => x.Url);
                context.ExecuteQuery();
                Console.WriteLine("Provisioning to the site with");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("\ttitle:url {0}:{1}", context.Web.Title, context.Web.Url);
                Console.ForegroundColor = ConsoleColor.White;

                var service = new CSOMProvisionService();
                service.RegisterModelHandlers(typeof(NintexFormO365Handler).Assembly);
                WebModel.PreProvision(context, service);
                Console.WriteLine("please ensure that the subweb NintexTest has the nintex apps installed and then press any key");
                WebModel.Provision(context, service);
            }
        }
Пример #26
0
        public static int NormalizeEnumJson(string repoRoot, string[] jsonInputFile, string jsonOutputFile, string[] rename, string[] exclude)
        {
            var renames = CommandLineUtils.ConvertValuePairsToDictionary(rename);

            HashSet <string>  excludes    = new HashSet <string>(exclude);
            List <EnumObject> enumObjects = new List <EnumObject>();

            foreach (var inputFile in jsonInputFile)
            {
                enumObjects.AddRange(EnumObject.LoadFromFile(inputFile));
            }

            var newObjects = EnumObjectUtils.NormalizeEnumObjects(repoRoot, enumObjects, renames, excludes).ToArray();

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();

            jsonSerializerSettings.NullValueHandling    = NullValueHandling.Ignore;
            jsonSerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;

            var jsonText = JsonConvert.SerializeObject(newObjects, Formatting.Indented, jsonSerializerSettings);

            File.WriteAllText(jsonOutputFile, jsonText);

            Regex containsLowerCase = new Regex(@"[a-z]+");

            foreach (var obj in newObjects)
            {
                if (obj.name != null && containsLowerCase.IsMatch(obj.name))
                {
                    Console.WriteLine($"Warning: {obj.name} enum contains lower case. Add a better name or exclude it.");
                    Console.Write("  Members: ");
                    foreach (var member in obj.members.Take(3))
                    {
                        Console.Write(member.name);
                        Console.Write(' ');
                    }

                    Console.WriteLine();
                }
            }

            return(0);
        }
        public StartServerResponse StartServer([FromQuery] ServerParameters parameters)
        {
            try
            {
                if (parameters.ApiKey != _config.GetValue <string>("ApiKey"))
                {
                    return(new StartServerResponse("Invalid ApiKey."));
                }

                Stopwatch sw = Stopwatch.StartNew();
                while (_isBusy)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    if (sw.Elapsed.TotalSeconds > 5)
                    {
                        throw new Exception("Request timeout: the previous request hasn't finished yet.");
                    }
                }

                _isBusy = true;

                var serverProcess = _privateServerService.SpawnNewPrivateServer(parameters.Players, parameters.ModName);
                _logger.LogInformation("Server started waiting for {0} players on port {1}.",
                                       parameters.Players, serverProcess.Port);

                string commandLine = CommandLineUtils.GetClientLaunchCommand(HttpContext.Request.Host.Host,
                                                                             serverProcess.Port,
                                                                             serverProcess.Mod.CommandLine);

                Thread.Sleep(TimeSpan.FromSeconds(2));
                return(new StartServerResponse(serverProcess.Port, commandLine));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                return(new StartServerResponse(generalErrorMessage));
            }
            finally
            {
                _isBusy = false;
            }
        }
Пример #28
0
    static void UploadApkFiles(string apkPath, WWWUtils.Environment env)
    {
        try
        {
            var tmpDir = "/tmp/apk";
            GeneralUtils.DeleteDirectory(tmpDir, true);               // mko: cleaning up build folder
            Directory.CreateDirectory(tmpDir);

            // unzip
            var res = CommandLineUtils.Run("/usr/bin/unzip", string.Format("-d {0} {1}", tmpDir, apkPath));
            Debug.Log(res);

            // generate the app.dll
            var files = new List <string>(Directory.GetFiles("/tmp/apk/assets/bin/Data/Managed", "*.dll", SearchOption.TopDirectoryOnly));
            files.Sort(System.StringComparer.OrdinalIgnoreCase);

            List <byte> bytes = new List <byte>();
            foreach (string filePath in files)
            {
                Debug.Log("Adding file " + filePath);
                bytes.AddRange(File.ReadAllBytes(filePath));
            }

            Debug.Log("MSIL size is " + EB.Localizer.FormatNumber(bytes.Count, true));

            WWWForm form = new WWWForm();
            form.AddBinaryData("data", bytes.ToArray(), "data");
            form.AddField("version", EB.Version.GetVersion());
            form.AddField("platform", "android");
            form.AddField("sha1", EB.Encoding.ToBase64String(EB.Digest.Sha1().Hash(bytes.ToArray())));

            var stoken  = WWWUtils.AdminLogin(env);
            var postUrl = WWWUtils.GetAdminUrl(env) + "/protect/upload?stoken=" + stoken;
            res = WWWUtils.Post(postUrl, form);
            Debug.Log("version: " + res);
        }
        catch (System.Exception e)
        {
            Debug.Log("Build Failed: exception: " + e.ToString());
            Failed(e);
        }
    }
Пример #29
0
    public static string UploadBuild(string ipaFile, string notes, string distribution_lists, bool notify = true)
    {
        UnityEditor.EditorUtility.UnloadUnusedAssetsImmediate();
        System.GC.Collect();

        var zipName = Path.GetFileNameWithoutExtension(ipaFile) + ".dSYM.zip";
        var zipDir  = Path.GetDirectoryName(ipaFile);
        var zipFile = Path.Combine(zipDir, zipName);

        notes = notes.Replace('\'', '`');               // moko: remove single quote from notes

        string args = string.Format("{0} -F file=@{1} -F api_token='{2}' -F team_token='{3}' -F notes='{4}' -F distribution_lists='{5}' -F replace=True -F notify={6}", upload_url, ipaFile, api_token, team_token, notes, distribution_lists, (notify?"True":"False"));

        Debug.Log("Testflight upload: " + args);
        if (File.Exists(zipFile))
        {
            args += " -F dsym=@" + zipFile;
        }
        string result = CommandLineUtils.Run("curl", args);

        return(result);
    }
Пример #30
0
        private void ProcessMessage(Source source, Message message)
        {
            var me          = Client.GetMe();
            var firstEntity = message?.Entities?.FirstOrDefault();

            if (null != firstEntity && firstEntity.Type == "bot_command" && firstEntity.Offset == 0)
            {
                string myName  = Client.GetMe().Username;
                string command = message.Text.Substring(firstEntity.Offset, firstEntity.Length);
                if (command.Contains("@") && !command.EndsWith($"@{myName}", StringComparison.InvariantCultureIgnoreCase))
                {
                    // not for me
                    Log.Trace($"Got command '{command}' but it is not for me.");
                }
                else
                {
                    command = command.Split("@").First()?.ToLowerInvariant();
                    var args = CommandLineUtils.SplitArgs(message.Text.Substring(firstEntity.Length).Trim()).ToArray();
                    ProcessCommand(source, message, command, args);
                }
            }
        }