public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            if (!isRequestFormatter)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.FormatterCannotBeUsedForRequestMessages)));
            }
            Message message = Message.CreateMessage(messageVersion, (string)null, CreateBodyWriter(parameters[0]));

            if (parameters[0] == null)
            {
                SuppressRequestEntityBody(message);
            }
            AttachMessageProperties(message, true);
            return(message);
        }
        void ValidateWorkflowRuntime(WorkflowRuntime workflowRuntime)
        {
            if (workflowRuntime.IsStarted)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.WorkflowRuntimeStartedBeforeHostOpen)));
            }

            WorkflowSchedulerService workflowSchedulerService = workflowRuntime.GetService <WorkflowSchedulerService>();

            if (!(workflowSchedulerService is SynchronizationContextWorkflowSchedulerService))
            {
                if (workflowSchedulerService != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.WrongSchedulerServiceRegistered)));
                }
                workflowRuntime.AddService(new SynchronizationContextWorkflowSchedulerService());
            }
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            WorkflowDefinitionContext workflowDefinitionContext = null;

            Stream workflowDefinitionStream = null;
            Stream ruleDefinitionStream     = null;

            if (string.IsNullOrEmpty(constructorString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.WorkflowServiceHostFactoryConstructorStringNotProvided)));
            }

            if (!HostingEnvironment.IsHosted)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.ProcessNotExecutingUnderHostedContext)));
            }

            Type workflowType = this.GetTypeFromString(constructorString, baseAddresses);

            if (workflowType != null)
            {
                workflowDefinitionContext = new CompiledWorkflowDefinitionContext(workflowType);
            }
            else
            {
                try
                {
                    IDisposable impersonationContext = null;
                    try
                    {
                        try
                        {
                        }
                        finally
                        {
                            //Ensure thread.Abort doesnt interfere b/w impersonate & assignment.
                            impersonationContext = HostingEnvironment.Impersonate();
                        }

                        string xomlVirtualPath = Path.Combine(AspNetEnvironment.Current.CurrentVirtualPath, constructorString);

                        if (HostingEnvironment.VirtualPathProvider.FileExists(xomlVirtualPath))
                        {
                            workflowDefinitionStream = HostingEnvironment.VirtualPathProvider.GetFile(xomlVirtualPath).Open();
                            string ruleFilePath = Path.ChangeExtension(xomlVirtualPath, WorkflowServiceBuildProvider.ruleFileExtension);

                            if (HostingEnvironment.VirtualPathProvider.FileExists(ruleFilePath))
                            {
                                ruleDefinitionStream      = HostingEnvironment.VirtualPathProvider.GetFile(ruleFilePath).Open();
                                workflowDefinitionContext = new StreamedWorkflowDefinitionContext(workflowDefinitionStream, ruleDefinitionStream, this.typeProvider);
                            }
                            else
                            {
                                workflowDefinitionContext = new StreamedWorkflowDefinitionContext(workflowDefinitionStream, null, this.typeProvider);
                            }
                        }
                    }
                    finally
                    {
                        if (impersonationContext != null)
                        {
                            impersonationContext.Dispose();
                        }
                    }
                }
                catch
                {
                    throw; //Prevent impersonation leak through Exception Filters.
                }
                finally
                {
                    if (workflowDefinitionStream != null)
                    {
                        workflowDefinitionStream.Close();
                    }

                    if (ruleDefinitionStream != null)
                    {
                        ruleDefinitionStream.Close();
                    }
                }
            }

            if (workflowDefinitionContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.CannotResolveConstructorStringToWorkflowType, constructorString)));
            }

            WorkflowServiceHost serviceHost = new WorkflowServiceHost(workflowDefinitionContext, baseAddresses);

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WorkflowServiceHostCreated, SR.GetString(SR.TraceCodeWorkflowServiceHostCreated), this);
            }
            return(serviceHost);
        }
 public override long Seek(long offset, SeekOrigin origin)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.XmlWriterBackedStreamMethodNotSupported, "Seek")));
 }
Beispiel #5
0
        internal static ReceiveContext GetReceiveContext(Activity activity,
                                                         string contextName,
                                                         string ownerActivityName)
        {
            if (activity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
            }
            if (string.IsNullOrEmpty(contextName))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("contextToken",
                                                                             SR2.GetString(SR2.Error_ArgumentValueNullOrEmptyString));
            }

            Activity contextActivity = activity.ContextActivity;
            Activity owner           = null;

            if (contextActivity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(SR2.GetString(SR2.Error_ContextOwnerActivityMissing)));
            }

            if (string.IsNullOrEmpty(ownerActivityName))
            {
                owner = contextActivity.RootActivity;
            }
            else
            {
                while (contextActivity != null)
                {
                    owner = contextActivity.GetActivityByName(ownerActivityName, true);
                    if (owner != null)
                    {
                        break;
                    }

                    contextActivity = contextActivity.Parent;
                    if (contextActivity != null)
                    {
                        contextActivity = contextActivity.ContextActivity;
                    }
                }
            }

            if (owner == null)
            {
                owner = Helpers.ParseActivityForBind(activity, ownerActivityName);
            }

            if (owner == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(SR2.GetString(SR2.Error_ContextOwnerActivityMissing)));
            }

            ReceiveContextCollection collection =
                owner.GetValue(ReceiveContextCollection.ReceiveContextCollectionProperty) as ReceiveContextCollection;

            if (collection == null)
            {
                return(null);
            }

            if (!collection.Contains(contextName))
            {
                return(null);
            }

            ReceiveContext receiveContext = collection[contextName];

            receiveContext.EnsureInitialized(owner.ContextGuid);

            return(receiveContext);
        }
 public override int Read(byte[] buffer, int offset, int count)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.XmlWriterBackedStreamMethodNotSupported, "Read")));
 }
 public override int EndRead(IAsyncResult asyncResult)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.XmlWriterBackedStreamMethodNotSupported, "EndRead")));
 }
        public override ValidationErrorCollection Validate(
            ValidationManager manager,
            object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            ReceiveActivity receiveActivity = obj as ReceiveActivity;

            if (receiveActivity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("obj",
                                                                             SR2.GetString(SR2.Error_ArgumentTypeInvalid, "obj", typeof(ReceiveActivity)));
            }

            ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider;

            if (typeProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                              SR2.GetString(SR2.General_MissingService, typeof(ITypeProvider).Name)));
            }

            if (receiveActivity.ServiceOperationInfo == null)
            {
                validationErrors.Add(
                    new ValidationError(
                        SR2.GetString(SR2.Error_Validation_OperationInfoNotSpecified, receiveActivity.Name),
                        WorkflowServicesErrorNumbers.Error_OperationInfoNotSpecified,
                        false,
                        "ServiceOperationInfo"));
            }
            else
            {
                // validate operation info
                //
                ValidationErrorCollection operationInfoValidationErrors =
                    ValidationHelper.ValidateOperationInfo(
                        receiveActivity,
                        receiveActivity.ServiceOperationInfo,
                        manager);

                validationErrors.AddRange(operationInfoValidationErrors);

                // do not validate parameter binding if the operation info is not valid
                // we might generate noise and false positives.
                //
                if (operationInfoValidationErrors.Count == 0)
                {
                    validationErrors.AddRange(
                        ValidationHelper.ValidateParameterBindings(receiveActivity, receiveActivity.ServiceOperationInfo,
                                                                   receiveActivity.ParameterBindings, manager));
                }

                // validate the context token
                //
                validationErrors.AddRange(
                    ValidationHelper.ValidateContextToken(receiveActivity, receiveActivity.ContextToken, manager));
            }

            // Check if the validation for all service operations being implemented
            // has been done previously.
            // If it has been done once then ServiceOperationsImplementedValidationMarker
            // will be on the context stack.
            //
            if (validationErrors.Count == 0 &&
                manager.Context[typeof(ServiceOperationsImplementedValidationMarker)] == null)
            {
                Activity rootActivity = receiveActivity;
                while (rootActivity.Parent != null)
                {
                    rootActivity = rootActivity.Parent;
                }

                validationErrors.AddRange(
                    ValidationHelper.ValidateAllServiceOperationsImplemented(
                        manager,
                        rootActivity));
            }

            return(validationErrors);
        }
        public string SelectOperation(ref Message message)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            bool   uriMatched;
            string result = this.SelectOperation(ref message, out uriMatched);

#pragma warning disable 56506 // [....], Message.Properties is never null
            message.Properties.Add(HttpOperationSelectorUriMatchedPropertyName, uriMatched);
#pragma warning restore 56506
            if (result != null)
            {
                message.Properties.Add(HttpOperationNamePropertyName, result);
                if (DiagnosticUtility.ShouldTraceInformation)
                {
#pragma warning disable 56506 // [....], Message.Headers is never null
                    TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.WebRequestMatchesOperation, SR2.GetString(SR2.TraceCodeWebRequestMatchesOperation, message.Headers.To, result));
#pragma warning restore 56506
                }
            }
            return(result);
        }
        protected virtual object ReadObject(Message message)
        {
            if (HttpStreamFormatter.IsEmptyMessage(message))
            {
                return(null);
            }
            XmlObjectSerializer[] inputSerializers = GetInputSerializers();
            XmlDictionaryReader   reader           = message.GetReaderAtBodyContents();

            if (inputSerializers != null)
            {
                for (int i = 0; i < inputSerializers.Length; ++i)
                {
                    if (inputSerializers[i].IsStartObject(reader))
                    {
                        return(inputSerializers[i].ReadObject(reader, false));
                    }
                }
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR2.GetString(SR2.CannotDeserializeBody, reader.LocalName, reader.NamespaceURI, operationName, contractName, contractNs, this.serializerType)));
        }
        public void DeserializeRequest(Message message, object[] parameters)
        {
            if (!isRequestFormatter)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.FormatterCannotBeUsedForRequestMessages)));
            }

            parameters[0] = ReadObject(message);
        }
        BodyWriter CreateBodyWriter(object body)
        {
            XmlObjectSerializer serializer;

            if (body != null)
            {
                serializer = GetOutputSerializer(body.GetType());
                if (serializer == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.CannotSerializeType, body.GetType(), this.operationName, this.contractName, this.contractNs, this.serializerType)));
                }
            }
            else
            {
                serializer = null;
            }
            return(new SingleParameterBodyWriter(body, serializer));
        }
        public static SingleBodyParameterMessageFormatter CreateJsonFormatter(OperationDescription operation, Type type, bool isRequestFormatter)
        {
            DataContractSerializerOperationBehavior dcsob = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();

            if (dcsob == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.JsonFormatRequiresDataContract, operation.Name, operation.DeclaringContract.Name, operation.DeclaringContract.Namespace)));
            }
            return(new SingleBodyParameterDataContractMessageFormatter(operation, type, isRequestFormatter, true, dcsob));
        }
        public static SingleBodyParameterMessageFormatter CreateXmlFormatter(OperationDescription operation, Type type, bool isRequestFormatter, UnwrappedTypesXmlSerializerManager xmlSerializerManager)
        {
            DataContractSerializerOperationBehavior dcsob = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();

            if (dcsob != null)
            {
                return(new SingleBodyParameterDataContractMessageFormatter(operation, type, isRequestFormatter, false, dcsob));
            }
            XmlSerializerOperationBehavior xsob = operation.Behaviors.Find <XmlSerializerOperationBehavior>();

            if (xsob != null)
            {
                return(new SingleBodyParameterXmlSerializerMessageFormatter(operation, type, isRequestFormatter, xsob, xmlSerializerManager));
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.OnlyDataContractAndXmlSerializerTypesInUnWrappedMode, operation.Name)));
        }
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            WebOperationContext        currentContext   = WebOperationContext.Current;
            OutgoingWebResponseContext outgoingResponse = null;

            if (currentContext != null)
            {
                outgoingResponse = currentContext.OutgoingResponse;
            }

            WebMessageFormat format = this.defaultFormat;

            if (outgoingResponse != null)
            {
                WebMessageFormat?nullableFormat = outgoingResponse.Format;
                if (nullableFormat.HasValue)
                {
                    format = nullableFormat.Value;
                }
            }

            if (!this.formatters.ContainsKey(format))
            {
                string operationName = "<null>";

                if (OperationContext.Current != null)
                {
                    MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties;
                    if (messageProperties.ContainsKey(WebHttpDispatchOperationSelector.HttpOperationNamePropertyName))
                    {
                        operationName = messageProperties[WebHttpDispatchOperationSelector.HttpOperationNamePropertyName] as string;
                    }
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.OperationDoesNotSupportFormat, operationName, format.ToString())));
            }

            if (outgoingResponse != null && string.IsNullOrEmpty(outgoingResponse.ContentType))
            {
                string automatedSelectionContentType = outgoingResponse.AutomatedFormatSelectionContentType;
                if (!string.IsNullOrEmpty(automatedSelectionContentType))
                {
                    // Don't set the content-type if it is default xml for backwards compatiabilty
                    if (!string.Equals(automatedSelectionContentType, defaultContentTypes[WebMessageFormat.Xml], StringComparison.OrdinalIgnoreCase))
                    {
                        outgoingResponse.ContentType = automatedSelectionContentType;
                    }
                }
                else
                {
                    // Don't set the content-type if it is default xml for backwards compatiabilty
                    if (format != WebMessageFormat.Xml)
                    {
                        outgoingResponse.ContentType = defaultContentTypes[format];
                    }
                }
            }

            Message message = this.formatters[format].SerializeReply(messageVersion, parameters, result);

            return(message);
        }
        public WebHttpDispatchOperationSelector(ServiceEndpoint endpoint)
        {
            if (endpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
            }
            if (endpoint.Address == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                              SR2.GetString(SR2.EndpointAddressCannotBeNull)));
            }
#pragma warning disable 56506 // [....], endpoint.Address.Uri is never null
            Uri baseUri = endpoint.Address.Uri;
            this.methodSpecificTables = new Dictionary <string, UriTemplateTable>();
            this.templates            = new Dictionary <string, UriTemplate>();
#pragma warning restore 56506

            WebHttpBehavior webHttpBehavior = endpoint.Behaviors.Find <WebHttpBehavior>();
            if (webHttpBehavior != null && webHttpBehavior.HelpEnabled)
            {
                this.helpUriTable = new UriTemplateTable(endpoint.ListenUri, HelpPage.GetOperationTemplatePairs());
            }

            Dictionary <WCFKey, string> alreadyHaves = new Dictionary <WCFKey, string>();

#pragma warning disable 56506 // [....], endpoint.Contract is never null
            foreach (OperationDescription od in endpoint.Contract.Operations)
#pragma warning restore 56506
            {
                // ignore callback operations
                if (od.Messages[0].Direction == MessageDirection.Input)
                {
                    string method = WebHttpBehavior.GetWebMethod(od);
                    string path   = UriTemplateClientFormatter.GetUTStringOrDefault(od);

                    //

                    if (UriTemplateHelpers.IsWildcardPath(path) && (method == WebHttpBehavior.WildcardMethod))
                    {
                        if (this.catchAllOperationName != "")
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                      new InvalidOperationException(
                                          SR2.GetString(SR2.MultipleOperationsInContractWithPathMethod,
                                                        endpoint.Contract.Name, path, method)));
                        }
                        this.catchAllOperationName = od.Name;
                    }
                    UriTemplate ut     = new UriTemplate(path);
                    WCFKey      wcfKey = new WCFKey(ut, method);
                    if (alreadyHaves.ContainsKey(wcfKey))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      SR2.GetString(SR2.MultipleOperationsInContractWithPathMethod,
                                                    endpoint.Contract.Name, path, method)));
                    }
                    alreadyHaves.Add(wcfKey, od.Name);

                    UriTemplateTable methodSpecificTable;
                    if (!methodSpecificTables.TryGetValue(method, out methodSpecificTable))
                    {
                        methodSpecificTable = new UriTemplateTable(baseUri);
                        methodSpecificTables.Add(method, methodSpecificTable);
                    }

                    methodSpecificTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, object>(ut, od.Name));
                    this.templates.Add(od.Name, ut);
                }
            }

            if (this.methodSpecificTables.Count == 0)
            {
                this.methodSpecificTables = null;
            }
            else
            {
                // freeze all the tables because they should not be modified after this point
                foreach (UriTemplateTable table in this.methodSpecificTables.Values)
                {
                    table.MakeReadOnly(true /* allowDuplicateEquivalentUriTemplates */);
                }

                if (!methodSpecificTables.TryGetValue(WebHttpBehavior.WildcardMethod, out wildcardTable))
                {
                    wildcardTable = null;
                }
            }
        }
        internal MessageHelpInformation(OperationDescription od, bool isRequest, Type type, bool wrapped)
        {
            this.Type         = type;
            this.SupportsJson = WebHttpBehavior.SupportsJsonFormat(od);
            string direction = isRequest ? SR2.GetString(SR2.HelpPageRequest) : SR2.GetString(SR2.HelpPageResponse);

            if (wrapped && !typeof(void).Equals(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsWrapped, direction);
                this.FormatString    = SR2.GetString(SR2.HelpPageUnknown);
            }
            else if (typeof(void).Equals(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsEmpty, direction);
                this.FormatString    = SR2.GetString(SR2.HelpPageNA);
            }
            else if (typeof(Message).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsMessage, direction);
                this.FormatString    = SR2.GetString(SR2.HelpPageUnknown);
            }
            else if (typeof(Stream).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsStream, direction);
                this.FormatString    = SR2.GetString(SR2.HelpPageUnknown);
            }
            else if (typeof(Atom10FeedFormatter).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Feed, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else if (typeof(Atom10ItemFormatter).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Entry, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else if (typeof(AtomPub10ServiceDocumentFormatter).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubServiceDocument, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else if (typeof(AtomPub10CategoriesDocumentFormatter).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubCategoriesDocument, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else if (typeof(Rss20FeedFormatter).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsRSS20Feed, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else if (typeof(SyndicationFeedFormatter).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsSyndication, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else if (typeof(XElement).IsAssignableFrom(type) || typeof(XmlElement).IsAssignableFrom(type))
            {
                this.BodyDescription = SR2.GetString(SR2.HelpPageIsXML, direction);
                this.FormatString    = WebMessageFormat.Xml.ToString();
            }
            else
            {
                try
                {
                    bool             usesXmlSerializer = od.Behaviors.Contains(typeof(XmlSerializerOperationBehavior));
                    XmlQualifiedName name;
                    this.SchemaSet = new XmlSchemaSet();
                    IDictionary <XmlQualifiedName, Type> knownTypes = new Dictionary <XmlQualifiedName, Type>();
                    if (usesXmlSerializer)
                    {
                        XmlReflectionImporter importer    = new XmlReflectionImporter();
                        XmlTypeMapping        typeMapping = importer.ImportTypeMapping(this.Type);
                        name = new XmlQualifiedName(typeMapping.ElementName, typeMapping.Namespace);
                        XmlSchemas        schemas  = new XmlSchemas();
                        XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
                        exporter.ExportTypeMapping(typeMapping);
                        foreach (XmlSchema schema in schemas)
                        {
                            this.SchemaSet.Add(schema);
                        }
                    }
                    else
                    {
                        XsdDataContractExporter exporter  = new XsdDataContractExporter();
                        List <Type>             listTypes = new List <Type>(od.KnownTypes);
                        bool isQueryable;
                        Type dataContractType = DataContractSerializerOperationFormatter.GetSubstituteDataContractType(this.Type, out isQueryable);
                        listTypes.Add(dataContractType);
                        exporter.Export(listTypes);
                        if (!exporter.CanExport(dataContractType))
                        {
                            this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema);
                            this.FormatString    = SR2.GetString(SR2.HelpPageUnknown);
                            return;
                        }
                        name = exporter.GetRootElementName(dataContractType);
                        DataContract typeDataContract = DataContract.GetDataContract(dataContractType);
                        if (typeDataContract.KnownDataContracts != null)
                        {
                            foreach (XmlQualifiedName dataContractName in typeDataContract.KnownDataContracts.Keys)
                            {
                                knownTypes.Add(dataContractName, typeDataContract.KnownDataContracts[dataContractName].UnderlyingType);
                            }
                        }
                        foreach (Type knownType in od.KnownTypes)
                        {
                            XmlQualifiedName knownTypeName = exporter.GetSchemaTypeName(knownType);
                            if (!knownTypes.ContainsKey(knownTypeName))
                            {
                                knownTypes.Add(knownTypeName, knownType);
                            }
                        }

                        foreach (XmlSchema schema in exporter.Schemas.Schemas())
                        {
                            this.SchemaSet.Add(schema);
                        }
                    }
                    this.SchemaSet.Compile();

                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        CloseOutput = false,
                        Indent      = true,
                    };

                    if (this.SupportsJson)
                    {
                        XDocument exampleDocument = new XDocument();
                        using (XmlWriter writer = XmlWriter.Create(exampleDocument.CreateWriter(), settings))
                        {
                            HelpExampleGenerator.GenerateJsonSample(this.SchemaSet, name, writer, knownTypes);
                        }
                        this.JsonExample = exampleDocument.Root;
                    }

                    if (name.Namespace != "http://schemas.microsoft.com/2003/10/Serialization/")
                    {
                        foreach (XmlSchema schema in this.SchemaSet.Schemas(name.Namespace))
                        {
                            this.Schema = schema;
                        }
                    }

                    XDocument XmlExampleDocument = new XDocument();
                    using (XmlWriter writer = XmlWriter.Create(XmlExampleDocument.CreateWriter(), settings))
                    {
                        HelpExampleGenerator.GenerateXmlSample(this.SchemaSet, name, writer);
                    }
                    this.XmlExample = XmlExampleDocument.Root;
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema);
                    this.FormatString    = SR2.GetString(SR2.HelpPageUnknown);
                    this.Schema          = null;
                    this.JsonExample     = null;
                    this.XmlExample      = null;
                }
            }
        }
        void SetFormatFromDefault(string operationName, string acceptHeader)
        {
            Fx.Assert(this.formatters.ContainsKey(operationName), "The calling method is responsible for ensuring that the 'operationName' key exists in the formatters dictionary.");
            WebMessageFormat format = this.formatters[operationName].DefaultFormat;

            if (!string.IsNullOrEmpty(acceptHeader))
            {
                this.caches[operationName].AddOrUpdate(acceptHeader.ToUpperInvariant(), new FormatContentTypePair(format, null));
            }

            WebOperationContext.Current.OutgoingResponse.Format = format;

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AutomaticFormatSelectedOperationDefault, SR2.GetString(SR2.TraceCodeAutomaticFormatSelectedOperationDefault, format.ToString()));
            }
        }
 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.XmlWriterBackedStreamMethodNotSupported, "BeginRead")));
 }
        void SetFormatAndContentType(WebMessageFormat format, string contentType)
        {
            OutgoingWebResponseContext outgoingResponse = WebOperationContext.Current.OutgoingResponse;

            outgoingResponse.Format = format;
            outgoingResponse.AutomatedFormatSelectionContentType = contentType;

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.AutomaticFormatSelectedRequestBased, SR2.GetString(SR2.TraceCodeAutomaticFormatSelectedRequestBased, format.ToString(), contentType));
            }
        }
 public override int ReadByte()
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.XmlWriterBackedStreamMethodNotSupported, "ReadByte")));
 }
        public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
        {
            if (description == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description");
            }
            if (dispatch == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatch");
            }
            if (dispatch.Parent == null ||
                dispatch.Parent.ChannelDispatcher == null ||
                dispatch.Parent.ChannelDispatcher.Host == null ||
                dispatch.Parent.ChannelDispatcher.Host.Description == null ||
                dispatch.Parent.ChannelDispatcher.Host.Description.Behaviors == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.DispatchOperationInInvalidState)));
            }

            WorkflowRuntimeBehavior workflowRuntimeBehavior = dispatch.Parent.ChannelDispatcher.Host.Description.Behaviors.Find <WorkflowRuntimeBehavior>();

            if (workflowRuntimeBehavior == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.NoWorkflowRuntimeBehavior)));
            }

            dispatch.Invoker = new WorkflowOperationInvoker(description, this, workflowRuntimeBehavior.WorkflowRuntime, dispatch.Parent);
        }
 public override void SetLength(long value)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.XmlWriterBackedStreamMethodNotSupported, "SetLength")));
 }
Beispiel #24
0
        internal static string GenerateValidEtagFromString(string entityTag)
        {
            // This method will generate a valid entityTag from a string by doing the following:
            //   1) Adding surrounding double quotes if the string doesn't already start and end with them
            //   2) Escaping any internal double quotes that aren't already escaped (preceded with a backslash)
            //   3) If a string starts with a double quote but doesn't end with one, or vice-versa, then the
            //      double quote is considered internal and is escaped.

            if (string.IsNullOrEmpty(entityTag))
            {
                return(null);
            }

            if (entityTag.StartsWith("W/\"", StringComparison.OrdinalIgnoreCase) &&
                entityTag.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                              SR2.GetString(SR2.WeakEntityTagsNotSupported, entityTag)));
            }

            List <int> escapeCharacterInsertIndices = null;
            int        lastEtagIndex   = entityTag.Length - 1;
            bool       startsWithQuote = entityTag[0] == '\"';
            bool       endsWithQuote   = entityTag[lastEtagIndex] == '\"';

            // special case where the entityTag is a single character, a double quote, '"'
            if (lastEtagIndex == 0 && startsWithQuote)
            {
                endsWithQuote = false;
            }

            bool needsSurroundingQuotes = !startsWithQuote || !endsWithQuote;

            if (startsWithQuote && !endsWithQuote)
            {
                if (escapeCharacterInsertIndices == null)
                {
                    escapeCharacterInsertIndices = new List <int>();
                }
                escapeCharacterInsertIndices.Add(0);
            }

            for (int x = 1; x < lastEtagIndex; x++)
            {
                if (entityTag[x] == '\"' && entityTag[x - 1] != '\\')
                {
                    if (escapeCharacterInsertIndices == null)
                    {
                        escapeCharacterInsertIndices = new List <int>();
                    }
                    escapeCharacterInsertIndices.Add(x + escapeCharacterInsertIndices.Count);
                }
            }

            // Possible that the ending internal quote is already escaped so must check the character before it
            if (!startsWithQuote && endsWithQuote && entityTag[lastEtagIndex - 1] != '\\')
            {
                if (escapeCharacterInsertIndices == null)
                {
                    escapeCharacterInsertIndices = new List <int>();
                }
                escapeCharacterInsertIndices.Add(lastEtagIndex + escapeCharacterInsertIndices.Count);
            }

            if (needsSurroundingQuotes || escapeCharacterInsertIndices != null)
            {
                int           escapeCharacterInsertIndicesCount = (escapeCharacterInsertIndices == null) ? 0 : escapeCharacterInsertIndices.Count;
                StringBuilder editedEtag = new StringBuilder(entityTag, entityTag.Length + escapeCharacterInsertIndicesCount + 2);
                for (int x = 0; x < escapeCharacterInsertIndicesCount; x++)
                {
                    editedEtag.Insert(escapeCharacterInsertIndices[x], '\\');
                }
                if (needsSurroundingQuotes)
                {
                    editedEtag.Insert(entityTag.Length + escapeCharacterInsertIndicesCount, '\"');
                    editedEtag.Insert(0, '\"');
                }
                entityTag = editedEtag.ToString();
            }

            return(entityTag);
        }
Beispiel #25
0
        static void RegisterReceiveContext(ReceiveActivity activity,
                                           Guid workflowId,
                                           string contextName,
                                           string ownerActivityName)
        {
            if (activity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
            }
            if (string.IsNullOrEmpty(contextName))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("contextName",
                                                                             SR2.GetString(SR2.Error_ArgumentValueNullOrEmptyString));
            }

            Activity contextActivity = activity.ContextActivity;
            Activity owner           = null;

            if (contextActivity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(SR2.GetString(SR2.Error_ContextOwnerActivityMissing)));
            }

            if (string.IsNullOrEmpty(ownerActivityName))
            {
                owner = contextActivity.RootActivity;
            }
            else
            {
                while (contextActivity != null)
                {
                    owner = contextActivity.GetActivityByName(ownerActivityName, true);
                    if (owner != null)
                    {
                        break;
                    }

                    contextActivity = contextActivity.Parent;
                    if (contextActivity != null)
                    {
                        contextActivity = contextActivity.ContextActivity;
                    }
                }
            }

            if (owner == null)
            {
                owner = Helpers.ParseActivityForBind(activity, ownerActivityName);
            }

            if (owner == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new InvalidOperationException(SR2.GetString(SR2.Error_ContextOwnerActivityMissing)));
            }

            ReceiveContextCollection collection =
                owner.GetValue(ReceiveContextCollection.ReceiveContextCollectionProperty) as ReceiveContextCollection;

            if (collection == null)
            {
                collection = new ReceiveContextCollection();
                owner.SetValue(ReceiveContextCollection.ReceiveContextCollectionProperty, collection);
            }

            if (!collection.Contains(contextName))
            {
                collection.Add(new ReceiveContext(contextName, workflowId, false));
            }
        }
 public void RegisterType(Object key, IList <Type> types)
 {
     if (key == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
     }
     if (types == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("types");
     }
     lock (thisLock)
     {
         if (this.serializersCreated)
         {
             Fx.Assert("An xml serializer type was added after the serializers were created");
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.XmlSerializersCreatedBeforeRegistration)));
         }
         for (int i = 0; i < types.Count; ++i)
         {
             if (!allTypes.ContainsKey(types[i]))
             {
                 allTypes.Add(types[i], importer.ImportTypeMapping(types[i]));
             }
         }
         operationTypes.Add(key, types);
     }
 }
        Type GetTypeFromString(string typeString, Uri[] baseAddresses)
        {
            if (baseAddresses == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAddresses");
            }
            if (baseAddresses.Length == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.BaseAddressesNotProvided)));
            }

            Type workflowType = Type.GetType(typeString, false);

            if (workflowType == null)
            {
                this.typeProvider = new TypeProvider(null);

                // retrieve the reference assembly names from the compiled string supplied by the build manager
                string compiledString;
                try
                {
                    IDisposable impersonationContext = null;
                    try
                    {
                        try
                        {
                        }
                        finally
                        {
                            //Ensure Impersonation + Assignment is atomic w.r.t to potential Thread.Abort.
                            impersonationContext = HostingEnvironment.Impersonate();
                        }
                        compiledString = BuildManager.GetCompiledCustomString(baseAddresses[0].AbsolutePath);
                    }
                    finally
                    {
                        if (impersonationContext != null)
                        {
                            impersonationContext.Dispose();
                        }
                    }
                }
                catch
                {
                    throw; //Prevent impersonation leak through exception filters.
                }

                if (string.IsNullOrEmpty(compiledString))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.InvalidCompiledString, baseAddresses[0].AbsolutePath)));
                }
                string[] components = compiledString.Split('|');
                if (components.Length < 3)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.InvalidCompiledString, baseAddresses[0].AbsolutePath)));
                }

                //Walk reverse direction to increase our chance to match assembly;
                for (int i = (components.Length - 1); i > 2; i--)
                {
                    Assembly assembly = Assembly.Load(components[i]);
                    this.typeProvider.AddAssembly(assembly);
                    workflowType = assembly.GetType(typeString, false);
                    if (workflowType != null)
                    {
                        break;
                    }
                }

                if (workflowType == null)
                {
                    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        this.typeProvider.AddAssembly(assembly);

                        workflowType = assembly.GetType(typeString, false);
                        if (workflowType != null)
                        {
                            break;
                        }
                    }
                }
            }
            return(workflowType);
        }
 public void DeserializeRequest(Message message, object[] parameters)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.SerializingRequestNotSupportedByFormatter, this)));
 }
 public override int GetArrayRank()
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
               SR2.GetString(SR2.Error_CurrentTypeNotAnArray));
 }
Beispiel #30
0
 public override string ToString()
 {
     return(String.Format(CultureInfo.InvariantCulture, SR2.GetString(SR2.WebBodyFormatPropertyToString, this.Format.ToString())));
 }