Code:
/ DotNET / DotNET / 8.0 / untmp / WIN_WINDOWS / lh_tools_devdiv_wpf / Windows / wcp / Build / 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: [....]/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.String); 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.String, 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.String, fullFilePath); Log.LogMessageFromResources(MessageImportance.Low, SRID.ResourceId.String, 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.String, 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.String); 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.String, 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
- FormsAuthenticationTicket.cs
- FilteredAttributeCollection.cs
- XDeferredAxisSource.cs
- WmlCalendarAdapter.cs
- ObjectFactoryCodeDomTreeGenerator.cs
- DistinctQueryOperator.cs
- XmlILOptimizerVisitor.cs
- RootDesignerSerializerAttribute.cs
- Utils.cs
- _MultipleConnectAsync.cs
- DBCommand.cs
- SocketStream.cs
- ObjectConverter.cs
- CriticalHandle.cs
- documentsequencetextcontainer.cs
- Serializer.cs
- TransformerInfoCollection.cs
- RouteData.cs
- ScriptModule.cs
- Splitter.cs
- XpsManager.cs
- SqlReorderer.cs
- OperationPickerDialog.designer.cs
- FileUtil.cs
- SharedConnectionWorkflowTransactionService.cs
- RectAnimationClockResource.cs
- TextEndOfLine.cs
- cookie.cs
- DatagridviewDisplayedBandsData.cs
- OpenFileDialog.cs
- XmlElementCollection.cs
- DataGridViewCellStyleContentChangedEventArgs.cs
- ScriptControl.cs
- MethodAccessException.cs
- WebAdminConfigurationHelper.cs
- WebPartZoneBase.cs
- OperandQuery.cs
- WebPartDisplayModeCollection.cs
- FtpCachePolicyElement.cs
- CryptoApi.cs
- TrustManagerMoreInformation.cs
- URLEditor.cs
- DataDocumentXPathNavigator.cs
- ConfigLoader.cs
- RoutedEvent.cs
- TextEditorMouse.cs
- XmlSerializerSection.cs
- FixedTextPointer.cs
- GroupDescription.cs
- Privilege.cs
- AssemblyInfo.cs
- WsiProfilesElementCollection.cs
- MissingMethodException.cs
- VirtualPathProvider.cs
- SymDocumentType.cs
- TextPenaltyModule.cs
- CodeConditionStatement.cs
- WebRequestModulesSection.cs
- Collection.cs
- OperatorExpressions.cs
- MenuDesigner.cs
- MustUnderstandSoapException.cs
- Style.cs
- RectConverter.cs
- ScrollChrome.cs
- OracleConnection.cs
- TickBar.cs
- BinaryReader.cs
- VirtualPathProvider.cs
- XmlRawWriterWrapper.cs
- Int32AnimationBase.cs
- TickBar.cs
- LinearGradientBrush.cs
- XmlSchemaAppInfo.cs
- WindowsEditBox.cs
- DeviceContext.cs
- ToolStrip.cs
- EditingCoordinator.cs
- PointAnimationClockResource.cs
- MimeMapping.cs
- CacheOutputQuery.cs
- SweepDirectionValidation.cs
- TagPrefixCollection.cs
- PerspectiveCamera.cs
- HotSpotCollection.cs
- Deflater.cs
- ProfileInfo.cs
- HwndTarget.cs
- ProbeDuplexAsyncResult.cs
- PhysicalOps.cs
- objectquery_tresulttype.cs
- Light.cs
- XmlDocumentSchema.cs
- HtmlHead.cs
- ServiceObjectContainer.cs
- DefaultValueAttribute.cs
- DictionaryContent.cs
- Utils.cs
- FormViewRow.cs
- SparseMemoryStream.cs