How to add new Yii webapp arguments? - yii

Using Yii 1.1.14
For those who have customised the webapp (ie, mywebapp) command, have you, or do you know, any way on how to add more parameters to that command?
We already have the git param for example, we wish to add some interactive prompts to the user too, for example: setup the config/main.php files.
Any clue about this subject?

This is a snippet of the run() function:
public function run($args) {
$vcs = false;
if (isset($args[1])) {
if ($args[1] != 'git' && $args[1] != 'hg')
$this->usageError('Unsupported VCS specified. Currently only git and hg supported.');
$vcs = $args[1];
}
// ...
Just like you see, $args[1] must be always the VCS you use.
By logic you need to change/develop the body of run() to be adapted to the new arguments you want.
A probably call would be:
webapp ../test git setconfig
or
webapp ../test git true
The third argument will be available as $args[2].

Related

Why do I need to reference a custom gradle config with square brackets?

I created a gradle build config just to download some dependencies. The documentation has been sparse, so I've piece together this working snippet based on random snippets and guesses.
configurations {
create("downloadDeps")
}
dependencies {
// JSON
configurations["downloadDeps"]("com.fasterxml.jackson.core:jackson-databind:2.13.3")
configurations["downloadDeps"]("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.3")
}
repositories {
// internal repository
maven {
url = uri("...")
credentials {
username = System.getenv("ARTIFACTORY_USER") ?: System.getProperty("ARTIFACTORY_USER") as String
password = System.getenv("ARTIFACTORY_TOKEN") ?: System.getProperty("ARTIFACTORY_TOKEN") as String
}
}
}
tasks.register<Copy> ("downloadDeps") {
from(configurations["downloadDeps"])
into("lib/")
}
If I reference the "downloadDeps" dependency like configuration.downloadDeps or downloadDeps("com.fasterxml.jackson.core:jackson-databind:2.13.3"). I get an error about an unresolved reference to "downloadDeps".
Why does implementation("...") or configuration.implementation.get() work?
The documentation #Slaw provided helped me understand why I can do something like this:
implementation("group:artifact:1.0.0")
but not
myCustomConfig("group:artifact:1.0.0")
implementation being declared that way is supported because it comes from a plugin (the Kotlin/Java plugins)
The simplest way to associate a dependency with myCustomConfig would be to do this (see these docs):
"myCustomConfig"("group:artifact:1.0.0")

How can I use environment specific variables in micronaut?

I'm new to micronaut and server side programming in general. The micronaut documentation, unfortunately, does not make a lot of sense to me, as I do not have a Java background. A lot of the terms like "ApplicationContext" make sense in english, but I have no idea how to use them in practice.
Trying to start with a very basic app that prints different configurations ("localhost", "dev", "prod") depending on the environment it is in.
Here's my controller
#Controller("/")
class EnvironmentController {
// this should return "localhost", "DEV", "PROD" depending on the environment
#Get("/env")
#Produces(MediaType.TEXT_PLAIN)
fun env() = "???" // what should I put here ?
// this should return the correct mongodb connection string for the environment
#Get("/mongo")
#Produces(MediaType.TEXT_PLAIN)
fun mongo() = "???" // what should I put here ?
}
Here's the application.yml. Ideally I'd have 1 yml file for each environment
micronaut:
application:
name: myApp
server:
port: 8090
environment: localhost
mongodb:
uri: 'mongodb://localhost:27017'
Application.kt is untouched with the rest of the files generated by the mn cli tool. How can I set per environment parameters, or pass the yml file as a parameter when starting micronaut?
Are there any conventions around this?
You can specify an environment with -Dmicronaut.environments, or by specifying them in the context builder Micronaut.run in your Application class.
https://docs.micronaut.io/latest/guide/index.html#environments
Then for example application-env.yml will be loaded.
https://docs.micronaut.io/latest/guide/index.html#propertySource
The docs are pretty clear on this
By default Micronaut only looks for application.yml. Then, for tests,dev and prod, it loads application.yml and overrides any values there with the ones defined in application-test.yml, application-dev.yml and application-prod.yml
If you want to enable any other environment, you need to do it manually
public static void main(String[] args) {
Micronaut.build(args)
.mainClass(Application.class)
.defaultEnvironments("dev")
.start();
}
https://docs.micronaut.io/latest/guide/index.html#_default_environment

ASP.net Core web API Swagger UI version field - Is it possible to set this value in code?

I have a ASP.Net Core Web API with Swagger configured that shows the API End Points.Also API Versioning is enabled. However, the swagger UI is not populating the mandatory field Version when checking the End Point.See image below:
Is it possible to populate this field automatically by code given that the API Action already configures this value i.e. the MaptoApiVersion. In theory this field should be populated automatically??
[MapToApiVersion("2")]
[HttpGet("GetV2")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IEnumerable<TodoDto>> GetV2()
{
var query = new AllTodosQuery(_context);
var todos = await query.ExecuteAsync();
return todos;
}
The issue is at least two-fold. First, the extensions to the API Explorer from API Versioning do provide the version parameter with a default value, but many Swagger/OpenAPI generators (such as Swashbuckle) still do not yet honor it. If you want to enable this behavior, you need a custom IOperationFilter which does something to the effect of:
var parameter = operation.Parameters.First(p => p.Name == "version");
var description = context.ApiDescription.ParameterDescriptions.First(p => p.Name == "version");
if (parameter.Schema.Default == null && description.DefaultValue != null)
{
parameter.Schema.Default = new OpenApiString(description.DefaultValue.ToString());
}
You can find a complete end-to-end example in the API Versioning repo in:
SwaggerDefaultValues.cs
Since you're versioning by URL segment, if you want that inlined into the route template without a corresponding parameter, you need only configure the API Explorer extensions to do so like this:
services.AddVersionedApiExplorer(options => options.SubstituteApiVersionInUrl = true);
This option only applies to the URL segment versioning method.
A complete end-to-end Swashbuckle example with API Versioning can be found inside Startup.cs inside the repo.

GitLab new project setup webhook

I have GitLab setup on a server. Every time I create a new project under my user, I have to manually add a Web Hook by navigating to Project -> Settings -> Web Hooks -> Add Web Hook
Since many users will be creating projects on the hosted GitLab it will be difficult to setup Web Hooks for each project individually.
Is there a way, so that when a new project is created, it automatically (as default) sets up a Web Hook as part of the new project?
Any help is much appreciated.
You could probably find a way to automate this via the System Hooks API. Listen for the project_create hook event, then make a call to the project hook endpoint to add the one you want.
It's webhooks all the way down!
I found this script what do all you need:
recive the hook and execute the query insert of web hook
Run with php -S 0.0.0.0:8080
<?php
$allowed_host = "ip_of_your_gitlab_server";
$sql_host = "localhost_or_ip_of_your_mysql_server";
$sql_user = "..";
$sql_password = "..";
$database = "gitlabhq_production";
if ($_SERVER['REMOTE_ADDR'] == $allowed_host) { // ofc you could increase security with some kind of API key or w/e
$sql = mysqli_connect($sql_host, $sql_user, $sql_password, $database);
if (mysqli_connect_errno()) {
exit;
}
$file = fopen("/tmp/sql_error", "a"); // you can use this as debug log too ;)
$input = json_decode(file_get_contents('php://input'), true);
$pid = $input['project_id'];
if ($input['event_name'] == "project_create") {
$url = 'url_of_your_project_hook';
// this creates a project hook, specify it for your needs..
$q = mysqli_query($sql, "INSERT INTO gitlabhq_production.web_hooks (url, project_id) VALUES('$url', '$pid')");
if (!$q) fwrite($file, $sql->error);
} elseif ($input['event_name'] == "project_destroy")
$q = mysqli_query($sql, "DELETE FROM gitlabhq_production.web_hooks WHERE project_id='$pid'");
mysqli_close($sql);
} else {
// redirect?
exit;
}

WCF Client Configuration: how can I check if endpoint is in config file, and fallback to code if not?

Looking to make a Client that sends serialized Message objects back to a server via WCF.
To make things easy for the end-developer (different departments) would be best that they didn't need to know how to edit their config file to set up the client end point data.
That said, would also be brilliant that the endpoint wasn't embedded/hard-coded into the Client either.
A mix scenario would appear to me to be the easiest solution to roll out:
IF (described in config) USE config file ELSE fallback to hard-coded endpoint.
What I've found out is:
new Client(); fails if no config file definition found.
new Client(binding,endpoint); works
therefore:
Client client;
try {
client = new Client();
}catch {
//Guess not defined in config file...
//fall back to hard coded solution:
client(binding, endpoint)
}
But is there any way to check (other than try/catch) to see if config file has an endpoint declared?
Would the above not fail as well if defined in config file, but not configured right? Would be good to distinguish between the two conditions?
I would like to propose improved version of AlexDrenea solution, that uses only special types for configuration sections.
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup serviceModelGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);
if (serviceModelGroup != null)
{
ClientSection clientSection = serviceModelGroup.Client;
//make all your tests about the correcteness of the endpoints here
}
here is the way to read the configuration file and load the data into an easy to manage object:
Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSectionGroup csg = c.GetSectionGroup("system.serviceModel");
if (csg != null)
{
ConfigurationSection css = csg.Sections["client"];
if (css != null && css is ClientSection)
{
ClientSection cs = (ClientSection)csg.Sections["client"];
//make all your tests about the correcteness of the endpoints here
}
}
The "cs" object will expose a collection named "endpoints" that allows you to access all the properties that you find in the config file.
Make sure you also treat the "else" branches of the "if"s and treat them as fail cases (configuration is invalid).