当前位置: 首页>>代码示例>>C#>>正文


C# ServiceModel.OperationContext类代码示例

本文整理汇总了C#中System.ServiceModel.OperationContext的典型用法代码示例。如果您正苦于以下问题:C# OperationContext类的具体用法?C# OperationContext怎么用?C# OperationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


OperationContext类属于System.ServiceModel命名空间,在下文中一共展示了OperationContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DataFeed

        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();
            }
        }
开发者ID:AlexandrKalinovskiy,项目名称:QService,代码行数:36,代码来源:DataFeed.cs

示例2: ParseHeader

        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;
            }
        }
开发者ID:akalafrancis,项目名称:sipsorcery-mono,代码行数:29,代码来源:SIPSorcerySecurityHeader.cs

示例3: CheckAccessCore

        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;
            }
        }
开发者ID:rag2111,项目名称:Hexa.Core,代码行数:34,代码来源:AuthorizationManager.cs

示例4: OperationContextPreservingSynchronizationContext

        /// <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;
        }
开发者ID:ytokas,项目名称:appacitive-dotnet-sdk,代码行数:13,代码来源:OperationContextPreservingSynchronizationContext.cs

示例5: CheckAccess

        // 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");
        }
开发者ID:gooster,项目名称:WCFHostWIF45,代码行数:8,代码来源:MyServiceAuthorizationManager.cs

示例6: ParseHeader

        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;
            }
        }
开发者ID:TilmannBach,项目名称:sipsorcery-fork,代码行数:29,代码来源:PullNotificationHeader.cs

示例7: CheckAccessCore

        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;
        }
开发者ID:luismdcp,项目名称:PROMPT-06-Services,代码行数:34,代码来源:CustomAuthorizationManager.cs

示例8: CheckAccess

        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;
        }
开发者ID:calderonsteven,项目名称:Preparation_For_Exam70-513,代码行数:34,代码来源:AuthorizationManager.cs

示例9: OperationContextScope

		public OperationContextScope (OperationContext context)
		{
			if (context == null)
				throw new ArgumentNullException ("context");
			previous = OperationContext.Current;
			OperationContext.Current = context;
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:OperationContextScope.cs

示例10: CheckAccessCore

        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] =
                Thread.CurrentPrincipal;

            return base.CheckAccessCore(operationContext);
        }
开发者ID:vendettamit,项目名称:PatternsFun,代码行数:7,代码来源:RestAuthorizationManager.cs

示例11: CheckAccessCore

 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;
 }
开发者ID:locdht,项目名称:MyVinaGerman,代码行数:7,代码来源:PersonnelAuthorizationManager.cs

示例12: OperationContextScope

 public OperationContextScope(OperationContext context)
 {
     this.originalContext = OperationContext.Current;
     this.originalScope = currentScope;
     this.thread = Thread.CurrentThread;
     this.PushContext(context);
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:OperationContextScope.cs

示例13: CheckAccess

        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;
        }
开发者ID:MPCC,项目名称:MPCC,代码行数:28,代码来源:ServiceAuthorization.cs

示例14: LockInstanceAfterCallout

        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();
                    }
                }
            }
        }
开发者ID:shijiaxing,项目名称:wcf,代码行数:31,代码来源:ConcurrencyBehavior.cs

示例15: CheckAccessCore

        /// <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;
        }
开发者ID:divyang4481,项目名称:REM,代码行数:40,代码来源:ServiceAuthorizationManager.cs


注:本文中的System.ServiceModel.OperationContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。