Ejemplo n.º 1
0
        public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node)
        {
            var jsBlock = new JsBlockStatement();

            var model     = Context.Instance.Compilation.GetSemanticModel(node.SyntaxTree);
            var classType = (INamedTypeSymbol)ModelExtensions.GetDeclaredSymbol(model, node);

            if (processedTypes.Contains(classType))
            {
                return;
            }
            processedTypes.Add(classType);

            JsBlockStatement typeInitializer;
            JsBlockStatement staticInitializer;

            jsBlock.Aggregate(idioms.CreateTypeFunction(classType, out typeInitializer, out staticInitializer));

            // Create default constructor
            var constructorBlock = new JsBlockStatement();

            constructorBlock.Express(idioms.InvokeMethodAsThis(classType.BaseType.InstanceConstructors.Single(x => x.Parameters.Count() == 0)));
            var constructor = classType.InstanceConstructors.Single();

            typeInitializer.Add(idioms.StoreInPrototype(constructor.GetMemberName(), Js.Function().Body(constructorBlock)));
            typeInitializer.Aggregate(idioms.InitializeConstructor(classType, constructor.GetMemberName(), new IParameterSymbol[0]));

            foreach (var property in classType.GetMembers().OfType <IPropertySymbol>())
            {
                typeInitializer.Aggregate(CreateProperty(property));
            }

            Action action = () =>
            {
                body.Aggregate(jsBlock);
            };

            actions.Add(Tuple.Create(classType, action));
        }
        public int Calculate(TypeDeclarationSyntax type)
        {
            int num = 0;

            if (type.BaseList != null)
            {
                SeparatedSyntaxList <BaseTypeSyntax> .Enumerator enumerator = type.BaseList.Types.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    BaseTypeSyntax current    = enumerator.Current;
                    SymbolInfo     symbolInfo = ModelExtensions.GetSymbolInfo(this.semanticModel, current, new CancellationToken());
                    for (INamedTypeSymbol i = symbolInfo.Symbol as INamedTypeSymbol; i != null; i = i.BaseType)
                    {
                        if (this.inheritableTypes.Any <TypeKind>((TypeKind x) => x == i.TypeKind))
                        {
                            num = checked (num + 1);
                        }
                    }
                }
            }
            return(num);
        }
Ejemplo n.º 3
0
        public override void VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            if (ModelExtensions.GetSymbolInfo(model, node).Symbol is IMethodSymbol symbol)
            {
                var isStep = IsStep(symbol);
                var isTask = IsTask(symbol);

                if (isStep || isTask)
                {
                    var task = result.Find(symbol);
                    if (task == null)
                    {
                        task = new Task(symbol, isStep);
                        result.Add(symbol, task);
                    }

                    current?.AddDependency(task);
                }
            }

            base.VisitInvocationExpression(node);
        }
        protected bool SaveCoverImages(string bookID, Stream imageStream)
        {
            var  @event = new AutoResetEvent(false);
            bool result = false;

            ((Action)(() =>
            {
                try
                {
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(imageStream);

                    using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var iconImageFile = isoStorage.CreateFile(ModelExtensions.GetBookCoverPath(bookID)))
                        {
                            bitmapImage.SaveJpeg(iconImageFile, 300, 300, true);
                        }

                        using (var coverImageFile = isoStorage.CreateFile(ModelExtensions.GetBookFullCoverPath(bookID)))
                        {
                            bitmapImage.SaveJpeg(coverImageFile, bitmapImage.PixelWidth, bitmapImage.PixelHeight, false);
                        }
                    }
                    result = true;
                }
                catch (Exception)
                {
                    result = false;
                }
                finally
                {
                    @event.Set();
                }
            })).OnUIThread();

            @event.WaitOne();
            return(result);
        }
Ejemplo n.º 5
0
            /// <summary>
            /// Update the specified object
            /// </summary>
            protected override TModel UpdateInternal(LocalDataContext context, TModel data)
            {
                if (data.IsEmpty())
                {
                    return(data);
                }

                foreach (var rp in this.m_properties)
                {
                    var instance = rp.GetValue(data);
                    if (instance != null && rp.Name != "SourceEntity") // HACK: Prevent infinite loops on associtive entities
                    {
                        instance = ModelExtensions.TryGetExisting(instance as IIdentifiedEntity, context);
                        if (instance != null)
                        {
                            rp.SetValue(data, instance);
                        }
                        ModelExtensions.UpdateParentKeys(data, rp);
                    }
                }
                return(base.UpdateInternal(context, data));
            }
Ejemplo n.º 6
0
        public PSKeyVault(Vault vault, ActiveDirectoryClient adClient)
        {
            var vaultTenantDisplayName = ModelExtensions.GetDisplayNameForTenant(vault.Properties.TenantId, adClient);

            VaultName         = vault.Name;
            Location          = vault.Location;
            ResourceId        = vault.Id;
            ResourceGroupName = (new ResourceIdentifier(vault.Id)).ResourceGroupName;
            Tags                         = TagsConversionHelper.CreateTagHashtable(vault.Tags);
            Sku                          = vault.Properties.Sku.Name.ToString();
            TenantId                     = vault.Properties.TenantId;
            TenantName                   = vaultTenantDisplayName;
            VaultUri                     = vault.Properties.VaultUri;
            EnabledForDeployment         = vault.Properties.EnabledForDeployment.HasValue ? vault.Properties.EnabledForDeployment.Value : false;
            EnabledForTemplateDeployment = vault.Properties.EnabledForTemplateDeployment;
            EnabledForDiskEncryption     = vault.Properties.EnabledForDiskEncryption;
            EnableSoftDelete             = vault.Properties.EnableSoftDelete;
            EnablePurgeProtection        = vault.Properties.EnablePurgeProtection;
            AccessPolicies               = vault.Properties.AccessPolicies.Select(s => new PSKeyVaultAccessPolicy(s, adClient)).ToArray();
            NetworkAcls                  = InitNetworkRuleSet(vault.Properties);
            OriginalVault                = vault;
        }
Ejemplo n.º 7
0
        private VariableDeclaratorSyntax ConvertToVariableDeclarator(CSS.DeclarationExpressionSyntax des)
        {
            var        id  = ((IdentifierNameSyntax)des.Accept(_nodesVisitor)).Identifier;
            var        ids = SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(id));
            TypeSyntax typeSyntax;

            if (des.Type.IsVar)
            {
                var typeSymbol = ModelExtensions.GetSymbolInfo(_semanticModel, des.Type).ExtractBestMatch <ITypeSymbol>();
                typeSyntax = typeSymbol?.ToVbSyntax(_semanticModel, des.Type);
            }
            else
            {
                typeSyntax = (TypeSyntax)des.Type.Accept(_nodesVisitor);
            }

            var simpleAsClauseSyntax = typeSyntax != null?SyntaxFactory.SimpleAsClause(typeSyntax) : null;   //Gracefully degrade when no type information available

            var equalsValueSyntax = SyntaxFactory.EqualsValue(SyntaxFactory.LiteralExpression(SyntaxKind.NothingLiteralExpression, SyntaxFactory.Token(SyntaxKind.NothingKeyword)));

            return(SyntaxFactory.VariableDeclarator(ids, simpleAsClauseSyntax, equalsValueSyntax));
        }
Ejemplo n.º 8
0
        private VariableDeclaratorSyntax ConvertToVariableDeclarator(CSS.PropertyDeclarationSyntax des)
        {
            var        id  = GetVbPropertyBackingFieldName(des);
            var        ids = SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(id));
            TypeSyntax typeSyntax;

            if (des.Type.IsVar)
            {
                var typeSymbol = ModelExtensions.GetSymbolInfo(_semanticModel, des.Type).ExtractBestMatch <ITypeSymbol>();
                typeSyntax = typeSymbol?.ToVbSyntax(_semanticModel, des.Type);
            }
            else
            {
                typeSyntax = (TypeSyntax)des.Type.Accept(_nodesVisitor);
            }

            var simpleAsClauseSyntax = typeSyntax != null?SyntaxFactory.SimpleAsClause(typeSyntax) : null;   //Gracefully degrade when no type information available

            EqualsValueSyntax equalsValueSyntax = null;

            return(SyntaxFactory.VariableDeclarator(ids, simpleAsClauseSyntax, equalsValueSyntax));
        }
Ejemplo n.º 9
0
        protected override object VisitPropertyDeclaration(PropertyDeclarationSyntax node)
        {
            var info   = ModelExtensions.GetSymbolInfo(context.RoslynModel, node.Type);
            var symbol = info.Symbol as ITypeSymbol;

            if (symbol == null)
            {
                throw new NotSupportedException();
            }
            var tt = context.Roslyn_ResolveType(symbol);

            var propertyName = _Name(node.Identifier);
            var mod          = VisitModifiers(node.Modifiers);
            var accessors    = node.AccessorList.Accessors.Select(i => Visit(i) as CsharpPropertyDeclarationAccessor)
                               .ToArray();
            var type = _ResolveLangType(node.Type);

            var doc         = DeclarationItemDescription.Parse(node);
            var declaration = new CsharpPropertyDeclaration(propertyName, type, accessors, mod, doc);

            return(declaration);
        }
Ejemplo n.º 10
0
            /// <summary>
            /// Ensure exists
            /// </summary>
            protected override TModel InsertInternal(LocalDataContext context, TModel data)
            {
                foreach (var rp in typeof(TModel).GetRuntimeProperties().Where(o => typeof(IdentifiedData).GetTypeInfo().IsAssignableFrom(o.PropertyType.GetTypeInfo())))
                {
                    if (rp.GetCustomAttribute <DataIgnoreAttribute>() != null)
                    {
                        continue;
                    }

                    var instance = rp.GetValue(data);
                    if (instance != null)
                    {
                        instance = ModelExtensions.TryGetExisting(instance as IIdentifiedEntity, context);
                        if (instance != null)
                        {
                            rp.SetValue(data, instance);
                        }
                        ModelExtensions.UpdateParentKeys(data, rp);
                    }
                }
                return(base.InsertInternal(context, data));
            }
        public override void ExecuteCmdlet()
        {
            IDictionary <string, string> tagPairs = null;

            if (Tag != null)
            {
                tagPairs = new Dictionary <string, string>();

                foreach (string key in Tag.Keys)
                {
                    tagPairs.Add(key, Tag[key].ToString());
                }
            }

            if (ParameterSetName == ResourceIdParameterSet)
            {
                var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
                ResourceGroupName = resourceIdentifier.ResourceGroupName;
                Name = resourceIdentifier.ResourceName;
            }
            else if (ParameterSetName == ObjectParameterSet)
            {
                ResourceGroupName = InputObject.ResourceGroupName;
                Name = InputObject.Name;
            }

            var netAppAccountBody = new NetAppAccountPatch()
            {
                Location          = Location,
                ActiveDirectories = (ActiveDirectory != null) ? ModelExtensions.ConvertActiveDirectoriesFromPs(ActiveDirectory) : null,
                Tags = tagPairs,
            };

            if (ShouldProcess(Name, string.Format(PowerShell.Cmdlets.NetAppFiles.Properties.Resources.UpdateResourceMessage, ResourceGroupName)))
            {
                var anfAccount = AzureNetAppFilesManagementClient.Accounts.Update(netAppAccountBody, ResourceGroupName, Name);
                WriteObject(anfAccount.ToPsNetAppFilesAccount());
            }
        }
Ejemplo n.º 12
0
        private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol asyncEnumerableUtility, INamedTypeSymbol asyncAction)
        {
            try
            {
                var invocation = (InvocationExpressionSyntax)context.Node;

                var method = context.SemanticModel.GetSymbolInfo(invocation.Expression).Symbol as IMethodSymbol;
                if (method?.Name != "UntilCanceled" || method.ContainingType != asyncEnumerableUtility)
                {
                    return;
                }

                if (invocation.ArgumentList.Arguments.Count != 0)
                {
                    return;
                }

                var containingMethod = invocation.Ancestors().OfType <MethodDeclarationSyntax>().FirstOrDefault();
                if (containingMethod is null)
                {
                    return;
                }

                var ienumerable      = context.SemanticModel.Compilation.GetTypeByMetadataName("System.Collections.Generic.IEnumerable`1");
                var returnTypeSymbol = ModelExtensions.GetSymbolInfo(context.SemanticModel, containingMethod.ReturnType).Symbol as INamedTypeSymbol;
                if (returnTypeSymbol?.ConstructedFrom == ienumerable && returnTypeSymbol?.TypeArguments[0] == asyncAction)
                {
                    return;
                }

                context.ReportDiagnostic(Diagnostic.Create(s_rule, invocation.ArgumentList.GetLocation()));
            }
            catch (NullReferenceException)
            {
                // A NullReferenceException happens inconsistently on the build server, breaking a small percentage of builds.
                // We have been unable to track it down, so are just ignoring it (and are trusting that the analyzer will work
                // to catch bugs on developers' systems.)
            }
        }
Ejemplo n.º 13
0
        public static void Write(this IdentifierNameSyntax syntax, IIndentedTextWriterWrapper textWriter, IContext context)
        {
            var symbol      = context.SemanticModel.GetSymbolInfo(syntax).Symbol;
            var classNode   = GetClassDeclarionSyntax(syntax);
            var classSymbol = (ITypeSymbol)ModelExtensions.GetDeclaredSymbol(context.SemanticModel, classNode);

            var previousToken         = syntax.GetFirstToken().GetPreviousToken();
            var previousPreviousToken = previousToken.GetPreviousToken();

            var isFollowingDot = previousToken.IsKind(SyntaxKind.DotToken);
            var identifierHasThisOrBaseReference =
                isFollowingDot && (
                    previousPreviousToken.IsKind(SyntaxKind.ThisKeyword) ||
                    previousPreviousToken.IsKind(SyntaxKind.BaseKeyword));

            var isPropertyFieldOrMethod =
                (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method);

            if ((!isFollowingDot || identifierHasThisOrBaseReference) && isPropertyFieldOrMethod && IsDeclaringTypeThisOrBase(symbol.ContainingType, classSymbol))
            {
                if (previousPreviousToken.IsKind(SyntaxKind.BaseKeyword))
                {
                    textWriter.Write("(element % _M.DOT_LVL(typeObject.Level - 1, true)).");
                }
                else
                {
                    textWriter.Write("(element % _M.DOT_LVL(typeObject.Level)).");
                }
            }

            if (symbol.Kind == SymbolKind.NamedType)
            {
                context.TypeReferenceWriter.WriteInteractionElementReference((ITypeSymbol)symbol, textWriter);
            }
            else
            {
                textWriter.Write(syntax.Identifier.Text);
            }
        }
Ejemplo n.º 14
0
        public bool IsVulnerable(SemanticModel model, AssignmentExpressionSyntax syntax)
        {
            if (!ContainsCertificateValidationCallback(syntax))
            {
                return(false);
            }

            var symbol = ModelExtensions.GetSymbolInfo(model, syntax.Left).Symbol as IPropertySymbol;

            if (symbol == null)
            {
                return(false);
            }

            //NOTE: only flagging those hard-coding a return value of true. Therefore could miss scenarios where the value is hardcoded in a const, config value.
            //TODO: therefore need dataflow to analyzer further
            //TODO: can we evaluate the expression? Possibly with the scripting lib. Would need to gather any references needed to execute.

            if (symbol.Name == "ServerCertificateValidationCallback" &&
                symbol.ContainingType.Name == "HttpWebRequest")
            {
                if (IsTrueLamdaExpression(syntax))
                {
                    return(true);
                }

                if (IsTrueDelegateMethod(syntax))
                {
                    return(true);
                }

                if (IsTrueMethod(model, syntax))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 15
0
        protected override async Task <EvaluationResult> EvaluateImpl(SyntaxNode node, SemanticModel semanticModel, Solution solution)
        {
            var classDeclaration = (ClassDeclarationSyntax)node;
            var symbol           = (ITypeSymbol)ModelExtensions.GetDeclaredSymbol(semanticModel, classDeclaration);
            var members          = symbol.GetMembers();

            var memberCount = members.Count(x => MemberKinds.Contains(x.Kind));

            if (memberCount < _threshold)
            {
                return(null);
            }

            var fields     = members.Where(x => x.Kind == SymbolKind.Field).AsArray();
            var fieldCount = fields.Length;

            if (fieldCount < _threshold)
            {
                return(null);
            }

            var references = await Task.WhenAll(fields.Select(solution.FindReferences)).ConfigureAwait(false);

            var sumFieldUsage = (double)references.Sum(r => r.Locations.Count());

            var lcomhs = (memberCount - (sumFieldUsage / fieldCount)) / (memberCount - 1);

            if (lcomhs < 1)
            {
                return(null);
            }

            var snippet = node.ToFullString();

            return(new EvaluationResult
            {
                Snippet = snippet
            });
        }
Ejemplo n.º 16
0
        public int Calculate(TypeDeclarationSyntax type)
        {
            var num = type.IsKind(SyntaxKind.ClassDeclaration) || type.IsKind(SyntaxKind.StructDeclaration) ? 1 : 0;

            if (type.BaseList != null)
            {
                foreach (var symbolInfo in type.BaseList.Types.Select(syntax => ModelExtensions.GetSymbolInfo(_semanticModel, syntax)))
                {
                    for (var symbol = symbolInfo.Symbol as INamedTypeSymbol; symbol != null; symbol = symbol.BaseType)
                    {
                        if (_inheritableTypes.Any(x => x == symbol.TypeKind))
                        {
                            num++;
                        }
                    }
                }
            }

            return(num == 0 && (type.IsKind(SyntaxKind.ClassDeclaration) || type.IsKind(SyntaxKind.StructDeclaration))
                                ? 1
                                : num);
        }
Ejemplo n.º 17
0
        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var fieldDeclaration = (FieldDeclarationSyntax)context.Node;
            var mods             = fieldDeclaration.Modifiers;

            // not readonly or private
            if (!mods.Any(SyntaxKind.ReadOnlyKeyword) || !mods.Any(SyntaxKind.PrivateKeyword))
            {
                return;
            }

            // not an interface
            var type         = fieldDeclaration.Declaration.Type;
            var variableType = ModelExtensions.GetTypeInfo(context.SemanticModel, type).ConvertedType;

            if (variableType.TypeKind != TypeKind.Interface)
            {
                return;
            }

            //    return false;

            var tree         = fieldDeclaration.SyntaxTree;
            var constructors = tree.GetRoot().DescendantNodes().OfType <ConstructorDeclarationSyntax>().ToList();
            var csor         = constructors.FirstOrDefault();

            if (csor != null)
            {
                if (csor.ParameterList.Parameters.ToString().Contains(type.ToString()))
                {
                    return;
                }
            }

            var diagnostic = Diagnostic.Create(InjectRule, fieldDeclaration.GetLocation());

            context.ReportDiagnostic(diagnostic);
        }
        private static async Task <Document> UsePropertyAssignment(Document document, AssignmentExpressionSyntax assignment, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var memberAccess = assignment.Left as MemberAccessExpressionSyntax;

            if (memberAccess == null)
            {
                return(document);
            }

            var symbol = ModelExtensions.GetSymbolInfo(semanticModel, memberAccess);

            if (symbol.Symbol is not IFieldSymbol field)
            {
                return(document);
            }

            var attributes = field.GetAttributes();
            var attribute  = attributes.First(w => w.AttributeClass.ToClassString() == UdonConstants.UdonSharpFieldChangeCallbackFullName);
            var reference  = await attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false) as AttributeSyntax;

            if (reference == null)
            {
                return(document);
            }

            var targetProperty = reference.ArgumentList.Arguments[0].Expression.ParseValue();
            var t        = semanticModel.GetTypeInfo(memberAccess.Expression);
            var members  = t.Type.GetMembers(targetProperty);
            var property = members.FirstOrDefault(w => w is IPropertySymbol p && p.Name == targetProperty) as IPropertySymbol;

            if (property == null)
            {
                return(document);
            }

            if (property.SetMethod is { DeclaredAccessibility : Accessibility.Public })
Ejemplo n.º 19
0
        public PSManagedHsm(ManagedHsm managedHsm, IMicrosoftGraphClient graphClient)
        {
            // PSKeyVaultIdentityItem's properties
            ResourceId        = managedHsm.Id;
            VaultName         = managedHsm.Name;
            ResourceGroupName = (new ResourceIdentifier(managedHsm.Id)).ResourceGroupName;
            Location          = managedHsm.Location;
            Tags = TagsConversionHelper.CreateTagHashtable(managedHsm.Tags);

            // PSManagedHsm's properties, hides type
            Name                      = managedHsm.Name;
            Sku                       = managedHsm.Sku.Name.ToString();
            TenantId                  = managedHsm.Properties.TenantId.Value;
            TenantName                = ModelExtensions.GetDisplayNameForTenant(TenantId, graphClient);
            InitialAdminObjectIds     = managedHsm.Properties.InitialAdminObjectIds.ToArray <string>();
            HsmUri                    = managedHsm.Properties.HsmUri;
            EnablePurgeProtection     = managedHsm.Properties.EnablePurgeProtection;
            EnableSoftDelete          = managedHsm.Properties.EnableSoftDelete;
            SoftDeleteRetentionInDays = managedHsm.Properties.SoftDeleteRetentionInDays;
            StatusMessage             = managedHsm.Properties.StatusMessage;
            ProvisioningState         = managedHsm.Properties.ProvisioningState;
            OriginalManagedHsm        = managedHsm;
        }
Ejemplo n.º 20
0
        public override void VisitFieldDeclaration(FieldDeclarationSyntax node)
        {
            visitingConstant = node.Modifiers.Any(SyntaxKind.ConstKeyword);

            foreach (var variable in node.Declaration.Variables)
            {
                var symbol = (IFieldSymbol)ModelExtensions.GetDeclaredSymbol(model, variable);

                var fullName = symbol.ToString();
                if (!substitutions.ContainsKey(fullName))
                {
                    continue;
                }

                if (FieldSubstitution.Qualifies(symbol))
                {
                    result.Add(variable, new FieldSubstitution(variable, symbol, substitutions[fullName]));
                }
            }

            base.VisitFieldDeclaration(node);
            visitingConstant = false;
        }
Ejemplo n.º 21
0
        public IActionResult Config(string id)
        {
            //If Id is empty then we load the default model
            if (string.IsNullOrEmpty(id))
            {
                //FOR Test
                var ret = ModelExtensions.GetAggrConfig("onoff.json");
                return(Ok(ret));
            }

            else
            {
                var model = _context.Find <AggrModel>(int.Parse(id));

                if (model == null)
                {
                    return(NotFound("Aggregation Model not found"));
                }

                var ret = model.GetConfig();
                return(Ok(ret));
            }
        }
Ejemplo n.º 22
0
            /// <summary>
            /// Ensure exists
            /// </summary>
            protected override TModel InsertInternal(LocalDataContext context, TModel data)
            {
                if (data.IsEmpty())
                {
                    return(data);
                }

                foreach (var rp in this.m_properties)
                {
                    var instance = rp.GetValue(data);
                    if (instance != null)
                    {
                        instance = ModelExtensions.TryGetExisting(instance as IIdentifiedEntity, context);
                        if (instance != null)
                        {
                            rp.SetValue(data, instance);
                        }

                        ModelExtensions.UpdateParentKeys(data, rp);
                    }
                }
                return(base.InsertInternal(context, data));
            }
Ejemplo n.º 23
0
        static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic)
        {
            diagnostic = default(Diagnostic);

            var semanticModel            = nodeContext.SemanticModel;
            var addOrSubstractExpression = nodeContext.Node as AssignmentExpressionSyntax;
            var rightMember = addOrSubstractExpression?.Right as ObjectCreationExpressionSyntax;

            if (rightMember == null || rightMember.ArgumentList.Arguments.Count != 1)
            {
                return(false);
            }

            var leftTypeInfo = ModelExtensions.GetTypeInfo(semanticModel, addOrSubstractExpression.Left).ConvertedType;

            if (leftTypeInfo == null || leftTypeInfo.Kind.Equals(SyntaxKind.EventDeclaration))
            {
                return(false);
            }

            diagnostic = Diagnostic.Create(descriptor, addOrSubstractExpression.Right.GetLocation());
            return(true);
        }
Ejemplo n.º 24
0
        private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
        {
            // The analyzer will run on every keystroke in the editor, so we are performing the quickest tests first
            var member     = context.Node as MemberAccessExpressionSyntax;
            var identifier = member?.Expression as IdentifierNameSyntax;

            if (identifier == null)
            {
                return;
            }

            if (identifier.Identifier.Text != nameof(DateTime) &&
                identifier.Identifier.Text != nameof(DateTimeOffset))
            {
                return;
            }

            var identifierSymbol = ModelExtensions.GetSymbolInfo(context.SemanticModel, identifier).Symbol as INamedTypeSymbol;

            if (identifierSymbol?.ContainingNamespace.ToString() != nameof(System))
            {
                return;
            }

            var accessor = member.Name.ToString();

            if (accessor != nameof(DateTime.Now) &&
                accessor != nameof(DateTime.UtcNow))
            {
                return;
            }

            var rule       = s_rule;
            var diagnostic = Diagnostic.Create(rule, member.GetLocation());

            context.ReportDiagnostic(diagnostic);
        }
Ejemplo n.º 25
0
        public override void VisitForEachStatement(ForEachStatementSyntax node)
        {
            // Hoist the variable into a field
            var symbol     = (ILocalSymbol)ModelExtensions.GetDeclaredSymbol(Transformer.Model, node);
            var identifier = HoistVariable(new LiftedVariableKey(node.Identifier, symbol));

            // Hoist the enumerator into a field
            var enumerator = HoistVariable(new LiftedVariableKey(identifier.Name + "$enumerator"));

            CurrentState.Add(
                enumerator.GetReference().Assign(
                    ((JsExpression)node.Expression.Accept(Transformer)).Member("GetEnumerator").Invoke()
                    ).Express()
                );

            var topOfLoop = GetNextState();

            GotoState(topOfLoop);
            CurrentState = topOfLoop;

            var afterLoop = GetNextState();
            var bodyState = GetNextState();

            var moveNext          = enumerator.GetReference().Member("MoveNext").Invoke();
            var newWhileStatement = Js.While(moveNext, GotoStateBlock(bodyState));

            CurrentState.Add(newWhileStatement);
            GotoState(afterLoop);

            CurrentState = bodyState;
            CurrentState.Add(identifier.GetReference().Assign(enumerator.GetReference().Member("get_Current").Invoke()).Express());

            AcceptStatement(node.Statement, afterLoop, topOfLoop);
            GotoState(topOfLoop);

            CurrentState = afterLoop;
        }
Ejemplo n.º 26
0
        public static IServiceCollection RegisterIModelPipeline <T>(this IServiceCollection collection)
            where T : class, IModel
        {
            //TODO Take furthest extended class rather than only a direct subclass.
            var controllerImplementation = ModelExtensions.GetAllSubclasses <CoHAController <T> >().SingleOrDefault();
            var serviceImplementation    = ModelExtensions.GetAllSubclasses <CoHAService <T> >().SingleOrDefault();
            var repoImplementation       = ModelExtensions.GetAllSubclasses <EntityRepository <T> >().SingleOrDefault();

            if (controllerImplementation != null) //If we have a concrete class register it.
            {
                collection.AddTransient(controllerImplementation);
            }
            else //Else register the default class.
            {
                collection.AddTransient <CoHAController <T> >();
            }

            if (serviceImplementation != null) //If we have a concrete class register it.
            {
                collection.AddTransient(serviceImplementation);
            }
            else //Else register the default class.
            {
                collection.AddTransient <CoHAService <T> >();
            }

            if (repoImplementation != null) //If we have a concrete class register it.
            {
                collection.AddTransient(repoImplementation);
            }
            else //Else register the default class.
            {
                collection.AddTransient <EntityRepository <T> >();
            }

            return(collection);
        }
Ejemplo n.º 27
0
        private IEnumerable <SolutionStyleError> InspectMethod <TCycle>(TCycle cycleStatement, SemanticModel semanticModel) where TCycle : StatementSyntax
        {
            var forStatement      = cycleStatement as ForStatementSyntax;
            var methodInvocations = (forStatement != null
                                        ? (forStatement.Condition?.DescendantNodes()).EmptyIfNull().Concat(forStatement.Statement.DescendantNodes())
                                        : cycleStatement.DescendantNodes())
                                    .OfType <InvocationExpressionSyntax>()
                                    .ToList();

            foreach (var methodInvocation in methodInvocations)
            {
                var symbol             = ModelExtensions.GetSymbolInfo(semanticModel, methodInvocation).Symbol;
                var argumentExpression = methodInvocation.ArgumentList.Arguments.FirstOrDefault()?.Expression;
                if (symbol?.ToString() != "System.Array.GetLength(int)" ||
                    argumentExpression == null ||
                    !argumentExpression.IsKind(SyntaxKind.NumericLiteralExpression))
                {
                    continue;
                }

                var variable = methodInvocation
                               .Expression
                               .DescendantNodes()
                               .FirstOrDefault();

                if (variable != null)
                {
                    var variableSymbol = semanticModel.GetSymbolInfo(variable).Symbol;
                    var variableName   = variableSymbol.ToString();
                    if (!cycleStatement.ContainsAssignmentOf(variableName, semanticModel) &&
                        !methodInvocations.Any(m => m.HasVariableAsArgument(variableName, semanticModel)))
                    {
                        yield return(new SolutionStyleError(StyleErrorType.ArrayLength01, methodInvocation));
                    }
                }
            }
        }
        public ExpressionSyntax AddExplicitConversion(Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax vbNode, ExpressionSyntax csNode, TypeConversionKind conversionKind, bool addParenthesisIfNeeded = false, bool isConst = false, ITypeSymbol forceTargetType = null)
        {
            var typeInfo        = ModelExtensions.GetTypeInfo(_semanticModel, vbNode);
            var vbType          = typeInfo.Type;
            var vbConvertedType = forceTargetType ?? typeInfo.ConvertedType;

            if (isConst && _expressionEvaluator.GetConstantOrNull(vbNode, vbConvertedType, csNode) is ExpressionSyntax constLiteral)
            {
                return(constLiteral);
            }

            switch (conversionKind)
            {
            case TypeConversionKind.Unknown:
            case TypeConversionKind.Identity:
                return(addParenthesisIfNeeded ? VbSyntaxNodeExtensions.ParenthesizeIfPrecedenceCouldChange(vbNode, csNode) : csNode);

            case TypeConversionKind.DestructiveCast:
            case TypeConversionKind.NonDestructiveCast:
                return(CreateCast(csNode, vbConvertedType));

            case TypeConversionKind.Conversion:
                return(AddExplicitConvertTo(vbNode, csNode, vbType, vbConvertedType));;

            case TypeConversionKind.NullableBool:
                return(SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, csNode,
                                                      LiteralConversions.GetLiteralExpression(true)));

            case TypeConversionKind.StringToCharArray:
                var memberAccessExpressionSyntax = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, csNode, SyntaxFactory.IdentifierName(nameof(string.ToCharArray)));
                return(SyntaxFactory.InvocationExpression(memberAccessExpressionSyntax,
                                                          SyntaxFactory.ArgumentList()));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public void PageInit()
        {
            Init();


            var entMan = new EntityManager();
            var relMan = new EntityRelationManager();

            ErpEntity = entMan.ReadEntity(ParentRecordId ?? Guid.Empty).Object;
            if (ErpEntity == null)
            {
                return;
            }

            var entityRelations = relMan.Read().Object.Where(x => x.TargetEntityId == ErpEntity.Id || x.OriginEntityId == ErpEntity.Id).ToList();

            Relation = entityRelations.SingleOrDefault(x => x.Id == RecordId);
            if (Relation == null)
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(ReturnUrl))
            {
                ReturnUrl = $"/sdk/objects/entity/r/{ErpEntity.Id}/rl/relations/r/{Relation.Id}/";
            }

            HeaderActions.AddRange(new List <string>()
            {
                PageUtils.GetActionTemplate(PageUtilsActionType.SubmitForm, label: "Save Relation", formId: "ManageRecord"),
                PageUtils.GetActionTemplate(PageUtilsActionType.Cancel, returnUrl: $"/sdk/objects/entity/r/{ErpEntity.Id}/rl/relations/r/{Relation.Id}/")
            });

            HeaderToolbar.AddRange(AdminPageUtils.GetEntityAdminSubNav(ErpEntity, "relations"));

            TypeOptions = ModelExtensions.GetEnumAsSelectOptions <EntityRelationType>().FindAll(x => x.Value != "1").ToList();
        }
Ejemplo n.º 30
0
        protected override async Task <ISymbol> GetSymbol(Document document, int tokenPosition, CancellationToken cancellationToken)
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            var syntaxTree = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken);

            var token = syntaxTree.FindToken(tokenPosition);

            if (token.Parent is ClassDeclarationSyntax c)
            {
                return(ModelExtensions.GetDeclaredSymbol(semanticModel, c));
            }

            var vds = token.Parent is VariableDeclarationSyntax variable ? variable : token.Parent?.Parent as VariableDeclarationSyntax;

            if (vds != null)
            {
                var info = semanticModel.GetSymbolInfo(vds.Type);
                if (string.IsNullOrWhiteSpace(info.Symbol.ToString()))
                {
                    return(null);
                }
                return(info.Symbol);
            }

            if (token.Parent is ParameterSyntax parameterSyntax)
            {
                var info = semanticModel.GetSymbolInfo(parameterSyntax.Type);
                if (string.IsNullOrWhiteSpace(info.Symbol.ToString()))
                {
                    return(null);
                }
                return(info.Symbol);
            }

            return(null);
        }