Beispiel #1
0
 public void SetUp()
 {
     AppConfig.Destroy();
     AppConfig.Load(ConfigFactory.CreateXmlConfig(@".\config.xml"));
 }
 public MsgPackVersionToleranceTests() : base(ConfigFactory.GetConfig(typeof(MsgPackSerializer)))
 {
 }
Beispiel #3
0
        public static async Task <ApplicationBuilder> CreateAsync(OutputContext output, FileInfo source, string?framework = null, ApplicationFactoryFilter?filter = null)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var queue   = new Queue <(ConfigApplication, HashSet <string>)>();
            var visited = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            var rootConfig = ConfigFactory.FromFile(source);

            rootConfig.Validate();

            var root = new ApplicationBuilder(source, rootConfig.Name !, new ContainerEngine(rootConfig.ContainerEngineType))
            {
                Namespace = rootConfig.Namespace
            };

            queue.Enqueue((rootConfig, new HashSet <string>()));

            while (queue.TryDequeue(out var item))
            {
                // dependencies represents a set of all dependencies
                var(config, dependencies) = item;

                if (!visited.Add(config.Source.FullName))
                {
                    continue;
                }

                if (config == rootConfig && !string.IsNullOrEmpty(config.Registry))
                {
                    root.Registry = new ContainerRegistry(config.Registry);
                }

                if (config == rootConfig)
                {
                    root.Network = rootConfig.Network;
                }

                foreach (var configExtension in config.Extensions)
                {
                    var extension = new ExtensionConfiguration((string)configExtension["name"]);
                    foreach (var kvp in configExtension)
                    {
                        if (kvp.Key == "name")
                        {
                            continue;
                        }

                        extension.Data.Add(kvp.Key, kvp.Value);
                    }

                    root.Extensions.Add(extension);
                }

                var services = filter?.ServicesFilter != null?
                               config.Services.Where(filter.ServicesFilter).ToList() :
                                   config.Services;

                var sw = Stopwatch.StartNew();
                // Project services will be restored and evaluated before resolving all other services.
                // This batching will mitigate the performance cost of running MSBuild out of process.
                var projectServices = services.Where(s => !string.IsNullOrEmpty(s.Project));
                var projectMetadata = new Dictionary <string, string>();

                var msbuildEvaluationResult = await EvaluateProjectsAsync(
                    projects : projectServices,
                    configRoot : config.Source.DirectoryName !,
                    output : output);

                var msbuildEvaluationOutput = msbuildEvaluationResult
                                              .StandardOutput
                                              .Split(Environment.NewLine);

                var multiTFMProjects = new List <ConfigService>();

                foreach (var line in msbuildEvaluationOutput)
                {
                    var trimmed = line.Trim();
                    if (trimmed.StartsWith("Microsoft.Tye metadata: "))
                    {
                        var values       = line.Split(':', 3);
                        var projectName  = values[1].Trim();
                        var metadataPath = values[2].Trim();
                        projectMetadata.Add(projectName, metadataPath);

                        output.WriteDebugLine($"Resolved metadata for service {projectName} at {metadataPath}");
                    }
                    else if (trimmed.StartsWith("Microsoft.Tye cross-targeting project: "))
                    {
                        var values      = line.Split(':', 2);
                        var projectName = values[1].Trim();

                        var multiTFMConfigService = projectServices.First(p => string.Equals(p.Name, projectName, StringComparison.OrdinalIgnoreCase));
                        multiTFMConfigService.BuildProperties.Add(new BuildProperty {
                            Name = "TargetFramework", Value = framework ?? string.Empty
                        });
                        multiTFMProjects.Add(multiTFMConfigService);
                    }
                }

                if (multiTFMProjects.Any())
                {
                    output.WriteDebugLine("Re-evaluating multi-targeted projects");

                    var multiTFMEvaluationResult = await EvaluateProjectsAsync(
                        projects : multiTFMProjects,
                        configRoot : config.Source.DirectoryName !,
                        output : output);

                    var multiTFMEvaluationOutput = multiTFMEvaluationResult
                                                   .StandardOutput
                                                   .Split(Environment.NewLine);

                    foreach (var line in multiTFMEvaluationOutput)
                    {
                        var trimmed = line.Trim();
                        if (trimmed.StartsWith("Microsoft.Tye metadata: "))
                        {
                            var values       = line.Split(':', 3);
                            var projectName  = values[1].Trim();
                            var metadataPath = values[2].Trim();
                            projectMetadata.Add(projectName, metadataPath);

                            output.WriteDebugLine($"Resolved metadata for service {projectName} at {metadataPath}");
                        }
                        else if (trimmed.StartsWith("Microsoft.Tye cross-targeting project: "))
                        {
                            var values      = line.Split(':', 2);
                            var projectName = values[1].Trim();
                            throw new CommandException($"Unable to run {projectName}. Your project targets multiple frameworks. Specify which framework to run using '--framework' or a build property in tye.yaml.");
                        }
                    }
                }

                output.WriteDebugLine($"Restore and project evaluation took: {sw.Elapsed.TotalMilliseconds}ms");

                foreach (var configService in services)
                {
                    ServiceBuilder service;
                    if (root.Services.Any(s => s.Name == configService.Name))
                    {
                        // Even though this service has already created a service, we still need
                        // to update dependency information
                        AddToRootServices(root, dependencies, configService.Name);
                        continue;
                    }

                    if (!string.IsNullOrEmpty(configService.Project))
                    {
                        var project = new DotnetProjectServiceBuilder(configService.Name !, new FileInfo(configService.ProjectFullPath));
                        service = project;

                        project.Build = configService.Build ?? true;
                        project.Args  = configService.Args;
                        foreach (var buildProperty in configService.BuildProperties)
                        {
                            project.BuildProperties.Add(buildProperty.Name, buildProperty.Value);
                        }

                        project.Replicas = configService.Replicas ?? 1;
                        project.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        project.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;

                        // We don't apply more container defaults here because we might need
                        // to prompt for the registry name.
                        project.ContainerInfo = new ContainerInfo()
                        {
                            UseMultiphaseDockerfile = false,
                        };

                        // If project evaluation is successful this should not happen, therefore an exception will be thrown.
                        if (!projectMetadata.ContainsKey(configService.Name))
                        {
                            throw new CommandException($"Evaluated project metadata file could not be found for service {configService.Name}");
                        }

                        ProjectReader.ReadProjectDetails(output, project, projectMetadata[configService.Name]);

                        // Do k8s by default.
                        project.ManifestInfo = new KubernetesManifestInfo();
                    }
                    else if (!string.IsNullOrEmpty(configService.Image))
                    {
                        var container = new ContainerServiceBuilder(configService.Name !, configService.Image !)
                        {
                            Args     = configService.Args,
                            Replicas = configService.Replicas ?? 1
                        };
                        service = container;

                        container.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        container.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;
                    }
                    else if (!string.IsNullOrEmpty(configService.DockerFile))
                    {
                        var dockerFile = new DockerFileServiceBuilder(configService.Name !, configService.Image !)
                        {
                            Args       = configService.Args,
                            Build      = configService.Build ?? true,
                            Replicas   = configService.Replicas ?? 1,
                            DockerFile = Path.Combine(source.DirectoryName !, configService.DockerFile),
                            // Supplying an absolute path with trailing slashes fails for DockerFileContext when calling docker build, so trim trailing slash.
                            DockerFileContext = GetDockerFileContext(source, configService),
                            BuildArgs         = configService.DockerFileArgs
                        };
                        service = dockerFile;

                        dockerFile.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        dockerFile.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;

                        // We don't apply more container defaults here because we might need
                        // to prompt for the registry name.
                        dockerFile.ContainerInfo = new ContainerInfo()
                        {
                            UseMultiphaseDockerfile = false,
                        };

                        // Do k8s by default.
                        dockerFile.ManifestInfo = new KubernetesManifestInfo();
                    }
                    else if (!string.IsNullOrEmpty(configService.Executable))
                    {
                        var expandedExecutable = Environment.ExpandEnvironmentVariables(configService.Executable);
                        var workingDirectory   = "";

                        // Special handling of .dlls as executables (it will be executed as dotnet {dll})
                        if (Path.GetExtension(expandedExecutable) == ".dll")
                        {
                            expandedExecutable = Path.GetFullPath(Path.Combine(config.Source.Directory !.FullName, expandedExecutable));
                            workingDirectory   = Path.GetDirectoryName(expandedExecutable) !;
                        }

                        var executable = new ExecutableServiceBuilder(configService.Name !, expandedExecutable)
                        {
                            Args             = configService.Args,
                            WorkingDirectory = configService.WorkingDirectory != null?
                                               Path.GetFullPath(Path.Combine(config.Source.Directory !.FullName, Environment.ExpandEnvironmentVariables(configService.WorkingDirectory))) :
                                                   workingDirectory,
                                                   Replicas = configService.Replicas ?? 1
                        };
                        service = executable;

                        executable.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        executable.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;
                    }
                    else if (!string.IsNullOrEmpty(configService.Include))
                    {
                        var expandedYaml = Environment.ExpandEnvironmentVariables(configService.Include);

                        var nestedConfig = GetNestedConfig(rootConfig, Path.Combine(config.Source.DirectoryName !, expandedYaml));
                        queue.Enqueue((nestedConfig, new HashSet <string>()));

                        AddToRootServices(root, dependencies, configService.Name);
                        continue;
                    }
                    else if (!string.IsNullOrEmpty(configService.Repository))
                    {
                        // clone to .tye folder
                        var path = configService.CloneDirectory ?? Path.Join(".tye", "deps");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        var clonePath = Path.Combine(rootConfig.Source.DirectoryName !, path, configService.Name);

                        if (!Directory.Exists(clonePath))
                        {
                            if (!await GitDetector.Instance.IsGitInstalled.Value)
                            {
                                throw new CommandException($"Cannot clone repository {configService.Repository} because git is not installed. Please install git if you'd like to use \"repository\" in tye.yaml.");
                            }

                            var result = await ProcessUtil.RunAsync("git", $"clone {configService.Repository} \"{clonePath}\"", workingDirectory : rootConfig.Source.DirectoryName, throwOnError : false);

                            if (result.ExitCode != 0)
                            {
                                throw new CommandException($"Failed to clone repository {configService.Repository} with exit code {result.ExitCode}.{Environment.NewLine}{result.StandardError}{result.StandardOutput}.");
                            }
                        }

                        if (!ConfigFileFinder.TryFindSupportedFile(clonePath, out var file, out var errorMessage))
                        {
                            throw new CommandException(errorMessage !);
                        }

                        // pick different service type based on what is in the repo.
                        var nestedConfig = GetNestedConfig(rootConfig, file);

                        queue.Enqueue((nestedConfig, new HashSet <string>()));

                        AddToRootServices(root, dependencies, configService.Name);

                        continue;
                    }
                    else if (!string.IsNullOrEmpty(configService.AzureFunction))
                    {
                        var azureFunctionDirectory = Path.Combine(config.Source.DirectoryName !, configService.AzureFunction);

                        var functionBuilder = new AzureFunctionServiceBuilder(
                            configService.Name,
                            azureFunctionDirectory)
                        {
                            Args               = configService.Args,
                            Replicas           = configService.Replicas ?? 1,
                            FuncExecutablePath = configService.FuncExecutable,
                        };

                        foreach (var proj in Directory.EnumerateFiles(azureFunctionDirectory))
                        {
                            var fileInfo = new FileInfo(proj);
                            if (fileInfo.Extension == ".csproj" || fileInfo.Extension == ".fsproj")
                            {
                                functionBuilder.ProjectFile = fileInfo.FullName;
                                break;
                            }
                        }

                        // TODO liveness?
                        service = functionBuilder;
                    }
                    else if (configService.External)
                    {
                        var external = new ExternalServiceBuilder(configService.Name);
                        service = external;
                    }
                    else
                    {
                        throw new CommandException("Unable to determine service type.");
                    }

                    // Add dependencies to ourself before adding ourself to avoid self reference
                    service.Dependencies.UnionWith(dependencies);

                    AddToRootServices(root, dependencies, service.Name);

                    root.Services.Add(service);

                    // If there are no bindings and we're in ASP.NET Core project then add an HTTP and HTTPS binding
                    if (configService.Bindings.Count == 0 &&
                        service is ProjectServiceBuilder project2 &&
                        project2.IsAspNet)
                    {
                        // HTTP is the default binding
                        service.Bindings.Add(new BindingBuilder()
                        {
                            Protocol = "http"
                        });
                        service.Bindings.Add(new BindingBuilder()
                        {
                            Name = "https", Protocol = "https"
                        });
                    }
 public void TestInitialize()
 {
     AppDomain.MonitoringIsEnabled = true;
     this.configFactory            = new ConfigFactory();
 }
Beispiel #5
0
        public bool TiXian(Order order, TipsFlow tf, string accountnm, string storename, decimal balance, int aid, string accountid, decimal tips, decimal point, out string msg)
        {
            CompanyPay.AliPay ali = new CompanyPay.AliPay();

            Aop.Api.Response.AlipayFundTransToaccountTransferResponse response = ali.GetCompanyPay(order.Out_trade_no, accountid, (order.Total_amount - tips).ToString(), storename, accountnm, order.Remark);
            CompanyPay.LogHelper.WriteLine(Jayrock.Json.Conversion.JsonConvert.ExportToString(response));

            CompanyPay.LogHelper.WriteLine(response.Body);


            #region MyRegion
            try
            {
                TakeList takelist = takelistapp.Repository.GetWhere(r => r.Out_trade_no == order.Out_trade_no).FirstOrDefault();
                order = Repository.Get(order.Id);
                if (response.Code == "10000")
                {
                    Account account = accountapp.Get(aid);
                    if (account == null)
                    {
                        throw new Exception("找不到该资金账户");
                    }
                    using (var tran = new TransactionScope())
                    {
                        if (point >= 1)
                        {
                            UnitWork.RegisterNew(new PointDetail()
                            {
                                FromType = order.PayType, Money = order.Total_amount, CreateTime = DateTime.Now.ToLocalTime(), IsActive = true, Point = point, StoreId = order.StoreNo, StoreName = storename, BuyerId = accountid
                            });
                        }

                        UnitWork.RegisterDirty(tf, () => new TipsFlow {
                            IsActive = true
                        });
                        UnitWork.RegisterDirty(takelist, () => new TakeList {
                            State = 1
                        });

                        order.Gmt_payment  = Convert.ToDateTime(response.PayDate);
                        order.Trade_status = response.Code;
                        order.IsSuccess    = 1;
                        order.Trade_no     = response.OrderId;
                        UnitWork.RegisterDirty <Order>(order);

                        account.Balance -= order.Total_amount;
                        account.TakeOut += order.Total_amount;
                        UnitWork.RegisterDirty <Account>(account);

                        UnitWork.Commit();
                        tran.Complete();
                    }
                }
                else
                {  //失败
                    using (var tran = new TransactionScope())
                    {
                        UnitWork.RegisterDirty(takelist, () => new TakeList {
                            State = 2
                        });

                        UnitWork.RegisterDirty <Order>(order, () => new Order()
                        {
                            Gmt_payment  = DateTime.Now,
                            Trade_status = response.Code,
                            IsSuccess    = 2,
                            Remark       = response.SubMsg + "【" + response.SubCode + "】",
                        });

                        UnitWork.Commit();
                        tran.Complete();
                    }
                }
                if (response.IsError)
                {
                    msg = response.SubMsg;
                    return(false);
                }
                else
                {
                    msg = response.Msg;
                    return(true);
                }
            }
            catch (Exception)
            {
                //记录这笔成功订单 写入JSON
                if (response.Code == "10000")
                {
                    string orderstr = response.Body;
                    orderstr  = orderstr.Substring(0, orderstr.LastIndexOf("sign") - 3).Replace("alipay_fund_trans_toaccount_transfer_response", "ResponseOrder");
                    orderstr += ",\"oid\":" + order.Id + ",\"tfid\":" + tf.Id + ",\"aid\":" + aid + ",\"point\":" + point + "}}";
                    OrderJson    orderjson = ConfigFactory.GetConfig <OrderJson>();
                    SuccessOrder resOrder  = Newtonsoft.Json.JsonConvert.DeserializeObject <SuccessOrder>(orderstr);
                    if (orderjson == null || orderjson.list == null)
                    {
                        orderjson      = new OrderJson();
                        orderjson.list = new List <SuccessOrder>();
                    }
                    orderjson.list.Add(new SuccessOrder {
                        ResponseOrder = resOrder.ResponseOrder
                    });
                    ConfigFactory.SetConfig <OrderJson>(orderjson);
                    msg = "支付成功,订单有误";
                }
                else
                {
                    msg = response.SubMsg;
                }
                return(false);
            }
            #endregion
        }
Beispiel #6
0
 public void SetUp()
 {
     AppConfig.Destroy();
     AppConfig.Load(ConfigFactory.CreateXmlConfig(@".\config.xml"));
     _k = new Kernal("test2");
 }
Beispiel #7
0
        public static async Task <ApplicationBuilder> CreateAsync(OutputContext output, FileInfo source)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var config = ConfigFactory.FromFile(source);

            ValidateConfigApplication(config);

            var builder = new ApplicationBuilder(source, config.Name ?? source.Directory.Name.ToLowerInvariant());

            if (!string.IsNullOrEmpty(config.Registry))
            {
                builder.Registry = new ContainerRegistry(config.Registry);
            }

            foreach (var configService in config.Services)
            {
                ServiceBuilder service;
                if (!string.IsNullOrEmpty(configService.Project))
                {
                    var projectFile = new FileInfo(Path.Combine(builder.Source.DirectoryName, configService.Project));
                    var project     = new ProjectServiceBuilder(configService.Name, projectFile);
                    service = project;

                    project.Build    = configService.Build ?? true;
                    project.Args     = configService.Args;
                    project.Replicas = configService.Replicas ?? 1;

                    await ProjectReader.ReadProjectDetailsAsync(output, project);

                    // We don't apply more container defaults here because we might need
                    // to prompty for the registry name.
                    project.ContainerInfo = new ContainerInfo()
                    {
                        UseMultiphaseDockerfile = false,
                    };
                }
                else if (!string.IsNullOrEmpty(configService.Image))
                {
                    var container = new ContainerServiceBuilder(configService.Name, configService.Image);
                    container.Args     = configService.Args;
                    container.Replicas = configService.Replicas ?? 1;
                    service            = container;
                }
                else if (!string.IsNullOrEmpty(configService.Executable))
                {
                    var executable = new ExecutableServiceBuilder(configService.Name, configService.Executable);
                    executable.Args             = configService.Args;
                    executable.WorkingDirectory = configService.WorkingDirectory;
                    executable.Replicas         = configService.Replicas ?? 1;
                    service = executable;
                }
                else if (configService.External)
                {
                    var external = new ExternalServiceBuilder(configService.Name);
                    service = external;
                }
                else
                {
                    throw new CommandException("Unable to determine service type.");
                }

                builder.Services.Add(service);

                foreach (var configBinding in configService.Bindings)
                {
                    var binding = new BindingBuilder()
                    {
                        Name             = configBinding.Name,
                        AutoAssignPort   = configBinding.AutoAssignPort,
                        ConnectionString = configBinding.ConnectionString,
                        Host             = configBinding.Host,
                        ContainerPort    = configBinding.ContainerPort,
                        Port             = configBinding.Port,
                        Protocol         = configBinding.Protocol,
                    };

                    if (binding.ConnectionString == null)
                    {
                        binding.Protocol ??= "http";
                    }

                    service.Bindings.Add(binding);
                }

                foreach (var configEnvVar in configService.Configuration)
                {
                    var envVar = new EnvironmentVariable(configEnvVar.Name, configEnvVar.Value);
                    if (service is ProjectServiceBuilder project)
                    {
                        project.EnvironmentVariables.Add(envVar);
                    }
                    else if (service is ContainerServiceBuilder container)
                    {
                        container.EnvironmentVariables.Add(envVar);
                    }
                    else if (service is ExecutableServiceBuilder executable)
                    {
                        executable.EnvironmentVariables.Add(envVar);
                    }
                    else if (service is ExternalServiceBuilder)
                    {
                        throw new CommandException("External services do not support environment variables.");
                    }
                    else
                    {
                        throw new CommandException("Unable to determine service type.");
                    }
                }

                foreach (var configVolume in configService.Volumes)
                {
                    var volume = new VolumeBuilder(configVolume.Source, configVolume.Target);
                    if (service is ProjectServiceBuilder project)
                    {
                        project.Volumes.Add(volume);
                    }
                    else if (service is ContainerServiceBuilder container)
                    {
                        container.Volumes.Add(volume);
                    }
                    else if (service is ExecutableServiceBuilder executable)
                    {
                        throw new CommandException("Executable services do not support volumes.");
                    }
                    else if (service is ExternalServiceBuilder)
                    {
                        throw new CommandException("External services do not support volumes.");
                    }
                    else
                    {
                        throw new CommandException("Unable to determine service type.");
                    }
                }
            }

            foreach (var configIngress in config.Ingress)
            {
                var ingress = new IngressBuilder(configIngress.Name);
                ingress.Replicas = configIngress.Replicas ?? 1;

                builder.Ingress.Add(ingress);

                foreach (var configBinding in configIngress.Bindings)
                {
                    var binding = new IngressBindingBuilder()
                    {
                        AutoAssignPort = configBinding.AutoAssignPort,
                        Name           = configBinding.Name,
                        Port           = configBinding.Port,
                        Protocol       = configBinding.Protocol ?? "http",
                    };
                    ingress.Bindings.Add(binding);
                }

                foreach (var configRule in configIngress.Rules)
                {
                    var rule = new IngressRuleBuilder()
                    {
                        Host    = configRule.Host,
                        Path    = configRule.Path,
                        Service = configRule.Service,
                    };
                    ingress.Rules.Add(rule);
                }
            }

            return(builder);
        }
Beispiel #8
0
        public static async Task <ApplicationBuilder> CreateAsync(OutputContext output, FileInfo source)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var queue   = new Queue <(ConfigApplication, HashSet <string>)>();
            var visited = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            var rootConfig = ConfigFactory.FromFile(source);

            rootConfig.Validate();

            var root = new ApplicationBuilder(source, rootConfig.Name ?? source.Directory.Name.ToLowerInvariant());

            root.Namespace = rootConfig.Namespace;

            queue.Enqueue((rootConfig, new HashSet <string>()));

            while (queue.Count > 0)
            {
                var item   = queue.Dequeue();
                var config = item.Item1;

                // dependencies represents a set of all dependencies
                var dependencies = item.Item2;
                if (!visited.Add(config.Source.FullName))
                {
                    continue;
                }

                if (config == rootConfig && !string.IsNullOrEmpty(config.Registry))
                {
                    root.Registry = new ContainerRegistry(config.Registry);
                }

                if (config == rootConfig)
                {
                    root.Network = rootConfig.Network;
                }

                foreach (var configExtension in config.Extensions)
                {
                    var extension = new ExtensionConfiguration((string)configExtension["name"]);
                    foreach (var kvp in configExtension)
                    {
                        if (kvp.Key == "name")
                        {
                            continue;
                        }

                        extension.Data.Add(kvp.Key, kvp.Value);
                    }

                    root.Extensions.Add(extension);
                }

                foreach (var configService in config.Services)
                {
                    ServiceBuilder service;
                    if (root.Services.Any(s => s.Name == configService.Name))
                    {
                        // Even though this service has already created a service, we still need
                        // to update dependency information
                        AddToRootServices(root, dependencies, configService.Name);
                        continue;
                    }

                    if (!string.IsNullOrEmpty(configService.Project))
                    {
                        var expandedProject = Environment.ExpandEnvironmentVariables(configService.Project);
                        var projectFile     = new FileInfo(Path.Combine(config.Source.DirectoryName, expandedProject));
                        var project         = new DotnetProjectServiceBuilder(configService.Name !, projectFile);
                        service = project;

                        project.Build = configService.Build ?? true;
                        project.Args  = configService.Args;
                        foreach (var buildProperty in configService.BuildProperties)
                        {
                            project.BuildProperties.Add(buildProperty.Name, buildProperty.Value);
                        }
                        project.Replicas = configService.Replicas ?? 1;

                        project.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        project.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;

                        // We don't apply more container defaults here because we might need
                        // to prompt for the registry name.
                        project.ContainerInfo = new ContainerInfo()
                        {
                            UseMultiphaseDockerfile = false,
                        };

                        await ProjectReader.ReadProjectDetailsAsync(output, project);

                        // Do k8s by default.
                        project.ManifestInfo = new KubernetesManifestInfo();
                    }
                    else if (!string.IsNullOrEmpty(configService.Image))
                    {
                        var container = new ContainerServiceBuilder(configService.Name !, configService.Image !)
                        {
                            Args     = configService.Args,
                            Replicas = configService.Replicas ?? 1
                        };
                        service = container;

                        container.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        container.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;
                    }
                    else if (!string.IsNullOrEmpty(configService.DockerFile))
                    {
                        var dockerFile = new DockerFileServiceBuilder(configService.Name !, configService.Image !)
                        {
                            Args       = configService.Args,
                            Build      = configService.Build ?? true,
                            Replicas   = configService.Replicas ?? 1,
                            DockerFile = Path.Combine(source.DirectoryName, configService.DockerFile),
                            // Supplying an absolute path with trailing slashes fails for DockerFileContext when calling docker build, so trim trailing slash.
                            DockerFileContext = GetDockerFileContext(source, configService)
                        };
                        service = dockerFile;

                        dockerFile.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        dockerFile.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;

                        // We don't apply more container defaults here because we might need
                        // to prompt for the registry name.
                        dockerFile.ContainerInfo = new ContainerInfo()
                        {
                            UseMultiphaseDockerfile = false,
                        };

                        // Do k8s by default.
                        dockerFile.ManifestInfo = new KubernetesManifestInfo();
                    }
                    else if (!string.IsNullOrEmpty(configService.Executable))
                    {
                        var expandedExecutable = Environment.ExpandEnvironmentVariables(configService.Executable);
                        var workingDirectory   = "";

                        // Special handling of .dlls as executables (it will be executed as dotnet {dll})
                        if (Path.GetExtension(expandedExecutable) == ".dll")
                        {
                            expandedExecutable = Path.GetFullPath(Path.Combine(config.Source.Directory.FullName, expandedExecutable));
                            workingDirectory   = Path.GetDirectoryName(expandedExecutable) !;
                        }

                        var executable = new ExecutableServiceBuilder(configService.Name !, expandedExecutable)
                        {
                            Args             = configService.Args,
                            WorkingDirectory = configService.WorkingDirectory != null?
                                               Path.GetFullPath(Path.Combine(config.Source.Directory.FullName, Environment.ExpandEnvironmentVariables(configService.WorkingDirectory))) :
                                                   workingDirectory,
                                                   Replicas = configService.Replicas ?? 1
                        };
                        service = executable;

                        executable.Liveness = configService.Liveness != null?GetProbeBuilder(configService.Liveness) : null;

                        executable.Readiness = configService.Readiness != null?GetProbeBuilder(configService.Readiness) : null;
                    }
                    else if (!string.IsNullOrEmpty(configService.Include))
                    {
                        var expandedYaml = Environment.ExpandEnvironmentVariables(configService.Include);

                        var nestedConfig = GetNestedConfig(rootConfig, Path.Combine(config.Source.DirectoryName, expandedYaml));
                        queue.Enqueue((nestedConfig, new HashSet <string>()));

                        AddToRootServices(root, dependencies, configService.Name);
                        continue;
                    }
                    else if (!string.IsNullOrEmpty(configService.Repository))
                    {
                        // clone to .tye folder
                        var path = Path.Join(rootConfig.Source.DirectoryName, ".tye", "deps");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        var clonePath = Path.Combine(path, configService.Name);

                        if (!Directory.Exists(clonePath))
                        {
                            if (!await GitDetector.Instance.IsGitInstalled.Value)
                            {
                                throw new CommandException($"Cannot clone repository {configService.Repository} because git is not installed. Please install git if you'd like to use \"repository\" in tye.yaml.");
                            }

                            var result = await ProcessUtil.RunAsync("git", $"clone {configService.Repository} {clonePath}", workingDirectory : path, throwOnError : false);

                            if (result.ExitCode != 0)
                            {
                                throw new CommandException($"Failed to clone repository {configService.Repository} with exit code {result.ExitCode}.{Environment.NewLine}{result.StandardError}{result.StandardOutput}.");
                            }
                        }

                        if (!ConfigFileFinder.TryFindSupportedFile(clonePath, out var file, out var errorMessage))
                        {
                            throw new CommandException(errorMessage !);
                        }

                        // pick different service type based on what is in the repo.
                        var nestedConfig = GetNestedConfig(rootConfig, file);

                        queue.Enqueue((nestedConfig, new HashSet <string>()));

                        AddToRootServices(root, dependencies, configService.Name);

                        continue;
                    }
                    else if (configService.External)
                    {
                        var external = new ExternalServiceBuilder(configService.Name !);
                        service = external;
                    }
                    else
                    {
                        throw new CommandException("Unable to determine service type.");
                    }

                    // Add dependencies to ourself before adding ourself to avoid self reference
                    service.Dependencies.UnionWith(dependencies);

                    AddToRootServices(root, dependencies, service.Name);

                    root.Services.Add(service);

                    // If there are no bindings and we're in ASP.NET Core project then add an HTTP and HTTPS binding
                    if (configService.Bindings.Count == 0 &&
                        service is ProjectServiceBuilder project2 &&
                        project2.IsAspNet)
                    {
                        // HTTP is the default binding
                        service.Bindings.Add(new BindingBuilder()
                        {
                            Protocol = "http"
                        });
                        service.Bindings.Add(new BindingBuilder()
                        {
                            Name = "https", Protocol = "https"
                        });
                    }
 private InteractConfig GetConfigFromFile(string fileName)
 {
     return(ConfigFactory.DeserializeXml <InteractConfig>(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Scripts", fileName))));
 }
        public FirstTimeSetup()
        {
            InitializeComponent();

            //create the password entry view
            PasswordEntryView pep = new PasswordEntryView();

            pep.OnSave += new EventHandler((o, e) =>
            {
                //get the public key ASN1
                SubjectPublicKeyInfo pubki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(m_keypair.Public);
                //get the private key ASN1
                PrivateKeyInfo privki = PrivateKeyInfoFactory.CreatePrivateKeyInfo(m_keypair.Private);

                //encrypt the private key
                byte[] encPrivKey = Crypto.EncryptKey(privki.GetDerEncoded(), pep.Text);
                m_keypair         = null;

                //delete the old notebooks
                if (Directory.Exists(NoteManager.GetNotebookDir()))
                {
                    Directory.Delete(NoteManager.GetNotebookDir(), true);
                }

                //save the keys to file
                KeyManager.SaveKeys(encPrivKey, pubki.GetDerEncoded());

                //erase the data
                Eraser.SecureErase(encPrivKey);

                //ask if the user wants to use a fingerprint
                IFingerprint fp = FingerprintFactory.GetInstance();
                fp.InitReader();
                if (fp.IsReady())
                {
                    Application.Current.MainPage = new FingerprintPage(new EventHandler((oo, ee) =>
                    {
                        byte[] data = (byte[])oo; //page returns the encrypted password
                        if (data != null)
                        {                         //only if was not skipped
                            //encrypt the password and save it
                            ConfigFactory.GetInstance().EncryptedPassword = data;
                            ConfigFactory.GetInstance().UseFingerprint    = true;
                        }
                        else
                        {
                            ConfigFactory.GetInstance().EncryptedPassword = new byte[] { 0 };
                            ConfigFactory.GetInstance().UseFingerprint    = false;
                        }
                        //trigger the setup complete event
                        if (OnSetupComplete != null)
                        {
                            OnSetupComplete(this, new EventArgs());
                        }
                    }), fp, pep.Text);
                }
                else
                {
                    //trigger the setup complete event
                    if (OnSetupComplete != null)
                    {
                        OnSetupComplete(this, new EventArgs());
                    }
                }
            });

            //create the activity indicator layout
            StackLayout actLayout = new StackLayout()
            {
                VerticalOptions = LayoutOptions.CenterAndExpand
            };
            ActivityIndicator actInd = new ActivityIndicator();;

            actLayout.Children.Add(actInd);
            actLayout.Children.Add(new Label()
            {
                Text = "Generating key pair", TextColor = Color.DarkGray, HorizontalTextAlignment = TextAlignment.Center
            });

            TapRandomizer tapRnd = new TapRandomizer();

            tapRnd.OnRandomized += new EventHandler((o, e) =>
            {
                m_seed = tapRnd.Seed;
                //show wait animation
                actInd.IsRunning = true;
                this.Content     = actLayout;
                //generate the key pair
                Crypto.StartGenerateKeypair(m_seed, new Crypto.GenCompleteEventHandler((keypair) =>
                {
                    m_keypair = keypair;
                    //hide wait animation
                    actInd.IsRunning = false;
                    //show the password entry page
                    this.Content = pep;
                }));
            });

            this.Content = tapRnd;
        }
Beispiel #11
0
        public static Task GenerateAsync(IConsole console, FileInfo path, Verbosity verbosity, bool interactive)
        {
            var application = ConfigFactory.FromFile(path);

            return(ExecuteGenerateAsync(new OutputContext(console, verbosity), application, environment: "production", interactive));
        }
Beispiel #12
0
 public void SetUp()
 {
     if (!AppConfig.Loaded)
         AppConfig.Load(ConfigFactory.CreateXmlConfig());
 }
Beispiel #13
0
        public bool UpdateEx(Order input)
        {
            OrderJson           orderjson = ConfigFactory.GetConfig <OrderJson>() ?? new OrderJson();
            List <SuccessOrder> list      = orderjson.list;

            if (list == null || list.Count == 0)
            {
                return(false);
            }
            SuccessOrder success = list.FirstOrDefault(r => r.ResponseOrder.out_biz_no == input.Out_trade_no);
            var          flag    = false;

            if (success != null)
            {
                ResponseOrder res      = success.ResponseOrder;
                TakeList      takelist = takelistapp.Repository.GetWhere(r => r.Out_trade_no == res.out_biz_no).FirstOrDefault();
                Order         order    = Repository.Get(res.oid);
                if (order == null || order.Out_trade_no != input.Out_trade_no)
                {
                    throw new MsgException("文件信息有误.");
                }
                if (order.IsSuccess != 0)
                {
                    throw new MsgException("订单已经改写,不能覆盖.");
                }

                Account  account = accountapp.Get(res.aid);
                TipsFlow tf      = tipsflowapp.Get(res.tfid);
                if (tf == null || tf.IsActive == true)
                {
                    throw new MsgException("手续费信息有误");
                }
                if (account == null)
                {
                    throw new MsgException("找不到该资金账户");
                }
                using (var tran = new TransactionScope())
                {
                    if (res.point >= 1)
                    {
                        UnitWork.RegisterNew(new PointDetail()
                        {
                            FromType = order.PayType, Money = order.Total_amount, CreateTime = DateTime.Now, IsActive = true, Point = res.point, StoreId = order.StoreNo, StoreName = takelist.StoreName, BuyerId = takelist.Account
                        });
                    }

                    UnitWork.RegisterDirty(tf, () => new TipsFlow {
                        IsActive = true
                    });
                    UnitWork.RegisterDirty(takelist, () => new TakeList {
                        State = 1
                    });

                    order.Gmt_payment  = Convert.ToDateTime(res.pay_date);
                    order.Trade_status = res.code;
                    order.IsSuccess    = 1;
                    order.Trade_no     = res.order_id;
                    UnitWork.RegisterDirty <Order>(order);

                    account.Balance -= order.Total_amount;
                    account.TakeOut += order.Total_amount;
                    UnitWork.RegisterDirty <Account>(account);

                    UnitWork.Commit();
                    tran.Complete();
                }
                list.Remove(success);
                //订单Json文件修改.
                ConfigFactory.SetConfig <OrderJson>(orderjson);

                flag = true;
            }
            else
            {
                throw new MsgException("未找到该订单信息");
            }
            return(flag);
        }
Beispiel #14
0
        public static async Task <ApplicationBuilder> CreateAsync(OutputContext output, FileInfo source)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var config = ConfigFactory.FromFile(source);

            ValidateConfigApplication(config);

            var builder = new ApplicationBuilder(source, config.Name ?? source.Directory.Name.ToLowerInvariant());

            if (!string.IsNullOrEmpty(config.Registry))
            {
                builder.Registry = new ContainerRegistry(config.Registry);
            }

            builder.Network = config.Network;

            foreach (var configExtension in config.Extensions)
            {
                var extension = new ExtensionConfiguration((string)configExtension["name"]);
                foreach (var kvp in configExtension)
                {
                    if (kvp.Key == "name")
                    {
                        continue;
                    }

                    extension.Data.Add(kvp.Key, kvp.Value);
                }

                builder.Extensions.Add(extension);
            }

            foreach (var configService in config.Services)
            {
                ServiceBuilder service;
                if (!string.IsNullOrEmpty(configService.Project))
                {
                    var expandedProject = Environment.ExpandEnvironmentVariables(configService.Project);
                    var projectFile     = new FileInfo(Path.Combine(builder.Source.DirectoryName, expandedProject));
                    var project         = new ProjectServiceBuilder(configService.Name, projectFile);
                    service = project;

                    project.Build    = configService.Build ?? true;
                    project.Args     = configService.Args;
                    project.Replicas = configService.Replicas ?? 1;

                    await ProjectReader.ReadProjectDetailsAsync(output, project);

                    // We don't apply more container defaults here because we might need
                    // to prompt for the registry name.
                    project.ContainerInfo = new ContainerInfo()
                    {
                        UseMultiphaseDockerfile = false,
                    };

                    // Do k8s by default.
                    project.ManifestInfo = new KubernetesManifestInfo();
                }
                else if (!string.IsNullOrEmpty(configService.Image))
                {
                    var container = new ContainerServiceBuilder(configService.Name, configService.Image)
                    {
                        Args     = configService.Args,
                        Replicas = configService.Replicas ?? 1
                    };
                    service = container;
                }
                else if (!string.IsNullOrEmpty(configService.Executable))
                {
                    var expandedExecutable = Environment.ExpandEnvironmentVariables(configService.Executable);
                    var workingDirectory   = "";

                    // Special handling of .dlls as executables (it will be executed as dotnet {dll})
                    if (Path.GetExtension(expandedExecutable) == ".dll")
                    {
                        expandedExecutable = Path.GetFullPath(Path.Combine(builder.Source.Directory.FullName, expandedExecutable));
                        workingDirectory   = Path.GetDirectoryName(expandedExecutable) !;
                    }

                    var executable = new ExecutableServiceBuilder(configService.Name, expandedExecutable)
                    {
                        Args             = configService.Args,
                        WorkingDirectory = configService.WorkingDirectory != null?
                                           Path.GetFullPath(Path.Combine(builder.Source.Directory.FullName, Environment.ExpandEnvironmentVariables(configService.WorkingDirectory))) :
                                               workingDirectory,
                                               Replicas = configService.Replicas ?? 1
                    };
                    service = executable;
                }
                else if (configService.External)
                {
                    var external = new ExternalServiceBuilder(configService.Name);
                    service = external;
                }
                else
                {
                    throw new CommandException("Unable to determine service type.");
                }

                builder.Services.Add(service);

                // If there are no bindings and we're in ASP.NET Core project then add an HTTP and HTTPS binding
                if (configService.Bindings.Count == 0 &&
                    service is ProjectServiceBuilder project2 &&
                    project2.IsAspNet)
                {
                    // HTTP is the default binding
                    service.Bindings.Add(new BindingBuilder()
                    {
                        Protocol = "http"
                    });

                    service.Bindings.Add(new BindingBuilder()
                    {
                        Name     = "https",
                        Protocol = "https"
                    });
                }
Beispiel #15
0
 private static IValidationConfigProvider ResolveConfig()
 => ConfigFactory.GetConfig <IValidationConfigProvider, ValidationConfig>(cfgContract.Value);
Beispiel #16
0
        public static (string, string) CreateTyeFileContent(FileInfo?path, bool force)
        {
            if (path is FileInfo && path.Exists && !force)
            {
                ThrowIfTyeFilePresent(path, "tye.yml");
                ThrowIfTyeFilePresent(path, "tye.yaml");
            }

            var template = @"
# tye application configuration file
# read all about it at https://github.com/dotnet/tye
#
# when you've given us a try, we'd love to know what you think:
#    https://aka.ms/AA7q20u
#
# define global settings here
# name: exampleapp # application name
# registry: exampleuser # dockerhub username or container registry hostname

# define multiple services here
services:
- name: myservice
  # project: app.csproj # msbuild project path (relative to this file)
  # executable: app.exe # path to an executable (relative to this file)
  # args: --arg1=3 # arguments to pass to the process
  # replicas: 5 # number of times to launch the application
  # env: # array of environment variables
  #  - name: key
  #    value: value
  # bindings: # optional array of bindings (ports, connection strings)
    # - port: 8080 # number port of the binding
".TrimStart();

            // Output in the current directory unless an input file was provided, then
            // output next to the input file.
            var outputFilePath = "tye.yaml";

            if (path is FileInfo && path.Exists)
            {
                var application = ConfigFactory.FromFile(path);
                var serializer  = YamlSerializer.CreateSerializer();

                var extension = path.Extension.ToLowerInvariant();
                var directory = path.Directory;

                // Clear all bindings if any for solutions and project files
                if (extension == ".sln" || extension == ".csproj" || extension == ".fsproj")
                {
                    // If the input file is a project or solution then use that as the name
                    application.Extensions = null !;
                    application.Ingress    = null !;

                    foreach (var service in application.Services)
                    {
                        service.Bindings      = null !;
                        service.Configuration = null !;
                        service.Volumes       = null !;
                        service.Project       = service.Project !.Substring(directory.FullName.Length).TrimStart('/');
                    }

                    // If the input file is a sln/project then place the config next to it
                    outputFilePath = Path.Combine(directory.FullName, "tye.yaml");
                }
                else
                {
                    // If the input file is a yaml, then replace it.
                    outputFilePath = path.FullName;
                }

                template = @"
# tye application configuration file
# read all about it at https://github.com/dotnet/tye
#
# when you've given us a try, we'd love to know what you think:
#    https://aka.ms/AA7q20u
#
".TrimStart() + serializer.Serialize(application);
            }

            return(template, outputFilePath);
        }
Beispiel #17
0
 public void TestFixtureSetUp()
 {
     AppConfig.Destroy();
     AppConfig.Load(ConfigFactory.CreateXmlConfig(@"..\..\_ConfigFiles\config.xml"));
 }
Beispiel #18
0
        public async Task SingleProjectRunTest()
        {
            var projectDirectory = new DirectoryInfo(Path.Combine(TestHelpers.GetSolutionRootDirectory("tye"), "samples", "single-project", "test-project"));

            using var tempDirectory = TempDirectory.Create();
            DirectoryCopy.Copy(projectDirectory.FullName, tempDirectory.DirectoryPath);

            var projectFile = new FileInfo(Path.Combine(tempDirectory.DirectoryPath, "test-project.csproj"));

            using var host = new TyeHost(ConfigFactory.FromFile(projectFile).ToHostingApplication(), Array.Empty <string>())
                  {
                      Sink = sink,
                  };

            await host.StartAsync();

            try
            {
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (a, b, c, d) => true,
                    AllowAutoRedirect = false
                };

                var client = new HttpClient(new RetryHandler(handler));

                // Make sure dashboard and applications are up.
                // Dashboard should be hosted in same process.
                var dashboardUri    = new Uri(host.DashboardWebApplication !.Addresses.First());
                var dashboardString = await client.GetStringAsync($"{dashboardUri}api/v1/services/test-project");

                var service           = JsonSerializer.Deserialize <V1Service>(dashboardString, _options);
                var binding           = service.Description !.Bindings.Where(b => b.Protocol == "http").Single();
                var uriBackendProcess = new Uri($"{binding.Protocol}://localhost:{binding.Port}");

                // This isn't reliable right now because micronetes only guarantees the process starts, not that
                // that kestrel started.
                try
                {
                    var appResponse = await client.GetAsync(uriBackendProcess);

                    Assert.Equal(HttpStatusCode.OK, appResponse.StatusCode);
                }
                finally
                {
                    // If we failed, there's a good chance the service isn't running. Let's get the logs either way and put
                    // them in the output.
                    var request  = new HttpRequestMessage(HttpMethod.Get, new Uri(dashboardUri, $"/api/v1/logs/{service.Description.Name}"));
                    var response = await client.SendAsync(request);

                    var text = await response.Content.ReadAsStringAsync();

                    output.WriteLine($"Logs for service: {service.Description.Name}");
                    output.WriteLine(text);
                }
            }
            finally
            {
                await host.StopAsync();
            }
        }
Beispiel #19
0
 public static Mode Detect(X509Certificate certificate) // throws PeppolLoadingException
 {
     return(Detect(certificate, ConfigFactory.Load()));
 }