Example #1
0
        private void HandleRequest(Request request)
        {
            var stackFolder = new ClrCallStackFolder();
            var foldedStack = request.CallStack.Select(stackFolder.Fold).ToList();

            var flamegraph = new Markup(foldedStack, new Flamegraph.Settings
            {
                CountName = "ms",
                CountFormat = v => (new decimal(v)/1000).ToString(CultureInfo.InvariantCulture),
                Title = request.Url,
            });

            using (var writer = _markupWriter.GetWriter(request))
            {
                flamegraph.Write(writer);
            }
        }
Example #2
0
        public void ParseAttrArgumentTest()
        {
            //Parse tokens
            MarkupParser markupParser = new MarkupParser(Init("(i = 1)"));
            Markup markup = new Markup();
            markupParser.ParseArguments(markup);

            //Test arguments
            Assert.AreEqual(1, markup.GetArguments().Count);
            Argument argument = (Argument)markup.GetArguments().Get(0);
            Assert.AreEqual(typeof(AttrArgument), argument.GetType());

            //Test specific argument
            AttrArgument attrArgument = (AttrArgument)argument;
            Assert.AreEqual("i", attrArgument.GetIdentifier());
            Assert.AreEqual(typeof(NumExpression), attrArgument.GetExpression().GetType());
        }
Example #3
0
        public JsonResponse <JS.TextSaveResult> Update([JsonRequestBody] JS.TextEditor text)
        {
            return(JsonResponse.Catch(() => {
                var p = Texts.All.FirstOrDefault(x => x.Id == text.Id && x.SiteId == Sites.CurrentSiteId);
                if (p == null)
                {
                    p = Texts.Add(new Data.Text {
                        Id = text.Id, SiteId = Sites.CurrentSiteId
                    });
                }

                p.BbText = text.Text;
                p.HtmlText = Markup.ToHtml(p.BbText ?? "", new MarkdownParseArgs {
                    AttachmentMixin = Url.Mixin(( TextController c ) => c.Attachment(text.Id))
                });
                UnitOfWork.Commit();

                return JsonResponse.Create(new JS.TextSaveResult {
                    Html = p.HtmlText
                });
            }, Log));
        }
Example #4
0
    private static IEnumerable <Segment> RenderAnnotation(TableRendererContext context, TableTitle?header, Style defaultStyle)
    {
        if (header == null)
        {
            return(Array.Empty <Segment>());
        }

        var paragraph = new Markup(header.Text, header.Style ?? defaultStyle)
                        .Alignment(Justify.Center)
                        .Overflow(Overflow.Ellipsis);

        // Render the paragraphs
        var segments = new List <Segment>();

        segments.AddRange(((IRenderable)paragraph).Render(context.Options, context.TableWidth));

        // Align over the whole buffer area
        Aligner.Align(segments, context.Alignment, context.MaxWidth);

        segments.Add(Segment.LineBreak);
        return(segments);
    }
Example #5
0
        public string Parse(string input)
        {
            char[] chars = input.ToCharArray();

            foreach (char letter in chars)
            {
                foreach (Markup mk in _markupPool)
                {
                    mk.Digest(letter);
                    if (mk.Successful)
                    {
                        _completedMarkups.Add(mk);
                        _markupPool.Remove(mk);
                        _markupPool.Add(Markup.CreateMarkup(mk.Type));
                    }
                }
            }

            // something something

            return(input);
        }
        public static async ValueTask StartTaskAsync(
            this ProgressContext progressContext,
            string description,
            Func <ProgressTask, ValueTask> performOperationAsync)
        {
            var progressTask = progressContext.AddTask(
                // Don't recognize random square brackets as style tags
                Markup.Escape(description),
                new ProgressTaskSettings {
                MaxValue = 1
            }
                );

            try
            {
                await performOperationAsync(progressTask);
            }
            finally
            {
                progressTask.StopTask();
            }
        }
Example #7
0
        void HandleSelectionChanged(object sender, EventArgs e)
        {
            labelDescription.Visible = false;
            TreeIter iter;

            if (!treeviewInspections.Selection.GetSelected(out iter))
            {
                return;
            }
            var actionNode = (BaseCodeIssueProvider)treeStore.GetValue(iter, 1);

            if (actionNode == null)
            {
                return;
            }
            labelDescription.Visible = true;
            labelDescription.Markup  = string.Format(
                "<b>{0}</b>\n{1}",
                Markup.EscapeText(actionNode.Title),
                Markup.EscapeText(actionNode.Description)
                );
        }
Example #8
0
        private static Markup CreateMarkup()
        {
            var markup = new Markup();

            markup.Topic = new Topic
            {
                BimSnippet = new BimSnippet
                {
                    isExternal      = false,
                    Reference       = "JsonElement.json",
                    ReferenceSchema = "http://json-schema.org",
                    SnippetType     = "JSON"
                },
                CreationAuthor = "*****@*****.**",
                CreationDate   = new DateTime(2015, 06, 21, 12, 00, 00, DateTimeKind.Utc),
                Description    = "This topic has an internal BIM Snippet reference",
                Guid           = BcFv21TestCaseData.INTERNAL_BIM_SNIPPET_TOPIC_GUID,
                Index          = 0,
                Title          = "Internal BIM Snippet"
            };
            return(markup);
        }
Example #9
0
        protected void Paste()
        {
            Markup.Clear();
            var map = new ObjectsMap(IsMirror);

            foreach (var source in SourceEnters)
            {
                var enterTarget = source.Target as TargetEnter;
                map.AddSegment(source.Enter.Id, enterTarget?.Enter.Id ?? 0);

                if (enterTarget != null)
                {
                    for (var i = 0; i < source.Points.Length; i += 1)
                    {
                        map.AddPoint(enterTarget.Enter.Id, (byte)(i + 1), (byte)((source.Points[i].Target as Target)?.Num + 1 ?? 0));
                    }
                }
            }

            Markup.FromXml(Mod.Version, IntersectionTemplate.Data, map);
            Panel.UpdatePanel();
        }
Example #10
0
        public void SetPointIcon(string name, Bitmap bitmap, int draw_y_add = 0)
        {
            Markup m;

            if (MarkupPointes.TryGetValue(name, out m))
            {
                if (bitmap == null)
                {
                    m.is_defualt_icon = true;
                    m.draw_y_add      = 0;
                }
                else
                {
                    m.is_defualt_icon = false;
                    m.bitmap          = ImageUtil.CloneBitmap(bitmap);
                    U.MakeTransparent(m.bitmap);

                    m.draw_y_add = draw_y_add;
                }
            }
            else
            {
                m           = new Markup();
                m.x         = 65535; //無効な値を適当に入れる.
                m.y         = 65535;
                m.uniqCount = this.MarkupPointes.Count;
                if (bitmap == null)
                {
                    m.is_defualt_icon = true;
                }
                else
                {
                    m.is_defualt_icon = false;
                    m.bitmap          = bitmap;
                }
                MarkupPointes[name] = m;
            }
            this.Map.Invalidate();
        }
Example #11
0
        public void RemoveView(ViewPoint view, Markup issue, bool delComm)
        {
            if (File.Exists(Path.Combine(TempPath, issue.Topic.Guid, view.Viewpoint)))
            {
                File.Delete(Path.Combine(TempPath, issue.Topic.Guid, view.Viewpoint));
            }
            if (File.Exists(view.SnapshotPath))
            {
                File.Delete(view.SnapshotPath);
            }

            var guid = view.Guid;

            issue.Viewpoints.Remove(view);
            //remove comments associated with that view
            var viewcomments = issue.Comment.Where(x => x.Viewpoint != null && x.Viewpoint.Guid == guid).ToList();

            if (!viewcomments.Any())
            {
                return;
            }

            foreach (var viewcomm in viewcomments)
            {
                if (delComm)
                {
                    issue.Comment.Remove(viewcomm);
                }
                else
                {
                    viewcomm.Viewpoint = null;
                }
            }



            HasBeenSaved = false;
        }
Example #12
0
        public static Dictionary <ObjectId, ObjectId> Befor1_2(Markup markup, Dictionary <ObjectId, ObjectId> map)
        {
            if (map == null)
            {
                map = new Dictionary <ObjectId, ObjectId>();
            }

            foreach (var enter in markup.Enters)
            {
                foreach (var point in enter.Points.Skip(1).Take(enter.PointCount - 2))
                {
                    switch (point.Location)
                    {
                    case MarkupPoint.LocationType.LeftEdge:
                        map[new ObjectId()
                            {
                                Point = point.Id
                            }] = new ObjectId()
                        {
                            Point = point.Id - (1 << 16)
                        };
                        break;

                    case MarkupPoint.LocationType.RightEdge:
                        map[new ObjectId()
                            {
                                Point = point.Id
                            }] = new ObjectId()
                        {
                            Point = point.Id + (1 << 16)
                        };
                        break;
                    }
                }
            }

            return(map);
        }
Example #13
0
        public void ParseExpressionArgumentTest()
        {
            //Parse tokens
            MarkupParser markupParser = new MarkupParser(Init("([1234,2345,3556,646])"));
            Markup       markup       = new Markup();

            markupParser.ParseArguments(markup);

            //Test argument
            Assert.AreEqual(1, markup.GetArguments().Count);
            Argument[] arguments = (Argument[])markup.GetArguments().ToArray();
            Assert.AreEqual(typeof(ExpressionArgument), arguments[0].GetType());

            //Test expression argument
            ExpressionArgument exprArgument = (ExpressionArgument)arguments[0];

            Assert.AreEqual(typeof(ListExpression), exprArgument.GetExpression().GetType());

            //Test list expression
            ListExpression listExpression = (ListExpression)exprArgument.GetExpression();

            Assert.AreEqual(4, listExpression.GetExpressions().Count);
        }
Example #14
0
        public JsonResponse <JS.PageSaveResult> Update([JsonRequestBody] JS.PageEditor page)
        {
            return(JsonResponse.Catch(() => {
                var p = Pages.All.FirstOrDefault(x => x.Id == page.Id && x.SiteId == Sites.CurrentSiteId);
                if (p == null)
                {
                    return JsonResponse <JS.PageSaveResult> .NotFound;
                }

                p.Title = page.Title ?? "";
                p.BbText = page.Text;
                p.TagsStandIn = page.TagsStandIn;
                p.ReferenceName = page.ReferenceName;
                p.HtmlText = Markup.ToHtml(p.BbText ?? "", new MarkdownParseArgs {
                    AttachmentMixin = Url.Mixin((PageController c) => c.Attachment(page.Id))
                });
                UnitOfWork.Commit();

                return JsonResponse.Create(new JS.PageSaveResult {
                    Title = p.Title, Html = p.HtmlText
                });
            }, Log));
        }
        private void ExceptionManagerUnhandledException(UnhandledExceptionArgs args)
        {
            args.ExitApplication = false;

            try
            {
                string message;
                var    exception = args.ExceptionObject as Exception;
                if (exception != null)
                {
                    if (exception.InnerException != null)
                    {
                        exception = exception.InnerException;
                    }

                    message = exception.Message + "\n" + exception.StackTrace;
                }
                else
                {
                    message = args.ExceptionObject.ToString();
                }

                message = Markup.EscapeText(message);

                var dialog = new MessageDialog(
                    this,
                    DialogFlags.DestroyWithParent,
                    MessageType.Error,
                    ButtonsType.Close,
                    message);
                dialog.Run();
                dialog.Destroy();
            }
            catch
            {
            }
        }
Example #16
0
        public static void Main()
        {
            var content = new Markup(
                "[underline]I[/] heard [underline on blue]you[/] like panels\n\n\n\n" +
                "So I put a panel in a panel").Centered();

            AnsiConsole.Render(
                new Panel(
                    new Panel(content)
                    .Border(BoxBorder.Rounded)));

            // Left adjusted panel with text
            AnsiConsole.Render(
                new Panel(new Text("Left adjusted\nLeft").LeftAligned())
                .Expand()
                .SquareBorder()
                .Header("Left")
                .HeaderStyle("red"));

            // Centered ASCII panel with text
            AnsiConsole.Render(
                new Panel(new Text("Centered\nCenter").Centered())
                .Expand()
                .AsciiBorder()
                .Header("Center")
                .HeaderStyle("green")
                .HeaderAlignment(Justify.Center));

            // Right adjusted, rounded panel with text
            AnsiConsole.Render(
                new Panel(new Text("Right adjusted\nRight").RightAligned())
                .Expand()
                .RoundedBorder()
                .Header("Right")
                .HeaderStyle("blue")
                .HeaderAlignment(Justify.Right));
        }
Example #17
0
        public bool CreateMarkup(Guid sourceId, string moduleKey, string memberId, MarkupType markupType, string sourceType = null, string moduleName = null)
        {
            try
            {
                var markup = new Markup
                {
                    Id         = KeyGenerator.GetGuidKey(),
                    SourceId   = sourceId,
                    ModuleKey  = moduleKey,
                    MemberId   = memberId,
                    MarkupType = markupType,
                    SourceType = sourceType,
                    CreateTime = DateTime.Now,
                    ModuleName = moduleName
                };

                return(_currencyService.Create(markup));
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "创建标记失败");
                return(false);
            }
        }
        private static Markup CreateMarkup()
        {
            var markup = new Markup();

            markup.Topic = new Topic
            {
                CreationAuthor    = "*****@*****.**",
                CreationDate      = new DateTime(2015, 10, 11, 12, 13, 14, DateTimeKind.Utc),
                Description       = "This topic has a document reference to an external file via an absolute URL. It references the old BCFv1 Markup Schema.",
                Guid              = BcFv21TestCaseData.DOCUMENT_REFERENCE_EXTERNAL_TOPIC_GUID,
                Index             = 0,
                Title             = "Document Reference External",
                DocumentReference = new List <TopicDocumentReference>
                {
                    new TopicDocumentReference
                    {
                        Description        = "BCFv1 Markup Schema",
                        isExternal         = true,
                        ReferencedDocument = "http://www.buildingsmart-tech.org/specifications/bcf-releases/bcfxml-v1/markup.xsd/at_download/file"
                    }
                }
            };
            return(markup);
        }
Example #19
0
        /// <summary>
        /// Visit Markup
        /// </summary>
        /// <param name="markup">Markup to check</param>
        public override void Visit(Markup markup)
        {
            //Check identifier in designator, it should be an XHTML or an user defined function
            String identifier = markup.GetDesignator().GetIdentifier();

            if (SymbolTable.ContainsFunction(identifier))
            {
                //Check arguments
                FunctionDefinition referencedDefinition = SymbolTable.GetFunctionDefinition(identifier);

                if (referencedDefinition.GetFormals().Count != markup.GetArguments().Count)
                {   //Arity mismatch
                    ExceptionList.Add(new FunctionCallArityIncorrect(identifier));
                }
            }
            else
            {
                //Check if it is XHTML, if not its undefined
                if (!IdentifierIsXHTML(identifier) && markup.GetCallState())
                {
                    ExceptionList.Add(new UndefinedFunction(identifier));
                }
            }
        }
Example #20
0
        public bool WriteMarkup(string filePath, Markup markup)
        {
            bool result = false;

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                XmlSerializer serializer = new XmlSerializer(typeof(Markup));
                StreamWriter  writer     = new StreamWriter(filePath);
                serializer.Serialize(writer, markup);
                writer.Close();
                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(filePath + "\nFailed to write markup.\n" + ex.Message, "Write Markup", MessageBoxButton.OK, MessageBoxImage.Warning);
                result = false;
            }
            return(result);
        }
Example #21
0
        /// <summary>
        /// Parser for Arguments
        /// </summary>
        /// <param name="markup">Markup to add arguments to</param>
        /// <returns>Parsed arguments</returns>
        public void ParseArguments(Markup markup)
        {
            //Skip ( character
            NextToken("(", "(Argument, Argument)", '(');

            while (TokenStream.HasNext())
            { //Parse argument(s)
                if (TokenStream.Peek(1).GetValue().ToString() == ")")
                { //No arguments left, so break
                    break;
                }
                else if (TokenStream.Peek(1).GetValue().ToString() == ",")
                { //Second argument
                    //Skip comma
                    NextToken(",", "Argument, Argument", ',');
                }

                //Parse argument
                markup.AddArgument(ParseArgument());
            }

            //Skip ) character
            NextToken(")", "(Argument, Argument)", ')');
        }
Example #22
0
        /// <summary>
        /// Parser for Arguments
        /// </summary>
        /// <param name="markup">Markup to add arguments to</param>
        /// <returns>Parsed arguments</returns>
        public void ParseArguments(Markup markup)
        {
            //Skip ( character
            NextToken("(", "(Argument, Argument)", '(');

            while (TokenStream.HasNext())
            {     //Parse argument(s)
                if (TokenStream.Peek(1).GetValue().ToString() == ")")
                { //No arguments left, so break
                    break;
                }
                else if (TokenStream.Peek(1).GetValue().ToString() == ",")
                { //Second argument
                    //Skip comma
                    NextToken(",", "Argument, Argument", ',');
                }

                //Parse argument
                markup.AddArgument(ParseArgument());
            }

            //Skip ) character
            NextToken(")", "(Argument, Argument)", ')');
        }
Example #23
0
    private Vector3 GetCorrectedDepthPoint(RaycastHit hit, out Markup m)
    {
        float z = 0;
        float x = 0;
        Debug.Log (hit.collider.name);
        m = null;
        for(int a =0; a < hit.collider.transform.childCount && m == null; a++){
            Transform child = hit.collider.transform.GetChild(a);
            if(child.name == "DepthMarkup"){
                m = child.GetComponent<Markup>();
                if(m.available){
                    z = child.position.z;
                    x = child.position.x;
                    Debug.Log (x);
                    m.available = false;
                }
                else{
                    m = null;
                }
            }
        }

        return new Vector3(x,hit.point.y ,z);
    }
Example #24
0
        private static Markup CreateMarkup()
        {
            var markup = new Markup();

            markup.Topic = new Topic
            {
                CreationAuthor    = "*****@*****.**",
                CreationDate      = new DateTime(2015, 10, 11, 12, 13, 14, DateTimeKind.Utc),
                Description       = "This topic has a document reference to an internal PDF file in the directory root.",
                Guid              = BcFv21TestCaseData.PDF_FILE_TOPIC_GUID,
                Index             = 0,
                Title             = "PDF File",
                DocumentReference = new List <TopicDocumentReference>
                {
                    new TopicDocumentReference
                    {
                        Description        = "Project requirements (pdf)",
                        isExternal         = false,
                        ReferencedDocument = "../Requirements.pdf"
                    }
                }
            };
            return(markup);
        }
        // Token: 0x06000622 RID: 1570 RVA: 0x00030C24 File Offset: 0x0002EE24
        public static void ConvertAndOutputBody(TextWriter output, Body body, Markup markup, OwaSafeHtmlCallbackBase callBack, bool isComposeBody)
        {
            string bodyString = string.Empty;
            BodyReadConfiguration bodyReadConfiguration = null;

            try
            {
                switch (markup)
                {
                case Markup.Html:
                    bodyReadConfiguration = new BodyReadConfiguration(BodyFormat.TextHtml);
                    bodyReadConfiguration.SetHtmlOptions(HtmlStreamingFlags.FilterHtml | HtmlStreamingFlags.Fragment, callBack);
                    break;

                case Markup.PlainText:
                    bodyReadConfiguration = new BodyReadConfiguration(BodyFormat.TextPlain);
                    break;
                }
                if (bodyReadConfiguration != null)
                {
                    using (TextReader textReader = body.OpenTextReader(bodyReadConfiguration))
                    {
                        bodyString = textReader.ReadToEnd();
                    }
                }
                BodyConversionUtilities.RenderBodyContent(output, bodyString, markup, isComposeBody);
            }
            catch (InvalidCharsetException innerException)
            {
                throw new OwaBodyConversionFailedException("Body Conversion Failed", innerException);
            }
            catch (ConversionFailedException innerException2)
            {
                throw new OwaBodyConversionFailedException("Body Conversion Failed", innerException2);
            }
        }
        public void ReportPerformanceExperience()
        {
            base.ResponseContentType = OwaEventContentType.Javascript;
            string      text        = (string)base.GetParameter("s");
            MessageItem messageItem = MessageItem.Create(base.UserContext.MailboxSession, base.UserContext.DraftsFolderId);

            messageItem[ItemSchema.ConversationIndexTracking] = true;
            Markup markup = Markup.Html;

            BodyConversionUtilities.SetBody(messageItem, (string)base.GetParameter("b"), markup, StoreObjectType.Message, base.UserContext);
            messageItem.Recipients.Add(new Participant(null, Globals.ErrorReportAddress, "SMTP"), RecipientItemType.To);
            messageItem.Subject = string.Concat(new string[]
            {
                "Performance Report on ",
                DateTime.UtcNow.ToLocalTime().ToShortDateString(),
                " ",
                DateTime.UtcNow.ToLocalTime().ToShortTimeString(),
                " for ",
                base.OwaContext.UserContext.ExchangePrincipal.MailboxInfo.DisplayName
            });
            messageItem.Save(SaveMode.ResolveConflicts);
            messageItem.Load();
            this.Writer.Write(messageItem.Id.ObjectId.ToBase64String());
        }
Example #27
0
        /// <summary>
        /// Add Issue to BCF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddIssueBCF(object sender, EventArgs e)
        {
            try
            {
                Tuple <Markup, Issue> tup = AddIssue(mainPan.jira.Bcf.TempPath, true);
                if (tup == null)
                {
                    return;
                }
                Markup issue = tup.Item1;

                if (issue != null)
                {
                    mainPan.jira.Bcf.Issues.Add(issue);
                    mainPan.jira.Bcf.HasBeenSaved          = false;
                    mainPan.bcfPan.issueList.SelectedIndex = mainPan.jira.Bcf.Issues.Count - 1;
                }
            }

            catch (System.Exception ex1)
            {
                MessageBox.Show("exception: " + ex1);
            }
        }
Example #28
0
  private HitType MarkupHitTest(Markup markup, IGeometry g, double distance, double scale)
  {
    WKTReader wktReader = new WKTReader();
    IGeometry geometry = wktReader.Read(markup.Shape);

    HitType hitType = HitType.None;

    if (geometry.OgcGeometryType != OgcGeometryType.Point || String.IsNullOrEmpty(markup.Text))
    {
      if ((g is IPoint && geometry.Distance(g) <= distance) || (!(g is IPoint) && geometry.Intersects(g)))
      {
        hitType = geometry.OgcGeometryType == OgcGeometryType.Point && markup.Measured.HasValue && markup.Measured == 1 ? HitType.Coordinate : HitType.Shape;
      }
    }
    else
    {
      System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new System.Drawing.Bitmap(10, 10));

      Coordinate origin = ((IPoint)geometry).Coordinate;
      System.Drawing.SizeF textSize = graphics.MeasureString(markup.Text, AppSettings.MarkupFont);

      Envelope box = new Envelope(new Coordinate(origin.X, origin.Y), new Coordinate(origin.X + textSize.Width * scale, origin.Y + textSize.Height * scale));

      if (box.ToPolygon().Intersects(g))
      {
        hitType = HitType.Text;
      }
    }

    return hitType;
  }
Example #29
0
  private HitType MarkupHitTest(DataRow markupRow, IGeometry g, double distance, double scale)
  {
    Markup markup = new Markup();
    markup.Shape = markupRow["Shape"].ToString();
    
    if (!markupRow.IsNull("Text"))
    {
      markup.Text = markupRow["Text"].ToString();
    }

    if (!markupRow.IsNull("Measured"))
    {
      markup.Measured = (int?)markupRow["Measured"];
    }

    return MarkupHitTest(markup, g, distance, scale);
  }
Example #30
0
 /// <summary>
 /// Set markup of mapping
 /// </summary>
 /// <param name="markup">Markup of mapping</param>
 public void SetMarkup(Markup.Markup markup)
 {
     Markup = markup;
 }
Example #31
0
        public void ParseExpressionArgumentTest()
        {
            //Parse tokens
            MarkupParser markupParser = new MarkupParser(Init("([1234,2345,3556,646])"));
            Markup markup = new Markup();
            markupParser.ParseArguments(markup);

            //Test argument
            Assert.AreEqual(1, markup.GetArguments().Count);
            Argument[] arguments = (Argument[]) markup.GetArguments().ToArray();
            Assert.AreEqual(typeof(ExpressionArgument), arguments[0].GetType());

            //Test expression argument
            ExpressionArgument exprArgument = (ExpressionArgument)arguments[0];
            Assert.AreEqual(typeof(ListExpression), exprArgument.GetExpression().GetType());

            //Test list expression
            ListExpression listExpression = (ListExpression) exprArgument.GetExpression();
            Assert.AreEqual(4, listExpression.GetExpressions().Count);
        }
Example #32
0
        /// <summary>
        /// Creates a new instance of IncCell
        /// </summary>
        public IncCell(string tag, ChainedProperties props)
        {
            Cell = new PdfPCell();

            var value = props["colspan"];

            if (value != null)
            {
                Cell.Colspan = int.Parse(value);
            }

            value = props["rowspan"];
            if (value != null)
            {
                Cell.Rowspan = int.Parse(value);
            }

            value = props["align"];
            if (tag.Equals("th"))
            {
                Cell.HorizontalAlignment = Element.ALIGN_CENTER;
            }

            if (value != null)
            {
                if (Util.EqualsIgnoreCase(value, "center"))
                {
                    Cell.HorizontalAlignment = Element.ALIGN_CENTER;
                }
                else if (Util.EqualsIgnoreCase(value, "right"))
                {
                    Cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                }
                else if (Util.EqualsIgnoreCase(value, "left"))
                {
                    Cell.HorizontalAlignment = Element.ALIGN_LEFT;
                }
                else if (Util.EqualsIgnoreCase(value, "justify"))
                {
                    Cell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                }
            }

            value = props["valign"];
            Cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            if (value != null)
            {
                if (Util.EqualsIgnoreCase(value, "top"))
                {
                    Cell.VerticalAlignment = Element.ALIGN_TOP;
                }
                else if (Util.EqualsIgnoreCase(value, "bottom"))
                {
                    Cell.VerticalAlignment = Element.ALIGN_BOTTOM;
                }
            }

            value = props["border"];
            float border = 0;

            if (value != null)
            {
                border = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            Cell.BorderWidth = border;
            value            = props["cellpadding"];
            if (value != null)
            {
                Cell.Padding = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            // Advanced formatting - does not conform to HTML standards
            value = props["bordertop"];
            if (value != null)
            {
                Cell.BorderWidthTop = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["borderbottom"];
            if (value != null)
            {
                Cell.BorderWidthBottom = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["borderleft"];
            if (value != null)
            {
                Cell.BorderWidthLeft = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["borderright"];
            if (value != null)
            {
                Cell.BorderWidthRight = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["cellpaddingtop"];
            if (value != null)
            {
                Cell.PaddingTop = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["cellpaddingbottom"];
            if (value != null)
            {
                Cell.PaddingBottom = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["cellpaddingleft"];
            if (value != null)
            {
                Cell.PaddingLeft = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["cellpaddingright"];
            if (value != null)
            {
                Cell.PaddingRight = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            value = props["bordercolor"];
            if (value != null)
            {
                Cell.BorderColor = Markup.DecodeColor(value);
            }

            Cell.UseDescender    = true;
            value                = props["bgcolor"];
            Cell.BackgroundColor = Markup.DecodeColor(value);
        }
Example #33
0
  private void LoadStateFromLaunchParams(Dictionary<String, String> launchParams)
  {
    _appState = new AppState();

    // recreate application state from a compressed string if provided

    if (launchParams.ContainsKey("state"))
    {
      RestoreState(launchParams["state"]);
      return;
    }

    // otherwise, if no application was specified, show the
    // available applications or an error

    if (String.IsNullOrEmpty(AppSettings.DefaultApplication) && !launchParams.ContainsKey("application"))
    {
      ShowError("An application has not been specified");
    }

    // check that Web.config has the necessary settings

    if (AppSettings.DefaultFullExtent == null)
    {
      ShowError("FullExtent has not been provided or is invalid in Web.config");
    }

    if (AppSettings.MapUnits == null)
    {
      ShowError("MapUnits has not been provided in Web.config");
    }
    else
    {
      string mapUnits = AppSettings.MapUnits;

      if (mapUnits != "feet" && mapUnits != "meters")
      {
        ShowError("MapUnits is invalid in Web.config, must be \"feet\" or \"meters\"");
      }
    }

    if (AppSettings.MeasureUnits == null)
    {
      ShowError("MeasureUnits has not been provided in Web.config");
    }
    else
    {
      string measureUnits = AppSettings.MeasureUnits;

      if (measureUnits != "feet" && measureUnits != "meters" && measureUnits != "both")
      {
        ShowError("MeasureUnits is invalid in Web.config, must be \"feet\", \"meters\", or \"both\"");
      }
    }

    if (AppSettings.CoordinateSystem == null)
    {
      ShowError("Projection parameters have not been provided or are invalid in Web.config");
    }

    // -- Active --

    if (AppSettings.ActiveColor.IsEmpty)
    {
      ShowError("ActiveColor has not been provided or is invalid in Web.config");
    }

    if (Double.IsNaN(AppSettings.ActiveOpacity))
    {
      ShowError("ActiveColor has not been provided in Web.config");
    }

    if (AppSettings.ActiveOpacity < 0 || 1 < AppSettings.ActiveOpacity)
    {
      ShowError("ActiveColor is invalid in Web.config");
    }

    if (AppSettings.ActivePolygonMode == null)
    {
      ShowError("ActivePolygonMode has not been provided in Web.config");
    }
    else
    {
      string polygonMode = AppSettings.ActivePolygonMode;

      if (polygonMode != "fill" && polygonMode != "outline")
      {
        ShowError("ActivePolygonMode is invalid in Web.config, must be \"fill\" or \"outline\"");
      }
    }

    if (AppSettings.ActivePenWidth == Int32.MinValue)
    {
      ShowError("ActivePenWidth has not been provided in Web.config");
    }

    if (AppSettings.ActivePenWidth <= 0)
    {
      ShowError("ActivePenWidth is invalid in Web.config");
    }

    if (AppSettings.ActiveDotSize == Int32.MinValue)
    {
      ShowError("ActiveDotSize has not been provided in Web.config");
    }

    if (AppSettings.ActiveDotSize <= 0)
    {
      ShowError("ActiveDotSize is invalid in Web.config");
    }

    // -- Target --

    if (AppSettings.TargetColor.IsEmpty)
    {
      ShowError("TargetColor has not been provided or is invalid in Web.config");
    }

    if (Double.IsNaN(AppSettings.TargetOpacity))
    {
      ShowError("TargetOpacity has not been provided in Web.config");
    }

    if (AppSettings.TargetOpacity < 0 || 1 < AppSettings.TargetOpacity)
    {
      ShowError("TargetOpacity is invalid in Web.config");
    }

    if (AppSettings.TargetPolygonMode == null)
    {
      ShowError("TargetPolygonMode has not been provided in Web.config");
    }
    else
    {
      string polygonMode = AppSettings.TargetPolygonMode;

      if (polygonMode != "fill" && polygonMode != "outline")
      {
        ShowError("TargetPolygonMode is invalid in Web.config, must be \"fill\" or \"outline\"");
      }
    }

    if (AppSettings.TargetPenWidth == Int32.MinValue)
    {
      ShowError("TargetPenWidth has not been provided in Web.config");
    }

    if (AppSettings.TargetPenWidth <= 0)
    {
      ShowError("TargetPenWidth is invalid in Web.config");
    }

    if (AppSettings.TargetDotSize == Int32.MinValue)
    {
      ShowError("TargetDotSize has not been provided in Web.config");
    }

    if (AppSettings.TargetDotSize <= 0)
    {
      ShowError("TargetDotSize is invalid in Web.config");
    }

    // -- Selection --

    if (AppSettings.SelectionColor.IsEmpty)
    {
      ShowError("SelectionColor has not been provided or is invalid in Web.config");
    }

    if (Double.IsNaN(AppSettings.SelectionOpacity))
    {
      ShowError("SelectionOpacity has not been provided in Web.config");
    }

    if (AppSettings.SelectionOpacity < 0 || 1 < AppSettings.SelectionOpacity)
    {
      ShowError("SelectionOpacity is invalid in Web.config");
    }

    if (AppSettings.SelectionPolygonMode == null)
    {
      ShowError("SelectionPolygonMode has not been provided in Web.config");
    }
    else
    {
      string polygonMode = AppSettings.SelectionPolygonMode;

      if (polygonMode != "fill" && polygonMode != "outline")
      {
        ShowError("SelectionPolygonMode is invalid in Web.config, must be \"fill\" or \"outline\"");
      }
    }

    if (AppSettings.SelectionPenWidth == Int32.MinValue)
    {
      ShowError("SelectionPenWidth has not been provided in Web.config");
    }

    if (AppSettings.SelectionPenWidth <= 0)
    {
      ShowError("SelectionPenWidth is invalid in Web.config");
    }

    if (AppSettings.SelectionDotSize == Int32.MinValue)
    {
      ShowError("SelectionDotSize has not been provided in Web.config");
    }

    if (AppSettings.SelectionDotSize <= 0)
    {
      ShowError("SelectionDotSize is invalid in Web.config");
    }

    // -- Filtered --

    if (AppSettings.FilteredColor.IsEmpty)
    {
      ShowError("FilteredColor has not been provided or is invalid in Web.config");
    }

    if (Double.IsNaN(AppSettings.FilteredOpacity))
    {
      ShowError("FilteredOpacity has not been provided in Web.config");
    }

    if (AppSettings.FilteredOpacity < 0 || 1 < AppSettings.FilteredOpacity)
    {
      ShowError("FilteredOpacity is invalid in Web.config");
    }

    if (AppSettings.FilteredPolygonMode == null)
    {
      ShowError("FilteredPolygonMode has not been provided in Web.config");
    }
    else
    {
      string polygonMode = AppSettings.FilteredPolygonMode;

      if (polygonMode != "fill" && polygonMode != "outline")
      {
        ShowError("FilteredPolygonMode is invalid in Web.config, must be \"fill\" or \"outline\"");
      }
    }

    if (AppSettings.FilteredPenWidth == Int32.MinValue)
    {
      ShowError("FilteredPenWidth has not been provided in Web.config");
    }

    if (AppSettings.FilteredPenWidth <= 0)
    {
      ShowError("FilteredPenWidth is invalid in Web.config");
    }

    if (AppSettings.FilteredDotSize == Int32.MinValue)
    {
      ShowError("FilteredDotSize has not been provided in Web.config");
    }

    if (AppSettings.FilteredDotSize <= 0)
    {
      ShowError("FilteredDotSize is invalid in Web.config");
    }

    // -- Buffer --

    if (AppSettings.BufferColor.IsEmpty)
    {
      ShowError("BufferColor has not been provided or is invalid in Web.config");
    }

    if (Double.IsNaN(AppSettings.BufferOpacity))
    {
      ShowError("BufferOpacity has not been provided in Web.config");
    }

    if (AppSettings.BufferOpacity < 0 || 1 < AppSettings.BufferOpacity)
    {
      ShowError("BufferOpacity is invalid in Web.config");
    }

    if (AppSettings.BufferOutlineColor.IsEmpty)
    {
      ShowError("BufferOutlineColor has not been provided or is invalid in Web.config");
    }

    if (Double.IsNaN(AppSettings.BufferOutlineOpacity))
    {
      ShowError("BufferOutlineOpacity has not been provided in Web.config");
    }

    if (AppSettings.BufferOutlineOpacity < 0 || 1 < AppSettings.BufferOutlineOpacity)
    {
      ShowError("BufferOutlineOpacity is invalid in Web.config");
    }

    if (AppSettings.BufferOutlineOpacity == Int32.MinValue)
    {
      ShowError("BufferOutlineOpacity has not been provided in Web.config");
    }

    if (AppSettings.ExportFormat == null)
    {
      ShowError("ExportFormat has not been provided in Web.config");
    }
    else
    {
      if (AppSettings.ExportFormat != "csv" && AppSettings.ExportFormat != "xls")
      {
        ShowError("ExportFormat is invalid in Web.config, must be \"csv\" or \"xls\"");
      }
    }

    if (AppSettings.PreserveOnActionChange != "target" && AppSettings.PreserveOnActionChange != "selection")
    {
      ShowError("PreserveOnActionChange is invalid in Web.config, must be \"target\" or \"selection\"");
    }

    if (AppSettings.MarkupTimeout == Int32.MinValue)
    {
      ShowError("MarkupTimeout has not been provided in Web.config");
    }

    // otherwise, load the query string into the application state
    // and validate against the configuration

    // === application ===

    _appState.Application = launchParams.ContainsKey("application") ? launchParams["application"] : AppSettings.DefaultApplication;

    Configuration.ApplicationRow application = _config.Application.FindByApplicationID(_appState.Application);
    Configuration.MapTabRow mapTab;

    // the Application must exist

    if (application == null)
    {
      ShowError("Application '" + _appState.Application + "' does not exist");
    }

    // the user must be authorized to run the application

    string roles = application.IsAuthorizedRolesNull() ? "public" : application.AuthorizedRoles;

    if (!AppUser.RoleIsInList(roles))
    {
      ShowError("You are not authorized to view the application '" + _appState.Application + "'");
    }

    _appState.Application = application.ApplicationID;
    _appState.Extent = application.GetFullExtentEnvelope();

    // get the default visible layers for all interactive legends

    foreach (Configuration.ApplicationMapTabRow applicationMapTab in application.GetApplicationMapTabRows())
    {
      mapTab = applicationMapTab.MapTabRow;

      if (!mapTab.IsInteractiveLegendNull() && mapTab.InteractiveLegend == 1)
      {
        string key = mapTab.MapTabID;
        StringCollection values = new StringCollection();

        foreach (Configuration.MapTabLayerRow mapTabLayer in mapTab.GetMapTabLayerRows())
        {
          if (!mapTabLayer.IsShowInLegendNull() && mapTabLayer.ShowInLegend == 1 &&
              !mapTabLayer.IsCheckInLegendNull() && mapTabLayer.CheckInLegend == 1)
          {
            values.Add(mapTabLayer.LayerID);
          }
        }

        _appState.VisibleLayers.Add(key, values);
      }
    }

    // === maptab ===

    mapTab = null;

    if (launchParams.ContainsKey("maptab"))
    {
      _appState.MapTab = launchParams["maptab"];
      mapTab = _config.MapTab.FindByMapTabID(_appState.MapTab);

      // the MapTab must exist

      if (mapTab == null)
      {
        ShowError("Map tab '" + _appState.MapTab + "' does not exist");
      }

      _appState.MapTab = mapTab.MapTabID;
      string filter = "ApplicationID = '" + application.ApplicationID + "' and MapTabID = '" + mapTab.MapTabID + "'";

      // the Application must contain the MapTab

      if (_config.ApplicationMapTab.Select(filter).Length == 0)
      {
        ShowError("Application '" + application.ApplicationID + "' does not contain map tab '" + mapTab.MapTabID + "'");
      }
    }

    // get the default MapTab from the Application if available

    if (mapTab == null)
    {
      if (!application.IsDefaultMapTabNull())
      {
        mapTab = (Configuration.MapTabRow)(_config.MapTab.Select("MapTabID = '" + application.DefaultMapTab + "'")[0]);
      }
      else
      {
        Configuration.ApplicationMapTabRow applicationMapTab = (Configuration.ApplicationMapTabRow)_config.ApplicationMapTab.Select("ApplicationID = '" + _appState.Application + "'")[0];
        mapTab = applicationMapTab.MapTabRow;
      }

      _appState.MapTab = mapTab.MapTabID;
    }

    // === layers on ===

    if (launchParams.ContainsKey("layerson"))
    {
      StringCollection layersOn = StringCollection.FromString(launchParams["layerson"], ',');
      StringCollection visibleLayers = _appState.VisibleLayers[mapTab.MapTabID];

      foreach (string layerId in layersOn)
      {
        Configuration.MapTabLayerRow mapTabLayer = mapTab.GetMapTabLayerRows().FirstOrDefault(o => o.LayerID == layerId);

        if (mapTabLayer == null)
        {
          ShowError(String.Format("Layer \"{0}\" does not exist in map tab \"{1}\"", layerId, mapTab.MapTabID));
        }
        else if (!mapTabLayer.IsShowInLegendNull() && mapTabLayer.ShowInLegend == 1 &&
            !mapTabLayer.IsCheckInLegendNull() && mapTabLayer.CheckInLegend >= 0 &&
            !visibleLayers.Contains(layerId))
        {
          visibleLayers.Add(layerId);
        }
      }
    }

    // === layers off ===

    if (launchParams.ContainsKey("layersoff"))
    {
      StringCollection layersOff = StringCollection.FromString(launchParams["layersoff"], ',');
      StringCollection visibleLayers = _appState.VisibleLayers[mapTab.MapTabID];

      foreach (string layerId in layersOff)
      {
        Configuration.MapTabLayerRow mapTabLayer = mapTab.GetMapTabLayerRows().FirstOrDefault(o => o.LayerID == layerId);

        if (mapTabLayer == null)
        {
          ShowError(String.Format("Layer \"{0}\" does not exist in map tab \"{1}\"", layerId, mapTab.MapTabID));
        }
        else if (!mapTabLayer.IsShowInLegendNull() && mapTabLayer.ShowInLegend == 1 &&
            !mapTabLayer.IsCheckInLegendNull() && mapTabLayer.CheckInLegend >= 1 &&
            visibleLayers.Contains(layerId))
        {
          visibleLayers.Remove(layerId);
        }
      }
    }

    // === level ===

    Configuration.ZoneLevelRow zoneLevel = application.ZoneLevelRow;
    Configuration.LevelRow[] levels = zoneLevel != null ? zoneLevel.GetLevelRows() : new Configuration.LevelRow[0];

    if (!application.IsDefaultLevelNull())
    {
      _appState.Level = application.DefaultLevel;
    }
    else if (levels.Length > 0)
    {
      _appState.Level = levels[0].LevelID;
    }

    if (launchParams.ContainsKey("level"))
    {
      if (levels.Length == 0)
      {
        ShowError("A level was specified but levels have not been configured for this application");
      }
      else if (!levels.Any(o => o.LevelID == launchParams["level"]))
      {
        ShowError(String.Format("Invalid level '{0}' specified", launchParams["level"]));
      }
      else
      {
        _appState.Level = launchParams["level"];
      }
    }

    // === action ===

    if (!application.IsDefaultActionNull())
    {
      _appState.Action = (Action)Enum.Parse(typeof(Action), application.DefaultAction, true);
    }

    if (launchParams.ContainsKey("action"))
    {
      try
      {
        _appState.Action = (Action)Enum.Parse(typeof(Action), launchParams["action"], true);
      }
      catch
      {
        ShowError("Invalid action '" + launchParams["action"] + "', must be either " + EnumHelper.ToChoiceString(typeof(Action)));
      }
    }

    // === targetlayer ===

    Configuration.LayerRow targetLayer = null;

    if (launchParams.ContainsKey("targetlayer"))
    {
      _appState.TargetLayer = launchParams["targetlayer"];
      targetLayer = _config.Layer.FindByLayerID(_appState.TargetLayer);

      // the Layer must exist

      if (targetLayer == null)
      {
        ShowError("Target layer '" + _appState.TargetLayer + "' does not exist");
      }

      _appState.TargetLayer = targetLayer.LayerID;

      // a MapTab must be specified or available by default

      if (mapTab == null)
      {
        ShowError("When providing a target layer, a map tab must also be specified or the application must have a default map tab defined");
      }

      string filter = "MapTabID = '" + mapTab.MapTabID + "' and LayerID = '" + targetLayer.LayerID + "'";
      DataRow[] rows = _config.MapTabLayer.Select(filter);

      // the MapTab must contain the Layer

      if (rows.Length == 0)
      {
        ShowError("Layer '" + targetLayer.LayerID + "' does not exist in map tab '" + mapTab.MapTabID + "'");
      }

      Configuration.MapTabLayerRow link = (Configuration.MapTabLayerRow)rows[0];

      // the Layer must be an allowed as a target in the MapTab

      if (link.IsAllowTargetNull() || link.AllowTarget <= 0)
      {
        ShowError("Layer '" + targetLayer.LayerID + "' is not allowed to be a target layer for map tab '" + mapTab.MapTabID + "'");
      }
    }

    // get the default target Layer from the Application

    if (targetLayer == null && !application.IsDefaultTargetLayerNull())
    {
      targetLayer = (Configuration.LayerRow)(_config.Layer.Select("LayerID = '" + application.DefaultTargetLayer + "'")[0]);
      _appState.TargetLayer = targetLayer.LayerID;
    }

    // === targetids ===

    if (launchParams.ContainsKey("targetids"))
    {
      if (launchParams.ContainsKey("targetparams"))
      {
        ShowError("When providing target IDs, target parameters are not allowed");
      }

      // action must be Select

      if (_appState.Action != Action.Select)
      {
        ShowError("When providing target IDs, action must be 'select'");
      }

      // a target Layer must be available

      if (targetLayer == null)
      {
        ShowError("When providing target IDs, a target layer must also be specified or the application must have a default target layer defined");
      }

      _appState.TargetIds = StringCollection.FromString(launchParams["targetids"], ',');
    }

    // === targetparams ===

    if (launchParams.ContainsKey("targetparams"))
    {
      // action must be Select

      if (_appState.Action != Action.Select)
      {
        ShowError("When providing target parameters, action must be 'select'");
      }

      // a target Layer must be available

      if (targetLayer == null)
      {
        ShowError("When providing target parameters, a target layer must also be specified or the application must have a default target layer defined");
      }

      if (!targetLayer.GetLayerFunctionRows().Any(o => o.FunctionName == "targetparams"))
      {
        ShowError("The target layer has not been configured to accept target parameters");
      }

      _appState.TargetIds = targetLayer.GetTargetIds(launchParams["targetparams"]);
    }

    // === proximity ===

    Configuration.ProximityRow proximity = null;

    if (launchParams.ContainsKey("proximity"))
    {
      _appState.Proximity = launchParams["proximity"];
      proximity = _config.Proximity.FindByProximityID(_appState.Proximity);

      // the Proximity must exist

      if (proximity == null)
      {
        ShowError(String.Format("Proximity '{0}' does not exist", _appState.Proximity));
      }

      _appState.Proximity = proximity.ProximityID;

      // a target Layer must be available

      if (targetLayer == null)
      {
        ShowError("When providing a proximity, a target layer must also be specified or the application must have a default target layer defined");
      }

      // the Proximity must be valid for the target Layer

      bool invalid = false;
      bool proximityAttachedToLayer = _config.LayerProximity.Select(String.Format("LayerID = '{0}' and ProximityID = '{1}'", targetLayer.LayerID, _appState.Proximity)).Length == 1;

      if (proximity.IsIsDefaultNull() || proximity.IsDefault == 1)
      {
        bool layerHasProximities = _config.LayerProximity.Select(String.Format("LayerID = '{0}'", targetLayer.LayerID)).Length > 0;
        invalid = layerHasProximities && !proximityAttachedToLayer;
      }
      else
      {
        invalid = !proximityAttachedToLayer;
      }

      if (invalid)
      {
        ShowError(String.Format("Proximity '{0}' is not valid for target layer '{1}'", _appState.Proximity, _appState.TargetLayer));
      }
    }

    // get the default Proximity from the Application or configuration

    if (proximity == null && !application.IsDefaultProximityNull())
    {
      proximity = (Configuration.ProximityRow)(_config.Proximity.Select(String.Format("ProximityID = '{0}'", application.DefaultProximity))[0]);
      _appState.Proximity = proximity.ProximityID;
    }

    // === selectionlayer ===

    Configuration.LayerRow selectionLayer = null;

    if (launchParams.ContainsKey("selectionlayer"))
    {
      _appState.SelectionLayer = launchParams["selectionlayer"];
      selectionLayer = _config.Layer.FindByLayerID(_appState.SelectionLayer);

      // the Layer must exist

      if (selectionLayer == null)
      {
        ShowError("Selection layer '" + _appState.SelectionLayer + "' does not exist");
      }

      _appState.SelectionLayer = selectionLayer.LayerID;

      // a MapTab must be specified or available by default

      if (mapTab == null)
      {
        ShowError("When providing a selection layer, a map tab must also be specified or the application must have a default map tab defined");
      }

      // a target Layer must be available

      if (targetLayer == null)
      {
        ShowError("When providing a selection layer, a target layer must also be specified or the application must have a default target layer defined");
      }

      string filter = "MapTabID = '" + mapTab.MapTabID + "' and LayerID = '" + selectionLayer.LayerID + "'";
      DataRow[] rows = _config.MapTabLayer.Select(filter);

      // the MapTab must contain the Layer

      if (rows.Length == 0)
      {
        ShowError("Layer '" + selectionLayer.LayerID + "' does not exist in map tab '" + mapTab.MapTabID + "'");
      }

      Configuration.MapTabLayerRow link = (Configuration.MapTabLayerRow)rows[0];

      // the Layer must be allowed for selection in the MapTab

      if (link.IsAllowSelectionNull() || link.AllowSelection <= 0)
      {
        ShowError("Layer '" + selectionLayer.LayerID + "' is not allowed to be a selection layer for map tab '" + mapTab.MapTabID + "'");
      }
    }

    // get the default selection Layer from the Application

    if (selectionLayer == null && !application.IsDefaultSelectionLayerNull())
    {
      selectionLayer = (Configuration.LayerRow)(_config.Layer.Select("LayerID = '" + application.DefaultSelectionLayer + "'")[0]);
      _appState.SelectionLayer = selectionLayer.LayerID;
    }

    // === selectionids ===

    if (launchParams.ContainsKey("selectionids"))
    {
      if (_appState.TargetIds.Count > 0)
      {
        ShowError("When providing target IDs or target parameters, selection IDs are not allowed");
      }

      // a selection Layer must be available

      if (selectionLayer == null)
      {
        ShowError("When providing selection IDs, a selection layer must also be specified or the application must have a default selection layer defined");
      }

      _appState.SelectionIds = StringCollection.FromString(launchParams["selectionids"], ',');

      if (_appState.Action == Action.FindAllWithin && String.IsNullOrEmpty(_appState.Proximity))
      {
        ShowError("When action is 'findallwithin' and selection IDs are provided, a proximity must also be specified or the application must have a default proximity defined");
      }

      if (_appState.Action != Action.Select)
      {
        _appState.SelectionManager.SelectTargets();
      }
    }

    // zoom to the extent of the target and/or selection features

    if (_appState.TargetIds.Count > 0 || _appState.SelectionIds.Count > 0)
    {
      Envelope extent = new Envelope();

      if (_appState.TargetIds.Count > 0)
      {
        extent.ExpandToInclude(_appState.SelectionManager.GetExtent(FeatureType.Target));
      }

      if (_appState.SelectionIds.Count > 0)
      {
        extent.ExpandToInclude(_appState.SelectionManager.GetExtent(FeatureType.Selection));
      }

      if (!extent.IsNull)
      {
        extent.ScaleBy(1.2);
        _appState.Extent = extent;
      }
    }

    // === activemapid ===

    if (launchParams.ContainsKey("activemapid"))
    {
      string activeMapId = launchParams["activemapid"];

      if (_appState.TargetIds.Contains(activeMapId))
      {
        _appState.ActiveMapId = activeMapId;
      }
    }

    // === activedataid ===

    if (launchParams.ContainsKey("activedataid"))
    {
      _appState.ActiveDataId = launchParams["activedataid"];
    }
    else
    {
      if (_appState.ActiveMapId.Length > 0)
      {
        _appState.ActiveDataId = _appState.ActiveMapId;
      }
    }

    // === query ===

    Configuration.QueryRow query = null;

    if (launchParams.ContainsKey("query"))
    {
      query = _config.Query.FindByQueryID(launchParams["query"]);

      // the Query must exist

      if (query == null)
      {
        ShowError("Query '" + launchParams["query"] + "' does not exist");
      }

      // a target Layer must be available

      if (targetLayer == null)
      {
        ShowError("When providing a query, a target layer must also be specified or the application must have a default target layer defined");
      }

      // the target Layer must contain the Query

      if (query.LayerID != targetLayer.LayerID)
      {
        ShowError("Target layer '" + targetLayer.LayerID + "' does not contain query '" + query.QueryID + "'");
      }
    }
    else if (!String.IsNullOrEmpty(_appState.TargetLayer))
    {
      query = _config.Query.Where(o => o.LayerID == _appState.TargetLayer).OrderBy(o => o.SequenceNo).FirstOrDefault();
    }

    if (query != null)
    {
      _appState.Query = query.QueryID;

      // a single TargetId was specified without ActiveMapId and ActiveDataId, try to fetch a single data ID for it
      // from the query stored procedure; if found set ActiveMapId and ActiveDataId

      if (_appState.TargetIds.Count == 1 && String.IsNullOrEmpty(_appState.ActiveMapId) && String.IsNullOrEmpty(_appState.ActiveDataId))
      {
        string mapId = _appState.TargetIds[0];
        string dataId = null;

        using (OleDbCommand command = query.GetDatabaseCommand())
        {
          command.Parameters[0].Value = mapId;

          if (command.Parameters.Count > 1)
          {
            command.Parameters[1].Value = AppUser.GetRole();
          }

          try
          {
            using (OleDbDataReader reader = command.ExecuteReader())
            {
              if (reader.Read())
              {
                try
                {
                  int dataIdColumn = reader.GetOrdinal("DataID");
                  dataId = reader.GetValue(dataIdColumn).ToString();
                }
                catch
                {
                  dataId = mapId;
                }
              }

              if (reader.Read())
              {
                dataId = null;
              }
            }
          }
          catch { }

          command.Connection.Close();
        }

        if (!String.IsNullOrEmpty(dataId))
        {
          _appState.ActiveMapId = mapId;
          _appState.ActiveDataId = dataId;
        }
      }
    }

    // === datatab ===

    if (launchParams.ContainsKey("datatab"))
    {
      _appState.DataTab = launchParams["datatab"];
      Configuration.DataTabRow dataTab = _config.DataTab.FindByDataTabID(_appState.DataTab);

      // the DataTab must exist

      if (dataTab == null)
      {
        ShowError("Data tab '" + _appState.DataTab + "' does not exist");
      }

      _appState.DataTab = dataTab.DataTabID;

      // a target Layer must be available

      if (targetLayer == null)
      {
        ShowError("When providing a data tab, a target layer must also be specified or the application must have a default target layer defined");
      }

      // the target Layer must contain the DataTab

      if (dataTab.LayerID != targetLayer.LayerID)
      {
        ShowError("Target layer '" + targetLayer.LayerID + "' does not contain data tab '" + dataTab.DataTabID + "'");
      }
    }

    // === function tabs ===

    if (!application.IsFunctionTabsNull())
    {
      _appState.FunctionTabs = (FunctionTab)Enum.Parse(typeof(FunctionTab), application.FunctionTabs, true);
    }

    if (launchParams.ContainsKey("functiontabs"))
    {
      string[] tabs = launchParams["functiontabs"].ToLower().Split(',');
      FunctionTab newTabs = FunctionTab.None;

      foreach (string tab in tabs)
      {
        FunctionTab functionTab = FunctionTab.None;

        try
        {
          functionTab = (FunctionTab)Enum.Parse(typeof(FunctionTab), tab, true);
        }
        catch
        {
          ShowError("Invalid function tab '" + tab + "', must be either " + EnumHelper.ToChoiceString(typeof(FunctionTab)));
        }

        if (functionTab == FunctionTab.All && _appState.FunctionTabs != FunctionTab.All)
        {
          ShowError("Use of all function tabs is not allowed in this application");
        }

        if (functionTab != FunctionTab.None && (functionTab & _appState.FunctionTabs) == FunctionTab.None)
        {
          ShowError("Function tab '" + tab + "', not allowed in this application");
        }

        newTabs |= functionTab;
      }

      _appState.FunctionTabs = newTabs;
    }

    // === active function tab ===

    if (launchParams.ContainsKey("activefunctiontab"))
    {
      string tab = launchParams["activefunctiontab"];
      FunctionTab functionTab = FunctionTab.None;

      try
      {
        functionTab = (FunctionTab)Enum.Parse(typeof(FunctionTab), tab, true);
      }
      catch
      {
        ShowError("Invalid active function tab '" + tab + "', must be either " + EnumHelper.ToChoiceString(typeof(FunctionTab)));
      }

      if (functionTab != FunctionTab.None && (functionTab & _appState.FunctionTabs) == FunctionTab.None)
      {
        ShowError("Function tab '" + tab + "' cannot be activated because is not present in this application");
      }

      _appState.ActiveFunctionTab = functionTab;
    }

    // === markup category ===

    Configuration.ApplicationMarkupCategoryRow markupCategory = null;

    if (launchParams.ContainsKey("markupcategory"))
    {
      string filter = String.Format("ApplicationID = '{0}' and CategoryID = '{1}'", application.ApplicationID, launchParams["markupcategory"]);
      DataRow[] rows = _config.ApplicationMarkupCategory.Select(filter);

      if (rows.Length > 0)
      {
        markupCategory = (Configuration.ApplicationMarkupCategoryRow)rows[0];
        _appState.MarkupCategory = markupCategory.CategoryID;
      }
      else
      {
        ShowError("Markup category '" + launchParams["markupcategory"] + "' is not available in application '" + application.ApplicationID + "'");
      }
    }
    else
    {
      Configuration.ApplicationMarkupCategoryRow[] markupCategories = application.GetApplicationMarkupCategoryRows();

      if (markupCategories.Length > 0)
      {
        markupCategory = markupCategories[0];
        _appState.MarkupCategory = markupCategories[0].CategoryID;
      }
    }

    // === markup groups ===

    if (launchParams.ContainsKey("markupgroup") || launchParams.ContainsKey("markupgroups"))
    {
      List<String> markupGroups = new List<String>(launchParams.ContainsKey("markupgroups") ? launchParams["markupgroups"].Split(',') : new string[] { launchParams["markupgroup"] });

      using (OleDbConnection connection = AppContext.GetDatabaseConnection())
      {
        foreach (string markupGroup in markupGroups)
        {
          int groupId = 0;
          Int32.TryParse(markupGroup, out groupId);

          if (groupId < 1)
          {
            ShowError("Invalid markup group ID specified");
          }

          if (markupCategory == null)
          {
            ShowError("Cannot show the specified markup group; the application does not contain any markup categories");
          }

          string sql = String.Format("select CategoryID from {0}MarkupGroup where GroupID = {1}",
              AppSettings.ConfigurationTablePrefix, groupId);
          string categoryID = null;

          using (OleDbCommand command = new OleDbCommand(sql, connection))
          {
            categoryID = command.ExecuteScalar() as String;
          }

          if (categoryID != markupCategory.CategoryID)
          {
            ShowError(String.Format("Markup group {0} is not a member of markup category '{1}'", markupGroup, markupCategory.CategoryID));
          }
        }

        _appState.MarkupGroups = new StringCollection(markupGroups);
        _appState.Extent = MarkupManager.GetExtent(_appState.MarkupGroups.Cast<String>().Select(o => Convert.ToInt32(o)).ToArray());
      }
    }

    // === zone ===

    if (launchParams.ContainsKey("zone"))
    {
      if (launchParams.ContainsKey("extent"))
      {
        ShowError("When providing a zone, an extent is not allowed");
      }

      if (launchParams.ContainsKey("centerx"))
      {
        ShowError("When providing a zone, a center X is not allowed");
      }

      if (launchParams.ContainsKey("centery"))
      {
        ShowError("When providing a zone, a center Y is not allowed");
      }

      if (launchParams.ContainsKey("centerlat"))
      {
        ShowError("When providing a zone, a center latitude is not allowed");
      }

      if (launchParams.ContainsKey("centerlon"))
      {
        ShowError("When providing a zone, a center longitude is not allowed");
      }

      Configuration.ZoneRow[] zones = zoneLevel != null ? zoneLevel.GetZoneRows() : new Configuration.ZoneRow[0];

      if (zones.Length == 0)
      {
        ShowError("A zone was specified but zones have not been configured for this application");
      }
      else if (!zones.Any(o => o.ZoneID == launchParams["zone"]))
      {
        ShowError(String.Format("Invalid zone '{0}' specified", launchParams["zone"]));
      }

      _appState.Extent = mapTab.GetZoneExtent(launchParams["zone"]);

      if (_appState.Extent.IsNull)
      {
        ShowError("Could not find the specified zone");
      }
      else
      {
        _appState.Extent.ScaleBy(1.2);
      }
    }

    // === extent ===

    if (launchParams.ContainsKey("extent"))
    {
      if (launchParams.ContainsKey("mapscale"))
      {
        ShowError("When providing an extent, a map scale is not allowed");
      }

      if (launchParams.ContainsKey("zoomlevel"))
      {
        ShowError("When providing an extent, a zoom level is not allowed");
      }

      if (launchParams.ContainsKey("centerx"))
      {
        ShowError("When providing an extent, a center X is not allowed");
      }

      if (launchParams.ContainsKey("centery"))
      {
        ShowError("When providing an extent, a center Y is not allowed");
      }

      if (launchParams.ContainsKey("centerlat"))
      {
        ShowError("When providing an extent, a center latitude is not allowed");
      }

      if (launchParams.ContainsKey("centerlon"))
      {
        ShowError("When providing an extent, a center longitude is not allowed");
      }

      if (launchParams.ContainsKey("scaleby"))
      {
        ShowError("When providing an extent, 'scale by' is not allowed");
      }

      try
      {
        string[] ext = launchParams["extent"].Split(',');

        double xmin = Convert.ToDouble(ext[0]);
        double ymin = Convert.ToDouble(ext[1]);
        double xmax = Convert.ToDouble(ext[2]);
        double ymax = Convert.ToDouble(ext[3]);

        _appState.Extent = new Envelope(new Coordinate(xmin, ymin),  new Coordinate(xmax, ymax));
      }
      catch
      {
        ShowError("Invalid extent specified");
      }
    }

    // === mapscale ===

    if (launchParams.ContainsKey("mapscale"))
    {
      if (launchParams.ContainsKey("zoomlevel"))
      {
        ShowError("When providing a map scale, a zoom level is not allowed");
      }

      if (launchParams.ContainsKey("scaleby"))
      {
        ShowError("When providing a map scale, 'scale by' is not allowed");
      }

      try
      {
        double mapScale = Convert.ToDouble(launchParams["mapscale"]);

        if (mapScale <= 0)
        {
          throw new Exception();
        }
      }
      catch
      {
        ShowError("Invalid map scale specified");
      }

      // NOTE:  The map scale is passed to the viewer as a JavaScript variable, and not through AppState,
      // because it depends to the size of the map control.  It is passed to directly to the printable map
      // via AppState below.
    }

    // === zoomlevel ===

    if (launchParams.ContainsKey("zoomlevel"))
    {
      if (launchParams.ContainsKey("scaleby"))
      {
        ShowError("When providing a zoom level, 'scale by' is not allowed");
      }

      double level = 1;

      try
      {
        level = Convert.ToDouble(launchParams["zoomlevel"]);
      }
      catch
      {
        ShowError("Invalid zoom level specified");
      }

      Envelope extent = application.GetFullExtentEnvelope();
      extent.Translate(_appState.Extent.Centre.X - extent.Centre.X, _appState.Extent.Centre.Y - extent.Centre.Y);
      extent.ScaleBy(1 / Math.Pow(1.414213562373095, level - 1));
      _appState.Extent = extent;
    }

    // === centerx ===

    if (launchParams.ContainsKey("centerx"))
    {
      if (launchParams.ContainsKey("scaleby"))
      {
        ShowError("When providing center X, 'scale by' is not allowed");
      }

      if (launchParams.ContainsKey("centerlat"))
      {
        ShowError("When providing center X, a center latitude is not allowed");
      }

      if (launchParams.ContainsKey("centerlon"))
      {
        ShowError("When providing center X, a center longitude is not allowed");
      }

      double x = 0;

      try
      {
        x = Convert.ToDouble(launchParams["centerx"]);
      }
      catch
      {
        ShowError("Invalid center X specified");
      }

      double dx = _appState.Extent.Width / 2;
      _appState.Extent = new Envelope( new Coordinate(x - dx, _appState.Extent.MinY),  new Coordinate(x + dx, _appState.Extent.MaxY));
    }

    // === centery ===

    if (launchParams.ContainsKey("centery"))
    {
      if (launchParams.ContainsKey("scaleby"))
      {
        ShowError("When providing center Y, 'scale by' is not allowed");
      }

      if (launchParams.ContainsKey("centerlat"))
      {
        ShowError("When providing center Y, a center latitude is not allowed");
      }

      if (launchParams.ContainsKey("centerlon"))
      {
        ShowError("When providing center Y, a center longitude is not allowed");
      }

      double y = 0;

      try
      {
        y = Convert.ToDouble(launchParams["centery"]);
      }
      catch
      {
        ShowError("Invalid center Y specified");
      }

      double dy = _appState.Extent.Height / 2;
      _appState.Extent = new Envelope( new Coordinate(_appState.Extent.MinX, y - dy),  new Coordinate(_appState.Extent.MaxX, y + dy));
    }

    // === centerlat ===

    if (launchParams.ContainsKey("centerlat") || launchParams.ContainsKey("centerlat"))
    {
      if (!launchParams.ContainsKey("centerlon"))
      {
        ShowError("When providing center latitude, a center longitude must also be provided");
      }

      if (!launchParams.ContainsKey("centerlat"))
      {
        ShowError("When providing center longitude, a center latitude must also be provided");
      }

      if (launchParams.ContainsKey("scaleby"))
      {
        ShowError("When providing center latitude/longitude, 'scale by' is not allowed");
      }

      double lat = 0;
      double lon = 0;

      try
      {
        lat = Convert.ToDouble(launchParams["centerlat"]);
      }
      catch
      {
        ShowError("Invalid center latitude specified");
      }

      try
      {
        lon = Convert.ToDouble(launchParams["centerlon"]);
      }
      catch
      {
        ShowError("Invalid center longitude specified");
      }

      double x;
      double y;

      AppSettings.CoordinateSystem.ToProjected(lon, lat, out x, out y);

      if (AppSettings.MapUnits == "feet")
      {
        x *= Constants.FeetPerMeter;
        y *= Constants.FeetPerMeter;
      }

      double dx = _appState.Extent.Width / 2;
      double dy = _appState.Extent.Height / 2;

      _appState.Extent = new Envelope( new Coordinate(x - dx, y - dy),  new Coordinate(x + dx, y + dy));
    }

    // === scaleby ===

    if (launchParams.ContainsKey("scaleby"))
    {
      if (_appState.TargetIds.Count == 0 && _appState.SelectionIds.Count == 0 && _appState.MarkupGroups.Count == 0 && !launchParams.ContainsKey("zone"))
      {
        ShowError("Target IDs, selection IDs, a markup group or a zone must be provided when 'scale by' is specified");
      }

      double scaleBy = Double.NaN;

      try
      {
        scaleBy = Convert.ToDouble(launchParams["scaleby"]);
      }
      catch { }

      if (scaleBy == Double.NaN || scaleBy <= 0)
      {
        ShowError("Invalid 'scale by' value specified, must be greater than zero");
      }

      _appState.Extent.ScaleBy(scaleBy / 1.2);
    }

    // === tool ==

    if (launchParams.ContainsKey("tool") && Page.FindControl("opt" + launchParams["tool"], false) == null)
    {
      ShowError("Unknown tool specified");
    }

    if (launchParams.ContainsKey("markcenter"))
    {
      string label = launchParams["markcenter"];
      
      Coordinate center = _appState.Extent.Centre;
      string point = String.Format("POINT({0} {1})", center.X, center.Y);
      Markup markup = new Markup(point, "#000000", 1);

      if (label != "1")
      {
        markup.Text = label;
      }

      _appState.Markup.Add(markup);
    }

    // === printtemplate and printtitle ===

    string templateID = null;
    string title = "";

    if (launchParams.ContainsKey("printtemplate"))
    {
      templateID = launchParams["printtemplate"];
    }

    if (launchParams.ContainsKey("printtitle"))
    {
      title = launchParams["printtitle"];
    }

    if (!String.IsNullOrEmpty(title) && templateID == null)
    {
      ShowError("When providing a print title, a print template must also be specified");
    }

    if (templateID != null)
    {
      Configuration.PrintTemplateRow printTemplate = _config.PrintTemplate.FindByTemplateID(templateID);

      // the PrintTemplate must exist

      if (printTemplate == null)
      {
        ShowError("Print template '" + templateID + "' does not exist");
      }

      if (!(!printTemplate.IsAlwaysAvailableNull() && printTemplate.AlwaysAvailable == 1))
      {
        string filter = "ApplicationID = '" + application.ApplicationID + "' and TemplateID = '" + templateID + "'";

        // the Application must contain the PrintTemplate

        if (_config.ApplicationPrintTemplate.Select(filter).Length == 0)
        {
          ShowError("Application '" + application.ApplicationID + "' does not contain print template '" + templateID + "'");
        }
      }

      // set the map scale if specified (a 1 inch [96 pixel] square window is assumed)

      if (launchParams.ContainsKey("mapscale"))
      {
        _appState.Extent.ScaleBy(Convert.ToDouble(launchParams["mapscale"]) / _appState.Extent.Width);
      }

      PdfMap pdfMap = new PdfMap(_appState, templateID, new List<String>(new string[] { title }), PreserveMode.Scale, 96);
      pdfMap.Write(Response);
      Response.End();
    }
  }
Example #34
0
        /// <summary>
        /// Visit Markup
        /// </summary>
        /// <param name="markup">Markup to check</param>
        public override void Visit(Markup markup)
        {
            //Check identifier in designator, it should be an XHTML or an user defined function
            String identifier = markup.GetDesignator().GetIdentifier();

            if(SymbolTable.ContainsFunction(identifier))
            {
                //Check arguments
                FunctionDefinition referencedDefinition = SymbolTable.GetFunctionDefinition(identifier);

                if(referencedDefinition.GetFormals().Count != markup.GetArguments().Count)
                {   //Arity mismatch
                    ExceptionList.Add(new FunctionCallArityIncorrect(identifier));
                }
            }
            else
            {
                //Check if it is XHTML, if not its undefined
                if (!IdentifierIsXHTML(identifier) && markup.GetCallState())
                {
                    ExceptionList.Add(new UndefinedFunction(identifier));
                }
            }
        }
Example #35
0
        /// <summary>
        /// Parser for markup
        /// </summary>
        /// <returns>Parsed markup</returns>
        public Markup ParseMarkup()
        {
            //First parse mandatory designator
            Markup markup = new Markup();
            markup.SetDesignator(ParseDesignator());

            //Determine if arguments are after designator
            if (TokenStream.Peek(1).GetType() == TokenType.SYMBOL && TokenStream.Peek(1).GetValue().ToString() == "(")
            {
                //We are dealing with an MarkupCall, so set Markup as Call
                markup.SetCall();
                ParseArguments(markup);
            }

            return markup;
        }
Example #36
0
 public void AddMarkup(Markup.Markup markup)
 {
     MarkupList.Add(markup);
 }
        private void SetAnnotationDefaultProperties(Markup markup)
        {
            var adph = AnnotationDefaultPropertyHelper.Instance;

            Color? fillColor, strokeColor;
            double? strokeThickness;

            if ((fillColor = adph.GetDefaultFillColor(markup.GetType())) != null)
            {
                markup.FillColor = (Color)fillColor;

                //Opacity for highlight
                if (markup as TextHighlight != null)
                {
                    Color c = markup.FillColor;
                    c.A = (byte)Math.Min((byte)0x44, markup.FillColor.A);
                    markup.FillColor = c;
                }
            }
            else { markup.FillColor = Colors.Transparent; }

            if ((strokeColor = adph.GetDefaultStrokeColor(markup.GetType())) != null)
            {
                markup.StrokeColor = (Color)strokeColor;
            }
            else { markup.StrokeColor = Colors.Transparent; }

            if ((strokeThickness = adph.GetDefaultStrokeThickness(markup.GetType())) != null)
            {
                markup.StrokeThickness = (double)strokeThickness;
            }else { markup.StrokeThickness = 0; }
        }
        private void SetAndBindProperties(Markup markup)
        {
            // Bind/Unbind
            if (markup == null)
            {
                this.ShowFillColor = false;
                this.ShowStrokeColor = false;
                this.ShowStrokeThickness = false;

                this.fillColorColorPicker.ClearValue(Controls.ColorPicker.ValueProperty);
                this.strokeColorColorPicker.ClearValue(Controls.ColorPicker.ValueProperty);
                this.strokeThicknessSlider.ClearValue(Slider.ValueProperty);
            }
            else
            {
                Binding b;

                //Fill Color
                b = new Binding();
                b.Source = markup;
                b.Path = new PropertyPath("FillColor");
                b.Mode = BindingMode.TwoWay;

                //Add opacity if markup is highlight
                if (markup as TextHighlight != null)
                {
                    b.Converter = new Utility.ColorAlphaConverter();
                    b.ConverterParameter = (byte)0x44;
                }

                this.fillColorColorPicker.SetBinding(Controls.ColorPicker.ValueProperty, b);

                //Stroke Color
                b = new Binding();
                b.Source = markup;
                b.Path = new PropertyPath("StrokeColor");
                b.Mode = BindingMode.TwoWay;
                this.strokeColorColorPicker.SetBinding(Controls.ColorPicker.ValueProperty, b);

                //Stroke Thickness
                b = new Binding();
                b.Source = markup;
                b.Path = new PropertyPath("StrokeThickness");
                b.Mode = BindingMode.TwoWay;
                this.strokeThicknessSlider.SetBinding(Slider.ValueProperty, b);

                var adhp = AnnotationDefaultPropertyHelper.Instance;
                this.ShowFillColor = (adhp.GetDefaultFillColor(markup.GetType()) != null);
                this.ShowStrokeColor = (adhp.GetDefaultStrokeColor(markup.GetType()) != null);
                this.ShowStrokeThickness = (adhp.GetDefaultStrokeThickness(markup.GetType()) != null);
            }
        }
Example #39
0
    private Markup GetTowerPoint(RaycastHit hit, out Markup m)
    {
        Markup main;

        m = null;
        for(int a =0; a < hit.collider.transform.childCount; a++){
            Transform child = hit.collider.transform.GetChild(a);
            if(child.name == "TowerMarkup"){
                main = child.GetComponent<Markup>();
                if(main.available){
                    return main;
                }
                else{
                    main = null;
                }
            }
            else if(child.name == "DepthMarkup"){
                m = child.GetComponent<Markup>();
                if(m.available){
                    m.available = false;
                }
                else{
                    m = null;
                }
            }
        }
        return null;
    }
 internal static string GetString(Markup.StringResources id)
 {
     return ((string)(Microsoft.SPOT.ResourceUtility.GetObject(ResourceManager, id)));
 }
Example #41
0
 public Stone(Color thisColor, Markup thisMarkup, string text)
 {
     Color      = thisColor;
     Annotation = thisMarkup;
     MarkupText = text;
 }
Example #42
0
        /// <summary>
        /// Add Issue
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isBcf"></param>
        /// <returns></returns>
        private Tuple <Markup, Issue> AddIssue(string path, bool isBcf)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                if (!(uidoc.ActiveView is View3D || uidoc.ActiveView is ViewSheet || uidoc.ActiveView is ViewPlan || uidoc.ActiveView is ViewSection || uidoc.ActiveView is ViewDrafting))
                {
                    MessageBox.Show("I'm sorry,\nonly 3D and 2D views are supported.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                    return(null);
                }

                Markup issue = new Markup(DateTime.Now);

                string folderIssue = Path.Combine(path, issue.Topic.Guid);
                if (!Directory.Exists(folderIssue))
                {
                    Directory.CreateDirectory(folderIssue);
                }

                var types      = new ObservableCollection <Issuetype>();
                var assignees  = new List <User>();
                var components = new ObservableCollection <IssueTracker.Classes.Component>();
                var priorities = new ObservableCollection <Priority>();
                var noCom      = true;
                var noPrior    = true;
                var noAssign   = true;

                if (!isBcf)
                {
                    types      = mainPan.jira.TypesCollection;
                    assignees  = mainPan.getAssigneesIssue();
                    components = mainPan.jira.ComponentsCollection;
                    priorities = mainPan.jira.PrioritiesCollection;
                    noCom      =
                        mainPan.jira.ProjectsCollection[mainPan.jiraPan.projIndex].issuetypes[0].fields.components ==
                        null;
                    noPrior =
                        mainPan.jira.ProjectsCollection[mainPan.jiraPan.projIndex].issuetypes[0].fields.priority ==
                        null;
                    noAssign =
                        mainPan.jira.ProjectsCollection[mainPan.jiraPan.projIndex].issuetypes[0].fields.assignee ==
                        null;
                }

                AddIssueRevit air = new AddIssueRevit(uidoc, folderIssue, types, assignees, components, priorities, noCom, noPrior, noAssign);
                air.Title = "Add Jira Issue";
                if (!isBcf)
                {
                    air.JiraFieldsBox.Visibility = System.Windows.Visibility.Visible;
                    air.VerbalStatus.Visibility  = System.Windows.Visibility.Collapsed;
                    air.BcfFieldsBox.Visibility  = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    air.JiraFieldsBox.Visibility = System.Windows.Visibility.Collapsed;
                    air.BcfFieldsBox.Visibility  = System.Windows.Visibility.Visible;
                }

                air.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                air.ShowDialog();
                if (air.DialogResult.HasValue && air.DialogResult.Value)
                {
                    ViewPoint vp = new ViewPoint(true);
                    vp.SnapshotPath = Path.Combine(folderIssue, "snapshot.png");
                    int elemCheck = 2;
                    if (air.all.IsChecked.Value)
                    {
                        elemCheck = 0;
                    }
                    else if (air.selected.IsChecked.Value)
                    {
                        elemCheck = 1;
                    }
                    vp.VisInfo = generateViewpoint(elemCheck);

                    //Add annotations for description with snapshot/viewpoint
                    StringBuilder descriptionText = new StringBuilder();
                    if (!string.IsNullOrWhiteSpace(air.CommentBox.Text))
                    {
                        descriptionText.AppendLine(air.CommentBox.Text);
                    }
                    if (!isBcf)
                    {
                        if (vp.VisInfo != null)
                        {
                            descriptionText.AppendLine(string.Format("<Viewpoint>[^{0}]</Viewpoint>", "viewpoint.bcfv"));
                        }
                        if (!string.IsNullOrWhiteSpace(vp.SnapshotPath))
                        {
                            descriptionText.AppendLine(string.Format("<Snapshot>[^{0}]</Snapshot>", "snapshot.png"));
                            descriptionText.AppendLine(string.Format("!{0}|width=200!", "snapshot.png"));
                        }
                    }

                    Issue issueJira = new Issue();
                    if (!isBcf)
                    {
                        issueJira.fields             = new Fields();
                        issueJira.fields.description = descriptionText.ToString().Trim();
                        issueJira.fields.issuetype   = (Issuetype)air.issueTypeCombo.SelectedItem;
                        issueJira.fields.priority    = (Priority)air.priorityCombo.SelectedItem;
                        if (!string.IsNullOrEmpty(air.ChangeAssign.Content.ToString()) &&
                            air.ChangeAssign.Content.ToString() != "none")
                        {
                            issueJira.fields.assignee      = new User();
                            issueJira.fields.assignee.name = air.ChangeAssign.Content.ToString();
                        }

                        if (air.SelectedComponents != null && air.SelectedComponents.Any())
                        {
                            issueJira.fields.components = air.SelectedComponents;
                        }
                    }

                    issue.Viewpoints.Add(vp);
                    issue.Topic.Title          = air.TitleBox.Text;
                    issue.Topic.Description    = descriptionText.ToString().Trim();
                    issue.Topic.AssignedTo     = air.BcfAssignee.Text;
                    issue.Topic.CreationAuthor = MySettings.Get("username");
                    issue.Topic.Priority       = air.BcfPriority.Text;
                    issue.Topic.TopicStatus    = air.VerbalStatus.Text;
                    issue.Topic.TopicType      = air.BcfIssueType.Text;

                    issue.Header[0].IfcProject = ExporterIFCUtils.CreateProjectLevelGUID(doc,
                                                                                         Autodesk.Revit.DB.IFC.IFCProjectLevelGUIDType.Project);
                    string projFilename = (doc.PathName != null && doc.PathName != "")
                  ? System.IO.Path.GetFileName(doc.PathName)
                  : "";
                    issue.Header[0].Filename = projFilename;
                    issue.Header[0].Date     = DateTime.Now;

                    return(new Tuple <Markup, Issue>(issue, issueJira));
                }
                else
                {
                    mainPan.DeleteDirectory(folderIssue);
                }
            }

            catch (System.Exception ex1)
            {
                MessageBox.Show("exception: " + ex1);
            }
            return(null);
        }
        /// <summary>
        /// New method contributed by Lubos Strapko
        /// @since 2.1.3
        /// </summary>
        /// <param name="h"></param>
        /// <param name="cprops"></param>
        public static void InsertStyle(Hashtable h, ChainedProperties cprops)
        {
            var style = (string)h["style"];

            if (style == null)
            {
                return;
            }

            var prop = Markup.ParseAttributes(style);

            foreach (string key in prop.Keys)
            {
                if (key.Equals(Markup.CSS_KEY_FONTFAMILY))
                {
                    h["face"] = prop[key];
                }
                else if (key.Equals(Markup.CSS_KEY_FONTSIZE))
                {
                    var actualFontSize = Markup.ParseLength(cprops[ElementTags.SIZE], Markup.DEFAULT_FONT_SIZE);
                    if (actualFontSize <= 0f)
                    {
                        actualFontSize = Markup.DEFAULT_FONT_SIZE;
                    }

                    h[ElementTags.SIZE] = Markup.ParseLength(prop[key], actualFontSize).ToString(NumberFormatInfo.InvariantInfo) + "pt";
                }
                else if (key.Equals(Markup.CSS_KEY_FONTSTYLE))
                {
                    var ss = prop[key].Trim().ToLowerInvariant();
                    if (ss.Equals("italic") || ss.Equals("oblique"))
                    {
                        h["i"] = null;
                    }
                }
                else if (key.Equals(Markup.CSS_KEY_FONTWEIGHT))
                {
                    var ss = prop[key].Trim().ToLowerInvariant();
                    if (ss.Equals("bold") || ss.Equals("700") || ss.Equals("800") || ss.Equals("900"))
                    {
                        h["b"] = null;
                    }
                }
                else if (key.Equals(Markup.CSS_KEY_TEXTDECORATION))
                {
                    var ss = prop[key].Trim().ToLowerInvariant();
                    if (ss.Equals(Markup.CSS_VALUE_UNDERLINE))
                    {
                        h["u"] = null;
                    }
                }
                else if (key.Equals(Markup.CSS_KEY_COLOR))
                {
                    var c = Markup.DecodeColor(prop[key]);
                    if (c != null)
                    {
                        var hh = c.ToArgb() & 0xffffff;
                        var hs = "#" + hh.ToString("X06", NumberFormatInfo.InvariantInfo);
                        h["color"] = hs;
                    }
                }
                else if (key.Equals(Markup.CSS_KEY_LINEHEIGHT))
                {
                    var ss             = prop[key].Trim();
                    var actualFontSize = Markup.ParseLength(cprops[ElementTags.SIZE], Markup.DEFAULT_FONT_SIZE);
                    if (actualFontSize <= 0f)
                    {
                        actualFontSize = Markup.DEFAULT_FONT_SIZE;
                    }

                    var v = Markup.ParseLength(prop[key], actualFontSize);
                    if (ss.EndsWith("%"))
                    {
                        v           /= 100;
                        h["leading"] = "0," + v.ToString(NumberFormatInfo.InvariantInfo);
                    }
                    else if (Util.EqualsIgnoreCase("normal", ss))
                    {
                        h["leading"] = "0,1.5";
                    }
                    else
                    {
                        h["leading"] = v.ToString(NumberFormatInfo.InvariantInfo) + ",0";
                    }
                }
                else if (key.Equals(Markup.CSS_KEY_TEXTALIGN))
                {
                    var ss = prop[key].Trim().ToLowerInvariant();
                    h["align"] = ss;
                }
                else if (key.Equals(Markup.CSS_KEY_PADDINGLEFT))
                {
                    var ss = prop[key].Trim().ToLowerInvariant();
                    h["indent"] = ss;
                }
            }
        }
Example #44
0
 public Stone(Color thisColor, Markup thisMarkup)
 {
     Color      = thisColor;
     Annotation = thisMarkup;
 }
Example #45
0
        public void ParseNoArgumentsTest()
        {
            //Parse tokens
            MarkupParser markupParser = new MarkupParser(Init("()"));
            Markup markup = new Markup();
            markupParser.ParseArguments(markup);

            //Test arguments
            Assert.AreEqual(0, markup.GetArguments().Count);
        }
Example #46
0
        /// <summary>
        /// Parser for Embed
        /// </summary>
        /// <returns>Parsed Embed</returns>
        public Embed ParseEmbed()
        {
            Embed    embed      = null;
            NodeList markupList = new NodeList();

            //Set up MarkupParser
            markupParser = new MarkupParser(EmbeddingTokenStream);

            //Parse Markup*
            //EmbeddingTokenStream.HasNext(2) && !(EmbeddingTokenStream.Peek(2).GetValue().ToString() == ">"
            while (NextTokenIsMarkup())
            {
                markupList.Add(markupParser.ParseMarkup());
            }

            //Check if an expression is remaining, otherwise embed is MarkupEmbedding
            if (IsExpressionRemaining())
            {   //ExpressionEmbedding
                ExpressionEmbed expressionEmbed = new ExpressionEmbed();

                //Add already parsed markups to expressionEmbed
                expressionEmbed.SetMarkups(markupList);

                //Set up expressionparser
                expressionParser = new ExpressionParser(EmbeddingTokenStream);

                //Parse expression
                expressionEmbed.SetExpression(expressionParser.ParseExpression());

                embed = expressionEmbed;
            }
            else
            {   //MarkupEmbedding
                //Get last item from markupList and add it as Markup
                if (markupList.Count != 0)
                {
                    Markup markup = (Markup)markupList.Get(markupList.Count - 1);
                    markupList.Remove(markupList.Count - 1);

                    MarkupEmbed markupEmbed = new MarkupEmbed();
                    markupEmbed.SetMarkups(markupList);
                    markupEmbed.SetMarkup(markup);

                    embed = markupEmbed;
                }
                else
                {   //Markup* Markup must contain at least one markup element
                    throw new UnexpectedToken("Markup expected, but found:", CurrentToken.GetValue().ToString(), CurrentToken.GetLine());
                }
            }

            /*//Determine if remaining embed is Markup or Expression
             * if (NextTokenIsMarkup())
             * {   //MarkupEmbedding
             *  MarkupEmbed markupEmbed = new MarkupEmbed();
             *
             *  //Add already parsed markups to markupEmbed
             *  markupEmbed.SetMarkups(markupList);
             *
             *  //Parse latest markup
             *  markupEmbed.SetMarkup(markupParser.ParseMarkup());
             *
             *  embed = markupEmbed;
             * }
             * else
             * {   //ExpressionEmbedding
             *  ExpressionEmbed expressionEmbed = new ExpressionEmbed();
             *
             *  //Add already parsed markups to expressionEmbed
             *  expressionEmbed.SetMarkups(markupList);
             *
             *  //Set up expressionparser
             *  expressionParser = new ExpressionParser(EmbeddingTokenStream);
             *
             *  //Parse expression
             *  expressionEmbed.SetExpression(expressionParser.ParseExpression());
             *
             *  embed = expressionEmbed;
             * }           */

            return(embed);
        }
Example #47
0
  private void DrawMarkup(Graphics graphics)
  {
    if (_appState.Markup.Count == 0 && _appState.MarkupGroups.Count == 0)
    {
      return;
    }

    List<Markup> markupList = new List<Markup>();

    if (_appState.MarkupGroups.Count > 0)
    {
      using (OleDbConnection connection = AppContext.GetDatabaseConnection())
      {
        foreach (string groupId in _appState.MarkupGroups)
        {
          string sql = String.Format("update {0}MarkupGroup set DateLastAccessed = ? where GroupID = {1}",
              AppSettings.ConfigurationTablePrefix, groupId);

          using (OleDbCommand command = new OleDbCommand(sql, connection))
          {
            command.Parameters.Add("@1", OleDbType.Date).Value = DateTime.Now;
            command.ExecuteNonQuery();
          }

          sql = String.Format("select Shape, Color, Glow, Text, Measured from {0}Markup where GroupID = {1} and Deleted = 0",
              AppSettings.ConfigurationTablePrefix, groupId);

          using (OleDbCommand command = new OleDbCommand(sql, connection))
          {
            using (OleDbDataReader reader = command.ExecuteReader())
            {
              while (reader.Read())
              {
                Markup markup = new Markup();

                markup.Shape = reader.GetString(0);
                markup.Color = reader.GetString(1);
                markup.Glow = !reader.IsDBNull(2) ? reader.GetString(2) : null;
                markup.Text = !reader.IsDBNull(3) ? reader.GetString(3) : null;
                markup.Measured = !reader.IsDBNull(4) ? (int?)reader.GetInt32(4) : null;

                markupList.Add(markup);
              }
            }
          }
        }
      }
    }

    if (_appState.Markup.Count > 0)
    {
      markupList.AddRange(_appState.Markup);
    }

    SolidBrush pointBrush = new SolidBrush(Color.Red);
    SolidBrush polygonBrush = new SolidBrush(Color.FromArgb(128, 255, 192, 192));
    Pen pen = new Pen(Color.Red, Convert.ToSingle(2 * _resolution));
    pen.EndCap = System.Drawing.Drawing2D.LineCap.Square;
    pen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;

    float dotSize = Convert.ToSingle(10 * _resolution);

    System.Drawing.Font font = AppSettings.MarkupFont;
    font = new System.Drawing.Font(font.FontFamily, Convert.ToSingle(font.Size * _resolution), font.Style, font.Unit);
    System.Drawing.Font coordinatesFont = AppSettings.CoordinatesFont;
    coordinatesFont = new System.Drawing.Font(coordinatesFont.FontFamily, Convert.ToSingle(coordinatesFont.Size * _resolution), coordinatesFont.Style, coordinatesFont.Unit);
    SolidBrush textBrush = new SolidBrush(Color.FromArgb(192, 0, 0));
    SolidBrush glowBrush = new SolidBrush(Color.Black);

    StringFormat format = new StringFormat();
    format.LineAlignment = StringAlignment.Far;

    Configuration config = AppContext.GetConfiguration();
    Configuration.ApplicationRow application = config.Application.FindByApplicationID(_appState.Application);
    string[] modes = application.IsCoordinateModesNull() ? new string[] { "ne" } : application.CoordinateModes.ToLower().Split(',');
    
    WKTReader wktReader = new WKTReader();

    foreach (Markup markup in markupList)
    {
      IGeometry geometry = wktReader.Read(markup.Shape);
      Color color = ColorTranslator.FromHtml(markup.Color);
      bool isMeasured = markup.Measured.HasValue && markup.Measured == 1;
      bool isGlow = !String.IsNullOrEmpty(markup.Glow);

      if (isGlow)
      {
        glowBrush.Color = ColorTranslator.FromHtml(markup.Glow);
      }

      switch (geometry.OgcGeometryType)
      {
        case OgcGeometryType.Point:
          bool isText = !String.IsNullOrEmpty(markup.Text);

          if (isText)
          {
            textBrush.Color = color;
            DrawText(graphics, (IPoint)geometry, markup.Text, font, textBrush, isGlow ? glowBrush : null, 0, 0, format);

            if (isMeasured)
            {
              pen.Color = color;
              pen.EndCap = System.Drawing.Drawing2D.LineCap.Flat;
              DrawCross(graphics, (IPoint)geometry, pen, 10);
            }
          }
          else
          {
            if (isMeasured)
            {
              pen.Color = color;
              pen.EndCap = System.Drawing.Drawing2D.LineCap.Flat;
              textBrush.Color = color;
              DrawCoordinate(graphics, (IPoint)geometry, modes, pen, coordinatesFont, textBrush, isGlow ? glowBrush : null, format);
            }
            else
            {
              pointBrush.Color = color;
              DrawPoint(graphics, (IPoint)geometry, pointBrush, dotSize);
            }
          }
          break;

        case OgcGeometryType.LineString:
          pen.Color = color;
          pen.EndCap = System.Drawing.Drawing2D.LineCap.Square;
          DrawLineString(graphics, (ILineString)geometry, pen);
          break;

        case OgcGeometryType.Polygon:
          pen.Color = color;
          pen.EndCap = System.Drawing.Drawing2D.LineCap.Square;
          polygonBrush.Color = Color.FromArgb(128, color);
          DrawPolygon(graphics, (IPolygon)geometry, polygonBrush, null, pen);
          break;
      }

      if (isMeasured && geometry.OgcGeometryType != OgcGeometryType.Point)
      {
        DrawMeasure(graphics, geometry);
      }
    }
  }
        public Font GetFont(ChainedProperties props)
        {
            var face = props[ElementTags.FACE];

            if (face != null)
            {
                var tok = new StringTokenizer(face, ",");
                while (tok.HasMoreTokens())
                {
                    face = tok.NextToken().Trim();
                    if (face.StartsWith("\""))
                    {
                        face = face.Substring(1);
                    }

                    if (face.EndsWith("\""))
                    {
                        face = face.Substring(0, face.Length - 1);
                    }

                    if (FontImp.IsRegistered(face))
                    {
                        break;
                    }
                }
            }
            var style = 0;

            if (props.HasProperty(HtmlTags.I))
            {
                style |= Font.ITALIC;
            }

            if (props.HasProperty(HtmlTags.B))
            {
                style |= Font.BOLD;
            }

            if (props.HasProperty(HtmlTags.U))
            {
                style |= Font.UNDERLINE;
            }

            if (props.HasProperty(HtmlTags.S))
            {
                style |= Font.STRIKETHRU;
            }

            var   value = props[ElementTags.SIZE];
            float size  = 12;

            if (value != null)
            {
                size = float.Parse(value, NumberFormatInfo.InvariantInfo);
            }

            var color    = Markup.DecodeColor(props["color"]);
            var encoding = props["encoding"];

            if (encoding == null)
            {
                encoding = BaseFont.WINANSI;
            }

            return(FontImp.GetFont(face, encoding, true, size, style, color));
        }
Example #49
0
 public virtual void Visit(Markup.Markup markup)
 {
     VisitSubNodes(markup);
 }