コード例 #1
0
        public async Task <ProcessFileResultModel> ProcessFiles(ProcessFileModel fileModel)
        {
            try
            {
                FileFacade    fileFacede      = new FileFacade(_fileValidators, _fileFormatValidators, _businessRuleValidators);
                string        folder          = System.Web.Hosting.HostingEnvironment.MapPath("~/CSVFiles/");
                List <string> serverFilePaths = new List <string>();
                foreach (string filePath in fileModel.FilePaths)
                {
                    serverFilePaths.Add(folder + filePath);
                }
                var fileResultTasks = fileFacede.ProcessFiles <Shipment>(serverFilePaths.ToArray());

                var fileResults = await Task.WhenAll(fileResultTasks);

                return(new ProcessFileResultModel {
                    Message = "File processing successful", FileResults = fileResults
                });
            }
            catch
            {
                //ToDo: Proper logging at business logic level
                return(new ProcessFileResultModel {
                    Message = "Error in processing file/s!"
                });
            }
        }
コード例 #2
0
ファイル: TableLoader.cs プロジェクト: HeewonChae/PoseProject
        private static void Load_ErrorCodeDescription(string rootPath)
        {
            var errors = FileFacade.ReadAllText(Path.Combine(rootPath, "ErrorCodeDescription.json"))
                         .JsonDeserialize <Dictionary <int, string> >();

            ErrorCodeDescription.Errors = errors;
        }
コード例 #3
0
        public void ProcessFiles_InvalidBusiness_Test()
        {
            //No assertion for this test case, needs enhancements (currently verified manually)
            FileFacade fileFacade = new FileFacade(_fileValidators, _fileFormatValidators, _businessRuleValidators);

            fileFacade.ProcessFiles <Shipment>("Shipment_Input_BusinessInvalid.csv");
        }
コード例 #4
0
ファイル: TableLoader.cs プロジェクト: HeewonChae/PoseProject
        private static void Load_InAppProduct(string rootPath)
        {
            var Purchases = FileFacade.ReadAllText(Path.Combine(rootPath, "InAppPurchase.json"))
                            .JsonDeserialize <InAppPurchase[]>();

            InAppPurchase.PostProcess(Purchases);
        }
コード例 #5
0
ファイル: FacadeProcess.cs プロジェクト: Guilegaton/Patterns
        public void StartExample()
        {
            var facade = new FileFacade("Sample.txt");

            facade.ReadFromFile();
            facade.WriteToFile();
        }
コード例 #6
0
ファイル: CabinetResolver.cs プロジェクト: sgtatham/Core
        private IBindFileWithPath CreateBindFileWithPath(FileFacade facade)
        {
            var result = this.ServiceProvider.GetService <IBindFileWithPath>();

            result.Id   = facade.Id;
            result.Path = facade.SourcePath;

            return(result);
        }
コード例 #7
0
 public OperatingSystemFacade()
 {
     Assembly          = new AssemblyFacade();
     Dialog            = new DialogFacade();
     Environment       = new Environment();
     File              = new FileFacade();
     MemoryMappedFiles = new MemoryMappedFileFactory();
     ProcessLocator    = new ProcessLocator();
     ProcessStarter    = new ProcessStarter();
     Registry          = new Registry();
 }
コード例 #8
0
 public OperatingSystemFacade()
 {
     Assembly = new AssemblyFacade();
     Dialog = new DialogFacade();
     Directory = new DirectoryFacade();
     Environment = new Environment();
     File = new FileFacade();
     MemoryMappedFiles = new MemoryMappedFileFactory();
     ProcessLocator = new ProcessLocator();
     ProcessStarter = new ProcessStarter();
     Registry = new Registry();
 }
コード例 #9
0
        public HttpResponseMessage GetFile(ProcessFileModel fileModel)
        {
            FileFacade fileFacede = new FileFacade();
            //Here we know that all files are in single folder so we are sending only one folder path for Zip creation
            //Current service method will support zip file creation from diffrent paths as well
            List <string> filePaths = new List <string>();

            filePaths.Add(fileModel.FilePaths[0]);
            string   filePath = fileFacede.CreateZip(filePaths);
            FileInfo fileInfo = new FileInfo(filePath);

            return(FileAsAttachment(filePath, fileInfo.Name));
        }
コード例 #10
0
        public static Email ReadEmail(string name = "", string cookieName = "set_emails")
        {
            if (string.IsNullOrEmpty(name))
            {
                name = ServicesCollection.Current.Resolve <CookiesService>().GetCookie(cookieName);
            }

            string tempFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.json");

            _blobStorageService.DownloadFile(name, tempFilePath, "emails");
            string fileContent = new FileFacade().ReadAllText(tempFilePath);
            var    email       = new JsonSerializer().Deserialize <Email>(fileContent);

            return(email);
        }
コード例 #11
0
        public void TrimEmptyLinesFromEndOfFile(string filePath, Func <string, bool> isLineEmpty)
        {
            string[] lines    = FileFacade.ReadAllLines(filePath);
            int      maxIndex = lines.Count();

            for (int i = lines.Count() - 1; i > 0; i--)
            {
                if (!isLineEmpty(lines[i]))
                {
                    break;
                }
                maxIndex--;
            }

            FileFacade.WriteAllLines(filePath, lines.Take(maxIndex));
        }
コード例 #12
0
        /// <summary>
        /// Adds a file to the cabinet.
        /// </summary>
        /// <param name="fileFacade">The file facade of the file to add.</param>
        public void AddFile(FileFacade fileFacade)
        {
            MsiInterop.MSIFILEHASHINFO hashInterop = new MsiInterop.MSIFILEHASHINFO();

            if (null != fileFacade.Hash)
            {
                hashInterop.FileHashInfoSize = 20;
                hashInterop.Data0            = (int)fileFacade.Hash[2];
                hashInterop.Data1            = (int)fileFacade.Hash[3];
                hashInterop.Data2            = (int)fileFacade.Hash[4];
                hashInterop.Data3            = (int)fileFacade.Hash[5];

                this.AddFile(fileFacade.WixFile.Source, fileFacade.File.File, hashInterop);
            }
            else
            {
                this.AddFile(fileFacade.WixFile.Source, fileFacade.File.File);
            }
        }
コード例 #13
0
        public void Setup()
        {
            _mockDataContext = new Mock <DataContext>();
            _mockDocumentDb  = new Mock <IDocumentDbRepository <UploadTransaction> >();
            _mockBlobManager = new Mock <IBlobManager>();

            _facade = new FileFacade(_mockDataContext.Object, _mockDocumentDb.Object, _mockBlobManager.Object);

            InitializeMockDataContext(_mockDataContext);

            InitializeMockDocumentDb(_mockDocumentDb);
            InitializeMockBlobManager(_mockBlobManager);

            var claim = new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
                                  _userId.ToString());

            Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                claim
            }));
        }
コード例 #14
0
 public async Task <ProcessFileResultModel> OmitAndIgnoreFormatValidation(ProcessFileModel fileModel)
 {
     try
     {
         FileFacade fileFacede = new FileFacade(_fileValidators, _fileFormatValidators, _businessRuleValidators);
         return(await fileFacede.OmitAndIgnoreFormatValidation <Shipment>(fileModel.FilePaths[0]).ContinueWith((resultTask) =>
         {
             var fileResults = new List <FileResult>();
             fileResults.Add(resultTask.Result);
             return new ProcessFileResultModel {
                 Message = "File processing successful", FileResults = fileResults.ToArray()
             };
         }));
     }
     catch
     {
         //ToDo: Proper logging at business logic level
         return(new ProcessFileResultModel {
             Message = "Error in processing file/s!"
         });
     }
 }
コード例 #15
0
ファイル: FileBuilder.cs プロジェクト: davoodkosari/Zibasazi
        private FileType DetectFileType()
        {
            if (this.Id == Guid.Empty)
            {
                return(FileType.Unkown);
            }
            var file = new FileFacade().Get(this.Id);

            if (file == null)
            {
                return(FileType.Unkown);
            }
            if (file.Extension.ToLower().Contains("swf"))
            {
                return(FileType.SWF);
            }
            var imageType = new[] { "jpg", "jpeg", "gif", "png" };

            if (imageType.Any(type => file.Extension.ToLower().Contains(type)))
            {
                return(FileType.Image);
            }
            return(FileType.Unkown);
        }
コード例 #16
0
ファイル: BindDatabaseCommand.cs プロジェクト: sgtatham/Core
        public IBindResult Execute()
        {
            if (!this.Intermediate.HasLevel(Data.IntermediateLevels.Linked) && !this.Intermediate.HasLevel(Data.IntermediateLevels.Resolved))
            {
                this.Messaging.Write(ErrorMessages.IntermediatesMustBeResolved(this.Intermediate.Id));
            }

            var section = this.Intermediate.Sections.Single();

            var fileTransfers = new List <IFileTransfer>();
            var trackedFiles  = new List <ITrackedFile>();

            var containsMergeModules = false;

            // If there are any fields to resolve later, create the cache to populate during bind.
            var variableCache = this.DelayedFields.Any() ? new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase) : null;

            // Load standard tables, authored custom tables, and extension custom tables.
            TableDefinitionCollection tableDefinitions;
            {
                var command = new LoadTableDefinitionsCommand(this.Messaging, section, this.BackendExtensions);
                command.Execute();

                tableDefinitions = command.TableDefinitions;
            }

            // Process the summary information table before the other tables.
            bool   compressed;
            bool   longNames;
            int    installerVersion;
            string modularizationSuffix;

            {
                var command = new BindSummaryInfoCommand(section);
                command.Execute();

                compressed           = command.Compressed;
                longNames            = command.LongNames;
                installerVersion     = command.InstallerVersion;
                modularizationSuffix = command.ModularizationSuffix;
            }

            // Add binder variables for all properties.
            if (SectionType.Product == section.Type || variableCache != null)
            {
                foreach (var propertyRow in section.Symbols.OfType <PropertySymbol>())
                {
                    // Set the ProductCode if it is to be generated.
                    if ("ProductCode".Equals(propertyRow.Id.Id, StringComparison.Ordinal) && "*".Equals(propertyRow.Value, StringComparison.Ordinal))
                    {
                        propertyRow.Value = Common.GenerateGuid();

#if TODO_PATCHING // Is this still necessary?
                        // Update the target ProductCode in any instance transforms.
                        foreach (SubStorage subStorage in this.Output.SubStorages)
                        {
                            Output subStorageOutput = subStorage.Data;
                            if (OutputType.Transform != subStorageOutput.Type)
                            {
                                continue;
                            }

                            Table instanceSummaryInformationTable = subStorageOutput.Tables["_SummaryInformation"];
                            foreach (Row row in instanceSummaryInformationTable.Rows)
                            {
                                if ((int)SummaryInformation.Transform.ProductCodes == row.FieldAsInteger(0))
                                {
                                    row[1] = row.FieldAsString(1).Replace("*", propertyRow.Value);
                                    break;
                                }
                            }
                        }
#endif
                    }

                    // Add the property name and value to the variableCache.
                    if (variableCache != null)
                    {
                        var key = String.Concat("property.", propertyRow.Id.Id);
                        variableCache[key] = propertyRow.Value;
                    }
                }
            }

            // Sequence all the actions.
            {
                var command = new SequenceActionsCommand(this.Messaging, section);
                command.Execute();
            }

            {
                var command = new CreateSpecialPropertiesCommand(section);
                command.Execute();
            }

#if TODO_PATCHING
            ////if (OutputType.Patch == this.Output.Type)
            ////{
            ////    foreach (SubStorage substorage in this.Output.SubStorages)
            ////    {
            ////        Output transform = substorage.Data;

            ////        ResolveFieldsCommand command = new ResolveFieldsCommand();
            ////        command.Tables = transform.Tables;
            ////        command.FilesWithEmbeddedFiles = filesWithEmbeddedFiles;
            ////        command.FileManagerCore = this.FileManagerCore;
            ////        command.FileManagers = this.FileManagers;
            ////        command.SupportDelayedResolution = false;
            ////        command.TempFilesLocation = this.TempFilesLocation;
            ////        command.WixVariableResolver = this.WixVariableResolver;
            ////        command.Execute();

            ////        this.MergeUnrealTables(transform.Tables);
            ////    }
            ////}
#endif

            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            this.Intermediate.UpdateLevel(Data.WindowsInstaller.IntermediateLevels.FullyBound);
            this.Messaging.Write(VerboseMessages.UpdatingFileInformation());

            // Extract files that come from binary .wixlibs and WixExtensions (this does not extract files from merge modules).
            {
                var command = new ExtractEmbeddedFilesCommand(this.BackendHelper, this.ExpectedEmbeddedFiles);
                command.Execute();

                trackedFiles.AddRange(command.TrackedFiles);
            }

            // This must occur after all variables and source paths have been resolved.
            List <FileFacade> fileFacades;
            if (SectionType.Patch == section.Type)
            {
                var command = new GetFileFacadesFromTransforms(this.Messaging, this.FileSystemManager, this.SubStorages);
                command.Execute();

                fileFacades = command.FileFacades;
            }
            else
            {
                var command = new GetFileFacadesCommand(section);
                command.Execute();

                fileFacades = command.FileFacades;
            }

            // Retrieve file information from merge modules.
            if (SectionType.Product == section.Type)
            {
                var wixMergeSymbols = section.Symbols.OfType <WixMergeSymbol>().ToList();

                if (wixMergeSymbols.Any())
                {
                    containsMergeModules = true;

                    var command = new ExtractMergeModuleFilesCommand(this.Messaging, wixMergeSymbols, fileFacades, installerVersion, this.IntermediateFolder, this.SuppressLayout);
                    command.Execute();

                    fileFacades.AddRange(command.MergeModulesFileFacades);
                }
            }

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            // Gather information about files that do not come from merge modules.
            {
                var command = new UpdateFileFacadesCommand(this.Messaging, section, fileFacades, fileFacades.Where(f => !f.FromModule), variableCache, overwriteHash: true);
                command.Execute();
            }

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            // Now that the variable cache is populated, resolve any delayed fields.
            if (this.DelayedFields.Any())
            {
                var command = new ResolveDelayedFieldsCommand(this.Messaging, this.DelayedFields, variableCache);
                command.Execute();
            }

#if TODO_FINISH_UPDATE // use symbols instead of rows
            // Extended binder extensions can be called now that fields are resolved.
            {
                Table updatedFiles = this.Output.EnsureTable(this.TableDefinitions["WixBindUpdatedFiles"]);

                foreach (IBinderExtension extension in this.Extensions)
                {
                    extension.AfterResolvedFields(this.Output);
                }

                List <FileFacade> updatedFileFacades = new List <FileFacade>();

                foreach (Row updatedFile in updatedFiles.Rows)
                {
                    string updatedId = updatedFile.FieldAsString(0);

                    FileFacade updatedFacade = fileFacades.First(f => f.File.File.Equals(updatedId));

                    updatedFileFacades.Add(updatedFacade);
                }

                if (updatedFileFacades.Any())
                {
                    UpdateFileFacadesCommand command = new UpdateFileFacadesCommand(this.Messaging, section, fileFacades, updateFileFacades, variableCache, overwriteHash: false);
                    //command.FileFacades = fileFacades;
                    //command.UpdateFileFacades = updatedFileFacades;
                    //command.ModularizationGuid = modularizationGuid;
                    //command.Output = this.Output;
                    //command.OverwriteHash = true;
                    //command.TableDefinitions = this.TableDefinitions;
                    //command.VariableCache = variableCache;
                    command.Execute();
                }
            }
#endif

            // Set generated component guids.
            {
                var command = new CalculateComponentGuids(this.Messaging, this.BackendHelper, this.PathResolver, section);
                command.Execute();
            }

            {
                var command = new ValidateComponentGuidsCommand(this.Messaging, section);
                command.Execute();
            }

            // Add missing CreateFolder symbols to null-keypath components.
            {
                var command = new AddCreateFoldersCommand(section);
                command.Execute();
            }

            // Update symbols that reference text files on disk.
            {
                var command = new UpdateFromTextFilesCommand(this.Messaging, section);
                command.Execute();
            }

            // Assign files to media and update file sequences.
            Dictionary <MediaSymbol, IEnumerable <FileFacade> > filesByCabinetMedia;
            IEnumerable <FileFacade> uncompressedFiles;
            {
                var order = new OptimizeFileFacadesOrderCommand(fileFacades);
                order.Execute();

                fileFacades = order.FileFacades;

                var assign = new AssignMediaCommand(section, this.Messaging, fileFacades, compressed);
                assign.Execute();

                filesByCabinetMedia = assign.FileFacadesByCabinetMedia;
                uncompressedFiles   = assign.UncompressedFileFacades;

                var update = new UpdateMediaSequencesCommand(section, fileFacades);
                update.Execute();
            }

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            // Time to create the output object. Try to put as much above here as possible, updating the IR is better.
            WindowsInstallerData output;
            {
                var command = new CreateOutputFromIRCommand(this.Messaging, section, tableDefinitions, this.BackendExtensions, this.WindowsInstallerBackendHelper);
                command.Execute();

                output = command.Output;
            }

            IEnumerable <string> suppressedTableNames = null;
            if (output.Type == OutputType.Module)
            {
                // Modularize identifiers.
                var modularize = new ModularizeCommand(output, modularizationSuffix, section.Symbols.OfType <WixSuppressModularizationSymbol>());
                modularize.Execute();

                // Ensure all sequence tables in place because, mergemod.dll requires them.
                var unsuppress = new AddBackSuppressedSequenceTablesCommand(output, tableDefinitions);
                suppressedTableNames = unsuppress.Execute();
            }
            else if (output.Type == OutputType.Patch)
            {
                foreach (var storage in this.SubStorages)
                {
                    output.SubStorages.Add(storage);
                }
            }

            // Stop processing if an error previously occurred.
            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            // Ensure the intermediate folder is created since delta patches will be
            // created there.
            Directory.CreateDirectory(this.IntermediateFolder);

            if (SectionType.Patch == section.Type && this.DeltaBinaryPatch)
            {
                var command = new CreateDeltaPatchesCommand(fileFacades, this.IntermediateFolder, section.Symbols.OfType <WixPatchIdSymbol>().FirstOrDefault());
                command.Execute();
            }

            // create cabinet files and process uncompressed files
            var layoutDirectory = Path.GetDirectoryName(this.OutputPath);
            if (!this.SuppressLayout || OutputType.Module == output.Type)
            {
                this.Messaging.Write(VerboseMessages.CreatingCabinetFiles());

                var mediaTemplate = section.Symbols.OfType <WixMediaTemplateSymbol>().FirstOrDefault();

                var command = new CreateCabinetsCommand(this.ServiceProvider, this.BackendHelper, mediaTemplate);
                command.CabbingThreadCount      = this.CabbingThreadCount;
                command.CabCachePath            = this.CabCachePath;
                command.DefaultCompressionLevel = this.DefaultCompressionLevel;
                command.Output               = output;
                command.Messaging            = this.Messaging;
                command.BackendExtensions    = this.BackendExtensions;
                command.LayoutDirectory      = layoutDirectory;
                command.Compressed           = compressed;
                command.ModularizationSuffix = modularizationSuffix;
                command.FileFacadesByCabinet = filesByCabinetMedia;
                command.ResolveMedia         = this.ResolveMedia;
                command.TableDefinitions     = tableDefinitions;
                command.IntermediateFolder   = this.IntermediateFolder;
                command.Execute();

                fileTransfers.AddRange(command.FileTransfers);
                trackedFiles.AddRange(command.TrackedFiles);
            }

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            // We can create instance transforms since Component Guids and Outputs are created.
            if (output.Type == OutputType.Product)
            {
                var command = new CreateInstanceTransformsCommand(section, output, tableDefinitions, this.BackendHelper);
                command.Execute();
            }
            else if (output.Type == OutputType.Patch)
            {
                // Copy output data back into the transforms.
                var command = new UpdateTransformsWithFileFacades(this.Messaging, output, this.SubStorages, tableDefinitions, fileFacades);
                command.Execute();
            }

            // Generate database file.
            this.Messaging.Write(VerboseMessages.GeneratingDatabase());

            {
                var trackMsi = this.BackendHelper.TrackFile(this.OutputPath, TrackedFileType.Final);
                trackedFiles.Add(trackMsi);

                var command = new GenerateDatabaseCommand(this.Messaging, this.BackendHelper, this.FileSystemManager, output, trackMsi.Path, tableDefinitions, this.IntermediateFolder, this.Codepage, keepAddedColumns: false, this.SuppressAddingValidationRows, useSubdirectory: false);
                command.Execute();

                trackedFiles.AddRange(command.GeneratedTemporaryFiles);
            }

            // Stop processing if an error previously occurred.
            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

            // Merge modules.
            if (containsMergeModules)
            {
                this.Messaging.Write(VerboseMessages.MergingModules());

                var command = new MergeModulesCommand(this.Messaging, fileFacades, section, suppressedTableNames, this.OutputPath, this.IntermediateFolder);
                command.Execute();
            }

            if (this.Messaging.EncounteredError)
            {
                return(null);
            }

#if TODO_FINISH_VALIDATION
            // Validate the output if there is an MSI validator.
            if (null != this.Validator)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                // set the output file for source line information
                this.Validator.Output = this.Output;

                Messaging.Instance.Write(WixVerboses.ValidatingDatabase());

                this.Validator.Validate(this.OutputPath);

                stopwatch.Stop();
                Messaging.Instance.Write(WixVerboses.ValidatedDatabase(stopwatch.ElapsedMilliseconds));

                // Stop processing if an error occurred.
                if (Messaging.Instance.EncounteredError)
                {
                    return;
                }
            }
#endif

            // Process uncompressed files.
            if (!this.Messaging.EncounteredError && !this.SuppressLayout && uncompressedFiles.Any())
            {
                var command = new ProcessUncompressedFilesCommand(section, this.BackendHelper, this.PathResolver);
                command.Compressed       = compressed;
                command.FileFacades      = uncompressedFiles;
                command.LayoutDirectory  = layoutDirectory;
                command.LongNamesInImage = longNames;
                command.ResolveMedia     = this.ResolveMedia;
                command.DatabasePath     = this.OutputPath;
                command.Execute();

                fileTransfers.AddRange(command.FileTransfers);
                trackedFiles.AddRange(command.TrackedFiles);
            }

            // TODO: this is not sufficient to collect all Input files (for example, it misses Binary and Icon tables).
            trackedFiles.AddRange(fileFacades.Select(f => this.BackendHelper.TrackFile(f.SourcePath, TrackedFileType.Input, f.SourceLineNumber)));

            var result = this.ServiceProvider.GetService <IBindResult>();
            result.FileTransfers = fileTransfers;
            result.TrackedFiles  = trackedFiles;
            result.Wixout        = this.CreateWixout(trackedFiles, this.Intermediate, output);

            return(result);
        }
コード例 #17
0
        private void UpdateFileFacade(FileFacade file)
        {
            var assemblyNameTuples = new Dictionary <string, MsiAssemblyNameTuple>();

            foreach (var assemblyTuple in this.Section.Tuples.OfType <MsiAssemblyNameTuple>())
            {
                assemblyNameTuples.Add(assemblyTuple.Component_ + "/" + assemblyTuple.Name, assemblyTuple);
            }

            FileInfo fileInfo = null;

            try
            {
                fileInfo = new FileInfo(file.WixFile.Source.Path);
            }
            catch (ArgumentException)
            {
                this.Messaging.Write(ErrorMessages.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source.Path));
                return;
            }
            catch (PathTooLongException)
            {
                this.Messaging.Write(ErrorMessages.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source.Path));
                return;
            }
            catch (NotSupportedException)
            {
                this.Messaging.Write(ErrorMessages.InvalidFileName(file.File.SourceLineNumbers, file.WixFile.Source.Path));
                return;
            }

            if (!fileInfo.Exists)
            {
                this.Messaging.Write(ErrorMessages.CannotFindFile(file.File.SourceLineNumbers, file.File.File, file.File.LongFileName, file.WixFile.Source.Path));
                return;
            }

            using (FileStream fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                if (Int32.MaxValue < fileStream.Length)
                {
                    throw new WixException(ErrorMessages.FileTooLarge(file.File.SourceLineNumbers, file.WixFile.Source.Path));
                }

                file.File.FileSize = Convert.ToInt32(fileStream.Length, CultureInfo.InvariantCulture);
            }

            string version  = null;
            string language = null;

            try
            {
                Installer.GetFileVersion(fileInfo.FullName, out version, out language);
            }
            catch (Win32Exception e)
            {
                if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND
                {
                    throw new WixException(ErrorMessages.FileNotFound(file.File.SourceLineNumbers, fileInfo.FullName));
                }
                else
                {
                    throw new WixException(ErrorMessages.Win32Exception(e.NativeErrorCode, e.Message));
                }
            }

            // If there is no version, it is assumed there is no language because it won't matter in the versioning of the install.
            if (String.IsNullOrEmpty(version)) // unversioned files have their hashes added to the MsiFileHash table
            {
                if (!this.OverwriteHash)
                {
                    // not overwriting hash, so don't do the rest of these options.
                }
                else if (null != file.File.Version)
                {
                    // Search all of the file rows available to see if the specified version is actually a companion file. Yes, this looks
                    // very expensive and you're probably thinking it would be better to create an index of some sort to do an O(1) look up.
                    // That's a reasonable thought but companion file usage is usually pretty rare so we'd be doing something expensive (indexing
                    // all the file rows) for a relatively uncommon situation. Let's not do that.
                    //
                    // Also, if we do not find a matching file identifier then the user provided a default version and is providing a version
                    // for unversioned file. That's allowed but generally a dangerous thing to do so let's point that out to the user.
                    if (!this.FileFacades.Any(r => file.File.Version.Equals(r.File.File, StringComparison.Ordinal)))
                    {
                        this.Messaging.Write(WarningMessages.DefaultVersionUsedForUnversionedFile(file.File.SourceLineNumbers, file.File.Version, file.File.File));
                    }
                }
                else
                {
                    if (null != file.File.Language)
                    {
                        this.Messaging.Write(WarningMessages.DefaultLanguageUsedForUnversionedFile(file.File.SourceLineNumbers, file.File.Language, file.File.File));
                    }

                    int[] hash;
                    try
                    {
                        Installer.GetFileHash(fileInfo.FullName, 0, out hash);
                    }
                    catch (Win32Exception e)
                    {
                        if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND
                        {
                            throw new WixException(ErrorMessages.FileNotFound(file.File.SourceLineNumbers, fileInfo.FullName));
                        }
                        else
                        {
                            throw new WixException(ErrorMessages.Win32Exception(e.NativeErrorCode, fileInfo.FullName, e.Message));
                        }
                    }

                    if (null == file.Hash)
                    {
                        file.Hash = new MsiFileHashTuple(file.File.SourceLineNumbers, file.File.Id);
                        this.Section.Tuples.Add(file.Hash);
                    }

                    file.Hash.File_     = file.File.File;
                    file.Hash.Options   = 0;
                    file.Hash.HashPart1 = hash[0];
                    file.Hash.HashPart2 = hash[1];
                    file.Hash.HashPart3 = hash[2];
                    file.Hash.HashPart4 = hash[3];
                }
            }
            else // update the file row with the version and language information.
            {
                // If no version was provided by the user, use the version from the file itself.
                // This is the most common case.
                if (String.IsNullOrEmpty(file.File.Version))
                {
                    file.File.Version = version;
                }
                else if (!this.FileFacades.Any(r => file.File.Version.Equals(r.File.File, StringComparison.Ordinal))) // this looks expensive, but see explanation below.
                {
                    // The user provided a default version for the file row so we looked for a companion file (a file row with Id matching
                    // the version value). We didn't find it so, we will override the default version they provided with the actual
                    // version from the file itself. Now, I know it looks expensive to search through all the file rows trying to match
                    // on the Id. However, the alternative is to build a big index of all file rows to do look ups. Since this case
                    // where the file version is already present is rare (companion files are pretty uncommon), we'll do the more
                    // CPU intensive search to save on the memory intensive index that wouldn't be used much.
                    //
                    // Also note this case can occur when the file is being updated using the WixBindUpdatedFiles extension mechanism.
                    // That's typically even more rare than companion files so again, no index, just search.
                    file.File.Version = version;
                }

                if (!String.IsNullOrEmpty(file.File.Language) && String.IsNullOrEmpty(language))
                {
                    this.Messaging.Write(WarningMessages.DefaultLanguageUsedForVersionedFile(file.File.SourceLineNumbers, file.File.Language, file.File.File));
                }
                else // override the default provided by the user (usually nothing) with the actual language from the file itself.
                {
                    file.File.Language = language;
                }

                // Populate the binder variables for this file information if requested.
                if (null != this.VariableCache)
                {
                    if (!String.IsNullOrEmpty(file.File.Version))
                    {
                        var key = String.Format(CultureInfo.InvariantCulture, "fileversion.{0}", file.File.File);
                        this.VariableCache[key] = file.File.Version;
                    }

                    if (!String.IsNullOrEmpty(file.File.Language))
                    {
                        var key = String.Format(CultureInfo.InvariantCulture, "filelanguage.{0}", file.File.File);
                        this.VariableCache[key] = file.File.Language;
                    }
                }
            }

            // If this is a CLR assembly, load the assembly and get the assembly name information
            if (FileAssemblyType.DotNetAssembly == file.WixFile.AssemblyType)
            {
                bool targetNetfx1       = false;
                var  assemblyNameValues = new Dictionary <string, string>();

                Guid referenceIdentityGuid = ClrInterop.ReferenceIdentityGuid;
                var  result = ClrInterop.GetAssemblyIdentityFromFile(fileInfo.FullName, ref referenceIdentityGuid, out var referenceIdentity);
                if (0 == result && null != referenceIdentity)
                {
                    var imageRuntimeVersion = referenceIdentity.GetAttribute(null, "ImageRuntimeVersion");
                    if (null != imageRuntimeVersion)
                    {
                        targetNetfx1 = imageRuntimeVersion.StartsWith("v1", StringComparison.OrdinalIgnoreCase);
                    }

                    string culture = referenceIdentity.GetAttribute(null, "Culture") ?? "neutral";
                    assemblyNameValues.Add("Culture", culture);

                    string name = referenceIdentity.GetAttribute(null, "Name");
                    if (null != name)
                    {
                        assemblyNameValues.Add("Name", name);
                    }

                    string processorArchitecture = referenceIdentity.GetAttribute(null, "ProcessorArchitecture");
                    if (null != processorArchitecture)
                    {
                        assemblyNameValues.Add("ProcessorArchitecture", processorArchitecture);
                    }

                    string publicKeyToken = referenceIdentity.GetAttribute(null, "PublicKeyToken");
                    if (null != publicKeyToken)
                    {
                        bool publicKeyIsNeutral = (String.Equals(publicKeyToken, "neutral", StringComparison.OrdinalIgnoreCase));

                        // Managed code expects "null" instead of "neutral", and
                        // this won't be installed to the GAC since it's not signed anyway.
                        assemblyNameValues.Add("publicKeyToken", publicKeyIsNeutral ? "null" : publicKeyToken.ToUpperInvariant());
                        assemblyNameValues.Add("publicKeyTokenPreservedCase", publicKeyIsNeutral ? "null" : publicKeyToken);
                    }
                    else if (file.WixFile.File_AssemblyApplication == null)
                    {
                        throw new WixException(ErrorMessages.GacAssemblyNoStrongName(file.File.SourceLineNumbers, fileInfo.FullName, file.File.Component_));
                    }

                    string assemblyVersion = referenceIdentity.GetAttribute(null, "Version");
                    if (null != version)
                    {
                        assemblyNameValues.Add("Version", assemblyVersion);
                    }
                }
                else
                {
                    this.Messaging.Write(ErrorMessages.InvalidAssemblyFile(file.File.SourceLineNumbers, fileInfo.FullName, String.Format(CultureInfo.InvariantCulture, "HRESULT: 0x{0:x8}", result)));
                    return;
                }

                if (assemblyNameValues.TryGetValue("name", out var value))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "name", value);
                }

                if (!String.IsNullOrEmpty(version))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "fileVersion", version);
                }

                if (assemblyNameValues.ContainsKey("version"))
                {
                    string assemblyVersion = assemblyNameValues["version"];

                    if (!targetNetfx1)
                    {
                        // There is a bug in v1 fusion that requires the assembly's "version" attribute
                        // to be equal to or longer than the "fileVersion" in length when its present;
                        // the workaround is to prepend zeroes to the last version number in the assembly
                        // version.
                        if (null != version && version.Length > assemblyVersion.Length)
                        {
                            string   padding = new string('0', version.Length - assemblyVersion.Length);
                            string[] assemblyVersionNumbers = assemblyVersion.Split('.');

                            if (assemblyVersionNumbers.Length > 0)
                            {
                                assemblyVersionNumbers[assemblyVersionNumbers.Length - 1] = String.Concat(padding, assemblyVersionNumbers[assemblyVersionNumbers.Length - 1]);
                                assemblyVersion = String.Join(".", assemblyVersionNumbers);
                            }
                        }
                    }

                    this.SetMsiAssemblyName(assemblyNameTuples, file, "version", assemblyVersion);
                }

                if (assemblyNameValues.ContainsKey("culture"))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "culture", assemblyNameValues["culture"]);
                }

                if (assemblyNameValues.ContainsKey("publicKeyToken"))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "publicKeyToken", assemblyNameValues["publicKeyToken"]);
                }

                if (!String.IsNullOrEmpty(file.WixFile.ProcessorArchitecture))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "processorArchitecture", file.WixFile.ProcessorArchitecture);
                }

                if (assemblyNameValues.ContainsKey("processorArchitecture"))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "processorArchitecture", assemblyNameValues["processorArchitecture"]);
                }

                // add the assembly name to the information cache
                if (null != this.VariableCache)
                {
                    string fileId       = file.File.File;
                    string key          = String.Concat("assemblyfullname.", fileId);
                    string assemblyName = String.Concat(assemblyNameValues["name"], ", version=", assemblyNameValues["version"], ", culture=", assemblyNameValues["culture"], ", publicKeyToken=", String.IsNullOrEmpty(assemblyNameValues["publicKeyToken"]) ? "null" : assemblyNameValues["publicKeyToken"]);
                    if (assemblyNameValues.ContainsKey("processorArchitecture"))
                    {
                        assemblyName = String.Concat(assemblyName, ", processorArchitecture=", assemblyNameValues["processorArchitecture"]);
                    }

                    this.VariableCache[key] = assemblyName;

                    // Add entries with the preserved case publicKeyToken
                    string pcAssemblyNameKey = String.Concat("assemblyfullnamepreservedcase.", fileId);
                    this.VariableCache[pcAssemblyNameKey] = (assemblyNameValues["publicKeyToken"] == assemblyNameValues["publicKeyTokenPreservedCase"]) ? assemblyName : assemblyName.Replace(assemblyNameValues["publicKeyToken"], assemblyNameValues["publicKeyTokenPreservedCase"]);

                    string pcPublicKeyTokenKey = String.Concat("assemblypublickeytokenpreservedcase.", fileId);
                    this.VariableCache[pcPublicKeyTokenKey] = assemblyNameValues["publicKeyTokenPreservedCase"];
                }
            }
            else if (FileAssemblyType.Win32Assembly == file.WixFile.AssemblyType)
            {
                // TODO: Consider passing in the this.FileFacades as an indexed collection instead of searching through
                // all files like this. Even though this is a rare case it looks like we might be able to index the
                // file earlier.
                FileFacade fileManifest = this.FileFacades.SingleOrDefault(r => r.File.File.Equals(file.WixFile.File_AssemblyManifest, StringComparison.Ordinal));
                if (null == fileManifest)
                {
                    this.Messaging.Write(ErrorMessages.MissingManifestForWin32Assembly(file.File.SourceLineNumbers, file.File.File, file.WixFile.File_AssemblyManifest));
                }

                string win32Type    = null;
                string win32Name    = null;
                string win32Version = null;
                string win32ProcessorArchitecture = null;
                string win32PublicKeyToken        = null;

                // loading the dom is expensive we want more performant APIs than the DOM
                // Navigator is cheaper than dom.  Perhaps there is a cheaper API still.
                try
                {
                    XPathDocument  doc = new XPathDocument(fileManifest.WixFile.Source.Path);
                    XPathNavigator nav = doc.CreateNavigator();
                    nav.MoveToRoot();

                    // this assumes a particular schema for a win32 manifest and does not
                    // provide error checking if the file does not conform to schema.
                    // The fallback case here is that nothing is added to the MsiAssemblyName
                    // table for an out of tolerance Win32 manifest.  Perhaps warnings needed.
                    if (nav.MoveToFirstChild())
                    {
                        while (nav.NodeType != XPathNodeType.Element || nav.Name != "assembly")
                        {
                            nav.MoveToNext();
                        }

                        if (nav.MoveToFirstChild())
                        {
                            bool hasNextSibling = true;
                            while (nav.NodeType != XPathNodeType.Element || nav.Name != "assemblyIdentity" && hasNextSibling)
                            {
                                hasNextSibling = nav.MoveToNext();
                            }
                            if (!hasNextSibling)
                            {
                                this.Messaging.Write(ErrorMessages.InvalidManifestContent(file.File.SourceLineNumbers, fileManifest.WixFile.Source.Path));
                                return;
                            }

                            if (nav.MoveToAttribute("type", String.Empty))
                            {
                                win32Type = nav.Value;
                                nav.MoveToParent();
                            }

                            if (nav.MoveToAttribute("name", String.Empty))
                            {
                                win32Name = nav.Value;
                                nav.MoveToParent();
                            }

                            if (nav.MoveToAttribute("version", String.Empty))
                            {
                                win32Version = nav.Value;
                                nav.MoveToParent();
                            }

                            if (nav.MoveToAttribute("processorArchitecture", String.Empty))
                            {
                                win32ProcessorArchitecture = nav.Value;
                                nav.MoveToParent();
                            }

                            if (nav.MoveToAttribute("publicKeyToken", String.Empty))
                            {
                                win32PublicKeyToken = nav.Value;
                                nav.MoveToParent();
                            }
                        }
                    }
                }
                catch (FileNotFoundException fe)
                {
                    this.Messaging.Write(ErrorMessages.FileNotFound(new SourceLineNumber(fileManifest.WixFile.Source.Path), fe.FileName, "AssemblyManifest"));
                }
                catch (XmlException xe)
                {
                    this.Messaging.Write(ErrorMessages.InvalidXml(new SourceLineNumber(fileManifest.WixFile.Source.Path), "manifest", xe.Message));
                }

                if (!String.IsNullOrEmpty(win32Name))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "name", win32Name);
                }

                if (!String.IsNullOrEmpty(win32Version))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "version", win32Version);
                }

                if (!String.IsNullOrEmpty(win32Type))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "type", win32Type);
                }

                if (!String.IsNullOrEmpty(win32ProcessorArchitecture))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "processorArchitecture", win32ProcessorArchitecture);
                }

                if (!String.IsNullOrEmpty(win32PublicKeyToken))
                {
                    this.SetMsiAssemblyName(assemblyNameTuples, file, "publicKeyToken", win32PublicKeyToken);
                }
            }
        }
コード例 #18
0
        public void Execute()
        {
            var section = this.Intermediate.Sections.Single();

            var fileTransfers = new List <FileTransfer>();

            var containsMergeModules = false;
            var suppressedTableNames = new HashSet <string>();

            // If there are any fields to resolve later, create the cache to populate during bind.
            var variableCache = this.DelayedFields.Any() ? new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase) : null;

            // Process the summary information table before the other tables.
            bool   compressed;
            bool   longNames;
            int    installerVersion;
            string modularizationGuid;

            {
                var command = new BindSummaryInfoCommand(section);
                command.Execute();

                compressed         = command.Compressed;
                longNames          = command.LongNames;
                installerVersion   = command.InstallerVersion;
                modularizationGuid = command.ModularizationGuid;
            }

            // Add binder variables for all properties.
            if (SectionType.Product == section.Type || variableCache != null)
            {
                foreach (var propertyRow in section.Tuples.OfType <PropertyTuple>())
                {
                    // Set the ProductCode if it is to be generated.
                    if ("ProductCode".Equals(propertyRow.Property, StringComparison.Ordinal) && "*".Equals(propertyRow.Value, StringComparison.Ordinal))
                    {
                        propertyRow.Value = Common.GenerateGuid();

#if TODO_FIX_INSTANCE_TRANSFORM // Is this still necessary?
                        // Update the target ProductCode in any instance transforms.
                        foreach (SubStorage subStorage in this.Output.SubStorages)
                        {
                            Output subStorageOutput = subStorage.Data;
                            if (OutputType.Transform != subStorageOutput.Type)
                            {
                                continue;
                            }

                            Table instanceSummaryInformationTable = subStorageOutput.Tables["_SummaryInformation"];
                            foreach (Row row in instanceSummaryInformationTable.Rows)
                            {
                                if ((int)SummaryInformation.Transform.ProductCodes == row.FieldAsInteger(0))
                                {
                                    row[1] = row.FieldAsString(1).Replace("*", propertyRow.Value);
                                    break;
                                }
                            }
                        }
#endif
                    }

                    // Add the property name and value to the variableCache.
                    if (variableCache != null)
                    {
                        var key = String.Concat("property.", propertyRow.Property);
                        variableCache[key] = propertyRow.Value;
                    }
                }
            }

            // Sequence all the actions.
            {
                var command = new SequenceActionsCommand(section);
                command.Messaging = this.Messaging;
                command.Execute();
            }

            {
                var command = new CreateSpecialPropertiesCommand(section);
                command.Execute();
            }

#if TODO_FINISH_PATCH
            ////if (OutputType.Patch == this.Output.Type)
            ////{
            ////    foreach (SubStorage substorage in this.Output.SubStorages)
            ////    {
            ////        Output transform = substorage.Data;

            ////        ResolveFieldsCommand command = new ResolveFieldsCommand();
            ////        command.Tables = transform.Tables;
            ////        command.FilesWithEmbeddedFiles = filesWithEmbeddedFiles;
            ////        command.FileManagerCore = this.FileManagerCore;
            ////        command.FileManagers = this.FileManagers;
            ////        command.SupportDelayedResolution = false;
            ////        command.TempFilesLocation = this.TempFilesLocation;
            ////        command.WixVariableResolver = this.WixVariableResolver;
            ////        command.Execute();

            ////        this.MergeUnrealTables(transform.Tables);
            ////    }
            ////}
#endif

            if (this.Messaging.EncounteredError)
            {
                return;
            }

            this.Messaging.Write(VerboseMessages.UpdatingFileInformation());

            // This must occur after all variables and source paths have been resolved.
            List <FileFacade> fileFacades;
            {
                var command = new GetFileFacadesCommand(section);
                command.Execute();

                fileFacades = command.FileFacades;
            }

            // Extract files that come from binary .wixlibs and WixExtensions (this does not extract files from merge modules).
            {
                var command = new ExtractEmbeddedFilesCommand(this.ExpectedEmbeddedFiles);
                command.Execute();
            }

            // Gather information about files that do not come from merge modules.
            {
                var command = new UpdateFileFacadesCommand(this.Messaging, section);
                command.FileFacades       = fileFacades;
                command.UpdateFileFacades = fileFacades.Where(f => !f.FromModule);
                command.OverwriteHash     = true;
                command.TableDefinitions  = this.TableDefinitions;
                command.VariableCache     = variableCache;
                command.Execute();
            }

            // Now that the variable cache is populated, resolve any delayed fields.
            if (this.DelayedFields.Any())
            {
                var command = new ResolveDelayedFieldsCommand(this.Messaging, this.DelayedFields, variableCache);
                command.Execute();
            }

            // Set generated component guids.
            {
                var command = new CalculateComponentGuids(this.Messaging, section);
                command.Execute();
            }

            // Retrieve file information from merge modules.
            if (SectionType.Product == section.Type)
            {
                var wixMergeTuples = section.Tuples.OfType <WixMergeTuple>().ToList();

                if (wixMergeTuples.Any())
                {
                    containsMergeModules = true;

                    var command = new ExtractMergeModuleFilesCommand(this.Messaging, section, wixMergeTuples);
                    command.FileFacades            = fileFacades;
                    command.OutputInstallerVersion = installerVersion;
                    command.SuppressLayout         = this.SuppressLayout;
                    command.IntermediateFolder     = this.IntermediateFolder;
                    command.Execute();

                    fileFacades.AddRange(command.MergeModulesFileFacades);
                }
            }
#if TODO_FINISH_PATCH
            else if (OutputType.Patch == this.Output.Type)
            {
                // Merge transform data into the output object.
                IEnumerable <FileFacade> filesFromTransform = this.CopyFromTransformData(this.Output);

                fileFacades.AddRange(filesFromTransform);
            }
#endif

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return;
            }

            // Assign files to media.
            Dictionary <int, MediaTuple> assignedMediaRows;
            Dictionary <MediaTuple, IEnumerable <FileFacade> > filesByCabinetMedia;
            IEnumerable <FileFacade> uncompressedFiles;
            {
                var command = new AssignMediaCommand(section, this.Messaging);
                command.FileFacades     = fileFacades;
                command.FilesCompressed = compressed;
                command.Execute();

                assignedMediaRows   = command.MediaRows;
                filesByCabinetMedia = command.FileFacadesByCabinetMedia;
                uncompressedFiles   = command.UncompressedFileFacades;
            }

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return;
            }

            // Time to create the output object. Try to put as much above here as possible, updating the IR is better.
            Output output;
            {
                var command = new CreateOutputFromIRCommand(section, this.TableDefinitions, this.BackendExtensions);
                command.Execute();

                output = command.Output;
            }

            // Update file sequence.
            {
                var command = new UpdateMediaSequencesCommand(output, fileFacades, assignedMediaRows);
                command.Execute();
            }

            // Modularize identifiers.
            if (OutputType.Module == output.Type)
            {
                var command = new ModularizeCommand(output, modularizationGuid, section.Tuples.OfType <WixSuppressModularizationTuple>());
                command.Execute();
            }
            else // we can create instance transforms since Component Guids are set.
            {
#if TODO_FIX_INSTANCE_TRANSFORM
                this.CreateInstanceTransforms(this.Output);
#endif
            }

#if TODO_FINISH_UPDATE
            // Extended binder extensions can be called now that fields are resolved.
            {
                Table updatedFiles = this.Output.EnsureTable(this.TableDefinitions["WixBindUpdatedFiles"]);

                foreach (IBinderExtension extension in this.Extensions)
                {
                    extension.AfterResolvedFields(this.Output);
                }

                List <FileFacade> updatedFileFacades = new List <FileFacade>();

                foreach (Row updatedFile in updatedFiles.Rows)
                {
                    string updatedId = updatedFile.FieldAsString(0);

                    FileFacade updatedFacade = fileFacades.First(f => f.File.File.Equals(updatedId));

                    updatedFileFacades.Add(updatedFacade);
                }

                if (updatedFileFacades.Any())
                {
                    UpdateFileFacadesCommand command = new UpdateFileFacadesCommand();
                    command.FileFacades        = fileFacades;
                    command.UpdateFileFacades  = updatedFileFacades;
                    command.ModularizationGuid = modularizationGuid;
                    command.Output             = this.Output;
                    command.OverwriteHash      = true;
                    command.TableDefinitions   = this.TableDefinitions;
                    command.VariableCache      = variableCache;
                    command.Execute();
                }
            }
#endif

            // Stop processing if an error previously occurred.
            if (this.Messaging.EncounteredError)
            {
                return;
            }

            // Ensure the intermediate folder is created since delta patches will be
            // created there.
            Directory.CreateDirectory(this.IntermediateFolder);

            if (SectionType.Patch == section.Type && this.DeltaBinaryPatch)
            {
                var command = new CreateDeltaPatchesCommand(fileFacades, this.IntermediateFolder, section.Tuples.OfType <WixPatchIdTuple>().FirstOrDefault());
                command.Execute();
            }

            // create cabinet files and process uncompressed files
            var layoutDirectory = Path.GetDirectoryName(this.OutputPath);
            if (!this.SuppressLayout || OutputType.Module == output.Type)
            {
                this.Messaging.Write(VerboseMessages.CreatingCabinetFiles());

                var command = new CreateCabinetsCommand();
                command.CabbingThreadCount      = this.CabbingThreadCount;
                command.CabCachePath            = this.CabCachePath;
                command.DefaultCompressionLevel = this.DefaultCompressionLevel;
                command.Output            = output;
                command.Messaging         = this.Messaging;
                command.BackendExtensions = this.BackendExtensions;
                command.LayoutDirectory   = layoutDirectory;
                command.Compressed        = compressed;
                command.FileRowsByCabinet = filesByCabinetMedia;
                command.ResolveMedia      = this.ResolveMedia;
                command.TableDefinitions  = this.TableDefinitions;
                command.TempFilesLocation = this.IntermediateFolder;
                command.WixMediaTuples    = section.Tuples.OfType <WixMediaTuple>();
                command.Execute();

                fileTransfers.AddRange(command.FileTransfers);
            }

#if TODO_FINISH_PATCH
            if (OutputType.Patch == this.Output.Type)
            {
                // copy output data back into the transforms
                this.CopyToTransformData(this.Output);
            }
#endif

            this.ValidateComponentGuids(output);

            // stop processing if an error previously occurred
            if (this.Messaging.EncounteredError)
            {
                return;
            }

            // Generate database file.
            this.Messaging.Write(VerboseMessages.GeneratingDatabase());
            string tempDatabaseFile = Path.Combine(this.IntermediateFolder, Path.GetFileName(this.OutputPath));
            this.GenerateDatabase(output, tempDatabaseFile, false, false);

            if (FileTransfer.TryCreate(tempDatabaseFile, this.OutputPath, true, output.Type.ToString(), null, out var transfer)) // note where this database needs to move in the future
            {
                transfer.Built = true;
                fileTransfers.Add(transfer);
            }

            // Stop processing if an error previously occurred.
            if (this.Messaging.EncounteredError)
            {
                return;
            }

            // Merge modules.
            if (containsMergeModules)
            {
                this.Messaging.Write(VerboseMessages.MergingModules());

                // Add back possibly suppressed sequence tables since all sequence tables must be present
                // for the merge process to work. We'll drop the suppressed sequence tables again as
                // necessary.
                foreach (SequenceTable sequence in Enum.GetValues(typeof(SequenceTable)))
                {
                    var sequenceTableName = sequence.ToString();
                    var sequenceTable     = output.Tables[sequenceTableName];

                    if (null == sequenceTable)
                    {
                        sequenceTable = output.EnsureTable(this.TableDefinitions[sequenceTableName]);
                    }

                    if (0 == sequenceTable.Rows.Count)
                    {
                        suppressedTableNames.Add(sequenceTableName);
                    }
                }

                var command = new MergeModulesCommand();
                command.FileFacades          = fileFacades;
                command.Output               = output;
                command.OutputPath           = tempDatabaseFile;
                command.SuppressedTableNames = suppressedTableNames;
                command.Execute();
            }

            if (this.Messaging.EncounteredError)
            {
                return;
            }

#if TODO_FINISH_VALIDATION
            // Validate the output if there is an MSI validator.
            if (null != this.Validator)
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                // set the output file for source line information
                this.Validator.Output = this.Output;

                Messaging.Instance.Write(WixVerboses.ValidatingDatabase());

                this.Validator.Validate(tempDatabaseFile);

                stopwatch.Stop();
                Messaging.Instance.Write(WixVerboses.ValidatedDatabase(stopwatch.ElapsedMilliseconds));

                // Stop processing if an error occurred.
                if (Messaging.Instance.EncounteredError)
                {
                    return;
                }
            }
#endif

            // Process uncompressed files.
            if (!this.Messaging.EncounteredError && !this.SuppressLayout && uncompressedFiles.Any())
            {
                var command = new ProcessUncompressedFilesCommand(section);
                command.Compressed       = compressed;
                command.FileFacades      = uncompressedFiles;
                command.LayoutDirectory  = layoutDirectory;
                command.LongNamesInImage = longNames;
                command.ResolveMedia     = this.ResolveMedia;
                command.DatabasePath     = tempDatabaseFile;
                command.Execute();

                fileTransfers.AddRange(command.FileTransfers);
            }

            this.FileTransfers    = fileTransfers;
            this.ContentFilePaths = fileFacades.Select(r => r.WixFile.Source.Path).ToList();
            this.Pdb = new Pdb {
                Output = output
            };

            // TODO: Eventually this gets removed
            var intermediate = new Intermediate(this.Intermediate.Id, new[] { section }, this.Intermediate.Localizations.ToDictionary(l => l.Culture, StringComparer.OrdinalIgnoreCase), this.Intermediate.EmbedFilePaths);
            intermediate.Save(Path.ChangeExtension(this.OutputPath, "wir"));
        }
コード例 #19
0
ファイル: FilesController.cs プロジェクト: adamjez/CVaS
 public FilesController(ILogger<FilesController> logger, FileFacade fileFacade, RunFacade runFacade, IFileStorage fileStorage)
 {
     _logger = logger;
     _fileFacade = fileFacade;
     _fileStorage = fileStorage;
 }
コード例 #20
0
        private bool CreateFacadesForMergeModuleFiles(WixMergeSymbol wixMergeRow, List <FileFacade> mergeModulesFileFacades, Dictionary <string, FileFacade> indexedFileFacades)
        {
            var containsFiles = false;

            try
            {
                // read the module's File table to get its FileMediaInformation entries and gather any other information needed from the module.
                using (var db = new Database(wixMergeRow.SourceFile, OpenDatabase.ReadOnly))
                {
                    if (db.TableExists("File") && db.TableExists("Component"))
                    {
                        var uniqueModuleFileIdentifiers = new Dictionary <string, FileFacade>(StringComparer.OrdinalIgnoreCase);

                        using (var view = db.OpenExecuteView("SELECT `File`, `Directory_` FROM `File`, `Component` WHERE `Component_`=`Component`"))
                        {
                            // add each file row from the merge module into the file row collection (check for errors along the way)
                            foreach (var record in view.Records)
                            {
                                // NOTE: this is very tricky - the merge module file rows are not added to the
                                // file table because they should not be created via idt import.  Instead, these
                                // rows are created by merging in the actual modules.
                                var fileSymbol = new FileSymbol(wixMergeRow.SourceLineNumbers, new Identifier(AccessModifier.Private, record[1]));
                                fileSymbol.Attributes   = wixMergeRow.FileAttributes;
                                fileSymbol.DirectoryRef = record[2];
                                fileSymbol.DiskId       = wixMergeRow.DiskId;
                                fileSymbol.Source       = new IntermediateFieldPathValue {
                                    Path = Path.Combine(this.IntermediateFolder, wixMergeRow.Id.Id, record[1])
                                };

                                var mergeModuleFileFacade = new FileFacade(true, fileSymbol);

                                // If case-sensitive collision with another merge module or a user-authored file identifier.
                                if (indexedFileFacades.TryGetValue(mergeModuleFileFacade.Id, out var collidingFacade))
                                {
                                    this.Messaging.Write(ErrorMessages.DuplicateModuleFileIdentifier(wixMergeRow.SourceLineNumbers, wixMergeRow.Id.Id, collidingFacade.Id));
                                }
                                else if (uniqueModuleFileIdentifiers.TryGetValue(mergeModuleFileFacade.Id, out collidingFacade)) // case-insensitive collision with another file identifier in the same merge module
                                {
                                    this.Messaging.Write(ErrorMessages.DuplicateModuleCaseInsensitiveFileIdentifier(wixMergeRow.SourceLineNumbers, wixMergeRow.Id.Id, mergeModuleFileFacade.Id, collidingFacade.Id));
                                }
                                else // no collision
                                {
                                    mergeModulesFileFacades.Add(mergeModuleFileFacade);

                                    // Keep updating the indexes as new rows are added.
                                    indexedFileFacades.Add(mergeModuleFileFacade.Id, mergeModuleFileFacade);
                                    uniqueModuleFileIdentifiers.Add(mergeModuleFileFacade.Id, mergeModuleFileFacade);
                                }

                                containsFiles = true;
                            }
                        }
                    }

                    // Get the summary information to detect the Schema
                    using (var summaryInformation = new SummaryInformation(db))
                    {
                        var moduleInstallerVersionString = summaryInformation.GetProperty(14);

                        try
                        {
                            var moduleInstallerVersion = Convert.ToInt32(moduleInstallerVersionString, CultureInfo.InvariantCulture);
                            if (moduleInstallerVersion > this.OutputInstallerVersion)
                            {
                                this.Messaging.Write(WarningMessages.InvalidHigherInstallerVersionInModule(wixMergeRow.SourceLineNumbers, wixMergeRow.Id.Id, moduleInstallerVersion, this.OutputInstallerVersion));
                            }
                        }
                        catch (FormatException)
                        {
                            throw new WixException(ErrorMessages.MissingOrInvalidModuleInstallerVersion(wixMergeRow.SourceLineNumbers, wixMergeRow.Id.Id, wixMergeRow.SourceFile, moduleInstallerVersionString));
                        }
                    }
                }
            }
            catch (FileNotFoundException)
            {
                throw new WixException(ErrorMessages.FileNotFound(wixMergeRow.SourceLineNumbers, wixMergeRow.SourceFile));
            }
            catch (Win32Exception)
            {
                throw new WixException(ErrorMessages.CannotOpenMergeModule(wixMergeRow.SourceLineNumbers, wixMergeRow.Id.Id, wixMergeRow.SourceFile));
            }

            return(containsFiles);
        }
コード例 #21
0
        /// <summary>
        /// Set an MsiAssemblyName row.  If it was directly authored, override the value, otherwise
        /// create a new row.
        /// </summary>
        /// <param name="assemblyNameTuples">MsiAssemblyName table.</param>
        /// <param name="file">FileFacade containing the assembly read for the MsiAssemblyName row.</param>
        /// <param name="name">MsiAssemblyName name.</param>
        /// <param name="value">MsiAssemblyName value.</param>
        private void SetMsiAssemblyName(Dictionary <string, MsiAssemblyNameTuple> assemblyNameTuples, FileFacade file, string name, string value)
        {
            // check for null value (this can occur when grabbing the file version from an assembly without one)
            if (String.IsNullOrEmpty(value))
            {
                this.Messaging.Write(WarningMessages.NullMsiAssemblyNameValue(file.File.SourceLineNumbers, file.File.Component_, name));
            }
            else
            {
                // if the assembly will be GAC'd and the name in the file table doesn't match the name in the MsiAssemblyName table, error because the install will fail.
                if ("name" == name && FileAssemblyType.DotNetAssembly == file.WixFile.AssemblyType &&
                    String.IsNullOrEmpty(file.WixFile.File_AssemblyApplication) &&
                    !String.Equals(Path.GetFileNameWithoutExtension(file.File.LongFileName), value, StringComparison.OrdinalIgnoreCase))
                {
                    this.Messaging.Write(ErrorMessages.GACAssemblyIdentityWarning(file.File.SourceLineNumbers, Path.GetFileNameWithoutExtension(file.File.LongFileName), value));
                }

                // override directly authored value
                var lookup = String.Concat(file.File.Component_, "/", name);
                if (!assemblyNameTuples.TryGetValue(lookup, out var assemblyNameRow))
                {
                    assemblyNameRow            = new MsiAssemblyNameTuple(file.File.SourceLineNumbers);
                    assemblyNameRow.Component_ = file.File.Component_;
                    assemblyNameRow.Name       = name;
                    assemblyNameRow.Value      = value;

                    if (null == file.AssemblyNames)
                    {
                        file.AssemblyNames = new List <MsiAssemblyNameTuple>();
                    }

                    file.AssemblyNames.Add(assemblyNameRow);
                    this.Section.Tuples.Add(assemblyNameRow);
                }

                assemblyNameRow.Value = value;

                if (this.VariableCache != null)
                {
                    var key = String.Format(CultureInfo.InvariantCulture, "assembly{0}.{1}", name, file.File.File).ToLowerInvariant();
                    this.VariableCache[key] = value;
                }
            }
        }
コード例 #22
0
ファイル: Startup.cs プロジェクト: LeagueOfDevelopers/EduHub
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            StartLoggly();

            services.AddWebSocketManager();

            IFileRepository     fileRepository;
            IGroupRepository    groupRepository;
            IKeysRepository     keysRepository;
            ITagRepository      tagRepository;
            IUserRepository     userRepository;
            ISanctionRepository sanctionRepository;
            IEventRepository    eventRepository;

            if (bool.Parse(Configuration.GetValue <string>("UseDB")))
            {
                var dbContext = Configuration.GetValue <string>("MysqlConnectionString");
                using (var context = new EduhubContext(dbContext))
                {
                    if (bool.Parse(Configuration.GetValue <string>("DeleteDB")))
                    {
                        context.Database.EnsureDeleted();
                    }
                    if (context.Database.EnsureCreated())
                    {
                        var dbName = dbContext.Split("database=")[1].Split(";")[0];
                        context.Database.ExecuteSqlCommand(
                            "ALTER DATABASE " + dbName + " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;");
                        var modelNames = context.Model.GetEntityTypes();
                        foreach (var modelname in modelNames)
                        {
                            var mapping   = context.Model.FindEntityType(modelname.Name).Relational();
                            var tableName = mapping.TableName;
                            context.Database.ExecuteSqlCommand(
                                "alter table " + tableName.ToLower()
                                + " convert to character set utf8mb4 collate utf8mb4_bin;");
                        }
                    }

                    context.Database.Migrate();
                }

                fileRepository     = new InMysqlFileRepository(dbContext);
                groupRepository    = new InMysqlGroupRepository(dbContext);
                keysRepository     = new InMysqlKeyRepository(dbContext);
                tagRepository      = new InMysqlTagRepository(dbContext);
                userRepository     = new InMysqlUserRepository(dbContext);
                sanctionRepository = new InMysqlSanctionRepository(dbContext);
                eventRepository    = new InMemoryEventRepository();
            }
            else
            {
                fileRepository     = new InMemoryFileRepository();
                groupRepository    = new InMemoryGroupRepository();
                keysRepository     = new InMemoryKeysRepository();
                tagRepository      = new InMemoryTagRepository();
                sanctionRepository = new InMemorySanctionRepository();
                userRepository     = new InMemoryUserRepository();
                eventRepository    = new InMemoryEventRepository();
            }

            var emailSettings = new EmailSettings(Configuration.GetValue <string>("EmailLogin"),
                                                  Configuration.GetValue <string>("Email"),
                                                  Configuration.GetValue <string>("EmailPassword"),
                                                  Configuration.GetValue <string>("SmtpAddress"),
                                                  Configuration.GetValue <string>("ConfirmAddress"),
                                                  int.Parse(Configuration.GetValue <string>("SmtpPort")));


            var defaultAvatarFilename    = Configuration.GetValue <string>("DefaultAvatarFilename");
            var defaultAvatarContentType = Configuration.GetValue <string>("DefaultAvatarContentType");
            var userSettings             = new UserSettings(defaultAvatarFilename);

            if (!fileRepository.DoesFileExists(defaultAvatarFilename))
            {
                fileRepository.AddFile(new UserFile(defaultAvatarFilename, defaultAvatarContentType));
            }

            var tagFacade   = new TagFacade(tagRepository);
            var emailSender = new EmailSender(emailSettings);
            var notificationsDistributor = new NotificationsDistributor(groupRepository, userRepository, emailSender);

            var groupSettings = new GroupSettings(Configuration.GetValue <int>("MinGroupSize"),
                                                  Configuration.GetValue <int>("MaxGroupSize"),
                                                  Configuration.GetValue <double>("MinGroupValue"),
                                                  Configuration.GetValue <double>("MaxGroupValue"));

            var eventBusSettings = new EventBusSettings(Configuration.GetValue <string>("RabbitMqServerHostName"),
                                                        Configuration.GetValue <string>("RabbitMqServerVirtualHost"),
                                                        Configuration.GetValue <string>("RabbitMqAdminUserName"),
                                                        Configuration.GetValue <string>("RabbitMqAdminPassword"));
            var eventBus = new EventBus(eventBusSettings);

            eventBus.StartListening();

            var adminsEventConsumer     = new AdminsEventConsumer(notificationsDistributor, eventRepository);
            var courseEventConsumer     = new CourseEventConsumer(notificationsDistributor, eventRepository);
            var curriculumEventConsumer = new CurriculumEventConsumer(notificationsDistributor, eventRepository);
            var groupEventsConsumer     = new GroupEventsConsumer(notificationsDistributor, eventRepository);
            var invitationConsumer      = new InvitationConsumer(notificationsDistributor, eventRepository);
            var memberActionsConsumer   = new MemberActionsConsumer(notificationsDistributor, eventRepository);

            eventBus.RegisterConsumer(new TagPopularityConsumer(tagFacade));
            eventBus.RegisterConsumer <ReportMessageEvent>(adminsEventConsumer);
            eventBus.RegisterConsumer <SanctionsAppliedEvent>(adminsEventConsumer);
            eventBus.RegisterConsumer <SanctionCancelledEvent>(adminsEventConsumer);
            eventBus.RegisterConsumer <TeacherFoundEvent>(courseEventConsumer);
            eventBus.RegisterConsumer <CourseFinishedEvent>(courseEventConsumer);
            eventBus.RegisterConsumer <ReviewReceivedEvent>(courseEventConsumer);
            eventBus.RegisterConsumer <CurriculumAcceptedEvent>(curriculumEventConsumer);
            eventBus.RegisterConsumer <CurriculumDeclinedEvent>(curriculumEventConsumer);
            eventBus.RegisterConsumer <CurriculumSuggestedEvent>(curriculumEventConsumer);
            eventBus.RegisterConsumer <NewCreatorEvent>(groupEventsConsumer);
            eventBus.RegisterConsumer <GroupIsFormedEvent>(groupEventsConsumer);
            eventBus.RegisterConsumer <InvitationAcceptedEvent>(invitationConsumer);
            eventBus.RegisterConsumer <InvitationDeclinedEvent>(invitationConsumer);
            eventBus.RegisterConsumer <InvitationReceivedEvent>(invitationConsumer);
            eventBus.RegisterConsumer <NewMemberEvent>(memberActionsConsumer);
            eventBus.RegisterConsumer <MemberLeftEvent>(memberActionsConsumer);

            var publisher = eventBus.GetEventPublisher();

            var userFacade      = new UserFacade(userRepository, groupRepository, eventRepository, publisher);
            var groupEditFacade = new GroupEditFacade(groupRepository, groupSettings, publisher);
            var userEditFacade  = new UserEditFacade(userRepository, fileRepository, sanctionRepository);
            var groupFacade     = new GroupFacade(groupRepository, userRepository, sanctionRepository, groupSettings,
                                                  publisher);
            var fileFacade        = new FileFacade(fileRepository);
            var chatFacade        = new ChatFacade(groupRepository, userRepository);
            var sanctionsFacade   = new SanctionFacade(sanctionRepository, userRepository, publisher);
            var userAccountFacade = new AccountFacade(keysRepository, userRepository, emailSender, userSettings);
            var reportFacade      = new ReportFacade(userRepository, eventRepository, publisher);

            services.AddSingleton <IUserFacade>(userFacade);
            services.AddSingleton <IGroupFacade>(groupFacade);
            services.AddSingleton <IFileFacade>(fileFacade);
            services.AddSingleton <IChatFacade>(chatFacade);
            services.AddSingleton <IGroupEditFacade>(groupEditFacade);
            services.AddSingleton <IUserEditFacade>(userEditFacade);
            services.AddSingleton <ITagFacade>(tagFacade);
            services.AddSingleton <ISanctionFacade>(sanctionsFacade);
            services.AddSingleton <IAccountFacade>(userAccountFacade);
            services.AddSingleton <IReportFacade>(reportFacade);
            services.AddSingleton(Env);

            userAccountFacade.CheckAdminExistence(Configuration.GetValue <string>("AdminEmail"));

            services.AddSwaggerGen(current =>
            {
                current.SwaggerDoc("v1", new Info
                {
                    Title   = "EduHub API",
                    Version = "v1"
                });
                current.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description =
                        "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In   = "header",
                    Type = "apiKey"
                });
                current.OperationFilter <ExamplesOperationFilter>();
                current.DescribeAllEnumsAsStrings();
                var a = string.Format(@"{0}\EduHub.xml", AppDomain.CurrentDomain.BaseDirectory);
                current.IncludeXmlComments(string.Format(@"{0}/EduHub.xml", AppDomain.CurrentDomain.BaseDirectory));
            });
            ConfigureSecurity(services);
            if (Configuration.GetValue <bool>("Authorization"))
            {
                services.AddMvc(o =>
                {
                    o.Filters.Add(new ExceptionFilter());
                    o.Filters.Add(new ActionFilter());
                });
            }
            else
            {
                services.AddMvc(o =>
                {
                    o.Filters.Add(new AllowAnonymousFilter());
                    o.Filters.Add(new ExceptionFilter());
                    o.Filters.Add(new ActionFilter());
                });
            }
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAnyOrigin",
                                  builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });
        }
コード例 #23
0
        /// <summary>
        /// Set an MsiAssemblyName row.  If it was directly authored, override the value, otherwise
        /// create a new row.
        /// </summary>
        /// <param name="assemblyNameSymbols">MsiAssemblyName table.</param>
        /// <param name="facade">FileFacade containing the assembly read for the MsiAssemblyName row.</param>
        /// <param name="name">MsiAssemblyName name.</param>
        /// <param name="value">MsiAssemblyName value.</param>
        private void SetMsiAssemblyName(Dictionary <string, MsiAssemblyNameSymbol> assemblyNameSymbols, FileFacade facade, string name, string value)
        {
            // check for null value (this can occur when grabbing the file version from an assembly without one)
            if (String.IsNullOrEmpty(value))
            {
                this.Messaging.Write(WarningMessages.NullMsiAssemblyNameValue(facade.SourceLineNumber, facade.ComponentRef, name));
            }
            else
            {
                // if the assembly will be GAC'd and the name in the file table doesn't match the name in the MsiAssemblyName table, error because the install will fail.
                if ("name" == name && AssemblyType.DotNetAssembly == facade.AssemblyType &&
                    String.IsNullOrEmpty(facade.AssemblyApplicationFileRef) &&
                    !String.Equals(Path.GetFileNameWithoutExtension(facade.FileName), value, StringComparison.OrdinalIgnoreCase))
                {
                    this.Messaging.Write(ErrorMessages.GACAssemblyIdentityWarning(facade.SourceLineNumber, Path.GetFileNameWithoutExtension(facade.FileName), value));
                }

                // override directly authored value
                var lookup = String.Concat(facade.ComponentRef, "/", name);
                if (!assemblyNameSymbols.TryGetValue(lookup, out var assemblyNameSymbol))
                {
                    assemblyNameSymbol = this.Section.AddSymbol(new MsiAssemblyNameSymbol(facade.SourceLineNumber, new Identifier(AccessModifier.Section, facade.ComponentRef, name))
                    {
                        ComponentRef = facade.ComponentRef,
                        Name         = name,
                        Value        = value,
                    });

                    if (null == facade.AssemblyNames)
                    {
                        facade.AssemblyNames = new List <MsiAssemblyNameSymbol>();
                    }

                    facade.AssemblyNames.Add(assemblyNameSymbol);

                    assemblyNameSymbols.Add(assemblyNameSymbol.Id.Id, assemblyNameSymbol);
                }

                assemblyNameSymbol.Value = value;

                if (this.VariableCache != null)
                {
                    var key = String.Format(CultureInfo.InvariantCulture, "assembly{0}.{1}", name, facade.Id).ToLowerInvariant();
                    this.VariableCache[key] = value;
                }
            }
        }
コード例 #24
0
        public void ProcessRequest(HttpContext context)
        {
            //            if (context.Request.Url.Host.Equals("localhost")) return;
            if (_id.Equals(Guid.Empty))
            {
                return;
            }
            var document = new FileFacade().Get(_id);

            if (document == null)
            {
                return;
            }
            var memoryStream = new MemoryStream(document.Content)
            {
                Position = 0
            };
            var ext = document.Extension.Replace(".", "").ToLower();

            switch (ext)
            {
            case "jpg":
                ext = "Jpeg";
                break;

            default:
                ext = ext[0].ToString().ToUpper() + ext.Substring(1, ext.Length - 1);
                break;
            }

            var c            = new ImageFormat(Guid.NewGuid());
            var propertyInfo = c.GetType().GetProperty(ext);
            var doDownload   = !string.IsNullOrEmpty(context.Request.QueryString["dl"]);

            if (doDownload)
            {
                doDownload = bool.Parse(context.Request.QueryString["dl"]);
            }
            if (doDownload)
            {
                var attachment = string.Format("attachment; filename={0}.{1}", document.FileName.Replace(" ", "_"), document.Extension);
                context.Response.ClearContent();
                context.Response.AddHeader("content-disposition", attachment);
                context.Response.ContentType = "application/" + ext;
                context.Response.BinaryWrite(document.Content);
                context.Response.End();
                return;
            }
            if (propertyInfo != null)
            {
                var imageFormat = (ImageFormat)propertyInfo.GetValue(c, null);
                context.Response.ContentType = "image/" + imageFormat;
                try
                {
                    if (!string.IsNullOrEmpty(context.Request.QueryString["w"]) || !string.IsNullOrEmpty(context.Request.QueryString["h"]))
                    {
                        var width  = int.Parse(context.Request.QueryString["w"]);
                        var height = width;
                        if (!string.IsNullOrEmpty(context.Request.QueryString["h"]))
                        {
                            height = int.Parse(context.Request.QueryString["h"]);
                        }
                        var bitmap = new System.Drawing.Bitmap(System.Drawing.Image.FromStream(memoryStream), width, height);

                        bitmap.Save(context.Response.OutputStream, imageFormat);
                    }
                    else
                    {
                        System.Drawing.Image.FromStream(memoryStream).Save(context.Response.OutputStream, imageFormat);
                    }
                }
                catch (Exception)
                {
                    context.Response.ContentType = imageFormat + "/plain";
                    System.Drawing.Image.FromStream(memoryStream).Save(context.Response.OutputStream, imageFormat);
                }
            }
            else
            {
                if (ext.ToLower().Contains("swf"))
                {
                    context.Response.AddHeader("Content-Disposition", string.Format("filename={0}", document.FileName));
                    context.Response.AddHeader("Content-Type", "application/x-shockwave-flash");
                }
                else if (ext.ToLower().Equals("js"))
                {
                    var attachment = string.Format("attachment; filename={0}.{1}", document.FileName, document.Extension);
                    context.Response.ClearContent();
                    context.Response.AddHeader("content-disposition", attachment);
                    context.Response.ContentType = "text/javascript";
                }
                else if (ext.ToLower().Equals("css"))
                {
                    var attachment = string.Format("attachment; filename={0}.{1}", document.FileName, document.Extension);
                    context.Response.ClearContent();
                    context.Response.AddHeader("content-disposition", attachment);
                    context.Response.ContentType = "text/css";
                }
                else
                {
                    var attachment = string.Format("attachment; filename={0}.{1}", document.FileName, document.Extension);
                    context.Response.ClearContent();
                    context.Response.AddHeader("content-disposition", attachment);
                    context.Response.ContentType = "application/" + ext;
                }
                context.Response.BinaryWrite(document.Content);
                context.Response.End();
            }
        }
コード例 #25
0
        private void UpdateFileFacade(FileFacade facade, Dictionary <string, MsiAssemblyNameSymbol> assemblyNameSymbols)
        {
            FileInfo fileInfo = null;

            try
            {
                fileInfo = new FileInfo(facade.SourcePath);
            }
            catch (ArgumentException)
            {
                this.Messaging.Write(ErrorMessages.InvalidFileName(facade.SourceLineNumber, facade.SourcePath));
                return;
            }
            catch (PathTooLongException)
            {
                this.Messaging.Write(ErrorMessages.InvalidFileName(facade.SourceLineNumber, facade.SourcePath));
                return;
            }
            catch (NotSupportedException)
            {
                this.Messaging.Write(ErrorMessages.InvalidFileName(facade.SourceLineNumber, facade.SourcePath));
                return;
            }

            if (!fileInfo.Exists)
            {
                this.Messaging.Write(ErrorMessages.CannotFindFile(facade.SourceLineNumber, facade.Id, facade.FileName, facade.SourcePath));
                return;
            }

            using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                if (Int32.MaxValue < fileStream.Length)
                {
                    throw new WixException(ErrorMessages.FileTooLarge(facade.SourceLineNumber, facade.SourcePath));
                }

                facade.FileSize = Convert.ToInt32(fileStream.Length, CultureInfo.InvariantCulture);
            }

            string version  = null;
            string language = null;

            try
            {
                Installer.GetFileVersion(fileInfo.FullName, out version, out language);
            }
            catch (Win32Exception e)
            {
                if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND
                {
                    throw new WixException(ErrorMessages.FileNotFound(facade.SourceLineNumber, fileInfo.FullName));
                }
                else
                {
                    throw new WixException(ErrorMessages.Win32Exception(e.NativeErrorCode, e.Message));
                }
            }

            // If there is no version, it is assumed there is no language because it won't matter in the versioning of the install.
            if (String.IsNullOrEmpty(version)) // unversioned files have their hashes added to the MsiFileHash table
            {
                if (!this.OverwriteHash)
                {
                    // not overwriting hash, so don't do the rest of these options.
                }
                else if (null != facade.Version)
                {
                    // Search all of the file rows available to see if the specified version is actually a companion file. Yes, this looks
                    // very expensive and you're probably thinking it would be better to create an index of some sort to do an O(1) look up.
                    // That's a reasonable thought but companion file usage is usually pretty rare so we'd be doing something expensive (indexing
                    // all the file rows) for a relatively uncommon situation. Let's not do that.
                    //
                    // Also, if we do not find a matching file identifier then the user provided a default version and is providing a version
                    // for unversioned file. That's allowed but generally a dangerous thing to do so let's point that out to the user.
                    if (!this.FileFacades.Any(r => facade.Version.Equals(r.Id, StringComparison.Ordinal)))
                    {
                        this.Messaging.Write(WarningMessages.DefaultVersionUsedForUnversionedFile(facade.SourceLineNumber, facade.Version, facade.Id));
                    }
                }
                else
                {
                    if (null != facade.Language)
                    {
                        this.Messaging.Write(WarningMessages.DefaultLanguageUsedForUnversionedFile(facade.SourceLineNumber, facade.Language, facade.Id));
                    }

                    int[] hash;
                    try
                    {
                        Installer.GetFileHash(fileInfo.FullName, 0, out hash);
                    }
                    catch (Win32Exception e)
                    {
                        if (0x2 == e.NativeErrorCode) // ERROR_FILE_NOT_FOUND
                        {
                            throw new WixException(ErrorMessages.FileNotFound(facade.SourceLineNumber, fileInfo.FullName));
                        }
                        else
                        {
                            throw new WixException(ErrorMessages.Win32Exception(e.NativeErrorCode, fileInfo.FullName, e.Message));
                        }
                    }

                    if (null == facade.Hash)
                    {
                        facade.Hash = this.Section.AddSymbol(new MsiFileHashSymbol(facade.SourceLineNumber, facade.Identifier));
                    }

                    facade.Hash.Options   = 0;
                    facade.Hash.HashPart1 = hash[0];
                    facade.Hash.HashPart2 = hash[1];
                    facade.Hash.HashPart3 = hash[2];
                    facade.Hash.HashPart4 = hash[3];
                }
            }
            else // update the file row with the version and language information.
            {
                // If no version was provided by the user, use the version from the file itself.
                // This is the most common case.
                if (String.IsNullOrEmpty(facade.Version))
                {
                    facade.Version = version;
                }
                else if (!this.FileFacades.Any(r => facade.Version.Equals(r.Id, StringComparison.Ordinal))) // this looks expensive, but see explanation below.
                {
                    // The user provided a default version for the file row so we looked for a companion file (a file row with Id matching
                    // the version value). We didn't find it so, we will override the default version they provided with the actual
                    // version from the file itself. Now, I know it looks expensive to search through all the file rows trying to match
                    // on the Id. However, the alternative is to build a big index of all file rows to do look ups. Since this case
                    // where the file version is already present is rare (companion files are pretty uncommon), we'll do the more
                    // CPU intensive search to save on the memory intensive index that wouldn't be used much.
                    //
                    // Also note this case can occur when the file is being updated using the WixBindUpdatedFiles extension mechanism.
                    // That's typically even more rare than companion files so again, no index, just search.
                    facade.Version = version;
                }

                if (!String.IsNullOrEmpty(facade.Language) && String.IsNullOrEmpty(language))
                {
                    this.Messaging.Write(WarningMessages.DefaultLanguageUsedForVersionedFile(facade.SourceLineNumber, facade.Language, facade.Id));
                }
                else // override the default provided by the user (usually nothing) with the actual language from the file itself.
                {
                    facade.Language = language;
                }

                // Populate the binder variables for this file information if requested.
                if (null != this.VariableCache)
                {
                    if (!String.IsNullOrEmpty(facade.Version))
                    {
                        var key = String.Format(CultureInfo.InvariantCulture, "fileversion.{0}", facade.Id);
                        this.VariableCache[key] = facade.Version;
                    }

                    if (!String.IsNullOrEmpty(facade.Language))
                    {
                        var key = String.Format(CultureInfo.InvariantCulture, "filelanguage.{0}", facade.Id);
                        this.VariableCache[key] = facade.Language;
                    }
                }
            }

            // If this is a CLR assembly, load the assembly and get the assembly name information
            if (AssemblyType.DotNetAssembly == facade.AssemblyType)
            {
                try
                {
                    var assemblyName = AssemblyNameReader.ReadAssembly(facade.SourceLineNumber, fileInfo.FullName, version);

                    this.SetMsiAssemblyName(assemblyNameSymbols, facade, "name", assemblyName.Name);
                    this.SetMsiAssemblyName(assemblyNameSymbols, facade, "culture", assemblyName.Culture);
                    this.SetMsiAssemblyName(assemblyNameSymbols, facade, "version", assemblyName.Version);

                    if (!String.IsNullOrEmpty(assemblyName.Architecture))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "processorArchitecture", assemblyName.Architecture);
                    }
                    // TODO: WiX v3 seemed to do this but not clear it should actually be done.
                    //else if (!String.IsNullOrEmpty(file.WixFile.ProcessorArchitecture))
                    //{
                    //    this.SetMsiAssemblyName(assemblyNameSymbols, file, "processorArchitecture", file.WixFile.ProcessorArchitecture);
                    //}

                    if (assemblyName.StrongNamedSigned)
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "publicKeyToken", assemblyName.PublicKeyToken);
                    }
                    else if (facade.AssemblyApplicationFileRef == null)
                    {
                        throw new WixException(ErrorMessages.GacAssemblyNoStrongName(facade.SourceLineNumber, fileInfo.FullName, facade.ComponentRef));
                    }

                    if (!String.IsNullOrEmpty(assemblyName.FileVersion))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "fileVersion", assemblyName.FileVersion);
                    }

                    // add the assembly name to the information cache
                    if (null != this.VariableCache)
                    {
                        this.VariableCache[$"assemblyfullname.{facade.Id}"] = assemblyName.GetFullName();
                    }
                }
                catch (WixException e)
                {
                    this.Messaging.Write(e.Error);
                }
            }
            else if (AssemblyType.Win32Assembly == facade.AssemblyType)
            {
                // TODO: Consider passing in the this.FileFacades as an indexed collection instead of searching through
                // all files like this. Even though this is a rare case it looks like we might be able to index the
                // file earlier.
                var fileManifest = this.FileFacades.FirstOrDefault(r => r.Id.Equals(facade.AssemblyManifestFileRef, StringComparison.Ordinal));
                if (null == fileManifest)
                {
                    this.Messaging.Write(ErrorMessages.MissingManifestForWin32Assembly(facade.SourceLineNumber, facade.Id, facade.AssemblyManifestFileRef));
                }

                try
                {
                    var assemblyName = AssemblyNameReader.ReadAssemblyManifest(facade.SourceLineNumber, fileManifest.SourcePath);

                    if (!String.IsNullOrEmpty(assemblyName.Name))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "name", assemblyName.Name);
                    }

                    if (!String.IsNullOrEmpty(assemblyName.Version))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "version", assemblyName.Version);
                    }

                    if (!String.IsNullOrEmpty(assemblyName.Type))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "type", assemblyName.Type);
                    }

                    if (!String.IsNullOrEmpty(assemblyName.Architecture))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "processorArchitecture", assemblyName.Architecture);
                    }

                    if (!String.IsNullOrEmpty(assemblyName.PublicKeyToken))
                    {
                        this.SetMsiAssemblyName(assemblyNameSymbols, facade, "publicKeyToken", assemblyName.PublicKeyToken);
                    }
                }
                catch (WixException e)
                {
                    this.Messaging.Write(e.Error);
                }
            }
        }
コード例 #26
0
ファイル: ImageBuilder.cs プロジェクト: davoodkosari/Zibasazi
        public string Buid()
        {
            var sw     = new StringWriter();
            var writer = new Html32TextWriter(sw);
            var query  = "";

            if (FixSize)
            {
                query = "w=" + this.Width + "&h=" + this.Height;
            }

            writer.AddAttribute("id", this.Name);
            writer.AddAttribute("name", this.Name);
            writer.AddAttribute("type", "hidden");
            writer.AddAttribute("value", this.Id.ToString());
            writer.RenderBeginTag("input");
            writer.RenderEndTag();

            if (DeleteButtonVisible)
            {
                var str = "document.getElementById('" + this.Name + "').value='" + null + "';"
                          + "$('#Delete-" + this.Name + "').hide();"
                          + "$('#atag-" + this.Name + "').hide();"
                          + "$('#imagetag-" + this.Name + "').hide();";

                writer.AddAttribute("id", "Delete-" + this.Name);
                writer.AddAttribute("name", "Delete-" + this.Name);
                writer.AddAttribute("onclick", str);
                writer.AddAttribute("style", "cursor:pointer;");
                writer.AddAttribute("title", Resources.FileManager.DeleteFile);
                writer.RenderBeginTag("a");
                writer.AddAttribute("class", "fa fa-trash fa-1x trash-icon");
                writer.RenderBeginTag("i");
                writer.RenderEndTag();
                writer.RenderEndTag();
            }
            if (Download)
            {
                var file = new FileFacade().Get(Id);
                writer.AddAttribute("Id", "atag-" + this.Name);
                writer.AddAttribute("href", FileManagerContants.FileHandlerRoot + this.Id + "?dl=true&" + query);
                writer.AddAttribute("target", "_blank");
                writer.RenderBeginTag("a");
                if (file != null)
                {
                    writer.WriteEncodedText(file.FullName);
                }
                writer.RenderEndTag();
            }
            else
            {
                writer.AddAttribute("Id", "imagetag-" + this.Name);
                writer.AddAttribute("src", FileManagerContants.FileHandlerRoot + this.Id + (string.IsNullOrEmpty(query) ? "" : "?") + query);
                if (this.Height.HasValue)
                {
                    writer.AddAttribute("height", this.Height.Value.ToString());
                }
                if (this.Width.HasValue)
                {
                    writer.AddAttribute("width", this.Width.Value.ToString());
                }
                if (!string.IsNullOrEmpty(this.Style))
                {
                    writer.AddAttribute("style", this.Style);
                }
                if (!string.IsNullOrEmpty(this.Title))
                {
                    writer.AddAttribute("title", this.Title);
                }
                if (!string.IsNullOrEmpty(this.Alt))
                {
                    writer.AddAttribute("alt", this.Alt);
                }
                if (this.OtherAttribute != null)
                {
                    foreach (var property in this.OtherAttribute.GetType().GetProperties())
                    {
                        writer.AddAttribute(property.Name, property.GetValue(this.OtherAttribute, null).ToString());
                    }
                }

                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag();
            }


            return(sw.ToString());
        }