コード例 #1
0
        public override async Task RunAsync()
        {
            var user = await _armManager.GetUserAsync();

            var functionApps = await _armManager.GetFunctionAppsAsync(await _armManager.GetCurrentSubscriptionAsync());

            if (functionApps.Any())
            {
                ColoredConsole.WriteLine(TitleColor("Function Apps:"));

                foreach (var app in functionApps)
                {
                    ColoredConsole
                    .WriteLine($"   -> {TitleColor("Name")}:   {app.SiteName} ({AdditionalInfoColor(app.Location)})")
                    .WriteLine($"      {TitleColor("Git Url")}: https://{user.PublishingUserName}@{app.SiteName}.scm.azurewebsites.net/")
                    .WriteLine();
                }
            }
            else
            {
                ColoredConsole.Error.WriteLine(ErrorColor("   -> No function apps found"));
            }
        }
コード例 #2
0
        private async Task SyncTriggers(Site functionApp)
        {
            await RetryHelper.Retry(async() =>
            {
                ColoredConsole.WriteLine("Syncing triggers...");
                HttpResponseMessage response = null;
                // This SyncTriggers function calls the endpoint for linux syncTriggers
                response = await AzureHelper.SyncTriggers(functionApp, AccessToken, ManagementURL);
                if (!response.IsSuccessStatusCode)
                {
                    var errorMessage = $"Error calling sync triggers ({response.StatusCode}). ";

                    // Add request ID if available
                    var requestIds = response.Headers.GetValues("x-ms-correlation-request-id");
                    if (requestIds != null)
                    {
                        errorMessage += $"Request ID = '{string.Join(",", requestIds)}'.";
                    }

                    throw new CliException(errorMessage);
                }
            }, retryCount : 5);
        }
コード例 #3
0
        private async Task PublishRunFromZip(Site functionApp, Stream zipFile)
        {
            ColoredConsole.WriteLine("Preparing archive...");

            var sas = await UploadZipToStorage(zipFile, functionApp.AzureAppSettings);

            functionApp.AzureAppSettings["WEBSITE_RUN_FROM_ZIP"] = sas;

            var result = await AzureHelper.UpdateFunctionAppAppSettings(functionApp, AccessToken);

            ColoredConsole.WriteLine("Upload completed successfully.");
            if (!result.IsSuccessful)
            {
                ColoredConsole
                .Error
                .WriteLine(ErrorColor("Error updating app settings:"))
                .WriteLine(ErrorColor(result.ErrorResult));
            }
            else
            {
                ColoredConsole.WriteLine("Deployment completed successfully.");
            }
        }
コード例 #4
0
        private async Task InternalPublishFunctionApp(GitIgnoreParser ignoreParser)
        {
            ColoredConsole.WriteLine("Getting site publishing info...");
            var functionApp = await _armManager.GetFunctionAppAsync(FunctionAppName);

            var functionAppRoot = ScriptHostHelpers.GetFunctionAppRootDirectory(Environment.CurrentDirectory);

            if (functionApp.IsLinux && !functionApp.IsDynamicLinux && RunFromZipDeploy)
            {
                ColoredConsole
                .WriteLine(ErrorColor("--zip is not supported with dedicated linux apps."));
            }
            // if consumption linux, or --zip, run from zip
            else if (functionApp.IsDynamicLinux || RunFromZipDeploy)
            {
                await PublishRunFromZip(functionApp, functionAppRoot, ignoreParser);
            }
            else
            {
                await PublishZipDeploy(functionApp, functionAppRoot, ignoreParser);
            }
            // else same old same old
        }
コード例 #5
0
        public override Task RunAsync()
        {
            ColoredConsole.WriteLine(TitleColor("App Settings:"));
            foreach (var pair in _secretsManager.GetSecrets())
            {
                ColoredConsole
                .WriteLine($"   -> {TitleColor("Name")}: {pair.Key}")
                .WriteLine($"      {TitleColor("Value")}: {(ShowValues ? pair.Value : "*****")}")
                .WriteLine();
            }

            ColoredConsole.WriteLine(TitleColor("Connection Strings:"));
            foreach (var connectionString in _secretsManager.GetConnectionStrings())
            {
                ColoredConsole
                .WriteLine($"   -> {TitleColor("Name")}: {connectionString.Name}")
                .WriteLine($"      {TitleColor("Value")}: {(ShowValues ? connectionString.Value : "*****")}")
                .WriteLine($"      {TitleColor("ProviderName")}: {connectionString.ProviderName}")
                .WriteLine();
            }

            return(Task.CompletedTask);
        }
コード例 #6
0
        private static async Task RestorePythonRequirementsPackapp(string functionAppRoot, string packagesLocation)
        {
            var packApp = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "tools", "python", "packapp");

            var pythonExe = await ValidatePythonVersion(errorOutIfOld : true);

            var exe      = new Executable(pythonExe, $"\"{packApp}\" --platform linux --python-version 36 --packages-dir-name {Constants.ExternalPythonPackages} \"{functionAppRoot}\" --verbose");
            var sbErrors = new StringBuilder();
            var exitCode = await exe.RunAsync(o => ColoredConsole.WriteLine(o), e => sbErrors.AppendLine(e));

            if (exitCode != 0)
            {
                var errorMessage = "There was an error restoring dependencies. " + sbErrors.ToString();
                // If --build-native-deps if required, we exit with this specific code to notify other toolings
                // If this exit code changes, partner tools must be updated
                if (exitCode == ExitCodes.BuildNativeDepsRequired)
                {
                    ColoredConsole.WriteLine(ErrorColor(errorMessage));
                    Environment.Exit(ExitCodes.BuildNativeDepsRequired);
                }
                throw new CliException(errorMessage);
            }
        }
コード例 #7
0
        public override async Task RunAsync()
        {
            var storageAccounts = await _armManager.GetStorageAccountsAsync();

            var storageAccount = storageAccounts.FirstOrDefault(st => st.StorageAccountName.Equals(StorageAccountName, StringComparison.OrdinalIgnoreCase));

            if (storageAccount == null)
            {
                ColoredConsole
                .Error
                .WriteLine(ErrorColor($"Can't find storage account with name {StorageAccountName} in current subscription ({_settings.CurrentSubscription})"));
            }
            else
            {
                storageAccount = await _armManager.LoadAsync(storageAccount);

                var name = $"{storageAccount.StorageAccountName}_STORAGE";
                _secretsManager.SetSecret(name, storageAccount.GetConnectionString());
                ColoredConsole
                .WriteLine($"Secret saved locally in {SecretsManager.AppSettingsFileName} under name {ExampleColor(name)}.")
                .WriteLine();
            }
        }
コード例 #8
0
    public IAction ChooseAction(Battle battle, Character character)
    {
        // This uses a menu-based approach. We create the choices from the menu, including their name, whether they are enabled, and
        // what action to pick if they are enabled and chosen.
        // After that, we display the menu and ask the user to make a selection.
        // If the selected option is enabled, use the action associated with it.

        List <MenuChoice> menuChoices = CreateMenuOptions(battle, character);

        for (int index = 0; index < menuChoices.Count; index++)
        {
            ColoredConsole.WriteLine($"{index + 1} - {menuChoices[index].Description}", menuChoices[index].Enabled ? ConsoleColor.Gray : ConsoleColor.DarkGray);
        }

        string choice    = ColoredConsole.Prompt("What do you want to do?");
        int    menuIndex = Convert.ToInt32(choice) - 1;

        if (menuChoices[menuIndex].Enabled)
        {
            return(menuChoices[menuIndex].Action !); // Checking if it is enabled is as good as a null check.
        }
        return(new DoNothingAction());               // <-- This is actually fairly unforgiving. Typing in garbage or attempting to use a disabled option results in doing nothing. It would be better to try again. (Maybe that can be done as a Making It Your Own challenge.
    }
コード例 #9
0
        // https://stackoverflow.com/q/3404421/3234163
        private static string InternalReadPassword()
        {
            var password = new StringBuilder();

            while (true)
            {
                var key = Console.ReadKey(true);
                if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
                {
                    password.Append(key.KeyChar);
                    ColoredConsole.Write("*");
                }
                else if (key.Key == ConsoleKey.Backspace && password.Length > 0)
                {
                    password.Remove(password.Length - 1, 1);
                    ColoredConsole.Write("\b \b");
                }
                else if (key.Key == ConsoleKey.Enter)
                {
                    return(password.ToString());
                }
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: atulmish/akkadotnet101
        static void Main(string[] args)
        {
            var actorSystem = ActorSystem.Create("ConsoleApp");

            ColoredConsole.WriteLineGreen($"{actorSystem.Name} Actor System Created.");

            /*
             * // start the Application Actors
             * // var consoleUi = actorSystem.ActorOf<ConsoleUiActor>("ConsoleUi");
             * var consoleUi = actorSystem.ActorOf(Props.Create<ConsoleUiActor>(), "ConsoleUi");
             * consoleUi.Tell("start");
             */

            actorSystem.Terminate();

            // wait for the actor system to terminate
            ColoredConsole.WriteLine("Awaiting for ActorSystem Termination.");
            actorSystem.WhenTerminated.Wait();
            ColoredConsole.WriteLine("ActorSystem Terminated.");

            ColoredConsole.WriteLine("Press 'enter' to exit.");
            Console.ReadLine();
        }
コード例 #11
0
        public static async Task <DeployStatus> WaitForDedicatedBuildToComplete(HttpClient client, Site functionApp)
        {
            // There is a tracked Locking issue in kudulite causing Race conditions, so we have to use this API
            // to gather deployment progress.
            ColoredConsole.Write("Remote build in progress, please wait");
            while (true)
            {
                var json = await InvokeRequest <IDictionary <string, bool> >(client, HttpMethod.Get, "/api/isdeploying");

                bool isDeploying = json["value"];
                if (!isDeploying)
                {
                    string deploymentId = await GetLatestDeploymentId(client, functionApp, restrictedToken : null);

                    DeployStatus status = await GetDeploymentStatusById(client, functionApp, restrictedToken : null, id : deploymentId);

                    ColoredConsole.Write($"done{Environment.NewLine}");
                    return(status);
                }
                ColoredConsole.Write(".");
                await Task.Delay(5000);
            }
        }
コード例 #12
0
        private void SetConnectionStringAndTaskHubName()
        {
            // Set connection string key and task hub name to defaults
            _connectionStringKey = DefaultConnectionStringKey;
            _taskHubName         = DefaultTaskHubName;

            try
            {
                if (File.Exists(ScriptConstants.HostMetadataFileName))
                {
                    // Attempt to retrieve Durable override settings from host.json
                    dynamic hostSettings = JObject.Parse(File.ReadAllText(ScriptConstants.HostMetadataFileName));

                    string version = hostSettings["version"];
                    if (version?.Equals("2.0") == true)
                    {
                        // If the version is (explicitly) 2.0, prepend path to 'durableTask' with 'extensions'
                        _connectionStringKey = hostSettings?.extensions?.durableTask?.AzureStorageConnectionStringName ?? _connectionStringKey;
                        _taskHubName         = hostSettings?.extensions?.durableTask?.HubName ?? _taskHubName;
                    }
                    else
                    {
                        _connectionStringKey = hostSettings?.durableTask?.AzureStorageConnectionStringName ?? _connectionStringKey;
                        _taskHubName         = hostSettings?.durableTask?.HubName ?? _taskHubName;
                    }
                }
                else
                {
                    ColoredConsole.WriteLine(Yellow($"Could not find local host metadata file '{ScriptConstants.HostMetadataFileName}'"));
                }
            }
            catch (Exception e)
            {
                ColoredConsole.WriteLine(Yellow($"Exception thrown while attempting to parse override connection string and task hub name from '{ScriptConstants.HostMetadataFileName}':"));
                ColoredConsole.WriteLine(Yellow(e.Message));
            }
        }
コード例 #13
0
        public void Run()
        {
            var start = head;
            var end   = tail;

            while (end != null &&
                   !string.IsNullOrWhiteSpace(parser.TargetToRun) &&
                   !end.Name.Equals(parser.TargetToRun, StringComparison.OrdinalIgnoreCase))
            {
                end = end.Previous;
            }

            if (end == null)
            {
                ColoredConsole.Error.WriteLine("No target was found to start".Red());
                return;
            }

            PrintTargetsToRun(start, end);

            while (start != null)
            {
                if (!start.Skip)
                {
                    ColoredConsole.WriteLine($"Executing target:{start.Name}".Cyan());
                    start.Target();
                    ColoredConsole.WriteLine($"Finished executing target:{start.Name}".DarkCyan());
                }

                if (start == end)
                {
                    break;
                }

                start = start.Next;
            }
        }
コード例 #14
0
        public override async Task RunAsync()
        {
            if (SourceControl != SourceControl.Git)
            {
                throw new Exception("Only Git is supported right now for vsc");
            }

            if (!string.IsNullOrEmpty(FolderName))
            {
                var folderPath = Path.Combine(Environment.CurrentDirectory, FolderName);
                FileSystemHelpers.EnsureDirectory(folderPath);
                Environment.CurrentDirectory = folderPath;
            }

            var language = string.Empty;

            if (string.IsNullOrEmpty(Language))
            {
                ColoredConsole.Write("Select a language: ");
                language = SelectionMenuHelper.DisplaySelectionWizard(availableLanguages.Keys);
                ColoredConsole.WriteLine(TitleColor(language));
            }
            else
            {
                language = Language;
            }

            language = NormalizeLanguage(language);
            await InitLanguageSpecificArtifacts(language);
            await WriteFiles();
            await WriteLocalSettingsJson(language);
            await WriteExtensionsJson();
            await SetupSourceControl();
            await WriteDockerfile(language);

            PostInit();
        }
コード例 #15
0
        public static void Zip()
        {
            var version = CurrentVersion;

            foreach (var runtime in Settings.TargetRuntimes)
            {
                var path = Path.Combine(Settings.OutputDir, runtime);

                var zipPath = Path.Combine(Settings.OutputDir, $"Azure.Functions.Cli.{runtime}.{version}.zip");
                ColoredConsole.WriteLine($"Creating {zipPath}");
                ZipFile.CreateFromDirectory(path, zipPath, CompressionLevel.Optimal, includeBaseDirectory: false);

                var shaPath = $"{zipPath}.sha2";
                ColoredConsole.WriteLine($"Creating {shaPath}");
                File.WriteAllText(shaPath, ComputeSha256(zipPath));

                try
                {
                    Directory.Delete(path, recursive: true);
                }
                catch
                {
                    ColoredConsole.Error.WriteLine($"Error deleting {path}");
                }

                ColoredConsole.WriteLine();
            }

            string ComputeSha256(string file)
            {
                using (var fileStream = File.OpenRead(file))
                {
                    var sha1 = new SHA256Managed();
                    return(BitConverter.ToString(sha1.ComputeHash(fileStream)).Replace("-", string.Empty).ToLower());
                }
            }
        }
コード例 #16
0
        private static void Main()
        {
            Log.Assign(new ConsoleLog(typeof(Program))
            {
                LogLevel = LogLevel.Trace
            });

            new ConnectionStringService().Approve();

            var subscriptionManager = SubscriptionManager.Default();

            subscriptionManager.Subscribe(new[] { typeof(WorkDoneEvent).FullName });

            var bus = ServiceBus
                      .Create(c => c.SubscriptionManager(subscriptionManager))
                      .Start();

            Console.WriteLine();
            ColoredConsole.WriteLine(ConsoleColor.Green, "Client bus started.  Press CTRL+C to stop.");
            Console.WriteLine();
            ColoredConsole.WriteLine(ConsoleColor.Green, "Press enter to publish an OrderCompleted event.");
            Console.WriteLine();

            while (true)
            {
                Console.ReadLine();

                var message = new OrderCompletedEvent
                {
                    OrderId = Guid.NewGuid()
                };

                bus.Publish(message);

                Console.WriteLine("Published OrderCompleted Id: {0}", message.OrderId);
            }
        }
コード例 #17
0
        public static async Task EnsureVirtualEnvrionmentIgnored()
        {
            if (InVirtualEnvironment)
            {
                try
                {
                    var virtualEnvName = Path.GetFileNameWithoutExtension(VirtualEnvironmentPath);
                    if (FileSystemHelpers.DirectoryExists(Path.Join(Environment.CurrentDirectory, virtualEnvName)))
                    {
                        var funcIgnorePath = Path.Join(Environment.CurrentDirectory, Constants.FuncIgnoreFile);
                        // If .funcignore exists and already has the venv name, we are done here
                        if (FileSystemHelpers.FileExists(funcIgnorePath))
                        {
                            var rawfuncIgnoreContents = await FileSystemHelpers.ReadAllTextFromFileAsync(funcIgnorePath);

                            if (rawfuncIgnoreContents.Contains(Environment.NewLine + virtualEnvName))
                            {
                                return;
                            }
                        }
                        // Write the current env to .funcignore
                        ColoredConsole.WriteLine($"Writing {Constants.FuncIgnoreFile}");
                        using (var fileStream = FileSystemHelpers.OpenFile(funcIgnorePath, FileMode.Append, FileAccess.Write))
                            using (var streamWriter = new StreamWriter(fileStream))
                            {
                                await streamWriter.WriteAsync(Environment.NewLine + virtualEnvName);

                                await streamWriter.FlushAsync();
                            }
                    }
                }
                catch (Exception)
                {
                    // Safe execution, we aren't harmed by failures here
                }
            }
        }
コード例 #18
0
        public override async Task RunAsync()
        {
            await PreRunConditions();

            if (VerboseLogging.HasValue && VerboseLogging.Value)
            {
                Utilities.PrintLogo();
            }
            Utilities.PrintVersion();

            ScriptApplicationHostOptions hostOptions = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory);

            ValidateAndBuildHostJsonConfigurationIfFileExists(hostOptions);

            (var listenUri, var baseUri, var certificate) = await Setup();

            IWebHost host = await BuildWebHost(hostOptions, listenUri, baseUri, certificate);

            var runTask = host.RunAsync();

            var hostService = host.Services.GetRequiredService <WebJobsScriptHostService>();

            await hostService.DelayUntilHostReady();

            var scriptHost  = hostService.Services.GetRequiredService <IScriptJobHost>();
            var httpOptions = hostService.Services.GetRequiredService <IOptions <HttpOptions> >();

            if (scriptHost != null && scriptHost.Functions.Any())
            {
                DisplayFunctionsInfoUtilities.DisplayFunctionsInfo(scriptHost.Functions, httpOptions.Value, baseUri);
            }
            if (VerboseLogging == null || !VerboseLogging.Value)
            {
                ColoredConsole.WriteLine(AdditionalInfoColor("For detailed output, run func with --verbose flag."));
            }
            await runTask;
        }
コード例 #19
0
        public override async Task RunAsync()
        {
            var functionApp = await _armManager.GetFunctionAppAsync(FunctionAppName);

            var basicHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{functionApp.PublishingUserName}:{functionApp.PublishingPassword}"));

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicHeaderValue);
                var response = await client.GetStreamAsync(new Uri($"https://{functionApp.ScmUri}/api/logstream/application"));

                using (var reader = new StreamReader(response))
                {
                    var buffer = new char[4096];
                    var count  = 0;
                    do
                    {
                        count = await reader.ReadAsync(buffer, 0, buffer.Length);

                        ColoredConsole.Write(new string(buffer.Take(count).ToArray()));
                    } while (count != 0);
                }
            }
        }
コード例 #20
0
        public override async Task RunAsync()
        {
            var workerRuntime = WorkerRuntimeLanguageHelper.GetCurrentWorkerRuntimeLanguage(_secretsManager);

            if (workerRuntime == WorkerRuntime.None)
            {
                ColoredConsole.WriteLine(WarningColor("your worker runtime is not set. As of 2.0.1-beta.26 a worker runtime setting is required."))
                .WriteLine(WarningColor($"Please run `{AdditionalInfoColor($"func settings add {Constants.FunctionsWorkerRuntime} <option>")}` or add {Constants.FunctionsWorkerRuntime} to your local.settings.json"))
                .WriteLine(WarningColor($"Available options: {WorkerRuntimeLanguageHelper.AvailableWorkersRuntimeString}"));
            }

            await PreRunConditions(workerRuntime);

            Utilities.PrintLogo();
            Utilities.PrintVersion();

            var settings = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory);

            (var listenUri, var baseUri, var certificate) = await Setup();

            IWebHost host = await BuildWebHost(settings, workerRuntime, listenUri, certificate);

            var runTask = host.RunAsync();

            var hostService = host.Services.GetRequiredService <WebJobsScriptHostService>();

            await hostService.DelayUntilHostReady();

            var scriptHost  = hostService.Services.GetRequiredService <IScriptJobHost>();
            var httpOptions = hostService.Services.GetRequiredService <IOptions <HttpOptions> >();

            DisplayHttpFunctionsInfo(scriptHost, httpOptions.Value, baseUri);
            DisplayDisabledFunctions(scriptHost);

            await runTask;
        }
コード例 #21
0
        public static void Zip()
        {
            var version = CurrentVersion;

            foreach (var runtime in Settings.TargetRuntimes)
            {
                var path = Path.Combine(Settings.OutputDir, runtime);

                var zipPath = Path.Combine(Settings.OutputDir, $"Azure.Functions.Cli.{runtime}.{version}.zip");
                ColoredConsole.WriteLine($"Creating {zipPath}");
                ZipFile.CreateFromDirectory(path, zipPath, CompressionLevel.Optimal, includeBaseDirectory: false);

                try
                {
                    Directory.Delete(path, recursive: true);
                }
                catch
                {
                    ColoredConsole.Error.WriteLine($"Error deleting {path}");
                }

                ColoredConsole.WriteLine();
            }
        }
コード例 #22
0
        public void PrintId()
        {
            try
            {
                var block73 = ReadBlock(0x73);
                var block7F = ReadBlock(0x7F);
                Console.WriteLine();
                Console.WriteLine($"Memory Size: {block73[1]}");
                Console.WriteLine($"Owner: '{ExtractString(block73, 0x30, 16)}'");
                Console.WriteLine(ExtractString(block7F, 0xBD, 15));
                Console.WriteLine(ExtractString(block7F, 0xCD, 15));
                Console.WriteLine(ExtractString(block7F, 0xDD, 15));
                Console.WriteLine(ExtractString(block7F, 0xED, 15));
            }
            catch (TimeoutException e)
            {
                using (var coloredConsole = new ColoredConsole(ConsoleColor.Red))
                {
                    Console.Error.WriteLine($"ERROR: {e.Message}");
                }

                Console.WriteLine("The transmitter does not repond to a connection request. Check the connection, or try to power-cycle the transmitter.");
            }
        }
コード例 #23
0
        public async Task PublishZipDeploy(Site functionApp, Func <Task <Stream> > zipFileFactory)
        {
            await RetryHelper.Retry(async() =>
            {
                using (var client = GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}")))
                    using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri("api/zipdeploy", UriKind.Relative)))
                    {
                        request.Headers.IfMatch.Add(EntityTagHeaderValue.Any);

                        ColoredConsole.WriteLine("Creating archive for current directory...");

                        request.Content = CreateStreamContentZip(await zipFileFactory());

                        ColoredConsole.WriteLine("Uploading archive...");
                        var response = await client.SendAsync(request);
                        if (!response.IsSuccessStatusCode)
                        {
                            throw new CliException($"Error uploading archive ({response.StatusCode}).");
                        }

                        ColoredConsole.WriteLine("Upload completed successfully.");
                    }
            }, 2);
        }
コード例 #24
0
        private async Task PreRunConditions(WorkerRuntime workerRuntime)
        {
            if (workerRuntime == WorkerRuntime.python)
            {
                // We need to update the PYTHONPATH to add worker's dependencies
                var pythonPath       = Environment.GetEnvironmentVariable("PYTHONPATH") ?? string.Empty;
                var pythonWorkerDeps = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "workers", "python", "deps");
                if (!pythonPath.Contains(pythonWorkerDeps))
                {
                    Environment.SetEnvironmentVariable("PYTHONPATH", $"{pythonWorkerDeps}{Path.PathSeparator}{pythonPath}", EnvironmentVariableTarget.Process);
                }
                if (StaticSettings.IsDebug)
                {
                    ColoredConsole.WriteLine($"PYTHONPATH for the process is: {Environment.GetEnvironmentVariable("PYTHONPATH")}");
                }
            }
            else if (workerRuntime == WorkerRuntime.dotnet && !NoBuild)
            {
                if (DotnetHelpers.CanDotnetBuild())
                {
                    var outputPath = Path.Combine("bin", "output");
                    await DotnetHelpers.BuildDotnetProject(outputPath, string.Empty);

                    Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, outputPath);
                }
                else if (StaticSettings.IsDebug)
                {
                    ColoredConsole.WriteLine("Could not find a valid .csproj file. Skipping the build.");
                }
            }

            if (!NetworkHelpers.IsPortAvailable(Port))
            {
                throw new CliException($"Port {Port} is unavailable. Close the process using that port, or specify another port using --port [-p].");
            }
        }
コード例 #25
0
        private async Task SyncTriggers(Site functionApp)
        {
            if (functionApp.IsDynamic)
            {
                ColoredConsole.WriteLine("Syncing triggers...");
                HttpResponseMessage response = null;
                if (functionApp.IsLinux)
                {
                    response = await _armManager.SyncTriggers(functionApp);
                }
                else
                {
                    using (var client = await GetRemoteZipClient(new Uri($"https://{functionApp.ScmUri}")))
                    {
                        response = await client.PostAsync("api/functions/synctriggers", content : null);
                    }
                }

                if (!response.IsSuccessStatusCode)
                {
                    throw new CliException($"Error calling sync triggers ({response.StatusCode}).");
                }
            }
        }
コード例 #26
0
        public override async Task RunAsync()
        {
            Utilities.PrintLogo();

            var settings = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory);

            (var baseAddress, var certificate) = Setup();

            IWebHost host = await BuildWebHost(settings, baseAddress, certificate);

            var runTask = host.RunAsync();

            var manager = host.Services.GetRequiredService <WebScriptHostManager>();
            await manager.DelayUntilHostReady();

            ColoredConsole.WriteLine($"Listening on {baseAddress}");
            ColoredConsole.WriteLine("Hit CTRL-C to exit...");

            DisplayHttpFunctionsInfo(manager, baseAddress);
            DisplayDisabledFunctions(manager);
            await SetupDebuggerAsync(baseAddress);

            await runTask;
        }
コード例 #27
0
        public async Task Deploy(string Name, Template template)
        {
            var path = Path.Combine(Environment.CurrentDirectory, Name);

            if (FileSystemHelpers.DirectoryExists(path))
            {
                var response = "n";
                do
                {
                    ColoredConsole.Write("A directory with the name {Name} already exists. Overwrite [y/n]? [n] ");
                    response = Console.ReadLine();
                } while (response != "n" && response != "y");
                if (response == "n")
                {
                    return;
                }
            }

            if (FileSystemHelpers.DirectoryExists(path))
            {
                FileSystemHelpers.DeleteDirectorySafe(path, ignoreErrors: false);
            }

            FileSystemHelpers.EnsureDirectory(path);

            foreach (var file in template.Files)
            {
                var filePath = Path.Combine(path, file.Key);
                ColoredConsole.WriteLine($"Writing {filePath}");
                await FileSystemHelpers.WriteAllTextToFileAsync(filePath, file.Value);
            }
            var functionJsonPath = Path.Combine(path, "function.json");

            ColoredConsole.WriteLine($"Writing {functionJsonPath}");
            await FileSystemHelpers.WriteAllTextToFileAsync(functionJsonPath, JsonConvert.SerializeObject(template.Function, Formatting.Indented));
        }
コード例 #28
0
        public async Task <bool> RequireDatabaseUpdate(PhotoId photoId, CancellationToken ct)
        {
            var(flickrId, title) = photoId;
            try
            {
                var photo = await _photoRepository.GetByHostingId(flickrId);

                if (photo == null)
                {
                    return(true);
                }


                // ColoredConsole.WriteLine("already saved: " + JsonSerializer.Serialize(photo), Colors.txtWarning);

                // todo: detect if caption is changed and the reupload is required.
                return(false);
            }
            catch (Exception e)
            {
                ColoredConsole.WriteLine($"{e}", Colors.bgDanger);
                return(false);
            }
        }
コード例 #29
0
ファイル: UMTL8D.cs プロジェクト: KLanausse/Lego_Pak_Explorer
        public override int Read()
        {
            var int32_1 = BigEndianBitConverter.ToInt32(fileData, iPos);

            iPos += 4;
            BigEndianBitConverter.ToInt32(fileData, iPos);
            iPos += 4;
            for (var index = 0; index < int32_1; ++index)
            {
                iPos += 4;
                iPos += 4;
                iPos += 4;
                iPos += 4;
                iPos += 4;
                iPos += 375;
                var int32_2 = BigEndianBitConverter.ToInt32(fileData, iPos);
                iPos += 4;
                iPos += 20;
                var int32_3 = BigEndianBitConverter.ToInt32(fileData, iPos);
                iPos += 4;
                iPos += 486;
                var int16 = BigEndianBitConverter.ToInt16(fileData, iPos);
                iPos += 2;
                var name    = readString((int)int16);
                var int32_4 = BigEndianBitConverter.ToInt32(fileData, iPos);
                iPos += 4;
                iPos += int32_4 * 200;
                var int32_5 = BigEndianBitConverter.ToInt32(fileData, iPos);
                iPos += 4;
                iPos += int32_5 * 3;
                iPos += 111;
                ColoredConsole.WriteLineInfo("{0:x8}   {4:0000} {1} --> Tex: {2}; Norm: {3}", (object)iPos, (object)name, (object)int32_2, (object)int32_3, (object)index);
                Materials.Add(new Material(name, int32_2, int32_3));
            }
            return(iPos);
        }
コード例 #30
0
        private void DisplayHttpFunctionsInfo(WebScriptHostManager hostManager, Uri baseUri)
        {
            if (hostManager != null)
            {
                var httpFunctions = hostManager.Instance.Functions.Where(f => f.Metadata.IsHttpFunction());
                if (httpFunctions.Any())
                {
                    ColoredConsole
                    .WriteLine()
                    .WriteLine(Yellow("Http Functions:"))
                    .WriteLine();
                }

                foreach (var function in httpFunctions)
                {
                    var binding   = function.Metadata.Bindings.FirstOrDefault(b => b.Type != null && b.Type.Equals("httpTrigger", StringComparison.OrdinalIgnoreCase));
                    var httpRoute = binding?.Raw?.GetValue("route", StringComparison.OrdinalIgnoreCase)?.ToString();
                    httpRoute = httpRoute ?? function.Name;
                    var extensions = hostManager.Instance.ScriptConfig.HostConfig.GetService <IExtensionRegistry>();
                    var httpConfig = extensions.GetExtensions <IExtensionConfigProvider>().OfType <HttpExtensionConfiguration>().Single();

                    string hostRoutePrefix = "";
                    if (!function.Metadata.IsProxy)
                    {
                        hostRoutePrefix = httpConfig.RoutePrefix ?? "api/";
                        hostRoutePrefix = string.IsNullOrEmpty(hostRoutePrefix) || hostRoutePrefix.EndsWith("/")
                            ? hostRoutePrefix
                            : $"{hostRoutePrefix}/";
                    }
                    var url = $"{baseUri.ToString().Replace("0.0.0.0", "localhost")}{hostRoutePrefix}{httpRoute}";
                    ColoredConsole
                    .WriteLine($"\t{Yellow($"{function.Name}:")} {Green(url)}")
                    .WriteLine();
                }
            }
        }