internal static DcNS.XsdDataContractImporter CreateDCImporter(CommandProcessorOptions options, CodeCompileUnit codeCompileUnit) { DcNS.XsdDataContractImporter importer = new DcNS.XsdDataContractImporter(codeCompileUnit); DcNS.ImportOptions dcOptions = CreateDCImportOptions(options); importer.Options = dcOptions; return(importer); }
private static void AddStateForXmlSerializerImport(CommandProcessorOptions options, WsdlImporter importer, CodeCompileUnit codeCompileUnit) { XmlSerializerImportOptions importOptions = new XmlSerializerImportOptions(codeCompileUnit) { WebReferenceOptions = new WsdlNS.WebReferenceOptions() }; importOptions.WebReferenceOptions.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateOrder; if (options.EnableDataBinding == true) { importOptions.WebReferenceOptions.CodeGenerationOptions |= CodeGenerationOptions.EnableDataBinding; } // Right now System.Data API not available in DNX. If it comes available we could consider uncommenting these. // importOptions.WebReferenceOptions.SchemaImporterExtensions.Add(typeof(TypedDataSetSchemaImporterExtensionFx35).AssemblyQualifiedName); // importOptions.WebReferenceOptions.SchemaImporterExtensions.Add(typeof(DataSetSchemaImporterExtension).AssemblyQualifiedName); importOptions.CodeProvider = options.CodeProvider; importOptions.ClrNamespace = options.NamespaceMappings.FirstOrDefault(m => m.Key == "*").Value; importer.State.Add(typeof(XmlSerializerImportOptions), importOptions); if (!importer.State.ContainsKey(typeof(WrappedOptions))) { importer.State.Add(typeof(WrappedOptions), new WrappedOptions { WrappedFlag = options.Wrapped == true }); } }
private static void RunFixups(IFixup[] fixups, CommandProcessorOptions options) { for (int i = 0; i < fixups.Length; i++) { fixups[i].Fixup(options); } }
internal static string GetOutputFileName(CommandProcessorOptions options, IEnumerable <MetadataSection> metadataSections) { string fileName = options.OutputFile?.FullName; if (string.IsNullOrWhiteSpace(fileName)) { var wsdlDocuments = metadataSections.Where(s => s.Metadata is WsdlNS.ServiceDescription).Cast <WsdlNS.ServiceDescription>(); foreach (WsdlNS.ServiceDescription wsdl in wsdlDocuments) { if (!string.IsNullOrEmpty(wsdl.Name)) { fileName = XmlConvert.DecodeName(wsdl.Name); if (!string.IsNullOrWhiteSpace(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) { break; } } } if (string.IsNullOrWhiteSpace(fileName)) { foreach (WsdlNS.ServiceDescription wsdl in wsdlDocuments) { if (wsdl.Services.Count > 0 && !string.IsNullOrEmpty(wsdl.Services[0].Name)) { fileName = XmlConvert.DecodeName(wsdl.Services[0].Name); if (!string.IsNullOrWhiteSpace(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) { break; } } } if (string.IsNullOrWhiteSpace(fileName)) { var schemaDocuments = metadataSections.Where(s => s.Metadata is XmlSchema).Cast <XmlSchema>(); foreach (XmlSchema schema in schemaDocuments) { if (!string.IsNullOrEmpty(schema.TargetNamespace)) { fileName = OutputPathHelper.FilenameFromUri(schema.TargetNamespace); if (!string.IsNullOrWhiteSpace(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) { break; } } } if (string.IsNullOrWhiteSpace(fileName)) { fileName = CodeSerializer.s_defaultFileName; } } } } return(fileName); }
private static bool CanAddProjectReferences(CommandProcessorOptions options) { // Project references are added at the end of the process, never but the bootstrapper which may not be even invoked. // ensure the output files goes under the project dir. return(options.NoProjectUpdates != true && options.Project != null && PathHelper.IsUnderDirectory(options.OutputFile.FullName, new DirectoryInfo(options.Project.DirectoryPath), out var filePath, out var relPath)); }
public static void RemoveUnneededSerializers(CommandProcessorOptions options, ServiceDescriptor serviceDescriptor, Collection <IWsdlImportExtension> wsdlImportExtensions) { if ((options.SerializerMode == SerializerMode.Auto || options.SerializerMode == SerializerMode.Default) && serviceDescriptor.ContainsHttpBindings()) { // NOTE: HTTP Get/Post binding indicates an old web service. We use XmlSerializer to prevent generating dup classes. // Please check devdiv bug 94078 options.SerializerMode = SerializerMode.XmlSerializer; } switch (options.SerializerMode) { case SerializerMode.Default: case SerializerMode.Auto: break; case SerializerMode.XmlSerializer: RemoveExtension(typeof(DataContractSerializerMessageContractImporter), wsdlImportExtensions); break; case SerializerMode.DataContractSerializer: RemoveExtension(typeof(XmlSerializerMessageContractImporter), wsdlImportExtensions); break; default: Debug.Assert(false, "Unrecognized serializer option!"); break; } }
internal CodeSerializer(CommandProcessorOptions options, IEnumerable <MetadataSection> inputMetadata) { string extension = GetOutputFileExtension(options); string outputFilename = GetOutputFileName(options, inputMetadata); _outputFilePath = OutputPathHelper.BuildFilePath(s_defaultFileName, options.OutputDir.FullName, outputFilename, extension, CommandProcessorOptions.Switches.OutputFile.Name); _codeProvider = options.CodeProvider; }
private static void ThrowOnValidationErrors(CommandProcessorOptions options) { if (options.Errors.Count() > 0) { var ex = new AggregateException(options.Errors.Select(e => e as ToolArgumentException ?? new ToolArgumentException(e.Message, e.InnerException))); throw ex; } }
internal ImportModule(CommandProcessorOptions options, ServiceDescriptor serviceDescriptor, WsdlImporter importer) { _codeCompileUnit = new CodeCompileUnit(); _options = options; _codegenExtension = new WcfCodeGenerationExtension(options); _wsdlImporter = importer; _contractGenerator = InitializationHelper.CreateServiceContractGenerator(options, _codeCompileUnit); }
internal static string GetOutputFileExtension(CommandProcessorOptions options) { string fileExtension = options.CodeProvider.FileExtension ?? string.Empty; if (fileExtension.Length > 0 && fileExtension[0] != '.') { fileExtension = "." + fileExtension; } return(fileExtension); }
private static void AddStateForDataContractSerializerImport(CommandProcessorOptions options, WsdlImporter importer, CodeCompileUnit codeCompileUnit) { DcNS.XsdDataContractImporter xsdDataContractImporter = CreateDCImporter(options, codeCompileUnit); importer.State.Add(typeof(DcNS.XsdDataContractImporter), xsdDataContractImporter); if (!importer.State.ContainsKey(typeof(WrappedOptions))) { importer.State.Add(typeof(WrappedOptions), new WrappedOptions { WrappedFlag = options.Wrapped == true }); } }
private static void SetValue(CommandProcessorOptions options, string optionName, object value) { try { options.SetValue(optionName, value); } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) { throw; } options.AddError(ex); } }
private static void ValidateUICulture(CommandProcessorOptions options) { if (options.EnableLoggingMarkup == true) { // The default encoding might not work while redirecting non-ANSI characters // UTF8 would support non-ANSI character and this should be same encoding at WCF tool side Console.InputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8; } if (options.CultureInfo != null) { CultureInfo.DefaultThreadCurrentUICulture = options.CultureInfo; CultureInfo.CurrentUICulture = options.CultureInfo; } }
private static async Task GenerateParamsFileAsync(CommandProcessorOptions options, ILogger logger, CancellationToken cancellationToken) { // params file is generated on first run, never on update and never by the bootstrapper. if (!(options.IsUpdateOperation || options.NoProjectUpdates == true)) { using (var safeLogger = await SafeLogger.WriteStartOperationAsync(logger, "Generating svcutil params file ...").ConfigureAwait(false)) { var updateOptions = options.CloneAs <UpdateOptions>(); updateOptions.ProviderId = Tool.ToolName; updateOptions.Version = Tool.PackageVersion; ProjectDependency.RemoveRedundantReferences(updateOptions.References); updateOptions.MakePathsRelativeTo(options.OutputDir); var paramsFile = Path.Combine(options.OutputDir.FullName, CommandProcessorOptions.SvcutilParamsFileName); await AsyncHelper.RunAsync(() => updateOptions.Save(paramsFile), cancellationToken).ConfigureAwait(false); } } }
private static void SetContractGeneratorOptions(CommandProcessorOptions options, ServiceContractGenerator contractGenerator) { contractGenerator.Options |= ServiceContractGenerationOptions.AsynchronousMethods; contractGenerator.Options |= ServiceContractGenerationOptions.TaskBasedAsynchronousMethod; if (options.InternalTypeAccess == true) { contractGenerator.Options |= ServiceContractGenerationOptions.InternalTypes; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.InternalTypes; } if (options.MessageContract == true) { contractGenerator.Options |= ServiceContractGenerationOptions.TypedMessages; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.TypedMessages; } }
private static DcNS.ImportOptions CreateDCImportOptions(CommandProcessorOptions options) { DcNS.ImportOptions dcOptions = new DcNS.ImportOptions { GenerateInternal = options.InternalTypeAccess == true, EnableDataBinding = options.EnableDataBinding == true }; foreach (Type referencedType in options.ReferencedTypes) { dcOptions.ReferencedTypes.Add(referencedType); } foreach (Type referencedCollectionType in options.ReferencedCollectionTypes) { dcOptions.ReferencedCollectionTypes.Add(referencedCollectionType); } foreach (KeyValuePair <string, string> namespaceMapping in options.NamespaceMappings) { Debug.Assert(!dcOptions.Namespaces.ContainsKey(namespaceMapping.Key), $"Key '{namespaceMapping.Key}' already added to dictionary!"); dcOptions.Namespaces[namespaceMapping.Key] = namespaceMapping.Value; } dcOptions.CodeProvider = options.CodeProvider; return(dcOptions); }
public static void ConfigureSerializers(CommandProcessorOptions options, CodeCompileUnit codeCompileUnit, WsdlImporter importer) { switch (options.SerializerMode) { case SerializerMode.Default: case SerializerMode.Auto: AddStateForDataContractSerializerImport(options, importer, codeCompileUnit); AddStateForXmlSerializerImport(options, importer, codeCompileUnit); break; case SerializerMode.XmlSerializer: AddStateForXmlSerializerImport(options, importer, codeCompileUnit); break; case SerializerMode.DataContractSerializer: AddStateForDataContractSerializerImport(options, importer, codeCompileUnit); break; default: Debug.Assert(false, "Unrecognized serializer option!"); break; } }
internal static ServiceContractGenerator CreateServiceContractGenerator(CommandProcessorOptions options, CodeCompileUnit codeCompileUnit) { ServiceContractGenerator contractGenerator = null; try { contractGenerator = new ServiceContractGenerator(codeCompileUnit); } catch (Exception e) { if (Utils.IsFatalOrUnexpected(e)) { throw; } throw new ToolRuntimeException(SR.ErrUnableToLoadInputs, e); } SetContractGeneratorOptions(options, contractGenerator); foreach (KeyValuePair <string, string> namespaceMapping in options.NamespaceMappings) { contractGenerator.NamespaceMappings.Add(namespaceMapping.Key, namespaceMapping.Value); } return(contractGenerator); }
private static async Task <int> ProcessExceptionAsync(Exception ex, CommandProcessorOptions options) { int retVal = (int)ToolExitCode.Unknown; Debug.Assert(ex != null, "exception should not be null!"); if (ex != null) { try { s_processingException = true; var agex = ex as AggregateException; if (agex != null) { foreach (var ax in agex.InnerExceptions) { retVal = await ProcessExceptionAsync(ax, options); } } else if (ex is BootstrapException bootstrapEx) { ToolConsole.WriteToolError(ex); retVal = bootstrapEx.ExitCode; } else if (ex is ProcessRunner.ProcessException rpe) { ToolConsole.WriteError(rpe, null); retVal = rpe.ExitCode; } else if (ex is ToolArgumentException ae) { ToolConsole.WriteToolError(ae); retVal = (int)ae.ExitCode; } else if (ex is ToolRuntimeException rt) { ToolConsole.WriteToolError(rt); retVal = (int)rt.ExitCode; } else if (ex is DcNS.InvalidDataContractException dce) { ToolConsole.WriteError(dce); retVal = (int)ToolExitCode.RuntimeError; } else if (Utils.IsUnexpected(ex)) { ToolConsole.WriteError(SR.ErrUnexpectedError); retVal = (int)ToolExitCode.RuntimeError; } else // (Exception e) { ToolConsole.WriteError(ex); retVal = (int)ToolExitCode.Unknown; } // don't log aggregate exceptions as the internal exceptions are already logged. if (agex == null) { string exMsg = null; if (options?.Logger != null) { exMsg = Utils.GetExceptionMessage(ex, true); await options.Logger.WriteErrorAsync(exMsg, logToUI : false).ConfigureAwait(false); } // Don't log telemetry if we're running from bootstrapper or connected service. // if options = null, it must be that a parsing exception occurred. if (options == null || options.ToolContext <= OperationalContext.Global) { exMsg = exMsg ?? Utils.GetExceptionMessage(ex, true); var telemetryClient = await AppInsightsTelemetryClient.GetInstanceAsync(CancellationToken.None).ConfigureAwait(false); telemetryClient.TrackError("Exception", exMsg); } } } catch { } } return(retVal); }
public WcfCodeGenerationExtension(CommandProcessorOptions options) { _options = options; }
// Instead of throwing exceptions we pass the first exception that happens as an out parameter. This lets us parse as many // arguments as we can correctly so we can respect options like noLogo and verbosity when showing errors. internal static CommandProcessorOptions ParseCommand(string[] cmd) { var options = new CommandProcessorOptions(); // work around https://github.com/dotnet/core-setup/issues/619 to ignore additionalprobingpath cmd = cmd.Where(c => !c.ToLowerInvariant().Contains("additionalprobingpath")).ToArray(); for (int i = 0; i < cmd.Length; i++) { string arg = cmd[i]?.Trim('\"').Trim(); if (string.IsNullOrWhiteSpace(arg)) { continue; } // if argument does not start with switch indicator, place into "default" arguments if (IsArgumentValue(arg)) { SetValue(options, CommandProcessorOptions.InputsKey, Environment.ExpandEnvironmentVariables(arg)); continue; } // check if this switch exists in the list of possible switches var argSwitch = CommandSwitch.FindSwitch(arg); var argValue = cmd.Length > i + 1 ? cmd[i + 1] : null; if (argSwitch == null) { options.AddError(string.Format(SR.ErrUnknownSwitchFormat, arg)); continue; } // we have a valid switch, now validate value. // make sure there's a value for the parameter. switch (argSwitch.SwitchType) { case SwitchType.Flag: argValue = "true"; break; case SwitchType.FlagOrSingletonValue: argValue = (argValue == null || !IsArgumentValue(argValue)) ? string.Empty : argValue; break; case SwitchType.SingletonValue: case SwitchType.ValueList: if (string.IsNullOrWhiteSpace(argValue) || !IsArgumentValue(argValue)) { options.AddError(string.Format(SR.ErrArgumentWithoutValue, argSwitch.Name)); continue; } break; } // check if switch is allowed to be specified multiple times // if not and it has already been specified and a new value has been parsed. if (argSwitch.SwitchType != SwitchType.ValueList && options.GetValue <object>(argSwitch.Name) != null) { options.AddError(string.Format(SR.ErrSingleUseSwitchFormat, argSwitch.Name)); continue; } SetValue(options, argSwitch.Name, argValue.Trim('\"').Trim()); if (argSwitch.SwitchType != SwitchType.Flag && argValue != string.Empty && IsArgumentValue(argValue)) { i++; // move to next input. } } return(options); }
private static async Task <bool> AddProjectReferencesAsync(MSBuildProj project, CommandProcessorOptions options, CancellationToken cancellationToken) { try { var dependencies = TargetFrameworkHelper.GetWcfProjectReferences(project.TargetFramework); if (dependencies != null) { bool needSave = false; foreach (var dep in dependencies) { needSave |= project.AddDependency(dep); } if (needSave) { await project.SaveAsync(options.Logger, cancellationToken).ConfigureAwait(false); } return(true); } } catch { } return(false); }
private static CodeDomVisitor[] GetVisitors(ServiceContractGenerator generator, CommandProcessorOptions options) { ArrayOfXElementTypeHelper arrayOfXElementTypeHelper = new ArrayOfXElementTypeHelper((generator.Options & ServiceContractGenerationOptions.InternalTypes) == ServiceContractGenerationOptions.InternalTypes, generator.TargetCompileUnit); CodeDomVisitor[] visitors = new CodeDomVisitor[] { new CodeNamespaceUniqueTypeFixer(), new AttributeFixer(generator), new ConstructorFixer(), // Visitors to remove sync methods if !options.Sync new MakeOldAsyncMethodsPrivate(), new RemoveExtensibleDataObjectImpl(), new XmlDomAttributeFixer(), new SpecialIXmlSerializableRemapper(arrayOfXElementTypeHelper), new EnsureAdditionalAssemblyReference(), new CreateCallbackImpl((generator.Options & ServiceContractGenerationOptions.TaskBasedAsynchronousMethod) == ServiceContractGenerationOptions.TaskBasedAsynchronousMethod, generator), new AddAsyncOpenClose(), // this one need to run after CreateCallbakImpl which provide name of VerifyCallbackEvents method }; if (options.Sync != true) { visitors = AddSyncVisitors(visitors); } return(visitors); }
internal static async Task <ToolExitCode> RunAsync(CommandProcessorOptions options, CancellationToken cancellationToken) { ImportModule importModule = null; var credsProvicer = new CmdCredentialsProvider(); ServiceDescriptor serviceDescriptor = options.Inputs.Count == 1 ? new ServiceDescriptor(options.Inputs[0].ToString(), credsProvicer, credsProvicer, credsProvicer) : new ServiceDescriptor(options.Inputs.Select(i => i.ToString()).ToList(), credsProvicer, credsProvicer, credsProvicer); // When in Infrastructure mode (WCF CS) it is assumed the metadata docs have been downloaded and passed in as wsdl files. if (options.ToolContext != OperationalContext.Infrastructure) { if (serviceDescriptor.MetadataUrl != null) { ToolConsole.WriteLine(string.Format(SR.RetreivingMetadataMsgFormat, serviceDescriptor.MetadataUrl.AbsoluteUri)); } else { var displayUri = serviceDescriptor.MetadataFiles.Count() == 1 ? serviceDescriptor.MetadataFiles.First().LocalPath : SR.WsdlOrSchemaFilesMsg; ToolConsole.WriteLine(string.Format(SR.ReadingMetadataMessageFormat, displayUri)); } } using (await SafeLogger.WriteStartOperationAsync(options.Logger, "Importing metadata ...").ConfigureAwait(false)) { try { await serviceDescriptor.ImportMetadataAsync( (wi) => importModule = new ImportModule(options, serviceDescriptor, wi), (sd) => importModule.BeforeImportMetadata(sd), (sd) => importModule.AfterImportMetadata(sd), cancellationToken).ConfigureAwait(false); } catch (Exception ex) { if (Utils.IsFatalOrUnexpected(ex)) { throw; } var exception = new ToolInputException(Utils.GetExceptionMessage(ex), ex); if (serviceDescriptor.MetadataUrl != null) { exception = new ToolMexException(exception, serviceDescriptor.MetadataUrl); } throw exception; } } using (await SafeLogger.WriteStartOperationAsync(options.Logger, "Processing Code DOM ...").ConfigureAwait(false)) { ToolConsole.WriteLine(SR.GeneratingFiles); CodeSerializer codeSerializer = new CodeSerializer(options, serviceDescriptor.MetadataDocuments); var filePath = codeSerializer.Save(importModule.CodeCompileUnit); // When in Infrastructure mode (WCF CS) it is assumed the output file path have been provided so no need to display it. ToolConsole.WriteLineIf(options.ToolContext != OperationalContext.Infrastructure, filePath, LogTag.Important); } return(ToolConsole.ExitCode); }
public void Fixup(CommandProcessorOptions options) { // Currently MetadataFixups don't use any options, so just call the overload with no parameters. Fixup(); }
public override void Fixup(CommandProcessorOptions options) { CodeDomVisitor.Visit(GetVisitors(generator, options), generator.TargetCompileUnit); }
public static void Init(CommandProcessorOptions options) { Verbosity = options.Verbosity.Value; IsMarkupEnabled = options.EnableLoggingMarkup == true; ToolModeLevel = options.ToolContext.Value; }
internal static async Task <int> MainAsync(string[] args, ILogger logger, CancellationToken cancellationToken) { int result = -1; CommandProcessorOptions options = null; WaitForDebugger(); try { options = await CommandProcessorOptions.ParseArgumentsAsync(args, logger, cancellationToken); ValidateUICulture(options); if (options.NoTelemetry == true) { AppInsightsTelemetryClient.IsUserOptedIn = false; } ToolConsole.Init(options); ToolConsole.WriteHeaderIf(options.NoLogo != true); ThrowOnValidationErrors(options); if (options.Help == true) { ToolConsole.WriteHelp(); result = (int)ToolExitCode.Success; } else { // Show early warnings var earlyWarnings = options.Warnings; foreach (string warning in earlyWarnings.Distinct()) { ToolConsole.WriteWarning(warning); } var operationMessage = (options.IsUpdateOperation ? "Update" : "Add") + " web service reference operation started!"; using (var safeLogger = await SafeLogger.WriteStartOperationAsync(options.Logger, operationMessage).ConfigureAwait(false)) { await options.ResolveAsync(cancellationToken).ConfigureAwait(false); ThrowOnValidationErrors(options); options.ProviderId = Tool.ToolName; options.Version = Tool.PackageVersion; foreach (string warning in options.Warnings.Distinct().Except(earlyWarnings)) { ToolConsole.WriteWarning(warning); } if (options.RequiresBoostrapping) { using (var bootstrapper = new SvcutilBootstrapper(options.CloneAs <SvcutilOptions>())) { await options.SetupBootstrappingDirectoryAsync(options.Logger, cancellationToken).ConfigureAwait(false); var bootstrapResult = await bootstrapper.BoostrapSvcutilAsync(options.KeepBootstrapDir, options.Logger, cancellationToken).ConfigureAwait(false); ToolConsole.WriteLine(bootstrapResult.OutputText); result = bootstrapResult.ExitCode; } } else { result = (int) await RunAsync(options, cancellationToken).ConfigureAwait(false); } if (IsSuccess(result)) { if (!File.Exists(options.OutputFile.FullName)) { await safeLogger.WriteMessageAsync("The process completed successfully but no proxy file was found!", logToUI : false); throw new ToolArgumentException(SR.ErrUnexpectedError); } else { await GenerateParamsFileAsync(options, options.Logger, cancellationToken); if (CanAddProjectReferences(options) && !await AddProjectReferencesAsync(options.Project, options, cancellationToken).ConfigureAwait(false)) { result = (int)ToolExitCode.InputError; } } // clean up only on success to allow to troubleshoot any problems on failure. options?.Cleanup(); } } } } catch (Exception e) { result = await ProcessExceptionAsync(e, options); } finally { try { // Don't log telemetry if we're running from bootstrapper or connected service. if (options?.ToolContext <= OperationalContext.Global) { var properties = new Dictionary <string, string>() { { "IsUpdate", (options?.IsUpdateOperation).ToString() }, { "TargetFramework", options?.TargetFramework?.FullName }, { "Parameters", options?.ToTelemetryString() }, { "ExitCode", result.ToString() }, { "RequiresBootstrapping", options?.RequiresBoostrapping.ToString() }, }; var telemetryClient = await AppInsightsTelemetryClient.GetInstanceAsync(cancellationToken).ConfigureAwait(false); telemetryClient.TrackEvent("ToolRun", properties); } } catch { } } return(result); }
public abstract void Fixup(CommandProcessorOptions options);