예제 #1
0
        public ModuleDefinition ProcessAssembly()
        {
            logger.Debug("Reading assembly {0}...", assemblyPath);
            var assemblyDefinition = AssemblyDefinition.ReadAssembly(assemblyPath);

            logger.Debug("Assembly read.  Processing...");
            var moduleWeaver = new ModuleWeaver
            {
                AssemblyResolver        = CreateAssemblyResolver(),
                Config                  = CreateFodyConfig(),
                LogError                = message => Errors.Add(message),
                LogWarning              = message => Warnings.Add(message),
                ProjectDirectoryPath    = projectPath,
                ReferenceCopyLocalPaths = GetCopyLocalAssemblies(assemblyPath),
                ModuleDefinition        = assemblyDefinition.MainModule
            };

            try
            {
                DoInWorkingDirectory(Path.GetDirectoryName(assemblyPath), moduleWeaver.Execute);
            }
            catch (Exception ex)
            {
                logger.DebugException("Fody processing failed for assembly at " + assemblyPath, ex);
                WeaverException = ex;
            }

            return(assemblyDefinition.MainModule);
        }
예제 #2
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);

            var typeName = jObject["type"]?.Value <string>() ?? jObject["@type"]?.Value <string>();

            if (typeName == null)
            {
                throw new AdaptiveSerializationException("Required property 'type' not found on adaptive card element");
            }

            if (TypedElementTypes.Value.TryGetValue(typeName, out var type))
            {
                if (typeof(AdaptiveInput).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) && jObject.Value <string>("id") == null)
                {
                    throw new AdaptiveSerializationException($"Required property 'id' not found on '{typeName}'");
                }

                var result = (AdaptiveTypedElement)Activator.CreateInstance(type);
                serializer.Populate(jObject.CreateReader(), result);

                HandleAdditionalProperties(result);
                return(result);
            }

            Warnings.Add(new AdaptiveWarning(-1, $"Unknown element '{typeName}'"));
            return(null);
        }
예제 #3
0
        override public void Run()
        {
            if (Errors.Count > 0)
            {
                return;
            }

            if (!IsSupported)
            {
                Warnings.Add(new CompilerWarning("PEVerify is not supported on this platform."));
                // linux
                return;
            }

            try
            {
                Process p = Boo.Lang.Builtins.shellp("peverify.exe", "\"" + Context.GeneratedAssemblyFileName + "\"");
                p.WaitForExit();
                if (0 != p.ExitCode)
                {
                    Errors.Add(new CompilerError(Boo.Lang.Compiler.Ast.LexicalInfo.Empty, p.StandardOutput.ReadToEnd()));
                }
            }
            catch (Win32Exception e)
            {
                _context.TraceWarning("Could not start peverify.exe: " + e.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// Get value of a specific individual
        /// </summary>
        /// <returns>value</returns>
        public double ValueofIndividual(Ruminant ind, PurchaseOrSalePricingStyleType purchaseStyle)
        {
            if (PricingAvailable())
            {
                List <Ruminant> animalList = new List <Ruminant>()
                {
                    ind
                };

                // search through RuminantPriceGroups for first match with desired purchase or sale flag
                foreach (AnimalPriceGroup item in Apsim.Children(PriceList, typeof(AnimalPriceGroup)).Cast <AnimalPriceGroup>().Where(a => a.PurchaseOrSale == purchaseStyle || a.PurchaseOrSale == PurchaseOrSalePricingStyleType.Both))
                {
                    if (animalList.Filter(item).Count() == 1)
                    {
                        return(item.Value * ((item.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0));
                    }
                }
                // no price match found.
                string warning = "No " + purchaseStyle.ToString() + " price entry was found for an indiviudal with details ([f=age: " + ind.Age + "] [f=herd: " + ind.HerdName + "] [f=gender: " + ind.GenderAsString + "] [f=weight: " + ind.Weight.ToString("##0") + "])";
                if (!Warnings.Exists(warning))
                {
                    Warnings.Add(warning);
                    Summary.WriteWarning(this, warning);
                }
            }
            return(0);
        }
예제 #5
0
파일: Treatment.cs 프로젝트: ptitim/PuffMvc
        public void AddWarningWithCode(HttpStatusCode httpcode, string message)
        {
            var tre = new TreatmentEvent(MessagesType.Warning, httpcode, message);

            StatusCode = httpcode;
            Warnings.Add(tre);
        }
 private void CalculationProgressWarning(object sender, WarningEventArgs e)
 {
     Dispatcher.UIThread.InvokeAsync(() =>
     {
         Warnings.Add(e.Message);
     });
 }
예제 #7
0
    List <int> FixMultiFileIndices(IEnumerable <int>?multiFileIndices, int targetCount)
    {
        if (Errors.Any())
        {
            return new List <int> {
                       0
            }
        }
        ;

        var indices = multiFileIndices?.ToList() ?? new List <int> {
            0
        };

        if (indices.Count > 0)
        {
            int startCount = indices.Count;

            indices = indices.Where(i => i < targetCount).ToList();

            if (startCount > indices.Count)
            {
                Warnings.Add("Multi-file index was higher than the number of targets.");
            }

            indices.Sort();
        }

        if (indices.Count == 0 || indices[0] != 0)
        {
            indices.Insert(0, 0);
        }

        return(indices);
    }
예제 #8
0
        /// <summary>
        /// Returns the link to the matching resource in the market place if found or creates a new clone copy for future transactions
        /// This allows this action to be performed once to store the link rather than at every transaction
        /// This functionality allows resources not in the market at the start of the simulation to be traded.
        /// </summary>
        /// <param name="resourceType">The resource type to trade</param>
        /// <returns>Whether the search was successful</returns>
        public IResourceWithTransactionType LinkToMarketResourceType(CLEMResourceTypeBase resourceType)
        {
            if (!(this.Parent is Market))
            {
                throw new ApsimXException(this, $"Logic error in code. Trying to link a resource type [r={resourceType.Name}] from the market with the same market./nThis is a coding issue. Please contact the developers");
            }

            // find parent group type
            ResourceBaseWithTransactions parent   = (resourceType as Model).Parent as ResourceBaseWithTransactions;
            ResourceBaseWithTransactions resGroup = GetResourceGroupByType(parent.GetType()) as ResourceBaseWithTransactions;

            if (resGroup is null)
            {
                // add warning the market is not currently trading in this resource
                string zoneName = FindAncestor <Zone>().Name;
                string warn     = $"[{zoneName}] is currently not accepting resources of type [r={parent.GetType().ToString()}]\nOnly resources groups provided in the [r=ResourceHolder] in the simulation tree will be traded.";
                if (!Warnings.Exists(warn) & Summary != null)
                {
                    Summary.WriteWarning(this, warn);
                    Warnings.Add(warn);
                }
                return(null);
            }

            // TODO: do some group checks. land units, currency

            // TODO: if market and looking for finance only return or create "Bank"

            // find resource type in group
            object resType = resGroup.GetByName((resourceType as IModel).Name) as IResourceWithTransactionType;

            if (resType is null)
            {
                // clone resource
                // too many problems with linked events to clone these objects and setup again
                // it will be the responsibility of the user to ensure the resources and details are in the market
                // resType = Apsim.Clone(resourceType);

                if (resType is null)
                {
                    // add warning the market does not have the resource
                    string zoneName = FindAncestor <Zone>().Name;
                    string warn     = $"The resource [r={resourceType.Parent.Name}.{resourceType.Name}] does not exist in [m={this.Parent.Name}].\nAdd resource and associated components to the market to permit trading.";
                    if (!Warnings.Exists(warn) & Summary != null)
                    {
                        Summary.WriteWarning(this, warn);
                        Warnings.Add(warn);
                    }
                    return(null);
                }
                else
                {
                    (resType as IModel).Parent            = resGroup;
                    (resType as CLEMModel).CLEMParentName = resGroup.CLEMParentName;
                    // add new resource type
                    resGroup.AddNewResourceType(resType as IResourceWithTransactionType);
                }
            }
            return(resType as IResourceWithTransactionType);
        }
예제 #9
0
        private void OnStartOfSimulation(object sender, EventArgs e)
        {
            //if the SQLite Database can't be opened throw an exception.
            var validationContext = new ValidationContext(this, null, null);

            validationResults = new List <ValidationResult>();
            Validator.TryValidateObject(this, validationContext, validationResults, true);

            if (OpenSQLiteDB() == false)
            {
                throw new Exception(ErrorMessage);
            }
            else
            {
                // create warning if database is not optimised for CLEM
                var result = SQLiteReader.ExecuteQuery("SELECT count(*) FROM sqlite_master WHERE type='index' and name='CLEM_next_growth';");
                if (result.Rows.Count >= 0 && Convert.ToInt32(result.Rows[0][0]) != 1)
                {
                    // add warning
                    string warn = $"The database [x={this.FileName.Replace("_", "\\_")}] specified in [x={this.Name}] has not been optimised for best performance in CLEM. Add the following index to your database using your chosen database management software (e.g. DB Browser) to significantly improve your simulation speed:\r\nCREATE INDEX CLEM\\_next\\_growth ON Native\\_Inputs (Region, Soil, GrassBA, LandCon, StkRate, Year, Month);\r\nThis index must be named CLEM\\_next\\_growth and should include the table and column names appropriate to your database.";
                    if (!Warnings.Exists(warn))
                    {
                        Summary.WriteWarning(this, warn);
                        Warnings.Add(warn);
                    }
                }
            }

            // get list of distinct stocking rates available in database
            // database has already been opened and checked in Validate()
            this.distinctStkRates       = GetCategories(StkRateColumnName);
            this.distinctGBAs           = GetCategories(GrassBAColumnName);
            this.distinctLandConditions = GetCategories(LandConColumnName);
        }
예제 #10
0
        /// <summary>
        /// Resource price
        /// </summary>
        public ResourcePricing Price(PurchaseOrSalePricingStyleType priceType)
        {
            // find pricing that is ok;
            ResourcePricing price = Apsim.Children(this, typeof(ResourcePricing)).Where(a => a.Enabled & ((a as ResourcePricing).PurchaseOrSale == PurchaseOrSalePricingStyleType.Both | (a as ResourcePricing).PurchaseOrSale == priceType) && (a as ResourcePricing).TimingOK).FirstOrDefault() as ResourcePricing;

            // does simulation have finance
            ResourcesHolder resources       = Apsim.Parent(this, typeof(ResourcesHolder)) as ResourcesHolder;
            bool            financesPresent = (resources.FinanceResource() != null);

            if (price == null)
            {
                if (financesPresent)
                {
                    string warn = "No pricing is available for [r=" + this.Parent.Name + "." + this.Name + "]";
                    if (Clock != null & Apsim.Children(this, typeof(ResourcePricing)).Count > 0)
                    {
                        warn += " in month [" + Clock.Today.ToString("MM yyyy") + "]";
                    }
                    warn += "\nAdd [r=ResourcePricing] component to [r=" + this.Parent.Name + "." + this.Name + "] to include financial transactions for purchases and sales.";

                    if (!Warnings.Exists(warn) & Summary != null)
                    {
                        Summary.WriteWarning(this, warn);
                        Warnings.Add(warn);
                    }
                }
                return(new ResourcePricing()
                {
                    PricePerPacket = 0, PacketSize = 1, UseWholePackets = true
                });
            }
            return(price);
        }
예제 #11
0
        override public void OnReferenceExpression(ReferenceExpression node)
        {
            IExternalEntity member = node.Entity as IExternalEntity;

            if (member == null)              //extract to OnInternalReferenceExpression
            {
                OnInternalReferenceExpression(node);
                return;
            }

            System.Attribute[] attributes = System.Attribute.GetCustomAttributes(member.MemberInfo, typeof(ObsoleteAttribute));
            foreach (ObsoleteAttribute attr in attributes)
            {
                if (attr.IsError)
                {
                    Errors.Add(
                        CompilerErrorFactory.Obsolete(node, member.ToString(), attr.Message));
                }
                else
                {
                    Warnings.Add(
                        CompilerWarningFactory.Obsolete(node, member.ToString(), attr.Message));
                }
            }
        }
예제 #12
0
 internal void SetupProject()         // Should this be protected? But the unit test needs to call it.
 {
     if (ConfigData != null && ConfigFilename != null)
     {
         Warnings.Add("WARNING: options --config-data and --config-file were both specified. Ignoring --config-file.");
         ConfigFilename = null;
     }
     if (ConfigData == null && ConfigFilename == null)
     {
         ConfigFilename = FindConfigFilename();
         // If ConfigFilename is STILL null at this point, it's because no config files were found at all,
         // so we'll use the default one from the resource.
     }
     SpanFactory = new ShapeSpanFactory();
     SegmentPool = new SegmentPool();
     if (ConfigData == null && ConfigFilename == null)
     {
         Project = GetProjectFromResource(SpanFactory, SegmentPool);
     }
     else if (ConfigData != null)
     {
         Project = GetProjectFromXmlString(SpanFactory, SegmentPool, ConfigData);
     }
     else if (ConfigFilename != null)
     {
         Project = GetProjectFromFilename(SpanFactory, SegmentPool, ConfigFilename);
     }
     else             // Should never get here given checks above, but let's be safe and write the check anyway
     {
         Project = GetProjectFromResource(SpanFactory, SegmentPool);
     }
 }
        public override void Run()
        {
            var referencedClasses = Classes.Where(c => c.DocumentationReferences.Any());

            foreach (MoaiClass moaiClass in referencedClasses)
            {
                if (!moaiClass.Exists)
                {
                    // Make an educated guess as to what type was meant.
                    IType typeProposal = Types.Find(moaiClass.Name,
                                                    MatchMode.FindSynonyms | MatchMode.FindSimilar, t => t.Exists);

                    foreach (FilePosition referencingFilePosition in moaiClass.DocumentationReferences)
                    {
                        string message = string.Format(
                            "Documentation mentions unknown type '{0}'.", moaiClass.Name);
                        if (typeProposal != null)
                        {
                            message += string.Format(" Should this be '{0}'?", typeProposal.Name);
                        }
                        Warnings.Add(referencingFilePosition, WarningType.UnexpectedValue, message);
                    }
                }
            }
        }
예제 #14
0
 public override void CheckContraints(Warnings warnings)
 {
     if (!MetaRepository.IsValidName(Name))
     {
         warnings.Add("Name must be alphanumeric", this);
     }
 }
예제 #15
0
        /// <summary>
        /// Returns the link to the matching resource in the market place if found or creates a new clone copy for future transactions
        /// This allows this action to be performed once to store the link rather than at every transaction
        /// This functionality allows resources not in the market at the start of the simulation to be traded.
        /// </summary>
        /// <param name="resourceType">The resource type to trade</param>
        /// <param name="linkToResourceType">A link to the associated resource type</param>
        /// <returns>Whether the search was successful</returns>
        public bool ResourceTypeExists(CLEMResourceTypeBase resourceType, out object linkToResourceType)
        {
            linkToResourceType = null;

            // find parent group type
            ResourceBaseWithTransactions parent   = (resourceType as Model).Parent as ResourceBaseWithTransactions;
            ResourceBaseWithTransactions resGroup = GetResourceGroupByType(parent.GetType()) as ResourceBaseWithTransactions;

            if (resGroup is null)
            {
                // add warning the market is not currently trading in this resource
                string zoneName = Apsim.Parent(this, typeof(Zone)).Name;
                Warnings.Add($"[{zoneName}] is currently not accepting resources of type [r={parent.GetType().ToString()}]\nOnly resources groups provided in the [r=ResourceHolder] in the simulation tree will be traded.");
                return(false);
            }

            // TODO: do some group checks. land units, currency

            // TODO: if market and looking for finance only return or create "Bank"

            // find resource type in group
            var resType = resGroup.GetByName((resourceType as IModel).Name);

            if (resType is null)
            {
                // clone resource
                resType = resourceType.Clone as CLEMResourceTypeBase;
                (resType as IModel).Parent = resGroup;

                // wire up events
                resGroup.AddChildEvents(resType as IResourceWithTransactionType);
            }
            linkToResourceType = resType;
            return(true);
        }
예제 #16
0
        public override void ExitStringLiteral(StringLiteral stringLiteral)
        {
            if (stringLiteral.Parent is NativeMethodInvocationExpression nativeMethodInvocation &&
                nativeMethodInvocation.NativeMethodName == "String" &&
                stringLiteral == nativeMethodInvocation.Arguments.First() ||
                stringLiteral.Parent is EnumValue)
            {
                return;
            }
            var root  = stringLiteral.NearestAncestorOfType <Root>();
            var parts = new List <IExpression> {
                stringLiteral
            };

            var(constructed, matchesCase) = Construct(root, stringLiteral.Context, parts);
            if (constructed == null)
            {
                Errors.Add(new CompilationError(stringLiteral.Context, "String can not be constructed from predefined strings in Overwatch"));
            }
            else
            {
                if (!matchesCase)
                {
                    Warnings.Add(new CompilationError(stringLiteral.Context, "String case might not match the predefined strings in Overwatch"));
                }
                stringLiteral.ReplaceWith(constructed);
                Visit(constructed);
            }
        }
예제 #17
0
 public void AddWarning(string warning)
 {
     if (!string.IsNullOrEmpty(warning))
     {
         Warnings.Add(warning);
     }
 }
예제 #18
0
        public override void EnterBinaryExpression(BinaryExpression binaryExpression)
        {
            if (!(binaryExpression.Type is StringType))
            {
                return;
            }
            var root  = binaryExpression.NearestAncestorOfType <Root>();
            var parts = GetStringConcatenationParts(binaryExpression).ToList();

            var(constructed, matchesCase) = Construct(root, binaryExpression.Context, parts);
            if (constructed == null)
            {
                Errors.Add(new CompilationError(binaryExpression.Operator.Context, "String can not be constructed from predefined strings in overwatch"));
            }
            else
            {
                if (!matchesCase)
                {
                    Warnings.Add(new CompilationError(binaryExpression.Context, "String case might not match the predefined strings in Overwatch"));
                }
                binaryExpression.ReplaceWith(constructed);
                Visit(constructed);
            }
            skipChildren = true;
        }
예제 #19
0
    public void Initialize(IEventSource eventSource)
    {
        eventSource.MessageRaised += (sender, e) =>
        {
            var shouldLog = e.Importance == MessageImportance.High &&
                            Verbosity >= LoggerVerbosity.Minimal;
            shouldLog |= e.Importance == MessageImportance.Normal &&
                         Verbosity >= LoggerVerbosity.Normal;
            shouldLog |= e.Importance == MessageImportance.Low &&
                         Verbosity >= LoggerVerbosity.Detailed;

            if (shouldLog)
            {
                output.WriteLine(e.Message);
                Messages.Add(e);
            }
        };

        if (Verbosity >= LoggerVerbosity.Detailed)
        {
            eventSource.AnyEventRaised += (sender, e) => output.WriteLine(e.Message);
        }

        eventSource.ErrorRaised += (sender, e) =>
        {
            output.WriteLine(e.Message);
            Errors.Add(e);
        };

        eventSource.WarningRaised += (sender, e) =>
        {
            output.WriteLine(e.Message);
            Warnings.Add(e);
        };
    }
        protected virtual List WalkMemberChain(MemberReferenceExpression memberRef)
        {
            List chain = new List();

            while (true)
            {
                MemberReferenceExpression container = memberRef.Target as MemberReferenceExpression;
                if (null == container ||
                    (IsSpecialMemberTarget(container) &&
                     IsReadOnlyMember(container)))
                {
                    Warnings.Add(
                        CompilerWarningFactory.AssignmentToTemporary(memberRef));
                    return(null);
                }
                if (IsSpecialMemberTarget(container) &&
                    EntityType.Field != container.Entity.EntityType)
                {
                    chain.Insert(0, new ChainItem(container));
                }
                if (IsTerminalReferenceNode(container.Target))
                {
                    break;
                }
                memberRef = container;
            }
            return(chain);
        }
예제 #21
0
        override public void LeaveBinaryExpression(BinaryExpression node)
        {
            if (CheckExpressionType(node.Right))
            {
                CheckExpressionType(node.Left);
            }

            if (BinaryOperatorType.ReferenceEquality == node.Operator)
            {
                if (IsTypeReference(node.Right))
                {
                    Warnings.Add(
                        CompilerWarningFactory.IsInsteadOfIsa(node));
                }
            }

            //check that the assignment or comparison is meaningful
            if (BinaryOperatorType.Assign == node.Operator ||
                AstUtil.GetBinaryOperatorKind(node) == BinaryOperatorKind.Comparison)
            {
                if (AreSameExpressions(node.Left, node.Right))
                {
                    Warnings.Add(
                        (BinaryOperatorType.Assign == node.Operator)
                                                ? CompilerWarningFactory.AssignmentToSameVariable(node)
                                                : CompilerWarningFactory.ComparisonWithSameVariable(node)
                        );
                }
                else if (BinaryOperatorType.Assign != node.Operator &&
                         AreConstantExpressions(node.Left, node.Right))
                {
                    WarnAboutConstantExpression(node);
                }
            }
        }
 //returns true if a stub has been created, false otherwise.
 //TODO: add entity argument to the method to not need return type?
 bool AbstractMemberNotImplemented(ClassDefinition node, TypeReference baseTypeRef, IMember member)
 {
     if (IsValueType(node))
     {
         Error(CompilerErrorFactory.ValueTypeCantHaveAbstractMember(baseTypeRef, GetType(node), member));
         return(false);
     }
     if (!node.IsAbstract)
     {
         //BEHAVIOR >= 0.7.7:	(see BOO-789 for details)
         //create a stub for this not implemented member
         //it will raise a NotImplementedException if called at runtime
         TypeMember      m       = CodeBuilder.CreateStub(node, member);
         CompilerWarning warning = null;
         if (null != m)
         {
             warning = CompilerWarningFactory.AbstractMemberNotImplementedStubCreated(baseTypeRef, GetType(node), member);
             if (m.NodeType != NodeType.Property || null == node.Members[m.Name])
             {
                 AddStub(node, m);
             }
         }
         else
         {
             warning = CompilerWarningFactory.AbstractMemberNotImplemented(baseTypeRef, GetType(node), member);
             _newAbstractClasses.AddUnique(node);
         }
         Warnings.Add(warning);
         return(null != m);
     }
     return(false);
 }
예제 #23
0
        public override void OnError(JScriptExceptionEventArgs error)
        {
            var span = new SourceSpan(
                new SourceLocation(
                    error.Exception.Span.Start,
                    error.Error.StartLine,
                    error.Error.StartColumn
                    ),
                new SourceLocation(
                    error.Exception.Span.End,
                    error.Error.EndLine,
                    error.Error.EndColumn
                    )
                );
            var result = new ErrorResult(error.Error.Message, span, error.Error.ErrorCode);

            if (error.Error.IsError)
            {
                Errors.Add(result);
            }
            else
            {
                Warnings.Add(result);
            }
        }
예제 #24
0
        private void IssueList_ListChanged(object sender, ListChangedEventArgs e)
        {
            var list = IssueList.ToArray();

            foreach (var item in list)
            {
                // If issue is unchecked or no longer a problem then...
                if (Warnings.Contains(item) && (!item.IsEnabled || !item.Severity.HasValue || item.Severity == IssueSeverity.None))
                {
                    // Remove from warnings list.
                    Warnings.Remove(item);
                }
                // If issue not found and problem found then...
                else if (!Warnings.Contains(item) && item.IsEnabled && item.Severity.HasValue && item.Severity.Value != IssueSeverity.None)
                {
                    // Add to warnings list.
                    Warnings.Add(item);
                }
            }
            // Get issues in progress.
            list = IssueList.Where(x => x.Status != IssueStatus.Idle).ToArray();
            var sb = new StringBuilder();

            foreach (var item in list)
            {
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                sb.AppendFormat("{0}/{1} {2}: {3}", IssueList.IndexOf(item), IssueList.Count, item.GetType().Name, item.Status);
            }
            StatusLabel.Text = sb.ToString();
            UpdateIgnoreAllButton();
            UpdateNoIssuesPanel();
        }
예제 #25
0
 protected void WarnIfProtectedMemberInSealedClass(TypeMember member)
 {
     if (member.IsProtected && !member.IsSynthetic && !member.IsOverride && member.DeclaringType.IsFinal)
     {
         Warnings.Add(CompilerWarningFactory.NewProtectedMemberInSealedType(member));
     }
 }
        private void Initialize(SPList list)
        {
            Created     = list.Created;
            Description = list.Description;
            GroupId     = list.GroupId;
            Id          = list.Id;
            IsEnabled   = true;
            ItemCount   = list.ItemCount;
            Modified    = list.Modified;
            Name        = list.Title;
            Root        = list.RootFolder;
            SPViewUrl   = list.SPViewUrl;
            SPWebUrl    = list.SPWebUrl;

            var listBase = listDataService.Get(Id);

            Url = listBase != null?documentUrls.BrowseDocuments(listBase) : SPWebUrl;

            VersioningEnabled = list.EnableVersioning;
            ViewId            = list.ViewId;

            foreach (var error in list.Errors)
            {
                Errors.Add(error);
            }

            foreach (var warning in list.Warnings)
            {
                Warnings.Add(warning);
            }
        }
예제 #27
0
        //this method returns -1 if it doesn't detect unreachable code
        //else it returns the index of the first unreachable in block.Statements
        private int DetectUnreachableCode(Block block, Statement limit)
        {
            var unreachable = false;
            var idx         = 0;

            foreach (var stmt in block.Statements)
            {
                //HACK: __switch__ builtin function is hard to detect/handle
                //		within this context, let's ignore whatever is after __switch__
                if (IsSwitchBuiltin(stmt))
                {
                    return(-1);                   //ignore followings
                }
                if (unreachable && stmt is LabelStatement)
                {
                    return(-1);
                }

                if (stmt == limit)
                {
                    unreachable = true;
                }
                else if (unreachable)
                {
                    if (!stmt.IsSynthetic)
                    {
                        Warnings.Add(CompilerWarningFactory.UnreachableCodeDetected(stmt));
                    }
                    return(idx);
                }

                idx++;
            }
            return(-1);
        }
예제 #28
0
        public void ToggleShowCardVisibility(Button uiAction)
        {
            FrameworkElement card = ActionShowCards[uiAction];
            var id = uiAction.GetContext() as AdaptiveInternalID;

            if (id == null)
            {
                Warnings.Add(new AdaptiveWarning(-1, $"Toggling visibility event handling is dropped " +
                                                 $"since the action set the button belongs to has null internal id"));
                return;
            }
            var peers = PeerShowCardsInActionSet[id];

            if (card != null && peers != null)
            {
                var targetVisibility = card.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
                // need to make sure we collapse all showcards before showing this one
                foreach (var showCard in peers)
                {
                    showCard.Visibility = Visibility.Collapsed;
                }

                card.Visibility = targetVisibility;
            }
        }
예제 #29
0
        /// <summary>
        /// Get value of a specific individual
        /// </summary>
        /// <returns>value</returns>
        public double ValueofIndividual(Ruminant ind, PurchaseOrSalePricingStyleType purchaseStyle)
        {
            if (PricingAvailable())
            {
                List <Ruminant> animalList = new List <Ruminant>()
                {
                    ind
                };

                // search through RuminantPriceGroups for first match with desired purchase or sale flag

                foreach (AnimalPriceGroup item in priceGroups.Where(a => a.PurchaseOrSale == purchaseStyle || a.PurchaseOrSale == PurchaseOrSalePricingStyleType.Both))
                {
                    if (animalList.Filter(item).Count() == 1)
                    {
                        return(item.Value * ((item.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0));
                    }
                }

                // no price match found.
                string warningString = $"No [{purchaseStyle.ToString()}] price entry was found for [r={ind.Breed}] meeting the required criteria [f=age: {ind.Age}] [f=gender: {ind.GenderAsString}] [f=weight: {ind.Weight.ToString("##0")}]";

                if (!Warnings.Exists(warningString))
                {
                    Warnings.Add(warningString);
                    Summary.WriteWarning(this, warningString);
                }
            }
            return(0);
        }
예제 #30
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);

            var typeName = jObject["type"]?.Value <string>() ?? jObject["@type"]?.Value <string>();

            if (typeName == null)
            {
                // Get value of this objectType's "Type" JsonProperty(Required)
                var typeJsonPropertyRequiredValue = objectType.GetRuntimeProperty("Type")
                                                    .CustomAttributes.Where(a => a.AttributeType == typeof(JsonPropertyAttribute)).FirstOrDefault()?
                                                    .NamedArguments.Where(a => a.TypedValue.ArgumentType == typeof(Required)).FirstOrDefault()
                                                    .TypedValue.Value.ToString();

                // If this objectType does not require "Type" attribute, use the objectType's XML "TypeName" attribute
                if (typeJsonPropertyRequiredValue == "0")
                {
                    typeName = objectType
                               .GetRuntimeFields().Where(x => x.Name == "TypeName").FirstOrDefault()?
                               .GetValue("TypeName").ToString();
                }
                else
                {
                    throw new AdaptiveSerializationException("Required property 'type' not found on adaptive card element");
                }
            }

            if (TypedElementTypes.Value.TryGetValue(typeName, out var type))
            {
                if (jObject.Value <string>("id") == null)
                {
                    if (typeof(AdaptiveInput).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
                    {
                        throw new AdaptiveSerializationException($"Required property 'id' not found on '{typeName}'");
                    }
                }
                else
                {
                    string objectId = jObject.Value <string>("id");
                    if (Ids.Contains(objectId))
                    {
                        throw new AdaptiveSerializationException($"Duplicate 'id' found: '{objectId}'");
                    }
                    else
                    {
                        Ids.Add(objectId);
                    }
                }

                var result = (AdaptiveTypedElement)Activator.CreateInstance(type);
                serializer.Populate(jObject.CreateReader(), result);

                HandleAdditionalProperties(result);
                return(result);
            }

            Warnings.Add(new AdaptiveWarning(-1, $"Unknown element '{typeName}'"));
            return(null);
        }
예제 #31
0
        /// <summary>
        /// Method to obtain all the warnings as a result of the validation of the html
        /// </summary>
        /// <param name="urlDocument">Xml document that represents the result of the validation</param>
        /// <param name="mNamespace">Namespace used to obtain some data such as line, colum, etc.</param>
        private void HTMLWarnings(XDocument urlDocument, XNamespace mNamespace)
        {
            warnings = new Warnings();

            //Obtaining the descendants of the elements labeled "warnings". With this we obtain all the warnings
            var warningsElements = from e in urlDocument.Descendants(mNamespace + "warnings")
                                   select e;
            //Obtaining the descendants of the elements labeled "warningcount". With this we can obtain the number of warnings.
            var warningCountElement = from e in warningsElements.Descendants(mNamespace + "warningcount")
                                      select e;
            //Obtaining the descendants of the elements labeled "warning". With this we can obtain information from each of the warnings. 
            var warningListElements = from e in warningsElements.Descendants(mNamespace + "warning")
                                      select e;

            //Iterate over the 'warningaccount' variable to obtain the number of warnings
            foreach (var element in warningCountElement)
            {
                //Store the value of the count
                warnings.warningCount = element.Value;

                //Iterate over the 'warningListElements' variable to obtain each error
                foreach (var warningElement in warningListElements)
                {
                    //Create an instance of a Warning
                    Warning warning = new Warning();

                    //If there is a number of line
                    if (warningElement.Descendants(mNamespace + "line").Count() > 0)
                        //Store all the información of the warning.
                        warning.line = warningElement.Descendants(mNamespace + "line").First().Value;
                    //If there is a number of column
                    if (warningElement.Descendants(mNamespace + "col").Count() > 0)
                        //Store all the información of the warning.
                        warning.col = warningElement.Descendants(mNamespace + "col").First().Value;
                    //If there is an explnation
                    if (warningElement.Descendants(mNamespace + "explanation").Count() > 0)
                        //Store all the información of the warning.
                        warning.explanation = warningElement.Descendants(mNamespace + "explanation").First().Value;
                    //If there is a source
                    if (warningElement.Descendants(mNamespace + "source").Count() > 0)
                        //Store all the información of the warning.
                        warning.source = warningElement.Descendants(mNamespace + "source").First().Value;
                    //If there is a messageid
                    if (warningElement.Descendants(mNamespace + "messageid").Count() > 0)
                    {
                        //If the messageid stars with a 'W' it means that the warning is a PotentialIssue
                        if (warningElement.Descendants(mNamespace + "messageid").First().Value.StartsWith("W"))
                        {
                            //Create an instance of a WarningPotentialIssue
                            WarningPotentialIssue warningPotentialIssue = new WarningPotentialIssue();

                            //Store the messageid in the warningPotentialIssue object
                            warningPotentialIssue.messageid = warningElement.Descendants(mNamespace + "messageid").First().Value;
                            //If there is a message
                            if (warningElement.Descendants(mNamespace + "message").Count() > 0)
                                //Store the message in the warningPotentialIssue object
                                warningPotentialIssue.message = warningElement.Descendants(mNamespace + "message").First().Value;
                            ////Add the warningPotentialIssue to the list of warningPotentialIssues.
                            warningPotentialIssues.Add(warningPotentialIssue);
                        }
                        //If the messageid not stars with a 'W'
                        else
                        {
                            //Store the messageid
                            warning.messageid = warningElement.Descendants(mNamespace + "messageid").First().Value;
                            //If there is a message
                            if (warningElement.Descendants(mNamespace + "message").Count() > 0)
                                //Store the message
                                warning.message = warningElement.Descendants(mNamespace + "message").First().Value;

                            //Add the warning to the list of warnings
                            warnings.Add(warning);
                        }
                    }
                }
            }
        }