protected override bool CheckAccessCore(OperationContext operationContext) { operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = Thread.CurrentPrincipal; return base.CheckAccessCore(operationContext); }
public OperationContextScope(OperationContext context) { this.originalContext = OperationContext.Current; this.originalScope = currentScope; this.thread = Thread.CurrentThread; this.PushContext(context); }
public OperationContextScope(IContextChannel channel) { this.originalContext = OperationContext.Current; this.originalScope = currentScope; this.thread = Thread.CurrentThread; this.PushContext(new OperationContext(channel)); }
public override bool CheckAccess(OperationContext operationContext) { if(HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Contains("authservice")) { return true; } var token = GetToken(operationContext); if(AuthManager.ValidateToken(token)) { var principal = AuthManager.GetPrincipal(token); var roles = Roles.GetRolesForUser(principal.Username); CurrentUser = new AuthUser() { Identity = new AuthIdentity() { IsAuthenticated = true, Name = principal.Username, _id = principal.MemberID.ToString() }, Principal = principal, Roles = roles }; return true; } return false; }
protected override bool CheckAccessCore(OperationContext operationContext) { //LocDHT: need this to avoid Evaluate exception operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = System.Threading.Thread.CurrentPrincipal; // If this point is reached, return false to deny access. return true; }
internal static void LockInstanceAfterCallout(OperationContext operationContext) { if (operationContext != null) { InstanceContext instanceContext = operationContext.InstanceContext; if (operationContext.IsServiceReentrant) { ConcurrencyInstanceContextFacet resource = instanceContext.Concurrency; ThreadWaiter waiter = null; lock (instanceContext.ThisLock) { if (!resource.Locked) { resource.Locked = true; } else { waiter = new ThreadWaiter(); resource.EnqueueCalloutMessage(waiter); } } if (waiter != null) { waiter.Wait(); } } } }
///<summary>Returns the Method info for the method (OperationContract) that is called in this WCF request.</summary> System.Reflection.MethodInfo GetActionMethodInfo(OperationContext operationContext) { string bindingName = operationContext.EndpointDispatcher.ChannelDispatcher.BindingName; string methodName = string.Empty; if (bindingName.Contains("WebHttpBinding")) { //REST request methodName = (string)operationContext.IncomingMessageProperties["HttpOperationName"]; } else { //SOAP request string action = operationContext.IncomingMessageHeaders.Action; var operationDescription = operationContext.EndpointDispatcher.DispatchRuntime.Operations.FirstOrDefault(o => o.Action == action); if (operationDescription != null) methodName = operationDescription.Name; } System.Type hostType = operationContext.Host.Description.ServiceType; return hostType.GetMethod(methodName); }
/// <summary> /// Checks authorization for the given operation context based on default policy evaluation. /// </summary> /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext"/> for the current authorization request.</param> /// <returns> /// true if access is granted; otherwise, false. The default is true. /// </returns> protected override bool CheckAccessCore( OperationContext operationContext ) { string key = string.Empty; // Always allow the Help interface var properties = operationContext.RequestContext.RequestMessage.Properties; if ( properties["HttpOperationName"].ToString() == "HelpPageInvoke" ) return true; // If the user is currently logged in var currentUser = System.Web.Security.Membership.GetUser(); if ( currentUser != null ) return true; // Get the matched uriTemplate UriTemplateMatch template = properties["UriTemplateMatchResults"] as UriTemplateMatch; if (template != null && !string.IsNullOrEmpty(template.BoundVariables["apiKey"])) { // Get the apiKey value from the uriTemplate key = template.BoundVariables["apiKey"]; // Read the user Rock.Services.Cms.UserService userService = new Rock.Services.Cms.UserService(); Rock.Models.Cms.User user = userService.Queryable(). Where( u => u.ApiKey == key && u.IsApproved == true && u.IsLockedOut == false ). FirstOrDefault(); // Verify that the key is valid if ( user != null ) return true; } return false; }
/// <summary> /// Checks authorization for the given operation context when access to a message is required. /// </summary> /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext"/>.</param> /// <param name="message">The <see cref="T:System.ServiceModel.Channels.Message"/> to be examined to determine authorization.</param> /// <returns> /// true if access is granted; otherwise; otherwise false. The default is false. /// </returns> public override bool CheckAccess(OperationContext operationContext, ref Message message) { // set ServiceSecurityContext SetSecurityContext(operationContext); // grab ICP var principal = GetPrincipal(operationContext); // create custom ICP var customPrincipal = GetCustomPrincipal(operationContext, principal); if (customPrincipal != null) { SetPrincipal(operationContext, customPrincipal); principal = customPrincipal; } // optionally inspect message bool result = CheckMessage(ref message, operationContext, principal); if (result == false) { return false; } // call authZ Manager return CheckClaimsAuthorizationManager(operationContext); }
public ErrorEvent LogException(OperationContext context, int contactID, Exception exception, string comments) { String message = null; String stackTrace = null; ErrorEvent errorEvent = null; try { //Consolidate message and stackTraces of the exception and any/all of its inner exceptions. Util.ExceptionUtil.BuildStrings(exception, out message, out stackTrace); if (exception != null) errorEvent = CreateErrorEvent(context, contactID, message, stackTrace, comments, true); else errorEvent = CreateErrorEvent(context, contactID, null, null, comments, true); ErrorEventDbUtil.Write(errorEvent); } catch (Exception ex) { String ip = null; String source = "svc"; try { ip = GetHostName(); source = GetSource(context); } catch { } ExceptionUtil.HandleLoggingException(ex, contactID, source, ip, false); } return errorEvent; }
private void ReadContent(OperationContext context) { using (var reader = context.RequestContext.RequestMessage.GetReaderAtBodyContents()) { Content = reader.ReadOuterXml(); } }
/// <summary> /// Resolve the accessing service and operation contract. /// </summary> /// <param name="operationContext"></param> /// <returns></returns> public static WCFLookupResult ResolvePermissionAttribute(OperationContext operationContext) { Type serviceImplType = operationContext.EndpointDispatcher.DispatchRuntime.Type; Type[] interfaceTypes = serviceImplType.GetInterfaces(); if (WebOperationContext.Current.IncomingRequest.UriTemplateMatch == null) return null; object WCFLookupResult = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.Data; //string operationContractName = DataBinder.Eval(WCFLookupResult, "OperationName") as string; string operationContractName = WCFLookupResult.ToString() ; foreach (Type interfaceType in interfaceTypes) { object[] serviceContractAttributes = interfaceType.GetCustomAttributes(typeof(ServiceContractAttribute), true); if (serviceContractAttributes.Length == 0) continue; string serviceContractName = ((ServiceContractAttribute)serviceContractAttributes[0]).Name; MethodInfo operationMethod = GetOperationMethodByOperationContractName(interfaceType, operationContractName); if (operationMethod == null) continue; object[] permissionAttributes = operationMethod.GetCustomAttributes(typeof(PermissionAttribute), true); if (permissionAttributes.Length == 0) continue; return new WCFLookupResult(serviceContractName, operationContractName); } return null; }
/// <summary> /// Checks authorization for the given operation context based on policy evaluation. /// </summary> /// <param name="operationContext"> /// The operation context. /// </param> /// <returns> /// true if authorized, false otherwise /// </returns> protected override bool CheckAccessCore( OperationContext operationContext ) { var canAccess = false; var applicationVirtualRoot = HostingEnvironment.ApplicationVirtualPath; if ( applicationVirtualRoot == null ) { throw new ArgumentException ( "The application virtual root could not be found for the current environment." ); } // Remove the deployment environment specific application virtual root from the front of the resource request identifier. var path = applicationVirtualRoot.Equals ( @"/" ) ? operationContext.EndpointDispatcher.EndpointAddress.Uri.LocalPath : operationContext.EndpointDispatcher.EndpointAddress.Uri.LocalPath.Remove ( 0, applicationVirtualRoot.Length ); var currentClaimsPrincipalService = IoC.CurrentContainer.Resolve<ICurrentClaimsPrincipalService> (); var principal = currentClaimsPrincipalService.GetCurrentPrincipal (); if ( principal.Identity.IsAuthenticated ) { var accessControlManager = IoC.CurrentContainer.Resolve<IAccessControlManager> (); canAccess = accessControlManager.CanAccess ( new ResourceRequest { path } ); } else { Logger.Debug ( string.Format ( "Access to service '{0}' is denied because the principal is not authenticated.", path ) ); } return canAccess; }
public OperationContextScope (OperationContext context) { if (context == null) throw new ArgumentNullException ("context"); previous = OperationContext.Current; OperationContext.Current = context; }
public override bool CheckAccess(OperationContext operationContext, ref Message message) { base.CheckAccess(operationContext, ref message); string action = operationContext.IncomingMessageHeaders.Action; if (action == "urn:msdnmag/IService/GetRoles") { // messags in WCF are always read-once // we create one copy to work with, and one copy to return back to the plumbing MessageBuffer buffer = operationContext.RequestContext.RequestMessage.CreateBufferedCopy(int.MaxValue); message = buffer.CreateMessage(); // get the username vale using XPath XPathNavigator nav = buffer.CreateNavigator(); StandardNamespaceManager nsm = new StandardNamespaceManager(nav.NameTable); nsm.AddNamespace("msdn", "urn:msdnmag"); XPathNavigator node = nav.SelectSingleNode("s:Envelope/s:Body/msdn:GetRoles/msdn:username", nsm); string parameter = node.InnerXml; // check authorization if (operationContext.ServiceSecurityContext.PrimaryIdentity.Name == parameter) { return true; } else { return (GetPrincipal(operationContext).IsInRole("administrators")); } } return true; }
public void ReceiveAsyncReply(System.ServiceModel.OperationContext operationContext, Message reply, System.Exception replyException) { this.OperationContext = operationContext; this.exceptionOnReply = replyException; this.Reply = reply; this.receivedReplyEvent.Set(); }
public static PullNotificationHeader ParseHeader(OperationContext context) { try { int headerIndex = context.IncomingMessageHeaders.FindHeader(NOTIFICATION_HEADER_NAME, PULL_NOTIFICATION_NAMESPACE); if (headerIndex != -1) { XmlDictionaryReader reader = context.IncomingMessageHeaders.GetReaderAtHeader(headerIndex); if (reader.IsStartElement(NOTIFICATION_HEADER_NAME, PULL_NOTIFICATION_NAMESPACE)) { reader.ReadStartElement(); reader.MoveToContent(); if (reader.IsStartElement(ADDRESS_ELEMENT_NAME, PULL_NOTIFICATION_NAMESPACE)) { string address = reader.ReadElementContentAsString(); return new PullNotificationHeader(address); } } } return null; } catch (Exception excp) { logger.Error("Exception PullNotificationHeader ParseHeader. " + excp.Message); throw; } }
public MessageProcessingContext (OperationContext opCtx) { operation_context = opCtx; request_context = opCtx.RequestContext; incoming_message = opCtx.IncomingMessage; user_events_handler = new UserEventsHandler (this); }
private List<string> _roles; //Коллекция ролей пользователя. Служит для снижения нагрузки на базу данных при частых вызовах методов DataFeed() { _context = new EFDbContext(); operationContext = OperationContext.Current; operationContext.Channel.Opened += Channel_Opened; operationContext.Channel.Closed += Channel_Closed; info = new Info(); _uManager = new UManager(new UserStore<User>(new IdentityContext())); _user = _uManager.FindByName(operationContext.ServiceSecurityContext.PrimaryIdentity.Name); //Получаем текущего Identity пользователя var roles = _uManager.GetUserRoles(_user.Id); //Создадим список ролей пользователя к которым будем обращаться в методах для проверки, чтобы не загружать БД лишними запросами. _roles = roles.Select(r => r.Name).ToList(); _conCount = roles.Max(r => r.NumberOfThreads); //Установить максимальное количество потоков доступное из ролей данному пользователю _connector = GetAvialableConnector(); _connector.ValuesChanged += Level1Changed; _connector.MarketDepthsChanged += Level2Changed; _connector.NewNews += NewNews; _connector.Error += Error; Console.WriteLine("SID: {0} ", operationContext.Channel.SessionId); _listener = new Listener(operationContext); //Запускаем вторичные потоки для обработки исторических данных for (int i = 0; i < _conCount; i++) { new Task(_listener.CandlesQueueStart).Start(); } }
protected override bool CheckAccessCore(OperationContext operationContext) { string action = operationContext.RequestContext.RequestMessage.Headers.Action; // parse the name of the operation that it is being invoked. string operationName = action.Substring(action.LastIndexOf('/') + 1); var httpRequest = operationContext.IncomingMessageProperties["httpRequest"] as HttpRequestMessageProperty; var authorizationHeader = httpRequest.Headers["Authorization"]; if (string.IsNullOrEmpty(authorizationHeader)) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } string user; string password; this.ParseUserPasswordFromHeader(authorizationHeader, out user, out password); if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password)) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } var authorizationService = ObjectFactory.GetInstance<IAuthorizationService>(); if (!authorizationService.Authorize(user, operationName)) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } return true; }
// Define the set of policies taking part in chaining. We will provide // the safe default set (primary token + all supporting tokens except token with // with SecurityTokenAttachmentMode.Signed + transport token). Implementor // can override and provide different selection of policies set. protected virtual ReadOnlyCollection<IAuthorizationPolicy> GetAuthorizationPolicies(OperationContext operationContext) { SecurityMessageProperty security = operationContext.IncomingMessageProperties.Security; if (security == null) { return EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance; } ReadOnlyCollection<IAuthorizationPolicy> externalPolicies = security.ExternalAuthorizationPolicies; if (security.ServiceSecurityContext == null) { return externalPolicies ?? EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance; } ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = security.ServiceSecurityContext.AuthorizationPolicies; if (externalPolicies == null || externalPolicies.Count <= 0) { return authorizationPolicies; } // Combine List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(authorizationPolicies); policies.AddRange(externalPolicies); return policies.AsReadOnly(); }
public void UserContextProperties () { var ch = ChannelFactory<IFooChannel>.CreateChannel (new BasicHttpBinding (), new EndpointAddress ("http://localhost:" + NetworkHelpers.FindFreePort ())); var o = new OperationContext (ch); // FIXME: this is strange. It should return non-null value. // Assert.IsNull(o.Channel, "#1"); Assert.IsNull (o.EndpointDispatcher, "#2"); Assert.IsNull (o.Host, "#3"); Assert.IsFalse (o.HasSupportingTokens, "#4"); Assert.IsNull (o.IncomingMessageHeaders, "#5"); Assert.IsNull (o.IncomingMessageProperties, "#6"); Assert.IsNotNull (o.OutgoingMessageHeaders, "#7"); Assert.IsNotNull (o.OutgoingMessageProperties, "#8"); Assert.IsNull (o.InstanceContext, "#9"); Assert.IsTrue (o.IsUserContext, "#10"); Assert.IsNull (o.RequestContext, "#11"); Assert.IsNull (o.ServiceSecurityContext, "#12"); Assert.IsNull (o.SessionId, "#13"); Assert.IsNull (o.SupportingTokens, "#14"); }
public override bool CheckAccess(OperationContext operationContext, ref Message message) { // Open the request message using an xml reader XmlReader xr = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(0); // Split the URL at the API name--Parameters junction indicated by the '?' character - taking the first string will ignore all parameters string[] urlSplit = xr.ReadElementContentAsString().Split('/'); // Extract just the API name and rest of the URL, which will be the last item in the split using '/' string[] apiSplit = urlSplit[3].Split('?'); // Logging the username and API name Tracer.WriteUserLog(apiSplit[0] + " request from user: "******"CheckAccess: Authorized"); return true; } else { Tracer.WriteUserLog("CheckAccess: NOT Authorized"); return false; } }
// We will always get here before we executing the service facade public override bool CheckAccess(OperationContext operationContext, ref Message message) { // This service is for techers only // The function will look at all the claims of type http://schemas.microsoft.com/ws/2008/06/identity/claims/role return Thread.CurrentPrincipal.IsInRole("Teacher"); }
/// <summary> /// Create a new operation-context-preserving synchronization context. /// </summary> /// <param name="operationContext"> /// The operation context to propagate. /// </param> public OperationContextPreservingSynchronizationContext(OperationContext operationContext) { if (operationContext == null) throw new ArgumentNullException("operationContext"); _operationContext = operationContext; }
internal static void UnlockInstanceBeforeCallout(OperationContext operationContext) { if (operationContext != null && operationContext.IsServiceReentrant) { ConcurrencyBehavior.UnlockInstance(operationContext.InstanceContext); } }
public static SIPSorcerySecurityHeader ParseHeader(OperationContext context) { try { int headerIndex = context.IncomingMessageHeaders.FindHeader(SECURITY_HEADER_NAME, SECURITY_NAMESPACE); if (headerIndex != -1) { XmlDictionaryReader reader = context.IncomingMessageHeaders.GetReaderAtHeader(headerIndex); if (reader.IsStartElement(SECURITY_HEADER_NAME, SECURITY_NAMESPACE)) { reader.ReadStartElement(); reader.MoveToContent(); if (reader.IsStartElement(AUTHID_ELEMENT_NAME, SECURITY_NAMESPACE)) { string authID = reader.ReadElementContentAsString(); return new SIPSorcerySecurityHeader(authID); } } } return null; } catch (Exception excp) { logger.Error("Exception SIPSorcerySecurityHeader ParseHeader. " + excp.Message); throw; } }
public override bool CheckAccess(OperationContext operationContext, ref Message message) { var contractName = operationContext.EndpointDispatcher.ContractName; if (contractName == "IMetadataExchange" || contractName == "IHttpGetHelpPageAndMetadataContract") { // support for MEX return true; } var digestState = new DigestAuthenticationState(operationContext, GetRealm(ref message)); if (!digestState.IsRequestDigestAuth) { return UnauthorizedResponse(digestState); } string password; if (!GetPassword(ref message, digestState.Username, out password)) { return UnauthorizedResponse(digestState); } digestState.Password = password; if (!digestState.Authorized || digestState.IsNonceStale) { return UnauthorizedResponse(digestState); } return Authorized(digestState, operationContext, ref message); }
/// <summary> /// Checks authorization for the given operation context based on default policy evaluation. /// </summary> /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext" /> for the current authorization request.</param> /// <returns> /// true if access is granted; otherwise, false. The default is true. /// </returns> protected override bool CheckAccessCore(OperationContext operationContext) { var retVal = base.CheckAccessCore(operationContext); SimpleWebToken token = null; if (retVal) { // Extract authorization data. var requestMessage = operationContext.RequestContext.RequestMessage; var httpDetails = requestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; var requestUri = WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.UriTemplateMatch != null ? WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri : requestMessage.Headers.To; token = ReadAuthToken(httpDetails); retVal = token != null && IsValidToken(token, requestUri); } var securityContext = ServiceSecurityContext.Anonymous; ClaimsPrincipal principal = new GenericPrincipal(new GenericIdentity(String.Empty), new string[0]); var identity = principal.Identity; if (retVal) { var claims = token.Claims.Select(keyValuePair => new Claim(keyValuePair.Key, keyValuePair.Value)); identity = new ClaimsIdentity(claims, "OAUTH-SWT"); principal = new ClaimsPrincipal(identity); Thread.CurrentPrincipal = principal; } securityContext.AuthorizationContext.Properties["Principal"] = principal; securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { identity }; operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; return retVal; //return true; }
protected override bool CheckAccessCore(OperationContext operationContext) { string action = operationContext.RequestContext.RequestMessage.Headers.Action; Log.DebugFormat("Authentication in progress. Action: {0}", action); // Check globally anonymous actions.. if (AnonymousActions.Contains(action)) { Log.Debug("Request authorized as an Anonymous Action"); return true; } if (Log.IsDebugEnabled) { int count = 0; foreach (IIdentity idt in operationContext.ServiceSecurityContext.GetIdentities()) { Log.DebugFormat("Identity{1}-{0}: {2}", idt.AuthenticationType, count++, idt.Name); } } if (operationContext.ServiceSecurityContext.AuthorizationContext.Properties.ContainsKey("Principal")) { Thread.CurrentPrincipal = (IPrincipal)operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"]; return base.CheckAccessCore(operationContext); } else { return false; } }
public Stream handlePostKeyValue(string id, Stream request) { System.ServiceModel.OperationContext op = System.ServiceModel.OperationContext.Current; System.ServiceModel.Web.WebOperationContext webop = System.ServiceModel.Web.WebOperationContext.Current; string content_type = webop.IncomingRequest.Headers["Content-Type"]; string s = "OK"; using (StreamReader sr = new StreamReader(request)) { s = sr.ReadToEnd(); } if (content_type == "application/x-www-form-urlencoded") { NameValueCollection kvp; kvp = HttpUtility.ParseQueryString(s); } else if (content_type == "application/json") { } else if (content_type == "plain/text") { } else { } return(new MemoryStream(System.Text.Encoding.UTF8.GetBytes($"{s}{System.Environment.NewLine}"))); }
protected override WorkflowCreationContext OnGetCreationContext(object[] inputs, OperationContext operationContext, Guid instanceId, WorkflowHostingResponseContext responseContext) { WorkflowCreationContext creationContext = new WorkflowCreationContext(); creationContext.CreateOnly = true; if (operationContext.IncomingMessageHeaders.Action.EndsWith("Create")) { Dictionary<string, object> arguments = (Dictionary<string, object>)inputs[0]; if (arguments != null && arguments.Count > 0) { foreach (KeyValuePair<string, object> pair in arguments) { creationContext.WorkflowArguments.Add(pair.Key, pair.Value); } } responseContext.SendResponse(instanceId, null); } else if (operationContext.IncomingMessageHeaders.Action.EndsWith("CreateWithInstanceId")) { Dictionary<string, object> arguments = (Dictionary<string, object>)inputs[0]; if (arguments != null && arguments.Count > 0) { foreach (KeyValuePair<string, object> pair in arguments) { creationContext.WorkflowArguments.Add(pair.Key, pair.Value); } } } else { throw new InvalidOperationException("Invalid Action: " + operationContext.IncomingMessageHeaders.Action); } return creationContext; }
public void OnReceiveMessage(System.ServiceModel.OperationContext operationContext, System.Activities.ExecutionProperties activityExecutionProperties) { try { Guid instanceId = operationContext.IncomingMessageHeaders.GetHeader <Guid>(HeaderName, HeaderNS); Console.WriteLine("Received a message from a workflow with instanceId = {0}", instanceId); } catch (MessageHeaderException) { Console.WriteLine("This message must not be from a workflow."); } }
/// <summary> /// Sets the event sink for the current channel. /// </summary> private void SetEventSink() { System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current; if (context != null) { IStackControl control = context.Channel.GetProperty <IStackControl>(); if (control != null) { control.SetEventSink(this); } } }
/// <summary> /// Queues an action. /// </summary> private void QueueStackAction(StackAction action) { System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current; if (context != null) { IStackControl control = context.Channel.GetProperty <IStackControl>(); if (control != null) { control.QueueAction(action); } } }
private WorkflowOperationContext(object[] inputs, System.ServiceModel.OperationContext operationContext, string operationName, bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction, WorkflowServiceInstance workflowInstance, IInvokeReceivedNotification notification, WorkflowOperationBehavior behavior, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.inputs = inputs; this.operationName = operationName; this.OperationContext = operationContext; this.CurrentTransaction = currentTransaction; this.performanceCountersEnabled = performanceCountersEnabled; this.propagateActivity = propagateActivity; this.timeoutHelper = new TimeoutHelper(timeout); this.workflowInstance = workflowInstance; this.thisLock = new object(); this.notification = notification; base.OnCompleting = onCompleting; this.bookmark = behavior.OnResolveBookmark(this, out this.bookmarkScope, out this.bookmarkValue); bool flag = false; try { if (TraceUtility.MessageFlowTracingOnly) { this.e2eActivityId = TraceUtility.GetReceivedActivityId(this.OperationContext); DiagnosticTrace.ActivityId = this.e2eActivityId; } if (this.workflowInstance.BufferedReceiveManager != null) { ReceiveContext.TryGet(this.OperationContext.IncomingMessageProperties, out this.receiveContext); this.OperationContext.IncomingMessageProperties.Remove(ReceiveContext.Name); } flag = this.ProcessRequest(); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } base.OnCompleting(this, exception); throw; } if (flag) { base.Complete(true); } }
/// <summary> /// Sets the event sink for the current channel. /// </summary> private void InterruptListener(int duration) { System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current; if (context != null) { IStackControl control = context.EndpointDispatcher.ChannelDispatcher.Listener.GetProperty <IStackControl>(); if (control != null) { StackAction action = new StackAction(); action.ActionType = StackActionType.CloseListeningSocket; action.Duration = duration; control.QueueAction(action); } } }
/// <summary> /// Start the monitor /// </summary> public async Task <CloudJob> StartAsync(System.ServiceModel.OperationContext context) { TraceHelper.TraceEvent(this.sessionid, TraceEventType.Information, "[AzureBatchJobMonitorEntry] Start monitor Entry."); this.currentState = Telepathy.Session.Data.JobState.Queued; this.context = context.GetCallbackChannel <ISchedulerNotify>(); this.cloudJob = await this.batchClient.JobOperations.GetJobAsync(AzureBatchSessionJobIdConverter.ConvertToAzureBatchJobId(this.sessionid)); if (this.cloudJob.State == JobState.Disabled) { ThrowHelper.ThrowSessionFault(SOAFaultCode.Session_ValidateJobFailed_JobCanceled, SR.SessionLauncher_ValidateJobFailed_JobCanceled, this.sessionid.ToString()); } if (this.cloudJob.Metadata != null) { MetadataItem maxUnitsItem = this.cloudJob.Metadata.FirstOrDefault(item => item.Name == "MaxUnits"); if (maxUnitsItem != null) { if (Int32.TryParse(maxUnitsItem.Value, out int result)) { this.maxUnits = result; } } } // monitor batch job state this.batchJobMonitor = new AzureBatchJobMonitor(this.sessionid, this.JobMonitor_OnReportJobState); try { Task.Run(() => this.StartMonitorAsync()); } catch (Exception e) { TraceHelper.TraceEvent(this.sessionid, TraceEventType.Warning, "[AzureBatchJobMonitorEntry] Exception thrown when start Azure Batch Job Monitor: {0}", e); } return(this.cloudJob); }
public void ReceiveReply(System.ServiceModel.OperationContext operationContext, Message reply) { this.OperationContext = operationContext; this.Reply = reply; }
internal MessageRpc(System.ServiceModel.Channels.RequestContext requestContext, Message request, DispatchOperationRuntime operation, ServiceChannel channel, ServiceHostBase host, ChannelHandler channelHandler, bool cleanThread, System.ServiceModel.OperationContext operationContext, System.ServiceModel.InstanceContext instanceContext) { this.Activity = null; this.AsyncResult = null; this.CanSendReply = true; this.Channel = channel; this.channelHandler = channelHandler; this.Correlation = EmptyArray.Allocate(operation.Parent.CorrelationCount); this.CorrelationCallback = null; this.DidDeserializeRequestBody = false; this.TransactionMessageProperty = null; this.TransactedBatchContext = null; this.Error = null; this.ErrorProcessor = null; this.FaultInfo = new ErrorHandlerFaultInfo(request.Version.Addressing.DefaultFaultAction); this.HasSecurityContext = false; this.Host = host; this.Instance = null; this.MessageRpcOwnsInstanceContextThrottle = false; this.NextProcessor = null; this.NotUnderstoodHeaders = null; this.Operation = operation; this.OperationContext = operationContext; this.paused = false; this.ParametersDisposed = false; this.ReceiveContext = null; this.Request = request; this.RequestContext = requestContext; this.RequestContextThrewOnReply = false; this.SuccessfullySendReply = false; this.RequestVersion = request.Version; this.Reply = null; this.ReplyTimeoutHelper = new TimeoutHelper(); this.SecurityContext = null; this.InstanceContext = instanceContext; this.SuccessfullyBoundInstance = false; this.SuccessfullyIncrementedActivity = false; this.SuccessfullyLockedInstance = false; this.switchedThreads = !cleanThread; this.transaction = null; this.InputParameters = null; this.OutputParameters = null; this.ReturnParameter = null; this.isInstanceContextSingleton = InstanceContextProviderBase.IsProviderSingleton(this.Channel.DispatchRuntime.InstanceContextProvider); this.invokeContinueGate = null; if (!operation.IsOneWay && !operation.Parent.ManualAddressing) { this.RequestID = request.Headers.MessageId; this.ReplyToInfo = new System.ServiceModel.Channels.RequestReplyCorrelator.ReplyToInfo(request); } else { this.RequestID = null; this.ReplyToInfo = new System.ServiceModel.Channels.RequestReplyCorrelator.ReplyToInfo(); } this.HostingProperty = AspNetEnvironment.Current.PrepareMessageForDispatch(request); if (DiagnosticUtility.ShouldUseActivity) { this.Activity = TraceUtility.ExtractActivity(this.Request); } if (DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivity) { this.ResponseActivityId = ActivityIdHeader.ExtractActivityId(this.Request); } else { this.ResponseActivityId = Guid.Empty; } this.InvokeNotification = new MessageRpcInvokeNotification(this.Activity, this.channelHandler); }
public static IAsyncResult BeginProcessRequest(WorkflowServiceInstance workflowInstance, System.ServiceModel.OperationContext operationContext, string operationName, object[] inputs, bool performanceCountersEnabled, bool propagateActivity, Transaction currentTransaction, IInvokeReceivedNotification notification, WorkflowOperationBehavior behavior, TimeSpan timeout, AsyncCallback callback, object state) { return(new WorkflowOperationContext(inputs, operationContext, operationName, performanceCountersEnabled, propagateActivity, currentTransaction, workflowInstance, notification, behavior, timeout, callback, state)); }