Example #1
0
		public DialogError(string message, Exception e, Window parent) : base("Error", parent, DialogFlags.Modal, Stock.Ok, ResponseType.Ok)
		{
			HBox hbox = new HBox();
			Image icon = new Image(Stock.DialogError,IconSize.Dialog);
			Label label = new Label(message);
			Expander exp = new Expander("Details");
			ScrolledWindow sw = new ScrolledWindow();
			TextView tview = new TextView();
			
			hbox.BorderWidth = 6;
			hbox.Spacing = 6;
			label.SetAlignment(0f, 0.5f);
			exp.BorderWidth = 6;
			tview.Buffer.Text = e.Message;
			tview.Buffer.Text += "\n";
			tview.Buffer.Text += e.StackTrace;
			
			sw.Add(tview);
			exp.Add(sw);
			hbox.PackStart(icon, false, false, 0);
			hbox.PackStart(label, true, true, 0);
			this.VBox.PackStart(hbox, false, false, 0);
			this.VBox.PackStart(exp, true, true, 0);
			this.ShowAll();
			
		}
		public Action (SecurityAction action)
		{
			this.action = action;
			this.TextView = new TextView ();
			this.TextView.Editable = false;
			this.Expander = new Expander (action.ToString ());
			this.Expander.Add (this.TextView);
		}
Example #3
0
File: Grid.cs Project: mono/stetic
 public void AppendGroup(string name, bool expanded)
 {
     Gtk.Expander exp = new Expander ("<b>" + name + "</b>");
     exp.UseMarkup = true;
     exp.Expanded = expanded;
     exp.AddNotification ("expanded", ExpansionChanged);
     Append (exp);
 }
Example #4
0
        public FaceSidebarWidget()
        {
            instance = this;

            mainVBox = new VBox();
            //mainVBox.Spacing = 6;
            //faceVBox = new VBox();
            faceVPane = new VPaned();

            pleaseSelectPictureLabel = new Label ();
            pleaseSelectPictureLabel.Markup = SelectImageMarkup;
            //headerLabel =  new Label (Catalog.GetString ("Not Implemented Yet"));
            mainVBox.PackStart(pleaseSelectPictureLabel,false,false,0);

            knownFaceExpander = new Expander("In this photo:");

            //faceVBox.PackStart(knownFaceExpander,true,true,0);
            //faceVPane.Add(knownFaceExpander);
            knownFaceScrolledWindow = new ScrolledWindow();
            knownFaceExpander.Add(knownFaceScrolledWindow);
            faceVPane.Pack1(knownFaceExpander,true,true);
            //knownFaceExpander.HeightRequest = 30;
            //			faceHandleBox = new HandleBox();
            //			faceHandleBox.HandlePosition = PositionType.Top;
            //			faceVBox.PackStart(faceHandleBox,false,false,0);

            unknownFaceExpander = new Expander("Who's also in this photo");
            //faceVBox.PackStart(unknownFaceExpander,true,true,0);
            //faceVPane.Add(unknownFaceExpander);

            unknownFaceScrolledWindow = new ScrolledWindow();
            unknownFaceExpander.Add(unknownFaceScrolledWindow);
            faceVPane.Pack2(unknownFaceExpander,true,true);
            //unknownFaceExpander.HeightRequest = 30;
            mainVBox.PackStart(faceVPane,true,true,0);

            detectFaceButton = new Button(Catalog.GetString("Re-Detect Face From This Picture"));
            mainVBox.PackEnd(detectFaceButton,false,false,0);
            detectFaceButton.Clicked += DetectFaceButtonClicked;

            addFaceButton = new Button(manualAddFaceString);
            mainVBox.PackEnd(addFaceButton,false,false,0);
            addFaceButton.Clicked += AddFaceButtonClicked;

            knownFaceScrolledWindow.Visible = false;
            unknownFaceScrolledWindow.Visible = false;

            knownFaceExpander.ResizeMode = ResizeMode.Parent;
            unknownFaceExpander.ResizeMode = ResizeMode.Parent;
            Log.Debug("HeightR");

            ShadowType = ShadowType.None;
            BorderWidth = 0;
            //AddWithViewport(pleaseSelectPictureLabel);
            AddWithViewport (mainVBox);
            //mainVBox.Visible = false;
            ShowAll();
        }
Example #5
0
        public void ExpandAllIntoTaskItems1()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            ObjectModelHelpers.AssertItemsMatch(@"foo", GetTaskArrayFromItemList(itemsOut));
        }
 public virtual void ExpanderAutomationPeerTypeAndClass()
 {
     Expander item = new Expander();
     ExpanderAutomationPeer peer = null;
     TestAsync(
         item,
         () => peer = FrameworkElementAutomationPeer.CreatePeerForElement(item) as ExpanderAutomationPeer,
         () => Assert.AreEqual(AutomationControlType.Group, peer.GetAutomationControlType(), "Unexpected AutomationControlType!"),
         () => Assert.AreEqual("Expander", peer.GetClassName(), "Unexpected ClassType!"));
 }
 public virtual void ExpanderCreatesAutomationPeer()
 {
     Expander item = new Expander();
     ExpanderAutomationPeer peer = null;
     TestAsync(
         item,
         () => peer = FrameworkElementAutomationPeer.CreatePeerForElement(item) as ExpanderAutomationPeer,
         () => Assert.IsNotNull(peer, "Expander peer should not be null!"),
         () => Assert.AreEqual(item, peer.Owner, "Expander should be owner of the peer!"));
 }
Example #8
0
        public DirPropertyWidget(FilePropertisData fpd)
        {
            project = fpd.Project;
            fiOld = project.FilesProperty.Find(x => x.SystemFilePath == fpd.Filename);
            if (fiOld == null){
                fiOld =new FileItem(fpd.Filename,false);
                fiOld.IsDirectory = true;
                project.FilesProperty.Add(fiOld);
            }
            if (fiOld.ConditionValues == null)
                fiOld.ConditionValues = new System.Collections.Generic.List<ConditionRule>();

            Table mainTable = new Table(2,1,false);
            Table propertyTable = new Table(5,2,false);

            Label lblFN =GetLabel(System.IO.Path.GetFileName(fiOld.SystemFilePath)); // new Label(System.IO.Path.GetFileName(fiOld.SystemFilePath));

            Entry entr = new Entry(fiOld.SystemFilePath);
            entr.IsEditable = false;

            Entry entrFullPath = new Entry(MainClass.Workspace.GetFullPath(fiOld.SystemFilePath));
            entrFullPath.IsEditable = false;

            Label lblPrj = GetLabel(project.ProjectName); //new Label(project.ProjectName);

            AddControl(ref propertyTable,0,lblFN,"Name ");
            AddControl(ref propertyTable,1,entr,"Relative Path ");
            AddControl(ref propertyTable,2,entrFullPath,"Full Path ");
            AddControl(ref propertyTable,3,lblPrj,"Project ");

            int rowCount = project.ConditoinsDefine.Count;
            Table conditionsTable = new Table((uint)(rowCount + 3),(uint)2,false);

            GenerateContent(ref conditionsTable, MainClass.Settings.Platform.Name, 1, MainClass.Settings.Platform,false);//tableSystem
            GenerateContent(ref conditionsTable, MainClass.Settings.Resolution.Name, 2,MainClass.Settings.Resolution,true); //project.Resolution);//tableSystem
            int i = 3;
            foreach (Condition cd in project.ConditoinsDefine) {
                GenerateContent(ref conditionsTable, cd.Name, i, cd,false);
                i++;
            }
            Expander exp1 = new Expander("General");
            exp1.Expanded = true;
            exp1.Add(propertyTable);

            Expander exp2 = new Expander("Conditions");
            exp2.Expanded = true;
            exp2.Add(conditionsTable);

            mainTable.Attach(exp1,0,1,0,1,AttachOptions.Expand|AttachOptions.Fill,AttachOptions.Fill,0,0);
            mainTable.Attach(exp2,0,1,1,2,AttachOptions.Expand|AttachOptions.Fill,AttachOptions.Fill,0,0);

            this.PackStart(mainTable,true,true,0);
            this.ShowAll();
        }
Example #9
0
        public Dialog(VariableSet variables)
            : base(_("UpdateCheck"), variables)
        {
            var vbox = new VBox(false, 12) {BorderWidth = 12};
              VBox.PackStart(vbox, true, true, 0);

              var table = new GimpTable(4, 3)
            {ColumnSpacing = 6, RowSpacing = 6};
              vbox.PackStart(table, true, true, 0);

              table.Attach(new GimpCheckButton(_("Check _GIMP"),
                       GetVariable<bool>("check_gimp")),
               0, 1, 0, 1);

              table.Attach(new GimpCheckButton(_("Check G_IMP#"),
                       GetVariable<bool>("check_gimp_sharp")),
               0, 1, 1, 2);

              table.Attach(new GimpCheckButton(_("Check _Unstable Releases"),
                       GetVariable<bool>("check_unstable")),
               0, 1, 2, 3);

              var enableProxy = GetVariable<bool>("enable_proxy");
              var httpProxy = GetVariable<string>("http_proxy");
              var port = GetVariable<string>("port");

              string tmp = Gimp.RcQuery("update-enable-proxy");
              enableProxy.Value = (tmp != null || tmp == "true");
              httpProxy.Value =  Gimp.RcQuery("update-http-proxy") ?? "";
              port.Value = Gimp.RcQuery("update-port") ?? "";

              var expander = new Expander(_("Proxy settings"));
              var proxyBox = new VBox(false, 12);

              proxyBox.Add(new GimpCheckButton(_("Manual proxy configuration"),
                       enableProxy));

              var hbox = new HBox(false, 12) {Sensitive = enableProxy.Value};
              proxyBox.Add(hbox);

              hbox.Add(new Label(_("HTTP Proxy:")));
              hbox.Add(new GimpEntry(httpProxy));

              hbox.Add(new Label(_("Port:")));
              hbox.Add(new GimpEntry(port) {WidthChars = 4});

              enableProxy.ValueChanged += delegate
            {
              hbox.Sensitive = enableProxy.Value;
            };

              expander.Add(proxyBox);
              table.Attach(expander, 0, 1, 3, 4);
        }
        public void SimpleEvaluationTests()
        {
            Parser p = new Parser();
            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary<ProjectPropertyInstance>());

            AssertParseEvaluate(p, "true", expander, true);
            AssertParseEvaluate(p, "on", expander, true);
            AssertParseEvaluate(p, "yes", expander, true);
            AssertParseEvaluate(p, "false", expander, false);
            AssertParseEvaluate(p, "off", expander, false);
            AssertParseEvaluate(p, "no", expander, false);
        }
Example #11
0
        public Form1()
        {
            _parser = new Parser();
            _expander = new Expander();
            _builder = new Builder();
            InitializeComponent();

            _settingsFilePath = @"c:\temp\parsing.xml";
            _itemsFilePath = @"c:\temp\items.xml";

            LoadSetting();
            Parse();
        }
Example #12
0
        public void RelationalTests()
        {
            Parser p = new Parser();
            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary<ProjectPropertyInstance>());

            AssertParseEvaluate(p, "1234 < 1235", expander, true);
            AssertParseEvaluate(p, "1234 <= 1235", expander, true);
            AssertParseEvaluate(p, "1235 < 1235", expander, false);
            AssertParseEvaluate(p, "1234 <= 1234", expander, true);
            AssertParseEvaluate(p, "1235 <= 1234", expander, false);
            AssertParseEvaluate(p, "1235 > 1234", expander, true);
            AssertParseEvaluate(p, "1235 >= 1235", expander, true);
            AssertParseEvaluate(p, "1235 >= 1234", expander, true);
            AssertParseEvaluate(p, "0.0==0", expander, true);
        }
Example #13
0
 private Widget CreateMoreOptionsExpander(string defaultDomainID)
 {
     optionsExpander = new Expander(Util.GS("More options"));
        optionsExpander.Activated += new EventHandler(OnOptionsExpanded);
        Table optionsTable = new Table(2, 3, false);
        optionsExpander.Add(optionsTable);
        optionsTable.ColumnSpacing = 10;
        optionsTable.RowSpacing = 10;
        optionsTable.SetColSpacing(0, 30);
        Label l = new Label(Util.GS("iFolder Account:"));
        l.Xalign = 0;
        optionsTable.Attach(l, 1,2,0,1,
     AttachOptions.Shrink | AttachOptions.Fill, 0,0,0);
        domainComboBox = ComboBox.NewText();
        optionsTable.Attach(domainComboBox, 2,3,0,1,
     AttachOptions.Expand | AttachOptions.Fill, 0,0,0);
        int defaultDomain = 0;
        for (int x = 0; x < domains.Length; x++)
        {
     domainComboBox.AppendText(domains[x].Name);
     if (defaultDomainID != null)
     {
      if (defaultDomainID == domains[x].ID)
       defaultDomain = x;
     }
     else
      defaultDomain = x;
        }
        domainComboBox.Active = defaultDomain;
        l = new Label(Util.GS("Description:"));
        l.Xalign = 0;
        optionsTable.Attach(l, 1,2,1,2,
     AttachOptions.Shrink | AttachOptions.Fill, 0,0,0);
        descriptionTextView = new TextView();
        descriptionTextView.LeftMargin = 4;
        descriptionTextView.RightMargin = 4;
        descriptionTextView.Editable = true;
        descriptionTextView.CursorVisible = true;
        descriptionTextView.AcceptsTab = false;
        descriptionTextView.WrapMode = WrapMode.WordChar;
        ScrolledWindow sw = new ScrolledWindow();
        sw.ShadowType = ShadowType.EtchedIn;
        sw.Add(descriptionTextView);
        optionsTable.Attach(sw, 2,3,1,2,
     AttachOptions.Expand | AttachOptions.Fill, 0,0,0);
        optionsTable.ShowAll();
        return optionsExpander;
 }
Example #14
0
        public ErrorListDialog () : base (Catalog.GetString ("Error"))
        {
            var table = new Table (3, 2, false) {
                RowSpacing = 12,
                ColumnSpacing = 16
            };

            table.Attach (icon_image = new Image () {
                    IconName = "dialog-error",
                    IconSize = (int)IconSize.Dialog,
                    Yalign = 0.0f
                }, 0, 1, 0, 3, AttachOptions.Shrink, AttachOptions.Fill | AttachOptions.Expand, 0, 0);

            table.Attach (header_label = new Label () { Xalign = 0.0f }, 1, 2, 0, 1,
                AttachOptions.Fill | AttachOptions.Expand,
                AttachOptions.Shrink, 0, 0);

            table.Attach (message_label = new Hyena.Widgets.WrapLabel (), 1, 2, 1, 2,
                AttachOptions.Fill | AttachOptions.Expand,
                AttachOptions.Shrink, 0, 0);

            var scrolled_window = new ScrolledWindow () {
                HscrollbarPolicy = PolicyType.Automatic,
                VscrollbarPolicy = PolicyType.Automatic,
                ShadowType = ShadowType.In
            };

            list_view = new TreeView () {
                HeightRequest = 120,
                WidthRequest = 200
            };
            scrolled_window.Add (list_view);

            table.Attach (details_expander = new Expander (Catalog.GetString ("Details")),
                1, 2, 2, 3,
                AttachOptions.Fill | AttachOptions.Expand,
                AttachOptions.Fill | AttachOptions.Expand,
                0, 0);
            details_expander.Add (scrolled_window);

            VBox.PackStart (table, true, true, 0);
            VBox.Spacing = 12;
            VBox.ShowAll ();

            details_expander.Activated += OnConfigureGeometry;
            Realized += OnConfigureGeometry;
        }
 public DeviceDescriptionInfo (Device device)
 {
     this.Build ();
     
     deviceType.Text = device.Type.ToString ();
     udn.Text = device.Udn;
     friendlyName.Text = device.FriendlyName;
     manufacturer.Text = device.Manufacturer;
     manufacturerUrl.Text = device.ManufacturerUrl != null ? device.ManufacturerUrl.ToString () : null;
     modelName.Text = device.ModelName;
     modelNumber.Text = device.ModelNumber;
     modelUrl.Text = device.ModelUrl != null ? device.ModelUrl.ToString () : null;
     serialNumber.Text = device.SerialNumber;
     upc.Text = device.Upc;
     foreach (var icon in device.Icons) {
         var expander = new Expander (string.Format ("{0}, {1}x{2}x{3}", icon.MimeType, icon.Width, icon.Height, icon.Depth));
         expander.Add (new LazyIcon (icon));
         iconBox.PackStart (expander, true, true, 0);
     }
 }
Example #16
0
        public void EqualityTests()
        {
            Parser p = new Parser();
            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary<ProjectPropertyInstance>());

            AssertParseEvaluate(p, "true == on", expander, true);
            AssertParseEvaluate(p, "TrUe == On", expander, true);
            AssertParseEvaluate(p, "true != false", expander, true);
            AssertParseEvaluate(p, "true==!false", expander, true);
            AssertParseEvaluate(p, "4 != 5", expander, true);
            AssertParseEvaluate(p, "-4 < 4", expander, true);
            AssertParseEvaluate(p, "5 == +5", expander, true);
            AssertParseEvaluate(p, "4 == 4.0", expander, true);
            AssertParseEvaluate(p, "4 == 4.0", expander, true);
            AssertParseEvaluate(p, ".45 == '.45'", expander, true);
            AssertParseEvaluate(p, "4 == '4'", expander, true);
            AssertParseEvaluate(p, "'0' == '4'", expander, false);
            AssertParseEvaluate(p, "4 == 0x0004", expander, true);
            AssertParseEvaluate(p, "0.0 == 0", expander, true);
            AssertParseEvaluate(p, "simplestring == 'simplestring'", expander, true);
        }
Example #17
0
		public DemoExpander () : base ("Demo Expander", null, DialogFlags.DestroyWithParent)
		{
			Resizable = false;

			VBox vbox = new VBox (false, 5);
			this.ContentArea.PackStart (vbox, true, true, 0);
			vbox.BorderWidth = 5;

			vbox.PackStart (new Label ("Expander demo. Click on the triangle for details."), false, false, 0);

			// Create the expander
			Expander expander = new Expander ("Details");
			expander.Add (new Label ("Details can be shown or hidden."));
			vbox.PackStart (expander, false, false, 0);

			AddButton (Stock.Close, ResponseType.Close);

			ShowAll ();
			Run ();
			Destroy ();
		}
Example #18
0
 protected virtual void OnMapped (object sender, System.EventArgs e)
 {
     if (!mapped) {
         mapped = true;
         ThreadPool.QueueUserWorkItem (state => {
             Gtk.Widget widget;
             try {
                 widget = provider.ProvideInfo (device);
             } catch (Exception exception) {
                 var box = new VBox ();
                 box.PackStart (new Gtk.Label ("Failed to Load " + provider.Name), true, true, 0);
                 var expander = new Expander ("Error");
                 expander.Add (new Label (exception.ToString ()));
                 box.PackStart (expander, true, true, 0);
                 widget = box;
             }
             Gtk.Application.Invoke ((o, a) => {
                 alignment.Remove (alignment.Child);
                 alignment.Add (widget);
                 ShowAll ();
             });
         });
     }
 }
Example #19
0
        public void PropertyFunctionDoesTaskHostExist_Evaluated()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

            pg["Runtime"] = ProjectPropertyInstance.Create("Runtime", "CurrentRuntime");
            pg["Architecture"] = ProjectPropertyInstance.Create("Architecture", "CurrentArchitecture");

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('$(Runtime)', '$(Architecture)'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            // This is the current, so it had better be true!
            Assert.True(String.Equals("true", result, StringComparison.OrdinalIgnoreCase));
        }
        public List <ScrubRule> getScrubRules()
        {
            //List<ScrubRule> sb = new List<ScrubRule>();
            TextBox filterCondition = (TextBox)this.FindName("FilterCondition");
            //sb.filterQuery = filterCondition.Text;
            List <ScrubRule> srList = new List <ScrubRule>();

            WrapPanel wrapPanel = (WrapPanel)this.FindName("WrapPanel");

            foreach (UIElement SPUI in wrapPanel.Children)
            {
                Expander            exp          = (Expander)SPUI;
                StackPanel          lrsp         = (StackPanel)exp.Content;
                UIElementCollection uiElementsSP = lrsp.Children;

                ScrubRule sr = new ScrubRule();

                foreach (UIElement uiElementSP in uiElementsSP)
                {
                    StackPanel          tempSP     = (StackPanel)uiElementSP;
                    UIElementCollection uiElements = tempSP.Children;

                    foreach (UIElement uiElement in uiElements)
                    {
                        if (uiElement.GetType().Name == "Label")
                        {
                            var ruleIdLabel = (Label)uiElement;
                            int ruleId;
                            if (int.TryParse(ruleIdLabel.Content.ToString(), out ruleId))
                            {
                                sr.RuleId = ruleId;
                            }
                            else
                            {
                                sr.RuleId = 0;
                            }
                        }

                        if (uiElement.GetType().Name == "TextBox")
                        {
                            TextBox tb = (TextBox)uiElement;

                            if (tb.Name.StartsWith("Filter"))
                            {
                                sr.FilterCondition = tb.Text.Trim();
                            }
                            else if (tb.Name.StartsWith("ScrubAttribute"))
                            {
                                sr.PropertyName = tb.Text.Trim();
                            }
                            else if (tb.Name.StartsWith("ScrubValue"))
                            {
                                sr.UpdateValue = tb.Text.Trim();
                            }
                            else if (tb.Name.StartsWith("FindValue"))
                            {
                                sr.FindValue = tb.Text.Trim();
                            }
                        }

                        if (uiElement.GetType().Name == "ComboBox")
                        {
                            ComboBox cb = (ComboBox)uiElement;
                            if (cb.Name.StartsWith("ScrubType"))
                            {
                                //sr.Type = (RuleType) Enum.Parse(typeof(RuleType), cb.Text);
                                RuleType rType;

                                if (Enum.TryParse <RuleType>(cb.Text, out rType))
                                {
                                    sr.Type = rType;
                                }
                                else
                                {
                                    sr.Type = null;
                                }
                            }
                        }
                    }
                }

                srList.Add(sr);
            }

            return(srList);
        }
        public ExceptionDialog(Exception e) : base()
        {
            debugInfo = BuildExceptionMessage(e);

            HasSeparator = false;
            BorderWidth  = 5;
            Resizable    = false;
            Title        = Catalog.GetString("F-Spot Encountered a Fatal Error");

            VBox.Spacing      = 12;
            ActionArea.Layout = ButtonBoxStyle.End;

            accel_group = new AccelGroup();
            AddAccelGroup(accel_group);

            HBox hbox = new HBox(false, 12);

            hbox.BorderWidth = 5;
            VBox.PackStart(hbox, false, false, 0);

            Image image = new Image(Stock.DialogError, IconSize.Dialog);

            image.Yalign = 0.0f;
            hbox.PackStart(image, true, true, 0);

            VBox label_vbox = new VBox(false, 0);

            label_vbox.Spacing = 12;
            hbox.PackStart(label_vbox, false, false, 0);

            Label label = new Label(String.Format("<b><big>{0}</big></b>", GLib.Markup.EscapeText(Title)));

            label.UseMarkup = true;
            label.Justify   = Justification.Left;
            label.LineWrap  = true;
            label.SetAlignment(0.0f, 0.5f);
            label_vbox.PackStart(label, false, false, 0);

            label = new Label(e.Message);

            label.UseMarkup = true;
            label.Justify   = Gtk.Justification.Left;
            label.LineWrap  = true;
            label.SetAlignment(0.0f, 0.5f);
            label_vbox.PackStart(label, false, false, 0);

            Label details_label = new Label(String.Format("<b>{0}</b>",
                                                          GLib.Markup.EscapeText(Catalog.GetString("Error Details"))));

            details_label.UseMarkup = true;
            Expander details_expander = new Expander("Details");

            details_expander.LabelWidget = details_label;
            label_vbox.PackStart(details_expander, true, true, 0);

            ScrolledWindow scroll = new ScrolledWindow();
            TextView       view   = new TextView();

            scroll.HscrollbarPolicy = PolicyType.Automatic;
            scroll.VscrollbarPolicy = PolicyType.Automatic;
            scroll.AddWithViewport(view);

            scroll.SetSizeRequest(450, 250);

            view.Editable    = false;
            view.Buffer.Text = debugInfo;

            details_expander.Add(scroll);

            hbox.ShowAll();

            AddButton(Stock.Close, ResponseType.Close, true);
        }
Example #22
0
        public void MydataGride_Loaded(object sender, RoutedEventArgs e)
        {
            Functions.ExpanderFunctions myfunctions = new Functions.ExpanderFunctions(MainStackPanel);
            //List<string> names = new List<string>();
            //names.Add("hai");
            //names.Add("SoWhat");
            // MydataGride.ItemsSource = kero.DefaultView;

            //DataTable kero = new DataTable();

            //    kero.Columns.Add("ان مكنتش تدلعنى مين هيدلعنى");

            //List<Person> t = new List<Person>();
            //t.Add(new Person() { Name = "asd", Age = "19" });
            //DataTable dt = new DataTable();
            //for (int i = 0; i < names.Count; i++)
            //{
            //    dt.Columns.Add(names[i]);
            //}
            //for (int i = 0; i < 5; i++)
            //{

            //}
            //dt.Columns.Add("Name");

            ////dt.Rows.Add("ayValue");
            string expandername = "ExpanderNumber ";
            string datagridname = "DataGridNumber ";

            DataTable table = myfunctions.Table();
            //  for (int i = 0; i < 9; i++)


            Expander expander = myfunctions.AddExpanderToStackPanel(expandername);

            DataGrid datagrid = myfunctions.NewDataGridToExpander(datagridname, expander);

            myfunctions.AddTableToDataGrid(table, datagrid);
            //try
            //{
            //MessageBox.Show((myfunctions.ColumnWidth(datagrid)).ToString());

            //}
            //catch(Exception ex)
            //{
            //    MessageBox.Show(ex.ToString());
            //}

            //myfunctions.AddTableToDataGrid(table, datagrid);
            //Style ColumnHeaderSyle = (Style)Application.Current.Resources["ColumnHeaderStyle"];

            // temp.ColumnHeaderStyle = ColumnHeaderSyle;

            //AddExpanderToStackPanel("FirstExpander");


            //Expander Search = GetExpander("FirstExpander");


            //if (Search != null)
            //{
            //    AddExpanderToExpander(Search, "SecondExpander");
            //}

            //AddExpanderToStackPanel("third");
            //// MessageBox.Show(t[0].Name);
        }
Example #23
0
        /// <summary>
        /// Processes a particular ToolsetPropertyDefinition into the correct value and location in the initial and/or final property set.
        /// </summary>
        /// <param name="property">The ToolsetPropertyDefinition being analyzed.</param>
        /// <param name="properties">The final set of properties that we wish this toolset property to be added to. </param>
        /// <param name="globalProperties">The global properties, used for expansion and to make sure none are overridden.</param>
        /// <param name="initialProperties">The initial properties, used for expansion and added to if "accumulateProperties" is true.</param>
        /// <param name="accumulateProperties">If "true", we add this property to the initialProperties dictionary, as well, so that properties later in the toolset can use this value.</param>
        /// <param name="toolsPath">If this toolset property is the "MSBuildToolsPath" property, we will return the value in this parameter.</param>
        /// <param name="binPath">If this toolset property is the "MSBuildBinPath" property, we will return the value in this parameter.</param>
        /// <param name="expander">The expander used to expand the value of the properties.  Ref because if we are accumulating the properties, we need to re-create the expander to account for the new property value.</param>
        private void EvaluateAndSetProperty(ToolsetPropertyDefinition property, PropertyDictionary <ProjectPropertyInstance> properties, PropertyDictionary <ProjectPropertyInstance> globalProperties, PropertyDictionary <ProjectPropertyInstance> initialProperties, bool accumulateProperties, ref string toolsPath, ref string binPath, ref Expander <ProjectPropertyInstance, ProjectItemInstance> expander)
        {
            if (0 == String.Compare(property.Name, ReservedPropertyNames.toolsPath, StringComparison.OrdinalIgnoreCase))
            {
                toolsPath = ExpandPropertyUnescaped(property, expander);
                toolsPath = ExpandRelativePathsRelativeToExeLocation(toolsPath);

                if (accumulateProperties)
                {
                    SetProperty
                    (
                        new ToolsetPropertyDefinition(ReservedPropertyNames.toolsPath, toolsPath, property.Source),
                        initialProperties,
                        globalProperties
                    );
                }
            }
            else if (0 == String.Compare(property.Name, ReservedPropertyNames.binPath, StringComparison.OrdinalIgnoreCase))
            {
                binPath = ExpandPropertyUnescaped(property, expander);
                binPath = ExpandRelativePathsRelativeToExeLocation(binPath);

                if (accumulateProperties)
                {
                    SetProperty
                    (
                        new ToolsetPropertyDefinition(ReservedPropertyNames.binPath, binPath, property.Source),
                        initialProperties,
                        globalProperties
                    );
                }
            }
            else if (ReservedPropertyNames.IsReservedProperty(property.Name))
            {
                // We don't allow toolsets to define reserved properties
                string baseMessage = ResourceUtilities.FormatResourceString("CannotModifyReservedProperty", property.Name);
                InvalidToolsetDefinitionException.Throw("InvalidPropertyNameInToolset", property.Name, property.Source.LocationString, baseMessage);
            }
            else
            {
                // It's an arbitrary property
                property.Value = ExpandPropertyUnescaped(property, expander);

                SetProperty(property, properties, globalProperties);

                if (accumulateProperties)
                {
                    SetProperty(property, initialProperties, globalProperties);
                }
            }

            if (accumulateProperties)
            {
                expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(initialProperties, FileSystems.Default);
            }
        }
Example #24
0
        public void PropertyFunctionConsumingItemMetadata()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            itemMetadataTable["Compile.Identity"] = "fOo.Cs";
            StringMetadataTable itemMetadata = new StringMetadataTable(itemMetadataTable);

            List<ProjectItemInstance> ig = new List<ProjectItemInstance>();
            pg.Set(ProjectPropertyInstance.Create("SomePath", @"c:\some\path"));
            ig.Add(new ProjectItemInstance(project, "Compile", "fOo.Cs", project.FullPath));

            ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>();
            itemsByType.ImportItems(ig);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, itemsByType, itemMetadata);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([System.IO.Path]::Combine($(SomePath),%(Compile.Identity)))", ExpanderOptions.ExpandAll, MockElementLocation.Instance);

            Assert.Equal(@"c:\some\path\fOo.Cs", result);
        }
Example #25
0
 private void AssertParseEvaluateThrow(Parser p, string expression, Expander <ProjectPropertyInstance, ProjectItemInstance> expander)
 {
     AssertParseEvaluateThrow(p, expression, expander, null);
 }
Example #26
0
 public static void SetVerticalHeaderPadding(Expander element, Thickness value)
 => element.SetValue(VerticalHeaderPaddingProperty, value);
        // update sidebar
        public static void UpdateSidebar(int gameId)
        {
            // get an instance of the MainWindow
            MainWindow mw = Application.Current.Windows.OfType <MainWindow>().FirstOrDefault();

            // new instance of the LibrarySidebar class
            LibrarySidebar lsb = new LibrarySidebar(gameId);

            /* define all controls that we want to set */

            // scrollviewer
            ScrollViewer sv = (ScrollViewer)mw.FindName("srcSidebar");

            // return out if hidesiderbar db field is true
            if (GlobalSettings.GetHideSidebar() == true)
            {
                sv.Visibility = Visibility.Collapsed;
                return;
            }

            sv.Visibility = Visibility.Visible;

            // set column definitions
            ColumnDefinition cd             = (ColumnDefinition)mw.FindName("sidebarColumn");
            ColumnDefinition colBoxartFront = (ColumnDefinition)mw.FindName("colBoxartFront");
            ColumnDefinition colBoxartBack  = (ColumnDefinition)mw.FindName("colBoxartBack");
            ColumnDefinition colMedia       = (ColumnDefinition)mw.FindName("colMedia");

            cd.Width = new GridLength(0.3, GridUnitType.Star);
            //colBoxartFront.Width = new GridLength(0.5, GridUnitType.Star);
            //colBoxartBack.Width = new GridLength(0.5, GridUnitType.Star);
            //colMedia.Width = new GridLength(0.5, GridUnitType.Star);

            UniformGrid gridManuals      = (UniformGrid)mw.FindName("gridManuals");
            UniformGrid ugridScreenshots = (UniformGrid)mw.FindName("ugridScreenshots");
            UniformGrid ugridFanarts     = (UniformGrid)mw.FindName("ugridFanarts");

            // borders
            Border brdSysInfo = (Border)mw.FindName("brdSidebarSystem");                            // game system info
            Border brdSidebarGameInformation = (Border)mw.FindName("brdSidebarGameInformation");    // main scraping info container

            brdSidebarGameInformation.Visibility = Visibility.Visible;

            Border brdGame = (Border)mw.FindName("brdSidebarGame");
            Border brdSidebarScreenshots = (Border)mw.FindName("brdSidebarScreenshots");
            Border brdSidebarFanArt      = (Border)mw.FindName("brdSidebarFanArt");
            Border brdSidebarOverview    = (Border)mw.FindName("brdSidebarOverview");

            Border brdManuals = (Border)mw.FindName("brdManuals");

            // expanders
            Expander expSysInfo         = (Expander)mw.FindName("expSysInfo");
            Expander expGameInfo        = (Expander)mw.FindName("expGameInfo");
            Expander expGameInformation = (Expander)mw.FindName("expGameInformation");
            Expander expOverview        = (Expander)mw.FindName("expOverview");
            Expander expManuals         = (Expander)mw.FindName("expManuals");

            // labels
            Label lblGameName      = (Label)mw.FindName("lblGameName");
            Label lblIsFavorite    = (Label)mw.FindName("lblIsFavorite");
            Label lblLastLaunched  = (Label)mw.FindName("lblLastLaunched");
            Label lblSessionLength = (Label)mw.FindName("lblSessionLength");
            Label lblTimesPlayed   = (Label)mw.FindName("lblTimesPlayed");
            Label lblTotalTime     = (Label)mw.FindName("lblTotalTime");

            Label lblAltNames    = (Label)mw.FindName("lblAltNames");
            Label lblReleaseDate = (Label)mw.FindName("lblReleaseDate");
            Label lblPlayers     = (Label)mw.FindName("lblPlayers");
            Label lblCoop        = (Label)mw.FindName("lblCoop");
            Label lblGenres      = (Label)mw.FindName("lblGenres");
            Label lblDeveloper   = (Label)mw.FindName("lblDeveloper");
            Label lblPublisher   = (Label)mw.FindName("lblPublisher");
            Label lblESRB        = (Label)mw.FindName("lblESRB");

            Label lblAltNamesTitle    = (Label)mw.FindName("lblAltNamesTitle");
            Label lblReleaseDateTitle = (Label)mw.FindName("lblReleaseDateTitle");
            Label lblPlayersTitle     = (Label)mw.FindName("lblPlayersTitle");
            Label lblCoopTitle        = (Label)mw.FindName("lblCoopTitle");
            Label lblGenresTitle      = (Label)mw.FindName("lblGenresTitle");
            Label lblDeveloperTitle   = (Label)mw.FindName("lblDeveloperTitle");
            Label lblPublisherTitle   = (Label)mw.FindName("lblPublisherTitle");
            Label lblESRBTitle        = (Label)mw.FindName("lblESRBTitle");

            TextBlock tbOverview = (TextBlock)mw.FindName("tbOverview");


            // listview
            ListView Screenshots = (ListView)mw.FindName("Screenshots");

            // images
            Image imgBoxartFront = (Image)mw.FindName("imgBoxartFront");
            Image imgBoxartBack  = (Image)mw.FindName("imgBoxartBack");
            Image imgBanner      = (Image)mw.FindName("imgBanner");
            Image imgMedia       = (Image)mw.FindName("imgMedia");

            // lists of gamesdb related controls
            List <Image> gdbImages = new List <Image>
            {
                imgBoxartFront,
                imgBoxartBack,
                imgBanner,
                imgMedia
            };
            List <Label> gdbLabels = new List <Label>
            {
                lblAltNames,
                lblAltNamesTitle,
                lblReleaseDate,
                lblReleaseDateTitle,
                lblPlayers,
                lblPlayersTitle,
                lblCoop,
                lblCoopTitle,
                lblGenres,
                lblGenresTitle,
                lblDeveloper,
                lblDeveloperTitle,
                lblPublisher,
                lblPublisherTitle
            };

            // screenshots
            Image ss1  = (Image)mw.FindName("ss1");
            Image ss2  = (Image)mw.FindName("ss2");
            Image ss3  = (Image)mw.FindName("ss3");
            Image ss4  = (Image)mw.FindName("ss4");
            Image ss5  = (Image)mw.FindName("ss5");
            Image ss6  = (Image)mw.FindName("ss6");
            Image ss7  = (Image)mw.FindName("ss7");
            Image ss8  = (Image)mw.FindName("ss8");
            Image ss9  = (Image)mw.FindName("ss9");
            Image ss10 = (Image)mw.FindName("ss10");
            Image ss11 = (Image)mw.FindName("ss11");
            Image ss12 = (Image)mw.FindName("ss12");
            Image ss13 = (Image)mw.FindName("ss13");
            Image ss14 = (Image)mw.FindName("ss14");
            Image ss15 = (Image)mw.FindName("ss15");
            Image ss16 = (Image)mw.FindName("ss16");
            Image ss17 = (Image)mw.FindName("ss17");
            Image ss18 = (Image)mw.FindName("ss18");
            Image ss19 = (Image)mw.FindName("ss19");
            Image ss20 = (Image)mw.FindName("ss20");
            Image ss21 = (Image)mw.FindName("ss21");
            Image ss22 = (Image)mw.FindName("ss22");
            Image ss23 = (Image)mw.FindName("ss23");
            Image ss24 = (Image)mw.FindName("ss24");
            Image ss25 = (Image)mw.FindName("ss25");
            Image ss26 = (Image)mw.FindName("ss26");
            Image ss27 = (Image)mw.FindName("ss27");
            Image ss28 = (Image)mw.FindName("ss28");
            Image ss29 = (Image)mw.FindName("ss29");
            Image ss30 = (Image)mw.FindName("ss30");
            Image ss31 = (Image)mw.FindName("ss31");
            Image ss32 = (Image)mw.FindName("ss32");
            Image ss33 = (Image)mw.FindName("ss33");
            Image ss34 = (Image)mw.FindName("ss34");
            Image ss35 = (Image)mw.FindName("ss35");
            Image ss36 = (Image)mw.FindName("ss36");

            List <Image> ss = new List <Image>
            {
                ss1, ss2, ss3, ss4, ss5, ss6, ss7, ss8, ss9, ss10, ss11, ss12, ss13, ss14, ss15, ss16, ss17, ss18, ss19, ss20, ss21, ss22, ss23, ss24, ss25, ss26, ss27, ss28, ss29, ss30, ss31, ss32, ss33, ss34, ss35, ss36
            };

            foreach (Image i in ss)
            {
                i.Visibility = Visibility.Collapsed;
            }


            // fanart
            Image fa1  = (Image)mw.FindName("fa1");
            Image fa2  = (Image)mw.FindName("fa2");
            Image fa3  = (Image)mw.FindName("fa3");
            Image fa4  = (Image)mw.FindName("fa4");
            Image fa5  = (Image)mw.FindName("fa5");
            Image fa6  = (Image)mw.FindName("fa6");
            Image fa7  = (Image)mw.FindName("fa7");
            Image fa8  = (Image)mw.FindName("fa8");
            Image fa9  = (Image)mw.FindName("fa9");
            Image fa10 = (Image)mw.FindName("fa10");
            Image fa11 = (Image)mw.FindName("fa11");
            Image fa12 = (Image)mw.FindName("fa12");
            Image fa13 = (Image)mw.FindName("fa13");
            Image fa14 = (Image)mw.FindName("fa14");
            Image fa15 = (Image)mw.FindName("fa15");
            Image fa16 = (Image)mw.FindName("fa16");
            Image fa17 = (Image)mw.FindName("fa17");
            Image fa18 = (Image)mw.FindName("fa18");
            Image fa19 = (Image)mw.FindName("fa19");
            Image fa20 = (Image)mw.FindName("fa20");
            Image fa21 = (Image)mw.FindName("fa21");
            Image fa22 = (Image)mw.FindName("fa22");
            Image fa23 = (Image)mw.FindName("fa23");
            Image fa24 = (Image)mw.FindName("fa24");
            Image fa25 = (Image)mw.FindName("fa25");
            Image fa26 = (Image)mw.FindName("fa26");
            Image fa27 = (Image)mw.FindName("fa27");
            Image fa28 = (Image)mw.FindName("fa28");
            Image fa29 = (Image)mw.FindName("fa29");
            Image fa30 = (Image)mw.FindName("fa30");
            Image fa31 = (Image)mw.FindName("fa31");
            Image fa32 = (Image)mw.FindName("fa32");
            Image fa33 = (Image)mw.FindName("fa33");
            Image fa34 = (Image)mw.FindName("fa34");
            Image fa35 = (Image)mw.FindName("fa35");
            Image fa36 = (Image)mw.FindName("fa36");

            List <Image> fa = new List <Image>
            {
                fa1, fa2, fa3, fa4, fa5, fa6, fa7, fa8, fa9, fa10, fa11, fa12, fa13, fa14, fa15, fa16, fa17, fa18, fa19, fa20, fa21, fa22, fa23, fa24, fa25, fa26, fa27, fa28, fa29, fa30, fa31, fa32, fa33, fa34, fa35, fa36
            };

            foreach (Image i in fa)
            {
                i.Visibility = Visibility.Collapsed;
            }

            // system info
            Label     lblSysName     = (Label)mw.FindName("lblSystemName");
            Image     sysImage       = (Image)mw.FindName("imgSystemImage");
            TextBlock tblockSysImage = (TextBlock)mw.FindName("tblockSystemDesc");

            string imageFileName = @"Data\Graphics\Systems\" + lsb.SystemCode.ToLower() + ".jpg";

            // game stats
            lblGameName.Content = lsb.GameName;
            if (lsb.IsFavorite == true)
            {
                lblIsFavorite.Content = "YES";
            }
            else
            {
                lblIsFavorite.Content = "NO";
            }

            string lp = lsb.LastPlayed.ToString("yyyy-MM-dd HH:mm");

            if (lp == "0001-01-01 00:00")
            {
                lblLastLaunched.Content = "Never";
            }
            else
            {
                lblLastLaunched.Content = lp;
            }

            // times played
            lblTimesPlayed.Content = lsb.TimesPlayed;

            // last session time
            lblSessionLength.Content = GetDatetimeDifference(lsb.LastPlayed, lsb.LastFinished);
            // Total game time
            lblTotalTime.Content = FormatMinutesToString(lsb.TotalPlayTime);

            // system info
            expSysInfo.Header   = lsb.SystemName;
            tblockSysImage.Text = lsb.SystemDescription;
            BitmapImage s = new BitmapImage();

            s.BeginInit();
            s.UriSource = new Uri(imageFileName, UriKind.Relative);
            s.EndInit();
            sysImage.Source = s;

            // Game info (scraped)
            // get the link table record

            GamesLibraryScrapedContent gd = new GamesLibraryScrapedContent();

            Game game = Game.GetGame(gameId);


            if (game.gdbId == null || game.gdbId == 0)
            {
                // no gdb data has been scraped - hide controls
                foreach (Image i in gdbImages)
                {
                    i.Visibility = Visibility.Collapsed;
                }
                foreach (Label l in gdbLabels)
                {
                    l.Visibility = Visibility.Collapsed;
                }
                expGameInformation.Header            = "Scraped Information";
                brdSidebarGameInformation.Visibility = Visibility.Collapsed;
                brdSidebarScreenshots.Visibility     = Visibility.Collapsed;
                brdSidebarFanArt.Visibility          = Visibility.Collapsed;
                brdSidebarOverview.Visibility        = Visibility.Collapsed;
                brdManuals.Visibility = Visibility.Collapsed;
                return;
            }
            else
            {
                ScrapedGameObject o = gd.GetScrapedGameObject(gameId, game.gdbId.Value);

                // link is there - SET DATA and control states
                bool isGameInfoData    = false;                         //GameInfo Expander
                bool isScreenshotsData = false;                         //Screenshots Expander
                bool isFanrtsData      = false;                         //Fanrt expander
                bool isManualsData     = false;                         //manuals expander

                // Game Title
                if (o.Data.Title == null || o.Data.Title == "")
                {
                    expGameInformation.Header = "Scraped Information";
                }
                else
                {
                    // Expander title
                    expGameInformation.Header = o.Data.Title;
                }

                // Back Cover Image
                if (o.BackCovers == null || o.BackCovers.Count == 0)
                {
                    imgBoxartBack.Source = null;
                    imgBoxartBack.SetVisibility();
                }
                else
                {
                    isGameInfoData = true;
                    // boxart - back
                    SetImage(imgBoxartBack, o.BackCovers.FirstOrDefault(), UriKind.Absolute);
                    imgBoxartBack.SetVisibility();
                }

                // Banner Image
                if (o.Banners == null || o.Banners.Count == 0)
                {
                    imgBanner.Source = null;
                    imgBanner.SetVisibility();
                }
                else
                {
                    isGameInfoData = true;
                    // banner (just take one)
                    List <string> banners = new List <string>();
                    SetImage(imgBanner, o.Banners.FirstOrDefault(), UriKind.Absolute);
                    imgBanner.SetVisibility();
                }

                // Front Cover Image
                if (o.FrontCovers == null || o.FrontCovers.Count == 0)
                {
                    imgBoxartFront.Source = null;
                    imgBoxartFront.SetVisibility();
                }
                else
                {
                    isGameInfoData = true;
                    // boxart - front
                    SetImage(imgBoxartFront, o.FrontCovers.FirstOrDefault(), UriKind.Absolute);
                    imgBoxartFront.SetVisibility();
                }

                // Media Image
                if (o.Medias == null || o.Medias.Count == 0)
                {
                    imgMedia.Source = null;
                    imgMedia.SetVisibility();
                }
                else
                {
                    isGameInfoData = true;
                    // media image
                    SetImage(imgMedia, o.Medias.FirstOrDefault(), UriKind.Absolute);
                    imgMedia.SetVisibility();
                }

                // Alternate Game Titles
                if (o.Data.AlternateTitles == null || o.Data.AlternateTitles.Count == 0)
                {
                    lblAltNames.Content         = null;
                    lblAltNamesTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData              = true;
                    lblAltNames.Content         = string.Join(", ", (o.Data.AlternateTitles).ToArray());
                    lblAltNames.Visibility      = Visibility.Visible;
                    lblAltNamesTitle.Visibility = Visibility.Visible;
                }

                // Release Date
                if (o.Data.Released == null || o.Data.Released == "")
                {
                    lblReleaseDate.Content         = null;
                    lblReleaseDateTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData                 = true;
                    lblReleaseDate.Content         = o.Data.Released;
                    lblReleaseDate.Visibility      = Visibility.Visible;
                    lblReleaseDateTitle.Visibility = Visibility.Visible;
                }

                // Coop
                if (o.Data.Coop == null || o.Data.Coop == "")
                {
                    lblCoop.Content         = null;
                    lblCoopTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData          = true;
                    lblCoop.Content         = o.Data.Coop;
                    lblCoop.Visibility      = Visibility.Visible;
                    lblCoopTitle.Visibility = Visibility.Visible;
                }

                // Developer
                if (o.Data.Developer == null || o.Data.Developer == "")
                {
                    lblDeveloper.Content         = null;
                    lblDeveloperTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData               = true;
                    lblDeveloper.Content         = o.Data.Developer;
                    lblDeveloper.Visibility      = Visibility.Visible;
                    lblDeveloperTitle.Visibility = Visibility.Visible;
                }

                // Publisher
                if (o.Data.Publisher == null || o.Data.Publisher == "")
                {
                    lblPublisher.Content         = null;
                    lblPublisherTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData               = true;
                    lblPublisher.Content         = o.Data.Publisher;
                    lblPublisher.Visibility      = Visibility.Visible;
                    lblPublisherTitle.Visibility = Visibility.Visible;
                }

                // Genres
                if (o.Data.Genres == null || o.Data.Genres.Count == 0)
                {
                    lblGenres.Content         = null;
                    lblGenresTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData            = true;
                    lblGenres.Content         = string.Join(", ", (o.Data.Genres).ToArray());
                    lblGenres.Visibility      = Visibility.Visible;
                    lblGenresTitle.Visibility = Visibility.Visible;
                }

                // ESRB Rating
                if (o.Data.ESRB == null || o.Data.ESRB == "")
                {
                    lblESRB.Content         = null;
                    lblESRBTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData          = true;
                    lblESRB.Content         = o.Data.ESRB;
                    lblESRB.Visibility      = Visibility.Visible;
                    lblESRBTitle.Visibility = Visibility.Visible;
                }

                // Number of players
                if (o.Data.Players == null || o.Data.Players == "")
                {
                    lblPlayers.Content         = null;
                    lblPlayersTitle.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData             = true;
                    lblPlayers.Content         = o.Data.Players;
                    lblPlayers.Visibility      = Visibility.Visible;
                    lblPlayersTitle.Visibility = Visibility.Visible;
                }

                // game overview (description)
                if (o.Data.Overview == null || o.Data.Overview == "")
                {
                    tbOverview.Text = null;
                    brdSidebarOverview.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isGameInfoData  = true;
                    tbOverview.Text = o.Data.Overview;
                    brdSidebarOverview.Visibility = Visibility.Visible;
                }

                // Fanart Images
                if (o.FanArts == null || o.FanArts.Count == 0)
                {
                    brdSidebarFanArt.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isFanrtsData = true;
                    int fanCount = o.FanArts.Count;
                    ugridFanarts.Columns        = DetermineUniformGridColumns(fanCount);
                    brdSidebarFanArt.Visibility = Visibility.Visible;
                    List <string> fshots = o.FanArts;
                    String[]      arr    = fshots.ToArray();
                    int           i      = 0;
                    while (i < fa.Count)
                    {
                        // check whether we have run out of images
                        if (i >= fshots.Count || fshots == null)
                        {
                            break;
                        }
                        // populate screenshot images
                        string path = arr[i];
                        Image  img  = (Image)mw.FindName("fa" + (i + 1).ToString());
                        SetImage(img, path, UriKind.Absolute);
                        img.SetVisibility();
                        i++;
                    }
                }

                // Screenshot Images
                if (o.Screenshots == null || o.Screenshots.Count == 0)
                {
                    brdSidebarScreenshots.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isScreenshotsData = true;
                    int screenCount = o.Screenshots.Count;
                    ugridScreenshots.Columns         = DetermineUniformGridColumns(screenCount);
                    brdSidebarScreenshots.Visibility = Visibility.Visible;
                    List <string> sshots = o.Screenshots;
                    String[]      arr    = sshots.ToArray();
                    int           i      = 0;
                    while (i < ss.Count)
                    {
                        // check whether we have run out of images
                        if (i >= sshots.Count || sshots == null)
                        {
                            break;
                        }
                        // populate screenshot images
                        string path = arr[i];
                        Image  img  = (Image)mw.FindName("ss" + (i + 1).ToString());
                        SetImage(img, path, UriKind.Absolute);
                        img.SetVisibility();
                        i++;
                    }
                }

                // Manuals (external documents)
                if (o.Manuals == null || o.Manuals.Count == 0)
                {
                    brdManuals.Visibility = Visibility.Collapsed;
                }
                else
                {
                    isManualsData         = true;
                    brdManuals.Visibility = Visibility.Visible;
                    // get number of manuals in the directory
                    int manCount = o.Manuals.Count;
                    // disable buttons that are not needed and setup the buttons that are required
                    int c = 1;
                    while (c <= 20)
                    {
                        Button b = (Button)mw.FindName("btnMan" + c);
                        if ((c - 1) < manCount)
                        {
                            // activate button
                            b.Visibility = Visibility.Visible;
                            // get just filename
                            string path = Path.GetFileName(o.Manuals[c - 1]);
                            b.Content  = path; // "Man " + c.ToString();
                            b.ToolTip  = o.Manuals[c - 1];
                            b.FontSize = 8;
                        }
                        else
                        {
                            // hide button
                            b.Visibility = Visibility.Collapsed;
                        }
                        c++;
                    }
                }

                // set border visibilities
                if (isGameInfoData == false)
                {
                    brdSidebarGameInformation.Visibility = Visibility.Collapsed;
                }
                else
                {
                    brdSidebarGameInformation.Visibility = Visibility.Visible;
                }
                if (isFanrtsData == false)
                {
                    brdSidebarFanArt.Visibility = Visibility.Collapsed;
                }
                else
                {
                    brdSidebarFanArt.Visibility = Visibility.Visible;
                }
                if (isScreenshotsData == false)
                {
                    brdSidebarScreenshots.Visibility = Visibility.Collapsed;
                }
                else
                {
                    brdSidebarScreenshots.Visibility = Visibility.Visible;
                }
                if (isManualsData == false)
                {
                    brdManuals.Visibility = Visibility.Collapsed;
                }
                else
                {
                    brdManuals.Visibility = Visibility.Visible;
                }
            }
        }
Example #28
0
        private void FillFileds()
        {
            try
            {
                int i = 0;
                do
                {
                    List <object> j = new List <object>()
                    {
                        null, 2, 3, 4, 5
                    };
                    var a = lst.SingleOrDefault(x => x.FieldName == "CreditCard" + j[i]);
                    if (a != null)
                    {
                        var q = a.GetType().GetProperty(a.FieldName).GetValue(a, null).ToString().Split('*');
                        ((TextBox)this.FindName("CCCode" + j[i])).Text     = q.FirstOrDefault();
                        ((PasswordBox)this.FindName("CC" + j[i])).Password = q.LastOrDefault();
                    }
                    var d = lst.SingleOrDefault(x => x.FieldName == "ExpirationDate" + j[i]);
                    if (d != null)
                    {
                        var b = d.GetType().GetProperty(d.FieldName).GetValue(d, null).ToString().Split(new String[] { "/" }, 5,
                                                                                                        StringSplitOptions.RemoveEmptyEntries);
                        ((PasswordBox)this.FindName("MM" + j[i])).Password = b.FirstOrDefault();
                        ((Label)this.FindName("lblMM" + j[i])).Visibility  = (string.IsNullOrEmpty(((PasswordBox)this.FindName("MM" + j[i])).Password) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden);
                        ((PasswordBox)this.FindName("YY" + j[i])).Password = b.LastOrDefault();
                        ((Label)this.FindName("lblYY" + j[i])).Visibility  = (string.IsNullOrEmpty(((PasswordBox)this.FindName("YY" + j[i])).Password) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden);
                    }
                    var l = lst.SingleOrDefault(x => x.FieldName == "CVV" + ((j[i] == null) ? 1 : int.Parse(j[i].ToString())));
                    if (l != null)
                    {
                        var c = new string(Common.toDecrypt(l.GetType().GetProperty(l.FieldName).GetValue(l, null).ToString()).Where(char.IsDigit).ToArray());
                        ((PasswordBox)this.FindName("Code" + j[i])).Password = (!string.IsNullOrEmpty(c)) ? c : string.Empty;
                        ((Label)this.FindName("lblCode" + j[i])).Visibility  = (string.IsNullOrEmpty(c)) ? System.Windows.Visibility.Visible : System.Windows.Visibility.Hidden;
                    }

                    var t = lst.SingleOrDefault(x => x.FieldName == "TypeOfService" + ((j[i] == null) ? 1 : int.Parse(j[i].ToString())));
                    if (t != null)
                    {
                        var q = t.GetType().GetProperty(t.FieldName).GetValue(t, null).ToString().Split('*');
                        if (q.Length >= 4)
                        {
                            ((CheckBox)this.FindName("chkAir" + j[i])).IsChecked   = (q.FirstOrDefault() == "Y") ? true : false;
                            ((CheckBox)this.FindName("chkCar" + j[i])).IsChecked   = (q[1] == "Y") ? true : false;
                            ((CheckBox)this.FindName("chkHtl" + j[i])).IsChecked   = (q[2] == "Y") ? true : false;
                            ((TextBox)this.FindName("txtSpecificUse" + j[i])).Text = q.LastOrDefault().Replace('¨', ' ');
                        }
                    }

                    ((Expander)this.FindName("Expander" + j[i])).Expanded         += Expander_Expanded;
                    ((TextBox)this.FindName("txtSpecificUse" + j[i])).TextChanged += header_TextChanged;
                    ((TextBox)this.FindName("CCCode" + j[i])).CharacterCasing      = CharacterCasing.Upper;
                    ((TextBox)this.FindName("CCCode" + j[i])).TextChanged         += header_TextChanged;
                    ((Label)this.FindName("lblCode" + j[i])).MouseLeftButtonUp    += UsrCtrlCCardsFirstLevel_MouseLeftButtonUp;
                    ((PasswordBox)this.FindName("CC" + j[i])).PasswordChanged     += UsrCtrlCCardsFirstLevel_PasswordChanged;
                    ((Label)this.FindName("lblMM" + j[i])).MouseLeftButtonUp      += UsrCtrlCCardsFirstLevel_MouseLeftButtonUp;
                    ((Label)this.FindName("lblYY" + j[i])).MouseLeftButtonUp      += UsrCtrlCCardsFirstLevel_MouseLeftButtonUp;
                    ((CheckBox)this.FindName("chkAir" + j[i])).Click += chk_Checked;
                    ((CheckBox)this.FindName("chkCar" + j[i])).Click += chk_Checked;
                    ((CheckBox)this.FindName("chkHtl" + j[i])).Click += chk_Checked;
                    ((TextBox)this.FindName("txtSpecificUse" + j[i])).CharacterCasing = CharacterCasing.Upper;
                    ((PasswordBox)this.FindName("MM" + j[i])).GotFocus   += UsrCtrlCCardsFirstLevel_GotFocus;
                    ((PasswordBox)this.FindName("YY" + j[i])).GotFocus   += UsrCtrlCCardsFirstLevel_GotFocus;
                    ((PasswordBox)this.FindName("Code" + j[i])).GotFocus += UsrCtrlCCardsFirstLevel_GotFocus;
                    Expander e = (Expander)this.FindName("Expander" + j[i]);
                    if (e != null & ((PasswordBox)this.FindName("CC" + j[i])).Password.Length >= 5)
                    {
                        e.Header = ((TextBox)this.FindName("CCCode" + j[i])).Text + "           " + "***********" + ((PasswordBox)this.FindName("CC" + j[i])).Password.Substring(((PasswordBox)this.FindName("CC" + j[i])).Password.Length - 4, 4)
                                   + "           "
                                   + (((CheckBox)this.FindName("chkAir" + j[i])).IsChecked == true ? "AIR" : "    ")
                                   + "    " + (((CheckBox)this.FindName("chkCar" + j[i])).IsChecked == true ? "CAR" : "    ")
                                   + "    " + (((CheckBox)this.FindName("chkHtl" + j[i])).IsChecked == true ? "HTL" : "    ")
                                   + "           " + ((TextBox)this.FindName("txtSpecificUse" + j[i])).Text.Replace('¨', ' ');
                    }
                    ++i;
                } while (i < 5);
            }
            catch (Exception ex)
            {
                throw new Exception("Error in FillFields Profiles: " + ex.Message);
            }
        }
Example #29
0
 public static Thickness GetVerticalHeaderPadding(Expander element)
 => (Thickness)element.GetValue(VerticalHeaderPaddingProperty);
        /// <summary>
        /// Returns a list of all items in the provided item group whose itemspecs match the specification, after it is split and any wildcards are expanded.
        /// If no items match, returns null.
        /// </summary>
        /// <param name="items">The items to match</param>
        /// <param name="specification">The specification to match against the items.</param>
        /// <param name="specificationLocation">The specification to match against the provided items</param>
        /// <param name="expander">The expander to use</param>
        /// <returns>A list of matching items</returns>
        private List <ProjectItemInstance> FindItemsMatchingSpecification
        (
            ICollection <ProjectItemInstance> items,
            string specification,
            ElementLocation specificationLocation,
            Expander <ProjectPropertyInstance, ProjectItemInstance> expander
        )
        {
            if (items.Count == 0 || specification.Length == 0)
            {
                return(null);
            }

            // This is a hashtable whose key is the filename for the individual items
            // in the Exclude list, after wildcard expansion.
            HashSet <string> specificationsToFind = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            // Split by semicolons
            var specificationPieces = expander.ExpandIntoStringListLeaveEscaped(specification, ExpanderOptions.ExpandAll, specificationLocation);

            foreach (string piece in specificationPieces)
            {
                // Take each individual path or file expression, and expand any
                // wildcards.  Then loop through each file returned, and add it
                // to our hashtable.

                // Don't unescape wildcards just yet - if there were any escaped, the caller wants to treat them
                // as literals. Everything else is safe to unescape at this point, since we're only matching
                // against the file system.
                string[] fileList = _engineFileUtilities.GetFileListEscaped(Project.Directory, piece);

                foreach (string file in fileList)
                {
                    // Now unescape everything, because this is the end of the road for this filename.
                    // We're just going to compare it to the unescaped include path to filter out the
                    // file excludes.
                    specificationsToFind.Add(EscapingUtilities.UnescapeAll(file));
                }
            }

            if (specificationsToFind.Count == 0)
            {
                return(null);
            }

            // Now loop through our list and filter out any that match a
            // filename in the remove list.
            List <ProjectItemInstance> itemsRemoved = new List <ProjectItemInstance>();

            foreach (ProjectItemInstance item in items)
            {
                // Even if the case for the excluded files is different, they
                // will still get excluded, as expected.  However, if the excluded path
                // references the same file in a different way, such as by relative
                // path instead of absolute path, we will not realize that they refer
                // to the same file, and thus we will not exclude it.
                if (specificationsToFind.Contains(item.EvaluatedInclude))
                {
                    itemsRemoved.Add(item);
                }
            }

            return(itemsRemoved);
        }
        /// <summary>
        /// Takes an item specification, evaluates it and expands it into a list of items
        /// </summary>
        /// <param name="originalItem">The original item data</param>
        /// <param name="expander">The expander to use.</param>
        /// <param name="keepMetadata">An <see cref="ISet{String}"/> of metadata names to keep.</param>
        /// <param name="removeMetadata">An <see cref="ISet{String}"/> of metadata names to remove.</param>
        /// <remarks>
        /// This code is very close to that which exists in the Evaluator.EvaluateItemXml method.  However, because
        /// it invokes type constructors, and those constructors take arguments of fundamentally different types, it has not
        /// been refactored.
        /// </remarks>
        /// <returns>A list of items.</returns>
        private IList <ProjectItemInstance> ExpandItemIntoItems
        (
            ProjectItemGroupTaskItemInstance originalItem,
            Expander <ProjectPropertyInstance, ProjectItemInstance> expander,
            ISet <string> keepMetadata,
            ISet <string> removeMetadata
        )
        {
            //todo this is duplicated logic with the item computation logic from evaluation (in LazyIncludeOperation.SelectItems)

            ProjectErrorUtilities.VerifyThrowInvalidProject(!(keepMetadata != null && removeMetadata != null), originalItem.KeepMetadataLocation, "KeepAndRemoveMetadataMutuallyExclusive");
            IList <ProjectItemInstance> items = new List <ProjectItemInstance>();

            // Expand properties and metadata in Include
            string evaluatedInclude = expander.ExpandIntoStringLeaveEscaped(originalItem.Include, ExpanderOptions.ExpandPropertiesAndMetadata, originalItem.IncludeLocation);

            if (evaluatedInclude.Length == 0)
            {
                return(items);
            }

            // Compute exclude fragments, without expanding wildcards
            var excludes = ImmutableList <string> .Empty.ToBuilder();

            if (originalItem.Exclude.Length > 0)
            {
                string evaluatedExclude = expander.ExpandIntoStringLeaveEscaped(originalItem.Exclude, ExpanderOptions.ExpandAll, originalItem.ExcludeLocation);

                if (evaluatedExclude.Length > 0)
                {
                    var excludeSplits = ExpressionShredder.SplitSemiColonSeparatedList(evaluatedExclude);

                    foreach (string excludeSplit in excludeSplits)
                    {
                        excludes.Add(excludeSplit);
                    }
                }
            }

            // Split Include on any semicolons, and take each split in turn
            var includeSplits = ExpressionShredder.SplitSemiColonSeparatedList(evaluatedInclude);
            ProjectItemInstanceFactory itemFactory = new ProjectItemInstanceFactory(this.Project, originalItem.ItemType);

            foreach (string includeSplit in includeSplits)
            {
                // If expression is "@(x)" copy specified list with its metadata, otherwise just treat as string
                bool throwaway;

                IList <ProjectItemInstance> itemsFromSplit = expander.ExpandSingleItemVectorExpressionIntoItems(includeSplit,
                                                                                                                itemFactory,
                                                                                                                ExpanderOptions.ExpandItems,
                                                                                                                false /* do not include null expansion results */,
                                                                                                                out throwaway,
                                                                                                                originalItem.IncludeLocation);

                if (itemsFromSplit != null)
                {
                    // Expression is in form "@(X)", so add these items directly.
                    foreach (ProjectItemInstance item in itemsFromSplit)
                    {
                        items.Add(item);
                    }
                }
                else
                {
                    // The expression is not of the form "@(X)". Treat as string

                    // Pass the non wildcard expanded excludes here to fix https://github.com/Microsoft/msbuild/issues/2621
                    string[] includeSplitFiles = _engineFileUtilities.GetFileListEscaped(
                        Project.Directory,
                        includeSplit,
                        excludes);

                    foreach (string includeSplitFile in includeSplitFiles)
                    {
                        items.Add(new ProjectItemInstance(
                                      Project,
                                      originalItem.ItemType,
                                      includeSplitFile,
                                      includeSplit /* before wildcard expansion */,
                                      null,
                                      null,
                                      originalItem.Location.File));
                    }
                }
            }

            // Evaluate, split, expand and subtract any Exclude
            HashSet <string> excludesUnescapedForComparison = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (string excludeSplit in excludes)
            {
                string[] excludeSplitFiles = _engineFileUtilities.GetFileListUnescaped(Project.Directory, excludeSplit);

                foreach (string excludeSplitFile in excludeSplitFiles)
                {
                    excludesUnescapedForComparison.Add(excludeSplitFile);
                }
            }

            List <ProjectItemInstance> remainingItems = new List <ProjectItemInstance>();

            for (int i = 0; i < items.Count; i++)
            {
                if (!excludesUnescapedForComparison.Contains(((IItem)items[i]).EvaluatedInclude))
                {
                    remainingItems.Add(items[i]);
                }
            }

            items = remainingItems;

            // Filter the metadata as appropriate
            if (keepMetadata != null)
            {
                foreach (var item in items)
                {
                    var metadataToRemove = item.MetadataNames.Where(name => !keepMetadata.Contains(name));
                    foreach (var metadataName in metadataToRemove)
                    {
                        item.RemoveMetadata(metadataName);
                    }
                }
            }
            else if (removeMetadata != null)
            {
                foreach (var item in items)
                {
                    var metadataToRemove = item.MetadataNames.Where(name => removeMetadata.Contains(name));
                    foreach (var metadataName in metadataToRemove)
                    {
                        item.RemoveMetadata(metadataName);
                    }
                }
            }

            return(items);
        }
Example #32
0
        private void LoadDefaults(string uri)
        {
            Style accordionStyle = (Style)Application.Current.Resources["AccordionItemStyle"];
            IMapper <string, HeaderedContentControl> accordionItems = new DictionaryMapper <string, HeaderedContentControl>();
            {
                var graph = new DefaultGraph();
                try {
                    new GraphMLIOHandler().Read(graph, uri);
                } catch (Exception) {
                    return;
                }
                List <StyleChooser> nodeChoosers = new List <StyleChooser>();
                foreach (var node in graph.Nodes)
                {
                    string tag = (string)(node.Tag ?? "Other");

                    if ("Dummy" == tag)
                    {
                        continue;
                    }

                    HeaderedContentControl accordionItem = accordionItems[tag];
                    if (null == accordionItem)
                    {
                        accordionItem = new Expander()
                        {
                            Style = accordionStyle
                        };
                        accordionItem.Header = tag;
                        accordionItems[tag]  = accordionItem;
                        StyleChooserAccordion.Items.Add(accordionItem);
                        var styleChooser = new StyleChooser();
                        styleChooser.ItemType          = typeof(INodeStyle);
                        styleChooser.ItemsSource       = new ObservableCollection <INode>();
                        styleChooser.SelectionChanged += delegate(object sender, SelectionChangedEventArgs args) {
                            if (args.AddedItems.Count > 0)
                            {
                                foreach (var n in nodeChoosers)
                                {
                                    if (n != sender)
                                    {
                                        n.Deselect();
                                    }
                                }
                            }
                        };
                        styleChooser.SelectionChanged += OnSelectionChanged;

                        nodeChoosers.Add(styleChooser);
                        accordionItem.Content            = styleChooser;
                        styleChooser.HorizontalAlignment = HorizontalAlignment.Stretch;
                    }

                    StyleChooser chooser = (StyleChooser)accordionItem.Content;
                    ObservableCollection <INode> itemSource = (ObservableCollection <INode>)chooser.ItemsSource;
                    itemSource.Add(node);
                }
                var nodeChooser = nodeChoosers.FirstOrDefault();
                if (nodeChooser != null)
                {
                    nodeChooser.SelectFirst();
                }

                HeaderedContentControl edgeTypesAccordionItem = new Expander()
                {
                    Style = accordionStyle
                };
                edgeTypesAccordionItem.Header = "Edge Types";
                StyleChooserAccordion.Items.Add(edgeTypesAccordionItem);
                var edgeStyleChooser = new StyleChooser();
                edgeStyleChooser.ItemType = typeof(IEdgeStyle);
                var edgeStyles = new ObservableCollection <IEdgeStyle>();
                edgeStyleChooser.ItemsSource = edgeStyles;

                edgeStyleChooser.SelectionChanged += OnSelectionChanged;


                edgeTypesAccordionItem.Content = edgeStyleChooser;

                foreach (var edge in graph.Edges)
                {
                    edgeStyles.Add(edge.Style);
                }

                edgeStyleChooser.SelectFirst();

                var labelTypesAccordionItem = new Expander()
                {
                    Style = accordionStyle
                };
                labelTypesAccordionItem.Header = "Label Types";
                StyleChooserAccordion.Items.Add(labelTypesAccordionItem);
                var labelStyleChooser = new StyleChooser();
                labelStyleChooser.ItemType = typeof(ILabelStyle);
                var labelStyles = new ObservableCollection <ILabelStyle>();
                labelStyleChooser.ItemsSource   = labelStyles;
                labelTypesAccordionItem.Content = labelStyleChooser;

                labelStyleChooser.SelectionChanged += OnSelectionChanged;

                foreach (var label in graph.Labels)
                {
                    if (label.Owner is INode && Equals("Dummy", label.Owner.Tag))
                    {
                        var style = label.Style;
                        if (style is NodeStyleLabelStyleAdapter)
                        {
                            // unwrap from NodeStyleLabelStyleAdapter
                            style = ((NodeStyleLabelStyleAdapter)style).LabelStyle;
                        }

                        // adjust the default flow direction of SimpleLabelStyles to the flowdirection of the current application.
                        if (style is DefaultLabelStyle)
                        {
                            ((DefaultLabelStyle)style).FlowDirection = this.FlowDirection;
                        }
                        if (style is LabelStyle)
                        {
                            ((LabelStyle)style).FlowDirection = this.FlowDirection;
                        }
                        labelStyles.Add(label.Style);
                    }
                }
                labelStyleChooser.SelectFirst();

                var portTypesAccordionItem = new Expander()
                {
                    Style = accordionStyle
                };
                portTypesAccordionItem.Header = "Port Types";
                StyleChooserAccordion.Items.Add(portTypesAccordionItem);
                var portStyleChooser = new StyleChooser();
                portStyleChooser.ItemType = typeof(IPortStyle);
                var portStyles = new ObservableCollection <IPortStyle>();
                portStyleChooser.ItemsSource   = portStyles;
                portTypesAccordionItem.Content = portStyleChooser;

                portStyleChooser.SelectionChanged += OnSelectionChanged;

                foreach (var port in graph.Ports)
                {
                    if (Equals("Dummy", port.Owner.Tag) && port.Tag != null)
                    {
                        portStyles.Add(port.Style);
                    }
                }
                // clear tags except for group nodes - no one needs them....
                foreach (var node in graph.Nodes)
                {
                    if (!Equals("Group Nodes", node.Tag))
                    {
                        node.Tag = null;
                    }
                }
                foreach (var edge in graph.Edges)
                {
                    edge.Tag = null;
                }
            }
        }
Example #33
0
        public void PropertyFunctionStaticMethodFileAttributes()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string tempFile = FileUtilities.GetTemporaryFile();
            try
            {
                File.SetAttributes(tempFile, FileAttributes.ReadOnly | FileAttributes.Archive);

                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseAnd(32,$([System.IO.File]::GetAttributes(" + tempFile + "))))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                Assert.Equal("32", result);
            }
            finally
            {
                File.SetAttributes(tempFile, FileAttributes.Normal);
                File.Delete(tempFile);
            }
        }
 public RowExpanderSize(Expander expander, Grid parentGrid)
 {
     _expanderRow = parentGrid.RowDefinitions[Grid.GetRow(expander)];
 }
Example #35
0
        public void PropertySimpleSpaced()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("SomeStuff", "This IS SOME STUff"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$( SomeStuff )", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal(String.Empty, result);
        }
Example #36
0
        public void ConditionedPropertyUpdateTests()
        {
            Parser          p             = new Parser();
            ProjectInstance parentProject = new ProjectInstance(ProjectRootElement.Create());
            ItemDictionary <ProjectItemInstance> itemBag = new ItemDictionary <ProjectItemInstance>();

            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "foo.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "bar.cs", parentProject.FullPath));
            itemBag.Add(new ProjectItemInstance(parentProject, "Compile", "baz.cs", parentProject.FullPath));

            Expander <ProjectPropertyInstance, ProjectItemInstance> expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(new PropertyDictionary <ProjectPropertyInstance>(), itemBag, FileSystems.Default);
            Dictionary <string, List <string> > conditionedProperties        = new Dictionary <string, List <string> >();

            ConditionEvaluator.IConditionEvaluationState state =
                new ConditionEvaluator.ConditionEvaluationState <ProjectPropertyInstance, ProjectItemInstance>
                (
                    String.Empty,
                    expander,
                    ExpanderOptions.ExpandAll,
                    conditionedProperties,
                    Directory.GetCurrentDirectory(),
                    ElementLocation.EmptyLocation,
                    FileSystems.Default
                );

            List <string> properties = null;

            AssertParseEvaluate(p, "'0' == '1'", expander, false, state);
            Assert.Empty(conditionedProperties);

            AssertParseEvaluate(p, "$(foo) == foo", expander, false, state);
            Assert.Single(conditionedProperties);
            properties = conditionedProperties["foo"];
            Assert.Single(properties);

            AssertParseEvaluate(p, "'$(foo)' != 'bar'", expander, true, state);
            Assert.Single(conditionedProperties);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);

            AssertParseEvaluate(p, "'$(branch)|$(build)|$(platform)' == 'lab22dev|debug|x86'", expander, false, state);
            Assert.Equal(4, conditionedProperties.Count);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["branch"];
            Assert.Single(properties);
            properties = conditionedProperties["build"];
            Assert.Single(properties);
            properties = conditionedProperties["platform"];
            Assert.Single(properties);

            AssertParseEvaluate(p, "'$(branch)|$(build)|$(platform)' == 'lab21|debug|x86'", expander, false, state);
            Assert.Equal(4, conditionedProperties.Count);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["branch"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["build"];
            Assert.Single(properties);
            properties = conditionedProperties["platform"];
            Assert.Single(properties);

            AssertParseEvaluate(p, "'$(branch)|$(build)|$(platform)' == 'lab23|retail|ia64'", expander, false, state);
            Assert.Equal(4, conditionedProperties.Count);
            properties = conditionedProperties["foo"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["branch"];
            Assert.Equal(3, properties.Count);
            properties = conditionedProperties["build"];
            Assert.Equal(2, properties.Count);
            properties = conditionedProperties["platform"];
            Assert.Equal(2, properties.Count);
            DumpDictionary(conditionedProperties);
        }
 /// <summary>
 /// Updates the expander header.
 /// </summary>
 /// <param name="expander">The expander.</param>
 /// <param name="notificationsState">The notification state.</param>
 private void UpdateExpanderHeader(Expander expander, NotificationsState notificationsState)
 {
     expander.Header = $"Notification settings ({this.GetNotificationsStateTextRepresentation(notificationsState)})"; // TODO resources
 }
Example #38
0
        public void ExpandAllIntoTaskItems3()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

            List<ProjectItemInstance> ig = new List<ProjectItemInstance>();
            ig.Add(new ProjectItemInstance(project, "Compile", "foo.cs", project.FullPath));
            ig.Add(new ProjectItemInstance(project, "Compile", "bar.cs", project.FullPath));

            List<ProjectItemInstance> ig2 = new List<ProjectItemInstance>();
            ig2.Add(new ProjectItemInstance(project, "Resource", "bing.resx", project.FullPath));

            ItemDictionary<ProjectItemInstance> itemsByType = new ItemDictionary<ProjectItemInstance>();
            itemsByType.ImportItems(ig);
            itemsByType.ImportItems(ig2);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, itemsByType);

            IList<TaskItem> itemsOut = expander.ExpandIntoTaskItemsLeaveEscaped("foo;bar;@(compile);@(resource)", ExpanderOptions.ExpandPropertiesAndItems, MockElementLocation.Instance);

            ObjectModelHelpers.AssertItemsMatch(@"
                foo
                bar
                foo.cs
                bar.cs
                bing.resx
                ", GetTaskArrayFromItemList(itemsOut));
        }
Example #39
0
        public void CreateGraphs()
        {
            Simulations sims = CreateTemplate();

            sims.FileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");

            DataStore storage = Apsim.Find(sims, typeof(DataStore)) as DataStore;

            storage.FileName = Path.ChangeExtension(sims.FileName, ".db");

            // Run the file to populate the datastore.
            Runner           runner = new Runner(sims);
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            // Open the .apsimx file in the GUI.
            sims.Write(sims.FileName);
            ExplorerPresenter explorer = UITestsMain.MasterPresenter.OpenApsimXFileInTab(sims.FileName, true);

            GtkUtilities.WaitForGtkEvents();

            // Create a graphs folder under the zone.
            IModel paddock = Apsim.Find(sims, typeof(Zone));
            Folder graphs  = new Folder();

            graphs.Name = "Graphs";

            var command = new AddModelCommand(Apsim.FullPath(paddock),
                                              graphs,
                                              explorer);

            explorer.CommandHistory.Add(command, true);

            // Add an empty graph to the folder.
            Models.Graph graph = new Models.Graph();
            graph.Name = "Graph";
            command    = new AddModelCommand(Apsim.FullPath(graphs),
                                             graph,
                                             explorer);
            explorer.CommandHistory.Add(command, true);

            // Add an empty series to the graph.
            Models.Series series = new Models.Series();
            series.Name = "Series";
            command     = new AddModelCommand(Apsim.FullPath(graph),
                                              series,
                                              explorer);
            explorer.CommandHistory.Add(command, true);

            // click on the series node.
            explorer.SelectNode(Apsim.FullPath(series));
            GtkUtilities.WaitForGtkEvents();

            // Get a reference to the OxyPlot PlotView via reflection.
            SeriesView seriesView = explorer.CurrentRightHandView as SeriesView;
            GraphView  view       = seriesView?.GraphView as GraphView;

            Assert.NotNull(view);

            PlotView plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;

            Assert.NotNull(plot);

            // Series has no table name or x/y series names yet, so there should
            // be nothing shown on the graph.
            Assert.AreEqual(0, plot.Model.Series.Count);

            // Now draw some data on the graph.
            seriesView.DataSource.SelectedValue = "Report";
            seriesView.X.SelectedValue          = "n";
            seriesView.Y.SelectedValue          = "n2";
            seriesView.SeriesType.SelectedValue = "Scatter";

            GtkUtilities.WaitForGtkEvents();

            // There should now be one series showing.
            Assert.AreEqual(1, plot.Model.Series.Count);

            // It should be a line series.
            Assert.True(plot.Model.Series[0] is LineSeries, "Graph series type is set to scatter, but the series object is not a LineSeries.");

            // Series colour should not be white, and should not be the same as the background colour.
            LineSeries line = plot.Model.Series[0] as LineSeries;

            OxyPlot.OxyColor empty = OxyPlot.OxyColor.FromArgb(0, 0, 0, 0);
            OxyPlot.OxyColor white = OxyPlot.OxyColor.FromArgb(0, 255, 255, 255);
            Assert.AreNotEqual(empty, line.Color, "Graph line series default colour is white on white.");
            Assert.AreNotEqual(white, line.Color, "Graph line series default colour is white on white.");

            // Legend should be visible but empty by default.
            Assert.True(plot.Model.IsLegendVisible);
            // todo - ensure legend is empty

            // Next, we want to change the legend position and ensure that the legend actually moves.

            // Click on the 'show in legend' checkbox.
            seriesView.ShowInLegend.IsChecked = true;
            GtkUtilities.WaitForGtkEvents();

            // Double click on the middle of the legend.
            Cairo.Rectangle legendRect = plot.Model.LegendArea.ToRect(true);
            double          x          = (legendRect.X + (legendRect.X + legendRect.Width)) / 2;
            double          y          = (legendRect.Y + (legendRect.Y + legendRect.Height)) / 2;

            GtkUtilities.DoubleClick(plot, x, y, wait: true);

            // Default legend position should be top-left.
            Assert.AreEqual(plot.Model.LegendPosition, OxyPlot.LegendPosition.TopLeft);

            // Now we want to change the legend position. First, get a reference to the legend view
            // via the legend presenter, via the graph presenter, via the series presenter, via the explorer presenter.
            Assert.True(explorer.CurrentPresenter is SeriesPresenter);
            SeriesPresenter seriesPresenter = explorer.CurrentPresenter as SeriesPresenter;
            LegendPresenter legendPresenter = seriesPresenter.GraphPresenter.CurrentPresenter as LegendPresenter;

            // todo: should we add something like a GetView() method to the IPresenter interface?
            // It might be a bit of work to set up but would save us having to use reflection
            LegendView legendView = ReflectionUtilities.GetValueOfFieldOrProperty("view", legendPresenter) as LegendView;

            // The legend options are inside a Gtk expander.
            Assert.IsTrue(legendView.MainWidget.Parent is Expander);
            Expander expander = legendView.MainWidget.Parent as Expander;

            // The expander should be expanded and the options visible.
            Assert.IsTrue(expander.Expanded);
            Assert.IsTrue(legendView.MainWidget.Visible);

            // The legend view contains a combo box with the legend position options (top-right, bottom-left, etc).
            // This should really be refactored to use a public IDropDownView, which is much more convenient to use.
            // First, get a reference to the combo box via reflection.
            ComboBox combo = ReflectionUtilities.GetValueOfFieldOrProperty("combobox1", legendView) as ComboBox;

            // fixme - we should support all valid OxyPlot legend position types.
            foreach (Models.Graph.LegendPositionType legendPosition in Enum.GetValues(typeof(Models.Graph.LegendPositionType)))
            {
                string name = legendPosition.ToString();
                GtkUtilities.SelectComboBoxItem(combo, name, wait: true);

                OxyPlot.LegendPosition oxyPlotEquivalent = (OxyPlot.LegendPosition)Enum.Parse(typeof(OxyPlot.LegendPosition), name);
                Assert.AreEqual(plot.Model.LegendPosition, oxyPlotEquivalent);
            }

            // If we change the graph to a box plot then the several unused properties should be disabled.
            // These are x variable dropdown, x cumulative, x on top, marker size/type checkboxes.

            // First, make sure that these options are sensitive to input and can be changed.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);

            // Now change series type to box plot.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Box", wait: true);
            Assert.AreEqual(SeriesType.Box, series.Type);

            // Ensure the box plot is not white in light theme.
            plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;
            Assert.NotNull(plot);
            BoxPlotSeries boxPlot = plot.Model.Series.OfType <BoxPlotSeries>().FirstOrDefault();

            Assert.NotNull(boxPlot);

            Assert.AreNotEqual(empty, boxPlot.Fill);
            Assert.AreNotEqual(white, boxPlot.Fill);
            Assert.AreNotEqual(empty, boxPlot.Stroke);
            Assert.AreNotEqual(white, boxPlot.Stroke);

            // The controls should no longer be sensitive.
            Assert.IsFalse(seriesView.XCumulative.IsSensitive);
            Assert.IsFalse(seriesView.XOnTop.IsSensitive);
            Assert.IsFalse(seriesView.MarkerSize.IsSensitive);
            Assert.IsFalse(seriesView.MarkerType.IsSensitive);

            // Change the series type back to scatter.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Scatter", wait: true);

            // The controls should be sensitive once more.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);
        }
        public void InitWindowContent(Project project, params Expander[] expanders)
        {
            var functionsExpander     = expanders[0];
            var featuresExpander      = expanders[1];
            var extraFeaturesExpander = expanders[2];

            this.Project = project;
            this.EquipmentList
                = new ObservableCollection <Equipment>(project.EquipmentList);
            this.Materials
                = new ObservableCollection <Material>(project.Materials);
            this.Positions
                = new ObservableCollection <Position>(project.Positions);

            this.Marks
                = new ObservableCollection <Mark>(project.Marks);
            this.TechnicalParameters
                     = new ObservableCollection <TechnicalParameter>(project.TechnicalParameters);
            Estimate = new Estimate();

            ProjectRepository pr             = new ProjectRepository(Context);
            Thickness         checkBoxMargin = new Thickness(20, 0, 0, 0);

            var        functionsList       = pr.GetAllFunctions().GroupBy(f => f.CategoryId).OrderBy(g => g.Key);
            StackPanel functionsStackPanel = functionsExpander.Content as StackPanel;

            foreach (var group in functionsList)
            {
                Expander expander = new Expander();
                expander.Header    = functionCategoryDictionary[group.Key];
                expander.Expanded += Parent.functionExpander_Expanded;
                StackPanel stkPanel = new StackPanel();
                foreach (var f in group)
                {
                    FunctionChecker funcChecker = new FunctionChecker(this, f, Project.Functions.Contains(f));
                    CheckBox        chBox       = new CheckBox()
                    {
                        DataContext = funcChecker, Margin = checkBoxMargin
                    };
                    chBox.SetBinding(CheckBox.IsCheckedProperty, "IsChecked");
                    chBox.SetBinding(CheckBox.ContentProperty, "Item.Title");
                    stkPanel.Children.Add(chBox);
                }
                expander.Content = stkPanel;

                functionsStackPanel.Children.Add(expander);
            }
            functionsExpander.Content = functionsStackPanel;

            var        featuresList       = pr.GetAllFeatures().GroupBy(f => f.Category).OrderBy(g => g.Key);
            StackPanel featuresStackPanel = featuresExpander.Content as StackPanel;

            foreach (var group in featuresList)
            {
                Expander expander = new Expander();
                expander.Header    = featureCategoryDictionary[group.Key];
                expander.Expanded += Parent.functionExpander_Expanded;
                StackPanel stkPanel = new StackPanel();
                foreach (var f in group)
                {
                    FeatureChecker featChecker = new FeatureChecker(this, f, Project.Features.Contains(f));
                    CheckBox       chBox       = new CheckBox()
                    {
                        DataContext = featChecker, Margin = checkBoxMargin
                    };
                    chBox.SetBinding(CheckBox.IsCheckedProperty, "IsChecked");
                    chBox.SetBinding(CheckBox.ContentProperty, "Item.Title");
                    stkPanel.Children.Add(chBox);
                }
                expander.Content = stkPanel;

                featuresStackPanel.Children.Add(expander);
            }
            featuresExpander.Content = featuresStackPanel;

            var        extraFeaturesList       = pr.GetAllExtraFeatures().OrderBy(ef => ef.Id);
            StackPanel extraFeaturesStackPanel = extraFeaturesExpander.Content as StackPanel;

            foreach (var f in extraFeaturesList)
            {
                ExtraFeatureChecker extraFeatChecker = new ExtraFeatureChecker(this, f, Project.ExtraFeatures.Contains(f));
                CheckBox            chBox            = new CheckBox()
                {
                    DataContext = extraFeatChecker, Margin = checkBoxMargin
                };
                chBox.SetBinding(CheckBox.IsCheckedProperty, "IsChecked");
                chBox.SetBinding(CheckBox.ContentProperty, "Item.Title");
                extraFeaturesStackPanel.Children.Add(chBox);
            }
            extraFeaturesExpander.Content = extraFeaturesStackPanel;
        }
Example #41
0
        /// <summary>
        /// Reads the settings for a specified tools version
        /// </summary>
        private Toolset ReadToolset
        (
            ToolsetPropertyDefinition toolsVersion,
            PropertyDictionary <ProjectPropertyInstance> globalProperties,
            PropertyDictionary <ProjectPropertyInstance> initialProperties,
            bool accumulateProperties
        )
        {
            // Initial properties is the set of properties we're going to use to expand property expressions like $(foo)
            // in the values we read out of the registry or config file. We'll add to it as we pick up properties (including binpath)
            // from the registry or config file, so that properties there can be referenced in values below them.
            // After processing all the properties, we don't need initialProperties anymore.
            string toolsPath = null;
            string binPath   = null;
            PropertyDictionary <ProjectPropertyInstance> properties = new PropertyDictionary <ProjectPropertyInstance>();

            IEnumerable <ToolsetPropertyDefinition> rawProperties = GetPropertyDefinitions(toolsVersion.Name);

            Expander <ProjectPropertyInstance, ProjectItemInstance> expander = new Expander <ProjectPropertyInstance, ProjectItemInstance>(initialProperties, FileSystems.Default);

            foreach (ToolsetPropertyDefinition property in rawProperties)
            {
                EvaluateAndSetProperty(property, properties, globalProperties, initialProperties, accumulateProperties, ref toolsPath, ref binPath, ref expander);
            }

            Dictionary <string, SubToolset> subToolsets        = new Dictionary <string, SubToolset>(StringComparer.OrdinalIgnoreCase);
            IEnumerable <string>            subToolsetVersions = GetSubToolsetVersions(toolsVersion.Name);

            foreach (string subToolsetVersion in subToolsetVersions)
            {
                string subToolsetToolsPath = null;
                string subToolsetBinPath   = null;
                IEnumerable <ToolsetPropertyDefinition>      rawSubToolsetProperties = GetSubToolsetPropertyDefinitions(toolsVersion.Name, subToolsetVersion);
                PropertyDictionary <ProjectPropertyInstance> subToolsetProperties    = new PropertyDictionary <ProjectPropertyInstance>();

                // If we have a sub-toolset, any values defined here will override the toolset properties.
                foreach (ToolsetPropertyDefinition property in rawSubToolsetProperties)
                {
                    EvaluateAndSetProperty(property, subToolsetProperties, globalProperties, initialProperties, false /* do not ever accumulate sub-toolset properties */, ref subToolsetToolsPath, ref subToolsetBinPath, ref expander);
                }

                if (subToolsetToolsPath != null || subToolsetBinPath != null)
                {
                    InvalidToolsetDefinitionException.Throw("MSBuildToolsPathNotSupportedInSubToolsets", toolsVersion.Name, toolsVersion.Source.LocationString, subToolsetVersion);
                }

                subToolsets[subToolsetVersion] = new SubToolset(subToolsetVersion, subToolsetProperties);
            }

            // All tools versions must specify a value for MSBuildToolsPath (or MSBuildBinPath)
            if (String.IsNullOrEmpty(toolsPath) && String.IsNullOrEmpty(binPath))
            {
                return(null);
            }

            // If both MSBuildBinPath and MSBuildToolsPath are present, they must be the same
            if (toolsPath != null && binPath != null && !toolsPath.Equals(binPath, StringComparison.OrdinalIgnoreCase))
            {
                InvalidToolsetDefinitionException.Throw("ConflictingValuesOfMSBuildToolsPath", toolsVersion.Name, toolsVersion.Source.LocationString);
            }

            AppendStandardProperties(properties, globalProperties, toolsVersion.Name, null, toolsPath);
            Toolset toolset = null;

            try
            {
                var importSearchPathsTable = GetProjectImportSearchPathsTable(toolsVersion.Name, NativeMethodsShared.GetOSNameForExtensionsPath());
                toolset = new Toolset(toolsVersion.Name, toolsPath == null ? binPath : toolsPath, properties, _environmentProperties, globalProperties, subToolsets, MSBuildOverrideTasksPath, DefaultOverrideToolsVersion, importSearchPathsTable);
            }
            catch (ArgumentException e)
            {
                InvalidToolsetDefinitionException.Throw("ErrorCreatingToolset", toolsVersion.Name, e.Message);
            }

            return(toolset);
        }
Example #42
0
        static bool EvaluateCondition(ProjectElement element, ExpanderOptions expanderOptions, ParserOptions parserOptions, Expander <P, I> expander, LazyItemEvaluator <P, I, M, D> lazyEvaluator)
        {
            if (element.Condition.Length == 0)
            {
                return(true);
            }

            bool result = ConditionEvaluator.EvaluateCondition
                          (
                element.Condition,
                parserOptions,
                expander,
                expanderOptions,
                GetCurrentDirectoryForConditionEvaluation(element, lazyEvaluator),
                element.ConditionLocation,
                lazyEvaluator._loggingService,
                lazyEvaluator._buildEventContext
                          );

            return(result);
        }
        void AddRuleWithData(WrapPanel parentStackPanel, int ruleIndex, ScrubRule scrubRule = null)
        {
            StackPanel RuleHeadersp = new StackPanel();

            RuleHeadersp.Orientation = Orientation.Horizontal;

            TextBlock HeaderTB = new TextBlock();

            HeaderTB.Text = "Rule " + (ruleIndex);

            Label RuleIdLabel = new Label();

            RuleIdLabel.Content    = ruleIndex;
            RuleIdLabel.Visibility = Visibility.Hidden;

            Button DeleteBtn = new Button();

            DeleteBtn.Name = "btnDelete_" + ruleIndex;
            DeleteBtn.HorizontalAlignment = HorizontalAlignment.Right;
            //DeleteBtn.Content = "Delete";
            DeleteBtn.Margin  = new Thickness(265, 0, 0, 0);
            DeleteBtn.Click  += DeleteBtn_Click;
            DeleteBtn.Content = new Image
            {
                Source            = new BitmapImage(new Uri("/Images/closeIcon.png", UriKind.Relative)),
                VerticalAlignment = VerticalAlignment.Center
            };

            RuleHeadersp.Children.Add(HeaderTB);
            RuleHeadersp.Children.Add(DeleteBtn);

            Expander exp = new Expander();

            exp.Header = RuleHeadersp;
            exp.HorizontalAlignment = HorizontalAlignment.Left;
            exp.Margin          = new Thickness(20, 30, 0, 0);
            exp.BorderThickness = new Thickness(1, 1, 1, 1);
            exp.Width           = 350;
            exp.BorderBrush     = Brushes.Gray;
            exp.Background      = Brushes.White;
            exp.IsExpanded      = true;
            exp.Name            = "RuleExpander_" + ruleIndex;

            StackPanel sp = new StackPanel();

            sp.Orientation = Orientation.Vertical;
            sp.Margin      = new Thickness(20, 5, 0, 0);

            StackPanel filterSP = new StackPanel();

            filterSP.Orientation = Orientation.Horizontal;
            filterSP.Margin      = new Thickness(0, 5, 0, 2);

            StackPanel attributeSP = new StackPanel();

            attributeSP.Orientation = Orientation.Horizontal;
            attributeSP.Margin      = new Thickness(0, 5, 0, 2);

            StackPanel scrubTypeSP = new StackPanel();

            scrubTypeSP.Orientation = Orientation.Horizontal;
            scrubTypeSP.Margin      = new Thickness(0, 5, 0, 2);

            StackPanel findValueSP = new StackPanel();

            findValueSP.Orientation = Orientation.Horizontal;
            findValueSP.Margin      = new Thickness(0, 5, 0, 2);

            StackPanel scrubValueSP = new StackPanel();

            scrubValueSP.Orientation = Orientation.Horizontal;
            scrubValueSP.Margin      = new Thickness(0, 5, 0, 2);

            TextBlock FilterLabel = new TextBlock();

            FilterLabel.VerticalAlignment = VerticalAlignment.Center;
            FilterLabel.Margin            = new Thickness(10, 0, 0, 0);
            //FilterLabel.MaxWidth = 150;

            Run runFilterLabel = new Run();

            runFilterLabel.Text     = "Filter Query";
            runFilterLabel.FontSize = 15;

            Run runFilterLabelHint = new Run();

            runFilterLabelHint.Text     = " \nEx: c.Type = \"document\"";
            runFilterLabelHint.FontSize = 10;

            FilterLabel.Inlines.Add(runFilterLabel);
            FilterLabel.Inlines.Add(runFilterLabelHint);

            TextBox FilterTB = new TextBox();

            FilterTB.Name  = "Filter" + ruleIndex;
            FilterTB.Width = 150;
            FilterTB.HorizontalContentAlignment = HorizontalAlignment.Left;
            FilterTB.VerticalAlignment          = VerticalAlignment.Center;
            FilterTB.Margin = new Thickness(20, 0, 0, 0);

            TextBlock AttributeScrubLabel = new TextBlock();

            AttributeScrubLabel.VerticalAlignment = VerticalAlignment.Center;
            AttributeScrubLabel.Margin            = new Thickness(10, 0, 0, 0);
            //AttributeScrubLabel.Width = 120;

            Run runAttributeScrubLabel = new Run();

            runAttributeScrubLabel.Text     = "Attribute To Scrub";
            runAttributeScrubLabel.FontSize = 15;

            Run runAttributeScrubLabelHint = new Run();

            runAttributeScrubLabelHint.Text     = " \nEx: c.Person.Email";
            runAttributeScrubLabelHint.FontSize = 10;

            AttributeScrubLabel.Inlines.Add(runAttributeScrubLabel);
            AttributeScrubLabel.Inlines.Add(runAttributeScrubLabelHint);

            TextBox AttributeScrubTB = new TextBox();

            AttributeScrubTB.Name  = "ScrubAttribute" + ruleIndex;
            AttributeScrubTB.Width = 150;
            AttributeScrubTB.HorizontalContentAlignment = HorizontalAlignment.Left;
            AttributeScrubTB.VerticalAlignment          = VerticalAlignment.Center;
            AttributeScrubTB.Margin = new Thickness(20, 0, 0, 0);

            TextBlock ScrubTypeLabel = new TextBlock();

            ScrubTypeLabel.Text              = "Scrub Type";
            ScrubTypeLabel.FontSize          = 15;
            ScrubTypeLabel.VerticalAlignment = VerticalAlignment.Center;
            ScrubTypeLabel.Margin            = new Thickness(10, 0, 0, 0);

            ComboBox ScrubTypeCB = new ComboBox();

            ScrubTypeCB.Name   = "ScrubType" + ruleIndex;
            ScrubTypeCB.Width  = 150;
            ScrubTypeCB.Margin = new Thickness(20, 0, 0, 0);

            foreach (RuleType val in Enum.GetValues(typeof(RuleType)))
            {
                ScrubTypeCB.Items.Add(val.ToString());
            }

            ScrubTypeCB.SelectionChanged += new SelectionChangedEventHandler(scrubTypeComboBox_SelectedIndexChanged);

            TextBlock FindValueLabel = new TextBlock();

            FindValueLabel.Text              = "Find";
            FindValueLabel.FontSize          = 15;
            FindValueLabel.VerticalAlignment = VerticalAlignment.Center;
            FindValueLabel.Margin            = new Thickness(10, 0, 0, 5);

            TextBox FindValueTB = new TextBox();

            FindValueTB.Name  = "FindValue" + ruleIndex;
            FindValueTB.Width = 150;
            FindValueTB.HorizontalContentAlignment = HorizontalAlignment.Left;
            FindValueTB.VerticalAlignment          = VerticalAlignment.Center;
            FindValueTB.Margin = new Thickness(20, 0, 0, 0);

            TextBlock ScrubValueLabel = new TextBlock();

            ScrubValueLabel.Text              = "Replace with";
            ScrubValueLabel.FontSize          = 15;
            ScrubValueLabel.VerticalAlignment = VerticalAlignment.Center;
            ScrubValueLabel.Margin            = new Thickness(10, 0, 0, 5);

            TextBox ScrubValueTB = new TextBox();

            ScrubValueTB.Name  = "ScrubValue" + ruleIndex;
            ScrubValueTB.Width = 150;
            ScrubValueTB.HorizontalContentAlignment = HorizontalAlignment.Left;
            ScrubValueTB.VerticalAlignment          = VerticalAlignment.Center;
            ScrubValueTB.Margin = new Thickness(20, 0, 0, 0);

            FilterLabel.Width         = 120;
            FilterTB.Width            = 150;
            AttributeScrubLabel.Width = 120;
            AttributeScrubTB.Width    = 150;
            ScrubTypeLabel.Width      = 120;
            ScrubTypeCB.Width         = 150;
            ScrubValueLabel.Width     = 120;
            FindValueTB.Width         = 150;
            FindValueLabel.Width      = 120;

            filterSP.Children.Add(FilterLabel);
            filterSP.Children.Add(FilterTB);

            attributeSP.Children.Add(AttributeScrubLabel);
            attributeSP.Children.Add(AttributeScrubTB);

            scrubTypeSP.Children.Add(ScrubTypeLabel);
            scrubTypeSP.Children.Add(ScrubTypeCB);

            findValueSP.Children.Add(FindValueLabel);
            findValueSP.Children.Add(FindValueTB);
            findValueSP.Visibility = Visibility.Collapsed;

            scrubValueSP.Children.Add(ScrubValueLabel);
            scrubValueSP.Children.Add(ScrubValueTB);
            scrubValueSP.Children.Add(RuleIdLabel);
            scrubValueSP.Visibility = Visibility.Hidden;

            sp.Children.Add(attributeSP);
            sp.Children.Add(filterSP);
            sp.Children.Add(scrubTypeSP);
            sp.Children.Add(findValueSP);
            sp.Children.Add(scrubValueSP);

            exp.Content = sp;

            if (scrubRule != null)
            {
                FilterTB.Text         = scrubRule.FilterCondition;
                AttributeScrubTB.Text = scrubRule.PropertyName;
                if (scrubRule.Type != null)
                {
                    ScrubTypeCB.SelectedIndex = (int)scrubRule.Type;
                }
                ScrubValueTB.Text = scrubRule.UpdateValue;
                FindValueTB.Text  = scrubRule.FindValue;
            }
            parentStackPanel.Children.Add(exp);
            if (!SaveRuleButton.IsEnabled)
            {
                SaveRuleButton.IsEnabled = true;
            }
        }
 /// <summary>
 /// Generic tree search. See page 72 in Russell and Norvig
 /// </summary>
 protected override void AddNodes(IQueue <T> fringe, T node, ISearchProblem <A, S, C> problem)
 {
     fringe.AddRange(Expander.Expand(problem, node));
 }
Example #45
0
        /// <summary>
        /// Builds this target if it has not already been built as part of its parent project. Before we actually execute the
        /// tasks for this target, though, we first call on all the dependent targets to build themselves.
        /// This function may throw InvalidProjectFileException
        /// </summary>
        internal void Build
        (
            ProjectBuildState buildContext
        )
        {
            // Depending on the build state, we may do different things.
            switch (buildState)
            {
            case BuildState.InProgress:
                // In single proc mode if the build state was already "in progress"
                // and somebody just told us to build ourselves, it means that there is
                // a loop (circular dependency) in the target dependency graph. In multi
                // proc mode we need to analyze the dependency graph before we can
                // tell if there a circular dependency or if two independent chains
                // of targets happen to need the result of this target.
                if (parentEngine.Router.SingleThreadedMode || buildContext.ContainsCycle(this.Name))
                {
                    ProjectErrorUtilities.VerifyThrowInvalidProject(false, TargetElement, "CircularDependency", targetName);
                }
                else
                {
                    buildContext.CurrentBuildContextState = ProjectBuildState.BuildContextState.WaitingForTarget;
                    this.executionState.AddWaitingBuildContext(buildContext);
                }
                break;

            case BuildState.CompletedSuccessfully:
            case BuildState.CompletedUnsuccessfully:
                // If this target has already been built as part of this project,
                // we're not going to build it again.  Just return the result
                // from when it was built previously.  Note:  This condition
                // could really only ever hold true if the user specifically
                // requested us to build multiple targets and there existed
                // a direct or indirect dependency relationship between two or
                // more of those top-level targets.
                // Note: we aren't really entering the target in question here, so don't use the target
                // event context. Using the target ID for skipped messages would force us to
                // cache the individual target IDs for unloaded projects and it's not really worth the trouble.
                // Just use the parent event context.
                parentEngine.LoggingServices.LogComment(buildContext.ProjectBuildEventContext,
                                                        ((buildState == BuildState.CompletedSuccessfully) ? "TargetAlreadyCompleteSuccess" : "TargetAlreadyCompleteFailure"),
                                                        this.targetName);

                // Only contexts which are generated from an MSBuild task could need
                // the outputs of this target, such contexts have a non-null evaluation
                // request
                if ((buildState == BuildState.CompletedSuccessfully) &&
                    (buildContext.BuildRequest.OutputsByTarget != null &&
                     buildContext.NameOfBlockingTarget == null))
                {
                    error.VerifyThrow(
                        String.Compare(EscapingUtilities.UnescapeAll(buildContext.NameOfTargetInProgress), this.Name, StringComparison.OrdinalIgnoreCase) == 0,
                        "The name of the target in progress is inconsistent with the target being built");

                    error.VerifyThrow(targetOutputItems != null,
                                      "If the target built successfully, we must have its outputs.");

                    buildContext.BuildRequest.OutputsByTarget[Name] = targetOutputItems.ToArray();
                }

                if (buildContext.NameOfBlockingTarget == null)
                {
                    buildContext.BuildRequest.ResultByTarget[Name] = buildState;
                }
                break;

            case BuildState.NotStarted:
            case BuildState.Skipped:
            {
                // Always have to create a new context in build as other projects or targets may try and build this target
                BuildEventContext targetBuildEventContext = new BuildEventContext
                                                            (
                    buildContext.ProjectBuildEventContext.NodeId,
                    this.id,
                    buildContext.ProjectBuildEventContext.ProjectContextId,
                    buildContext.ProjectBuildEventContext.TaskId
                                                            );

                Expander expander = new Expander(this.parentProject.evaluatedProperties, this.parentProject.evaluatedItemsByName);

                // We first make sure no batching was attempted with the target's condition.
                if (!conditionCheckedForInvalidMetadataReferences)
                {
                    if (ExpressionShredder.ContainsMetadataExpressionOutsideTransform(this.Condition))
                    {
                        ProjectErrorUtilities.ThrowInvalidProject(this.conditionAttribute, "TargetConditionHasInvalidMetadataReference", targetName, this.Condition);
                    }
                    conditionCheckedForInvalidMetadataReferences = true;
                }

                // If condition is false (based on propertyBag), set this target's state to
                // "Skipped" since we won't actually build it.
                if (!Utilities.EvaluateCondition(this.Condition, this.conditionAttribute,
                                                 expander, null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists,
                                                 parentEngine.LoggingServices, targetBuildEventContext))
                {
                    buildState = BuildState.Skipped;

                    if (buildContext.NameOfBlockingTarget == null)
                    {
                        buildContext.BuildRequest.ResultByTarget[Name] = buildState;
                    }

                    if (!parentEngine.LoggingServices.OnlyLogCriticalEvents)
                    {
                        // Expand the expression for the Log.
                        string expanded = expander.ExpandAllIntoString(this.Condition, this.conditionAttribute);
                        // By design: Not building dependencies. This is what NAnt does too.
                        parentEngine.LoggingServices.LogComment(targetBuildEventContext, "TargetSkippedFalseCondition",
                                                                this.targetName, this.Condition, expanded);
                    }
                }
                else
                {
                    // This target has not been built yet.  So build it!
                    // Change our state to "in progress". TargetParameters will need to be re-calculated if Inputs and Outputs attribute has changed.
                    buildState = BuildState.InProgress;
                    List <string> batchableTargetParameters = GetBatchableTargetParameters();
                    executionState = new TargetExecutionWrapper(this, taskElementList, batchableTargetParameters, targetElement, expander, targetBuildEventContext);
                    ContinueBuild(buildContext, null);
                }
            }
            break;

            default:
                error.VerifyThrow(false, "Build state {0} not handled in Target.Build method", buildState);
                break;
            }
        }
Example #46
0
        private List <ItemSpecFragment> BuildItemFragments(IElementLocation itemSpecLocation, string projectDirectory, bool expandProperties)
        {
            //  Code corresponds to Evaluator.CreateItemsFromInclude
            var evaluatedItemspecEscaped = ItemSpecString;

            if (string.IsNullOrEmpty(evaluatedItemspecEscaped))
            {
                return(new List <ItemSpecFragment>());
            }

            // STEP 1: Expand properties in Include
            if (expandProperties)
            {
                evaluatedItemspecEscaped = Expander.ExpandIntoStringLeaveEscaped(
                    ItemSpecString,
                    ExpanderOptions.ExpandProperties,
                    itemSpecLocation);
            }

            var semicolonCount = 0;

            foreach (var c in evaluatedItemspecEscaped)
            {
                if (c == ';')
                {
                    semicolonCount++;
                }
            }

            // estimate the number of fragments with the number of semicolons. This is will overestimate in case of transforms with semicolons, but won't underestimate.
            var fragments = new List <ItemSpecFragment>(semicolonCount + 1);

            // STEP 2: Split Include on any semicolons, and take each split in turn
            if (evaluatedItemspecEscaped.Length > 0)
            {
                var splitsEscaped = ExpressionShredder.SplitSemiColonSeparatedList(evaluatedItemspecEscaped);

                foreach (var splitEscaped in splitsEscaped)
                {
                    // STEP 3: If expression is "@(x)" copy specified list with its metadata, otherwise just treat as string
                    var itemReferenceFragment = ProcessItemExpression(
                        splitEscaped,
                        itemSpecLocation,
                        projectDirectory,
                        out var isItemListExpression);

                    if (isItemListExpression)
                    {
                        fragments.Add(itemReferenceFragment);
                    }
                    else
                    {
                        // The expression is not of the form "@(X)". Treat as string

                        //  Code corresponds to EngineFileUtilities.GetFileList
                        var containsEscapedWildcards = EscapingUtilities.ContainsEscapedWildcards(splitEscaped);
                        var containsRealWildcards    = FileMatcher.HasWildcards(splitEscaped);

                        // '*' is an illegal character to have in a filename.
                        // todo: file-system assumption on legal path characters: https://github.com/Microsoft/msbuild/issues/781
                        if (containsEscapedWildcards && containsRealWildcards)
                        {
                            // Just return the original string.
                            fragments.Add(new ValueFragment(splitEscaped, projectDirectory));
                        }
                        else if (!containsEscapedWildcards && containsRealWildcards)
                        {
                            // Unescape before handing it to the filesystem.
                            var filespecUnescaped = EscapingUtilities.UnescapeAll(splitEscaped);

                            fragments.Add(new GlobFragment(filespecUnescaped, projectDirectory));
                        }
                        else
                        {
                            // No real wildcards means we just return the original string.  Don't even bother
                            // escaping ... it should already be escaped appropriately since it came directly
                            // from the project file

                            fragments.Add(new ValueFragment(splitEscaped, projectDirectory));
                        }
                    }
                }
            }

            return(fragments);
        }
Example #47
0
        public void PropertyFunctionDoesTaskHostExist_Error()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

                Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('ASDF', 'CurrentArchitecture'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                // We should have failed before now
                Assert.True(false);
            }
           );
        }
Example #48
0
        private void DesenhandoInformaçoes(List <string> resultado)
        {
            //StackPanel que guardará o icone e a key da licença
            StackPanel hed = new StackPanel()
            {
                Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Left
            };
            //Icon que guardará a messagem de como deletar a lic
            PackIcon icon = new PackIcon()
            {
                Kind = PackIconKind.InfoCircle, Margin = new Thickness(5), VerticalAlignment = VerticalAlignment.Center, ToolTip = "Clique dentro do Card que deseja remover a licença!"
            };

            //adicionando icon no stack
            _ = hed.Children.Add(icon);
            //adicionando key da lic no stack
            _ = hed.Children.Add(new TextBlock {
                Text = resultado[2], VerticalAlignment = VerticalAlignment.Center
            });
            //icone de copiar
            PackIcon ic = new PackIcon()
            {
                Kind = PackIconKind.ContentCopy, Height = 15, Width = 15, ToolTip = resultado[2]
            };

            ToolTipService.SetIsEnabled(ic, false);
            //criando botao que copiará a licença.
            Button copy = new Button {
                Margin = new Thickness(10, 0, 0, 0), Width = 20, Height = 20, ToolTip = "Copiar", VerticalAlignment = VerticalAlignment.Center, Content = ic
            };

            //adicioando style Icon no botao
            copy.SetResourceReference(StyleProperty, "MaterialDesignIconButton");
            //evento de click do botao
            copy.Click += Copy_Click;
            //adicionando botao de copiar no stack
            _ = hed.Children.Add(copy);
            //criando o Expander que conterá as informaçoes da licença
            Expander ex = new Expander()
            {
                IsExpanded = true, Margin = new Thickness(5), Background = null, FontFamily = new FontFamily("Consolas"), FontSize = 12
            };

            //adicionando o stack na proriedade Header (titulo, cabeçario) do expander.
            ex.Header = hed;
            //setando resource no expander, para que quando for mudado o theme do programa, a cor da fonte será a inversa
            ex.SetResourceReference(ForegroundProperty, "MaterialDesignBody");
            //stack que agrupará o clientCode e o pluginCode|GlobalLic
            StackPanel st1 = new StackPanel()
            {
                Orientation = Orientation.Vertical, Margin = new Thickness(10)
            };

            //adicionando mensagem do codigo do cliente
            _ = st1.Children.Add(new TextBlock()
            {
                Text = $"Codigo cliente: {resultado[0]}", Margin = new Thickness(5)
            });
            //adicionando mensagem do codigo do plugin ou licença global
            _ = st1.Children.Add(new TextBlock()
            {
                Text = Convert.ToBoolean(resultado[3]).Equals(false) ? $"Codigo plugin: {resultado[1]}" : "Licença Global", Margin = new Thickness(5)
            });
            //stack que agrupará a data, hora e se está suspenso.
            StackPanel st2 = new StackPanel()
            {
                Orientation = Orientation.Vertical, Margin = new Thickness(10)
            };

            //adicionando data e hora
            _ = st2.Children.Add(new TextBlock()
            {
                Text = $"Data criaçao: {resultado[4].Substring(0, 10)} as {resultado[5]}", Margin = new Thickness(5)
            });
            //adicionando suspensao!.
            _ = st2.Children.Add(new TextBlock()
            {
                Text = $"Suspensa: {(Convert.ToBoolean(resultado[6]) ? "Sim" : "Nao")}", Margin = new Thickness(5)
            });
            //adicionando {st1} e {st2} dentro de um wrap para o texto ficar responsivo.
            WrapPanel geralWrap = new WrapPanel();

            _ = geralWrap.Children.Add(st1);
            _ = geralWrap.Children.Add(st2);
            StackPanel geralStack = new StackPanel();

            _ = geralStack.Children.Add(geralWrap);//Adicionando ip do servidor nas informaçoes.
            _ = geralStack.Children.Add(new TextBlock()
            {
                TextWrapping = TextWrapping.Wrap, Text = $"Servidor: {resultado[7]}", Margin = new Thickness(15, 0, 5, 5)
            });
            //adicionando o wrap dentro da propriedade content do expander, ou seja, será as informaçoes da licença ali dentro.
            ex.Content = geralStack;
            //criando card que terá o expander dentro, este elemento so serve para o expander ficar bunito '-'
            Card card = new Card()
            {
                Margin = new Thickness(5)
            };

            //envento de MouseDown (ao clicar no Card) para poder aplicar na deleçao da lic
            card.MouseDown += Card_MouseDown;
            //adicionando o expander dentro do card
            card.Content = ex;
            //adicionando o card dentro do Stack que foi criado na View, onde conterá todas as licenças(cards) que foram mostradas, e tbm para poder exclui-los.
            _ = ListaLicencas_sp.Children.Add(card);
        }
Example #49
0
        public void PropertyFunctionDoesTaskHostExist_NonexistentTaskHost()
        {
            string taskHostName = Environment.GetEnvironmentVariable("MSBUILDTASKHOST_EXE_NAME");
            try
            {
                Environment.SetEnvironmentVariable("MSBUILDTASKHOST_EXE_NAME", "asdfghjkl.exe");
                NodeProviderOutOfProcTaskHost.ClearCachedTaskHostPaths();

                PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

                Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::DoesTaskHostExist('CLR2', 'CurrentArchitecture'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                // CLR has been forced to pretend not to exist, whether it actually does or not
                Assert.True(String.Equals("false", result, StringComparison.OrdinalIgnoreCase));
            }
            finally
            {
                Environment.SetEnvironmentVariable("MSBUILDTASKHOST_EXE_NAME", taskHostName);
                NodeProviderOutOfProcTaskHost.ClearCachedTaskHostPaths();
            }
        }
Example #50
0
        void LoadUpdates(List <Update> updates)
        {
            if (updates == null || updates.Count == 0)
            {
                SetMessage(GettextCatalog.GetString("No updates available"));
                return;
            }

            foreach (var c in productBox.Children)
            {
                productBox.Remove(c);
                c.Destroy();
            }

            productBox.Spacing = 0;

            foreach (var update in updates)
            {
                var updateBox = new VBox()
                {
                    Spacing = 2
                };
                var labelBox = new HBox();
                updateBox.PackStart(labelBox, false, false, 0);

                string warning = null;
                switch (update.Level)
                {
                case UpdateLevel.Alpha:
                    warning = GettextCatalog.GetString("ALPHA");
                    break;

                case UpdateLevel.Beta:
                    warning = GettextCatalog.GetString("BETA");
                    break;

                case UpdateLevel.Test:
                    warning = GettextCatalog.GetString("TEST");
                    break;
                }
                if (warning != null)
                {
                    warning = "<b><span color=\"#DD1111\">" + warning + "</span></b>";
                }

                var updateExpander = new Expander("");
                updateExpander.LabelWidget = new Label()
                {
                    Markup = string.Format("<b>{0}</b>\n{1} ({2:yyyy-MM-dd}) {3}", update.Name, update.Version, update.Date,
                                           warning ?? ""),
                };
                labelBox.PackStart(updateExpander, true, true, 0);

                var downloadButton = new Button()
                {
                    Label = GettextCatalog.GetString("Download")
                };

                //NOTE: grab the variable from the loop var so the closure captures it
                var url = update.Url;
                downloadButton.Clicked += delegate {
                    DesktopService.ShowUrl(url);
                };
                labelBox.PackStart(downloadButton, false, false, 0);

                var sb = new StringBuilder();
                for (int i = 0; i < update.Releases.Count; i++)
                {
                    var release = update.Releases[i];
                    if (i > 0)
                    {
                        if (i == 1)
                        {
                            sb.AppendLine();
                            sb.AppendLine("This release also includes previous updates:");
                        }
                        sb.AppendLine();
                        sb.AppendFormat("{0} ({1:yyyy-MM-dd})\n", release.Version, release.Date);
                        sb.AppendLine();
                    }
                    sb.Append(release.Notes.Trim('\t', ' ', '\n', '\r'));
                    sb.AppendLine();
                }
                var buffer = new TextBuffer(null);
                buffer.Text = sb.ToString();
                var textView = new TextView(buffer);
                textView.WrapMode   = WrapMode.Word;
                textView.Editable   = false;
                textView.LeftMargin = textView.RightMargin = 4;
                updateBox.PackStart(textView, false, false, 0);

                bool startsExpanded = false;
                updateExpander.Expanded   = startsExpanded;
                updateExpander.Activated += delegate {
                    textView.Visible = updateExpander.Expanded;
                };

                updateBox.BorderWidth = 4;

                productBox.PackStart(updateBox, false, false, 0);
                updateBox.ShowAll();
                //this has to be set false after the ShowAll
                textView.Visible = startsExpanded;


                var sep = new HSeparator();
                productBox.PackStart(sep, false, false, 0);
                sep.Show();
            }

            notebook1.CurrentPage = PAGE_UPDATES;
        }
Example #51
0
        public void PropertyFunctionStaticMethodIntrinsicMaths()
        {
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(39.9, 2.1))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((39.9 + 2.1).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((40 + 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Subtract(44, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((44 - 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Subtract(42.9, 0.9))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((42.9 - 0.9).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Multiply(21, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((21 * 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Multiply(84.0, 0.5))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((84.0 * 0.5).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Divide(84, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((84 / 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Divide(84.4, 2.0))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((84.4 / 2.0).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Modulo(85, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((85 % 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Modulo(2345.5, 43))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((2345.5 % 43).ToString(), result);

            // test for overflow wrapping
            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::Add(9223372036854775807, 20))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            double expectedResult = 9223372036854775807D + 20D;
            Assert.Equal(expectedResult.ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseOr(40, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((40 | 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseAnd(42, 2))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((42 & 2).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseXor(213, 255))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((213 ^ 255).ToString(), result);

            result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::BitwiseNot(-43))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

            Assert.Equal((~-43).ToString(), result);
        }
Example #52
0
        public override void Initialize()
        {
            selectedMealPlan     = new List <MealPlan>(new MealPlan[rooms.Count]);
            selectedWebsitePrice = new List <Tuple <Website, int> >(new Tuple <Website, int> [rooms.Count]);
            int    boxSpacing = 50;
            double cardWidth  = canvas.Width - 0.2 * canvas.Width;
            double cardHeight = 0.7 * canvas.Height;

            canvas.Background = new SolidColorBrush(Color.FromRgb(239, 239, 239));

            ScrollViewer roomScrollViewer = new ScrollViewer
            {
                Height = canvas.Height
            };

            canvas.Children.Add(roomScrollViewer);

            StackPanel roomCardStackPanel = new StackPanel();

            roomScrollViewer.Content = roomCardStackPanel;

            for (int i = 0; i < rooms.Count; i++)
            {
                Room room = rooms[i];

                //creates room card
                Border cardBorder = new Border
                {
                    BorderBrush     = new SolidColorBrush(Color.FromRgb(0, 0, 0)),
                    BorderThickness = new Thickness(3),
                    Width           = cardWidth,
                    Margin          = new Thickness(0.1 * canvas.Width, boxSpacing, 0.1 * canvas.Width, 0)
                };
                Grid roomGrid = new Grid
                {
                    Width = cardWidth,

                    ColumnDefinitions =
                    {
                        new ColumnDefinition {
                            Width = new GridLength(0.4 * cardWidth)
                        },
                        new ColumnDefinition {
                            Width = new GridLength(0.6 * cardWidth)
                        }
                    },
                    RowDefinitions =
                    {
                        new RowDefinition {
                            Height = GridLength.Auto
                        },
                        new RowDefinition {
                            Height = GridLength.Auto
                        }
                    }
                };
                cardBorder.Child = roomGrid;
                roomCardStackPanel.Children.Add(cardBorder);

                //set card image
                Image roomImage = room.image.GetImage();
                roomImage.MaxWidth  = 0.35 * cardWidth;
                roomImage.MaxHeight = 0.85 * cardHeight;
                Grid.SetColumn(roomImage, 0);
                Grid.SetRow(roomImage, 0);
                roomGrid.Children.Add(roomImage);

                //set roomdatastackpanel
                StackPanel roomDataStackPanel = new StackPanel
                {
                    Width  = 0.6 * cardWidth,
                    Height = 0.85 * cardHeight,
                };
                Grid.SetColumn(roomDataStackPanel, 1);
                Grid.SetRow(roomDataStackPanel, 0);
                roomGrid.Children.Add(roomDataStackPanel);

                //set room type
                Label roomTypeLabel = new Label
                {
                    Content  = "Room Type: " + room.type.name,
                    FontSize = 22,
                    Margin   = new Thickness(0, 0.2 * cardHeight, 0, 0)
                };
                roomDataStackPanel.Children.Add(roomTypeLabel);

                //set hotel name
                Label roomHotelLabel = new Label
                {
                    Content  = "Hotel: " + room.hotel.name,
                    FontSize = 22,
                    Margin   = new Thickness(0, 0.05 * cardHeight, 0, 0)
                };
                roomDataStackPanel.Children.Add(roomHotelLabel);

                //set room price
                Label roomPriceLabel = new Label
                {
                    Content  = "Price: ",
                    FontSize = 22,
                    Margin   = new Thickness(0, 0.05 * cardHeight, 0, 0)
                };
                roomDataStackPanel.Children.Add(roomPriceLabel);

                //set view more button
                Grid grid = new Grid
                {
                    ColumnDefinitions =
                    {
                        new ColumnDefinition {
                            Width = new GridLength(0.5 * roomDataStackPanel.Width)
                        },
                        new ColumnDefinition {
                            Width = new GridLength(0.5 * roomDataStackPanel.Width)
                        }
                    },
                    Margin = new Thickness(0, 0.05 * cardHeight, 0, 0)
                };

                Label locationLabel = new Label
                {
                    Content  = "Loaction: " + room.hotel.location.city + ", " + room.hotel.location.country,
                    FontSize = 22,
                };
                Grid.SetColumn(locationLabel, 0);
                grid.Children.Add(locationLabel);

                Button viewMoreButton = FrontEndHelper.CreateButton(cardWidth * 0.1, cardHeight * 0.1, "Reserve");

                Grid.SetColumn(viewMoreButton, 1);
                grid.Children.Add(viewMoreButton);
                roomDataStackPanel.Children.Add(grid);

                //creates view more expander
                Expander viewMoreExpander = new Expander
                {
                    Width  = canvas.Width,
                    Margin = new Thickness(0, 0, 0, 0.05 * cardHeight),
                    Header = "More Data"
                };
                Grid.SetColumnSpan(viewMoreExpander, 2);
                Grid.SetRow(viewMoreExpander, 1);
                roomGrid.Children.Add(viewMoreExpander);

                //creates tabs
                TabControl MoreDetailsTabs = new TabControl();
                viewMoreExpander.Content   = MoreDetailsTabs;
                MoreDetailsTabs.Background = new SolidColorBrush(Color.FromRgb(239, 239, 239));

                //creates meals tab
                TabItem MealsTab = new TabItem {
                    Header = "Meals"
                };
                StackPanel MealsPanel = new StackPanel();
                MealsTab.Content = MealsPanel;
                MoreDetailsTabs.Items.Add(MealsTab);

                for (int j = 0; j < room.hotel.mealPlans.Count; j++)
                {
                    MealPlan    mealPlan            = room.hotel.mealPlans[j];
                    RadioButton mealPlanRadioButton = new RadioButton
                    {
                        GroupName = "MealPlanRadioGroup " + i.ToString(),
                        Content   = mealPlan,
                        FontSize  = 22,
                        Margin    = new Thickness(0, 0.025 * cardHeight, 0, 0)
                    };
                    mealPlanRadioButton.Checked += mealRadioButtonChecked;
                    if (j == 0)
                    {
                        mealPlanRadioButton.IsChecked = true;
                    }
                    MealsPanel.Children.Add(mealPlanRadioButton);
                }

                //creates website and prices tab
                TabItem websitesTab = new TabItem {
                    Header = "Websites"
                };
                StackPanel websitesPanel = new StackPanel();
                websitesTab.Content = websitesPanel;
                MoreDetailsTabs.Items.Add(websitesTab);

                List <Tuple <Website, int> > websitePrice = DataModels.GetInstance().GetWebsitePricesForRoom(room);
                for (int j = 0; j < websitePrice.Count; j++)
                {
                    RadioButton websitePriceRadioButton = new RadioButton
                    {
                        GroupName   = "WebsitePriceRadioGroup " + i.ToString(),
                        DataContext = websitePrice[j],
                        Content     = websitePrice[j].Item1.name + " , " + websitePrice[j].Item2.ToString(),
                        FontSize    = 22,
                        Margin      = new Thickness(0, 0.025 * cardHeight, 0, 0)
                    };
                    websitePriceRadioButton.Checked += webstiePriceRadioButtonChecked;
                    if (j == 0)
                    {
                        websitePriceRadioButton.IsChecked = true;
                    }
                    websitesPanel.Children.Add(websitePriceRadioButton);
                }

                //creates room view tab
                TabItem roomViewsTab = new TabItem {
                    Header = "Views"
                };
                StackPanel roomViewsPanel = new StackPanel();
                roomViewsTab.Content = roomViewsPanel;
                MoreDetailsTabs.Items.Add(roomViewsTab);

                foreach (RoomView view in room.views)
                {
                    Label viewLabel = new Label
                    {
                        Content  = view.view,
                        FontSize = 22,
                        Margin   = new Thickness(0, 0.025 * cardHeight, 0, 0)
                    };
                    roomViewsPanel.Children.Add(viewLabel);
                }

                //create room photos
                TabItem hotelPhotosTab = new TabItem {
                    Header = "Photos"
                };
                Canvas hotelPhotosCanvas = new Canvas
                {
                    Width  = cardWidth,
                    Height = 300
                };
                hotelPhotosTab.Content = hotelPhotosCanvas;
                MoreDetailsTabs.Items.Add(hotelPhotosTab);

                List <CustomImage> images = new List <CustomImage>();
                images.Add(room.hotel.image);
                foreach (HotelFacility facility in room.hotel.facilities)
                {
                    images.Add(facility.image);
                }
                foreach (PlaceOfIntrest placeOfIntrest in room.hotel.location.placesOfIntrest)
                {
                    images.Add(placeOfIntrest.image);
                }
                ImageAlbum hotelAlbum = new ImageAlbum(hotelPhotosCanvas, 25, 25, 250, 250, images);

                //creates room reviews
                TabItem roomReviewsTab = new TabItem {
                    Header = "Room Reviews"
                };
                StackPanel roomReviewsStackPanel = new StackPanel();
                roomReviewsTab.Content = roomReviewsStackPanel;
                MoreDetailsTabs.Items.Add(roomReviewsTab);

                List <Booking> roomBookings = DataModels.GetInstance().GetRoomBookings(room);
                for (int j = 0; j < roomBookings.Count; j++)
                {
                    Booking booking = roomBookings[j];
                    Border  roomBookingCardBorder = new Border
                    {
                        Width               = 0.8 * cardWidth,
                        BorderBrush         = new SolidColorBrush(Color.FromRgb(0, 0, 0)),
                        BorderThickness     = new Thickness(3),
                        HorizontalAlignment = HorizontalAlignment.Left
                    };
                    if (j == roomBookings.Count - 1)
                    {
                        roomBookingCardBorder.Margin = new Thickness(0.1 * cardWidth, 25, 0.1 * cardWidth, 25);
                    }
                    else
                    {
                        roomBookingCardBorder.Margin = new Thickness(0.1 * cardWidth, 25, 0.1 * cardWidth, 0);
                    }
                    StackPanel roomBookingCardPanel = new StackPanel();
                    roomBookingCardBorder.Child = roomBookingCardPanel;
                    roomReviewsStackPanel.Children.Add(roomBookingCardBorder);

                    Label userNameLabel = new Label
                    {
                        Content  = "User Name : " + booking.bookingUser.username,
                        FontSize = 22
                    };
                    roomBookingCardPanel.Children.Add(userNameLabel);

                    Label ratingLabel = new Label
                    {
                        Content  = "Rating : " + booking.bookingReview.rating,
                        FontSize = 22
                    };
                    roomBookingCardPanel.Children.Add(ratingLabel);

                    Label startDateLabel = new Label
                    {
                        Content  = "From " + booking.startDate.ToShortDateString() + " To " + booking.endDate.ToShortDateString(),
                        FontSize = 22
                    };
                    roomBookingCardPanel.Children.Add(startDateLabel);

                    TextBlock description = new TextBlock
                    {
                        Width        = 0.8 * cardWidth - 5,
                        Text         = "Description : " + booking.bookingReview.description,
                        FontSize     = 22,
                        Margin       = new Thickness(0, 0, 0, 10),
                        TextWrapping = TextWrapping.WrapWithOverflow,
                        Padding      = new Thickness(5, 0, 0, 0)
                    };
                    roomBookingCardPanel.Children.Add(description);
                }
            }
        }
Example #53
0
        public void PropertyFunctionGetRegistryValueFromView2()
        {
            try
            {
                PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
                pg.Set(ProjectPropertyInstance.Create("SomeProperty", "Value"));

                Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);
                RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\MSBuild_test");

                key.SetValue(String.Empty, "%TEMP%", RegistryValueKind.ExpandString);
                string result = expander.ExpandIntoStringLeaveEscaped(@"$([MSBuild]::GetRegistryValueFromView('HKEY_CURRENT_USER\Software\Microsoft\MSBuild_test', null, null, Microsoft.Win32.RegistryView.Default))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                Assert.Equal(Environment.GetEnvironmentVariable("TEMP"), result);
            }
            finally
            {
                Registry.CurrentUser.DeleteSubKey(@"Software\Microsoft\MSBuild_test");
            }
        }        /// <summary>
        private void AddTextureMapSelections(string materialName, PhysicallyBasedMaterial physicallyBasedMaterial)
        {
            if (physicallyBasedMaterial == null)
            {
                return;
            }

            var expander = new Expander()
            {
                Header     = materialName,
                Margin     = new Thickness(0, 0, 0, 3),
                IsExpanded = true
            };

            TextureMapsPanel.Children.Add(expander);


            var stackPanel = new StackPanel()
            {
                Orientation = Orientation.Vertical
            };

            expander.Content = stackPanel;


            //if (!string.IsNullOrEmpty(materialName))
            //{
            //    var textBlock = new TextBlock()
            //    {
            //        Text       = materialName,
            //        FontWeight = FontWeights.Bold,
            //        Margin = new Thickness(0, 0, 0, 3)
            //    };

            //    TextureMapsPanel.Children.Add(textBlock);
            //}

            bool   hasDiffuseColor = physicallyBasedMaterial.HasTextureMap(TextureMapTypes.DiffuseColor);
            string baseFolder      = System.IO.Path.GetDirectoryName(_loadedFileName);

            foreach (var supportedTextureMapType in KnownTextureFiles.PBRSupportedTextureMapTypes)
            {
                // Show only one of DiffuseColor or BaseColor (not both)
                // Show DiffuseColor only if there is a texture map defined for it
                if ((supportedTextureMapType == TextureMapTypes.DiffuseColor && !hasDiffuseColor) ||
                    (supportedTextureMapType == TextureMapTypes.BaseColor && hasDiffuseColor))
                {
                    continue;
                }

                var textureMapSelectionControl = new TextureMapSelectionControl(physicallyBasedMaterial, supportedTextureMapType, baseFolder);
                textureMapSelectionControl.Margin = new Thickness(23, 0, 0, 7);

                textureMapSelectionControl.MapSettingsChanged += TextureMapSelectionControlOnMapSettingsChanged;
                textureMapSelectionControl.LayoutTransform     = new ScaleTransform(0.75, 0.75);

                if (MainDXViewportView.DXScene != null)
                {
                    textureMapSelectionControl.DXDevice = MainDXViewportView.DXScene.DXDevice;
                }

                //TextureMapsPanel.Children.Add(textureMapSelectionControl);
                stackPanel.Children.Add(textureMapSelectionControl);
            }
        }
Example #55
0
        public void Medley()
        {
            // Make absolutely sure that the static method cache hasn't been polluted by the other tests.  
            AvailableStaticMethods.Reset_ForUnitTestsOnly();

            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("File", @"foo\file.txt"));

            pg.Set(ProjectPropertyInstance.Create("a", "no"));
            pg.Set(ProjectPropertyInstance.Create("b", "true"));
            pg.Set(ProjectPropertyInstance.Create("c", "1"));
            pg.Set(ProjectPropertyInstance.Create("position", "4"));
            pg.Set(ProjectPropertyInstance.Create("d", "xxx"));
            pg.Set(ProjectPropertyInstance.Create("e", "xxx"));
            pg.Set(ProjectPropertyInstance.Create("and", "and"));
            pg.Set(ProjectPropertyInstance.Create("a_semi_b", "a;b"));
            pg.Set(ProjectPropertyInstance.Create("a_apos_b", "a'b"));
            pg.Set(ProjectPropertyInstance.Create("foo_apos_foo", "foo'foo"));
            pg.Set(ProjectPropertyInstance.Create("a_escapedsemi_b", "a%3bb"));
            pg.Set(ProjectPropertyInstance.Create("a_escapedapos_b", "a%27b"));
            pg.Set(ProjectPropertyInstance.Create("has_trailing_slash", @"foo\"));
            pg.Set(ProjectPropertyInstance.Create("emptystring", @""));
            pg.Set(ProjectPropertyInstance.Create("space", @" "));
            pg.Set(ProjectPropertyInstance.Create("listofthings", @"a;b;c;d;e;f;g;h;i;j;k;l"));
            pg.Set(ProjectPropertyInstance.Create("input", @"EXPORT a"));
            pg.Set(ProjectPropertyInstance.Create("propertycontainingnullasastring", @"null"));

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg);

            string[,] validTests = {
                {"$(input.ToString()[1])", "X"},
                {"$(input[1])", "X"},
                {"$(listofthings.Split(';')[$(position)])","e"},
                {@"$([System.Text.RegularExpressions.Regex]::Match($(Input), `EXPORT\s+(.+)`).Groups[1].Value)","a"},
                {"$([MSBuild]::Add(1,2).CompareTo(3))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo(3))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo(3.0))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo('3'))", "0"},
                {"$([MSBuild]::Add(1,2).CompareTo(3.1))", "-1"},
                {"$([MSBuild]::Add(1,2).CompareTo(2))", "1"},
                {"$([MSBuild]::Add(1,2).Equals(3))", "True"},
                {"$([MSBuild]::Add(1,2).Equals(3.0))", "True"},
                {"$([MSBuild]::Add(1,2).Equals('3'))", "True"},
                {"$([MSBuild]::Add(1,2).Equals(3.1))", "False"},
                {"$(a.Insert(0,'%28'))", "%28no"},
                {"$(a.Insert(0,'\"'))", "\"no"},
                {"$(a.Insert(0,'(('))", "%28%28no"},
                {"$(a.Insert(0,'))'))", "%29%29no"},
                {"A$(Reg:A)A", "AA"},
                {"A$(Reg:AA)", "A"},
                {"$(Reg:AA)", ""},
                {"$(Reg:AAAA)", ""},
                {"$(Reg:AAA)", ""},
                {"$([MSBuild]::Add(2,$([System.Convert]::ToInt64('28', 16))))", "42"},
                {"$([MSBuild]::Add(2,$([System.Convert]::ToInt64('28', $([System.Convert]::ToInt32(16))))))", "42"},
                {"$(e.Length.ToString())", "3"},
                {"$(e.get_Length().ToString())", "3"},
                {"$(emptystring.Length)", "0" },
                {"$(space.Length)", "1" },
                {"$([System.TimeSpan]::Equals(null, null))", "True"}, // constant, unquoted null is a special value
                {"$([MSBuild]::Add(40,null))", "40"},
                {"$([MSBuild]::Add( 40 , null ))", "40"},
                {"$([MSBuild]::Add(null,40))", "40"},
                {"$([MSBuild]::Escape(';'))", "%3b"},
                {"$([MSBuild]::UnEscape('%3b'))", ";"},
                {"$(e.Substring($(e.Length)))", ""},
                {"$([System.Int32]::MaxValue)", System.Int32.MaxValue.ToString()},
                {"x$()", "x"},
                {"A$(Reg:A)A", "AA"},
                {"A$(Reg:AA)", "A"},
                {"$(Reg:AA)", ""},
                {"$(Reg:AAAA)", ""},
                {"$(Reg:AAA)", ""}
                                   };

            string[] errorTests = {
            "$(input[)",
            "$(input.ToString()])",
            "$(input.ToString()[)",
            "$(input.ToString()[12])",
            "$(input[])",
            "$(input[-1])",
            "$(listofthings.Split(';')[)",
            "$(listofthings.Split(';')['goo'])",
            "$(listofthings.Split(';')[])",
            "$(listofthings.Split(';')[-1])",
            "$([]::())",
                                                      @"
 
$(
 
$(
 
[System.IO]::Path.GetDirectory('c:\foo\bar\baz.txt')
 
).Substring(
 
'$([System.IO]::Path.GetPathRoot(
 
'$([System.IO]::Path.GetDirectory('c:\foo\bar\baz.txt'))'
 
).Length)'
 
 
 
)
 
",
                "$([Microsoft.VisualBasic.FileIO.FileSystem]::CurrentDirectory)", // not allowed
                "$(e.Length..ToString())",
                "$(SomeStuff.get_Length(null))",
                "$(SomeStuff.Substring((1)))",
                "$(b.Substring(-10, $(c)))",
                "$(b.Substring(-10, $(emptystring)))",
                "$(b.Substring(-10, $(space)))",
                "$([MSBuild]::Add.Sub(null,40))",
                "$([MSBuild]::Add( ,40))", // empty parameter is empty string
                "$([MSBuild]::Add('',40))", // empty quoted parameter is empty string
                "$([MSBuild]::Add(40,,,))",
                "$([MSBuild]::Add(40, ,,))",
                "$([MSBuild]::Add(40,)",
                "$([MSBuild]::Add(40,X)",
                "$([MSBuild]::Add(40,",
                "$([MSBuild]::Add(40",
                "$([MSBuild]::Add(,))", // gives "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."
                "$([System.TimeSpan]::Equals(,))", // empty parameter is interpreted as empty string
                "$([System.TimeSpan]::Equals($(space),$(emptystring)))", // empty parameter is interpreted as empty string
                "$([System.TimeSpan]::Equals($(emptystring),$(emptystring)))", // empty parameter is interpreted as empty string
                "$([MSBuild]::Add($(PropertyContainingNullAsAString),40))", // a property containing the word null is a string "null"
                "$([MSBuild]::Add('null',40))", // the word null is a string "null"
                "$(SomeStuff.Substring(-10))",
                "$(.Length)",
                "$(.Substring(1))",
                "$(.get_Length())",
                "$(e.)",
                "$(e..)",
                "$(e..Length)",
                "$(e$(d).Length)",
                "$($(d).Length)",
                "$(e`.Length)",
                "$([System.IO.Path]Combine::Combine(`a`,`b`))",
                "$([System.IO.Path]::Combine((`a`,`b`))",
                "$([System.IO.Path]::Combine(`|`,`b`))",
                "$([System.IO.Path]Combine(::Combine(`a`,`b`))",
                "$([System.IO.Path]Combine(`::Combine(`a`,`b`)`, `b`)`)",
                "$([System.IO.Path]::`Combine(`a`, `b`)`)",
                "$([System.IO.Path]::(`Combine(`a`, `b`)`))",
                "$([System.DateTime]foofoo::Now)",
                "$([System.DateTime].Now)",
                "$([].Now)",
                "$([ ].Now)",
                "$([ .Now)",
                "$([])",
                "$([ )",
                "$([ ])",
                "$([System.Diagnostics.Process]::Start(`NOTEPAD.EXE`))",
                "$([[]]::Start(`NOTEPAD.EXE`))",
                "$([(::Start(`NOTEPAD.EXE`))",
                "$([Goop]::Start(`NOTEPAD.EXE`))",
                "$([System.Threading.Thread]::CurrentThread)",
                "$",
                "$(",
                "$((",
                "@",
                "@(",
                "@()",
                "%",
                "%(",
                "%()",
                "exists",
                "exists(",
                "exists()",
                "exists( )",
                "exists(,)",
                "@(x->'",
                "@(x->''",
                "@(x-",
                "@(x->'x','",
                "@(x->'x',''",
                "@(x->'x','')",
                "-1>x",
                "\n",
                "\t",
                "+-1",
                "$(SomeStuff.)",
                "$(SomeStuff.!)",
                "$(SomeStuff.`)",
                "$(SomeStuff.GetType)",
                "$(goop.baz`)",
                "$(SomeStuff.Substring(HELLO!))",
                "$(SomeStuff.ToLowerInvariant()_goop)",
                "$(SomeStuff($(System.DateTime.Now)))",
                "$(System.Foo.Bar.Lgg)",
                "$(SomeStuff.Lgg)",
                "$(SomeStuff($(Value)))",
                "$(e.$(e.Length))",
                "$(e.Substring($(e.Substring(,)))",
                "$(e.Substring($(e.Substring(a)))",
                "$(e.Substring($([System.IO.Path]::Combine(`a`, `b`))))",
                "$([]::())",
                "$((((",
                "$(Registry:X)",
                "$($())",
                "$",
                "()"
            };

            string result;
            for (int i = 0; i < validTests.GetLength(0); i++)
            {
                result = expander.ExpandIntoStringLeaveEscaped(validTests[i, 0], ExpanderOptions.ExpandProperties, MockElementLocation.Instance);

                if (!String.Equals(result, validTests[i, 1]))
                {
                    string message = "FAILURE: " + validTests[i, 0] + " expanded to '" + result + "' instead of '" + validTests[i, 1] + "'";
                    Console.WriteLine(message);
                    Assert.True(false, message);
                }
                else
                {
                    Console.WriteLine(validTests[i, 0] + " expanded to '" + result + "'");
                }
            }

            for (int i = 0; i < errorTests.GetLength(0); i++)
            {
                // If an expression is invalid,
                //      - Expansion may throw InvalidProjectFileException, or
                //      - return the original unexpanded expression
                bool success = true;
                bool caughtException = false;
                result = String.Empty;
                try
                {
                    result = expander.ExpandIntoStringLeaveEscaped(errorTests[i], ExpanderOptions.ExpandProperties, MockElementLocation.Instance);
                    if (String.Compare(result, errorTests[i]) == 0)
                    {
                        Console.WriteLine(errorTests[i] + " did not expand.");
                        success = false;
                    }
                }
                catch (InvalidProjectFileException ex)
                {
                    Console.WriteLine(errorTests[i] + " caused '" + ex.Message + "'");
                    caughtException = true;
                }
                Assert.True(
                        (success == false || caughtException == true),
                        "FAILURE: Expected '" + errorTests[i] + "' to not parse or not be evaluated but it evaluated to '" + result + "'"
                    );
            }
        }
Example #56
0
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="ExpanderAutomationPeer" />
 /// class.
 /// </summary>
 /// <param name="owner">
 /// The element associated with this automation peer.
 /// </param>
 public ExpanderAutomationPeer(Expander owner)
     : base(owner)
 {
 }
Example #57
0
        /// <summary>
        /// Creates an expander populated with some ProjectPropertyInstances and ProjectPropertyItems.
        /// </summary>
        /// <returns></returns>
        private Expander<ProjectPropertyInstance, ProjectItemInstance> CreateItemFunctionExpander()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("p", "v0"));
            pg.Set(ProjectPropertyInstance.Create("p", "v1"));
            pg.Set(ProjectPropertyInstance.Create("Val", "2"));
            pg.Set(ProjectPropertyInstance.Create("a", "filename"));

            ItemDictionary<ProjectItemInstance> ig = new ItemDictionary<ProjectItemInstance>();

            for (int n = 0; n < 10; n++)
            {
                ProjectItemInstance pi = new ProjectItemInstance(project, "i", "i" + n.ToString(), project.FullPath);
                for (int m = 0; m < 5; m++)
                {
                    pi.SetMetadata("Meta" + m.ToString(), @"c:\firstdirectory\seconddirectory\file" + m.ToString() + ".ext");
                }
                pi.SetMetadata("Meta9", @"seconddirectory\file.ext");
                pi.SetMetadata("Meta10", @";someo%3bherplace\foo.txt;secondd%3brectory\file.ext;");
                pi.SetMetadata("MetaBlank", @"");

                if (n % 2 > 0)
                {
                    pi.SetMetadata("Even", "true");
                    pi.SetMetadata("Odd", "false");
                }
                else
                {
                    pi.SetMetadata("Even", "false");
                    pi.SetMetadata("Odd", "true");
                }
                ig.Add(pi);
            }

            Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            itemMetadataTable["Culture"] = "abc%253bdef;$(Gee_Aych_Ayee)";
            itemMetadataTable["Language"] = "english";
            IMetadataTable itemMetadata = new StringMetadataTable(itemMetadataTable);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, ig, itemMetadata);

            return expander;
        }
Example #58
0
 private void AssertParseEvaluate(Parser p, string expression, Expander <ProjectPropertyInstance, ProjectItemInstance> expander, bool expected)
 {
     AssertParseEvaluate(p, expression, expander, expected, null);
 }
Example #59
0
        /// <summary>
        /// Creates an expander populated with some ProjectPropertyInstances and ProjectPropertyItems.
        /// </summary>
        /// <returns></returns>
        private Expander<ProjectPropertyInstance, ProjectItemInstance> CreateExpander()
        {
            ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance();
            PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>();
            pg.Set(ProjectPropertyInstance.Create("p", "v0"));
            pg.Set(ProjectPropertyInstance.Create("p", "v1"));

            ItemDictionary<ProjectItemInstance> ig = new ItemDictionary<ProjectItemInstance>();
            ProjectItemInstance i0 = new ProjectItemInstance(project, "i", "i0", project.FullPath);
            ProjectItemInstance i1 = new ProjectItemInstance(project, "i", "i1", project.FullPath);
            ig.Add(i0);
            ig.Add(i1);

            Expander<ProjectPropertyInstance, ProjectItemInstance> expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(pg, ig);

            return expander;
        }
        public DapPropertiesDialog(DapSource source) : base(
                // Translators: {0} is the name assigned to a Digital Audio Player by its owner
                String.Format(Catalog.GetString("{0} Properties"), source.Name),
                null,
                DialogFlags.Modal | DialogFlags.NoSeparator,
                Stock.Close,
                ResponseType.Close)
        {
            this.source = source;

            HBox iconbox = new HBox();

            iconbox.Spacing = 10;
            //Image icon = new Image (source.Properties.Get<string> ("Icon.Names")[0], IconSize.Dialog);
            //icon.Yalign = 0.0f;
            //icon.Pixbuf = device.GetIcon(48);
            //iconbox.PackStart(icon, false, false, 0);

            VBox box = new VBox();

            box.Spacing = 10;

            PropertyTable table = new PropertyTable();

            table.ColumnSpacing = 10;
            table.RowSpacing    = 5;

            if (!source.IsReadOnly && source.CanRename)
            {
                nameEntry          = table.AddEntry(Catalog.GetString("Device name"), source.Name);
                nameEntry.Changed += OnEntryChanged;
            }
            else
            {
                table.AddLabel(Catalog.GetString("Device name"), source.Name);
            }

            /*if(device.ShowOwner) {
             *  if(!device.IsReadOnly && device.CanSetOwner) {
             *      ownerEntry = table.AddEntry(Catalog.GetString("Owner name"), device.Owner);
             *      ownerEntry.Changed += OnEntryChanged;
             *  } else {
             *      table.AddLabel(Catalog.GetString("Owner name"), device.Owner);
             *  }
             * }*/

            if (!source.IsReadOnly)
            {
                try {
                    VBox profile_description_box            = new VBox();
                    ProfileComboBoxConfigurable profile_box = new ProfileComboBoxConfigurable(ServiceManager.MediaProfileManager,
                                                                                              source.UniqueId, profile_description_box);
                    profile_box.Combo.MimeTypeFilter = source.AcceptableMimeTypes;
                    table.AddWidget(Catalog.GetString("Encode to"), profile_box);
                    table.AddWidget(null, profile_description_box);
                    profile_description_box.Show();

                    table.AddSeparator();
                } catch (Exception e) {
                    Console.WriteLine(e);
                }
            }

            table.AddWidget(Catalog.GetString("Capacity used"), UsedProgressBar);

            box.PackStart(table, true, true, 0);

            PropertyTable extTable = new PropertyTable();

            extTable.ColumnSpacing = 10;
            extTable.RowSpacing    = 5;

            foreach (DapSource.DapProperty property in source.DapProperties)
            {
                extTable.AddLabel(property.Name, property.Value);
            }

            Expander expander = new Expander(Catalog.GetString("Advanced details"));

            expander.Add(extTable);
            box.PackStart(expander, false, false, 0);

            BorderWidth = 10;
            Resizable   = false;
            iconbox.PackStart(box, true, true, 0);
            iconbox.ShowAll();
            VBox.Add(iconbox);
        }