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
- CapabilitiesPattern.cs
- ChtmlMobileTextWriter.cs
- AmbientValueAttribute.cs
- TextBoxView.cs
- XmlObjectSerializerReadContextComplexJson.cs
- StateRuntime.cs
- StickyNoteHelper.cs
- InfoCardCryptoHelper.cs
- _Connection.cs
- Content.cs
- OperationAbortedException.cs
- CodePageUtils.cs
- XmlElement.cs
- UIElementAutomationPeer.cs
- RenameRuleObjectDialog.cs
- BitmapEffectInputConnector.cs
- Int32Collection.cs
- FontDifferentiator.cs
- MetadataFile.cs
- SkipStoryboardToFill.cs
- GridViewActionList.cs
- QuaternionAnimation.cs
- EntityCommandCompilationException.cs
- AddDataControlFieldDialog.cs
- Int32Collection.cs
- LocationFactory.cs
- Automation.cs
- IndependentAnimationStorage.cs
- RotationValidation.cs
- AsyncContentLoadedEventArgs.cs
- TypeLibConverter.cs
- DictionaryKeyPropertyAttribute.cs
- GroupItem.cs
- _Connection.cs
- DateTimeFormat.cs
- EntitySetBaseCollection.cs
- SecurityRequiresReviewAttribute.cs
- ManagementQuery.cs
- ExceptQueryOperator.cs
- WebBrowser.cs
- MeasureData.cs
- AppSettingsSection.cs
- FontStretch.cs
- ModelTreeEnumerator.cs
- FastEncoder.cs
- ProviderSettingsCollection.cs
- newinstructionaction.cs
- WindowsScrollBarBits.cs
- CompatibleComparer.cs
- SerializationStore.cs
- COM2TypeInfoProcessor.cs
- ColorAnimationUsingKeyFrames.cs
- BitmapEffectrendercontext.cs
- ExecutionScope.cs
- SqlConnection.cs
- recordstatefactory.cs
- ToolStripRenderEventArgs.cs
- SmtpNtlmAuthenticationModule.cs
- EdmError.cs
- AuthorizationPolicyTypeElement.cs
- UIElementIsland.cs
- WebPartCatalogCloseVerb.cs
- JpegBitmapDecoder.cs
- DtdParser.cs
- AssemblyInfo.cs
- OleAutBinder.cs
- RelationshipConverter.cs
- ColumnHeaderConverter.cs
- ContextDataSource.cs
- ControlPersister.cs
- ZoomComboBox.cs
- PropertyIDSet.cs
- QuaternionAnimation.cs
- TcpHostedTransportConfiguration.cs
- WindowsListView.cs
- AsyncCodeActivity.cs
- SystemInfo.cs
- _emptywebproxy.cs
- GeneralTransform3D.cs
- ClientRuntimeConfig.cs
- ImageConverter.cs
- SqlMethodCallConverter.cs
- SqlFunctions.cs
- XmlImplementation.cs
- BitmapCodecInfoInternal.cs
- SqlNodeTypeOperators.cs
- CharUnicodeInfo.cs
- XhtmlBasicLabelAdapter.cs
- RequestCacheManager.cs
- VoiceSynthesis.cs
- ServiceInstallComponent.cs
- AssemblyAttributes.cs
- SecureStringHasher.cs
- SiteMembershipCondition.cs
- TempEnvironment.cs
- ContentElement.cs
- LineMetrics.cs
- GAC.cs
- SweepDirectionValidation.cs
- DataGridViewEditingControlShowingEventArgs.cs