Code:
/ DotNET / DotNET / 8.0 / untmp / WIN_WINDOWS / lh_tools_devdiv_wpf / Windows / wcp / Speech / Src / Recognition / GrammarBuilder.cs / 1 / GrammarBuilder.cs
//------------------------------------------------------------------ //// Copyright (c) Microsoft Corporation. All rights reserved. // //----------------------------------------------------------------- using System.Collections.ObjectModel; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Speech.Internal.SrgsParser; using System.Speech.Internal.SrgsCompiler; using System.Speech.Internal.GrammarBuilding; using System.Speech.Internal; using System.Text; using System.IO; namespace System.Speech.Recognition { ////// /// [DebuggerDisplay ("{DebugSummary}")] public class GrammarBuilder { //******************************************************************* // // Constructors // //******************************************************************* #region Constructors ////// /// public GrammarBuilder () { _grammarBuilder = new InternalGrammarBuilder (); } ////// /// /// public GrammarBuilder (string phrase) : this () { Append (phrase); } ////// /// /// /// public GrammarBuilder (string phrase, SubsetMatchingMode subsetMatchingCriteria) : this () { Append (phrase, subsetMatchingCriteria); } ////// /// /// /// /// public GrammarBuilder (string phrase, int minRepeat, int maxRepeat) : this () { Append (phrase, minRepeat, maxRepeat); } ////// /// /// /// /// public GrammarBuilder (GrammarBuilder builder, int minRepeat, int maxRepeat) : this () { Append (builder, minRepeat, maxRepeat); } ////// /// /// public GrammarBuilder (Choices alternateChoices) : this () { Append (alternateChoices); } ////// /// /// public GrammarBuilder (SemanticResultKey key) : this () { Append (key); } ////// /// /// public GrammarBuilder (SemanticResultValue value) : this () { Append (value); } #endregion Constructors //******************************************************************** // // Public Methods // //******************************************************************* #region Public Methods // Append connecting words ////// /// /// public void Append (string phrase) { Helpers.ThrowIfEmptyOrNull (phrase, "phrase"); AddItem (new GrammarBuilderPhrase (phrase)); } ////// /// /// /// public void Append (string phrase, SubsetMatchingMode subsetMatchingCriteria) { Helpers.ThrowIfEmptyOrNull (phrase, "phrase"); GrammarBuilder.ValidateSubsetMatchingCriteriaArgument (subsetMatchingCriteria, "subsetMatchingCriteria"); AddItem (new GrammarBuilderPhrase (phrase, subsetMatchingCriteria)); } ////// /// /// /// /// public void Append (string phrase, int minRepeat, int maxRepeat) { Helpers.ThrowIfEmptyOrNull (phrase, "phrase"); GrammarBuilder.ValidateRepeatArguments (minRepeat, maxRepeat, "minRepeat", "maxRepeat"); // Wrap the phrase in an item if min and max repeat are set GrammarBuilderPhrase elementPhrase = new GrammarBuilderPhrase (phrase); if (minRepeat != 1 || maxRepeat != 1) { AddItem (new ItemElement (elementPhrase, minRepeat, maxRepeat)); } else { AddItem (elementPhrase); } } // Append list of rulerefs ////// /// /// public void Append (GrammarBuilder builder) { Helpers.ThrowIfNull (builder, "builder"); // Should never happens has it is a RO value Helpers.ThrowIfNull (builder.InternalBuilder, "builder.InternalBuilder"); Helpers.ThrowIfNull (builder.InternalBuilder.Items, "builder.InternalBuilder.Items"); // Clone the items if we are playing with the local list. foreach (GrammarBuilderBase item in builder.InternalBuilder.Items) { if (item == null) { // This should never happen! throw new ArgumentException (SR.Get (SRID.ArrayOfNullIllegal), "builder"); } } // Clone the items if we are playing with the local list. Listitems = builder == this ? builder.Clone ().InternalBuilder.Items : builder.InternalBuilder.Items; foreach (GrammarBuilderBase item in items) { AddItem (item); } } // Append one-of /// /// /// /// public void Append (Choices alternateChoices) { Helpers.ThrowIfNull (alternateChoices, "alternateChoices"); AddItem (alternateChoices.OneOf); } ////// /// /// public void Append (SemanticResultKey key) { Helpers.ThrowIfNull (key, "builder"); AddItem (key.SemanticKeyElement); } ////// /// /// public void Append (SemanticResultValue value) { Helpers.ThrowIfNull (value, "builder"); AddItem (value.Tag); } ////// /// /// /// /// public void Append (GrammarBuilder builder, int minRepeat, int maxRepeat) { Helpers.ThrowIfNull (builder, "builder"); GrammarBuilder.ValidateRepeatArguments (minRepeat, maxRepeat, "minRepeat", "maxRepeat"); // Should never happens has it is a RO value Helpers.ThrowIfNull (builder.InternalBuilder, "builder.InternalBuilder"); // Wrap the phrase in an item if min and max repeat are set if (minRepeat != 1 || maxRepeat != 1) { AddItem (new ItemElement (builder.InternalBuilder.Items, minRepeat, maxRepeat)); } else { Append (builder); } } // Append dictation element ////// /// public void AppendDictation () { AddItem (new GrammarBuilderDictation ()); } ////// /// /// public void AppendDictation (string category) { Helpers.ThrowIfEmptyOrNull (category, "category"); AddItem (new GrammarBuilderDictation (category)); } // Append wildcard element ////// /// public void AppendWildcard () { AddItem (new GrammarBuilderWildcard ()); } ////// TODOC /// Append external rule ref /// /// public void AppendRuleReference (string path) { Helpers.ThrowIfEmptyOrNull (path, "path"); Uri uri; try { uri = new Uri (path, UriKind.RelativeOrAbsolute); } catch (UriFormatException e) { throw new ArgumentException (e.Message, path, e); } AddItem (new GrammarBuilderRuleRef (uri, null)); } ////// TODOC /// Append external rule ref /// /// /// public void AppendRuleReference (string path, string rule) { Helpers.ThrowIfEmptyOrNull (path, "path"); Helpers.ThrowIfEmptyOrNull (rule, "rule"); Uri uri; try { uri = new Uri (path, UriKind.RelativeOrAbsolute); } catch (UriFormatException e) { throw new ArgumentException (e.Message, path, e); } AddItem (new GrammarBuilderRuleRef (uri, rule)); } ////// TODOC /// ///public string DebugShowPhrases { get { return DebugSummary; } } #endregion Constructors //******************************************************************** // // Public Properties // //******************************************************************** #region Public Properties /// /// TODOC /// public CultureInfo Culture { set { if (value == null) { throw new ArgumentNullException ("value"); } _culture = value; } get { return _culture; } } #endregion //******************************************************************* // // Operator Overloads // //******************************************************************** #region Operator Overloads ////// /// /// /// ///public static GrammarBuilder operator + (string phrase, GrammarBuilder builder) { return Add (phrase, builder); } /// /// /// /// /// ///public static GrammarBuilder Add (string phrase, GrammarBuilder builder) { Helpers.ThrowIfNull (builder, "builder"); GrammarBuilder grammar = new GrammarBuilder (phrase); grammar.Append (builder); return grammar; } /// /// /// /// /// ///public static GrammarBuilder operator + (GrammarBuilder builder, string phrase) { return Add (builder, phrase); } /// /// /// /// /// ///public static GrammarBuilder Add (GrammarBuilder builder, string phrase) { Helpers.ThrowIfNull (builder, "builder"); GrammarBuilder grammar = builder.Clone (); grammar.Append (phrase); return grammar; } /// /// /// /// /// ///public static GrammarBuilder operator + (Choices choices, GrammarBuilder builder) { return Add (choices, builder); } /// /// /// /// /// ///public static GrammarBuilder Add (Choices choices, GrammarBuilder builder) { Helpers.ThrowIfNull (choices, "choices"); Helpers.ThrowIfNull (builder, "builder"); GrammarBuilder grammar = new GrammarBuilder (choices); grammar.Append (builder); return grammar; } /// /// /// /// /// ///public static GrammarBuilder operator + (GrammarBuilder builder, Choices choices) { return Add (builder, choices); } /// /// /// /// /// ///public static GrammarBuilder Add (GrammarBuilder builder, Choices choices) { Helpers.ThrowIfNull (builder, "builder"); Helpers.ThrowIfNull (choices, "choices"); GrammarBuilder grammar = builder.Clone (); grammar.Append (choices); return grammar; } /// /// /// /// /// ///public static GrammarBuilder operator + (GrammarBuilder builder1, GrammarBuilder builder2) { return Add (builder1, builder2); } /// /// /// /// /// ///public static GrammarBuilder Add (GrammarBuilder builder1, GrammarBuilder builder2) { Helpers.ThrowIfNull (builder1, "builder1"); Helpers.ThrowIfNull (builder2, "builder2"); GrammarBuilder grammar = builder1.Clone (); grammar.Append (builder2); return grammar; } /// /// TODOC /// /// ///public static implicit operator GrammarBuilder (string phrase) { return new GrammarBuilder (phrase); } /// /// TODOC /// /// ///public static implicit operator GrammarBuilder (Choices choices) { return new GrammarBuilder (choices); } /// /// TODOC /// /// ///public static implicit operator GrammarBuilder (SemanticResultKey semanticKey) { return new GrammarBuilder (semanticKey); } /// /// TODOC /// /// ///public static implicit operator GrammarBuilder (SemanticResultValue semanticValue) { return new GrammarBuilder (semanticValue); } #endregion //******************************************************************* // // Internal Methods // //******************************************************************* #region Internal Methods /// /// /// /// /// /// /// static internal void ValidateRepeatArguments (int minRepeat, int maxRepeat, string minParamName, string maxParamName) { if (minRepeat < 0) { throw new ArgumentOutOfRangeException (minParamName, SR.Get (SRID.InvalidMinRepeat, minRepeat)); } if (minRepeat > maxRepeat) { throw new ArgumentException (SR.Get (SRID.MinGreaterThanMax), maxParamName); } } ////// /// /// /// static internal void ValidateSubsetMatchingCriteriaArgument (SubsetMatchingMode subsetMatchingCriteria, string paramName) { switch (subsetMatchingCriteria) { case SubsetMatchingMode.OrderedSubset: case SubsetMatchingMode.OrderedSubsetContentRequired: case SubsetMatchingMode.Subsequence: case SubsetMatchingMode.SubsequenceContentRequired: break; default: throw new ArgumentException (SR.Get (SRID.EnumInvalid, paramName), paramName); } } ////// /// /// internal void CreateGrammar (IElementFactory elementFactory) { // Create a new Identifier Collection which will provide unique ids // for each rule IdentifierCollection ruleIds = new IdentifierCollection (); elementFactory.Grammar.Culture = Culture; _grammarBuilder.CreateElement (elementFactory, null, null, ruleIds); } ////// /// /// internal void Compile (Stream stream) { Backend backend = new Backend (); #if !NO_STG CustomGrammar cg = new CustomGrammar (); SrgsElementCompilerFactory elementFactory = new SrgsElementCompilerFactory (backend, cg); #else SrgsElementCompilerFactory elementFactory = new SrgsElementCompilerFactory(backend); #endif CreateGrammar (elementFactory); // Optimize in-memory graph representation of the grammar. backend.Optimize (); using (StreamMarshaler streamHelper = new StreamMarshaler (stream)) { backend.Commit (streamHelper); } stream.Position = 0; } internal GrammarBuilder Clone () { GrammarBuilder builder = new GrammarBuilder (); builder._grammarBuilder = (InternalGrammarBuilder) _grammarBuilder.Clone (); return builder; } #endregion //******************************************************************* // // Internal Properties // //******************************************************************** #region Internal Properties internal virtual string DebugSummary { get { StringBuilder sb = new StringBuilder (); foreach (GrammarBuilderBase item in InternalBuilder.Items) { if (sb.Length > 0) { sb.Append (' '); } sb.Append (item.DebugSummary); } return sb.ToString (); } } internal BuilderElements InternalBuilder { get { return _grammarBuilder; } } #endregion //******************************************************************* // // Private Methods // //******************************************************************** #region Private Methods ////// /// private void AddItem (GrammarBuilderBase item) { InternalBuilder.Items.Add (item.Clone ()); } #endregion //******************************************************************** // // Private Fields // //******************************************************************* #region Private Fields private InternalGrammarBuilder _grammarBuilder; private CultureInfo _culture = CultureInfo.CurrentUICulture; #endregion //******************************************************************** // // Private Type // //******************************************************************* #region Private Type ////// /// private class InternalGrammarBuilder : BuilderElements { //******************************************************************* // // Internal Methods // //******************************************************************* #region Internal Methods ////// /// ///internal override GrammarBuilderBase Clone () { InternalGrammarBuilder newGrammarbuilder = new InternalGrammarBuilder (); foreach (GrammarBuilderBase i in Items) { newGrammarbuilder.Items.Add (i.Clone ()); } return newGrammarbuilder; } /// /// /// /// /// /// /// ///internal override IElement CreateElement (IElementFactory elementFactory, IElement parent, IRule rule, IdentifierCollection ruleIds) { Collection newRules = new Collection (); CalcCount (null); Optimize (newRules); foreach (GrammarBuilderBase baseRule in newRules) { Items.Add (baseRule); } // The id of the root rule string rootId = ruleIds.CreateNewIdentifier ("root"); // Set the grammar's root rule elementFactory.Grammar.Root = rootId; elementFactory.Grammar.TagFormat = System.Speech.Recognition.SrgsGrammar.SrgsTagFormat.KeyValuePairs; // Create the root rule IRule root = elementFactory.Grammar.CreateRule (rootId, RulePublic.False, RuleDynamic.NotSet, false); // Create all the rules foreach (GrammarBuilderBase item in Items) { if (item is RuleElement) { item.CreateElement (elementFactory, root, root, ruleIds); } } // Create an item which represents the grammar foreach (GrammarBuilderBase item in Items) { if (!(item is RuleElement)) { IElement element = item.CreateElement (elementFactory, root, root, ruleIds); if (element != null) { element.PostParse (root); elementFactory.AddElement (root, element); } } } // Post parse the root rule root.PostParse (elementFactory.Grammar); elementFactory.Grammar.PostParse (null); return null; } #endregion } #endregion } } // 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
- UITypeEditor.cs
- JpegBitmapDecoder.cs
- HwndTarget.cs
- SwitchElementsCollection.cs
- ErrorTolerantObjectWriter.cs
- FeatureManager.cs
- ButtonField.cs
- TypeSystem.cs
- CompiledQuery.cs
- WeakRefEnumerator.cs
- documentsequencetextview.cs
- StrongNameKeyPair.cs
- NumericPagerField.cs
- DoWhileDesigner.xaml.cs
- UrlAuthorizationModule.cs
- Hashtable.cs
- PkcsMisc.cs
- RectangleHotSpot.cs
- CollectionTypeElement.cs
- StringResourceManager.cs
- DocumentSequenceHighlightLayer.cs
- CacheChildrenQuery.cs
- WCFServiceClientProxyGenerator.cs
- AdRotator.cs
- TokenizerHelper.cs
- DetailsViewDeleteEventArgs.cs
- AppSecurityManager.cs
- XPathAncestorQuery.cs
- SR.Designer.cs
- XhtmlBasicCommandAdapter.cs
- _Events.cs
- ApplicationBuildProvider.cs
- MarkupCompiler.cs
- DescendantBaseQuery.cs
- TreeNodeBindingCollection.cs
- WebPartConnection.cs
- SelectionBorderGlyph.cs
- EntityCommandCompilationException.cs
- HttpContext.cs
- ClientTargetSection.cs
- Matrix.cs
- QilXmlWriter.cs
- UrlParameterWriter.cs
- PagesChangedEventArgs.cs
- SessionChannels.cs
- SimpleApplicationHost.cs
- Timeline.cs
- AttributeParameterInfo.cs
- TypePropertyEditor.cs
- DataPagerFieldCommandEventArgs.cs
- PackageDigitalSignatureManager.cs
- DesignerToolboxInfo.cs
- CompositeScriptReference.cs
- WebPartConnectionsCancelVerb.cs
- RestClientProxyHandler.cs
- XmlElementList.cs
- DataObjectCopyingEventArgs.cs
- BinaryObjectInfo.cs
- EmbeddedMailObject.cs
- DmlSqlGenerator.cs
- ComboBoxItem.cs
- TextElementEnumerator.cs
- PipeStream.cs
- TouchEventArgs.cs
- ValueSerializer.cs
- Converter.cs
- VSDExceptions.cs
- ProfileBuildProvider.cs
- Baml2006KnownTypes.cs
- HTMLTextWriter.cs
- CultureInfoConverter.cs
- RegexCompilationInfo.cs
- SetUserLanguageRequest.cs
- FormatVersion.cs
- WaveHeader.cs
- Attributes.cs
- UserControl.cs
- MarkedHighlightComponent.cs
- GuidConverter.cs
- RuleProcessor.cs
- BamlLocalizer.cs
- ADMembershipProvider.cs
- Interlocked.cs
- Mutex.cs
- RC2CryptoServiceProvider.cs
- GeometryHitTestResult.cs
- WmlCommandAdapter.cs
- SchemaMerger.cs
- DataGridRelationshipRow.cs
- CodeSnippetTypeMember.cs
- ChangeInterceptorAttribute.cs
- GridSplitterAutomationPeer.cs
- DataGridCommandEventArgs.cs
- ReversePositionQuery.cs
- FilterElement.cs
- XamlPointCollectionSerializer.cs
- PrePostDescendentsWalker.cs
- VScrollProperties.cs
- GenericIdentity.cs
- CommandEventArgs.cs