Code:
/ Dotnetfx_Vista_SP2 / Dotnetfx_Vista_SP2 / 8.0.50727.4016 / DEVDIV / depot / DevDiv / releases / Orcas / QFE / 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
- RefExpr.cs
- CollectionDataContractAttribute.cs
- FormViewUpdatedEventArgs.cs
- Context.cs
- SqlBinder.cs
- ParameterCollectionEditor.cs
- CultureInfoConverter.cs
- DESCryptoServiceProvider.cs
- OneOf.cs
- TextParagraphCache.cs
- DNS.cs
- EndOfStreamException.cs
- UniqueConstraint.cs
- VersionedStream.cs
- ValidatorCompatibilityHelper.cs
- StackSpiller.Bindings.cs
- CollectionViewSource.cs
- RelatedImageListAttribute.cs
- QueryOperator.cs
- ExtractedStateEntry.cs
- AuthenticationModulesSection.cs
- DataServices.cs
- ListViewUpdateEventArgs.cs
- CodeTypeReferenceSerializer.cs
- IpcChannelHelper.cs
- DataGridViewCellValidatingEventArgs.cs
- TextElementEnumerator.cs
- RuleRef.cs
- UIElement3DAutomationPeer.cs
- SynchronizationHandlesCodeDomSerializer.cs
- PrintController.cs
- ListViewItem.cs
- UInt32Converter.cs
- LayoutTableCell.cs
- PersonalizationStateInfoCollection.cs
- WorkflowViewElement.cs
- HttpWebRequestElement.cs
- UIElementPropertyUndoUnit.cs
- Parameter.cs
- RuleConditionDialog.Designer.cs
- Maps.cs
- UserControl.cs
- OutputCacheProfile.cs
- CaseCqlBlock.cs
- ReadWriteSpinLock.cs
- PageCopyCount.cs
- EngineSiteSapi.cs
- TableCell.cs
- ObjectStateManager.cs
- RoleManagerEventArgs.cs
- SoapCodeExporter.cs
- EntityTemplateUserControl.cs
- WindowAutomationPeer.cs
- PreviewPageInfo.cs
- XmlConvert.cs
- EditorBrowsableAttribute.cs
- RegexCode.cs
- Pkcs9Attribute.cs
- DodSequenceMerge.cs
- RelationshipEndMember.cs
- SmtpClient.cs
- IntegerFacetDescriptionElement.cs
- Base64Encoding.cs
- ExpressionBinding.cs
- NativeMethods.cs
- AssemblyFilter.cs
- QilLoop.cs
- _BufferOffsetSize.cs
- DataSourceExpression.cs
- XmlSchemaValidationException.cs
- InputReportEventArgs.cs
- TreeNodeBinding.cs
- StructuralComparisons.cs
- ThreadAttributes.cs
- XmlWriterTraceListener.cs
- HtmlInputControl.cs
- TextControl.cs
- Fault.cs
- OdbcParameterCollection.cs
- WebPartConnectionsCloseVerb.cs
- CursorConverter.cs
- CodeGroup.cs
- FilterableAttribute.cs
- arabicshape.cs
- HMAC.cs
- QEncodedStream.cs
- BridgeDataRecord.cs
- ToolStripItemEventArgs.cs
- ThicknessKeyFrameCollection.cs
- CodeIdentifiers.cs
- AudioFileOut.cs
- RuntimeResourceSet.cs
- TimerEventSubscription.cs
- ResourceManager.cs
- NonSerializedAttribute.cs
- ExpressionLexer.cs
- ControlValuePropertyAttribute.cs
- ParameterCollection.cs
- RootProfilePropertySettingsCollection.cs
- SingleTagSectionHandler.cs