Exemple #1
0
        internal bool IsIncluded(string name)
        {
            if (Exclude != null)
            {
                return(!Exclude.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase)));
            }
            else if (Include != null)
            {
                return(Include.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase)));
            }

            return(true);
        }
Exemple #2
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);
        }
Exemple #3
0
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            if (Files == null)
            {
                return(true);
            }

            try {
                var itemsNotUpdated = new List <ITaskItem>();

                Files = Files.Where(f => Exclude?.Any(g => g.ItemSpec == f.ItemSpec) ?? true).ToArray();

                //System.Threading.Tasks.Parallel.ForEach(Files, item => {
                foreach (var item in Files)
                {
                    if (!string.IsNullOrEmpty(Meta) && !string.IsNullOrEmpty(item.GetMetadata(Meta)) && item.GetMetadata(Meta) != "false")
                    {
                        lock (itemsNotUpdated) itemsNotUpdated.Add(item);
                        //return;
                        continue;
                    }

                    string file = item.ItemSpec;

                    string text;
                    if (_useDefaultEncoding)
                    {
                        text = File.ReadAllText(file);
                    }
                    else
                    {
                        text = File.ReadAllText(file, _encoding);
                    }

                    var replacings = GetReplacings(item, text).ToArray();
                    if (!replacings.Any())
                    {
                        continue;                                        // return;
                    }
                    var any = false;
                    foreach (var repl in replacings)
                    {
                        if (!string.IsNullOrEmpty(repl.Scope))
                        {
                            var scope = new Regex(repl.Scope, repl.Options);
                            var regex = new Regex(repl.Expression, repl.Options);
                            text = scope.Replace(text, match => {
                                any = true;
                                if (match.Groups["scope"] != null && match.Groups["scope"].Success == true)
                                {
                                    var s = match.Groups["scope"];
                                    return(match.Result(match.Value.Substring(0, s.Index - match.Index) + regex.Replace(s.Value, repl.Replacement ?? "", repl.Count) + match.Value.Substring(s.Index + s.Length - match.Index)));
                                }
                                else
                                {
                                    return(match.Result(regex.Replace(match.Value, repl.Replacement ?? "", repl.Count)));
                                }
                            }, repl.ScopeCount);
                        }
                        else
                        {
                            var regex = new Regex(repl.Expression, repl.Options);
                            text = regex.Replace(text,
                                                 match => {
                                any = true;
                                return(match.Result(repl.Replacement ?? ""));
                            },
                                                 repl.Count);
                        }
                    }

                    if (!any)
                    {
                        lock (itemsNotUpdated) itemsNotUpdated.Add(item);

                        if (_warnOnNoUpdate)
                        {
                            Log.LogWarning(String.Format("No updates were performed on file : {0}.", file));
                        }
                    }
                    else
                    {
                        if (ShowProgress)
                        {
                            Log.LogMessage("Replace on {0}", file);
                        }

                        if (_useDefaultEncoding)
                        {
                            File.WriteAllText(file, text);
                        }
                        else
                        {
                            File.WriteAllText(file, text, _encoding);
                        }
                    }
                    //});
                }

                if (itemsNotUpdated.Count > 0)
                {
                    ItemsNotUpdated = itemsNotUpdated.ToArray();
                    AllItemsUpdated = false;
                }
                Log.LogMessage("{0} on {1} files.", this.GetType().Name, Files.Length - itemsNotUpdated.Count);
            } catch (Exception ex) {
                Log.LogErrorFromException(ex);
                AllItemsUpdated = false;
                return(false);
            }
            return(true);
        }