Inheritance: GameAction
            public void Actor_to_actor()
            {
                var one = system.FreshActorOf<TestInsideActor>();
                var another = system.FreshActorOf<TestActor>();

                Assert.Throws<ApplicationException>(async () =>
                {
                    var message = new Throw {Exception = new ApplicationException("a-a")};
                    await one.Tell(new DoTell {Target = another, Message = message});
                });
            }
        private DrawableComposite(IMagickImage image)
        {
            Throw.IfNull(nameof(image), image);

            _image = image;
        }
 // TODO: in addition to the treatment done by base.VisitThrow, transform rethrown -> throw stack_0.
 public override Statement VisitThrow(Throw thrw)
 {
   Statement stat = base.VisitThrow(thrw);
   thrw = stat as Throw;
   if (thrw == null) return stat;
   /* TODO: see if the following lines are correct
   if (thrw.Expression == null)
     thrw.Expression = get_stack_var(0);
     */
   return thrw;
 }
Exemple #4
0
void case_981()
#line 6528 "cs-parser.jay"
{
		Error_SyntaxError (yyToken);
		yyVal = new Throw (null, GetLocation (yyVals[-1+yyTop]));
	  }
 public override Statement VisitThrow(Throw Throw) {
   this.lastBranchWasUnconditional = true;
   return Throw;
 }
Exemple #6
0
 private static string RethrowToString(Throw thrw) 
 {
   return "rethrow";
 }
Exemple #7
0
 protected virtual void VisitThrow(Throw Throw){
   if (Throw == null) return;
   if (Throw.NodeType == NodeType.Rethrow)
     this.ILGenerator.Emit(OpCodes.Rethrow);
   else{
     this.Visit(Throw.Expression);
     this.ILGenerator.Emit(OpCodes.Throw);
   }
 }
Exemple #8
0
 void QueueDieThrow(string diceType, int quantity, string description)
 {
     Debug.Log(string.Format("Queueing a dice throw"));
     Throw newThrow = new Throw();
     newThrow.description = description;
     for(int i=0; i<quantity; i++)
     {
         newThrow.Add(diceType);
     }
     throws.Add(newThrow);
 }
Exemple #9
0
 /// <summary>
 /// Creates a MonitorTraceListener instance.
 /// </summary>
 /// <param name="grandOutput">The <see cref="Monitoring.GrandOutput"/> to send traces to.</param>
 /// <param name="failFast">
 /// When true <see cref="Environment.FailFast(string)"/> will terminate the application on <see cref="Debug.Assert(bool)"/>, <see cref="Trace.Assert(bool)"/>,
 /// <see cref="Debug.Fail(string)"/> and <see cref="Trace.Fail(string)"/>.
 /// See this <see cref="MonitorTraceListener"/>'s remarks section to understand why this should be false.
 /// </param>
 public MonitorTraceListener(GrandOutput grandOutput, bool failFast)
 {
     Throw.CheckNotNullArgument(grandOutput);
     GrandOutput = grandOutput;
     FailFast    = failFast;
 }
Exemple #10
0
 internal void SetResultForHash(Hash hash, byte[] result)
 {
     Throw.IfNull(result, nameof(result));
     Throw.If(result.Length > 32 * 1024, "transaction result is too large");
     _resultMap[hash] = result;
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="exception"></param>
        public WebSocketManagerErrorEventArgs(WebSocketManagerException exception)
        {
            Throw.IfNull(exception, nameof(exception));

            Exception = exception;
        }
Exemple #12
0
 /// <summary>
 /// Creates a DataType for a collection of the given type.
 /// </summary>
 /// <param name="elementType">The DataType of the elements of the collection.</param>
 /// <returns>A new DataType for a collection.</returns>
 public static DataType Collection(DataType elementType)
 {
     Throw.IfArgumentNull(elementType, nameof(elementType));
     return(new DataType($"Collection({elementType})"));
 }
Exemple #13
0
        public async Task <List <SqsMessage <T> > > ConsumeAsync(CancellationToken cancellationToken)
        {
            if (_currentConsumerOptions is null || _client is null)
            {
                Throw.Exception(MisconfiguredConsumerMessage);
            }

            var request = new ReceiveMessageRequest
            {
                QueueUrl              = _currentConsumerOptions.QueueUrl,
                MaxNumberOfMessages   = _currentConsumerOptions.MaxNumberOfMessages,
                WaitTimeSeconds       = _currentConsumerOptions.WaitTimeSeconds,
                AttributeNames        = _currentConsumerOptions.SQSMessageAttributes,
                MessageAttributeNames = _currentConsumerOptions.CustomMessageAttributes
            };

            if (_currentConsumerOptions.VisibilityTimeout.HasValue)
            {
                request.VisibilityTimeout = _currentConsumerOptions.VisibilityTimeout.Value;
            }

            var response = await _client.ReceiveMessageAsync(request, cancellationToken);

            if (response is null || response.HttpStatusCode != HttpStatusCode.OK || response.Messages is null || response.Messages.Count == 0)
            {
                return(_emptyList);
            }

            var result = new List <SqsMessage <T> >(response.Messages.Count);

            foreach (var message in response.Messages)
            {
                var properties = new Dictionary <string, string>(message.Attributes.Count + message.MessageAttributes.Count, StringComparer.Ordinal);

                foreach (var attribute in message.Attributes)
                {
                    properties[attribute.Key] = attribute.Value;
                }

                foreach (var msgAttribute in message.MessageAttributes)
                {
                    properties[msgAttribute.Key] = msgAttribute.Value.StringValue;
                }

                var contentType = ContentTypes.Json;

                if (message.MessageAttributes.TryGetValue(KnownProperties.ContentType, out var cta))
                {
                    contentType = cta.StringValue;
                }

                var messageType = default(string);
                if (message.MessageAttributes.TryGetValue(KnownProperties.ValueTypeName, out var vtn))
                {
                    messageType = vtn.StringValue;
                }

                if (_acknowledgementAction is null)
                {
                    Throw.Exception("Acknowledgement action cannot be null for SQS message");
                }

                try
                {
                    result.Add(new SqsMessage <T>(_acknowledgementAction)
                    {
                        Id            = message.MessageId,
                        Properties    = properties,
                        ReceiptHandle = message.ReceiptHandle,
                        QueueUrl      = _currentConsumerOptions.QueueUrl,
                        Value         = _deserializationProvider.From <T>(message.Body, contentType, messageType ?? string.Empty)
                    });
                }
                catch (Exception e)
                {
                    // Swallow deserialization exception to prevent blocking the pipeline and processing of subsequent messages.
                    _logger.LogError(e, $"Error deserializing message body. {e.Message}. {nameof(message.MessageId)}:{message.MessageId}. {nameof(message.MD5OfBody)}:{message.MD5OfBody}");
                }
            }

            return(result);
        }
Exemple #14
0
        private static HasCustomDebugInformationTag ToHasCustomDebugInformationTag(HandleKind kind)
        {
            switch (kind)
            {
            case HandleKind.MethodDefinition: return(HasCustomDebugInformationTag.MethodDef);

            case HandleKind.FieldDefinition: return(HasCustomDebugInformationTag.Field);

            case HandleKind.TypeReference: return(HasCustomDebugInformationTag.TypeRef);

            case HandleKind.TypeDefinition: return(HasCustomDebugInformationTag.TypeDef);

            case HandleKind.Parameter: return(HasCustomDebugInformationTag.Param);

            case HandleKind.InterfaceImplementation: return(HasCustomDebugInformationTag.InterfaceImpl);

            case HandleKind.MemberReference: return(HasCustomDebugInformationTag.MemberRef);

            case HandleKind.ModuleDefinition: return(HasCustomDebugInformationTag.Module);

            case HandleKind.DeclarativeSecurityAttribute: return(HasCustomDebugInformationTag.DeclSecurity);

            case HandleKind.PropertyDefinition: return(HasCustomDebugInformationTag.Property);

            case HandleKind.EventDefinition: return(HasCustomDebugInformationTag.Event);

            case HandleKind.StandaloneSignature: return(HasCustomDebugInformationTag.StandAloneSig);

            case HandleKind.ModuleReference: return(HasCustomDebugInformationTag.ModuleRef);

            case HandleKind.TypeSpecification: return(HasCustomDebugInformationTag.TypeSpec);

            case HandleKind.AssemblyDefinition: return(HasCustomDebugInformationTag.Assembly);

            case HandleKind.AssemblyReference: return(HasCustomDebugInformationTag.AssemblyRef);

            case HandleKind.AssemblyFile: return(HasCustomDebugInformationTag.File);

            case HandleKind.ExportedType: return(HasCustomDebugInformationTag.ExportedType);

            case HandleKind.ManifestResource: return(HasCustomDebugInformationTag.ManifestResource);

            case HandleKind.GenericParameter: return(HasCustomDebugInformationTag.GenericParam);

            case HandleKind.GenericParameterConstraint: return(HasCustomDebugInformationTag.GenericParamConstraint);

            case HandleKind.MethodSpecification: return(HasCustomDebugInformationTag.MethodSpec);

            case HandleKind.Document: return(HasCustomDebugInformationTag.Document);

            case HandleKind.LocalScope: return(HasCustomDebugInformationTag.LocalScope);

            case HandleKind.LocalVariable: return(HasCustomDebugInformationTag.LocalVariable);

            case HandleKind.LocalConstant: return(HasCustomDebugInformationTag.LocalConstant);

            case HandleKind.ImportScope: return(HasCustomDebugInformationTag.ImportScope);

            default:
                Throw.InvalidArgument_UnexpectedHandleKind(kind);
                return(0);
            }
        }
Exemple #15
0
        public virtual OrderBookTop Deserialize(string json)
        {
            Throw.IfNullOrWhiteSpace(json, nameof(json));

            return(DeserializeOrderBookTop(JObject.Parse(json)));
        }
Exemple #16
0
    public override Node VisitQueryTransact(QueryTransact qt) {
      if (qt == null || qt.Source == null || qt.Source.Type == null) return null;
      Block block = new Block(new StatementList(10));
      qt.Transaction = this.NewClosureLocal(SystemTypes.IDbTransaction, this.currentMethod.Body.Scope);
      Expression locCommit = this.NewClosureLocal(SystemTypes.Boolean, this.currentMethod.Body.Scope);
      TypeNode txType = null;
      if (this.GetTypeView(qt.Source.Type).IsAssignableTo(SystemTypes.IDbConnection)) {
        txType = SystemTypes.IDbConnection;
      }
      else if (this.GetTypeView(qt.Source.Type).IsAssignableTo(SystemTypes.IDbTransactable)) {
        txType = SystemTypes.IDbTransactable;
      }
      Expression source = this.typeSystem.ExplicitCoercion(qt.Source, txType, this.TypeViewer);
      if (qt.Isolation != null) {
        Method mBegin = this.GetTypeView(txType).GetMethod(idBeginTransaction, SystemTypes.IsolationLevel);
        MethodCall mcBegin = new MethodCall(new MemberBinding(source, mBegin), new ExpressionList(qt.Isolation));
        mcBegin.Type = mBegin.ReturnType;
        mcBegin.NodeType = NodeType.Callvirt;
        block.Statements.Add(new AssignmentStatement(qt.Transaction, mcBegin));
      }
      else {
        Method mBegin = this.GetTypeView(txType).GetMethod(idBeginTransaction);
        MethodCall mcBegin = new MethodCall(new MemberBinding(source, mBegin), null);
        mcBegin.Type = mBegin.ReturnType;
        mcBegin.NodeType = NodeType.Callvirt;
        block.Statements.Add(new AssignmentStatement(qt.Transaction, mcBegin));
      }
      block.Statements.Add(new AssignmentStatement(locCommit, Literal.True));

      // prepare finally block
      Block finBlock = new Block(new StatementList(10));
      Method mRollback = SystemTypes.IDbTransaction.GetMethod(idRollback);
      MethodCall mcRollback = new MethodCall(new MemberBinding(qt.Transaction, mRollback), null);
      mcRollback.Type = mRollback.ReturnType;
      mcRollback.NodeType = NodeType.Callvirt;
      Method mCommit = SystemTypes.IDbTransaction.GetMethod(idCommit);
      MethodCall mcCommit = new MethodCall(new MemberBinding(qt.Transaction, mCommit), null);
      mcCommit.Type = mCommit.ReturnType;
      mcCommit.NodeType = NodeType.Callvirt;
      Method mDispose = SystemTypes.IDisposable.GetMethod(StandardIds.Dispose);
      MethodCall mcDispose = new MethodCall(new MemberBinding(qt.Transaction, mDispose), null);
      mcDispose.Type = mDispose.ReturnType;
      mcDispose.NodeType = NodeType.Callvirt;
      Block bCommitStart = new Block();
      Block bCommitBody = new Block(qt.CommitBody.Statements);
      Block bRollbackBody = new Block(qt.RollbackBody.Statements);
      Block finExit = new Block();
      finBlock.Statements.Add(new Branch(locCommit, bCommitStart));
      finBlock.Statements.Add(new ExpressionStatement(mcRollback));
      finBlock.Statements.Add(bRollbackBody);
      finBlock.Statements.Add(new Branch(null, finExit));
      finBlock.Statements.Add(bCommitStart);
      finBlock.Statements.Add(new ExpressionStatement(mcCommit));
      finBlock.Statements.Add(bCommitBody);
      finBlock.Statements.Add(finExit);
      finBlock.Statements.Add(new ExpressionStatement(mcDispose));
      finBlock.Statements.Add(new AssignmentStatement(qt.Transaction, Literal.Null));

      // prepare catcher
      Local locEx = new Local(SystemTypes.Object);
      Block catchBlock = new Block(new StatementList(2));
      catchBlock.Statements.Add(new AssignmentStatement(locCommit, Literal.False));
      Throw _throw = new Throw(locEx);
      _throw.NodeType = NodeType.Rethrow;
      catchBlock.Statements.Add(_throw);
      CatchList catchers = new CatchList(1);
      catchers.Add(new Catch(catchBlock, locEx, SystemTypes.Object));

      // prepare try block
      Block tryBlock = new Block(new StatementList(4));
      qt.CommitBody.Statements = null;;
      qt.RollbackBody.Statements = null;
      tryBlock.Statements.Add(qt.Body);
      tryBlock.Statements.Add(new Branch(null, qt.CommitBody));
      tryBlock.Statements.Add(qt.RollbackBody);
      tryBlock.Statements.Add(new AssignmentStatement(locCommit, Literal.False));
      tryBlock.Statements.Add(qt.CommitBody);
      this.exceptionBlockFor[qt.CommitBody.UniqueKey] = tryBlock;
      this.exceptionBlockFor[qt.RollbackBody.UniqueKey] = tryBlock;

      // add try-finally to block      
      block.Statements.Add(new Try(tryBlock, catchers, null, null, new Finally(finBlock)));
      this.currentTransaction = qt;
      Node result = this.VisitBlock(block);
      this.currentTransaction = null;
      return result;
    }
 public void Handle(Throw cmd)
 {
     throw cmd.Exception;
 }
Exemple #18
0
        public virtual OrderBook Deserialize(string json)
        {
            Throw.IfNullOrWhiteSpace(json, nameof(json));

            return(JsonConvert.DeserializeObject <OrderBook>(json, _settings));
        }
Exemple #19
0
 public void Add(Throw newThrow)
 {
     throwQueue.Add(newThrow);
 }
Exemple #20
0
        public virtual string Serialize(OrderBook orderBook)
        {
            Throw.IfNull(orderBook, nameof(orderBook));

            return(JsonConvert.SerializeObject(orderBook, _settings));
        }
Exemple #21
0
		public virtual object Visit (Throw throwStatement)
		{
			return null;
		}
Exemple #22
0
 public override Statement VisitThrow(Throw Throw)
 {
     this.lastBranchWasUnconditional = true;
     return(Throw);
 }
 public override Statement VisitThrow(Throw Throw)
 {
   throw new ApplicationException("unimplemented");
 }
Exemple #24
0
 public static Channel Build(RSS rss)
 {
     Throw.IfIsNull(rss, nameof(rss));
     return(BuildCore(rss, rss.Raw.Element(ElementName)));
 }
Exemple #25
0
void case_979()
#line 6518 "cs-parser.jay"
{
		yyVal = new Throw ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
		lbag.AddStatement (yyVal, GetLocation (yyVals[0+yyTop]));
	  }
Exemple #26
0
        /// <summary>
        /// Performs compression on the specified the file. With some formats the image will be decoded
        /// and encoded and this will result in a small quality reduction. If the new file size is not
        /// smaller the file won't be overwritten.
        /// </summary>
        /// <param name="file">The image file to compress.</param>
        /// <param name="quality">The jpeg quality.</param>
        public void Compress(FileInfo file, int quality)
        {
            Throw.IfNull(nameof(file), file);

            DoCompress(file, false, quality);
        }
 public virtual void Throw(VariableBase Exception)
 {
     Throw TempCommand = new Throw(Exception);
     TempCommand.Setup();
     Commands.Add(TempCommand);
 }
Exemple #28
0
        /// <summary>
        /// Performs lossless compression on the specified the file. If the new file size is not smaller
        /// the file won't be overwritten.
        /// </summary>
        /// <param name="file">The jpeg file to compress.</param>
        public void LosslessCompress(FileInfo file)
        {
            Throw.IfNull(nameof(file), file);

            DoCompress(file, true, 0);
        }
			public override object Visit (Throw throwStatement)
			{
				var result = new ThrowStatement ();
				var location = LocationsBag.GetLocations (throwStatement);
				
				result.AddChild (new CSharpTokenNode (Convert (throwStatement.loc), ThrowStatement.ThrowKeywordRole), ThrowStatement.ThrowKeywordRole);
				if (throwStatement.Expr != null)
					result.AddChild ((Expression)throwStatement.Expr.Accept (this), Roles.Expression);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.Semicolon), Roles.Semicolon);
				return result;
			}
Exemple #30
0
 public object Any(Throw request) => HttpError.Conflict("Conflict message");
Exemple #31
0
 public virtual Statement MarkAsInstrumentationCode(Block block){
   Throw rethrow = new Throw();
   rethrow.NodeType = NodeType.Rethrow;
   Catch catchClause = new Catch(new Block(new StatementList(rethrow)), new Local(SystemTypes.ContractMarkerException), SystemTypes.ContractMarkerException);
   CatchList catchers = new CatchList(1);
   catchers.Add(catchClause);
   return new Try(block, catchers, null, null, null);
 }
        private static Expression Translate(ParameterExpression parameter, ODataExpression expression)
        {
            switch (expression.Kind)
            {
                case ODataExpressionKind.BinaryOp:
                    var binaryOp = (ODataBinaryOpExpression)expression;
                    var originalLeft = Translate(parameter, binaryOp.Left);
                    var originalRight = Translate(parameter, binaryOp.Right);
                    // MA: nullability negotiation comes up with an expression like "NullableDoubleProp eq 0.1"
                    var left = originalLeft.NegotiateNullabilityWith(originalRight);
                    var right = originalRight.NegotiateNullabilityWith(originalLeft);
                    switch (binaryOp.Operator)
                    {
                        case ODataBinaryOp.Or:
                            return Expression.OrElse(left, right);
                        case ODataBinaryOp.And:
                            return Expression.AndAlso(left, right);
                        case ODataBinaryOp.Add:
                            return Expression.Add(left, right);
                        case ODataBinaryOp.Subtract:
                            return Expression.Subtract(left, right);
                        case ODataBinaryOp.Multiply:
                            return Expression.Multiply(left, right);
                        case ODataBinaryOp.Divide:
                            return Expression.Divide(left, right);
                        case ODataBinaryOp.Modulo:
                            return Expression.Modulo(left, right);
                        case ODataBinaryOp.Equal:
                            return Expression.Equal(left, right);
                        case ODataBinaryOp.NotEqual:
                            return Expression.NotEqual(left, right);
                        case ODataBinaryOp.GreaterThan:
                            return Expression.GreaterThan(left, right);
                        case ODataBinaryOp.GreaterThanOrEqual:
                            return Expression.GreaterThanOrEqual(left, right);
                        case ODataBinaryOp.LessThan:
                            return Expression.LessThan(left, right);
                        case ODataBinaryOp.LessThanOrEqual:
                            return Expression.LessThanOrEqual(left, right);
                        default:
                            throw Throw.UnexpectedCase(binaryOp.Operator);
                    }
                case ODataExpressionKind.Call:
                    var call = (ODataCallExpression)expression;
                    var arguments = call.Arguments.Select(a => Translate(parameter, a))
                        .ToArray();
                    switch (call.Function)
                    {
                        // TODO FUTURE: rethink how we apply functions to nullables NullReferenceExceptions
                        case ODataFunction.Cast:
                            return Expression.Convert(arguments[0], (Type)((ConstantExpression)arguments[1]).Value);
                        case ODataFunction.Ceiling:
                            return Expression.Call(typeof(Math), "Ceiling", Type.EmptyTypes, ValueOf(arguments.Single()));
                        case ODataFunction.Floor:
                            return Expression.Call(typeof(Math), "Floor", Type.EmptyTypes, ValueOf(arguments.Single()));
                        case ODataFunction.Concat:
                            return Expression.Call(Helpers.GetMethod(() => string.Concat(default(string), default(string))), arguments);
                        case ODataFunction.Length:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((string s) => s.Length));
                        case ODataFunction.EndsWith:
                            return Expression.Call(arguments[0], "EndsWith", Type.EmptyTypes, arguments[1]);
                        case ODataFunction.StartsWith:
                            return Expression.Call(arguments[0], "StartsWith", Type.EmptyTypes, arguments[1]);

                        // MA: I'm not 100% sure that EF supports these properties because they also have the SqlFunctions. However, if they
                        // don't we can always apply a custom post-translator to replace them
                        case ODataFunction.Day:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((DateTime dt) => dt.Day));
                            //return Expression.Call(typeof(SqlFunctions), "DatePart", Type.EmptyTypes, Expression.Constant("d"), arguments.Single());
                        case ODataFunction.Hour:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((DateTime dt) => dt.Hour));
                            //return Expression.Call(typeof(SqlFunctions), "DatePart", Type.EmptyTypes, Expression.Constant("h"), arguments.Single());
                        case ODataFunction.Month:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((DateTime dt) => dt.Month));
                            //return Expression.Call(typeof(SqlFunctions), "DatePart", Type.EmptyTypes, Expression.Constant("m"), arguments.Single());
                        case ODataFunction.Minute:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((DateTime dt) => dt.Minute));
                            //return Expression.Call(typeof(SqlFunctions), "DatePart", Type.EmptyTypes, Expression.Constant("mi"), arguments.Single());
                        case ODataFunction.Second:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((DateTime dt) => dt.Second));
                            //return Expression.Call(typeof(SqlFunctions), "DatePart", Type.EmptyTypes, Expression.Constant("s"), arguments.Single());
                        case ODataFunction.Year:
                            return Expression.MakeMemberAccess(ValueOf(arguments.Single()), Helpers.GetProperty((DateTime dt) => dt.Year));
                            //return Expression.Call(typeof(SqlFunctions), "DatePart", Type.EmptyTypes, Expression.Constant("yy"), arguments.Single());

                        case ODataFunction.IndexOf:
                            return Expression.Call(arguments[0], "IndexOf", Type.EmptyTypes, arguments[1]);
                        case ODataFunction.IsOf:
                            return arguments.Length == 1
                                ? Expression.TypeIs(parameter, (Type)((ConstantExpression)arguments.Single()).Value)
                                : Expression.TypeIs(arguments[0], (Type)((ConstantExpression)arguments[1]).Value);
                        case ODataFunction.Replace:
                            return Expression.Call(arguments[0], "Replace", Type.EmptyTypes, arguments[1], arguments[2]);
                        case ODataFunction.Round:
                            return Expression.Call(typeof(Math), "Round", Type.EmptyTypes, ValueOf(arguments.Single()));
                        case ODataFunction.Substring:
                            return arguments.Length == 2
                                ? Expression.Call(arguments[0], "Substring", Type.EmptyTypes, arguments[1])
                                : Expression.Call(arguments[0], "Substring", Type.EmptyTypes, arguments[1], arguments[2]);
                        case ODataFunction.SubstringOf:
                            // http://services.odata.org/Northwind/Northwind.svc/Customers?$filter=substringof('Alfreds', CompanyName) eq true&$format=application/json
                            // returns an entry with "CompanyName":"Alfreds Futterkiste". Thus, this is interpreted as "is the first argument a substring of the second"
                            // or second.Contains(first)
                            return Expression.Call(arguments[1], "Contains", Type.EmptyTypes, arguments[0]);
                        case ODataFunction.ToLower:
                            return Expression.Call(arguments.Single(), "ToLower", Type.EmptyTypes);
                        case ODataFunction.ToUpper:
                            return Expression.Call(arguments.Single(), "ToUpper", Type.EmptyTypes);
                        case ODataFunction.Trim:
                            return Expression.Call(arguments.Single(), "Trim", Type.EmptyTypes);
                        default:
                            throw Throw.UnexpectedCase(call.Function);
                    }
                case ODataExpressionKind.Constant:
                    // note that we don't pass a type here but instead rely on the value being the right type (guaranteed by the static factory)
                    // that also allows this to work better with nulls
                    return Expression.Constant(((ODataConstantExpression)expression).Value);
                case ODataExpressionKind.Convert:
                    var toConvert = Translate(parameter, ((ODataConvertExpression)expression).Expression);
                    var convertToType = expression.ClrType;
                    return Expression.Convert(toConvert, toConvert.Type.CanBeNull() && !convertToType.CanBeNull() ? typeof(Nullable<>).MakeGenericType(convertToType) : convertToType);
                case ODataExpressionKind.MemberAccess:
                    var memberAccess = (ODataMemberAccessExpression)expression;
                    return Expression.MakeMemberAccess(memberAccess.Expression != null ? Translate(parameter, memberAccess.Expression) : parameter, memberAccess.Member);
                case ODataExpressionKind.UnaryOp:
                    var unaryOp = (ODataUnaryOpExpression)expression;
                    switch (unaryOp.Operator)
                    {
                        case ODataUnaryOp.Not:
                            return Expression.Not(Translate(parameter, unaryOp.Operand));
                        default:
                            throw Throw.UnexpectedCase(unaryOp);
                    }
                default:
                    throw Throw.UnexpectedCase(expression.Kind, "Cannot translate " + expression.Kind + " to LINQ");
            }
        }
Exemple #33
0
    // Instead of overriding VisitRequiresPlain or VisitRequiresOtherwise, just process the list.
    // Almost all of the code is the same for both plain and otherwise requires.
    // This could be done by overriding VisitRequires -- but would depend upon introducing
    // a VisitRequires method in StandardVisitor.
    public override RequiresList VisitRequiresList(RequiresList Requires){
      // add a default precondition here and not earlier in the pipeline so it doesn't confuse
      // the contract inheritance checks.
      // REVIEW: probably better to add it earlier and have a HasCompilerGeneratedSignature on it
      // so it can be ignored in the inheritance checks.
      bool addDefaultPrecondition = 
        this.currentMethod != null
        && !this.currentMethod.IsStatic
        && !this.currentMethod.IsAbstract
        && this.currentMethod.Body != null && this.currentMethod.Body.Statements != null
        && !(this.currentMethod.HasCompilerGeneratedSignature && !this.currentMethod.Name.Name.StartsWith("get_") && !this.currentMethod.Name.Name.StartsWith("set_"))
        && this.currentMethod.NodeType != NodeType.InstanceInitializer
        && this.currentMethod.NodeType != NodeType.StaticInitializer
        && (this.currentType != null && this.currentType.Contract != null && this.currentType.Contract.FramePropertyGetter != null)
        && this.currentMethod.GetAttribute(SystemTypes.NoDefaultContractAttribute) == null
        ;
      
      RequiresList newRequires = new RequiresList();

      if (addDefaultPrecondition){
        Method frameGetter = this.currentType.Contract.FramePropertyGetter;
        Method m = null;
        // We used to use "get_CanStartWriting" for non-virtual methods. But Rustan and I decided
        // that it should be fine to use the transitive one for all methods. It is more liberal
        // but still prevents re-entrance into a method in a frame that is exposed.
        m = SystemTypes.Guard.GetMethod(Identifier.For("get_CanStartWritingTransitively"), null);

        // default precondition is (as normalized IR):
        // requires this.get_FrameGuard().get_CanStartWriting(); if it is a non-virtual method
        // requires this.get_FrameGuard().get_CanStartWritingTransitively(); if it is a virtual method
        if (frameGetter != null && m != null){
          SourceContext sc = this.currentMethod.Name.SourceContext;
          MethodCall getFrameGuard = new MethodCall(new MemberBinding(this.currentThisParameter, frameGetter), null, NodeType.MethodCall, SystemTypes.Guard, sc);
          Requires r = new RequiresOtherwise(
            new MethodCall(
            new MemberBinding(getFrameGuard,m),
            null,
            NodeType.MethodCall,
            SystemTypes.Boolean),
            new Construct(new MemberBinding(null, SystemTypes.RequiresException.GetConstructor(SystemTypes.String)), new ExpressionList(new Literal("The target object of this call must be exposable.", SystemTypes.String)), SystemTypes.RequiresException)
            );
          r.SourceContext = sc;
          newRequires.Add(r);
        }
      }

      if ((this.currentMethod.IsPublic || this.currentMethod.IsFamilyOrAssembly) &&
        !(this.currentCompilation != null && this.currentCompilation.CompilerParameters != null &&
        ((CompilerOptions)this.currentCompilation.CompilerParameters).DisableNullParameterValidation)){
        ParameterList parameters = this.currentMethod.Parameters;
        for (int i = 0, n = parameters == null ? 0 : parameters.Count; i < n; i++){
          Parameter parameter = parameters[i];
          if (parameter != null && !parameter.IsOut && this.typeSystem.IsNonNullType(parameter.Type)){
            RequiresOtherwise r;
            Reference rtype = parameter.Type as Reference;
            if (rtype == null) {
              TypeNode parameterType = TypeNode.StripModifier(parameter.Type, SystemTypes.NonNullType);
              Expression e = null;
              if (this.useGenerics && (parameterType is TypeParameter || parameterType is ClassParameter)) {
                e = new BinaryExpression(parameter, new MemberBinding(null, parameterType), NodeType.Box, SystemTypes.Object, parameter.SourceContext);
              } else {
                e = new ParameterBinding(parameter, parameter.SourceContext);
              }
              r =
                new RequiresOtherwise(
                new BinaryExpression(e, new Literal(null, TypeNode.StripModifiers(parameter.Type)), NodeType.Ne, SystemTypes.Boolean, parameter.SourceContext),
                new Construct(new MemberBinding(null, SystemTypes.ArgumentNullException.GetConstructor(SystemTypes.String)), new ExpressionList(new Literal(parameter.Name.Name, SystemTypes.String)), SystemTypes.ArgumentNullException));
            }
            else {
              // have to perform deref
              r =
                new RequiresOtherwise(
                new BinaryExpression(new AddressDereference(new ParameterBinding(parameter, parameter.SourceContext), rtype.ElementType), new Literal(null, TypeNode.StripModifiers(rtype.ElementType)), NodeType.Ne, SystemTypes.Boolean, parameter.SourceContext),
                new Construct(new MemberBinding(null, SystemTypes.ArgumentNullException.GetConstructor(SystemTypes.String)), new ExpressionList(new Literal(parameter.Name.Name, SystemTypes.String)), SystemTypes.ArgumentNullException));
            }
            r.SourceContext = parameter.SourceContext;
            newRequires.Add(r);
          }
        }
      }

      for (int i = 0, n = Requires == null ? 0 : Requires.Count; i < n; i++){
        newRequires.Add(Requires[i]);
      }

      if (newRequires.Count == 0)
          return Requires;

      Block preConditionBlock = new Block(new StatementList());
      preConditionBlock.HasLocals = true;

      for (int i = 0, n = newRequires.Count; i < n; i++)
      {
        Requires r = newRequires[i];
        if (r == null) continue;
        if (r.Condition == null) continue;

        // Code generation for preconditions needs to be such that the
        // data flow analysis will "see" the consequences. If the value
        // of the precondition is assigned to a local, then the information
        // is lost.
        //
        // try {
        //   if re goto pre_i_holds;
        // }
        // catch { throw new ErrorDuringPreConditionEvaluation(...); }
        // throw new PreConditionException(...);
        // pre_i_holds: nop

        bool noAllocationAllowed = this.currentMethod.GetAttribute(SystemTypes.BartokNoHeapAllocationAttribute) != null;
        Local exceptionDuringPreCondition = new Local(Identifier.For("SS$exceptionDuringPreCondition" + i),SystemTypes.Exception);
        Local exceptionDuringPreCondition3 = new Local(Identifier.For("SS$objectExceptionDuringPreCondition" + i),SystemTypes.Object);
        Expression cond = r.Condition;
        string condition = cond != null && cond.SourceContext.SourceText != null && cond.SourceContext.SourceText.Length > 0 ?
          cond.SourceContext.SourceText : "<unknown condition>";
        Expression ec2;
        Expression ec3;
        if (noAllocationAllowed) {
          ec2 = ec3 = new MemberBinding(null, SystemTypes.PreAllocatedExceptions.GetField(Identifier.For("InvalidContract")));
        }
        else {
          MemberBinding excBinding2 = new MemberBinding(null, SystemTypes.InvalidContractException.GetConstructor(SystemTypes.String, SystemTypes.Exception));
          MemberBinding excBinding3 = new MemberBinding(null, SystemTypes.InvalidContractException.GetConstructor(SystemTypes.String));
          string msg2 = "Exception occurred during evaluation of precondition '" + condition + "' in method '" + currentMethod.FullName + "'";
          ec2 = new Construct(excBinding2, new ExpressionList(new Literal(msg2, SystemTypes.String), exceptionDuringPreCondition));
          ec3 = new Construct(excBinding3, new ExpressionList(new Literal(msg2, SystemTypes.String)));
        }

        #region If the precondition fails, throw an exception
        Expression throwExpression = null;
        #region Create the expression to throw. Deal with different subtypes of Requires
        if (noAllocationAllowed) {
          throwExpression = new MemberBinding(null, SystemTypes.PreAllocatedExceptions.GetField(Identifier.For("Requires")));
        }
        else {
          if (r is RequiresPlain) {
            MemberBinding excBinding = new MemberBinding(null, SystemTypes.RequiresException.GetConstructor(SystemTypes.String));
            Construct ec = new Construct(excBinding, new ExpressionList());
            string msg = "Precondition '" + condition + "' violated from method '" + currentMethod.FullName + "'";
            ec.Operands.Add(new Literal(msg, SystemTypes.String));
            throwExpression = ec;
          }
          else if (r is RequiresOtherwise) {
            RequiresOtherwise otherwise = (RequiresOtherwise)r;
            if (otherwise.ThrowException is Literal) {
              // it was "requires P otherwise E" where E is a type name of an exception class
              Literal l = (Literal)otherwise.ThrowException;
              Class exceptionClass = (Class)l.Value;
              MemberBinding excBinding = new MemberBinding(null, this.GetTypeView(exceptionClass).GetConstructor());
              // what to do if there is no nullary constructor? I guess that should have been checked in the context checker
              Construct ec = new Construct(excBinding, new ExpressionList());
              throwExpression = ec;
            }
            else {
              // it was "requires P otherwise new E(...)" (or some other expression whose value is an exception)
              throwExpression = this.VisitExpression(otherwise.ThrowException);
            }
          }
          else {
            Debug.Assert(false, "Expecting only RequiresOtherwise and RequiresPlain as subtypes of Requires");
          }
        }
        #endregion
        Throw t = new Throw(throwExpression,r.SourceContext);
        #endregion

        Block pre_i_holds = new Block();

        //CatchList cl = new CatchList(2);
        //cl.Add(new Catch(new Block(new StatementList(new Throw(ec2,r.Condition.SourceContext))),exceptionDuringPreCondition,SystemTypes.Exception));
        //cl.Add(new Catch(new Block(new StatementList(new Throw(ec3,r.Condition.SourceContext))),exceptionDuringPreCondition3,SystemTypes.Object));

        //Try tryPre = new Try(new Block(new StatementList(new If(r.Condition,new Block(new StatementList(new Branch(null,pre_i_holds))),null))),cl,null,null,null);
        //preConditionBlock.Statements.Add(tryPre);
        preConditionBlock.Statements.Add(new If(r.Condition,new Block(new StatementList(new Branch(null,pre_i_holds))),null));
        preConditionBlock.Statements.Add(t);
        preConditionBlock.Statements.Add(pre_i_holds);

      }

      preConditionBlock = this.VisitBlock(preConditionBlock);
      this.currentContractPrelude.Statements.Add(preConditionBlock);
      return Requires;
    }
Exemple #34
0
        public SettingsViewModel(Library library, ViewSettings viewSettings, CoreSettings coreSettings, IWindowManager windowManager, Guid accessToken, MobileApiInfo mobileApiInfo)
        {
            if (library == null)
                Throw.ArgumentNullException(() => library);

            if (viewSettings == null)
                Throw.ArgumentNullException(() => viewSettings);

            if (coreSettings == null)
                Throw.ArgumentNullException(() => coreSettings);

            if (mobileApiInfo == null)
                throw new ArgumentNullException("mobileApiInfo");

            this.library = library;
            this.viewSettings = viewSettings;
            this.coreSettings = coreSettings;
            this.windowManager = windowManager;
            this.accessToken = accessToken;

            this.canCreateAdmin = this
                .WhenAnyValue(x => x.CreationPassword, x => !string.IsNullOrWhiteSpace(x) && !this.isAdminCreated)
                .ToProperty(this, x => x.CanCreateAdmin);

            this.CreateAdminCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanCreateAdmin),
                ImmediateScheduler.Instance); // Immediate execution, because we set the password to an empty string afterwards
            this.CreateAdminCommand.Subscribe(p =>
            {
                this.library.LocalAccessControl.SetLocalPassword(this.accessToken, this.CreationPassword);
                this.isAdminCreated = true;
            });

            this.ChangeToPartyCommand = ReactiveCommand.Create(this.CreateAdminCommand.Select(x => true).StartWith(false));
            this.ChangeToPartyCommand.Subscribe(p =>
            {
                this.library.LocalAccessControl.DowngradeLocalAccess(this.accessToken);
                this.ShowSettings = false;
            });

            this.canLogin = this.WhenAnyValue(x => x.LoginPassword, x => !string.IsNullOrWhiteSpace(x))
                .ToProperty(this, x => x.CanLogin);

            this.LoginCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanLogin),
                ImmediateScheduler.Instance); // Immediate execution, because we set the password to an empty string afterwards
            this.LoginCommand.Subscribe(p =>
            {
                try
                {
                    this.library.LocalAccessControl.UpgradeLocalAccess(this.accessToken, this.LoginPassword);
                    this.IsWrongPassword = false;

                    this.ShowLogin = false;
                    this.ShowSettings = true;
                }

                catch (WrongPasswordException)
                {
                    this.IsWrongPassword = true;
                }
            });

            this.OpenLinkCommand = ReactiveCommand.Create();
            this.OpenLinkCommand.Cast<string>().Subscribe(x =>
            {
                try
                {
                    Process.Start(x);
                }

                catch (Win32Exception ex)
                {
                    this.Log().ErrorException(String.Format("Could not open link {0}", x), ex);
                }
            });

            this.ReportBugCommand = ReactiveCommand.Create();
            this.ReportBugCommand.Subscribe(p => this.windowManager.ShowWindow(new BugReportViewModel()));

            this.ChangeAccentColorCommand = ReactiveCommand.Create();
            this.ChangeAccentColorCommand.Subscribe(x => this.viewSettings.AccentColor = (string)x);

            this.ChangeAppThemeCommand = ReactiveCommand.Create();
            this.ChangeAppThemeCommand.Subscribe(x => this.viewSettings.AppTheme = (string)x);

            this.UpdateLibraryCommand = ReactiveCommand.Create(this.library.WhenAnyValue(x => x.IsUpdating, x => !x)
                .ObserveOn(RxApp.MainThreadScheduler)
                .CombineLatest(this.library.WhenAnyValue(x => x.SongSourcePath).Select(x => !String.IsNullOrEmpty(x)), (x1, x2) => x1 && x2));
            this.UpdateLibraryCommand.Subscribe(_ => this.library.UpdateNow());

            this.librarySource = this.library.WhenAnyValue(x => x.SongSourcePath)
                .ToProperty(this, x => x.LibrarySource);

            this.port = this.coreSettings.Port;
            this.ChangePortCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Port, NetworkHelpers.IsPortValid));
            this.ChangePortCommand.Subscribe(_ => this.coreSettings.Port = this.Port);

            this.remoteControlPassword = this.coreSettings.RemoteControlPassword;
            this.ChangeRemoteControlPasswordCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.RemoteControlPassword)
                .Select(x => !String.IsNullOrWhiteSpace(x)));
            this.ChangeRemoteControlPasswordCommand.Subscribe(x =>
                this.library.RemoteAccessControl.SetRemotePassword(this.accessToken, this.RemoteControlPassword));
            this.showRemoteControlPasswordError = this.WhenAnyValue(x => x.RemoteControlPassword, x => x.LockRemoteControl,
                    (password, lockRemoteControl) => String.IsNullOrWhiteSpace(password) && lockRemoteControl)
                .ToProperty(this, x => x.ShowRemoteControlPasswordError);

            this.isRemoteAccessReallyLocked = this.library.RemoteAccessControl.WhenAnyValue(x => x.IsRemoteAccessReallyLocked)
                .ToProperty(this, x => x.IsRemoteAccessReallyLocked);

            this.isPortOccupied = mobileApiInfo.IsPortOccupied.ToProperty(this, x => x.IsPortOccupied);

            this.enableChangelog = this.viewSettings.WhenAnyValue(x => x.EnableChangelog)
                .ToProperty(this, x => x.EnableChangelog);

            this.defaultPlaybackEngine = this.coreSettings.WhenAnyValue(x => x.DefaultPlaybackEngine)
                .ToProperty(this, x => x.DefaultPlaybackEngine);
        }
Exemple #35
0
        public void Send(string argument)
        {
            Throw.IfNullOrWhiteSpace(argument, nameof(argument));

            this.process.StandardInput.WriteLine(argument);
        }
Exemple #36
0
        /// <summary>
        /// Returns a unique key for the specified <paramref name="item"/>.
        /// </summary>
        /// <param name="item">The item in the collection a key is needed for.</param>
        /// <returns>Returns the <see cref="VstMidiCategory.Name"/> property.</returns>
        protected override string GetKeyForItem(VstMidiCategory item)
        {
            Throw.IfArgumentIsNull(item, nameof(item));

            return(item.Name);
        }
Exemple #37
0
    void ThrowDice(Throw dieThrow, Vector3 startPosition, Vector3 endPosition)
    {
        if(null == dieThrow)
            if(null == lastThrow) return;
            else dieThrow = lastThrow;
        else lastThrow = dieThrow;

        foreach(string dieType in dieThrow.dice)
        {
            GameObject die = CreateDie(dieType);

        //			rigidbody.angularVelocity = Random.insideUnitSphere * randomSpin;
        //			rigidbody.velocity = Random.insideUnitSphere * randomVelocity;
            transform.rotation = Quaternion.LookRotation(Random.onUnitSphere);
            die.transform.position = startPosition;
            die.transform.LookAt(endPosition);
            die.rigidbody.velocity = Camera.main.transform.forward * -10 + Camera.main.transform.right * 5;
            die.rigidbody.angularVelocity = Vector3.right * 10;

            startPosition = startPosition + new Vector3(die.transform.localScale.x + 1, 0, 0);

            //Camera.main.GetComponent<CamControl>().LookAtDice(die.transform);
        }
    }
        public static IServiceCollection AddWebAuthentication(this IServiceCollection services, ResultsAndCertificationConfiguration config, ILogger logger, IWebHostEnvironment env)
        {
            double cookieAndSessionTimeout = 5;
            var    overallSessionTimeout   = TimeSpan.FromMinutes(cookieAndSessionTimeout);
            var    cookieSecurePolicy      = env.IsDevelopment() ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always;

            services.AddAntiforgery(options =>
            {
                options.Cookie.SecurePolicy = cookieSecurePolicy;
            });
            services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.Cookie.Name         = "tl-rc-auth-cookie";
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.SlidingExpiration   = true;
                options.ExpireTimeSpan      = TimeSpan.FromMinutes(cookieAndSessionTimeout);
                options.LogoutPath          = config.DfeSignInSettings.LogoutPath;
                options.AccessDeniedPath    = "/home/accessdenied";
                //options.EventsType = typeof(CustomCookieAuthenticationEvents);
            })
            .AddOpenIdConnect(options =>
            {
                options.SignInScheme         = CookieAuthenticationDefaults.AuthenticationScheme;
                options.MetadataAddress      = config.DfeSignInSettings.MetadataAddress;
                options.RequireHttpsMetadata = false;

                options.ClientId     = config.DfeSignInSettings.ClientId;
                options.ClientSecret = config.DfeSignInSettings.ClientSecret;
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("email");
                options.Scope.Add("profile");

                options.Scope.Add("organisation");
                //options.Scope.Add("offline_access");

                // Prompt=consent is required to be issued with a refresh token
                //options.Prompt = "consent";

                // When we expire the session, ensure user is prompted to sign in again at DfE Sign In
                options.MaxAge = overallSessionTimeout;

                options.SaveTokens             = true;
                options.CallbackPath           = new PathString(config.DfeSignInSettings.CallbackPath);
                options.SignedOutCallbackPath  = new PathString(config.DfeSignInSettings.SignedOutCallbackPath);
                options.SignedOutRedirectUri   = "/signin/signoutcomplete";
                options.SecurityTokenValidator = new JwtSecurityTokenHandler
                {
                    InboundClaimTypeMap            = new Dictionary <string, string>(),
                    TokenLifetimeInMinutes         = int.Parse(cookieAndSessionTimeout.ToString()),
                    SetDefaultTimesOnTokenCreation = true,
                };
                options.ProtocolValidator = new OpenIdConnectProtocolValidator
                {
                    RequireSub             = true,
                    RequireStateValidation = false,
                    NonceLifetime          = TimeSpan.FromMinutes(cookieAndSessionTimeout)
                };

                options.DisableTelemetry = true;

                options.Events = new OpenIdConnectEvents
                {
                    // Sometimes, problems in the OIDC provider (such as session timeouts)
                    // Redirect the user to the /auth/cb endpoint. ASP.NET Core middleware interprets this by default
                    // as a successful authentication and throws in surprise when it doesn't find an authorization code.
                    // This override ensures that these cases redirect to the root.
                    OnMessageReceived = context =>
                    {
                        var isSpuriousAuthCbRequest =
                            context.Request.Path == options.CallbackPath &&
                            context.Request.Method == "GET" &&
                            !context.Request.Query.ContainsKey("code");

                        if (isSpuriousAuthCbRequest)
                        {
                            logger.LogWarning("Spurious log in attempt received for DFE sign in");

                            context.HandleResponse();
                            context.Response.StatusCode          = 302;
                            context.Response.Headers["Location"] = "/";
                        }

                        return(Task.CompletedTask);
                    },

                    // Sometimes the auth flow fails. The most commonly observed causes for this are
                    // Cookie correlation failures, caused by obscure load balancing stuff.
                    // In these cases, rather than send user to a 500 page, prompt them to re-authenticate.
                    // This is derived from the recommended approach: https://github.com/aspnet/Security/issues/1165
                    OnRemoteFailure = ctx =>
                    {
                        logger.LogWarning("Remote failure for DFE-sign in");
                        ctx.HandleResponse();
                        return(Task.FromException(ctx.Failure));
                    },

                    OnRedirectToIdentityProvider = context =>
                    {
                        return(Task.CompletedTask);
                    },

                    // that event is called after the OIDC middleware received the authorisation code,
                    // redeemed it for an access token and a refresh token,
                    // and validated the identity token
                    OnTokenValidated = async x =>
                    {
                        //logger.LogMethodEnter();
                        logger.LogWarning("User has been authorised by DFE");
                        var cliendId  = config.DfeSignInSettings.ClientId;
                        var issuer    = config.DfeSignInSettings.Issuer;
                        var audience  = config.DfeSignInSettings.Audience;
                        var apiSecret = config.DfeSignInSettings.APISecret;
                        var apiUri    = config.DfeSignInSettings.APIUri;

                        Throw.IfNull(issuer, nameof(issuer));
                        Throw.IfNull(audience, nameof(audience));
                        Throw.IfNull(apiSecret, nameof(apiSecret));
                        Throw.IfNull(apiUri, nameof(apiUri));

                        var token = new JwtBuilder()
                                    .WithAlgorithm(new HMACSHA256Algorithm())
                                    .Issuer(issuer)
                                    .Audience(audience)
                                    .WithSecret(apiSecret)
                                    .Encode();

                        //Gather user/org details
                        var identity = (ClaimsIdentity)x.Principal.Identity;
                        Organisation organisation;
                        try
                        {
                            organisation = JsonConvert.DeserializeObject <Organisation>(
                                identity.Claims.Where(c => c.Type == "organisation")
                                .Select(c => c.Value).FirstOrDefault());
                        }
                        catch
                        {
                            throw new SystemException("Unable to get organisation details from DFE. Please clear session cookies, or try using private browsing mode.");
                        }

                        var userClaims = new DfeClaims()
                        {
                            UserId    = Guid.Parse(identity.Claims.Where(c => c.Type == "sub").Select(c => c.Value).SingleOrDefault()),
                            ServiceId = Guid.Parse(identity.Claims.Where(c => c.Type == "sid").Select(c => c.Value).SingleOrDefault()),
                        };

                        var client = new HttpClient();
                        client.SetBearerToken(token);
                        var response = await client.GetAsync($"{apiUri}/services/{cliendId}/organisations/{organisation.Id}/users/{userClaims.UserId}");

                        if (response.IsSuccessStatusCode)
                        {
                            var json            = response.Content.ReadAsStringAsync().Result;
                            userClaims          = JsonConvert.DeserializeObject <DfeClaims>(json);
                            userClaims.RoleName = userClaims.Roles.Select(r => r.Name).FirstOrDefault();
                            userClaims.UKPRN    = organisation.UKPRN.HasValue ? organisation.UKPRN.Value.ToString() : string.Empty;
                            userClaims.UserName = identity.Claims.Where(c => c.Type == "email").Select(c => c.Value).SingleOrDefault();
                        }
                        else
                        {
                            //throw new SystemException("Could not get Role Type for User");
                        }

                        logger.LogError("User " + userClaims.UserName + " has been authenticated by DFE");

                        List <Claim> roleClaims = new List <Claim>();
                        if (userClaims.Roles != null && userClaims.Roles.Any())
                        {
                            foreach (var role in userClaims.Roles)
                            {
                                roleClaims.Add(new Claim(ClaimTypes.Role, role.Name));
                            }

                            if (roleClaims.Count > 0)
                            {
                                identity.AddClaims(roleClaims);
                            }
                        }
                        // store both access and refresh token in the claims - hence in the cookie
                        identity.AddClaims(new[]
                        {
                            //new Claim("access_token", x.TokenEndpointResponse.AccessToken),
                            //new Claim("refresh_token", x.TokenEndpointResponse.RefreshToken),
                            new Claim("UKPRN", userClaims.UKPRN),
                            new Claim("user_id", userClaims.UserId.ToString()),
                            new Claim("OrganisationId", organisation.Id.ToString().ToUpper())
                        });

                        // so that we don't issue a session cookie but one with a fixed expiration
                        x.Properties.IsPersistent = true;

                        x.Properties.ExpiresUtc = DateTime.UtcNow.Add(overallSessionTimeout);
                    }
                };
            });

            return(services);
        }
 protected internal override Node TransformThrow(Throw @throw)
 {
     return Dispatch(@throw);
 }
Exemple #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:Geocrest.Web.Mvc.Syndication.PublicationCategory" /> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="label">The label.</param>
 public PublicationCategory(string name, string label = null)
 {
     Throw.IfArgumentNullOrEmpty(name, "name");
     Name  = name;
     Label = label;
 }
 public virtual Statement VisitThrow(Throw Throw1, Throw Throw2)
 {
     if (Throw1 == null) return null;
     if (Throw2 == null)
         Throw1.Expression = this.VisitExpression(Throw1.Expression, null);
     else
         Throw1.Expression = this.VisitExpression(Throw1.Expression, Throw2.Expression);
     return Throw1;
 }
Exemple #42
0
 private void Awake()
 {
     sortZ       = GetComponent <SortZ>();
     spr         = GetComponent <SpriteRenderer>();
     throwAction = GetComponent <Throw>();
 }
Exemple #43
0
 private static string ThrowToString(Throw thrw) {
   return
     (thrw.Expression != null) ? ("throw " + expression2str(thrw.Expression)) : "rethrow";
 }
        public UserDataKeepAliveTimerProvider(IServiceProvider services)
        {
            Throw.IfNull(services, nameof(services));

            _services = services;
        }
 public object Any(Throw request)
 {
     if (request.StatusCode.HasValue)
     {
         throw new HttpError(
             request.StatusCode.Value,
             typeof(NotImplementedException).Name,
             request.Message);
     }
     throw new NotImplementedException(request.Message + " is not implemented");
 }
Exemple #46
0
 public KeyEqualityComparer(Func <T, object> keyExtractor)
 {
     Throw.IfArgumentNull(keyExtractor, nameof(keyExtractor));
     _keyExtractor = keyExtractor;
 }
 protected internal override void TraverseThrow(Throw @throw)
 {
     Dispatch(@throw);
 }
Exemple #48
0
 protected internal override Statement VisitThrow(Throw inst)
 {
     return(new ThrowStatement(exprBuilder.Translate(inst.Argument)));
 }
Exemple #49
0
 public override Statement VisitThrow(Throw Throw) {
   if (Throw == null) return null;
   TypeNode thrownType = null;
   if (Throw.Expression == null) {
     if (!this.insideCatchClause) {
       this.HandleError(Throw, Error.BadEmptyThrow);
       return null;
     }
     Throw.NodeType = NodeType.Rethrow;
     thrownType = this.currentCatchClause.Type != null ? this.currentCatchClause.Type : SystemTypes.Object;
   } else {
     Expression e = Throw.Expression = this.VisitExpression(Throw.Expression);
     if (e == null || e.Type == null) return null;
     thrownType = e.Type;
     if (thrownType != null)
       thrownType = this.typeSystem.Unwrap(thrownType);
     if (!this.GetTypeView(thrownType).IsAssignableTo(SystemTypes.Exception)) {
       this.HandleError(e, Error.BadExceptionType);
       return null;
     }
     e = Throw.Expression = this.typeSystem.ImplicitCoercion(e, thrownType, this.TypeViewer);
   }
   #region Dealing with checked/unchecked exceptions
   if (this.GetTypeView(thrownType).IsAssignableTo(SystemTypes.ICheckedException)) {
     int i = 0;
     int n = this.allowedExceptions.Count;
     while (i < n) {
       TypeNode t = this.allowedExceptions[i];
       if (this.GetTypeView(thrownType).IsAssignableTo(t))
         break;
       i++;
     }
     if (i == n) // no allowed exception covers this one
       this.HandleError(Throw, Error.CheckedExceptionNotInThrowsClause, this.GetTypeName(thrownType), this.GetMethodSignature(this.currentMethod));
   } else if (
     (this.currentPreprocessorDefinedSymbols == null || !this.currentPreprocessorDefinedSymbols.ContainsKey("compatibility"))
     &&
     !this.currentOptions.DisableDefensiveChecks
     ) {
     // if we can't be sure the thrown exception's *dynamic* type is an unchecked exception, then need to
     // insert a runtime check. Just because its static type is not a subtype of ICheckedException
     // doesn't mean its runtime type isn't, since CheckedException is a subtype of Exception.
     //
     // BUT: do this only if compiler options say to! This is to preserve C# backwards compatibility.
     if (Throw.Expression == null) {
       // if Throw.Expression == null ==> this was "throw;" in a catch block, definitely need the check
       // need to know if there is a variable because it could have been "catch {}" or "catch (Exception){}"
       Block b = new Block(new StatementList(2));
       b.HasLocals = true;
       // now the really bad case: need to transform "catch" or "catch (Exception){}" into "catch (Exception e)"
       if (this.currentCatchClause.Type == null)
         this.currentCatchClause.Type = SystemTypes.Exception;
       if (this.currentCatchClause.Variable == null) {
         Local e = new Local(Identifier.For("SS$exception local"), this.currentCatchClause.Type, b);
         this.currentCatchClause.Variable = e;
       }
       b.Statements.Add(new Assertion(
         new UnaryExpression(
         new BinaryExpression(this.currentCatchClause.Variable, new MemberBinding(null, SystemTypes.ICheckedException), NodeType.Is, SystemTypes.Boolean),
         NodeType.LogicalNot)));
       b.Statements.Add(Throw);
       return b;
     } else if (Throw.Expression.NodeType != NodeType.Construct) {
       // if it is "throw new T" where T is not a checked exception, then we don't need the assert
       Block b = new Block(new StatementList(3));
       b.HasLocals = true;
       // Exception e = Throw.Expression;
       // Assert(!(e is ICheckedException) );
       // throw e;
       Local e = new Local(Identifier.For("SS$exception local"), SystemTypes.Exception, b);
       b.Statements.Add(new AssignmentStatement(e, Throw.Expression));
       b.Statements.Add(new Assertion(
         new UnaryExpression(
         new BinaryExpression(e, new MemberBinding(null, SystemTypes.ICheckedException), NodeType.Is, SystemTypes.Boolean),
         NodeType.LogicalNot)));
       Throw.Expression = e;
       b.Statements.Add(Throw);
       return b;
     }
   }
   #endregion Dealing with checked/unchecked exceptions
   return Throw;
 }
Exemple #50
0
 public override void EndVisit(Throw node)
 {
     currentStatement = null;
 }
Exemple #51
0
void case_980()
#line 6523 "cs-parser.jay"
{
		Error_SyntaxError (yyToken);
		yyVal = new Throw ((Expression) yyVals[-1+yyTop], GetLocation (yyVals[-2+yyTop]));
	  }
Exemple #52
0
 public override bool Visit(Throw node)
 {
     currentStatement = node;
     return(true);
 }
 protected internal virtual void TraverseThrow(Throw @throw) { @throw.Unsupported(); }
Exemple #54
0
        /// <summary>
        /// Performs lossless compression on the specified file. If the new file size is not smaller
        /// the file won't be overwritten.
        /// </summary>
        /// <param name="file">The gif file to compress.</param>
        /// <returns>True when the image could be compressed otherwise false.</returns>
        public bool LosslessCompress(FileInfo file)
        {
            Throw.IfNull(nameof(file), file);

            return(DoLosslessCompress(file));
        }
 public override Statement VisitThrow(Throw thrw) 
 {
   base.VisitThrow(thrw);
   // when a throw occurs, the entire evaluation stack is flushed out.
   depth = 0;
   return thrw;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DrawableFillColor"/> class.
        /// </summary>
        /// <param name="color">The color to use.</param>
        public DrawableFillColor(MagickColor color)
        {
            Throw.IfNull(nameof(color), color);

            Color = color;
        }
    public virtual Differences VisitThrow(Throw throw1, Throw throw2){
      Differences differences = new Differences(throw1, throw2);
      if (throw1 == null || throw2 == null){
        if (throw1 != throw2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      Throw changes = (Throw)throw2.Clone();
      Throw deletions = (Throw)throw2.Clone();
      Throw insertions = (Throw)throw2.Clone();

      Differences diff = this.VisitExpression(throw1.Expression, throw2.Expression);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Expression = diff.Changes as Expression;
      deletions.Expression = diff.Deletions as Expression;
      insertions.Expression = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.Expression && diff.Deletions == deletions.Expression && diff.Insertions == insertions.Expression);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
Exemple #58
0
 public Block MarkAsInstrumentationCodeNormalized(Method method, Block normalizedCode) {
   Throw t = new Throw();
   t.NodeType = NodeType.Rethrow;
   return CreateTryCatchBlock(
     method,
     normalizedCode, // try body
     new Block(new StatementList(t)), // catch: just rethrow
     new Local(Identifier.For("SS$Contract Marker"), SystemTypes.ContractMarkerException)
     );
 }
Exemple #59
0
 public virtual Statement VisitThrow(Throw Throw, Throw changes, Throw deletions, Throw insertions){
   this.UpdateSourceContext(Throw, changes);
   if (Throw == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return Throw;
 }
        /// <summary>
        /// Get the deposit history.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="user"></param>
        /// <param name="asset"></param>
        /// <param name="status"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="recvWindow"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <string> GetDepositsAsync(this IBinanceHttpClient client, IBinanceApiUser user, string asset = null, DepositStatus?status = null, DateTime startTime = default, DateTime endTime = default, long recvWindow = default, CancellationToken token = default)
        {
            Throw.IfNull(client, nameof(client));
            Throw.IfNull(user, nameof(user));

            if (recvWindow == default)
            {
                recvWindow = client.DefaultRecvWindow;
            }

            if (client.RateLimiter != null)
            {
                await client.RateLimiter.DelayAsync(token : token)
                .ConfigureAwait(false);
            }

            var request = new BinanceHttpRequest("/wapi/v3/depositHistory.html")
            {
                ApiKey = user.ApiKey
            };

            if (!string.IsNullOrWhiteSpace(asset))
            {
                request.AddParameter("asset", asset.FormatSymbol());
            }

            if (status.HasValue)
            {
                request.AddParameter("status", (int)status);
            }

            if (startTime != default)
            {
                if (startTime.Kind != DateTimeKind.Utc)
                {
                    throw new ArgumentException("Date/Time must be UTC.", nameof(startTime));
                }

                request.AddParameter("startTime", startTime.ToTimestamp());
            }

            if (endTime != default)
            {
                if (endTime.Kind != DateTimeKind.Utc)
                {
                    throw new ArgumentException("Date/Time must be UTC.", nameof(endTime));
                }

                request.AddParameter("endTime", endTime.ToTimestamp());
            }

            if (recvWindow > 0)
            {
                request.AddParameter("recvWindow", recvWindow);
            }

            await client.SignAsync(request, user, token)
            .ConfigureAwait(false);

            return(await client.GetAsync(request, token)
                   .ConfigureAwait(false));
        }