Code:
/ DotNET / DotNET / 8.0 / untmp / WIN_WINDOWS / lh_tools_devdiv_wpf / Windows / wcp / Speech / Src / Internal / SrgsCompiler / AppDomainGrammarProxy.cs / 1 / AppDomainGrammarProxy.cs
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
//
// Description:
// AppDomainProxy for the SrgsCompiler
//
// History:
// 10/1/2004 [....] Created
//----------------------------------------------------------------------------
#region Using directives
using System;
using System.Globalization;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Speech.Recognition;
using System.Speech.Recognition.SrgsGrammar;
using System.Text;
#endregion
#pragma warning disable 1634, 1691 // Allows suppression of certain PreSharp messages.
#pragma warning disable 56500 // Remove all the catch all statements warnings used by the interop layer
namespace System.Speech.Internal.SrgsCompiler
{
///
/// TODOC
///
internal class AppDomainGrammarProxy : MarshalByRefObject
{
internal SrgsRule [] OnInit (string method, object [] parameters, string onInitParameters, out Exception exceptionThrown)
{
exceptionThrown = null;
try
{
// If the onInitParameters are provided as a string, get the values as an array of value.
if (!string.IsNullOrEmpty (onInitParameters))
{
parameters = MatchInitParameters (method, onInitParameters, _rule, _rule);
}
// Find the constructor to call - there could be several
Type [] types = new Type [parameters != null ? parameters.Length : 0];
if (parameters != null)
{
for (int i = 0; i < parameters.Length; i++)
{
types [i] = parameters [i].GetType ();
}
}
MethodInfo onInit = _grammarType.GetMethod (method, types);
// If somehow we failed to find a constructor, let the system handle it
if (onInit == null)
{
throw new InvalidOperationException (SR.Get (SRID.ArgumentMismatch));
}
SrgsRule [] extraRules = null;
if (onInit != null)
{
_internetPermissionSet.PermitOnly ();
extraRules = (SrgsRule []) onInit.Invoke (_grammar, parameters);
}
return extraRules;
}
catch (Exception e)
{
exceptionThrown = e;
return null;
}
}
internal object OnRecognition (string method, object [] parameters, out Exception exceptionThrown)
{
exceptionThrown = null;
try
{
MethodInfo onRecognition = _grammarType.GetMethod (method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
// Execute the parse routine
_internetPermissionSet.PermitOnly ();
return onRecognition.Invoke (_grammar, parameters);
}
catch (Exception e)
{
exceptionThrown = e;
}
return null;
}
internal object OnParse (string rule, string method, object [] parameters, out Exception exceptionThrown)
{
exceptionThrown = null;
try
{
MethodInfo onParse;
System.Speech.Recognition.Grammar grammar;
GetRuleInstance (rule, method, out onParse, out grammar);
// Execute the parse routine
_internetPermissionSet.PermitOnly ();
return onParse.Invoke (grammar, parameters);
}
catch (Exception e)
{
exceptionThrown = e;
return null;
}
}
internal void OnError (string rule, string method, object [] parameters, out Exception exceptionThrown)
{
exceptionThrown = null;
try
{
MethodInfo onError;
System.Speech.Recognition.Grammar grammar;
GetRuleInstance (rule, method, out onError, out grammar);
// Execute the parse routine
_internetPermissionSet.PermitOnly ();
onError.Invoke (grammar, parameters);
}
catch (Exception e)
{
exceptionThrown = e;
}
}
internal void Init (string rule, byte [] il, byte [] pdb)
{
_assembly = Assembly.Load (il, pdb);
// Get the grammar class carrying the .Net Semantics code
_grammarType = GetTypeForRule (_assembly, rule);
// Something is Wrong if the grammar class cannot be found
if (_grammarType == null)
{
throw new FormatException (SR.Get (SRID.RecognizerRuleNotFoundStream, rule));
}
_rule = rule;
try
{
_grammar = (System.Speech.Recognition.Grammar) _assembly.CreateInstance (_grammarType.FullName);
}
catch (MissingMemberException)
{
throw new ArgumentException (SR.Get (SRID.RuleScriptInvalidParameters, _grammarType.FullName, rule), "rule");
}
_internetPermissionSet = PolicyLevel.CreateAppDomainLevel ().GetNamedPermissionSet ("Internet");
_internetPermissionSet.AddPermission (new ReflectionPermission (PermissionState.Unrestricted));
}
private void GetRuleInstance (string rule, string method, out MethodInfo onParse, out System.Speech.Recognition.Grammar grammar)
{
Type ruleClass = rule == _rule ? _grammarType : GetTypeForRule (_assembly, rule);
if (ruleClass == null || !ruleClass.IsSubclassOf (typeof (System.Speech.Recognition.Grammar)))
{
throw new FormatException (SR.Get (SRID.RecognizerInvalidBinaryGrammar));
}
try
{
grammar = ruleClass == _grammarType ? _grammar : (System.Speech.Recognition.Grammar) _assembly.CreateInstance (ruleClass.FullName);
}
catch (MissingMemberException)
{
throw new ArgumentException (SR.Get (SRID.RuleScriptInvalidParameters, ruleClass.FullName, rule), "rule");
}
onParse = grammar.MethodInfo (method);
}
static private Type GetTypeForRule (Assembly assembly, string rule)
{
Type [] types = assembly.GetTypes ();
for (int iType = 0; iType < types.Length; iType++)
{
Type type = types [iType];
if (type.Name == rule && type.IsPublic && type.IsSubclassOf (typeof (System.Speech.Recognition.Grammar)))
{
return type;
}
}
return null;
}
///
/// Construct a list of parameters from a sapi:params string.
///
///
///
///
///
///
private object [] MatchInitParameters (string method, string onInitParameters, string grammar, string rule)
{
MethodInfo [] mis = _grammarType.GetMethods ();
NameValuePair [] pairs = ParseInitParams (onInitParameters);
object [] values = new object [pairs.Length];
bool foundConstructor = false;
for (int iCtor = 0; iCtor < mis.Length && !foundConstructor; iCtor++)
{
if (mis [iCtor].Name != method)
{
continue;
}
ParameterInfo [] paramInfo = mis [iCtor].GetParameters ();
// Check if enough parameters are provided.
if (paramInfo.Length > pairs.Length)
{
continue;
}
foundConstructor = true;
for (int i = 0; i < pairs.Length && foundConstructor; i++)
{
NameValuePair pair = pairs [i];
// annonymous
if (pair._name == null)
{
values [i] = pair._value;
}
else
{
bool foundParameter = false;
for (int j = 0; j < paramInfo.Length; j++)
{
if (paramInfo [j].Name == pair._name)
{
values [j] = ParseValue (paramInfo [j].ParameterType, pair._value);
foundParameter = true;
break;
}
}
if (!foundParameter)
{
foundConstructor = false;
}
}
}
}
if (!foundConstructor)
{
throw new FormatException (SR.Get (SRID.CantFindAConstructor, grammar, rule, FormatConstructorParameters (mis, method)));
}
return values;
}
///
/// Parse the value for a type from a string to a strong type.
/// If the type does not support the Parse method then the operation fails.
///
///
///
///
private static object ParseValue (Type type, string value)
{
if (type == typeof (string))
{
return value;
}
return type.InvokeMember ("Parse", BindingFlags.InvokeMethod, null, null, new object [] { value }, CultureInfo.InvariantCulture);
}
///
/// Returns the list of the possible parameter names and type for a grammar
///
///
///
///
private static string FormatConstructorParameters (MethodInfo [] cis, string method)
{
StringBuilder sb = new StringBuilder ();
for (int iCtor = 0; iCtor < cis.Length; iCtor++)
{
if (cis [iCtor].Name == method)
{
sb.Append (sb.Length > 0 ? " or sapi:parms=\"" : "sapi:parms=\"");
ParameterInfo [] pis = cis [iCtor].GetParameters ();
for (int i = 0; i < pis.Length; i++)
{
if (i > 0)
{
sb.Append (';');
}
ParameterInfo pi = pis [i];
sb.Append (pi.Name);
sb.Append (':');
sb.Append (pi.ParameterType.Name);
}
sb.Append ("\"");
}
}
return sb.ToString ();
}
///
/// Split the init parameter strings into an array of name/values
/// The format must be "name:value". If the ':' then parameter is anonymous.
///
///
///
private static NameValuePair [] ParseInitParams (string initParameters)
{
string[] parameters = initParameters.Split(new char[] { ';' }, StringSplitOptions.None);
NameValuePair [] pairs = new NameValuePair [parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
string parameter = parameters [i];
int posColon = parameter.IndexOf (':');
if (posColon >= 0)
{
pairs [i]._name = parameter.Substring (0, posColon);
pairs [i]._value = parameter.Substring (posColon + 1);
}
else
{
pairs [i]._value = parameter;
}
}
return pairs;
}
#pragma warning disable 56524 // Arclist does not hold on any resouces
private System.Speech.Recognition.Grammar _grammar;
#pragma warning restore 56524 // Arclist does not hold on any resouces
private Assembly _assembly;
private string _rule;
private Type _grammarType;
private PermissionSet _internetPermissionSet;
private struct NameValuePair
{
internal string _name;
internal string _value;
}
}
}
// 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
- ObjectDataProvider.cs
- ObjectSpanRewriter.cs
- InertiaRotationBehavior.cs
- WizardPanel.cs
- BigInt.cs
- SmiConnection.cs
- IndentedWriter.cs
- Decorator.cs
- StorageComplexTypeMapping.cs
- ConnectionStringsExpressionBuilder.cs
- CompilerError.cs
- WebPartCollection.cs
- DataChangedEventManager.cs
- sqlnorm.cs
- XmlSchemaComplexContentRestriction.cs
- ITextView.cs
- GridViewSelectEventArgs.cs
- ReadWriteSpinLock.cs
- InputProviderSite.cs
- SecurityRuntime.cs
- _AutoWebProxyScriptHelper.cs
- COM2IProvidePropertyBuilderHandler.cs
- TemplateControlBuildProvider.cs
- Overlapped.cs
- RotateTransform3D.cs
- DataError.cs
- UIElementCollection.cs
- HostProtectionPermission.cs
- PerspectiveCamera.cs
- xmlglyphRunInfo.cs
- WhereaboutsReader.cs
- VirtualPathData.cs
- DataKeyArray.cs
- GenericRootAutomationPeer.cs
- WorkflowElementDialog.cs
- LiteralControl.cs
- BooleanExpr.cs
- ComponentCommands.cs
- ASCIIEncoding.cs
- NameService.cs
- AuthenticationModulesSection.cs
- DataGridViewRowStateChangedEventArgs.cs
- ReceiveActivity.cs
- RelationshipWrapper.cs
- UnsafeNativeMethodsCLR.cs
- TextRunCacheImp.cs
- XPathQilFactory.cs
- TreeNode.cs
- PeerDefaultCustomResolverClient.cs
- TimeSpanSecondsOrInfiniteConverter.cs
- Vector3DKeyFrameCollection.cs
- ClientSettingsSection.cs
- uribuilder.cs
- NavigationWindowAutomationPeer.cs
- ImageCodecInfoPrivate.cs
- InternalConfigSettingsFactory.cs
- LockedBorderGlyph.cs
- glyphs.cs
- arabicshape.cs
- CodeDOMUtility.cs
- x509utils.cs
- Helper.cs
- XmlSchemaComplexType.cs
- _NegotiateClient.cs
- DataSourceXmlSerializationAttribute.cs
- DependencyPropertyHelper.cs
- BaseInfoTable.cs
- FormViewPagerRow.cs
- WebConfigurationManager.cs
- StandardOleMarshalObject.cs
- PageAsyncTaskManager.cs
- ResXResourceReader.cs
- ListCollectionView.cs
- DBNull.cs
- CommandDevice.cs
- CollectionCodeDomSerializer.cs
- ApplicationDirectoryMembershipCondition.cs
- StylusTip.cs
- ReflectionTypeLoadException.cs
- NamedObject.cs
- HitTestDrawingContextWalker.cs
- EdmProviderManifest.cs
- TypeBrowser.xaml.cs
- DataFormats.cs
- GroupStyle.cs
- AffineTransform3D.cs
- Misc.cs
- XmlSchemaComplexContentExtension.cs
- DesignerCategoryAttribute.cs
- SQLInt16Storage.cs
- XsltSettings.cs
- TextElementEnumerator.cs
- Table.cs
- TemplatePropertyEntry.cs
- EventMap.cs
- Int16Animation.cs
- OutputCacheSettings.cs
- CorruptingExceptionCommon.cs
- DocumentXmlWriter.cs
- ReliabilityContractAttribute.cs