本文整理汇总了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();
}
}
示例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;
}
}
示例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;
}
}
示例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");
}
示例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;
}
}
示例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;
}
示例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;
}
示例9: OperationContextScope
public OperationContextScope (OperationContext context)
{
if (context == null)
throw new ArgumentNullException ("context");
previous = OperationContext.Current;
OperationContext.Current = context;
}
示例10: CheckAccessCore
protected override bool CheckAccessCore(OperationContext operationContext)
{
operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] =
Thread.CurrentPrincipal;
return base.CheckAccessCore(operationContext);
}
示例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;
}
示例12: OperationContextScope
public OperationContextScope(OperationContext context)
{
this.originalContext = OperationContext.Current;
this.originalScope = currentScope;
this.thread = Thread.CurrentThread;
this.PushContext(context);
}
示例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;
}
示例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();
}
}
}
}
示例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;
}