public void WriteParagraph(string text) { this.Reset(); this.AppendParagraph(text); ToolConsole.WriteLine(_stringBuilder.ToString()); _stringBuilder = null; }
private void CheckForBasicOptions() { _parent._noLogo = _arguments.ContainsArgument(Options.Cmd.NoLogo); #if DEBUG ToolConsole.SetOptions(_arguments.ContainsArgument(Options.Cmd.Debug)); #endif }
public static int Main(string[] args) { try { // ValidateUICulture() makes sure that this command-line tool can run on RightToLeft systems. ValidateUICulture(); Options options = Options.ParseArguments(args); ToolRuntime runtime = new ToolRuntime(options); return((int)runtime.Run()); } catch (ToolArgumentException ae) { ToolConsole.WriteHeader(); ToolConsole.WriteToolError(ae); return((int)ae.ExitCode); } catch (ToolRuntimeException re) { ToolConsole.WriteToolError(re); return((int)re.ExitCode); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) { throw; } ToolConsole.WriteUnexpectedError(e); Tool.FailFast(e.ToString()); return((int)ToolExitCodes.Unknown); // unreachable code; } }
private void LoadReferencedAssemblies(IList <string> referenceArgs) { foreach (string path in referenceArgs) { Assembly assembly; try { assembly = InputModule.LoadAssembly(path); if (!_parent._referencedAssemblies.Contains(assembly)) { _parent._referencedAssemblies.Add(assembly); } else { throw new ToolOptionException(SR.Format(SR.ErrDuplicateReferenceValues, Options.Cmd.Reference, assembly.Location)); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) { throw; } ToolConsole.WriteWarning(SR.Format(SR.ErrCouldNotLoadReferenceAssemblyAt, path)); } } }
public void WriteHelp() { int start = s_nameMidpoint; ToolConsole.WriteLine(new string(' ', _nameStart) + _name); ToolConsole.WriteLine(); if (_description != null) { s_categoryBuilder.WriteParagraph(_description); ToolConsole.WriteLine(); } if (_syntax != null) { s_categoryBuilder.WriteParagraph(_syntax); ToolConsole.WriteLine(); } if (_inputs != null) { ArgumentInfo.WriteArguments(_inputs); ToolConsole.WriteLine(); } if (_options != null) { ToolConsole.WriteLine(SR.Format(SR.HelpOptions)); ToolConsole.WriteLine(); ArgumentInfo.WriteArguments(_options); ToolConsole.WriteLine(); } }
private List <Type> CollectXmlSerializerTypes(Assembly assembly, List <XmlMapping> mappings) { List <Type> types = new List <Type>(); ExportModule.ContractLoader contractLoader = new ExportModule.ContractLoader(new Assembly[] { assembly }, _isTypeExcluded); contractLoader.ContractLoadErrorCallback = delegate(Type contractType, string errorMessage) { ToolConsole.WriteWarning(SR.Format(SR.WrnUnableToLoadContractForSGen, contractType, errorMessage)); }; foreach (ContractDescription contract in contractLoader.GetContracts()) { types.Add(contract.ContractType); foreach (OperationDescription operation in contract.Operations) { XmlSerializerOperationBehavior behavior = operation.Behaviors.Find <XmlSerializerOperationBehavior>(); if (behavior != null) { foreach (XmlMapping map in behavior.GetXmlMappings()) { mappings.Add(map); } } } } return(types); }
private void LoadSMReferenceAssembly() { string smReferenceArg = _arguments.GetArgument(Options.Cmd.SMReference); IList <string> referencedAssembliesArgs = smReferenceArg.Split(';').ToList(); if (referencedAssembliesArgs != null && referencedAssembliesArgs.Count > 0) { string smassembly = ""; string smpassembly = ""; foreach (string path in referencedAssembliesArgs) { var file = new FileInfo(path); if (file.Name.Equals("System.ServiceModel.Primitives.dll", StringComparison.OrdinalIgnoreCase)) { smassembly = path; } if (file.Name.Equals("System.Private.ServiceModel.dll", StringComparison.OrdinalIgnoreCase)) { smpassembly = path; } } if ((string.IsNullOrEmpty(smassembly)) || (string.IsNullOrEmpty(smpassembly))) { ToolConsole.WriteError("Missing one or both of the paths for System.ServiceModel.Primitives and System.Private.ServiceModel"); throw new ArgumentException("Invalid smreference value"); } try { ToolConsole.WriteLine("Load Assembly From " + smpassembly); InputModule.LoadAssembly(smpassembly); ToolConsole.WriteLine($"Successfully Load {smpassembly}"); } catch (Exception e) { ToolConsole.WriteError(string.Format("Fail to load the assembly {0} with the error {1}", smpassembly, e.Message)); throw; } try { ToolConsole.WriteLine("Load Assembly From " + smassembly); Tool.SMAssembly = InputModule.LoadAssembly(smassembly); ToolConsole.WriteLine($"Successfully Load {smassembly}"); } catch (Exception e) { ToolConsole.WriteError(string.Format("Fail to load the assembly {0} with the error {1}", smassembly, e.Message)); throw; } } else { ToolConsole.WriteError("Need to pass the System.ServiceModel.Primitives.dll and the System.Private.ServiceModel.dll paths through the 'smreference' parameter."); throw new ArgumentException("Need to pass the System.ServiceModel.Primitives.dll and the System.Private.ServiceModel.dll paths through the 'smreference' parameter."); } }
private static bool IsContractType(Type type) { if (serviceContractAttributeType == null) { string error = $"Type System.ServiceModel.ServiceContractAttribute not found type System.ServiceModel.ServiceContractAttribute in {Tool.SMAssembly.FullName}"; ToolConsole.WriteError(error); throw new ToolRuntimeException(error); } return((type.IsInterface || type.IsClass) && (type.IsDefined(serviceContractAttributeType, false))); }
internal static void Assert(bool condition, string message) { if (!condition) { #if DEBUG ToolConsole.WriteError("Please file a bug or report the following issue with this tool:"); StackTrace st = new StackTrace(true); ToolConsole.WriteLine(st.ToString()); #endif ToolConsole.WriteUnexpectedError(message); Tool.FailFast(message); } }
internal void GenerateCode(List <Assembly> assemblies) { if (!string.IsNullOrEmpty(_outFile) && assemblies.Count > 1) { ToolConsole.WriteWarning(SR.Format(SR.WrnOptionConflictsWithInput, Options.Cmd.Out)); _outFile = null; } foreach (Assembly assembly in assemblies) { GenerateCode(assembly); } }
internal static void WriteHelpText() { HelpGenerator.WriteUsage(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteCommonOptionsHelp(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteXmlSerializerTypeGenerationHelp(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); HelpGenerator.WriteExamples(); ToolConsole.WriteLine(); ToolConsole.WriteLine(); }
public static void WriteArguments(ArgumentInfo[] arguments) { int maxArgumentLength = CalculateMaxNameLength(arguments); int helpTextIndent = argHelpPrefix.Length + maxArgumentLength + argHelpSeperator.Length; string helpPattern = argHelpPrefix + "{0, -" + maxArgumentLength + "}" + argHelpSeperator + "{1}"; ToolStringBuilder builder = new ToolStringBuilder(helpTextIndent); foreach (ArgumentInfo argument in arguments) { if (argument.BeginGroup) { ToolConsole.WriteLine(); } string optionHelp = argument.GenerateHelp(helpPattern); builder.WriteParagraph(optionHelp); } }
internal static void WriteError(Exception e, string prefix) { #if DEBUG if (s_debug) { ToolConsole.WriteLine(); WriteError(e.ToString(), prefix); return; } #endif WriteError(e.Message, prefix); while (e.InnerException != null) { if (e.Message != e.InnerException.Message) { WriteError(e.InnerException.Message, " "); } e = e.InnerException; } }
static public Type[] LoadTypes(Assembly assembly) { Type[] types; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException rtle) { ToolConsole.WriteWarning(SR.Format(SR.WrnCouldNotLoadTypesFromReferenceAssemblyAt, assembly.Location)); foreach (Exception e in rtle.LoaderExceptions) { ToolConsole.WriteLine(" " + e.Message, 2); } types = Array.FindAll <Type>(rtle.Types, delegate(Type t) { return(t != null); }); if (types.Length == 0) { throw new ToolInputException(SR.Format(SR.ErrCouldNotLoadTypesFromAssemblyAt, assembly.Location)); } } return(types); }
private List <Type> CollectXmlSerializerTypes(Assembly assembly, List <XmlMapping> mappings) { List <Type> types = new List <Type>(); ExportModule.ContractLoader contractLoader = new ExportModule.ContractLoader(new Assembly[] { assembly }, _isTypeExcluded); contractLoader.ContractLoadErrorCallback = delegate(Type contractType, string errorMessage) { ToolConsole.WriteWarning(SR.Format(SR.WrnUnableToLoadContractForSGen, contractType, errorMessage)); }; Type contractDescriptionType = Tool.SMAssembly.GetType("System.ServiceModel.Description.ContractDescription"); if (contractDescriptionType == null) { ToolConsole.WriteError($"Not found type System.ServiceModel.Description.ContractDescription in {Tool.SMAssembly.FullName}"); throw new ToolRuntimeException(); } PropertyInfo contractTypeProperty = contractDescriptionType.GetProperty("ContractType"); if (contractTypeProperty == null) { ToolConsole.WriteError($"Not found property ContractType in type {contractDescriptionType}"); throw new ToolRuntimeException(); } Type xmlSerializerOperationBehaviorType = Tool.SMAssembly.GetType("System.ServiceModel.Description.XmlSerializerOperationBehavior"); if (xmlSerializerOperationBehaviorType == null) { ToolConsole.WriteError($"Not found type System.ServiceModel.Description.XmlSerializerOperationBehaviorType in {Tool.SMAssembly.FullName}"); throw new ToolRuntimeException(); } Type operationType = Tool.SMAssembly.GetType("System.ServiceModel.Description.OperationDescription"); if (operationType == null) { ToolConsole.WriteError($"Not found type System.ServiceModel.Description.OperationDescription in {Tool.SMAssembly.FullName}"); throw new ToolRuntimeException(); } PropertyInfo getBehaviorsProperty = operationType.GetProperty("Behaviors"); if (getBehaviorsProperty == null) { ToolConsole.WriteError($"Not found method get_Behaviors in type {operationType}"); throw new ToolRuntimeException(); } Type keyedByTypeCollectionType = Tool.SMAssembly.GetType("System.Collections.Generic.KeyedByTypeCollection`1"); if (keyedByTypeCollectionType == null) { ToolConsole.WriteError($"Not found type System.Collections.Generic.KeyedByTypeCollection`1 in {Tool.SMAssembly.FullName}"); throw new ToolRuntimeException(); } Type iOperationBehaviorType = Tool.SMAssembly.GetType("System.ServiceModel.Description.IOperationBehavior"); if (iOperationBehaviorType == null) { ToolConsole.WriteError($"Not found type System.ServiceModel.Description.IOperationBehavior in {Tool.SMAssembly.FullName}"); throw new ToolRuntimeException(); } keyedByTypeCollectionType = keyedByTypeCollectionType.MakeGenericType(new Type[] { iOperationBehaviorType }); if (keyedByTypeCollectionType == null) { ToolConsole.WriteError($"Cannot make Generic Type System.Collections.Generic.KeyedByTypeCollection<IOperationBehavior> in {Tool.SMAssembly.FullName}"); throw new ToolRuntimeException(); } MethodInfo findMethod = keyedByTypeCollectionType.GetMethod("Find"); if (findMethod == null) { ToolConsole.WriteError($"Not found method find in type {keyedByTypeCollectionType}"); throw new ToolRuntimeException(); } findMethod = findMethod.MakeGenericMethod(new Type[] { xmlSerializerOperationBehaviorType }); if (findMethod == null) { ToolConsole.WriteError($"Not found method Find<XmlSerializerOperationBehavior> in operation.Behaviors"); throw new ToolRuntimeException(); } MethodInfo getXmlMappingsMethod = xmlSerializerOperationBehaviorType.GetMethod("GetXmlMappings"); if (getXmlMappingsMethod == null) { ToolConsole.WriteError($"Not found method getXmlMappings in XmlSerializerOperationBehavior"); throw new ToolRuntimeException(); } PropertyInfo operationsProperty = contractDescriptionType.GetProperty("Operations"); if (operationsProperty == null) { ToolConsole.WriteError($"Not found property Operations in type {contractDescriptionType}"); throw new ToolRuntimeException(); } //Use reflection to replace the following code //foreach (ContractDescription contract in contractLoader.GetContracts()) //{ // types.Add(contract.ContractType); // foreach (OperationDescription operation in contract.Operations) // { // XmlSerializerOperationBehavior behavior = operation.Behaviors.Find<XmlSerializerOperationBehavior>(); // if (behavior != null) // { // foreach (XmlMapping map in behavior.GetXmlMappings()) // { // mappings.Add(map); // } // } // } //} foreach (object contract in contractLoader.GetContracts()) { types.Add((Type)contractTypeProperty.GetValue(contract)); System.Collections.IEnumerable operations = (System.Collections.IEnumerable)operationsProperty.GetValue(contract); foreach (var operation in operations) { if (operation == null) { throw new ToolRuntimeException("operation is null"); } var behaviors = getBehaviorsProperty.GetValue(operation); var behavior = findMethod.Invoke(behaviors, new object[] { }); if (behavior != null) { var xmlMappings = (Collection <XmlMapping>)getXmlMappingsMethod.Invoke(behavior, new object[] { }); if (xmlMappings != null) { foreach (XmlMapping map in xmlMappings) { mappings.Add(map); } } } } } return(types); }
private void GenerateCode(Assembly assembly) { List <XmlMapping> mappings = new List <XmlMapping>(); List <Type> types = CollectXmlSerializerTypes(assembly, mappings); if (types.Count == 0) { ToolConsole.WriteWarning(SR.Format(SR.WrnNoServiceContractTypes, assembly.GetName().CodeBase)); return; } if (mappings.Count == 0) { ToolConsole.WriteWarning(SR.Format(SR.WrnNoXmlSerializerOperationBehavior, assembly.GetName().CodeBase)); return; } bool success = false; bool toDeleteFile = true; string codePath = Path.GetTempFileName(); try { if (File.Exists(codePath)) { File.Delete(codePath); } using (FileStream fs = File.Create(codePath)) { MethodInfo method = typeof(System.Xml.Serialization.XmlSerializer).GetMethod("GenerateSerializer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method == null) { throw new ToolRuntimeException(SR.GenerateSerializerNotFound); } else { success = (bool)method.Invoke(null, new object[] { types.ToArray(), mappings.ToArray(), fs }); } } } finally { if (!success && toDeleteFile && File.Exists(codePath)) { File.Delete(codePath); } } string sgenSource = XmlSerializer.GetXmlSerializerAssemblyName(types[0]); // delete all temp files generated by CodeDom except source file sgenSource = BuildFilePath(sgenSource, sourceExtension, null); if (File.Exists(sgenSource)) { File.Delete(sgenSource); } string sourceName; if (_outFile != null) { sourceName = FilenameHelper.UniquifyFileName(_outFile, sourceExtension); } else { sourceName = FilenameHelper.UniquifyFileName(sgenSource, sourceExtension); } string sourceFilePath = BuildFilePath(sourceName, sourceExtension, null); CreateDirectoryIfNeeded(sourceFilePath); File.Copy(codePath, sourceFilePath, true); ToolConsole.WriteLine(sourceFilePath); return; }
private void LoadSMReferenceAssembly() { IList <string> referencedAssembliesArgs = _arguments.GetArguments(Options.Cmd.SMReference); if (referencedAssembliesArgs != null && referencedAssembliesArgs.Count > 0) { string smassembly = referencedAssembliesArgs[0]; // Allow the reference to be for System.Private.ServiceModel as well. if ((smassembly.LastIndexOf("System.ServiceModel.Primitives", StringComparison.OrdinalIgnoreCase) == -1) && (smassembly.LastIndexOf("System.Private.ServiceModel", StringComparison.OrdinalIgnoreCase) == -1)) { ToolConsole.WriteError("Need to pass the right path of System.ServiceModel.Primitives for smreference parameter"); throw new ArgumentException("Invalid smreference value"); } string smpassembly = smassembly.Replace("System.ServiceModel.Primitives", "System.Private.ServiceModel"); //for some lowercase path smpassembly = smpassembly.Replace("system.servicemodel.primitives", "system.private.servicemodel"); int refplace = smassembly.LastIndexOf("ref"); if (refplace > 0) { smassembly = smassembly.Remove(refplace, 3).Insert(refplace, "lib"); refplace = smpassembly.LastIndexOf("ref"); smpassembly = smpassembly.Remove(refplace, 3).Insert(refplace, "lib"); int libplace = smpassembly.LastIndexOf("lib"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { smpassembly = smpassembly.Remove(libplace, 3).Insert(libplace, @"runtimes\win\lib"); } else { smpassembly = smpassembly.Remove(libplace, 3).Insert(libplace, @"runtimes/unix/lib"); } } try { ToolConsole.WriteLine("Load Assembly From " + smpassembly); InputModule.LoadAssembly(smpassembly); ToolConsole.WriteLine($"Successfully Load {smpassembly}"); } catch (Exception e) { ToolConsole.WriteError(string.Format("Fail to load the assembly {0} with the error {1}", smpassembly, e.Message)); throw; } try { ToolConsole.WriteLine("Load Assembly From " + smassembly); Tool.SMAssembly = InputModule.LoadAssembly(smassembly); ToolConsole.WriteLine($"Successfully Load {smassembly}"); } catch (Exception e) { ToolConsole.WriteError(string.Format("Fail to load the assembly {0} with the error {1}", smassembly, e.Message)); throw; } } else { ToolConsole.WriteError("Need pass the System.ServiceModel.Primitive.dll through SM parameter"); throw new ArgumentException("Need pass the System.ServiceModel.Primitive.dll through SM parameter"); } }
internal static void WriteHeader() { // Using CommonResStrings.WcfTrademarkForCmdLine for the trademark: the proper resource for command line tools. ToolConsole.WriteLine(SR.Format(SR.Logo, SR.WcfTrademarkForCmdLine, ThisAssembly.InformationalVersion, SR.CopyrightForCmdLine)); }
} // beforefieldInit internal static void WriteUsage() { ToolConsole.WriteLine(SR.Format(SR.HelpUsage1)); ToolConsole.WriteLine(); ToolConsole.WriteLine(SR.Format(SR.HelpUsage6)); }
internal static void WriteToolError(ToolArgumentException ae) { WriteError(ae); ToolConsole.WriteLine(SR.Format(SR.MoreHelp, Options.Abbr.Help)); }
private static void WriteExample(string syntax, string explanation) { ToolConsole.WriteLine(string.Format(CultureInfo.InvariantCulture, " {0}", syntax)); s_exampleBuilder.WriteParagraph(string.Format(CultureInfo.InvariantCulture, " {0}", explanation)); ToolConsole.WriteLine(); }