Exemple #1
0
        protected void StartWebAppHost(
            SingleWebHostTestConfiguration configuration)
        {
            if (null == configuration)
            {
                throw new ArgumentNullException("configuration");
            }

            this.Config = configuration;

            this.Server = IisExpress.Start(
                configuration.WebHostConfig,
                configuration.AttachDebugger);

            this.HttpClient = new HttpClient
            {
                BaseAddress = new Uri(configuration.ApplicationUri)
            };

            this.Listener = new HttpListenerObservable(configuration.TelemetryListenerUri);
            this.Listener.Start();

            this.EtwSession = new EtwEventSession();
            this.EtwSession.Start();
        }
        public static void AssemblyInit(TestContext context)
        {
            Console.WriteLine("CredentialFixture ctor: This should only be run once");
            EventHub.OnDebugMessage   += LogHelper.HandleLogMessage;
            EventHub.OnErrorMessage   += LogHelper.HandleLogMessage;
            EventHub.OnFatalMessage   += LogHelper.HandleLogMessage;
            EventHub.OnInfoMessage    += LogHelper.HandleLogMessage;
            EventHub.OnVerboseMessage += LogHelper.HandleLogMessage;
            EventHub.OnWarnMessage    += LogHelper.HandleLogMessage;

            string solutionFolder = GetSolutionFolder(System.IO.Path.GetFullPath("."));

            var workingDirectory = System.IO.Path.Combine(solutionFolder, @"Metriks.Service");
            var configPath       = System.IO.Path.Combine(solutionFolder, @".vs\Metriks\config\applicationhost.config");

            _iisExpress = new IisExpress();

            _iisExpress.Start(configPath, workingDirectory);
            // Executes once before the test run. (Optional)
        }
Exemple #3
0
        public override bool Execute()
        {
            if (System.Type.GetType("Mono.Runtime") != null)               // Don't execute under Mono.
            {
                Log.LogMessage(MessageImportance.High, "The GenerateWebProxies task doesn't run under Mono.");
                return(true);
            }
            if ((Files == null || (Urls == null && Sources == null)) && SourceProject == null)
            {
                return(true);
            }

            var tool = ToolExe;

            if (tool == null)
            {
                Log.LogError("GenerateWebProxies: Cannot find " + (WCF ? "svcutil.exe" : "wsdl.exe") + ", please install Windows SDK.");
            }


            var projTime = string.IsNullOrEmpty(Project) ? DateTime.MinValue : File.GetLastWriteTimeUtc(Project);

            DateTime[] sourceTimes = null;

            IisExpress.SSL = SSL;
            var iisport       = IisExpress.RandomPort;
            var useIisExpress = Urls == null;
            var newiis        = false;

            if (Urls == null || AutoRest || Swagger)
            {
                var site = Path.GetFullPath(SourceProject).Trim('\\');
                newiis = IisExpress.SiteFolder != site || !IisExpress.IsStarted;
                if (newiis)
                {
                    IisExpress.SiteFolder = site;
                }
            }

            if (!newiis)
            {
                iisport = IisExpress.Port.Value;
            }

            var ServerUrl = (SSL ? "https" : "http") + "://localhost:" + iisport.ToString() + "/";

            if (Urls == null)
            {
                if (!AutoRest && !Swagger)
                {
                    Sources = Sources ?? Directory.EnumerateFiles(SourceProject, WCF ? "*.svc" : "*.asmx", SearchOption.AllDirectories)
                              .Where(p => !(Exclude?.Any(x => x.ItemSpec == p) ?? false))
                              .Select(path => new TaskItem(path)).ToArray();

                    Urls = Sources.Select(src => new TaskItem(ServerUrl + src.ItemSpec.Substring(SourceProject.Length).Trim('\\', '/', ' ').Replace('\\', '/') /*+ (WCF ? "?wsdl" : "") */))
                           .ToArray();
                    var files = Sources.Select(src => new TaskItem(Path.ChangeExtension(src.ItemSpec.Substring(SourceProject.Length), (FileSuffix ?? Type.ToString()) + "." + Language.ToLower())))
                                .ToDictionary(src => src.ItemSpec);
                    if (Files == null)
                    {
                        Files = files.Values.ToArray();
                    }
                    else
                    {
                        var items = Files.ToDictionary(f => f.ItemSpec);
                        Files = files.Values.Select(f => items.ContainsKey(f.ItemSpec) ? items[f.ItemSpec] : f).ToArray();
                    }
                    var regex = new Regex(@"<%@ (?:WebService|ServiceHost).*?(?:CodeBehind|CodeFile)\s*=\s*(?:(?:""(?<code>[^""]*)"")|(?:'(?<code>[^']*)')).*?%>");
                    sourceTimes = Sources.Select(src => {                     // get times of svc or asmx C# source files
                        var sourceInfo = new FileInfo(src.ItemSpec);
                        if (sourceInfo.Exists)
                        {
                            var m = regex.Match(File.ReadAllText(src.ItemSpec));
                            var t = sourceInfo.LastWriteTimeUtc;
                            if (m.Success)
                            {
                                var codeInfo = new FileInfo(Path.Combine(Path.GetDirectoryName(src.ItemSpec), m.Groups["code"].Value));
                                var codet    = codeInfo.Exists ? codeInfo.LastWriteTimeUtc : DateTime.MinValue;
                                return(codet > t ? codet : t);
                            }
                        }
                        return(DateTime.MinValue);
                    }).ToArray();
                }
            }
            var output    = new List <TaskItem>();
            var processes = new ProcessCollection();
            var startTime = DateTime.UtcNow;

            var wait = new ManualResetEvent(false);

            var iisstarted   = false;
            var anyprocesses = false;

            System.Net.ServicePointManager.DefaultConnectionLimit = 9999;

            var serverError = false;

            if (!AutoRest && !Swagger)
            {
                System.Threading.Tasks.Parallel.For(0, Urls.Length, i => {
                    //for (int i = 0; i < Urls.Length; i++) {
                    try {
                        var meta = Files[i].GetMetadata(Meta);
                        if (!string.IsNullOrEmpty(Meta) && !string.IsNullOrEmpty(meta) && meta != "false")
                        {
                            return;
                        }

                        var url  = Urls[i].ItemSpec;
                        var file = Files[i].ItemSpec;
                        var src  = Sources?[i].ItemSpec;
                        var ns   = Files[i].GetMetadata("Namespace");
                        if (string.IsNullOrEmpty(ns))
                        {
                            ns = Namespace;
                        }
                        var config                 = Config != null ? $"/config:{Config} /mergeConfig " : "";
                        var serializer             = Serializer != null ? $"/serializer:{Serializer} " : "";
                        var useSerializerForFaults = Serializer != null && UseSerializerForFaults ? $"/useSerializerForFaults " : "";
                        var async        = Async ? "/async " : "/syncOnly ";
                        string reference = "";
                        if (Reference != null)
                        {
                            var refs = Reference.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
                            var str  = new StringBuilder();
                            foreach (var r in refs)
                            {
                                str.Append("\"/r:");
                                str.Append(Path.GetFullPath(r));
                                str.Append("\" ");
                            }
                            reference = str.ToString();
                        }
                        var targetVersion     = TargetClientVersion != null ? $"/targetClientVersion:{TargetClientVersion} " : "";
                        var importXmlTypes    = ImportXmlTypes ? "/importXmlTypes " : "";
                        var dataContractOnly  = DataContractOnly ? "/dataContractOnly " : "";
                        var serviceContract   = ServiceContract ? "/serviceContract " : "";
                        var enableDataBinding = EnableDataBinding ? "/enableDataBinding " : "";
                        string excludeType    = "";
                        if (ExcludeType != null)
                        {
                            var types = ExcludeType.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
                            var str   = new StringBuilder();
                            foreach (var t in types)
                            {
                                str.Append("\"/et:");
                                str.Append(Path.GetFullPath(t));
                                str.Append("\" ");
                            }
                            excludeType = str.ToString();
                        }
                        var _internal   = Internal ? "/internal " : "";
                        var mergeConfig = MergeConfig ? "/mergeConfig " : "";
                        var noConfig    = NoConfig ? "/noConfig " : "";
                        var noStdLib    = NoStdLib ? "/noStdLib " : "";

                        var arg = WCF ? $"/t:code /out:{file} /namespace:{ns} /language:{Language} {config}{serializer}{useSerializerForFaults}{async}{targetVersion}{importXmlTypes}{reference}{dataContractOnly}{serviceContract}{enableDataBinding}{excludeType}{_internal}{mergeConfig}{noConfig}{noStdLib}{url}" :
                                  $"/out:{file} /namespace:{ns} /language:{Language} /protocol:{Protocol}" + (WSE ? " /type:" + (type == Types.WseSoapClient ? "soapClient" : "webClient") : (type == Types.Client ? "" : (type == Types.Server ? " /server" : " /serverInterface"))) + (Sharetypes ? " /sharetypes" : "") + " " + url;
                        var fileInfo   = new FileInfo(file);
                        var fileTime   = fileInfo.LastWriteTimeUtc;
                        var sourceTime = sourceTimes[i];

                        if (src == null || !fileInfo.Exists || fileTime < projTime || fileTime < sourceTime)
                        {
                            lock (this) {
                                if (useIisExpress && !iisstarted)
                                {
                                    iisstarted = true;
                                    if (newiis)
                                    {
                                        IisExpress.Stop();
                                        IisExpress.Start(iisport);
                                        var web = new WebClient();
                                        try {
                                            serverError = (web.DownloadString(url) == null);
                                        } catch (Exception ex) {
                                            serverError = true;
                                        }
                                    }
                                }
                            }

                            if (serverError)
                            {
                                Log.LogError("Server still has errors.");
                                return;
                            }

                            var wsdlstart = new ProcessStartInfo(tool)
                            {
                                UseShellExecute        = false,
                                WorkingDirectory       = Environment.CurrentDirectory,
                                CreateNoWindow         = true,
                                WindowStyle            = ProcessWindowStyle.Hidden,
                                RedirectStandardOutput = true,
                                Arguments = arg
                            };
                            var p                 = new Process();
                            p.StartInfo           = wsdlstart;
                            p.EnableRaisingEvents = true;
                            p.Exited             += (sender, a) => {
                                var any = !Terminated(p, processes, false);
                                ProcessInfo[] infos;
                                lock (processes) infos = processes.ToArray();
                                foreach (var info in infos)
                                {
                                    any |= !Terminated(info.Process, processes, false);
                                }
                                if (!any)
                                {
                                    wait.Set();
                                }
                            };
                            lock (processes) processes.Add(new ProcessInfo {
                                    Process = p, File = file, Url = url, Args = arg
                                });
                            lock (output) output.Add(new TaskItem(Files[i]));
                            anyprocesses = true;
                            p.Start();
                        }
                    } catch (Exception ex) {
                        Log.LogErrorFromException(ex);
                    }
                });

                //foreach (var p in processes.ToArray()) p.Start();

                if (anyprocesses && !wait.WaitOne(Timeout * 1000))
                {
                    ProcessInfo[] infos;
                    lock (processes) infos = processes.ToArray();
                    foreach (var info in infos)
                    {
                        if (!info.Process.HasExited)
                        {
                            info.Process.Kill();
                        }
                        Terminated(info.Process, processes, true);
                    }
                }
            }
            else
            {
                var swaggerdocsurl = SwaggerUrl ?? (ServerUrl + "/swagger/docs/" + (ApiVersion ?? "v1"));
                serverError = false;
                if (AutoRest || SwaggerUrl == null)
                {
                    if (newiis)
                    {
                        IisExpress.Stop();
                        IisExpress.Start(iisport);
                        iisstarted = true;
                        var web = new WebClient();
                        try {
                            serverError = (web.DownloadString(ServerUrl) == null);
                        } catch {
                            serverError = true;
                        }
                        if (serverError)
                        {
                            Log.LogError($"Server still has errors: {ServerUrl}.");
                            return(false);
                        }
                    }
                }
                var swaggerjson = new WebClient().DownloadString(swaggerdocsurl);
                var jsonfile    = Path.Combine(OutputDirectory, "swagger.json");
                if (!File.Exists(jsonfile) || File.ReadAllText(jsonfile) != swaggerjson)
                {
                    if (Directory.Exists(OutputDirectory))
                    {
                        Directory.Delete(OutputDirectory, true);
                    }
                    Directory.CreateDirectory(OutputDirectory);
                    File.WriteAllText(jsonfile, swaggerjson);
                    if (AutoRest)
                    {
                        // AutoRest
                        var outdir      = OutputDirectory != null ? $"-OutputDirectory \"{OutputDirectory}\" " : "";
                        var codegen     = CodeGenerator != null ? $"-CodeGenerator {CodeGenerator} " : "";
                        var modeler     = Modeler != null ? $"-Modeler {Modeler} " : "";
                        var clientname  = ClientName != null ? $"-ClientName {ClientName} " : "";
                        var payloadthrs = PayloadFlatteningTreshold != null ? $"-PayloadFlatteningThreshold {PayloadFlatteningTreshold} " : "";
                        var header      = Header != null ? $"-Header \"{Header}\" " : "";
                        var credentials = AddCredentials != null ? $"-AddCredentials {AddCredentials} " : "";
                        var outfile     = OutputFileName != null ? $"-OutputFileName \"{OutputFileName}\" " : "";
                        var verbose     = Verbose ? $"-Verbose " : "";
                        var settings    = CodeGenSettings != null ? $"-CodeGenSettings \"{CodeGenSettings}\"" : "";

                        var args = $"{outdir}{codegen}{modeler}{clientname}{payloadthrs}{header}{credentials}{outfile}{verbose}{settings}".Trim();
                        Process.Start(ToolExe, args);
                    }
                    else if (Swagger)
                    {
                        try {
                            var codegenurl = "http://generator.swagger.io/api/gen/clients/" + (Language ?? "typescript-angular2");
                            var body       = new StringWriter();
                            body.Write("{\"spec\": ");
                            body.Write(swaggerjson);
                            body.Write(",\"swaggerUrl\":null");
                            if (Options != null)
                            {
                                body.Write($",\"options\":{Options}");
                            }
                            if (Authorization != null)
                            {
                                body.Write($",\"authorizationValue\":{Authorization}");
                            }
                            if (Security != null)
                            {
                                body.Write($",\"securityDefinition\": {Security}");
                            }
                            body.Write("}");
                            var gen = (HttpWebRequest)WebRequest.Create(codegenurl);
                            gen.Method          = "POST";
                            gen.ContentType     = "application/json";
                            gen.Accept          = "application/json";
                            gen.ProtocolVersion = HttpVersion.Version11;
                            var buf = Encoding.UTF8.GetBytes(body.ToString());
                            gen.ContentLength = buf.Length;
                            var w = gen.GetRequestStream();
                            w.Write(buf, 0, buf.Length);
                            w.Close();
                            var     res     = (HttpWebResponse)gen.GetResponse();
                            var     r       = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                            dynamic result  = SimpleJson.DeserializeObject(r.ReadToEnd());
                            var     rawzip  = new WebClient().DownloadData(result.link);
                            var     zipfile = Path.Combine(OutputDirectory, "swagger.zip");
                            File.WriteAllBytes(zipfile, rawzip);
                            var zip = new Ionic.Zip.ZipFile(zipfile);
                            zip.ExtractAll(OutputDirectory);
                        } catch (Exception ex) {
                            Log.LogErrorFromException(ex);
                            return(false);
                        }
                    }

                    var odir = Path.Combine(Environment.CurrentDirectory, OutputDirectory);
                    output.AddRange(
                        Directory.EnumerateFiles(OutputDirectory)
                        .Select(file => new TaskItem {
                        ItemSpec = file.StartsWith(odir) ? file.Substring(odir.Length).Trim('\\') : file
                    }));
                }
            }

            //if (iisstarted) IisExpress.Stop();

            Output = output.ToArray();
            return(!Log.HasLoggedErrors);
        }