예제 #1
0
        public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int blockId, int delta, CancellationToken cancellationToken)
        {
            var kvLogMessage = logMessage as KeyValueLogMessage;
            if (kvLogMessage == null)
            {
                return;
            }

            try
            {
                // guard us from exception thrown by telemetry
                var telemetryEvent = CreateTelemetryEvent(functionId, End);
                SetBlockId(telemetryEvent, functionId, blockId);

                var durationName = functionId.GetPropertyName(Duration);
                telemetryEvent.SetIntProperty(durationName, delta);

                var cancellationName = functionId.GetPropertyName(CancellationRequested);
                telemetryEvent.SetBoolProperty(cancellationName, cancellationToken.IsCancellationRequested);

                _session.PostEvent(telemetryEvent);
            }
            catch
            {
            }
        }
예제 #2
0
        internal AggregateNode(DataTable table, FunctionId aggregateType, string columnName, bool local, string relationName) : base(table) {
            Debug.Assert(columnName != null, "Invalid parameter column name (null).");
            this.aggregate = (Aggregate)(int)aggregateType;

            if (aggregateType == FunctionId.Sum)
                this.type = AggregateType.Sum;
            else if (aggregateType == FunctionId.Avg)
                this.type = AggregateType.Mean;
            else if (aggregateType == FunctionId.Min)
                this.type = AggregateType.Min;
            else if (aggregateType == FunctionId.Max)
                this.type = AggregateType.Max;
            else if (aggregateType == FunctionId.Count)
                this.type = AggregateType.Count;
            else if (aggregateType == FunctionId.Var)
                this.type = AggregateType.Var;
            else if (aggregateType == FunctionId.StDev)
                this.type = AggregateType.StDev;
            else {
                throw ExprException.UndefinedFunction(Function.FunctionName[(Int32)aggregateType]);
            }

            this.local = local;
            this.relationName = relationName;
            this.columnName = columnName;
        }
예제 #3
0
        private static Option<bool> CreateOption(FunctionId id)
        {
            var name = Enum.GetName(typeof(FunctionId), id);

            return new Option<bool>(nameof(FunctionIdOptions), name, defaultValue: false,
                storageLocations: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name));
        }
 internal Function()
 {
     this.parameters = new Type[3];
     this.name = null;
     this.id = FunctionId.none;
     this.result = null;
     this.IsValidateArguments = false;
     this.argumentCount = 0;
 }
예제 #5
0
            public void Construct(FunctionId functionId, string message, int blockId, CancellationToken cancellationToken)
            {
                this.functionId = functionId;
                this.tick = Environment.TickCount;
                this.blockId = blockId;
                this.cancellationToken = cancellationToken;

                RoslynEventSource.Instance.BlockStart(message, functionId, blockId);
            }
예제 #6
0
        public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
        {
            if (!_pendingActivities.TryRemove(uniquePairId, out var activity))
            {
                Contract.Requires(false, "when can this happen?");
                return;
            }

            activity.Dispose();
        }
예제 #7
0
            public TraceLogBlock(FeatureId featureId, FunctionId functionId, string message, int uniquePairId, CancellationToken cancellationToken)
            {
                this.featureId = featureId;
                this.functionId = functionId;
                this.uniquePairId = uniquePairId;
                this.cancellationToken = cancellationToken;

                this.watch = Stopwatch.StartNew();
                Trace.WriteLine(string.Format("[{0}] Start({1}) : {2}/{3} - {4}", Thread.CurrentThread.ManagedThreadId, uniquePairId, featureId.ToString(), functionId.ToString(), message));
            }
예제 #8
0
 private static bool GetDefaultValue(FunctionId id)
 {
     switch (id)
     {
         // change not to enable any etw events by default.
         // we used to couple this to other logger such as code marker but now it is only specific to etw.
         // each events should be enabled specifically when needed.
         default:
             return false;
     }
 }
예제 #9
0
            public void Construct(ILogger logger, FunctionId functionId, LogMessage logMessage, int blockId, CancellationToken cancellationToken)
            {
                this.logger = logger;
                this.functionId = functionId;
                this.logMessage = logMessage;
                this.tick = Environment.TickCount;
                this.blockId = blockId;
                this.cancellationToken = cancellationToken;

                logger.LogBlockStart(functionId, logMessage, blockId, cancellationToken);
            }
예제 #10
0
 public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
 {
     if (cancellationToken.IsCancellationRequested)
     {
         RoslynEventSource.Instance.BlockCanceled(functionId, delta, uniquePairId);
     }
     else
     {
         RoslynEventSource.Instance.BlockStop(functionId, delta, uniquePairId);
     }
 }
예제 #11
0
        public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int blockId, CancellationToken cancellationToken)
        {
            var kvLogMessage = logMessage as KeyValueLogMessage;
            if (kvLogMessage == null)
            {
                return;
            }

            try
            {
                // guard us from exception thrown by telemetry
                var telemetryEvent = CreateTelemetryEvent(functionId, Start, kvLogMessage);
                SetBlockId(telemetryEvent, functionId, blockId);

                _session.PostEvent(telemetryEvent);
            }
            catch
            {
            }
        }
 internal Function(string name, FunctionId id, Type result, bool IsValidateArguments, bool IsVariantArgumentList, int argumentCount, Type a1, Type a2, Type a3)
 {
     this.parameters = new Type[3];
     this.name = name;
     this.id = id;
     this.result = result;
     this.IsValidateArguments = IsValidateArguments;
     this.IsVariantArgumentList = IsVariantArgumentList;
     this.argumentCount = argumentCount;
     if (a1 != null)
     {
         this.parameters[0] = a1;
     }
     if (a2 != null)
     {
         this.parameters[1] = a2;
     }
     if (a3 != null)
     {
         this.parameters[2] = a3;
     }
 }
예제 #13
0
        public void Log(FunctionId functionId, LogMessage logMessage)
        {
            var kvLogMessage = logMessage as KeyValueLogMessage;
            if (kvLogMessage == null)
            {
                return;
            }

            try
            {
                // guard us from exception thrown by telemetry
                if (!kvLogMessage.ContainsProperty)
                {
                    _session.PostSimpleEvent(functionId.GetEventName());
                    return;
                }

                var telemetryEvent = CreateTelemetryEvent(functionId, logMessage: kvLogMessage);
                _session.PostEvent(telemetryEvent);
            }
            catch
            {
            }
        }
예제 #14
0
 public bool IsEnabled(FunctionId functionId)
 {
     return(_loggingChecker == null || _loggingChecker(functionId));
 }
예제 #15
0
 public void LogString(string message, FunctionId functionId)
 {
     WriteEvent(1, message ?? string.Empty, (int)functionId);
 }
예제 #16
0
 internal AggregateNode(DataTable?table, FunctionId aggregateType, string columnName) :
     this(table, aggregateType, columnName, true, null)
 {
 }
예제 #17
0
 public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
 {
     Trace.WriteLine(string.Format("[{0}] Start({1}) : {2} - {3}", Thread.CurrentThread.ManagedThreadId, uniquePairId, functionId.ToString(), logMessage.GetMessage()));
 }
예제 #18
0
 public Task <Segment <IAggregateEntry> > GetAggregateStatsAsync(FunctionId functionId, DateTime startTime, DateTime endTime, string continuationToken)
 {
     throw new NotImplementedException();
 }
예제 #19
0
        private static void FireCodeMarkers <T>(Dictionary <FunctionId, List <T> > map, FunctionId functionId, Func <T, int> getter)
        {
            if (!map.TryGetValue(functionId, out var items))
            {
                return;
            }

            for (var i = 0; i < items.Count; i++)
            {
                var marker = getter(items[i]);
                Microsoft.Internal.Performance.CodeMarkers.Instance.CodeMarker(marker);
            }
        }
예제 #20
0
 public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
 => TraceSource.TraceData(TraceEventType.Verbose, StartEventId, s_functionIdCache[functionId], uniquePairId);
예제 #21
0
 public void BlockStart(string message, FunctionId functionId, int blockId)
 {
     WriteEvent(2, message ?? string.Empty, (int)functionId, blockId);
 }
예제 #22
0
 public bool IsEnabled(FunctionId functionId)
 {
     // we log every roslyn activity
     return(true);
 }
예제 #23
0
 public void Log(FunctionId functionId, LogMessage logMessage)
 => TraceSource.TraceData(TraceEventType.Verbose, LogEventId, s_functionIdCache[functionId], logMessage.GetMessage());
예제 #24
0
        private TelemetryEvent CreateTelemetryEvent(FunctionId functionId, KeyValueLogMessage logMessage)
        {
            var eventName = functionId.GetEventName();

            return(AppendProperties(new TelemetryEvent(eventName), functionId, logMessage));
        }
예제 #25
0
 public bool IsEnabled(FunctionId functionId)
 => true;
예제 #26
0
        public void Import(IAcDomain acDomain, IAcSession acSession, string appSystemCode)
        {
            if (_isChanged)
            {
                lock (Locker)
                {
                    if (_isChanged)
                    {
                        var privilegeBigramRepository = acDomain.RetrieveRequiredService <IRepository <Privilege> >();
                        if (string.IsNullOrEmpty(appSystemCode))
                        {
                            throw new ArgumentNullException("appSystemCode");
                        }
                        AppSystemState appSystem;
                        if (!acDomain.AppSystemSet.TryGetAppSystem(appSystemCode, out appSystem))
                        {
                            throw new ValidationException("意外的应用系统码" + appSystemCode);
                        }
                        // TODO:提取配置
                        var assemblyStrings = new List <string> {
                            "Anycmd.Ac.Web.Mvc",
                            "Anycmd.Edi.Web.Mvc",
                            "Anycmd.Mis.Web.Mvc"
                        };
                        var dlls                = assemblyStrings.Select(Assembly.Load).ToList();
                        var oldPages            = acDomain.UiViewSet;
                        var oldFunctions        = acDomain.FunctionSet.Cast <IFunction>().ToList();
                        var reflectionFunctions = new List <FunctionId>();
                        #region 通过反射程序集初始化功能和页面列表
                        foreach (var dll in dlls)
                        {
                            // 注意这里约定区域名为二级命名空间的名字
                            var areaCode = dll.GetName().Name.Split('.')[1];

                            var types            = dll.GetTypes();
                            var actionResultType = typeof(ActionResult);
                            var controllerType   = typeof(AnycmdController);
                            var viewResultType   = typeof(ViewResultBase);
                            foreach (var type in types)
                            {
                                var isController = controllerType.IsAssignableFrom(type);
                                // 跳过不是Controller的类型
                                if (!isController)
                                {
                                    continue;
                                }
                                var controller   = type.Name.Substring(0, type.Name.Length - "Controller".Length);
                                var resourceCode = controller;// 注意这里约定资源码等于控制器名
                                var methodInfos  = type.GetMethods();
                                int sortCode     = 10;
                                foreach (var method in methodInfos)
                                {
                                    bool   isPage   = viewResultType.IsAssignableFrom(method.ReturnType);
                                    bool   isAction = isPage || actionResultType.IsAssignableFrom(method.ReturnType);
                                    string action   = method.Name;

                                    CatalogState resource;
                                    string       description;
                                    Guid         developerId;
                                    // 跳过不是Action的方法
                                    if (!isAction)
                                    {
                                        continue;
                                    }
                                    var descriptionAttrs = method.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), inherit: false);
                                    // 如果打有描述文本标记则使用描述文本作为操作说明,否则试用Action方法名
                                    if (descriptionAttrs.Length > 0)
                                    {
                                        description = ((DescriptionAttribute)descriptionAttrs[0]).Description;
                                        if (string.IsNullOrEmpty(description))
                                        {
                                            description = action;
                                        }
                                    }
                                    else
                                    {
                                        description = action;
                                    }
                                    object[] byAttrs = method.GetCustomAttributes(typeof(ByAttribute), inherit: false);
                                    if (byAttrs.Length > 0)
                                    {
                                        string       loginName = ((ByAttribute)byAttrs[0]).DeveloperCode;
                                        AccountState developer;
                                        if (!acDomain.SysUserSet.TryGetDevAccount(loginName, out developer))
                                        {
                                            throw new ValidationException("意外的开发人员" + loginName + "在" + controllerType.FullName + "在" + method.Name);
                                        }
                                        developerId = developer.Id;
                                    }
                                    else
                                    {
                                        throw new ValidationException(type.FullName + method.Name);
                                    }

                                    if (!acDomain.CatalogSet.TryGetCatalog(appSystem.Code + "." + resourceCode, out resource))
                                    {
                                        throw new ValidationException("意外的资源码" + resourceCode);
                                    }
                                    var oldFunction = oldFunctions.FirstOrDefault(
                                        o => o.ResourceTypeId == resource.Id &&
                                        string.Equals(o.Code, action, StringComparison.OrdinalIgnoreCase));
                                    if (oldFunction == null)
                                    {
                                        // TODO:持久化托管标识
                                        var function = FunctionId.Create(Guid.NewGuid(), appSystemCode, areaCode, resourceCode, action);
                                        if (reflectionFunctions.Any(a => a.AreaCode == areaCode && a.ResourceCode == resourceCode && string.Equals(a.FunctionCode, action, StringComparison.OrdinalIgnoreCase)))
                                        {
                                            throw new ValidationException("同一Controller下不能有命名相同的Action。" + method.DeclaringType.FullName + "." + method.Name);
                                        }
                                        reflectionFunctions.Add(function);
                                        acDomain.Handle(new FunctionCreateInput()
                                        {
                                            Description    = description,
                                            DeveloperId    = developerId,
                                            Id             = function.Id,
                                            IsEnabled      = 1,
                                            IsManaged      = false,
                                            ResourceTypeId = resource.Id,
                                            SortCode       = sortCode,
                                            Code           = function.FunctionCode
                                        }.ToCommand(acSession));
                                        if (isPage)
                                        {
                                            acDomain.Handle(new UiViewCreateInput
                                            {
                                                Id = function.Id
                                            }.ToCommand(acSession));
                                        }
                                    }
                                    else
                                    {
                                        // TODO:持久化托管标识
                                        // 更新作者
                                        if (oldFunction.DeveloperId != developerId)
                                        {
                                            acDomain.Handle(new FunctionUpdateInput
                                            {
                                                Code        = oldFunction.Code,
                                                Description = oldFunction.Description,
                                                DeveloperId = developerId,
                                                Id          = oldFunction.Id,
                                                SortCode    = oldFunction.SortCode
                                            }.ToCommand(acSession));
                                        }
                                        reflectionFunctions.Add(FunctionId.Create(oldFunction.Id, appSystemCode, areaCode, resourceCode, action));
                                        if (isPage)
                                        {
                                            if (oldPages.All(a => a.Id != oldFunction.Id))
                                            {
                                                acDomain.Handle(new UiViewCreateInput
                                                {
                                                    Id = oldFunction.Id
                                                }.ToCommand(acSession));
                                            }
                                        }
                                        else
                                        {
                                            // 删除废弃的页面
                                            if (oldPages.All(a => a.Id != oldFunction.Id))
                                            {
                                                acDomain.Handle(new RemoveUiViewCommand(acSession, oldFunction.Id));
                                            }
                                        }
                                    }
                                    sortCode += 10;
                                }
                            }
                        }
                        #endregion
                        #region  除废弃的功能
                        foreach (var oldFunction in oldFunctions)
                        {
                            if (reflectionFunctions.All(o => o.Id != oldFunction.Id))
                            {
                                // 删除角色功能
                                var privilegeType = AcElementType.Function.ToName();
                                foreach (var rolePrivilege in privilegeBigramRepository.AsQueryable().Where(a => privilegeType == a.ObjectType && a.ObjectInstanceId == oldFunction.Id).ToList())
                                {
                                    privilegeBigramRepository.Remove(rolePrivilege);
                                    acDomain.EventBus.Publish(new PrivilegeRemovedEvent(acSession, rolePrivilege));
                                }
                                acDomain.EventBus.Commit();
                                privilegeBigramRepository.Context.Commit();
                                acDomain.Handle(new RemoveFunctionCommand(acSession, oldFunction.Id));
                            }
                        }
                        #endregion
                        _isChanged = false;
                    }
                }
            }
        }
예제 #27
0
 public void BlockCanceled(FunctionId functionId, int number, int blockId)
 {
     WriteEvent(4, (int)functionId, number, blockId);
 }
예제 #28
0
 public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
 => TraceSource.TraceData(TraceEventType.Verbose, EndEventId, s_functionIdCache[functionId], uniquePairId, cancellationToken.IsCancellationRequested, delta, logMessage.GetMessage());
예제 #29
0
        private static bool GetDefaultValue(FunctionId id)
        {
            switch (id)
            {
                case FunctionId.TestEvent_NotUsed:
                    return false;

                case FunctionId.Tagger_AdornmentManager_OnLayoutChanged:
                case FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans:
                case FunctionId.Tagger_BatchChangeNotifier_NotifyEditorNow:
                case FunctionId.Tagger_BatchChangeNotifier_NotifyEditor:
                case FunctionId.Tagger_TagSource_ProcessNewTags:
                case FunctionId.Tagger_SyntacticClassification_TagComputer_GetTags:
                case FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags:
                case FunctionId.Tagger_BraceHighlighting_TagProducer_ProduceTags:
                case FunctionId.Tagger_LineSeparator_TagProducer_ProduceTags:
                case FunctionId.Tagger_Outlining_TagProducer_ProduceTags:
                case FunctionId.Tagger_Highlighter_TagProducer_ProduceTags:
                case FunctionId.Tagger_ReferenceHighlighting_TagProducer_ProduceTags:
                    return false;

                case FunctionId.Workspace_SourceText_GetChangeRanges:
                case FunctionId.Workspace_Recoverable_RecoverRootAsync:
                case FunctionId.Workspace_Recoverable_RecoverRoot:
                case FunctionId.Workspace_Recoverable_RecoverTextAsync:
                case FunctionId.Workspace_Recoverable_RecoverText:
                    return false;

                case FunctionId.Misc_NonReentrantLock_BlockingWait:
                    return false;

                case FunctionId.Cache_Created:
                case FunctionId.Cache_AddOrAccess:
                case FunctionId.Cache_Remove:
                case FunctionId.Cache_Evict:
                case FunctionId.Cache_EvictAll:
                case FunctionId.Cache_ItemRank:
                    return false;

                case FunctionId.Simplifier_ReduceAsync:
                case FunctionId.Simplifier_ExpandNode:
                case FunctionId.Simplifier_ExpandToken:
                    return false;

                case FunctionId.TemporaryStorageServiceFactory_ReadText:
                case FunctionId.TemporaryStorageServiceFactory_WriteText:
                case FunctionId.TemporaryStorageServiceFactory_ReadStream:
                case FunctionId.TemporaryStorageServiceFactory_WriteStream:
                    return false;

                case FunctionId.WorkCoordinator_DocumentWorker_Enqueue:
                case FunctionId.WorkCoordinator_ProcessProjectAsync:
                case FunctionId.WorkCoordinator_ProcessDocumentAsync:
                case FunctionId.WorkCoordinator_SemanticChange_Enqueue:
                case FunctionId.WorkCoordinator_SemanticChange_EnqueueFromMember:
                case FunctionId.WorkCoordinator_SemanticChange_EnqueueFromType:
                case FunctionId.WorkCoordinator_SemanticChange_FullProjects:
                case FunctionId.WorkCoordinator_Project_Enqueue:
                    return false;

                case FunctionId.Diagnostics_SyntaxDiagnostic:
                case FunctionId.Diagnostics_SemanticDiagnostic:
                case FunctionId.Diagnostics_ProjectDiagnostic:
                case FunctionId.Diagnostics_DocumentReset:
                case FunctionId.Diagnostics_DocumentOpen:
                case FunctionId.Diagnostics_RemoveDocument:
                case FunctionId.Diagnostics_RemoveProject:
                    return false;

                default:
                    return true;
            }
        }
예제 #30
0
 public bool IsEnabled(FunctionId functionId)
 {
     return true;
 }
예제 #31
0
 public void BlockCanceled(FunctionId functionId, int tick, int blockId)
 {
     WriteEvent(5, (int)functionId, tick, blockId);
 }
예제 #32
0
 public void Log(FunctionId functionId, LogMessage logMessage)
 {
 }
예제 #33
0
 public bool IsEnabled(FunctionId functionId) => _session.IsOptedIn;
예제 #34
0
 public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
 {
 }
예제 #35
0
        private object EvalFunction(FunctionId id, object[] argumentValues, DataRow row, DataRowVersion version)
        {
            StorageType storageType;

            switch (id)
            {
            case FunctionId.Abs:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));

                storageType = DataStorage.GetStorageType(argumentValues[0].GetType());
                if (ExpressionNode.IsInteger(storageType))
                {
                    return(Math.Abs((long)argumentValues[0]));
                }
                if (ExpressionNode.IsNumeric(storageType))
                {
                    return(Math.Abs((double)argumentValues[0]));
                }

                throw ExprException.ArgumentTypeInteger(s_funcs[_info]._name, 1);

            case FunctionId.cBool:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));

                storageType = DataStorage.GetStorageType(argumentValues[0].GetType());
                switch (storageType)
                {
                case StorageType.Boolean:
                    return((bool)argumentValues[0]);

                case StorageType.Int32:
                    return((int)argumentValues[0] != 0);

                case StorageType.Double:
                    return((double)argumentValues[0] != 0.0);

                case StorageType.String:
                    return(bool.Parse((string)argumentValues[0]));

                default:
                    throw ExprException.DatatypeConvertion(argumentValues[0].GetType(), typeof(bool));
                }

            case FunctionId.cInt:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));
                return(Convert.ToInt32(argumentValues[0], FormatProvider));

            case FunctionId.cDate:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));
                return(Convert.ToDateTime(argumentValues[0], FormatProvider));

            case FunctionId.cDbl:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));
                return(Convert.ToDouble(argumentValues[0], FormatProvider));

            case FunctionId.cStr:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));
                return(Convert.ToString(argumentValues[0], FormatProvider));

            case FunctionId.Charindex:
                Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));

                Debug.Assert(argumentValues[0] is string, "Invalid argument type for " + s_funcs[_info]._name);
                Debug.Assert(argumentValues[1] is string, "Invalid argument type for " + s_funcs[_info]._name);

                if (DataStorage.IsObjectNull(argumentValues[0]) || DataStorage.IsObjectNull(argumentValues[1]))
                {
                    return(DBNull.Value);
                }

                if (argumentValues[0] is SqlString)
                {
                    argumentValues[0] = ((SqlString)argumentValues[0]).Value;
                }

                if (argumentValues[1] is SqlString)
                {
                    argumentValues[1] = ((SqlString)argumentValues[1]).Value;
                }

                return(((string)argumentValues[1]).IndexOf((string)argumentValues[0], StringComparison.Ordinal));

            case FunctionId.Iif:
                Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider));

                object first = _arguments[0].Eval(row, version);

                if (DataExpression.ToBoolean(first) != false)
                {
                    return(_arguments[1].Eval(row, version));
                }
                else
                {
                    return(_arguments[2].Eval(row, version));
                }

            case FunctionId.In:
                // we never evaluate IN directly: IN as a binary operator, so evaluation of this should be in
                // BinaryNode class
                throw ExprException.NYI(s_funcs[_info]._name);

            case FunctionId.IsNull:
                Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount: ");

                if (DataStorage.IsObjectNull(argumentValues[0]))
                {
                    return(argumentValues[1]);
                }
                else
                {
                    return(argumentValues[0]);
                }

            case FunctionId.Len:
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));
                Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name);

                if (argumentValues[0] is SqlString)
                {
                    if (((SqlString)argumentValues[0]).IsNull)
                    {
                        return(DBNull.Value);
                    }
                    else
                    {
                        argumentValues[0] = ((SqlString)argumentValues[0]).Value;
                    }
                }

                return(((string)argumentValues[0]).Length);


            case FunctionId.Substring:
                Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider));
                Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid first argument " + argumentValues[0].GetType().FullName + " in " + s_funcs[_info]._name);
                Debug.Assert(argumentValues[1] is int, "Invalid second argument " + argumentValues[1].GetType().FullName + " in " + s_funcs[_info]._name);
                Debug.Assert(argumentValues[2] is int, "Invalid third argument " + argumentValues[2].GetType().FullName + " in " + s_funcs[_info]._name);

                // work around the differences in .NET and VBA implementation of the Substring function
                // 1. The <index> Argument is 0-based in .NET, and 1-based in VBA
                // 2. If the <Length> argument is longer then the string length .NET throws an ArgumentException
                //    but our users still want to get a result.

                int start = (int)argumentValues[1] - 1;

                int length = (int)argumentValues[2];

                if (start < 0)
                {
                    throw ExprException.FunctionArgumentOutOfRange("index", "Substring");
                }

                if (length < 0)
                {
                    throw ExprException.FunctionArgumentOutOfRange("length", "Substring");
                }

                if (length == 0)
                {
                    return(string.Empty);
                }

                if (argumentValues[0] is SqlString)
                {
                    argumentValues[0] = ((SqlString)argumentValues[0]).Value;
                }

                int src_length = ((string)argumentValues[0]).Length;

                if (start > src_length)
                {
                    return(DBNull.Value);
                }

                if (start + length > src_length)
                {
                    length = src_length - start;
                }

                return(((string)argumentValues[0]).Substring(start, length));

            case FunctionId.Trim:
            {
                Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider));
                Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name);

                if (DataStorage.IsObjectNull(argumentValues[0]))
                {
                    return(DBNull.Value);
                }

                if (argumentValues[0] is SqlString)
                {
                    argumentValues[0] = ((SqlString)argumentValues[0]).Value;
                }

                return(((string)argumentValues[0]).Trim());
            }

            case FunctionId.Convert:
                if (_argumentCount != 2)
                {
                    throw ExprException.FunctionArgumentCount(_name);
                }

                if (argumentValues[0] == DBNull.Value)
                {
                    return(DBNull.Value);
                }

                Type        type   = (Type)argumentValues[1];
                StorageType mytype = DataStorage.GetStorageType(type);
                storageType = DataStorage.GetStorageType(argumentValues[0].GetType());

                if (mytype == StorageType.DateTimeOffset)
                {
                    if (storageType == StorageType.String)
                    {
                        return(SqlConvert.ConvertStringToDateTimeOffset((string)argumentValues[0], FormatProvider));
                    }
                }

                if (StorageType.Object != mytype)
                {
                    if ((mytype == StorageType.Guid) && (storageType == StorageType.String))
                    {
                        return(new Guid((string)argumentValues[0]));
                    }

                    if (ExpressionNode.IsFloatSql(storageType) && ExpressionNode.IsIntegerSql(mytype))
                    {
                        if (StorageType.Single == storageType)
                        {
                            return(SqlConvert.ChangeType2((float)SqlConvert.ChangeType2(argumentValues[0], StorageType.Single, typeof(float), FormatProvider), mytype, type, FormatProvider));
                        }
                        else if (StorageType.Double == storageType)
                        {
                            return(SqlConvert.ChangeType2((double)SqlConvert.ChangeType2(argumentValues[0], StorageType.Double, typeof(double), FormatProvider), mytype, type, FormatProvider));
                        }
                        else if (StorageType.Decimal == storageType)
                        {
                            return(SqlConvert.ChangeType2((decimal)SqlConvert.ChangeType2(argumentValues[0], StorageType.Decimal, typeof(decimal), FormatProvider), mytype, type, FormatProvider));
                        }
                        return(SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider));
                    }

                    return(SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider));
                }

                return(argumentValues[0]);

            case FunctionId.DateTimeOffset:
                if (argumentValues[0] == DBNull.Value || argumentValues[1] == DBNull.Value || argumentValues[2] == DBNull.Value)
                {
                    return(DBNull.Value);
                }
                switch (((DateTime)argumentValues[0]).Kind)
                {
                case DateTimeKind.Utc:
                    if ((int)argumentValues[1] != 0 && (int)argumentValues[2] != 0)
                    {
                        throw ExprException.MismatchKindandTimeSpan();
                    }
                    break;

                case DateTimeKind.Local:
                    if (DateTimeOffset.Now.Offset.Hours != (int)argumentValues[1] && DateTimeOffset.Now.Offset.Minutes != (int)argumentValues[2])
                    {
                        throw ExprException.MismatchKindandTimeSpan();
                    }
                    break;

                case DateTimeKind.Unspecified: break;
                }
                if ((int)argumentValues[1] < -14 || (int)argumentValues[1] > 14)
                {
                    throw ExprException.InvalidHoursArgument();
                }
                if ((int)argumentValues[2] < -59 || (int)argumentValues[2] > 59)
                {
                    throw ExprException.InvalidMinutesArgument();
                }
                // range should be within -14 hours and  +14 hours
                if ((int)argumentValues[1] == 14 && (int)argumentValues[2] > 0)
                {
                    throw ExprException.InvalidTimeZoneRange();
                }
                if ((int)argumentValues[1] == -14 && (int)argumentValues[2] < 0)
                {
                    throw ExprException.InvalidTimeZoneRange();
                }

                return(new DateTimeOffset((DateTime)argumentValues[0], new TimeSpan((int)argumentValues[1], (int)argumentValues[2], 0)));

            default:
                throw ExprException.UndefinedFunction(s_funcs[_info]._name);
            }
        }
예제 #36
0
 public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
 {
 }
예제 #37
0
        public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
        {
            var functionString = functionId.ToString() + (cancellationToken.IsCancellationRequested ? " Canceled" : string.Empty);

            Trace.WriteLine(string.Format("[{0}] End({1}) : [{2}ms] {3}", Thread.CurrentThread.ManagedThreadId, uniquePairId, delta, functionString));
        }
예제 #38
0
파일: DataModel.cs 프로젝트: belav/roslyn
 public void BlockStart(FunctionId functionId)
 {
     _activities[(int)functionId - 1].Start();
 }
예제 #39
0
 public void Log(FunctionId functionId, LogMessage logMessage)
 {
     Trace.WriteLine(string.Format("[{0}] {1} - {2}", Thread.CurrentThread.ManagedThreadId, functionId.ToString(), logMessage.GetMessage()));
 }
예제 #40
0
파일: DataModel.cs 프로젝트: belav/roslyn
 public void BlockDisposed(FunctionId functionId)
 {
     _activities[(int)functionId - 1].Stop();
 }
예제 #41
0
 public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
 {
     _model.BlockDisposed(functionId);
 }
예제 #42
0
파일: Logger.cs 프로젝트: stark-lang/stark
 /// <summary>
 /// simplest way to log a start and end pair
 /// </summary>
 public static IDisposable LogBlock(FunctionId functionId, CancellationToken token)
 {
     return(LogBlock(functionId, string.Empty, token));
 }
예제 #43
0
 public void BlockStop(FunctionId functionId, int number, int blockId)
 {
     WriteEvent(3, (int)functionId, number, blockId);
 }
예제 #44
0
 private static bool CanHandle(FunctionId functionId)
 {
     return s_functionIds.Contains(functionId);
 }
예제 #45
0
 public static Option<bool> GetOption(FunctionId id)
 {
     return options.GetOrAdd(id, optionGetter);
 }
예제 #46
0
 public bool IsEnabled(FunctionId functionId)
 {
     return CanHandle(functionId);
 }
예제 #47
0
 public void Log(string message, FeatureId featureId, FunctionId functionId)
 {
     WriteEvent(1, message ?? string.Empty, (int)featureId, (int)functionId);
 }
예제 #48
0
 public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
 {
     var eventName = functionId.GetEventName();
     _pendingActivities[uniquePairId] = new TelemetryActivity(_service, eventName, startCodeMarker: 0, endCodeMarker: 0, codeMarkerData: null, parentCorrelationId: Guid.Empty);
 }
예제 #49
0
 public void BlockStop(FunctionId functionId, int tick, int blockId)
 {
     WriteEvent(3, (int)functionId, tick, blockId);
 }
예제 #50
0
 public Function Get(FunctionId id)
 {
     if (!_functions.ContainsKey(id) && Function.ArgumentRegex.IsMatch(id.Id))
     {
         AddUserFunctionArgument(int.Parse(id.Id[1..]));
        /// <devdoc>
        ///     parse the argument to an Aggregate function.
        ///     the syntax is
        ///          Func(child[(relation_name)].column_name)
        ///     When the function is called we have already parsed the Aggregate name, and open paren
        /// </devdoc>
        private ExpressionNode ParseAggregateArgument(FunctionId aggregate) {
            Debug.Assert(token == Tokens.LeftParen, "ParseAggregateArgument(): Invalid argument, token <> '('");

            bool child;
            string relname;
            string colname;

            Scan();

            try {
                if (token != Tokens.Child) {
                    if (token != Tokens.Name)
                        throw ExprException.AggregateArgument();

                    colname = NameNode.ParseName(text, start, pos);
                    ScanToken(Tokens.RightParen);
                    return new AggregateNode(_table, aggregate, colname);
                }

                child = (token == Tokens.Child);
                prevOperand = Scalar;

                // expecting an '(' or '.'
                Scan();

                if (token == Tokens.LeftParen) {
                    //read the relation name
                    ScanToken(Tokens.Name);
                    relname = NameNode.ParseName(text, start, pos);
                    ScanToken(Tokens.RightParen);
                    ScanToken(Tokens.Dot);
                }
                else {
                    relname = null;
                    CheckToken(Tokens.Dot);
                }

                ScanToken(Tokens.Name);
                colname = NameNode.ParseName(text, start, pos);
                ScanToken(Tokens.RightParen);
            }
            catch (Exception e){
                // 
                if (!Common.ADP.IsCatchableExceptionType(e)) {
                    throw;
                }
                throw ExprException.AggregateArgument();
            }
            return new AggregateNode(_table, aggregate, colname, !child, relname);
        }
예제 #52
0
 private static bool CanHandle(FunctionId functionId)
 {
     return(s_map.ContainsKey(functionId) || s_blockMap.ContainsKey(functionId));
 }
예제 #53
0
 public static Option<bool> GetOption(FunctionId id)
 {
     return s_options.GetOrAdd(id, s_optionCreator);
 }
예제 #54
0
 public FunctionIdAttribute(FunctionId functionId)
     : base((uint)functionId)
 {
 }
예제 #55
0
 public void Log(FunctionId functionId, LogMessage logMessage)
 {
     Contract.Fail("Shouldn't be called");
 }
예제 #56
0
 public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
 {
     FireCodeMarkers(s_blockMap, functionId, s_startGetter);
 }
예제 #57
0
 public bool IsEnabled(FunctionId functionId)
 {
     return(Microsoft.Internal.Performance.CodeMarkers.Instance.IsEnabled && CanHandle(functionId));
 }
예제 #58
0
 public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
 {
     FireCodeMarkers(s_map, functionId, s_getter);
     FireCodeMarkers(s_blockMap, functionId, s_endGetter);
 }
예제 #59
0
 private static void LogAction(FunctionId functionId, object provider)
 {
     if (IsRoslynCodefix(provider))
     {
         Log(functionId, $"Name: {provider.GetType().FullName} Assembly Version: {provider.GetType().Assembly.GetName().Version}");
     }
     else
     {
         Log(functionId);
     }
 }
예제 #60
0
 public void Log(FunctionId functionId, LogMessage logMessage)
 {
     FireCodeMarkers(s_map, functionId, s_getter);
 }