public Token(Regex match, TokenType tokenType, OperationType operationType = OperationType.Operator, TokenDiscardPolicy discardPolicy = TokenDiscardPolicy.Keep)
 {
     m_TokenType = tokenType;
     m_DiscardPolicy = discardPolicy;
     m_OperationType = operationType;
     m_Regex = match;
 }
Example #2
0
		public TokenRule( OperationType op, Symbol tokenID, string symbol )
		{
			this.operation = op;
			this.tokenID = tokenID;
			this.symbol = symbol;
			this.errorID = 0;
		}
        internal DependencyPropertyChangedEventArgs(
            DependencyProperty  property, 
            PropertyMetadata    metadata,
            bool                isAValueChange, 
            EffectiveValueEntry oldEntry, 
            EffectiveValueEntry newEntry,
            OperationType       operationType) 
        {
            _property             = property;
            _metadata             = metadata;
            _oldEntry             = oldEntry; 
            _newEntry             = newEntry;
 
            _flags = 0; 
            _operationType        = operationType;
            IsAValueChange        = isAValueChange; 

            // This is when a mutable default is promoted to a local value. On this operation mutable default
            // value acquires a freezable context. However this value promotion operation is triggered
            // whenever there has been a sub property change to the mutable default. Eg. Adding a TextEffect 
            // to a TextEffectCollection instance which is the mutable default. Since we missed the sub property
            // change due to this add, we flip the IsASubPropertyChange bit on the following change caused by 
            // the value promotion to coalesce these operations. 
            IsASubPropertyChange = (operationType == OperationType.ChangeMutableDefaultValue);
        } 
        public virtual void AddAfter(IQueryPart part, OperationType operation)
        {
            var first = Parts.LastOrDefault(p => p.OperationType == operation);
            var index = Parts.IndexOf(first) + 1;

            Parts.Insert(index, part);
        }
		private async Task<String> GetProductDetailsXml(String asins, OperationType type = OperationType.ItemLookup)
		{
			var requestParameters = new Dictionary<String, String>
			{
				{ "IdType", "ASIN" },
				{ "ResponseGroup", "Large" },
				{ "Service", "AWSECommerceService" },
				{ "AssociateTag", _associateTag }
			};

		    if (type == OperationType.ItemLookup)
		    {
                requestParameters.Add("Operation", "ItemLookup");
                requestParameters.Add("ItemId", asins);
            }
            else if (type == OperationType.ItemSearch)
            {
                requestParameters.Add("Operation", "ItemSearch");
                requestParameters.Add("SearchIndex", "All");
                requestParameters.Add("Keywords", asins);
            }

			var amazonRequestUri = _requestSigner.Sign(requestParameters);
		    var httpClient = new HttpClient
		                        {
		                            Timeout = TimeSpan.FromSeconds(5)
		                        };

		    return await httpClient.GetStringAsync(amazonRequestUri);
		}
        public IVariable Calculate(IMilpManager milpManager, OperationType type, params IVariable[] arguments)
        {
            if(!SupportsOperation(type,arguments)) throw new NotSupportedException(SolverUtilities.FormatUnsupportedMessage(type, arguments));
            if (arguments.All(x => x.IsConstant()))
            {
                if (arguments[0].IsInteger())
                {
                    return milpManager.FromConstant(Math.Abs((int)arguments[0].ConstantValue.Value));
                }
                return milpManager.FromConstant(Math.Abs(arguments[0].ConstantValue.Value));
            }

            var number = arguments[0];
            var numberNegated = number.Operation(OperationType.Negation);
            var result = milpManager.CreateAnonymous(number.IsInteger() ? Domain.PositiveOrZeroInteger : Domain.PositiveOrZeroReal);

            result.Set(ConstraintType.GreaterOrEqual, number)
                .Set(ConstraintType.GreaterOrEqual, numberNegated);

            milpManager.Operation(OperationType.Addition,
                    result.Operation(OperationType.IsEqual, number),
                    result.Operation(OperationType.IsEqual, numberNegated))
                .Set(ConstraintType.GreaterOrEqual, milpManager.FromConstant(1));

            result.ConstantValue = number.ConstantValue.HasValue ? Math.Abs(number.ConstantValue.Value) : number.ConstantValue;
            result.Expression = $"|{number.FullExpression()}|";
            return result;
        }
Example #7
0
 public Operation(OperationType type, int fileNumber, int start, int length)
 {
     Type = type;
     FileNumber = fileNumber;
     Start = start;
     Length = length;
 }
Example #8
0
 public TextChangedEventArgs(OperationType operation, int start, int length, string text)
 {
     _operation = operation;
     _start = start;
     _length = length;
     _text = text;
 }
Example #9
0
 public DesktopChangeEventArgs(int x1, int y1, int x2, int y2, OperationType type) {
     this.x = x1;
     this.y = y1;
     this.w = x2 - x1;
     this.h = y2 - y1;
     this.type = type;
 }
        public static LogOrder GetLogOrderEntity(OrderTask orderTask,OperationType operationType,string objectId)
        {
            LogOrder logEntity = new LogOrder();

            string hostname = Dns.GetHostName();
            IPHostEntry localhost = Dns.GetHostEntry(hostname);
            IPAddress localaddr = localhost.AddressList[0];
            logEntity.IP = localaddr.ToString();

            logEntity.UserId = ConsoleClient.Instance.User.UserId;
            logEntity.UserName = ConsoleClient.Instance.User.UserName;
            logEntity.Event = objectId;// "ExecuteOrder";
            logEntity.ExchangeCode = orderTask.ExchangeCode;
            logEntity.OperationType = operationType;
            logEntity.OrderId = orderTask.OrderId;
            logEntity.OrderCode = orderTask.Code;
            logEntity.AccountCode = orderTask.AccountCode;
            logEntity.InstrumentCode = orderTask.InstrumentCode;
            logEntity.IsBuy = orderTask.IsBuy == BuySell.Buy;
            logEntity.IsOpen = orderTask.IsOpen == OpenClose.Open;
            logEntity.Lot = orderTask.Lot.Value;
            logEntity.SetPrice = orderTask.SetPrice;
            logEntity.OrderType = orderTask.OrderType;
            logEntity.OrderRelation = null;
            logEntity.TransactionCode = orderTask.Transaction.Code;

            return logEntity;
        }
Example #11
0
 public Token(TokenType type, OperationType operationType, string value, TokenPosition position)
 {
     OperationType = operationType;
     Type = type;
     Value = value;
     Position = position;
 }
		public NetSendResult EnqueueMessage(OperationType opType, PacketPayload payload, DeliveryMethod method, bool encrypt, byte channel, int connectionId)
		{
			outgoingMessageQueue.syncRoot.EnterWriteLock();
			try
			{
				//This is similar to how Photon works on the Unity client.
				//They enqueue actions
				outgoingMessageQueue.Enqueue(() =>
				{
					INetworkMessageRouterService sender = sendServiceStrategy.GetRouterService(connectionId);

					sender.TrySendMessage(opType, payload, method, encrypt, channel);
				});

				//signal any handlers that a message is in the queue
				//it is important to do this in a lock. Reset could be called after Set
				//in the other thread and we'd end up with potential unhandled messages in that race condition
				outgoingMessageQueue.QueueSemaphore.Set();
			}
			finally
			{
				outgoingMessageQueue.syncRoot.ExitWriteLock();
			}

			return NetSendResult.Queued;
		}
Example #13
0
        public IVariable Calculate(IMilpManager milpManager, OperationType type, params IVariable[] arguments)
        {
            if (!SupportsOperation(type, arguments)) throw new NotSupportedException(SolverUtilities.FormatUnsupportedMessage(type, arguments));
            if (arguments.All(a => a.IsConstant()))
            {
                var constantResult = (int) arguments[0].ConstantValue.Value%(int) arguments[1].ConstantValue.Value;
                return milpManager.FromConstant((int)constantResult);
            }
            IVariable numerator = arguments[0];
            IVariable denominator = arguments[1];

            var one = milpManager.FromConstant(1);
            var any = milpManager.CreateAnonymous(Domain.PositiveOrZeroInteger);
            any.Operation(OperationType.Multiplication, denominator).Set(ConstraintType.LessOrEqual, numerator);
            any.Operation(OperationType.Addition, one)
                .Operation(OperationType.Multiplication, denominator)
                .Set(ConstraintType.GreaterOrEqual, numerator.Operation(OperationType.Addition, one));

            IVariable result = milpManager.CreateAnonymous(Domain.PositiveOrZeroInteger);
            result.Set(ConstraintType.LessOrEqual, denominator);
            result.Set(ConstraintType.Equal,
                numerator.Operation(OperationType.Subtraction,
                    denominator.Operation(OperationType.Multiplication, any)));

            result.ConstantValue = numerator.ConstantValue%denominator.ConstantValue;
            result.Expression = $"{numerator.FullExpression()} % {denominator.FullExpression()}";
            return result;
        }
 public GceOperation(OperationType operationType, string projectId, string zoneName, string name)
 {
     OperationType = operationType;
     ProjectId = projectId;
     ZoneName = zoneName;
     Name = name;
 }
Example #15
0
 internal Operation(int id, string name, string desc, OperationType type)
 {
     _operationId = id;
     _name = name;
     _description = desc;
     _type = type;
 }
 // For send/receive
 private TransportAsyncWorker(ITransport transport, OperationType operation, byte[] buffer, int offset, int size, AsyncCallback callback, object state)
     : this(transport, operation, callback, state)
 {
     _buffer = buffer;
     _offset = offset;
     _size = size;
 }
Example #17
0
 public QueryPart(OperationType operation, Type entityType, string id)
 {
     OperationType = operation;
     ID = id ?? operation.ToString();
     EntityType = entityType;
     _parts = new Lazy<List<IQueryPart>>(() => new List<IQueryPart>());
 }
        /// <summary>
        /// Отправить уведомление об изменении состоянии объекта
        /// </summary>
        /// <param name="replicationInfo">Информация о реплицируемом объекте</param>
        /// <param name="operationType">Тип операции репликации</param>
        /// <param name="sender">Отправитель</param>
        public void SendObjectChanged(ReplicationInfo replicationInfo, OperationType operationType, IReplicationCallbackContract sender)
        {
            IReplicationCallbackContract[] subscribersCopy;

            lock (_subscribers)
            {
                subscribersCopy = _subscribers.Where(s=> s!=sender).ToArray();
            }

            foreach (var subscriber in subscribersCopy)
            {
                if (((ICommunicationObject)subscriber).State == CommunicationState.Opened)
                {
                    try
                    {
                        subscriber.SimulateObjectChanged(replicationInfo, operationType);
                    }
                    catch (Exception ex)
                    {
                        //TODO сделать лог
                    }
                }
                else
                {
                    RemoveSubscriber(subscriber);
                }
            }
        }
Example #19
0
 public OperationInfo(
     OperationType type, bool isCommutative, bool isBinary)
 {
     this.type = type;
     this.isCommutative = isCommutative;
     this.isBinary = isBinary;
 }
 // defaults to no texture
 public MapTextureStage()
 {
     this.Operation = OperationType.Replace;
     this.Tilesize = 50;
     CreateBlankTexture();
     CreateBlankBlendTexture();
 }
Example #21
0
 public void Add(List<XObject> objects, bool checkUploadFile = false)
 {
     if (objects == null)
         throw new ArgumentNullException("objects", "Can not be null.");
     if (objects.Count == 0)
         return;
     CurrentOperationType = OperationType.Add;
     var data = new { objects };
     var arrList = ExecuteTemplate<ArrayList>(EndPoint.object_array, XHttpMethod.POST, data);
     // Parse arrayList. Item of array can contains id object or error
     var errors = new Dictionary<int, object>();
     int i = 0;
     foreach (var obj in objects){
         int id = -1;
         if (arrList[i] is string && int.TryParse(arrList[i] as string, out id)){
             obj.Id = id;
             if (checkUploadFile)
                 CheckNeedUploadFiles(obj);
         }
         else
             errors.Add(i, arrList[i]);
         i++;
     }
     if (errors.Count > 0){
         var concatErrors = new StringBuilder();
         foreach (var error in errors)
             if (error.Value is ArrayList && (error.Value as ArrayList).Count > 0 && arrList.Count > error.Key)
                 concatErrors.AppendLine("Index object: " + error.Key + ". Error: " + (arrList[error.Key] as ArrayList)[0] + "; ");
         throw new FxServerException("FlexiDB server error." + concatErrors);
     }
 }
Example #22
0
 public FRConfiguration(String fileName, String source, FRSearch search)
 {
     this.type = OperationType.FindInSource;
     this.path = fileName;
     this.search = search;
     this.source = source;
 }
Example #23
0
 public void SetAuditTrail(string un, OperationType op, string cat, string msg)
 {
     UserName = un;
     Operation = op;
     Category = cat;
     Message = msg;
 }
Example #24
0
 /// <summary>
 /// 同步计划的运营历史操作
 /// </summary>
 /// <param name="StartDate">开始时间</param>
 /// <param name="planHistoryID">计划明细ID</param>
 /// <param name="tag">标志</param>
 /// <param name="dbContext">域上下文</param>
 public static void SyncOperationHistroy(FleetEntities dbContext, Guid planHistoryID, OperationType tag)
 {
     //当前计划历史
     var currentPlanHisotry = dbContext.PlanHistories.FirstOrDefault(p => p.PlanHistoryID == planHistoryID);
     if (currentPlanHisotry == null || currentPlanHisotry.ApprovalHistoryID == null) return;
     //运行日期
     DateTime? StartDate = GetOperationDateByApprovalHistory(currentPlanHisotry.ApprovalHistoryID, dbContext);
     if (StartDate == null) return;
     //当前有效的年度
     var currentOpenAnnual = (from t in dbContext.Plans.Include("Annuals")
                              from r in dbContext.PlanHistories
                              where
                                  t.PlanID == r.PlanID &&
                                  r.PlanHistoryID == currentPlanHisotry.PlanHistoryID
                              select t.Annual).FirstOrDefault();
     if (currentOpenAnnual == null) return;
     switch (tag)
     {
         case OperationType.OperationLastYearPlan:
             SynOperationLastYearPlan(dbContext, currentPlanHisotry, (DateTime)StartDate, currentOpenAnnual);
             break;
         case OperationType.OperationNextYearPlan:
             SynOperationNextYearPlan(dbContext, currentPlanHisotry, currentOpenAnnual);
             break;
         default:
             break;
     }
 }
Example #25
0
 protected BaseProcessor(Stream inputStream, Stream outputStream, OperationType operationType, HashTypes hashType = HashTypes.Undefined)
 {
     this.hashType = hashType;
     this.inputStream = inputStream;
     this.outputStream = outputStream;
     this.operationType = operationType;
 }
Example #26
0
		public TokenRule( OperationType op, Symbol tokenID )
		{
			this.operation = op;
			this.tokenID = tokenID;
			this.symbol = "";
			this.errorID = 0;
		}
 public bool SupportsOperation(OperationType type, params IVariable[] arguments)
 {
     return type == OperationType.Multiplication && HasVariablesToMultiply(arguments) && (
         MultiplyOnlyConstants(arguments) ||
         MultiplyBinaryVariables(arguments) ||
         MultiplyAtMostOneNonconstant(arguments) ||
         MultiplyAnyIntegers(arguments));
 }
Example #28
0
 public FRConfiguration(String path, String fileMask, Boolean recursive, FRSearch search)
 {
     this.path = path;
     this.type = OperationType.FindInPath;
     this.recursive = recursive;
     this.mask = fileMask;
     this.search = search;
 }
        // For accept
        private TransportAsyncWorker(ITransport transport, OperationType operation, AsyncCallback callback, object state)
        {
            _transport = transport;
            _operation = operation;

            _callback = callback;
            _result = new TransportAsyncResult(this, state);
        }
 // blend needs two textures
 public MapTextureStageModel( OperationType operation, int Tilesize, ImageWrapper splattexture, ImageWrapper blendtexture )
 {
     LogFile.WriteLine("MapTextureStage(), two stages");
     this.Operation = operation;
     this.splattexture = splattexture;
     this.blendtexture = blendtexture;
     this.Tilesize = Tilesize;
 }
        protected ChooseOperationBase(bool highlightEntities, DocumentChoiceType choiceType, OperationType operationType = OperationType.Any)
            : base(choiceType)
        {
            this.highlightEntities = highlightEntities;
            this.operationType     = operationType;

            Initialize();
        }
Example #32
0
        public async Task <FetchRequireClaimsResult <IEnumerable <Claim> > > FetchRequiredClaimsAsync(OperationType operationType, string fieldPath)
        {
            var query = from item in GraphQLFieldAuthorityRecords
                        where item.OperationType == operationType && fieldPath == item.FieldPath
                        select item;
            GraphQLFieldAuthorityRecord record;
            var result = new FetchRequireClaimsResult <IEnumerable <Claim> >()
            {
                StatusCode = query.Any() ? GraphQLFieldAuthority_CODE.FOUND : GraphQLFieldAuthority_CODE.NOT_FOUND,
                Value      = !query.Any() ? new List <Claim>() : query.FirstOrDefault().Claims
            };

            return(result);
        }
 // Merge
 public void Merge <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, OperationType operationType, Action <decimal> progress) where T : class
 {
     MergeAsync(context, type, entities, tableInfo, operationType, progress, CancellationToken.None, isAsync: false).GetAwaiter().GetResult();
 }
        protected async Task MergeAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, OperationType operationType, Action <decimal> progress, CancellationToken cancellationToken, bool isAsync) where T : class
        {
            var entityPropertyWithDefaultValue = entities.GetPropertiesWithDefaultValue(type);

            if (tableInfo.BulkConfig.CustomSourceTableName == null)
            {
                tableInfo.InsertToTempTable = true;

                var dropTempTableIfExists = tableInfo.BulkConfig.UseTempDB;

                if (dropTempTableIfExists)
                {
                    var sqlDropTable = SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
                    if (isAsync)
                    {
                        await context.Database.ExecuteSqlRawAsync(sqlDropTable, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Database.ExecuteSqlRaw(sqlDropTable);
                    }
                }

                var sqlCreateTableCopy = SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo);
                if (isAsync)
                {
                    await context.Database.ExecuteSqlRawAsync(sqlCreateTableCopy, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    context.Database.ExecuteSqlRaw(sqlCreateTableCopy);
                }

                if (tableInfo.TimeStampColumnName != null)
                {
                    var sqlAddColumn = SqlQueryBuilder.AddColumn(tableInfo.FullTempTableName, tableInfo.TimeStampColumnName, tableInfo.TimeStampOutColumnType);
                    if (isAsync)
                    {
                        await context.Database.ExecuteSqlRawAsync(sqlAddColumn, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Database.ExecuteSqlRaw(sqlAddColumn);
                    }
                }
            }

            if (tableInfo.CreatedOutputTable)
            {
                var sqlCreateOutputTableCopy = SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempOutputTableName, tableInfo, true);
                if (isAsync)
                {
                    await context.Database.ExecuteSqlRawAsync(sqlCreateOutputTableCopy, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    context.Database.ExecuteSqlRaw(sqlCreateOutputTableCopy);
                }

                if (tableInfo.TimeStampColumnName != null)
                {
                    var sqlAddColumn = SqlQueryBuilder.AddColumn(tableInfo.FullTempOutputTableName, tableInfo.TimeStampColumnName, tableInfo.TimeStampOutColumnType);
                    if (isAsync)
                    {
                        await context.Database.ExecuteSqlRawAsync(sqlAddColumn, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Database.ExecuteSqlRaw(sqlAddColumn);
                    }
                }

                if (operationType == OperationType.InsertOrUpdateOrDelete)
                {
                    // Output returns all changes including Deleted rows with all NULL values, so if TempOutput.Id col not Nullable it breaks
                    var sqlAlterTableColumnsToNullable = SqlQueryBuilder.AlterTableColumnsToNullable(tableInfo.FullTempOutputTableName, tableInfo);
                    if (isAsync)
                    {
                        await context.Database.ExecuteSqlRawAsync(sqlAlterTableColumnsToNullable, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Database.ExecuteSqlRaw(sqlAlterTableColumnsToNullable);
                    }
                }
            }

            bool keepIdentity = tableInfo.BulkConfig.SqlBulkCopyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);

            try
            {
                if (tableInfo.BulkConfig.CustomSourceTableName == null)
                {
                    if (isAsync)
                    {
                        await InsertAsync(context, type, entities, tableInfo, progress, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        Insert(context, type, entities, tableInfo, progress);
                    }
                }

                if (keepIdentity && tableInfo.HasIdentity)
                {
                    var sqlSetIdentityInsertTrue = SqlQueryBuilder.SetIdentityInsert(tableInfo.FullTableName, true);
                    if (isAsync)
                    {
                        await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);

                        await context.Database.ExecuteSqlRawAsync(sqlSetIdentityInsertTrue, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Database.OpenConnection();
                        context.Database.ExecuteSqlRaw(sqlSetIdentityInsertTrue);
                    }
                }

                var sqlMergeTable = SqlQueryBuilder.MergeTable <T>(context, tableInfo, operationType, entityPropertyWithDefaultValue);
                if (isAsync)
                {
                    await context.Database.ExecuteSqlRawAsync(sqlMergeTable.sql, sqlMergeTable.parameters, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    context.Database.ExecuteSqlRaw(sqlMergeTable.sql, sqlMergeTable.parameters);
                }

                if (tableInfo.CreatedOutputTable)
                {
                    if (isAsync)
                    {
                        await tableInfo.LoadOutputDataAsync(context, type, entities, tableInfo, cancellationToken, isAsync : true).ConfigureAwait(false);
                    }
                    else
                    {
                        tableInfo.LoadOutputDataAsync(context, type, entities, tableInfo, cancellationToken, isAsync: false).GetAwaiter().GetResult();
                    }
                }
            }
            finally
            {
                if (!tableInfo.BulkConfig.UseTempDB)
                {
                    if (tableInfo.CreatedOutputTable)
                    {
                        var sqlDropOutputTable = SqlQueryBuilder.DropTable(tableInfo.FullTempOutputTableName, tableInfo.BulkConfig.UseTempDB);
                        if (isAsync)
                        {
                            await context.Database.ExecuteSqlRawAsync(sqlDropOutputTable, cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            context.Database.ExecuteSqlRaw(sqlDropOutputTable);
                        }
                    }
                    if (tableInfo.BulkConfig.CustomSourceTableName == null)
                    {
                        var sqlDropTable = SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
                        if (isAsync)
                        {
                            await context.Database.ExecuteSqlRawAsync(sqlDropTable, cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            context.Database.ExecuteSqlRaw(sqlDropTable);
                        }
                    }
                }

                if (keepIdentity && tableInfo.HasIdentity)
                {
                    var sqlSetIdentityInsertFalse = SqlQueryBuilder.SetIdentityInsert(tableInfo.FullTableName, false);
                    if (isAsync)
                    {
                        await context.Database.ExecuteSqlRawAsync(sqlSetIdentityInsertFalse, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        context.Database.ExecuteSqlRaw(sqlSetIdentityInsertFalse);
                    }
                    context.Database.CloseConnection();
                }
            }
        }
        public void SolveTask(string data, OperationType operationType)
        {
            CombControllerArgs combControllerArgs = new CombControllerArgs(data, operationType);

            SolveTaskEvent(this, combControllerArgs);
        }
Example #36
0
 /// <summary>
 /// Logs the header of the summary of an operation
 /// </summary>
 /// <param name="operationType"></param>
 /// <param name="libraryId"></param>
 public static void LogEventsHeader(OperationType operationType, string libraryId)
 {
     LogEvent(LogMessageGenerator.GetOperationHeaderString(operationType, libraryId), LogLevel.Task);
 }
Example #37
0
        private static void LogOperationSummary(IEnumerable <ILibraryOperationResult> totalResults, OperationType operation, TimeSpan elapsedTime)
        {
            string messageText = LogMessageGenerator.GetOperationSummaryString(totalResults, operation, elapsedTime);

            if (!string.IsNullOrEmpty(messageText))
            {
                LogEvent(messageText, LogLevel.Operation);
            }
        }
Example #38
0
        /// <summary>
        /// Logs errors messages for a given <see cref="OperationType"/>
        /// </summary>
        /// <param name="results">Operation results</param>
        /// <param name="operationType"><see cref="OperationType"/></param>
        /// <param name="endOfMessage">Whether or not to log end of message lines</param>
        public static void LogErrorsSummary(IEnumerable <ILibraryOperationResult> results, OperationType operationType, bool endOfMessage = true)
        {
            List <string> errorStrings = GetErrorStrings(results);

            LogErrorsSummary(errorStrings, operationType, endOfMessage);
        }
Example #39
0
        public static void Run()
        {
            Console.WriteLine("\nDay 16");

            List <string> input = new List <string>();

            using (StreamReader reader = new StreamReader("input/input16-1.txt"))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    input.Add(line);
                }
            }

            int total = 0;
            List <List <OperationType> > opcodeCandidates = new List <List <OperationType> >();

            for (OperationType op = OperationType.ADDR; op < OperationType.NUM_TYPES; op++)
            {
                opcodeCandidates.Add(Enumerable.Range(0, (int)OperationType.NUM_TYPES).Cast <OperationType>().ToList());
            }

            for (int index = 0; index < input.Count - 2; index = index + 4)
            {
                int[]    before       = new int[] { input[index][9] - '0', input[index][12] - '0', input[index][15] - '0', input[index][18] - '0' };
                string[] operation    = input[index + 1].Split(' ');
                int[]    operands     = new int[] { int.Parse(operation[1]), int.Parse(operation[2]), int.Parse(operation[3]) };
                int      currOpcode   = int.Parse(operation[0]);
                int[]    after        = new int[] { input[index + 2][9] - '0', input[index + 2][12] - '0', input[index + 2][15] - '0', input[index + 2][18] - '0' };
                int      validOpcodes = 0;
                for (OperationType opcode = OperationType.ADDR; opcode < OperationType.NUM_TYPES; opcode++)
                {
                    int[] result  = doOperation(opcode, before, operands);
                    bool  validOp = true;
                    for (int i = 0; i < result.Length; i++)
                    {
                        if (result[i] != after[i])
                        {
                            opcodeCandidates[currOpcode].Remove(opcode);
                            validOp = false;
                            break;
                        }
                    }
                    if (validOp)
                    {
                        validOpcodes++;
                        if (validOpcodes == 3)
                        {
                            total++;
                        }
                    }
                }
            }
            Dictionary <int, OperationType> assignedOpcodes = new Dictionary <int, OperationType>();

            while (assignedOpcodes.Count < (int)OperationType.NUM_TYPES)
            {
                for (int index = 0; index < (int)OperationType.NUM_TYPES; index++)
                {
                    if (assignedOpcodes.ContainsKey(index))
                    {
                        continue;
                    }
                    List <OperationType> toRemove = assignedOpcodes.Values.ToList();
                    opcodeCandidates[index].RemoveAll(x => toRemove.Contains(x));
                }
                for (int index = 0; index < (int)OperationType.NUM_TYPES; index++)
                {
                    if (assignedOpcodes.ContainsKey(index))
                    {
                        continue;
                    }
                    if (opcodeCandidates[index].Count == 1)
                    {
                        assignedOpcodes.Add(index, opcodeCandidates[index][0]);
                    }
                }
            }
            Console.WriteLine(String.Format("3+ opcode samples: {0}", total));

            input = new List <string>();
            using (StreamReader reader = new StreamReader("input/input16-2.txt"))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    input.Add(line);
                }
            }

            int[] registers = new int[] { 0, 0, 0, 0 };
            for (int index = 0; index < input.Count; index++)
            {
                string[]      operation  = input[index].Split(' ');
                int[]         operands   = new int[] { int.Parse(operation[1]), int.Parse(operation[2]), int.Parse(operation[3]) };
                OperationType currOpcode = assignedOpcodes[int.Parse(operation[0])];
                registers = doOperation(currOpcode, registers, operands);
            }
            Console.WriteLine("Test program output: " + registers[0]);
        }
Example #40
0
        public void FinishOperation(bool completeInstance, bool performPersistence, Exception operationException)
        {
            try
            {
                bool          disposeInstance;
                OperationType operation = FinishOperationCommon(completeInstance, operationException, out disposeInstance);

                Fx.Assert(
                    (performPersistence || (operation != OperationType.Delete && operation != OperationType.Unlock)),
                    "If we aren't performing persistence then we are a NotAllowed contract and therefore should never have loaded from persistence.");

                if (performPersistence)
                {
                    switch (operation)
                    {
                    case OperationType.Unlock:
                        // Do the null check out here to avoid creating the scope
                        if (this.lockingProvider != null)
                        {
                            using (PersistenceScope scope = new PersistenceScope(
                                       this.saveStateInOperationTransaction,
                                       this.clonedTransaction))
                            {
                                this.lockingProvider.Unlock(this.operationTimeout);
                            }
                        }
                        break;

                    case OperationType.Delete:
                        using (PersistenceScope scope = new PersistenceScope(
                                   this.saveStateInOperationTransaction,
                                   this.clonedTransaction))
                        {
                            this.provider.Delete(this.instance, this.operationTimeout);

                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                string traceText = SR.GetString(SR.TraceCodeServiceDurableInstanceDeleted, this.InstanceId);
                                TraceUtility.TraceEvent(TraceEventType.Information,
                                                        TraceCode.ServiceDurableInstanceDeleted, traceText,
                                                        new StringTraceRecord("DurableInstanceDetail", traceText),
                                                        this, null);
                            }
                        }
                        break;

                    case OperationType.Create:
                        using (PersistenceScope scope = new PersistenceScope(
                                   this.saveStateInOperationTransaction,
                                   this.clonedTransaction))
                        {
                            if (this.lockingProvider != null)
                            {
                                this.lockingProvider.Create(this.Instance, this.operationTimeout, disposeInstance);
                            }
                            else
                            {
                                this.provider.Create(this.Instance, this.operationTimeout);
                            }

                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
                                TraceUtility.TraceEvent(TraceEventType.Information,
                                                        TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved),
                                                        new StringTraceRecord("DurableInstanceDetail", traceText),
                                                        this, null);
                            }
                        }
                        break;

                    case OperationType.Update:
                        using (PersistenceScope scope = new PersistenceScope(
                                   this.saveStateInOperationTransaction,
                                   this.clonedTransaction))
                        {
                            if (this.lockingProvider != null)
                            {
                                this.lockingProvider.Update(this.Instance, this.operationTimeout, disposeInstance);
                            }
                            else
                            {
                                this.provider.Update(this.Instance, this.operationTimeout);
                            }

                            if (DiagnosticUtility.ShouldTraceInformation)
                            {
                                string traceText = SR2.GetString(SR2.ServiceDurableInstanceSavedDetails, this.InstanceId, (this.lockingProvider != null) ? "True" : "False");
                                TraceUtility.TraceEvent(TraceEventType.Information,
                                                        TraceCode.ServiceDurableInstanceSaved, SR.GetString(SR.TraceCodeServiceDurableInstanceSaved),
                                                        new StringTraceRecord("DurableInstanceDetail", traceText),
                                                        this, null);
                            }
                        }
                        break;

                    case OperationType.None:
                        break;

                    default:
                        Fx.Assert("We should never get an unknown OperationType.");
                        break;
                    }
                }

                if (disposeInstance)
                {
                    DisposeInstance();
                }
            }
            finally
            {
                CompleteClonedTransaction();
            }
        }
        /// <summary>
        /// Gets the operation summary string based on number of successful and failure operations.
        /// </summary>
        public static string GetOperationSummaryString(IEnumerable <ILibraryOperationResult> results, OperationType operation, TimeSpan elapsedTime)
        {
            if (results != null && results.Any())
            {
                int totalResultsCounts = results.Count();
                IEnumerable <ILibraryOperationResult> successfulResults = results.Where(r => r.Success && !r.UpToDate);
                IEnumerable <ILibraryOperationResult> failedResults     = results.Where(r => r.Errors.Any());
                IEnumerable <ILibraryOperationResult> cancelledRessults = results.Where(r => r.Cancelled);
                IEnumerable <ILibraryOperationResult> upToDateResults   = results.Where(r => r.UpToDate);

                bool allSuccess   = successfulResults.Count() == totalResultsCounts;
                bool allFailed    = failedResults.Count() == totalResultsCounts;
                bool allCancelled = cancelledRessults.Count() == totalResultsCounts;
                bool allUpToDate  = upToDateResults.Count() == totalResultsCounts;

                string messageText = string.Empty;
                string libraryId   = string.Empty;

                if (allUpToDate)
                {
                    messageText = LibraryManager.Resources.Text.Restore_LibrariesUptodate + Environment.NewLine;
                }
                else if (allSuccess)
                {
                    libraryId   = GetLibraryId(results, operation);
                    messageText = LogMessageGenerator.GetAllSuccessString(operation, totalResultsCounts, elapsedTime, libraryId);
                }
                else if (allCancelled)
                {
                    libraryId   = GetLibraryId(results, operation);
                    messageText = LogMessageGenerator.GetAllCancelledString(operation, totalResultsCounts, elapsedTime, libraryId);
                }
                else if (allFailed)
                {
                    libraryId   = GetLibraryId(results, operation);
                    messageText = LogMessageGenerator.GetAllFailuresString(operation, totalResultsCounts, libraryId);
                }
                else
                {
                    messageText = LogMessageGenerator.GetPartialSuccessString(operation,
                                                                              successfulResults.Count(), failedResults.Count(), cancelledRessults.Count(), upToDateResults.Count(), elapsedTime);
                }

                return(messageText);
            }

            return(string.Empty);
        }
 protected ChooseOperation(bool highlightEntities, DocumentChoiceType choiceType, OperationType operationType = OperationType.Any)
     : base(highlightEntities, choiceType, operationType)
 {
 }
Example #43
0
            public FinishOperationAsyncResult(ServiceDurableInstance durableInstance, bool completeInstance, bool performPersistence, Exception operationException, AsyncCallback callback, object state)
                : base(callback, state)
            {
                this.durableInstance = durableInstance;

                IAsyncResult  result       = null;
                OperationType operation    = OperationType.None;
                bool          completeSelf = false;
                bool          disposeInstace;

                operation = this.durableInstance.FinishOperationCommon(completeInstance, operationException, out disposeInstace);

                if (performPersistence)
                {
                    switch (operation)
                    {
                    case OperationType.Unlock:
                        if (this.durableInstance.lockingProvider != null)
                        {
                            using (PersistenceScope scope = new PersistenceScope(
                                       this.durableInstance.saveStateInOperationTransaction,
                                       this.durableInstance.clonedTransaction))
                            {
                                result = this.durableInstance.lockingProvider.BeginUnlock(this.durableInstance.operationTimeout, unlockCallback, this);
                            }
                        }
                        break;

                    case OperationType.Delete:
                        using (PersistenceScope scope = new PersistenceScope(
                                   this.durableInstance.saveStateInOperationTransaction,
                                   this.durableInstance.clonedTransaction))
                        {
                            result = this.durableInstance.provider.BeginDelete(this.durableInstance.Instance, this.durableInstance.operationTimeout, deleteCallback, this);
                        }
                        break;

                    case OperationType.Create:
                        using (PersistenceScope scope = new PersistenceScope(
                                   this.durableInstance.saveStateInOperationTransaction,
                                   this.durableInstance.clonedTransaction))
                        {
                            if (this.durableInstance.lockingProvider != null)
                            {
                                result = this.durableInstance.lockingProvider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, createCallback, this);
                            }
                            else
                            {
                                result = this.durableInstance.provider.BeginCreate(this.durableInstance.Instance, this.durableInstance.operationTimeout, createCallback, this);
                            }
                        }
                        break;

                    case OperationType.Update:
                        using (PersistenceScope scope = new PersistenceScope(
                                   this.durableInstance.saveStateInOperationTransaction,
                                   this.durableInstance.clonedTransaction))
                        {
                            if (this.durableInstance.lockingProvider != null)
                            {
                                result = this.durableInstance.lockingProvider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, disposeInstace, updateCallback, this);
                            }
                            else
                            {
                                result = this.durableInstance.provider.BeginUpdate(this.durableInstance.Instance, this.durableInstance.operationTimeout, updateCallback, this);
                            }
                        }
                        break;

                    case OperationType.None:
                        break;

                    default:
                        Fx.Assert("Unknown OperationType was passed in.");
                        break;
                    }
                }

                if (disposeInstace)
                {
                    this.durableInstance.DisposeInstance();
                }

                if (operation == OperationType.None ||
                    (result != null && result.CompletedSynchronously))
                {
                    completeSelf = true;
                }

                if (!performPersistence)
                {
                    Fx.Assert(result == null, "Should not have had a result if we didn't perform persistence.");
                    Complete(true);
                    return;
                }

                if (completeSelf)
                {
                    CallEndOperation(operation, result);

                    Complete(true);
                }
            }
Example #44
0
 /// <summary>
 /// Logs the footer message of the summary of an operation
 /// </summary>
 /// <param name="operationType"></param>
 /// <param name="elapsedTime"></param>
 public static void LogEventsFooter(OperationType operationType, TimeSpan elapsedTime)
 {
     LogEvent(string.Format(LibraryManager.Resources.Text.TimeElapsed, elapsedTime), LogLevel.Operation);
     LogEvent(LibraryManager.Resources.Text.SummaryEndLine + Environment.NewLine, LogLevel.Operation);
 }
Example #45
0
        // Extracted partition key might be invalid as CollectionCache might be stale.
        // Stale collection cache is refreshed through PartitionKeyMismatchRetryPolicy
        // and partition-key is extracted again.
        private async Task <ResponseMessage> ExtractPartitionKeyAndProcessItemStreamAsync <T>(
            PartitionKey?partitionKey,
            string itemId,
            T item,
            OperationType operationType,
            ItemRequestOptions requestOptions,
            CosmosDiagnosticsContext diagnosticsContext,
            CancellationToken cancellationToken)
        {
            if (diagnosticsContext == null)
            {
                throw new ArgumentNullException(nameof(diagnosticsContext));
            }

            Stream itemStream;

            using (diagnosticsContext.CreateScope("ItemSerialize"))
            {
                itemStream = this.ClientContext.SerializerCore.ToStream <T>(item);
            }

            // User specified PK value, no need to extract it
            if (partitionKey.HasValue)
            {
                return(await this.ProcessItemStreamAsync(
                           partitionKey,
                           itemId,
                           itemStream,
                           operationType,
                           requestOptions,
                           diagnosticsContext : diagnosticsContext,
                           cancellationToken : cancellationToken));
            }

            PartitionKeyMismatchRetryPolicy requestRetryPolicy = null;

            while (true)
            {
                using (diagnosticsContext.CreateScope("ExtractPkValue"))
                {
                    partitionKey = await this.GetPartitionKeyValueFromStreamAsync(itemStream, cancellationToken);
                }

                ResponseMessage responseMessage = await this.ProcessItemStreamAsync(
                    partitionKey,
                    itemId,
                    itemStream,
                    operationType,
                    requestOptions,
                    diagnosticsContext : diagnosticsContext,
                    cancellationToken : cancellationToken);

                if (responseMessage.IsSuccessStatusCode)
                {
                    return(responseMessage);
                }

                if (requestRetryPolicy == null)
                {
                    requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(await this.ClientContext.DocumentClient.GetCollectionCacheAsync(), null);
                }

                ShouldRetryResult retryResult = await requestRetryPolicy.ShouldRetryAsync(responseMessage, cancellationToken);

                if (!retryResult.ShouldRetry)
                {
                    return(responseMessage);
                }
            }
        }
Example #46
0
        /// <summary>
        /// Logs the summary messages for a given <see cref="OperationType"/>
        /// </summary>
        /// <param name="totalResults"></param>
        /// <param name="operationType"></param>
        /// <param name="elapsedTime"></param>
        /// <param name="endOfMessage"></param>
        public static void LogEventsSummary(IEnumerable <ILibraryOperationResult> totalResults, OperationType operationType, TimeSpan elapsedTime, bool endOfMessage = true)
        {
            LogErrors(totalResults);
            LogEvent(LogMessageGenerator.GetSummaryHeaderString(operationType), LogLevel.Task);
            LogOperationSummary(totalResults, operationType, elapsedTime);

            if (endOfMessage)
            {
                LogEventsFooter(operationType, elapsedTime);
            }
        }
 public async Task MergeAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, OperationType operationType, Action <decimal> progress, CancellationToken cancellationToken) where T : class
 {
     await MergeAsync(context, type, entities, tableInfo, operationType, progress, cancellationToken, isAsync : true).ConfigureAwait(false);
 }
Example #48
0
        public static void Execute <T>(DbContext context, Type type, IList <T> entities, OperationType operationType, BulkConfig bulkConfig, Action <decimal> progress) where T : class
        {
            type ??= typeof(T);
            using (ActivitySources.StartExecuteActivity(operationType, entities.Count))
            {
                if (entities.Count == 0 &&
                    operationType != OperationType.InsertOrUpdateOrDelete &&
                    operationType != OperationType.Truncate &&
                    operationType != OperationType.SaveChanges &&
                    (bulkConfig == null || bulkConfig.CustomSourceTableName == null))
                {
                    return;
                }

                if (operationType == OperationType.SaveChanges)
                {
                    DbContextBulkTransactionSaveChanges.SaveChanges(context, bulkConfig, progress);
                    return;
                }
                else if (bulkConfig?.IncludeGraph == true)
                {
                    DbContextBulkTransactionGraphUtil.ExecuteWithGraph(context, entities, operationType, bulkConfig, progress);
                }
                else
                {
                    TableInfo tableInfo = TableInfo.CreateInstance(context, type, entities, operationType, bulkConfig);

                    if (operationType == OperationType.Insert && !tableInfo.BulkConfig.SetOutputIdentity && tableInfo.BulkConfig.CustomSourceTableName == null)
                    {
                        SqlBulkOperation.Insert(context, type, entities, tableInfo, progress);
                    }
                    else if (operationType == OperationType.Read)
                    {
                        SqlBulkOperation.Read(context, type, entities, tableInfo, progress);
                    }
                    else if (operationType == OperationType.Truncate)
                    {
                        SqlBulkOperation.Truncate(context, tableInfo);
                    }
                    else
                    {
                        SqlBulkOperation.Merge(context, type, entities, tableInfo, operationType, progress);
                    }
                }
            }
        }
Example #49
0
 public async Task AddClaimsAsync(OperationType operationType, string fieldPath, List <Claim> claims)
 {
     AddClaims(operationType, fieldPath, claims);
 }
Example #50
0
        public static async Task ExecuteAsync <T>(DbContext context, Type type, IList <T> entities, OperationType operationType, BulkConfig bulkConfig, Action <decimal> progress, CancellationToken cancellationToken = default) where T : class
        {
            type ??= typeof(T);
            using (ActivitySources.StartExecuteActivity(operationType, entities.Count))
            {
                if (entities.Count == 0 && operationType != OperationType.InsertOrUpdateOrDelete && operationType != OperationType.Truncate && operationType != OperationType.SaveChanges)
                {
                    return;
                }

                if (operationType == OperationType.SaveChanges)
                {
                    await DbContextBulkTransactionSaveChanges.SaveChangesAsync(context, bulkConfig, progress, cancellationToken);
                }
                else if (bulkConfig?.IncludeGraph == true)
                {
                    await DbContextBulkTransactionGraphUtil.ExecuteWithGraphAsync(context, entities, operationType, bulkConfig, progress, cancellationToken);
                }
                else
                {
                    TableInfo tableInfo = TableInfo.CreateInstance(context, type, entities, operationType, bulkConfig);

                    if (operationType == OperationType.Insert && !tableInfo.BulkConfig.SetOutputIdentity)
                    {
                        await SqlBulkOperation.InsertAsync(context, type, entities, tableInfo, progress, cancellationToken);
                    }
                    else if (operationType == OperationType.Read)
                    {
                        await SqlBulkOperation.ReadAsync(context, type, entities, tableInfo, progress, cancellationToken);
                    }
                    else if (operationType == OperationType.Truncate)
                    {
                        await SqlBulkOperation.TruncateAsync(context, tableInfo, cancellationToken);
                    }
                    else
                    {
                        await SqlBulkOperation.MergeAsync(context, type, entities, tableInfo, operationType, progress, cancellationToken);
                    }
                }
            }
        }
Example #51
0
 public async Task <IEnumerable <History> > GetAllAsyncBy(string currency, OperationType operationType)
 => await _context.History.Where(x => x.Currency == currency.ToUpperInvariant())
 .Where(x => x.OperationType == operationType)
 .OrderByDescending(x => x.ExchangeTime)
 .ToListAsync();
Example #52
0
 public OperationResult(OperationType operationType, object result)
 {
     OperationType = operationType;
     Result        = result;
 }
Example #53
0
        private OperationType GetOperation(
            TypeContext tc,
            ResolvedTypeCategory leftType,
            ResolvedTypeCategory rightType,
            string op)
        {
            Dictionary <string, Dictionary <ResolvedTypeCategory, Dictionary <ResolvedTypeCategory, OperationType> > > consolidationLookup;

            if (tc.OpConsolidationLookupHack != null)
            {
                consolidationLookup = (Dictionary <string, Dictionary <ResolvedTypeCategory, Dictionary <ResolvedTypeCategory, OperationType> > >)tc.OpConsolidationLookupHack;
            }
            else
            {
                consolidationLookup          = new Dictionary <string, Dictionary <ResolvedTypeCategory, Dictionary <ResolvedTypeCategory, OperationType> > >();
                tc.OpConsolidationLookupHack = consolidationLookup;

                OperationType[] operations = new OperationType[] {
                    new OperationType(ResolvedTypeCategory.NULL, ResolvedTypeCategory.NULL, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, true)); }),
                    new OperationType(ResolvedTypeCategory.NULL, ResolvedTypeCategory.NULL, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, false)); }),
                    new OperationType(ResolvedTypeCategory.BOOLEAN, ResolvedTypeCategory.BOOLEAN, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetBool(opChain.Left) == GetBool(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.BOOLEAN, ResolvedTypeCategory.BOOLEAN, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetBool(opChain.Left) != GetBool(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "&", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) & GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "|", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) | GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "^", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) ^ GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "<<", tc.INTEGER, (opChain) =>
                    {
                        int right = GetInt(opChain.Right);
                        if (right < 0)
                        {
                            throw new ParserException(opChain.FirstToken, "Cannot bit shift by a negative number.");
                        }
                        return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) << right));
                    }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, ">>", tc.INTEGER, (opChain) =>
                    {
                        int right = GetInt(opChain.Right);
                        if (right < 0)
                        {
                            throw new ParserException(opChain.FirstToken, "Cannot bit shift by a negative number.");
                        }
                        return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) >> right));
                    }),

                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "+", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) + GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "-", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) - GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "*", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) * GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "/", tc.INTEGER, (opChain) => { CheckZero(opChain.Right); return(MakeInt(opChain.FirstToken, GetInt(opChain.Left) / GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "%", tc.INTEGER, (opChain) => { return(MakeInt(opChain.FirstToken, PositiveModInt(opChain.Left, opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "<=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) <= GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, ">=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) >= GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "<", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) < GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, ">", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) > GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) == GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) != GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.INTEGER, "**", tc.FLOAT, (opChain) =>
                    {
                        int right = GetInt(opChain.Right);
                        int left  = GetInt(opChain.Left);
                        if (right == 0)
                        {
                            return(MakeFloat(opChain.FirstToken, 1.0));
                        }
                        return(MakeFloat(opChain.FirstToken, Math.Pow(left, right)));
                    }),

                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "+", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetInt(opChain.Left) + GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "-", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetInt(opChain.Left) - GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "*", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetInt(opChain.Left) * GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "/", tc.FLOAT, (opChain) => { CheckZero(opChain.Right); return(MakeFloat(opChain.FirstToken, GetInt(opChain.Left) / GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "%", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, PositiveModFloat(opChain.Left, opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "<=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) <= GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, ">=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) >= GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "<", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) < GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, ">", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) > GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) == GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetInt(opChain.Left) != GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.FLOAT, "**", tc.FLOAT, (opChain) =>
                    {
                        double right = GetFloat(opChain.Right);
                        int left     = GetInt(opChain.Left);
                        if (FloatIsAbsoluteZero(right))
                        {
                            return(MakeFloat(opChain.FirstToken, 1.0));
                        }
                        if (!FloatIsAbsoluteZero(right % 1) && left < 0)
                        {
                            throw new ParserException(opChain.OpToken, "Exponent creates a complex expression.");
                        }
                        return(MakeFloat(opChain.FirstToken, Math.Pow(left, right)));
                    }),

                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "+", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) + GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "-", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) - GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "*", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) * GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "/", tc.FLOAT, (opChain) => { CheckZero(opChain.Right); return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) / GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "%", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, PositiveModFloat(opChain.Left, opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "<=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) <= GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, ">=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) >= GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "<", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) < GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, ">", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) > GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) == GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) != GetInt(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.INTEGER, "**", tc.FLOAT, (opChain) =>
                    {
                        int right   = GetInt(opChain.Right);
                        double left = GetFloat(opChain.Left);
                        if (right == 0)
                        {
                            return(MakeFloat(opChain.FirstToken, 1.0));
                        }
                        return(MakeFloat(opChain.FirstToken, Math.Pow(left, right)));
                    }),

                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "+", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) + GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "-", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) - GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "*", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) * GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "/", tc.FLOAT, (opChain) => { CheckZero(opChain.Right); return(MakeFloat(opChain.FirstToken, GetFloat(opChain.Left) / GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "%", tc.FLOAT, (opChain) => { return(MakeFloat(opChain.FirstToken, PositiveModFloat(opChain.Left, opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "<=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) <= GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, ">=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) >= GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "<", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) < GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, ">", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) > GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) == GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetFloat(opChain.Left) != GetFloat(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.FLOAT, "**", tc.FLOAT, (opChain) =>
                    {
                        double right = GetFloat(opChain.Right);
                        double left  = GetFloat(opChain.Left);
                        if (FloatIsAbsoluteZero(right))
                        {
                            return(MakeFloat(opChain.FirstToken, 1.0));
                        }
                        if (!FloatIsAbsoluteZero(right % 1) && left < 0)
                        {
                            throw new ParserException(opChain.OpToken, "Exponent creates a complex expression.");
                        }
                        return(MakeFloat(opChain.FirstToken, Math.Pow(left, right)));
                    }),

                    new OperationType(ResolvedTypeCategory.BOOLEAN, ResolvedTypeCategory.STRING, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetBool(opChain.Left).ToString() + GetString(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.STRING, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetInt(opChain.Left).ToString() + GetString(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.FLOAT, ResolvedTypeCategory.STRING, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetFloatAsString(opChain.Left) + GetString(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.BOOLEAN, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetString(opChain.Left) + GetBool(opChain.Right).ToString())); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.INTEGER, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetString(opChain.Left) + GetInt(opChain.Right).ToString())); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.FLOAT, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetString(opChain.Left) + GetFloatAsString(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.STRING, "+", tc.STRING, (opChain) => { return(MakeString(opChain.FirstToken, GetString(opChain.Left) + GetString(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.STRING, "==", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetString(opChain.Left) == GetString(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.STRING, "!=", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetString(opChain.Left) != GetString(opChain.Right))); }),

                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.INSTANCE, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.INSTANCE, ResolvedTypeCategory.STRING, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.CLASS_DEFINITION, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.CLASS_DEFINITION, ResolvedTypeCategory.STRING, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.FUNCTION_POINTER, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.FUNCTION_POINTER, ResolvedTypeCategory.STRING, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.LIST, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.LIST, ResolvedTypeCategory.STRING, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.DICTIONARY, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.DICTIONARY, ResolvedTypeCategory.STRING, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.OBJECT, "+", tc.STRING, null),
                    new OperationType(ResolvedTypeCategory.OBJECT, ResolvedTypeCategory.STRING, "+", tc.STRING, null),

                    new OperationType(ResolvedTypeCategory.BOOLEAN, ResolvedTypeCategory.BOOLEAN, "&&", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetBool(opChain.Left) && GetBool(opChain.Right))); }),
                    new OperationType(ResolvedTypeCategory.BOOLEAN, ResolvedTypeCategory.BOOLEAN, "||", tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, GetBool(opChain.Left) || GetBool(opChain.Right))); }),

                    new OperationType(ResolvedTypeCategory.INTEGER, ResolvedTypeCategory.STRING, "*", tc.STRING, (opChain) => { return(GenerateMultipliedStringIfNotTooLong(opChain, opChain.Left, opChain.Right)); }),
                    new OperationType(ResolvedTypeCategory.STRING, ResolvedTypeCategory.INTEGER, "*", tc.STRING, (opChain) => { return(GenerateMultipliedStringIfNotTooLong(opChain, opChain.Left, opChain.Right)); }),
                };

                foreach (OperationType ot in operations)
                {
                    if (!consolidationLookup.ContainsKey(ot.Op))
                    {
                        consolidationLookup[ot.Op] = new Dictionary <ResolvedTypeCategory, Dictionary <ResolvedTypeCategory, OperationType> >();
                    }
                    if (!consolidationLookup[ot.Op].ContainsKey(ot.LeftType))
                    {
                        consolidationLookup[ot.Op][ot.LeftType] = new Dictionary <ResolvedTypeCategory, OperationType>();
                    }
                    consolidationLookup[ot.Op][ot.LeftType].Add(ot.RightType, ot); // causes exception if duplicate
                }
            }

            // The op will always have some types registered, so you can dereference the first level of lookups without checking.
            Dictionary <ResolvedTypeCategory, Dictionary <ResolvedTypeCategory, OperationType> > l1 = consolidationLookup[op];

            if (l1.ContainsKey(leftType))
            {
                Dictionary <ResolvedTypeCategory, OperationType> l2 = l1[leftType];
                if (l2.ContainsKey(rightType))
                {
                    return(l2[rightType]);
                }
            }

            if (op == "==")
            {
                // == comparisons between different kinds of objects should resolve to false at compile time.
                // Lazily initialize these operation types as they are encountered.
                if (leftType != rightType &&
                    !(leftType == ResolvedTypeCategory.INTEGER && rightType == ResolvedTypeCategory.FLOAT) &&
                    !(leftType == ResolvedTypeCategory.FLOAT && rightType == ResolvedTypeCategory.INTEGER) &&
                    leftType != ResolvedTypeCategory.ANY &&
                    rightType != ResolvedTypeCategory.ANY &&
                    leftType != ResolvedTypeCategory.OBJECT &&
                    rightType != ResolvedTypeCategory.OBJECT)
                {
                    if (!consolidationLookup[op].ContainsKey(leftType))
                    {
                        consolidationLookup[op][leftType] = new Dictionary <ResolvedTypeCategory, OperationType>();
                    }
                    OperationType ot = new OperationType(leftType, rightType, op, tc.BOOLEAN, (opChain) => { return(MakeBool(opChain.FirstToken, false)); });
                    consolidationLookup[op][leftType][rightType] = ot;
                    return(ot);
                }
            }

            return(null);
        }
Example #54
0
        static int[] doOperation(OperationType opcode, int[] before, int[] operands)
        {
            int[] result = new int[4];
            before.CopyTo(result, 0);
            switch (opcode)
            {
            case OperationType.ADDI:
                result[operands[2]] = before[operands[0]] + operands[1];
                return(result);

            case OperationType.ADDR:
                result[operands[2]] = before[operands[0]] + before[operands[1]];
                return(result);

            case OperationType.MULI:
                result[operands[2]] = before[operands[0]] * operands[1];
                return(result);

            case OperationType.MULR:
                result[operands[2]] = before[operands[0]] * before[operands[1]];
                return(result);

            case OperationType.BANI:
                result[operands[2]] = before[operands[0]] & operands[1];
                return(result);

            case OperationType.BANR:
                result[operands[2]] = before[operands[0]] & before[operands[1]];
                return(result);

            case OperationType.BORI:
                result[operands[2]] = before[operands[0]] | operands[1];
                return(result);

            case OperationType.BORR:
                result[operands[2]] = before[operands[0]] | before[operands[1]];
                return(result);

            case OperationType.SETI:
                result[operands[2]] = operands[0];
                return(result);

            case OperationType.SETR:
                result[operands[2]] = before[operands[0]];
                return(result);

            case OperationType.EQIR:
                result[operands[2]] = operands[0] == before[operands[1]] ? 1 : 0;
                return(result);

            case OperationType.EQRI:
                result[operands[2]] = before[operands[0]] == operands[1] ? 1 : 0;
                return(result);

            case OperationType.EQRR:
                result[operands[2]] = before[operands[0]] == before[operands[1]] ? 1 : 0;
                return(result);

            case OperationType.GTIR:
                result[operands[2]] = operands[0] > before[operands[1]] ? 1 : 0;
                return(result);

            case OperationType.GTRI:
                result[operands[2]] = before[operands[0]] > operands[1] ? 1 : 0;
                return(result);

            case OperationType.GTRR:
                result[operands[2]] = before[operands[0]] > before[operands[1]] ? 1 : 0;
                return(result);

            default:
                return(null);
            }
        }
Example #55
0
 private Parameters(OperationType operation, string inputFilePath, string outputFilePath)
 {
     Operation      = operation;
     InputFilePath  = inputFilePath;
     OutputFilePath = outputFilePath;
 }
 public ExerciseOption(IntervalType resultIntervalType, OperationType operationType, QuantityType quantityType)
 {
     this.resultIntervalType = resultIntervalType;
     this.operationType      = operationType;
     this.quantityType       = quantityType;
 }
Example #57
0
        private ReadOnlyCollection <Uri> GetPreferredAvailableEndpoints(ReadOnlyDictionary <string, Uri> endpointsByLocation, ReadOnlyCollection <string> orderedLocations, OperationType expectedAvailableOperation, Uri fallbackEndpoint)
        {
            List <Uri> endpoints = new List <Uri>();
            DatabaseAccountLocationsInfo currentLocationInfo = this.locationInfo;

            // if enableEndpointDiscovery is false, we always use the defaultEndpoint that user passed in during documentClient init
            if (this.enableEndpointDiscovery)
            {
                if (this.CanUseMultipleWriteLocations() || expectedAvailableOperation.HasFlag(OperationType.Read))
                {
                    List <Uri> unavailableEndpoints = new List <Uri>();

                    // When client can not use multiple write locations, preferred locations list should only be used
                    // determining read endpoints order.
                    // If client can use multiple write locations, preferred locations list should be used for determining
                    // both read and write endpoints order.

                    foreach (string location in currentLocationInfo.PreferredLocations)
                    {
                        Uri endpoint;
                        if (endpointsByLocation.TryGetValue(location, out endpoint))
                        {
                            if (this.IsEndpointUnavailable(endpoint, expectedAvailableOperation))
                            {
                                unavailableEndpoints.Add(endpoint);
                            }
                            else
                            {
                                endpoints.Add(endpoint);
                            }
                        }
                    }

                    if (endpoints.Count == 0)
                    {
                        endpoints.Add(fallbackEndpoint);
                    }

                    endpoints.AddRange(unavailableEndpoints);
                }
                else
                {
                    foreach (string location in orderedLocations)
                    {
                        Uri endpoint;
                        if (!string.IsNullOrEmpty(location) && // location is empty during manual failover
                            endpointsByLocation.TryGetValue(location, out endpoint))
                        {
                            endpoints.Add(endpoint);
                        }
                    }
                }
            }

            if (endpoints.Count == 0)
            {
                endpoints.Add(fallbackEndpoint);
            }

            return(endpoints.AsReadOnly());
        }
 public CombControllerArgs(string data, OperationType operationType)
 {
     Data          = data;
     OperationType = operationType;
 }
        private static string GetLibraryId(IEnumerable <ILibraryOperationResult> totalResults, OperationType operation)
        {
            if (operation == OperationType.Uninstall || operation == OperationType.Upgrade)
            {
                if (totalResults != null && totalResults.Count() == 1)
                {
                    return(totalResults.First().InstallationState.LibraryId);
                }
            }

            return(string.Empty);
        }
Example #60
0
        OperationType FinishOperationCommon(bool completeInstance, Exception operationException, out bool disposeInstance)
        {
            // No need for Interlocked because we don't support
            // ConcurrencyMode.Multiple
            this.outstandingOperations--;

            DurableOperationContext.EndOperation();

            Fx.Assert(this.outstandingOperations >= 0,
                      "OutstandingOperations should never go below zero.");

            Fx.Assert(this.instance != null,
                      "Instance should never been null here - we only get here if StartOperation completes successfully.");

            OperationType operation = OperationType.None;

            disposeInstance = false;

            // This is a "fuzzy" still referenced.  Immediately
            // after this line another message could come in and
            // reference this InstanceContext, but it doesn't matter
            // because regardless of scheme used the other message
            // would have had to reacquire the database lock.
            bool stillReferenced = this.contextManager.GetReferenceCount(this.InstanceId) > 1;

            this.markedForCompletion |= completeInstance;

            if (this.outstandingOperations == 0)
            {
                if (this.saveStateInOperationTransaction &&
                    this.clonedTransaction != null &&
                    this.clonedTransaction.TransactionInformation.Status == TransactionStatus.Aborted)
                {
                    this.abortInstance       = false;
                    this.markedForCompletion = false;
                    disposeInstance          = true;
                }
                else if (operationException != null && !(operationException is FaultException))
                {
                    if (this.unknownExceptionAction == UnknownExceptionAction.TerminateInstance)
                    {
                        if (this.existsInPersistence)
                        {
                            operation = OperationType.Delete;
                        }

                        this.existsInPersistence = true;
                        disposeInstance          = true;
                    }
                    else
                    {
                        Fx.Assert(this.unknownExceptionAction == UnknownExceptionAction.AbortInstance, "If it is not TerminateInstance then it must be AbortInstance.");

                        if (this.existsInPersistence)
                        {
                            operation = OperationType.Unlock;
                        }

                        this.existsInPersistence = true;
                        disposeInstance          = true;
                        this.markedForCompletion = false;
                    }
                }
                else if (this.abortInstance)
                {
                    this.abortInstance = false;

                    // AbortInstance can only be called in ConcurrencyMode.Single
                    // and therefore markedForCompletion could only have been
                    // set true by this same operation (either declaratively or
                    // programmatically).  We set it false again so that the
                    // next operation doesn't cause instance completion.
                    this.markedForCompletion = false;

                    if (this.existsInPersistence && !stillReferenced)
                    {
                        // No need for a transactional version of this as we do not allow
                        // AbortInstance to be called in scenarios with SaveStateInOperationTransaction
                        // set to true
                        Fx.Assert(!this.saveStateInOperationTransaction,
                                  "SaveStateInOperationTransaction must be false if we allowed an abort.");

                        if (this.lockingProvider != null)
                        {
                            operation = OperationType.Unlock;
                        }
                    }

                    this.existsInPersistence = true;
                    disposeInstance          = true;
                }
                else if (this.markedForCompletion)
                {
                    if (this.existsInPersistence)
                    {
                        // We don't set exists in persistence to
                        // false here because we want the proper
                        // persistence exceptions to get back to the
                        // client if we end up here again.

                        operation = OperationType.Delete;
                    }

                    // Even if we didn't delete the instance because it
                    // never existed we should set this to true.  This will
                    // make sure that any future requests to this instance of
                    // ServiceDurableInstance will treat the object as deleted.
                    this.existsInPersistence = true;
                    disposeInstance          = true;
                }
                else
                {
                    if (this.existsInPersistence)
                    {
                        operation = OperationType.Update;
                    }
                    else
                    {
                        operation = OperationType.Create;
                    }

                    this.existsInPersistence = true;
                    if (!stillReferenced)
                    {
                        disposeInstance = true;
                    }
                }
            }

            return(operation);
        }