private string Process(IList<JsStatement> stmts, IAssembly mainAssembly, IMetadataImporter metadata = null, INamer namer = null) { var compilation = new Mock<ICompilation>(); compilation.SetupGet(_ => _.MainAssembly).Returns(mainAssembly); var obj = new Linker(metadata ?? new MockMetadataImporter(), namer ?? new MockNamer(), compilation.Object); var processed = obj.Process(stmts); return string.Join("", processed.Select(s => OutputFormatter.Format(s, allowIntermediates: false))); }
public static Tuple<string, MockErrorReporter> Compile(string source, bool expectErrors = false) { var sourceFile = new MockSourceFile("file.cs", source); var er = new MockErrorReporter(!expectErrors); var n = new Namer(); var references = new[] { Files.Mscorlib }; var compilation = PreparedCompilation.CreateCompilation("x", new[] { sourceFile }, references, null);; var s = new AttributeStore(compilation.Compilation, er); var md = new MetadataImporter(er, compilation.Compilation, s, new CompilerOptions()); var rtl = new RuntimeLibrary(md, er, compilation.Compilation, n, s); var l = new MockLinker(); md.Prepare(compilation.Compilation.GetAllTypeDefinitions()); var compiler = new Compiler(md, n, rtl, er); var compiledTypes = compiler.Compile(compilation).ToList(); if (expectErrors) { Assert.That(er.AllMessages, Is.Not.Empty, "Compile should have generated errors"); return Tuple.Create((string)null, er); } Assert.That(er.AllMessages, Is.Empty, "Compile should not generate errors"); var js = new OOPEmulatorInvoker(new OOPEmulator(compilation.Compilation, md, rtl, n, l, s, er), md, er).Process(compiledTypes, null); js = new Linker(md, n, s, compilation.Compilation).Process(js); string script = OutputFormatter.Format(js, allowIntermediates: false); return Tuple.Create(script, er); }
private string Process(IList<JsStatement> stmts, IAssembly[] assemblies, IMetadataImporter metadata = null, INamer namer = null) { var compilation = new Mock<ICompilation>(); compilation.SetupGet(_ => _.MainAssembly).Returns(assemblies[0]); compilation.SetupGet(_ => _.Assemblies).Returns(assemblies); var s = new AttributeStore(compilation.Object, new MockErrorReporter()); var obj = new Linker(metadata ?? new MockMetadataImporter(), namer ?? new MockNamer(), s, compilation.Object); var processed = obj.Process(stmts); return OutputFormatter.Format(processed, allowIntermediates: false); }
public Response HasPermissionsRedirect(Permissions perm, NancyContext context, string routeName, HttpStatusCode code) { var url = Linker.BuildRelativeUri(context, routeName); var response = ForbiddenIfNot(ctx => { var permissions = GetPermissions(ctx.CurrentUser); var result = permissions.HasFlag(perm); return(result); }); var r = response(context); return(r.StatusCode == code ? new RedirectResponse($"{url.ToString()}?redirect={context.Request.Path}") : null); }
public void Link_AssignLabelAddress() { ExecutableModule notUsed = Linker.Link(m_relModules); CheckAssignedLabelAddress( TestUtils.MakeArray( LabelDefinitionTest.Make("SUB", 0x0000, SUB_Address), LabelDefinitionTest.Make("ADDEND", 0x0000, ADDEND_Address), LabelDefinitionTest.Make("ADD1234", 0x0001, ADD1234_Address)), m_subRelModule, "SUB プログラムのラベル"); CheckAssignedLabelAddress( TestUtils.MakeArray( LabelDefinitionTest.Make("MAIN", 0x0000, MAIN_Address), LabelDefinitionTest.Make("LBL101", 0x0000, LBL101_Address), LabelDefinitionTest.Make("LTRL0001", 0x0005, LTRL0001_Address)), m_mainRelModule, "MAIN プログラムのラベル。'=3456' のリテラルのラベルが生成される"); }
void btn_notify_MouseDown(object sender, MouseButtonEventArgs e) { try { if (Linker.isRunning()) { if (!(Linker.opened() is NotificationWindow)) { Linker.run(new NotificationWindow()); } } } catch (Exception x) { Message.show(x.Message); } }
private Output LinkPhase(IEnumerable <Intermediate> intermediates, TableDefinitionCollection tableDefinitions) { var sections = intermediates.SelectMany(i => i.Sections).ToList(); sections.AddRange(SectionsFromLibraries(tableDefinitions)); var linker = new Linker(); foreach (var data in this.Extensions.Create <IExtensionData>()) { linker.AddExtensionData(data); } var output = linker.Link(sections, this.OutputType); return(output); }
public void Destruct() { if (isDestructed) { return; } isDestructed = true; downloadQueue?.Destruct(); linker?.Destruct(); coroutineOwner?.Destruct(); downloadQueue = null; linker = null; coroutineOwner = null; errorHandler = null; }
/// <summary> /// Writes the multiboot header. /// </summary> /// <param name="entryPoint">The virtualAddress of the multiboot compliant entry point.</param> protected void WriteMultibootHeader(LinkerSymbol entryPoint) { // According to the multiboot specification this header must be within the first 8K of the kernel binary. Linker.SetFirst(multibootHeader); var writer = new BinaryWriter(multibootHeader.Stream, Encoding.ASCII); // flags - multiboot flags uint flags = HEADER_MB_FLAG_MEMORY_INFO_REQUIRED | HEADER_MB_FLAG_MODULES_PAGE_ALIGNED | (HasVideo ? HEADER_MB_FLAG_VIDEO_MODES_REQUIRED : 0); // magic writer.Write(HEADER_MB_MAGIC); // flags writer.Write(flags); // checksum writer.Write(unchecked (0U - HEADER_MB_MAGIC - flags)); // header_addr - load address of the multiboot header Linker.Link(LinkType.AbsoluteAddress, PatchType.I32, multibootHeader, (int)writer.BaseStream.Position, multibootHeader, 0); writer.Write(0); // load_addr - address of the binary in memory writer.Write(0); // load_end_addr - address past the last byte to load from the image writer.Write(0); // bss_end_addr - address of the last byte to be zeroed out writer.Write(0); // entry_addr - address of the entry point to invoke Linker.Link(LinkType.AbsoluteAddress, PatchType.I32, multibootHeader, (int)writer.BaseStream.Position, entryPoint, 0); writer.Write(0); // Write video settings if video has been specified, otherwise pad writer.Write(0); writer.Write(HasVideo ? Width : 0); writer.Write(HasVideo ? Height : 0); writer.Write(HasVideo ? Depth : 0); }
protected void Page_Load(object sender, EventArgs e) { if (Request.Url.HasProfile()) { //We got profile var profile = Request.Url.GetProfile(); if (profile.IsAuthorized) { //SAMPLE //Do something with it var username = profile.UniqueId; var userData = profile.UserDisplayName; var linker = new Linker(ConfigurationManager.ConnectionStrings["openids"]); var linked = linker.GetLinkedObjects(profile); if (linked.Count() > 0) { //Already has something } else { linker.AddLink("Hellou!!!", profile); } var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(5), false, userData, FormsAuthentication.FormsCookiePath); // Encrypt the ticket. string encTicket = FormsAuthentication.Encrypt(ticket); // Create the cookie. Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); // Redirect back to original URL. Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false)); } else { //Show errors Error = profile.AuthorizationError; } } }
protected void FixConstantIntegerToFloat(InstructionNode node) { var source = node.Operand1; var result = node.Result; if (result.IsR4) { var symbol = Linker.GetConstantSymbol((float)source.ConstantUnsigned64); var label = Operand.CreateLabel(result.Type, symbol.Name); node.SetInstruction(MovssLoad, result, label, ConstantZero); } else if (result.IsR8) { var symbol = Linker.GetConstantSymbol((double)source.ConstantUnsigned64); var label = Operand.CreateLabel(result.Type, symbol.Name); node.SetInstruction(MovsdLoad, result, label, ConstantZero); } }
protected override void RunPreCompile() { multibootHeader = Linker.DefineSymbol(MultibootHeaderSymbolName, SectionKind.Text, 1, 0x30); Linker.DefineSymbol(MultibootEAX, SectionKind.BSS, Architecture.NativeAlignment, Architecture.NativePointerSize); Linker.DefineSymbol(MultibootEBX, SectionKind.BSS, Architecture.NativeAlignment, Architecture.NativePointerSize); multibootMethod = Compiler.CreateLinkerMethod("MultibootInit"); Linker.EntryPoint = Linker.GetSymbol(multibootMethod.FullName); MethodScanner.MethodInvoked(multibootMethod, multibootMethod); var startUpType = TypeSystem.GetTypeByName("Mosa.Runtime", "StartUp"); var initializeMethod = startUpType.FindMethodByName("Initialize"); MethodScanner.MethodInvoked(initializeMethod, multibootMethod); }
public static Hook Create(Linker.HookData data) { switch (data.type) { case 1: return new WriteHook(false, data.args); case 2: return new WriteHook(true, data.args); case 3: return new BranchHook(false, data.args); case 4: return new BranchHook(true, data.args); case 5: return new PatchExitHook(data.args); default: throw new NotImplementedException("unknown command type"); } }
public bool Make(string fileName, out UnitComposition composition) { composition = null; var made = Linker.Make(fileName); if (made.Messages.Any()) { Printer.PrintErrors(made.Messages); } if (!made.Success) { return(false); } composition = made.Value; return(true); }
void HeaderFragment_Loaded(object sender, RoutedEventArgs e) { try { if (!Linker.isRunning()) { return; } // Configure buttons btn_notify.MouseDown += btn_notify_MouseDown; btn_settings.MouseDown += btn_settings_MouseDown; btn_about.MouseDown += btn_about_MouseDown; // Initital settings isrc_notification = btn_notify.Source; // Observing changes DispatcherTimer observerTimer = new DispatcherTimer(); observerTimer.Interval = new TimeSpan(TimeSpan.TicksPerSecond / 2); observerTimer.Tick += delegate(object s, EventArgs args) { Database d = Linker.opened().getDatabase(); // Company name observing txt_name.Text = d.settings.companyName; // Notification observer if (d.products.Where(p => p.Quantity <= d.settings.notifyOn).Count() > 0) { btn_notify.Visibility = btn_notify.Visibility != Visibility.Hidden ? Visibility.Hidden : Visibility.Visible; } else { btn_notify.Visibility = Visibility.Hidden; } }; observerTimer.Start(); } catch (Exception x) { Message.show(x.Message); } }
private void PerformStaticAllocation(Context context) { var allocatedType = context.MosaType; // node.Result.Type; var handle = context.Operand1; bool newObject = context.Instruction == IRInstruction.NewObject; int elements = 0; //Debug.WriteLine($"Method: {Method} : {node}"); //Debug.WriteLine($" --> {allocatedType}"); MethodScanner.TypeAllocated(allocatedType, Method); int allocationSize; if (newObject) { allocationSize = TypeLayout.GetTypeSize(allocatedType); } else { elements = (int)GetConstant(context.Operand3); allocationSize = (TypeLayout.GetTypeSize(allocatedType.ElementType) * elements) + (TypeLayout.NativePointerSize * 3); } var symbolName = Linker.DefineSymbol(StaticSymbolPrefix + allocatedType.FullName, SectionKind.BSS, Architecture.NativeAlignment, allocationSize); string typeDefinitionSymbol = Metadata.TypeDefinition + allocatedType.FullName; Linker.Link(LinkType.AbsoluteAddress, Is32BitPlatform ? PatchType.I32 : PatchType.I64, symbolName, 0, typeDefinitionSymbol, 0); var staticAddress = Operand.CreateSymbol(allocatedType, symbolName.Name); var move = Is32BitPlatform ? (BaseInstruction)IRInstruction.Move32 : IRInstruction.Move64; var store = Is32BitPlatform ? (BaseInstruction)IRInstruction.Store32 : IRInstruction.Store64; context.SetInstruction(move, context.Result, staticAddress); context.AppendInstruction(store, null, staticAddress, ConstantZero, handle); if (!newObject) { context.AppendInstruction(store, null, staticAddress, CreateConstant32(2 * (Is32BitPlatform ? 4 : 8)), CreateConstant32(elements)); } }
private static void Main(string[] args) { //:D Args = args; //Same thingy as in GCC if (args.Length == 0) { WriteError("no input files"); } else { //If we wanna see all messages by ANATOLIY if (HasArgument("--debug")) { Interpreter.Debug = true; } //If we wanna be a little faster if (HasArgument("--dontlinkstd")) { Interpreter.LinkStd = false; } //If the file passed does indeed exist if (args.Any(File.Exists)) { var file = args.First(File.Exists); if (Interpreter.Debug) { Console.WriteLine($"{file} file was selected.\nStarting.."); } //Add the standart classes like for IO, and etc. Linker.AddStd("std"); //...and finally run the file Interpreter.Interpret(file); if (Interpreter.Debug) { Console.WriteLine("\nAnatoliy is happy, the code ran without errors! :D"); } } else { WriteError("none of the files exist"); } } }
public void RoundTripMixedTypes() { var schema = this.CreateSchema <MixedContainer>(); var decoder = Linker.CreateDecoder(schema); var encoder = Linker.CreateEncoder(schema); SchemaTester.AssertRoundTrip(decoder, encoder, new MixedContainer { floats = new[] { 1.1f, 2.2f, 3.3f }, integer = 17, option = SomeEnum.B, pairs = new Dictionary <string, string> { { "a", "aaa" }, { "b", "bbb" } }, text = "Hello, World!" }); }
private LinkerSymbol CreateCustomAttribute(MosaUnit unit, MosaCustomAttribute ca, int position) { // Emit custom attribute list string name = unit.FullName + ">>" + position.ToString() + ":" + ca.Constructor.DeclaringType.Name; var customAttributeSymbol = Linker.DefineSymbol(Metadata.CustomAttribute + name, SectionKind.ROData, TypeLayout.NativePointerAlignment, 0); var writer1 = new EndianAwareBinaryWriter(customAttributeSymbol.Stream, Architecture.Endianness); // 1. Pointer to Attribute Type Linker.Link(LinkType.AbsoluteAddress, NativePatchType, customAttributeSymbol, writer1.Position, Metadata.TypeDefinition + ca.Constructor.DeclaringType.FullName, 0); writer1.WriteZeroBytes(TypeLayout.NativePointerSize); // 2. Pointer to Constructor Method Definition Linker.Link(LinkType.AbsoluteAddress, NativePatchType, customAttributeSymbol, writer1.Position, Metadata.MethodDefinition + ca.Constructor.FullName, 0); writer1.WriteZeroBytes(TypeLayout.NativePointerSize); // 3. Number of Arguments (Both unnamed and named) writer1.Write((uint)(ca.Arguments.Length + ca.NamedArguments.Length), TypeLayout.NativePointerSize); // 4. Pointers to Custom Attribute Arguments (Both unnamed and named) for (int i = 0; i < ca.Arguments.Length; i++) { // Build definition var customAttributeArgumentSymbol = CreateCustomAttributeArgument(name, i, null, ca.Arguments[i], false); // Link Linker.Link(LinkType.AbsoluteAddress, NativePatchType, customAttributeSymbol, writer1.Position, customAttributeArgumentSymbol, 0); writer1.WriteZeroBytes(TypeLayout.NativePointerSize); } foreach (var namedArg in ca.NamedArguments) { // Build definition var customAttributeArgumentSymbol = CreateCustomAttributeArgument(name, 0, namedArg.Name, namedArg.Argument, namedArg.IsField); // Link Linker.Link(LinkType.AbsoluteAddress, NativePatchType, customAttributeSymbol, writer1.Position, customAttributeArgumentSymbol, 0); writer1.WriteZeroBytes(TypeLayout.NativePointerSize); } return(customAttributeSymbol); }
public void DecodeFlatStructure() { const string source = "{" + "\"lorem\":0," + "\"ipsum\":65464658634633," + "\"sit\":1.1," + "\"amet\":\"Hello, World!\"," + "\"consectetur\":255," + "\"adipiscing\":64," + "\"elit\":\"z\"," + "\"sed\":53.25," + "\"pulvinar\":\"I sense a soul in search of answers\"," + "\"fermentum\":6553," + "\"hendrerit\":-32768" + "}"; var decoder = Linker.CreateDecoder(new JSONSchema <MyFlatStructure>()); CompareNewtonsoft.BenchDecode(decoder, source, 10000); }
public void Link_LinkedWords() { ExecutableModule exeModule = Linker.Link(m_relModules); Word[] expected = WordTest.MakeArray( // Sub 0x1234, // ADDEND DC #1234 0x2010, ADDEND_Address, // ADD1234 ADDA GR1,ADDEND 0x8100, // RET // Main 0x1010, LTRL0001_Address, // LBL101 LD GR1,=3456 0x8000, ADD1234_Address, // CALL SUB 0x8100, // RET 3456); // LTRL0001 DC 3456 IEnumerable <Word> actual = exeModule.Words; TestUtils.CheckEnumerable( expected, actual, "各再配置可能モジュールの語が結合される"); }
public async Task <Response> Authorize() { var code = Request.Query["code"].ToString(); var state = Request.Query["state"].ToString(); var expectedState = Session[SessionKeys.CSRF] as string; if (state != expectedState) { throw new InvalidOperationException("SECURITY FAIL!"); } Session[SessionKeys.CSRF] = null; var token = await StatusChecker.OAuthAccessToken(code); Session[SessionKeys.OAuthToken] = token.AccessToken; return(Context.GetRedirect(Linker.BuildRelativeUri(Context, "AboutPage").ToString())); }
private Intermediate LinkPhase(IEnumerable <Intermediate> intermediates) { var creator = this.ServiceProvider.GetService <ITupleDefinitionCreator>(); var libraries = this.LoadLibraries(creator); if (this.Messaging.EncounteredError) { return(null); } var linker = new Linker(this.ServiceProvider); linker.OutputType = this.OutputType; linker.Intermediates = intermediates; linker.Libraries = libraries; linker.TupleDefinitionCreator = creator; return(linker.Execute()); }
private void EmitFields() { writer.WriteLine("[Fields]"); writer.WriteLine("TypeID\tIndex\tFullName\tName\tFieldTypeID\tAddress\tAttributes\tOffset\tDataLength\tDataAddress"); foreach (var type in TypeSystem.AllTypes) { if (type.IsModule) { continue; } int index = 0; foreach (var field in type.Fields) { var symbolName = Metadata.FieldDefinition + field.FullName; if (!Linker.IsSymbolDefined(symbolName)) { continue; } var symbol = Linker.GetSymbol(symbolName); //var datasection = (field.Data != null) ? SectionKind.ROData : SectionKind.BSS; // not used yet writer.WriteLine( "{0}\t{1}\t{2}\t{3}\t{4}\t{5:x8}\t{6}\t{7}\t{8}\t{9:x8}", type.ID, index++, field.FullName, field.Name, field.FieldType.ID, symbol?.VirtualAddress ?? 0, (int)field.FieldAttributes, field.IsStatic && !field.IsLiteral ? 0 : TypeLayout.GetFieldOffset(field), // todo: missing first offset field.Data?.Length ?? 0, 0 // todo: DataAddress ); } } }
public void DecodeNestedArray() { const string source = "{" + "\"children\":[{" + "\"children\":[],\"value\":\"a\"" + "},{" + "\"children\":[{\"children\":[],\"value\":\"b\"},{\"children\":[],\"value\":\"c\"}]," + "\"value\":\"d\"" + "},{" + "\"children\":[],\"value\":\"e\"" + "}]," + "\"value\":\"f\"" + "}"; var decoder = Linker.CreateDecoder(new JSONSchema <MyNestedArray>()); CompareNewtonsoft.BenchDecode(decoder, source, 10000); }
private Operand MoveConstantToFloatRegister(Context context, Operand operand) { if (!operand.IsConstant) { return(operand); } var v1 = operand.IsR4 ? AllocateVirtualRegisterR4() : AllocateVirtualRegisterR8(); var symbol = operand.IsR4 ? Linker.GetConstantSymbol(operand.ConstantFloat) : Linker.GetConstantSymbol(operand.ConstantDouble); var label = Operand.CreateLabel(v1.Type, symbol.Name); var instruction = operand.IsR4 ? (BaseInstruction)X64.MovssLoad : X64.MovsdLoad; context.InsertBefore().SetInstruction(instruction, v1, label, ConstantZero); return(v1); }
private LinkerSymbol EmitStringWithLength(string name, string data) { // Strings are now going to be embedded objects since they are immutable var symbol = Linker.DefineSymbol(name, SectionKind.ROData, TypeLayout.NativePointerAlignment, (uint)(Compiler.ObjectHeaderSize + NativePointerSize + (data.Length * 2))); var writer = new BinaryWriter(symbol.Stream); Linker.Link(LinkType.AbsoluteAddress, NativePatchType, symbol, Compiler.ObjectHeaderSize - NativePointerSize, Metadata.TypeDefinition + "System.String", 0); // 1. Object Header writer.WriteZeroBytes(Compiler.ObjectHeaderSize); // 2. Length writer.Write(data.Length, NativePointerSize); // 3. Unicode writer.Write(Encoding.Unicode.GetBytes(data)); return(symbol); }
private void CreateDefinitionTables() { // Emit assembly list var assemblyListSymbol = Linker.DefineSymbol(Metadata.AssembliesTable, SectionKind.ROData, TypeLayout.NativePointerAlignment, 0); var writer = new EndianAwareBinaryWriter(assemblyListSymbol.Stream, Architecture.Endianness); // 1. Number of Assemblies writer.Write((uint)TypeSystem.Modules.Count, TypeLayout.NativePointerSize); // 2. Pointers to Assemblies foreach (var module in TypeSystem.Modules) { var assemblyTableSymbol = CreateAssemblyDefinition(module); // Link Linker.Link(LinkType.AbsoluteAddress, NativePatchType, assemblyListSymbol, writer.Position, assemblyTableSymbol, 0); writer.WriteZeroBytes(TypeLayout.NativePointerSize); } }
protected override void RunPostCompile() { if (string.IsNullOrEmpty(CompilerOptions.OutputFile)) { return; } File.Delete(CompilerOptions.OutputFile); if (Compiler.IsStopped) { return; } using (var file = new FileStream(CompilerOptions.OutputFile, FileMode.Create)) { Linker.Emit(file); } }
public void EncodeFlatStructure() { var encoder = Linker.CreateEncoder(new JSONSchema <MyFlatStructure>()); var instance = new MyFlatStructure { adipiscing = 64, amet = "Hello, World!", consectetur = 255, elit = 'z', fermentum = 6553, hendrerit = -32768, ipsum = 65464658634633, lorem = 0, pulvinar = "I sense a soul in search of answers", sed = 53.25f, sit = 1.1 }; CompareNewtonsoft.BenchEncode(encoder, instance, 10000); }
public LinkedModule Compile(SourceModule sourceModule) { Contract.Requires(sourceModule != null); // package up our inputs to the linker LinkContext linkContext = new LinkContext(); linkContext.AddModule(sourceModule); // load any imports that haven't already been loaded linkContext.LoadImports(); // link Linker linker = new Linker(); linker.Link(linkContext); // return the result return(linkContext.LinkedModule); }
/// <inheritdoc/> public void Dispose() { if (!Linker.IsInvalid) { Linker.Dispose(); Linker.SetHandleAsInvalid(); } if (!Store.IsInvalid) { Store.Dispose(); Store.SetHandleAsInvalid(); } if (!Engine.IsInvalid) { Engine.Dispose(); Engine.SetHandleAsInvalid(); } }
private void ExternalMethod() { if (!Method.IsExternal) { return; } IsCILDecodeRequired = false; IsExecutePipeline = false; IsStackFrameRequired = false; var intrinsic = Architecture.GetInstrinsicMethod(Method.ExternMethodModule); if (intrinsic != null) { return; } Linker.DefineExternalSymbol(Method.FullName, Method.ExternMethodName, SectionKind.Text); }
public void RoundTripNestedValue() { var schema = this.CreateSchema <NestedValue>(); var decoder = Linker.CreateDecoder(schema); var encoder = Linker.CreateEncoder(schema); SchemaTester.AssertRoundTrip(decoder, encoder, new NestedValue { child = new NestedValue { child = new NestedValue { child = null, value = 64 }, value = 42 }, value = 17 }); }
public void ShouldCreateTasks() { Task.Tasks.Clear(); var workspace = new Workspace(); workspace.BasePath = Path.Combine(basePath, "ShouldCreateTasks"); Directory.CreateDirectory(workspace.TasksDir); var f = File.Create(Path.Combine(workspace.TasksDir, "task1.crake")); var buf = ASCIIEncoding.ASCII.GetBytes("namespace :name1 do\ntask :todo1 do\nint i;\nSay();\nSay();\nend\nend\n public void Say() {\nConsole.WriteLine(\"oi\");\n}"); f.Write(buf, 0, buf.Length); f.Close(); workspace.LoadFiles(); workspace.Parse(); workspace.Compile(); var linker = new Linker(workspace); Assert.AreEqual(0, Task.Tasks.Count); linker.CreateTasks(); Assert.AreEqual(1, Task.Tasks.Count); Task.Tasks["name1:todo1"].Run(); }
public void AssembleComponents(Linker linker) { linker.WireInterface (typeof (IFirstUniqueInstanceAttributedComponent), typeof (FirstUniqueInstanceAttributedComponent), false); linker.WireInterface (typeof (IThirdUniqueInstanceAttributedComponent), typeof (ThirdUniqueInstanceAttributedComponentImpl), false); }
/// <summary> /// Generates the appropriate MSI file for the package. /// </summary> /// <param name="sourceDoc">WiX document to create MSI from.</param> /// <param name="filePath">File path for the RSS feed.</param> private void GenerateMsi(XmlDocument sourceDoc, string filePath) { // Compile Compiler compiler = new Compiler(); compiler.Message += new MessageEventHandler(this.MessageHandler); Intermediate intermediate = compiler.Compile(sourceDoc); if (intermediate == null) { return; } // locate the applib.wixlib string assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string applibPath = Path.Combine(assemblyPath, "applib.wixlib"); if (!File.Exists(applibPath)) { this.OnMessage(ClickThroughErrors.CannotLoadApplib(applibPath)); return; } WixVariableResolver wixVariableResolver = new WixVariableResolver(); wixVariableResolver.Message += new MessageEventHandler(this.MessageHandler); // create the linker Linker linker = new Linker(); linker.Message += new MessageEventHandler(this.MessageHandler); linker.WixVariableResolver = wixVariableResolver; // load applib.wixlib Library lowImpactAppLib = Library.Load(applibPath, linker.TableDefinitions, false, false); SectionCollection sections = new SectionCollection(); sections.AddRange(intermediate.Sections); sections.AddRange(lowImpactAppLib.Sections); // Link Output output = linker.Link(sections); if (output == null) { return; } Table components = output.Tables["Component"]; foreach (Row row in components.Rows) { switch ((string)row[0]) { case "ThisApplicationVersionRegistryKeyComponent": row[1] = String.Concat("{", Guid.NewGuid().ToString().ToUpper(), "}"); break; case "ThisApplicationCacheFolderComponent": row[1] = String.Concat("{", Guid.NewGuid().ToString().ToUpper(), "}"); break; case "ThisApplicationShortcutComponent": row[1] = String.Concat("{", Guid.NewGuid().ToString().ToUpper(), "}"); break; } } // Bind Binder binder = new Binder(); binder.Extension = new BinderExtension(); binder.Extension.SourcePaths.Add(Path.GetDirectoryName(filePath)); binder.Extension.SourcePaths.Add(assemblyPath); binder.WixVariableResolver = wixVariableResolver; binder.Message += new MessageEventHandler(this.MessageHandler); binder.Bind(output, filePath); return; }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); // Load Music SoundEffect musicMenu = Content.Load<SoundEffect>("Music/town"); SoundEffect musicGameplay = Content.Load<SoundEffect>("Music/town"); SoundEffect musicGuard = Content.Load<SoundEffect>("Music/guard"); // Load Menu Texture2D memories = Content.Load<Texture2D>("Textures/Menu_Memories"); Texture2D options = Content.Load<Texture2D>("Textures/Menu_Options"); Texture2D quit = Content.Load<Texture2D>("Textures/Menu_Quit"); MenuScreen = new Menu(memories, options, quit, musicMenu); ItemPeopleMenu = new ItemPeopleUI(); ItemPeopleMenu.MenuSprite = Content.Load<Texture2D>("UI/MenuScreen"); ItemPeopleMenu.LoadImages( Content.Load<Texture2D>("UI/FaceProfiles"), Content.Load<Texture2D>("UI/ItemSprites"), Content.Load<Texture2D>("UI/ItemDescriptions"), Content.Load<Texture2D>("UI/ProfileDescriptions") ); // Blank tile for testing blankTexture = Content.Load<Texture2D>("Textures/blank"); // Load Level LoadLevel(); // Player Dying Sprite level.PlayerDying = Content.Load<Texture2D>("Textures/SamiDying"); // Loads all levels in memory level.Level2Texture = Content.Load<Texture2D>("LevelTextures/Level2"); level.Level3Texture = Content.Load<Texture2D>("LevelTextures/Level3"); // Load SoundEffects level.LoadSounds( Content.Load<SoundEffect>("Audio/collect item"), Content.Load<SoundEffect>("Audio/death chime"), Content.Load<SoundEffect>("Audio/female mumbling"), Content.Load<SoundEffect>("Audio/finish level chime"), Content.Load<SoundEffect>("Audio/ghosts scream"), Content.Load<SoundEffect>("Audio/give item"), Content.Load<SoundEffect>("Audio/item revealed"), Content.Load<SoundEffect>("Audio/male mumbling"), Content.Load<SoundEffect>("Audio/running to a stop"), Content.Load<SoundEffect>("Audio/running"), Content.Load<SoundEffect>("Audio/sneak start"), Content.Load<SoundEffect>("Audio/speech popup"), Content.Load<SoundEffect>("Audio/walking") ); gameMode = (int)GameMode.Menu; font = Content.Load<SpriteFont>("Arial"); // CoolDownTimer int timerWidth = 60; int timerHeight = 60; int eventDuration = 60; int cooldown = 60; TimeSpan rate = TimeSpan.FromMilliseconds(50); Texture2D CooldownTimer = Content.Load<Texture2D>("Textures/blank"); CoolDownTimers.Add(new Cooldown(CooldownTimer, new Rectangle(40, ScreenHeight - timerWidth - 40, timerWidth, timerHeight), eventDuration, cooldown, rate)); // Level Linker LevelLinker = new Linker( Content.Load<Texture2D>("Linker/health1"), Content.Load<Texture2D>("Linker/child1"), Content.Load<Texture2D>("Linker/pregnant1"), Content.Load<Texture2D>("Linker/hungry1"), Content.Load<Texture2D>("Linker/gender1"), Content.Load<Texture2D>("Linker/pregnant2"), Content.Load<Texture2D>("Linker/health2"), Content.Load<Texture2D>("Linker/hungry2") ); }
protected bool Comp(Linker a, Linker b) { switch (m_Compare) { case CompareType.Less: return a.m_Elem < b.m_Elem; default: return a.m_Elem > b.m_Elem; } }
public void AssembleComponents(Linker linker) { linker.WireInterface (typeof (ISecondAttributedComponent), typeof (SecondNonAttributedComponentImpl)); }
public void AssembleComponents(Linker linker) { linker.WireInterface (typeof (IFirstVariousImplementationComponent), typeof (OneAttribute), typeof (FirstVariousImplementationComponentOneImpl)); linker.WireInterface (typeof (IFirstVariousImplementationComponent), typeof (TwoAttribute), typeof (FirstVariousImplementationComponentTwoImpl)); linker.WireInterface (typeof (ISecondVariousImplementationComponent), typeof (OneAttribute), typeof (SecondVariousImplementationComponentOneImpl)); linker.WireInterface (typeof (ISecondVariousImplementationComponent), typeof (TwoAttribute), typeof (SecondVariousImplementationComponentTwoImpl)); }
/** * This method allows a user to add some state in the ConnectTo call (see SNCO). */ virtual protected Connector GetConnector(ISender sender, Address target, string ConnectionType, string token) { ConnectionType mt = Connection.StringToMainType(ConnectionType); /* * This is an anonymous delegate which is called before * the Connector starts. If it returns true, the Connector * will finish immediately without sending an ConnectToMessage */ Linker l = new Linker(_node, target, null, ConnectionType, token); object link_task = l.Task; Connector.AbortCheck abort = delegate(Connector c) { bool stop = false; stop = _node.ConnectionTable.Contains( mt, target ); if (!stop ) { /* * Make a linker to get the task. We won't use * this linker. * No need in sending a ConnectToMessage if we * already have a linker going. */ stop = _node.TaskQueue.HasTask( link_task ); } return stop; }; ConnectToMessage ctm = GetConnectToMessage(ConnectionType, token); Connector con = new Connector(_node, sender, ctm, this, target); con.FinishEvent += ConnectorEndHandler; con.AbortIf = abort; return con; }
/** * Connectors just send and receive ConnectToMessages. They return all responses * to the ConnectionOverlord that initiated the ConnectToMessage * @return true if we have enough responses for this connector, and should * stop listening for more */ virtual public bool HandleCtmResponse(Connector c, ISender return_path, ConnectToMessage resp) { /** * Time to start linking: */ ICollection transports = resp.Target.Transports; if(TAAuth != null) { ArrayList trans = new ArrayList(); foreach(TransportAddress ta in resp.Target.Transports) { if(TAAuth.Authorize(ta) != TAAuthorizer.Decision.Deny) { trans.Add(ta); } } transports = trans; } Linker l = new Linker(_node, resp.Target.Address, transports, resp.ConnectionType, resp.Token); l.FinishEvent += LinkerEndHandler; _node.TaskQueue.Enqueue( l ); return true; }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { Linker linker = null; Localizer localizer = null; SectionCollection sections = new SectionCollection(); ArrayList transforms = new ArrayList(); try { // parse the command line this.ParseCommandLine(args); // load any extensions List<WixExtension> loadedExtensionList = new List<WixExtension>(); foreach (string extension in this.extensionList) { WixExtension wixExtension = WixExtension.Load(extension); loadedExtensionList.Add(wixExtension); // If the extension provides a binder, use that now if it // matches the class from the command line. if (null != wixExtension.CustomBinder && null != this.binderClass && wixExtension.CustomBinder.GetType().Name.Equals(this.binderClass, StringComparison.Ordinal)) { this.binder = wixExtension.CustomBinder; } } // If a binder was specified, but not found then show an error. if (!String.IsNullOrEmpty(this.binderClass) && null == this.binder) { throw new WixException(WixErrors.SpecifiedBinderNotFound(this.binderClass)); } // create the linker, binder, and validator linker = new Linker(); if (null == this.binder) { this.binder = new Microsoft.Tools.WindowsInstallerXml.Binder(); } // have the binder parse the command line arguments light did not recognize string[] unparsedArgsArray = new string[this.unparsedArgs.Count]; this.unparsedArgs.CopyTo(unparsedArgsArray, 0); StringCollection remainingArgs = this.binder.ParseCommandLine(unparsedArgsArray, this.messageHandler); // Loop through the extensions to give them a shot at processing the remaining command-line args. foreach (WixExtension wixExtension in loadedExtensionList) { if (0 == remainingArgs.Count) { break; } remainingArgs = wixExtension.ParseCommandLine(remainingArgs, this.messageHandler); } this.ParseCommandLinePassTwo(remainingArgs); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return this.messageHandler.LastErrorNumber; } foreach (string parameter in this.invalidArgs) { this.messageHandler.Display(this, WixWarnings.UnsupportedCommandLineArgument(parameter)); } this.invalidArgs = null; // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return this.messageHandler.LastErrorNumber; } if (0 == this.inputFiles.Count) { this.showHelp = true; } else if (null == this.outputFile) { if (1 < this.inputFiles.Count) { throw new WixException(WixErrors.MustSpecifyOutputWithMoreThanOneInput()); } this.outputFile = Path.ChangeExtension(Path.GetFileName(this.inputFiles[0]), ".wix"); // we'll let the linker change the extension later } this.binder.OutputFile = this.outputFile; this.binder.PostParseCommandLine(); if (this.showLogo) { AppCommon.DisplayToolHeader(); } if (this.showHelp) { this.PrintHelp(); AppCommon.DisplayToolFooter(); return this.messageHandler.LastErrorNumber; } linker.AllowIdenticalRows = this.allowIdenticalRows; linker.AllowUnresolvedReferences = this.allowUnresolvedReferences; linker.Cultures = this.cultures; linker.UnreferencedSymbolsFile = this.unreferencedSymbolsFile; linker.ShowPedanticMessages = this.showPedanticMessages; linker.DropUnrealTables = this.dropUnrealTables; linker.SuppressLocalization = this.suppressLocalization; linker.SuppressMsiAssemblyTable = this.suppressMsiAssemblyTable; linker.WixVariableResolver = this.wixVariableResolver; // set the sequence suppression options linker.SuppressAdminSequence = this.suppressAdminSequence; linker.SuppressAdvertiseSequence = this.suppressAdvertiseSequence; linker.SuppressUISequence = this.suppressUISequence; linker.SectionIdOnRows = this.sectionIdOnRows; this.binder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); this.binder.WixVariableResolver = this.wixVariableResolver; if (null != this.bindPaths) { foreach (string bindPath in this.bindPaths) { if (-1 == bindPath.IndexOf('=')) { this.sourcePaths.Add(bindPath); } } } // instantiate the localizer and load any localization files if (!this.suppressLocalization || 0 < this.localizationFiles.Count || null != this.cultures || !this.outputXml) { List<Localization> localizations = new List<Localization>(); localizer = new Localizer(); localizer.Message += new MessageEventHandler(this.messageHandler.Display); // load each localization file foreach (string localizationFile in this.localizationFiles) { Localization localization = Localization.Load(localizationFile, linker.TableDefinitions, this.suppressSchema); localizations.Add(localization); } if (null != this.cultures) { // add localizations in order specified in cultures foreach (string culture in this.cultures) { foreach (Localization localization in localizations) { if (culture.Equals(localization.Culture, StringComparison.OrdinalIgnoreCase)) { localizer.AddLocalization(localization); } } } } else { bool neutralFound = false; foreach (Localization localization in localizations) { if (0 == localization.Culture.Length) { // if a neutral wxl was provided use it localizer.AddLocalization(localization); neutralFound = true; } } if (!neutralFound) { // cultures wasn't specified and no neutral wxl are available, include all of the files foreach (Localization localization in localizations) { localizer.AddLocalization(localization); } } } // immediately stop processing if any errors were found if (this.messageHandler.EncounteredError) { return this.messageHandler.LastErrorNumber; } // tell all of the objects about the localizer linker.Localizer = localizer; this.binder.Localizer = localizer; this.wixVariableResolver.Localizer = localizer; } // process loaded extensions foreach (WixExtension wixExtension in loadedExtensionList) { linker.AddExtension(wixExtension); this.binder.AddExtension(wixExtension); // load the extension's localizations Library library = wixExtension.GetLibrary(linker.TableDefinitions); if (null != library) { // load the extension's default culture if it provides one and we don't specify any cultures string[] extensionCultures = this.cultures; if (null == extensionCultures && null != wixExtension.DefaultCulture) { extensionCultures = new string[] { wixExtension.DefaultCulture }; } library.GetLocalizations(extensionCultures, localizer); } } this.binder.ProcessExtensions(loadedExtensionList.ToArray()); // set the message handlers linker.Message += new MessageEventHandler(this.messageHandler.Display); this.binder.AddMessageEventHandler(new MessageEventHandler(this.messageHandler.Display)); Output output = null; // loop through all the believed object files foreach (string inputFile in this.inputFiles) { string dirName = Path.GetDirectoryName(inputFile); string inputFileFullPath = Path.GetFullPath(inputFile); if (!this.sourcePaths.Contains(dirName)) { this.sourcePaths.Add(dirName); } // try loading as an object file try { Intermediate intermediate = Intermediate.Load(inputFileFullPath, linker.TableDefinitions, this.suppressVersionCheck, this.suppressSchema); sections.AddRange(intermediate.Sections); continue; // next file } catch (WixNotIntermediateException) { // try another format } // try loading as a library file try { Library library = Library.Load(inputFileFullPath, linker.TableDefinitions, this.suppressVersionCheck, this.suppressSchema); library.GetLocalizations(this.cultures, localizer); sections.AddRange(library.Sections); continue; // next file } catch (WixNotLibraryException) { // try another format } // try loading as an output file output = Output.Load(inputFileFullPath, this.suppressVersionCheck, this.suppressSchema); } // immediately stop processing if any errors were found if (this.messageHandler.EncounteredError) { return this.messageHandler.LastErrorNumber; } // set the binder file manager information foreach (string bindPath in this.bindPaths) { //Checking as IndexOf will return 0 if the string value is String.Empty. if (String.IsNullOrEmpty(bindPath)) { continue; } if (-1 == bindPath.IndexOf('=')) { this.binder.FileManager.BindPaths.Add(bindPath); } else { string[] namedPair = bindPath.Split('='); //It is ok to have duplicate key. this.binder.FileManager.NamedBindPaths.Add(namedPair[0], namedPair[1]); } } foreach (string sourcePath in this.sourcePaths) { this.binder.FileManager.SourcePaths.Add(sourcePath); } // and now for the fun part if (null == output) { OutputType expectedOutputType = OutputType.Unknown; if (this.outputFile != null) { expectedOutputType = Output.GetOutputType(Path.GetExtension(this.outputFile)); } output = linker.Link(sections, transforms, expectedOutputType); // if an error occurred during linking, stop processing if (null == output) { return this.messageHandler.LastErrorNumber; } } else if (0 != sections.Count) { throw new InvalidOperationException(LightStrings.EXP_CannotLinkObjFilesWithOutpuFile); } // Now that the output object is either linked or loaded, tell the binder file manager about it. this.binder.FileManager.Output = output; // only output the xml if its a patch build or user specfied to only output wixout if (this.outputXml || OutputType.Patch == output.Type) { string outputExtension = Path.GetExtension(this.outputFile); if (null == outputExtension || 0 == outputExtension.Length || ".wix" == outputExtension) { if (OutputType.Patch == output.Type) { this.outputFile = Path.ChangeExtension(this.outputFile, ".wixmsp"); } else { this.outputFile = Path.ChangeExtension(this.outputFile, ".wixout"); } } output.Save(this.outputFile, (this.bindFiles ? this.binder.FileManager : null), this.wixVariableResolver, this.binder.TempFilesLocation); } else // finish creating the MSI/MSM { string outputExtension = Path.GetExtension(this.outputFile); if (null == outputExtension || 0 == outputExtension.Length || ".wix" == outputExtension) { outputExtension = Output.GetExtension(output.Type); this.outputFile = Path.ChangeExtension(this.outputFile, outputExtension); } this.binder.Bind(output, this.outputFile); } } catch (WixException we) { if (we is WixInvalidIdtException) { // make sure the IDT files stay around this.tidy = false; } this.messageHandler.Display(this, we.Error); } catch (Exception e) { // make sure the files stay around for debugging this.tidy = false; this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } finally { if (null != binder) { this.binder.Cleanup(this.tidy); } } return this.messageHandler.LastErrorNumber; }
/// <summary> /// Generates the appropriate MSI file for the package. /// </summary> /// <param name="sourceDoc">WiX document to create MSI from.</param> /// <param name="outputFile">File path for the MSI file.</param> /// <returns>True if generation works, false if anything goes wrong.</returns> private bool GenerateMsi(XmlDocument sourceDoc, string outputFile) { // Create the Compiler. Compiler compiler = new Compiler(); compiler.Message += this.core.MessageEventHandler; // Compile the source document. Intermediate intermediate = compiler.Compile(sourceDoc); if (intermediate == null) { return false; } // Create the variable resolver that will be used in the Linker and Binder. WixVariableResolver wixVariableResolver = new WixVariableResolver(); wixVariableResolver.Message += this.core.MessageEventHandler; // Create the Linker. Linker linker = new Linker(); linker.Message += this.core.MessageEventHandler; linker.WixVariableResolver = wixVariableResolver; // Load the isolatedapp.wixlib. System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); Library appLib = LoadLibraryHelper(assembly, "Microsoft.Tools.WindowsInstallerXml.Extensions.OfficeAddin.Data.OfficeAddin.wixlib", linker.TableDefinitions); // Link the compiled source document and the isolatedapp.wixlib together. SectionCollection sections = new SectionCollection(); sections.AddRange(intermediate.Sections); sections.AddRange(appLib.Sections); Output output = linker.Link(sections); if (output == null) { return false; } // Tweak the compiled output to add a few GUIDs for Components from the oaddin.wixlib. Table components = output.Tables["Component"]; foreach (Row row in components.Rows) { switch ((string)row[0]) { case "ThisApplicationVersionRegistryKeyComponent": row[1] = Guid.NewGuid().ToString("B"); break; case "ThisApplicationCacheFolderComponent": row[1] = Guid.NewGuid().ToString("B"); break; case "ThisApplicationShortcutComponent": row[1] = Guid.NewGuid().ToString("B"); break; } } // Bind the final output. Binder binder = new Binder(); binder.FileManager = new BinderFileManager(); binder.FileManager.SourcePaths.Add(Path.GetDirectoryName(outputFile)); binder.FileManager.SourcePaths.Add(this.source); binder.FileManager.SourcePaths.Add(Path.GetDirectoryName(assembly.Location)); binder.Message += this.core.MessageEventHandler; binder.WixVariableResolver = wixVariableResolver; return binder.Bind(output, outputFile); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { try { XmlSchemaCollection objectSchema = new XmlSchemaCollection(); FileInfo currentFile = null; ArrayList intermediates = new ArrayList(); Linker linker = null; Microsoft.Tools.WindowsInstallerXml.Binder binder = null; Localizer localizer = null; try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.FoundError) { return this.messageHandler.PostProcess(); } if (0 == this.objectFiles.Count) { this.showHelp = true; } else if (null == this.outputFile) { if (1 < this.objectFiles.Count) { throw new ArgumentException("must specify output file when using more than one input file", "-out"); } FileInfo fi = (FileInfo)this.objectFiles[0]; this.outputFile = new FileInfo(Path.ChangeExtension(fi.Name, ".wix")); // we'll let the linker change the extension later } if (this.showLogo) { Assembly lightAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xml Linker version {0}", lightAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved."); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: light.exe [-?] [-b basePath] [-nologo] [-out outputFile] objectFile [objectFile ...]"); Console.WriteLine(); Console.WriteLine(" -ai allow identical rows, identical rows will be treated as a warning"); Console.WriteLine(" -au (experimental) allow unresolved references, will not create a valid output"); Console.WriteLine(" -b base path to locate all files (default: current directory)"); Console.WriteLine(" -cc path to cache built cabinets (will not be deleted after linking)"); Console.WriteLine(" -ext extension (class, assembly), should extend SchemaExtension or BinderExtension"); Console.WriteLine(" -fv add a 'fileVersion' entry to the MsiAssemblyName table (rarely needed)"); Console.WriteLine(" -i specify the base output path for uncompressed images (default: -out parameter)"); Console.WriteLine(" -loc read localization string sfrom .wxl file"); Console.WriteLine(" -nologo skip printing light logo information"); Console.WriteLine(" -notidy do not delete temporary files (useful for debugging)"); Console.WriteLine(" -reusecab reuse cabinets from cabinet cache"); Console.WriteLine(" -out specify output file (default: write to current directory)"); Console.WriteLine(" -xo output xml instead of MSI format"); Console.WriteLine(" -pedantic:<level> pedantic checks (levels: easy, heroic, legendary)"); Console.WriteLine(" -reusecab reuse cabinets from cabinet cache"); Console.WriteLine(" -sa suppress assemblies: do not get assembly name information for assemblies"); Console.WriteLine(" -sacl suppress resetting ACLs (useful when laying out image to a network share)"); Console.WriteLine(" -sadmin suppress default admin sequence actions"); Console.WriteLine(" -sadv suppress default adv sequence actions"); Console.WriteLine(" -sa suppress assemblys: do not get assembly name information for assemblies"); Console.WriteLine(" -sf suppress files: do not get any file information (equivalent to -sa and -sh)"); Console.WriteLine(" -sh suppress file info: do not get hash, version, language, etc"); Console.WriteLine(" -sl suppress layout"); Console.WriteLine(" -ss suppress schema validation of documents (performance boost)"); Console.WriteLine(" -sui suppress default UI sequence actions"); Console.WriteLine(" -sv suppress intermediate file version mismatch checking"); Console.WriteLine(" -ts tag sectionId attribute on tuples (ignored if not used with -xo)"); Console.WriteLine(" -ust use small table definitions (for backwards compatiblity)"); Console.WriteLine(" -wx treat warnings as errors"); Console.WriteLine(" -w<N> set the warning level (0: show all, 3: show none)"); Console.WriteLine(" -sw suppress all warnings (same as -w3)"); Console.WriteLine(" -sw<N> suppress warning with specific message ID"); Console.WriteLine(" -v verbose output (same as -v2)"); Console.WriteLine(" -v<N> sets the level of verbose output (0: most output, 3: none)"); Console.WriteLine(" -? this help information"); Console.WriteLine(); Console.WriteLine("Environment variables:"); Console.WriteLine(" WIX_TEMP overrides the temporary directory used for cab creation, msm exploding, ..."); Console.WriteLine(); Console.WriteLine("Common extensions:"); Console.WriteLine(" .wxs - Windows installer Xml Source file"); Console.WriteLine(" .wxi - Windows installer Xml Include file"); Console.WriteLine(" .wxl - Windows installer Xml Localization file"); Console.WriteLine(" .wixobj - Windows installer Xml Object file (in XML format)"); Console.WriteLine(" .wixlib - Windows installer Xml Library file (in XML format)"); Console.WriteLine(" .wixout - Windows installer Xml Output file (in XML format)"); Console.WriteLine(); Console.WriteLine(" .msm - Windows installer Merge Module"); Console.WriteLine(" .msi - Windows installer Product Database"); Console.WriteLine(" .mst - Windows installer Transform"); Console.WriteLine(" .pcp - Windows installer Patch Creation Package"); Console.WriteLine(); Console.WriteLine("For more information see: http://wix.sourceforge.net"); return this.messageHandler.PostProcess(); } // create the linker and the binder linker = new Linker(this.useSmallTables); binder = new Microsoft.Tools.WindowsInstallerXml.Binder(this.useSmallTables); linker.AllowIdenticalRows = this.allowIdenticalRows; linker.AllowUnresolvedReferences = this.allowUnresolvedReferences; linker.PedanticLevel = this.pedanticLevel; // set the sequence suppression options linker.SuppressAdminSequence = this.suppressAdminSequence; linker.SuppressAdvertiseSequence = this.suppressAdvertiseSequence; linker.SuppressUISequence = this.suppressUISequence; linker.SectionIdOnTuples = this.sectionIdOnTuples; binder.SuppressAclReset = this.suppressAclReset; binder.SetMsiAssemblyNameFileVersion = this.setMsiAssemblyNameFileVersion; binder.SuppressAssemblies = this.suppressAssemblies; binder.SuppressFileHashAndInfo = this.suppressFileHashAndInfo; if (this.suppressFiles) { binder.SuppressAssemblies = true; binder.SuppressFileHashAndInfo = true; } binder.SuppressLayout = this.suppressLayout; binder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); if (null != this.cabCachePath || this.reuseCabinets) { // ensure the cabinet cache path exists if we are going to use it if (null != this.cabCachePath && !Directory.Exists(this.cabCachePath)) { Directory.CreateDirectory(this.cabCachePath); } } if (null != this.basePaths) { foreach (string basePath in this.basePaths) { this.sourcePaths.Add(basePath); } } // load any extensions bool binderExtensionLoaded = false; foreach (string extension in this.extensionList) { Type extensionType = Type.GetType(extension); if (null == extensionType) { throw new WixInvalidExtensionException(extension); } if (extensionType.IsSubclassOf(typeof(BinderExtension))) { object[] extensionArgs = new object[] { this.basePaths, this.cabCachePath, this.reuseCabinets, this.sourcePaths }; BinderExtension binderExtension = Activator.CreateInstance(extensionType, extensionArgs) as BinderExtension; Debug.Assert(null != binderExtension); if (binderExtensionLoaded) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "cannot load binder extension: {0}. light can only load one binder extension and has already loaded binder extension: {1}.", binderExtension.ToString(), binder.Extension.ToString()), "ext"); } binder.Extension = binderExtension; binderExtensionLoaded = true; } else if (extensionType.IsSubclassOf(typeof(SchemaExtension))) { linker.AddExtension((SchemaExtension)Activator.CreateInstance(extensionType)); } else { throw new WixInvalidExtensionException(extension, extensionType, typeof(BinderExtension), typeof(SchemaExtension)); } } // if the binder extension has not been loaded yet use the built-in binder extension if (!binderExtensionLoaded) { binder.Extension = new LightBinderExtension(this.basePaths, this.cabCachePath, this.reuseCabinets, this.sourcePaths); } if (null != this.imagebaseOutputPath) { binder.ImageBaseOutputPath = this.imagebaseOutputPath; } // set the message handlers linker.Message += new MessageEventHandler(this.messageHandler.Display); binder.Message += new MessageEventHandler(this.messageHandler.Display); // load the object schema if (!this.suppressSchema) { Assembly wixAssembly = Assembly.Load("wix"); using (Stream objectsSchemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.objects.xsd")) { XmlReader reader = new XmlTextReader(objectsSchemaStream); objectSchema.Add("http://schemas.microsoft.com/wix/2003/04/objects", reader); } } Output output = null; // loop through all the believed object files foreach (FileInfo objectFile in this.objectFiles) { currentFile = objectFile; string dirName = Path.GetDirectoryName(currentFile.FullName); if (!StringArrayContains(this.sourcePaths, dirName)) { this.sourcePaths.Add(dirName); } // load the object file into an intermediate object and add it to the list to be linked using (Stream fileStream = new FileStream(currentFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { XmlReader fileReader = new XmlTextReader(fileStream); try { XmlReader intermediateReader = fileReader; if (!this.suppressSchema) { intermediateReader = new XmlValidatingReader(fileReader); ((XmlValidatingReader)intermediateReader).Schemas.Add(objectSchema); } Intermediate intermediate = Intermediate.Load(intermediateReader, currentFile.FullName, linker.TableDefinitions, this.suppressVersionCheck); intermediates.Add(intermediate); continue; // next file } catch (WixNotIntermediateException) { // try another format } try { Library library = Library.Load(currentFile.FullName, linker.TableDefinitions, this.suppressVersionCheck); intermediates.AddRange(library.Intermediates); continue; // next file } catch (WixNotLibraryException) { // try another format } output = Output.Load(currentFile.FullName, this.suppressVersionCheck); } } // instantiate the localizer and load any wixloc files if (0 < this.localizationFiles.Count || !this.outputXml) { localizer = new Localizer(); localizer.Message += new MessageEventHandler(this.messageHandler.Display); // load each wixloc file foreach (string localizationFile in this.localizationFiles) { localizer.LoadFromFile(localizationFile); } // immediately stop processing if any errors were found if (this.messageHandler.FoundError) { return this.messageHandler.PostProcess(); } } // and now for the fun part currentFile = this.outputFile; if (null == output) { // tell the linker about the localizer linker.Localizer = localizer; localizer = null; output = linker.Link((Intermediate[])intermediates.ToArray(typeof(Intermediate))); // if an error occurred during linking, stop processing if (null == output) { return this.messageHandler.PostProcess(); } } else if (0 != intermediates.Count) { throw new InvalidOperationException("Cannot link object files (.wixobj) files with an output file (.wixout)"); } output.Path = this.outputFile.FullName; // only output the xml if (this.outputXml) { string outputExtension = Path.GetExtension(this.outputFile.FullName); if (null == outputExtension || 0 == outputExtension.Length || ".wix" == outputExtension) { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".wixout"); } output.Save(); } else // finish creating the MSI/MSM { string outputExtension = Path.GetExtension(this.outputFile.FullName); if (null == outputExtension || 0 == outputExtension.Length || ".wix" == outputExtension) { if (OutputType.Module == output.Type) { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".msm"); } else if (OutputType.PatchCreation == output.Type) { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".pcp"); } else { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".msi"); } } // tell the binder about the localizer binder.Localizer = localizer; binder.Bind(output); } currentFile = null; } catch (WixInvalidIdtException) { this.tidy = false; // make sure the IDT files stay around throw; } catch (WixMergeFailureException) { this.tidy = false; // make sure the merge.log stays around throw; } finally { if (null != binder) { if (this.tidy) { if (!binder.DeleteTempFiles()) { Console.WriteLine("Warning, failed to delete temporary directory: {0}", binder.TempFilesLocation); } } else { Console.WriteLine("Temporary directory located at '{0}'.", binder.TempFilesLocation); } } } } catch (WixException we) { // TODO: once all WixExceptions are converted to errors, this clause // should be a no-op that just catches WixFatalErrorException's this.messageHandler.Display("light.exe", "LGHT", we); return 1; } catch (Exception e) { this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } return this.messageHandler.PostProcess(); }
public void AssembleComponents(Linker linker) { linker.WireInterface (typeof (IFirstComponent), typeof (FirstComponentImpl)); linker.WireInterface (typeof (ISecondComponent), typeof (SecondComponentFieldInjectionImpl), true); linker.WireInterface (typeof (IThirdComponent), typeof (ThirdComponentConstructorInjectionImpl)); }
private void HandleProjectItemChange(ProjectItem projectItem, ProjectItemAction action, string oldName = null) { Argument.IsNotNull("projectItem", projectItem); if (!_isSolutionLoaded) { return; } Log.Debug("Handling action '{0}' for item '{1}'", action, projectItem.Name); var configuration = _configurationService.LoadConfigurationForCurrentSolution(); if (configuration.EnableAutoLink) { var sourceProject = projectItem.ContainingProject; var sourceProjectName = sourceProject.Name; var projectsToLink = (from projectMapping in configuration.ProjectMappings where string.Equals(projectMapping.SourceProject, sourceProjectName, StringComparison.OrdinalIgnoreCase) select _visualStudioService.GetProjectByName(projectMapping.TargetProject)).ToArray(); var linker = new Linker(sourceProject, projectsToLink, configuration); linker.RemoveMissingFiles = true; linker.HandleProjectItemChange(projectItem, action, oldName); } }