Code:
/ Dotnetfx_Win7_3.5.1 / Dotnetfx_Win7_3.5.1 / 3.5.1 / DEVDIV / depot / DevDiv / releases / Orcas / NetFXw7 / wpf / src / BuildTasks / Microsoft / Build / Tasks / Windows / ResourcesGenerator.cs / 1 / ResourcesGenerator.cs
//---------------------------------------------------------------------------- // //// Copyright (C) Microsoft Corporation. All rights reserved. // // // Description: An MSBuild task that generate .resources file from given // resource files, .jpg, .ico, .baml, etc. // // Spec: http://avalon/app/Compilation/Avalon-MSBUILD%20Targets.doc // // History: // 04/27/2005 : Integrate from ResourcesGenerator // //--------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; using Microsoft.Build.Tasks.Windows; using MS.Internal; using MS.Internal.Tasks; // Since we disable PreSharp warnings in this file, PreSharp warning is unknown to C# compiler. // We first need to disable warnings about unknown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 namespace Microsoft.Build.Tasks.Windows { #region ResourcesGenerator Task class ////// /// public sealed class ResourcesGenerator : Task { //----------------------------------------------------- // // Constructors // //----------------------------------------------------- #region Constructors ////// ctor /// public ResourcesGenerator ( ) : base(SR.ResourceManager) { // set the source directory _sourceDir = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //----------------------------------------------------- #region Public Methods ////// Execute /// ///public override bool Execute() { TaskHelper.DisplayLogo(Log, SR.Get(SRID.ResourcesGeneratorTask)); // // Validate the property settings // if (ValidResourceFiles(ResourceFiles) == false) { // ValidResourceFiles has already showed up error message. // Just stop here. return false; } if (OutputResourcesFile != null && OutputResourcesFile.Length > 1) { // Every task should generate only one .resources. Log.LogErrorWithCodeFromResources(SRID.MoreResourcesFiles); return false; } bool successful = true; ResourceWriter resWriter = null; try { // create output directory if (!Directory.Exists(OutputPath)) { Directory.CreateDirectory(OutputPath); } string resourcesFile = OutputResourcesFile[0].ItemSpec; Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourcesGenerating, resourcesFile); // Go through all the files and create a resources file. resWriter = new ResourceWriter(resourcesFile); #pragma warning disable 6518 // Warning 56518 Local IDisposable object not disposed // Comments from CLR code owners as why not to call Close on the memeory stream: // // This is one of those strange places where the lifetime of the MemoryStream must be // at least until you call Generate on the ResourceWriter. // This is one of those poorly-defined lifetime issues your code could decide to // close the MemoryStream after its done generating the ResourceWriter, but we have // no good way of letting you know of this requirement up front. // // Since there arent any relatively precious native handles involved, you are best // off not closing the MemoryStream, and letting the GC do its job. // // Presharp violations are just an indication that something could be wrong. Some of // the rules are noisy. you have a live reference to the MemoryStream in resWriter // so for this case, The Presharp violation is wrong for this situataion and should // be suppressed. // for (int i = 0; i < ResourceFiles.Length; i++) { byte[] fileBuffer = null; string resourceId = null; string resFileName = ResourceFiles[i].ItemSpec; string fullFilePath = Path.GetFullPath(resFileName); resourceId = GetResourceIdForResourceFile(ResourceFiles[i]); // read the file as a byte array using (FileStream resourceStream = File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { // limit size to System.Int32.MaxValue long length = resourceStream.Length; if (length > (long)System.Int32.MaxValue) { throw new ApplicationException(SR.Get(SRID.ResourceTooBig, resFileName, System.Int32.MaxValue)); } Log.LogMessageFromResources(MessageImportance.Low, SRID.ReadResourceFile, fullFilePath); Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourceId, resourceId); //Store the assembly stream to a byte array. fileBuffer = new byte[(int)length]; if (fileBuffer != null) { int read = resourceStream.Read(fileBuffer, 0, (int)length); MemoryStream stream = new MemoryStream(fileBuffer); // add the resource resWriter.AddResource(resourceId, stream); } } } #pragma warning restore 6518 // Generate the .resources file. resWriter.Generate(); Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourcesGenerated, resourcesFile); } catch (Exception e) { // PreSharp Complaint 6500 - do not handle null-ref or SEH exceptions. if (e is NullReferenceException || e is SEHException) { throw; } else { string message; string errorId; errorId = Log.ExtractMessageCode(e.Message, out message); if (String.IsNullOrEmpty(errorId)) { errorId = UnknownErrorID; message = SR.Get(SRID.UnknownBuildError, message); } Log.LogError(null, errorId, null, null, 0, 0, 0, 0, message, null); successful = false; } } #pragma warning disable 6500 catch // Non-cls compliant errors { Log.LogErrorWithCodeFromResources(SRID.NonClsError); successful = false; } #pragma warning restore 6500 finally { if (resWriter != null) { // close the resource writer resWriter.Close(); } } return successful; } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// /// Image or baml files which will be embedded into Resources File /// [Required] public ITaskItem [] ResourceFiles { get { return _inputFiles; } set { _inputFiles = value; } } ////// The directory where the generated resources file lives. /// [Required] public string OutputPath { get { return _outputPath; } set { _outputPath = Path.GetFullPath(value); if (!_outputPath.EndsWith((Path.DirectorySeparatorChar).ToString(), StringComparison.Ordinal)) _outputPath += Path.DirectorySeparatorChar; } } ////// Generated resources file. This is a required input item. /// Every task should generate only one .resource file. /// If the resource is for a specific culture, the ItemSpec should have syntax like /// Filebasename.$(Culture).resources. /// /// The file path should also include OutputPath. /// [Output] [Required] public ITaskItem [] OutputResourcesFile { get { return _outputResourcesFile; } set { _outputResourcesFile = value; } } #endregion Public Properties //----------------------------------------------------- // // Public Events // //------------------------------------------------------ #region Public Events #endregion Public Events //----------------------------------------------------- // // Protected Methods // //----------------------------------------------------- #region Protected Methods #endregion Protected Methods //----------------------------------------------------- // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //----------------------------------------------------- // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Internal Events // //----------------------------------------------------- #region Internal Events #endregion Internal Events //------------------------------------------------------ // // Private Methods // //----------------------------------------------------- #region Private Methods ////// Check if the passed files have valid path /// /// ///private bool ValidResourceFiles(ITaskItem[] inputFiles) { bool bValid = true; foreach (ITaskItem inputFile in inputFiles) { string strFileName; strFileName = inputFile.ItemSpec; if (!File.Exists(TaskHelper.CreateFullFilePath(strFileName, SourceDir))) { bValid = false; Log.LogErrorWithCodeFromResources(SRID.FileNotFound, strFileName); } } return bValid; } /// /// Return the correct resource id for the passed resource file path. /// /// Resource File Path ///the resource id private string GetResourceIdForResourceFile(ITaskItem resFile) { string resourceId = null; string fullFilePath = Path.GetFullPath(resFile.ItemSpec); string relPath; // // If the resFile is relative to the StagingDir (OutputPath here) // take the relative path as resource id. // If the resFile is not relative to StagingDir, but relative // to the project directory, take this relative path as resource id. // Otherwise, just take the file name as resource id. // relPath = TaskHelper.GetRootRelativePath(OutputPath, fullFilePath); if (String.IsNullOrEmpty(relPath)) { relPath = TaskHelper.GetRootRelativePath(SourceDir, fullFilePath); } if (String.IsNullOrEmpty(relPath) == false) { resourceId = relPath; } else { resourceId = Path.GetFileName(fullFilePath); } // Modify resource ID to correspond to canonicalized Uri format // i.e. - all lower case, use "/" as separator // ' ' is converted to escaped version %20 // resourceId = ResourceIDHelper.GetResourceIDFromRelativePath(resourceId); return resourceId; } #endregion Private Methods //----------------------------------------------------- // // Private Properties // //----------------------------------------------------- #region Private Properties private string SourceDir { get { return _sourceDir; } } #endregion Private Properties //------------------------------------------------------ // // Private Fields // //----------------------------------------------------- #region Private Fields private ITaskItem [] _inputFiles; private ITaskItem [] _outputResourcesFile; private string _outputPath; private string _sourceDir; private const string UnknownErrorID = "RG1000"; #endregion Private Fields } #endregion ResourcesGenerator Task class } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- // //// Copyright (C) Microsoft Corporation. All rights reserved. // // // Description: An MSBuild task that generate .resources file from given // resource files, .jpg, .ico, .baml, etc. // // Spec: http://avalon/app/Compilation/Avalon-MSBUILD%20Targets.doc // // History: // 04/27/2005 : Integrate from ResourcesGenerator // //--------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Globalization; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; using Microsoft.Build.Tasks.Windows; using MS.Internal; using MS.Internal.Tasks; // Since we disable PreSharp warnings in this file, PreSharp warning is unknown to C# compiler. // We first need to disable warnings about unknown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 namespace Microsoft.Build.Tasks.Windows { #region ResourcesGenerator Task class ////// /// public sealed class ResourcesGenerator : Task { //----------------------------------------------------- // // Constructors // //----------------------------------------------------- #region Constructors ////// ctor /// public ResourcesGenerator ( ) : base(SR.ResourceManager) { // set the source directory _sourceDir = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //----------------------------------------------------- #region Public Methods ////// Execute /// ///public override bool Execute() { TaskHelper.DisplayLogo(Log, SR.Get(SRID.ResourcesGeneratorTask)); // // Validate the property settings // if (ValidResourceFiles(ResourceFiles) == false) { // ValidResourceFiles has already showed up error message. // Just stop here. return false; } if (OutputResourcesFile != null && OutputResourcesFile.Length > 1) { // Every task should generate only one .resources. Log.LogErrorWithCodeFromResources(SRID.MoreResourcesFiles); return false; } bool successful = true; ResourceWriter resWriter = null; try { // create output directory if (!Directory.Exists(OutputPath)) { Directory.CreateDirectory(OutputPath); } string resourcesFile = OutputResourcesFile[0].ItemSpec; Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourcesGenerating, resourcesFile); // Go through all the files and create a resources file. resWriter = new ResourceWriter(resourcesFile); #pragma warning disable 6518 // Warning 56518 Local IDisposable object not disposed // Comments from CLR code owners as why not to call Close on the memeory stream: // // This is one of those strange places where the lifetime of the MemoryStream must be // at least until you call Generate on the ResourceWriter. // This is one of those poorly-defined lifetime issues your code could decide to // close the MemoryStream after its done generating the ResourceWriter, but we have // no good way of letting you know of this requirement up front. // // Since there arent any relatively precious native handles involved, you are best // off not closing the MemoryStream, and letting the GC do its job. // // Presharp violations are just an indication that something could be wrong. Some of // the rules are noisy. you have a live reference to the MemoryStream in resWriter // so for this case, The Presharp violation is wrong for this situataion and should // be suppressed. // for (int i = 0; i < ResourceFiles.Length; i++) { byte[] fileBuffer = null; string resourceId = null; string resFileName = ResourceFiles[i].ItemSpec; string fullFilePath = Path.GetFullPath(resFileName); resourceId = GetResourceIdForResourceFile(ResourceFiles[i]); // read the file as a byte array using (FileStream resourceStream = File.Open(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { // limit size to System.Int32.MaxValue long length = resourceStream.Length; if (length > (long)System.Int32.MaxValue) { throw new ApplicationException(SR.Get(SRID.ResourceTooBig, resFileName, System.Int32.MaxValue)); } Log.LogMessageFromResources(MessageImportance.Low, SRID.ReadResourceFile, fullFilePath); Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourceId, resourceId); //Store the assembly stream to a byte array. fileBuffer = new byte[(int)length]; if (fileBuffer != null) { int read = resourceStream.Read(fileBuffer, 0, (int)length); MemoryStream stream = new MemoryStream(fileBuffer); // add the resource resWriter.AddResource(resourceId, stream); } } } #pragma warning restore 6518 // Generate the .resources file. resWriter.Generate(); Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourcesGenerated, resourcesFile); } catch (Exception e) { // PreSharp Complaint 6500 - do not handle null-ref or SEH exceptions. if (e is NullReferenceException || e is SEHException) { throw; } else { string message; string errorId; errorId = Log.ExtractMessageCode(e.Message, out message); if (String.IsNullOrEmpty(errorId)) { errorId = UnknownErrorID; message = SR.Get(SRID.UnknownBuildError, message); } Log.LogError(null, errorId, null, null, 0, 0, 0, 0, message, null); successful = false; } } #pragma warning disable 6500 catch // Non-cls compliant errors { Log.LogErrorWithCodeFromResources(SRID.NonClsError); successful = false; } #pragma warning restore 6500 finally { if (resWriter != null) { // close the resource writer resWriter.Close(); } } return successful; } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// /// Image or baml files which will be embedded into Resources File /// [Required] public ITaskItem [] ResourceFiles { get { return _inputFiles; } set { _inputFiles = value; } } ////// The directory where the generated resources file lives. /// [Required] public string OutputPath { get { return _outputPath; } set { _outputPath = Path.GetFullPath(value); if (!_outputPath.EndsWith((Path.DirectorySeparatorChar).ToString(), StringComparison.Ordinal)) _outputPath += Path.DirectorySeparatorChar; } } ////// Generated resources file. This is a required input item. /// Every task should generate only one .resource file. /// If the resource is for a specific culture, the ItemSpec should have syntax like /// Filebasename.$(Culture).resources. /// /// The file path should also include OutputPath. /// [Output] [Required] public ITaskItem [] OutputResourcesFile { get { return _outputResourcesFile; } set { _outputResourcesFile = value; } } #endregion Public Properties //----------------------------------------------------- // // Public Events // //------------------------------------------------------ #region Public Events #endregion Public Events //----------------------------------------------------- // // Protected Methods // //----------------------------------------------------- #region Protected Methods #endregion Protected Methods //----------------------------------------------------- // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //----------------------------------------------------- // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Internal Events // //----------------------------------------------------- #region Internal Events #endregion Internal Events //------------------------------------------------------ // // Private Methods // //----------------------------------------------------- #region Private Methods ////// Check if the passed files have valid path /// /// ///private bool ValidResourceFiles(ITaskItem[] inputFiles) { bool bValid = true; foreach (ITaskItem inputFile in inputFiles) { string strFileName; strFileName = inputFile.ItemSpec; if (!File.Exists(TaskHelper.CreateFullFilePath(strFileName, SourceDir))) { bValid = false; Log.LogErrorWithCodeFromResources(SRID.FileNotFound, strFileName); } } return bValid; } /// /// Return the correct resource id for the passed resource file path. /// /// Resource File Path ///the resource id private string GetResourceIdForResourceFile(ITaskItem resFile) { string resourceId = null; string fullFilePath = Path.GetFullPath(resFile.ItemSpec); string relPath; // // If the resFile is relative to the StagingDir (OutputPath here) // take the relative path as resource id. // If the resFile is not relative to StagingDir, but relative // to the project directory, take this relative path as resource id. // Otherwise, just take the file name as resource id. // relPath = TaskHelper.GetRootRelativePath(OutputPath, fullFilePath); if (String.IsNullOrEmpty(relPath)) { relPath = TaskHelper.GetRootRelativePath(SourceDir, fullFilePath); } if (String.IsNullOrEmpty(relPath) == false) { resourceId = relPath; } else { resourceId = Path.GetFileName(fullFilePath); } // Modify resource ID to correspond to canonicalized Uri format // i.e. - all lower case, use "/" as separator // ' ' is converted to escaped version %20 // resourceId = ResourceIDHelper.GetResourceIDFromRelativePath(resourceId); return resourceId; } #endregion Private Methods //----------------------------------------------------- // // Private Properties // //----------------------------------------------------- #region Private Properties private string SourceDir { get { return _sourceDir; } } #endregion Private Properties //------------------------------------------------------ // // Private Fields // //----------------------------------------------------- #region Private Fields private ITaskItem [] _inputFiles; private ITaskItem [] _outputResourcesFile; private string _outputPath; private string _sourceDir; private const string UnknownErrorID = "RG1000"; #endregion Private Fields } #endregion ResourcesGenerator Task class } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- BuilderPropertyEntry.cs
- DataGridViewComboBoxColumn.cs
- DateTimeFormatInfoScanner.cs
- EventLog.cs
- GridViewUpdatedEventArgs.cs
- CompilationUtil.cs
- OleDbParameter.cs
- DefaultAsyncDataDispatcher.cs
- ActivityExecutor.cs
- TextSelection.cs
- CfgParser.cs
- HttpClientProtocol.cs
- AppLevelCompilationSectionCache.cs
- XmlSchemaAttributeGroup.cs
- OracleDataAdapter.cs
- NotifyIcon.cs
- RadioButton.cs
- ObjectTypeMapping.cs
- PatternMatcher.cs
- InputGestureCollection.cs
- SqlBulkCopyColumnMappingCollection.cs
- _NestedSingleAsyncResult.cs
- Thread.cs
- NetNamedPipeBinding.cs
- CallbackValidator.cs
- Soap.cs
- ListViewEditEventArgs.cs
- AliasExpr.cs
- TreeViewItem.cs
- Peer.cs
- parserscommon.cs
- DataList.cs
- Rules.cs
- ArrayTypeMismatchException.cs
- SqlTypeSystemProvider.cs
- EmptyEnumerator.cs
- XpsViewerException.cs
- SystemIcmpV4Statistics.cs
- WebPartZone.cs
- TransformPatternIdentifiers.cs
- NameTable.cs
- RuleRefElement.cs
- SemaphoreSecurity.cs
- Event.cs
- AnimationClock.cs
- AttachedPropertyBrowsableWhenAttributePresentAttribute.cs
- BindingValueChangedEventArgs.cs
- OrthographicCamera.cs
- NamedObject.cs
- LicFileLicenseProvider.cs
- WebControlsSection.cs
- MethodRental.cs
- NullReferenceException.cs
- DefaultTypeArgumentAttribute.cs
- ReflectTypeDescriptionProvider.cs
- EnumerableRowCollectionExtensions.cs
- StatusStrip.cs
- TransactionFlowOption.cs
- ContainsRowNumberChecker.cs
- PerfService.cs
- ListControl.cs
- DoubleAverageAggregationOperator.cs
- ServicePointManagerElement.cs
- ConfigPathUtility.cs
- ComPlusInstanceProvider.cs
- WpfWebRequestHelper.cs
- TextCharacters.cs
- PersonalizationStateInfo.cs
- SqlStream.cs
- FSWPathEditor.cs
- MSAAEventDispatcher.cs
- DocumentViewer.cs
- SettingsProviderCollection.cs
- GlobalizationAssembly.cs
- TextEditorParagraphs.cs
- AsyncCodeActivityContext.cs
- ImportCatalogPart.cs
- BitmapPalettes.cs
- DataGridParentRows.cs
- NewItemsContextMenuStrip.cs
- NegationPusher.cs
- WebPart.cs
- StsCommunicationException.cs
- Attributes.cs
- ConsoleCancelEventArgs.cs
- ConfigurationStrings.cs
- _ScatterGatherBuffers.cs
- WeakRefEnumerator.cs
- QilGeneratorEnv.cs
- RepeaterDesigner.cs
- Pipe.cs
- SizeAnimation.cs
- CharKeyFrameCollection.cs
- PointHitTestParameters.cs
- PrinterResolution.cs
- InteropAutomationProvider.cs
- CFStream.cs
- DescriptionAttribute.cs
- ConfigXmlText.cs
- RsaKeyIdentifierClause.cs