Пример #1
0
    unsafe public void Create()
    {
        xc.XInitXCGUI("");
        int hWindow = XWnd.Create(0, 0, 500, 300, "xcgui", 0, 15);

        int hList = XList.Create(0, 0, 300, 200, hWindow);

        XList.SetItemTemplateXML(hList, "..\\..\\List_Item.xml");
        XList.AddColumn(hList, 100);
        XList.AddColumn(hList, 100);

        int hHead = XAdapterMap.Create();

        XList.BindAdapterHeader(hList, hHead);
        XAdapterMap.AddItemText(hHead, "name", "第一列");
        XAdapterMap.AddItemText(hHead, "name2", "第二列");


        int body = XAdapterTable.Create();

        XList.BindAdapter(hList, body);
        XAdapterTable.AddColumn(body, "name");
        XAdapterTable.AddColumn(body, "name2");

        int nItem = XAdapterTable.AddItemText(body, "1.1");

        XAdapterTable.SetItemText(body, nItem, 1, "1.2");


        XWnd.ShowWindow(hWindow, 5);
        xc.XRunXCGUI();
        xc.XExitXCGUI();
    }
Пример #2
0
 public AutopackageModel()
 {
     CompositionData = new Composition();
     DestinationDirectoryFiles = Enumerable.Empty<FileEntry>();
     Roles = new XList<Role>();
     Assemblies = new List<PackageAssembly>();
 }
Пример #3
0
        public virtual Topic AddBarrierRight()
        {
            Topic selectedTp = SelectedTopic;
            Topic refTopic   = null;

            if (selectedTp.Type == TopicType.Barrier)
            {
                refTopic   = SelectedTopic;
                selectedTp = selectedTp.ParentTopic;
                if (refTopic.Left <= refTopic.GetRoot().Left)
                {
                    XList <Topic> siblings = refTopic.ParentTopic.Children;
                    int           index    = siblings.IndexOf(refTopic) - 1;
                    if (index >= 0)
                    {
                        refTopic = siblings[index];
                    }
                    else
                    {
                        refTopic = null;
                    }
                }
            }
            if (selectedTp != null && (selectedTp.Type == TopicType.Consequence || selectedTp.Type == TopicType.Threat || selectedTp.Type == TopicType.Escalation))
            {
                return(AddSubTopic(selectedTp, refTopic, TopicType.Barrier, false));
            }
            else
            {
                return(null);
            }
        }
Пример #4
0
 public void AddTwoBags(PositionsBag bagOne, PositionsBag bagTwo)
 {
     XList.AddRange(bagOne.XList);
     XList.AddRange(bagTwo.XList);
     YList.AddRange(bagOne.YList);
     YList.AddRange(bagTwo.YList);
 }
Пример #5
0
        public Chart()
        {
            ChartBox              = CreateChartBox();
            ChartBox.Bounds       = DisplayRectangle;
            ChartBox.Paint       += new PaintEventHandler(ChartBox_Paint);
            ChartBox.MouseDown   += new MouseEventHandler(ChartBox_MouseDown);
            ChartBox.MouseUp     += new MouseEventHandler(ChartBox_MouseUp);
            ChartBox.MouseMove   += new MouseEventHandler(ChartBox_MouseMove);
            ChartBox.MouseLeave  += new EventHandler(ChartBox_MouseLeave);
            ChartBox.MouseWheel  += new MouseEventHandler(ChartBox_MouseWheel);
            ChartBox.DoubleClick += new EventHandler(ChartBox_DoubleClick);
            ChartBox.KeyDown     += new KeyEventHandler(ChartBox_KeyDown);
            ChartBox.KeyUp       += new KeyEventHandler(ChartBox_KeyUp);
            ChartBox.KeyPress    += new KeyPressEventHandler(ChartBox_KeyPress);
            ChartBox.Resize      += new EventHandler(ChartBox_Resize);
            Controls.Add(ChartBox);

            SetPaintStyles();

            Labels = new XList <ChartLabel>();
            Layers = new XList <ChartLayer>();

            Selector = new SelectionLayer(this);
            Layers.Add(Selector);

            MinimumChartSize = DefaultMinimumChartSize;
        }
Пример #6
0
 private Deindexing(Tensor <T> content, XList <Scalar <int>, int> shape, TensorList indices) :
     base("Deindex", content, shape, indices)
 {
     Content = content;
     Shape   = shape;
     Indices = indices;
 }
Пример #7
0
        private void SeriesUpdate()
        {
            if (RenderableSeries != null)
            {
                RenderableSeries.Clear();

                RenderableSeries.Add(new ColumnRenderableSeriesViewModel()
                {
                    DataPointWidth = 1,
                    Stroke         = System.Windows.Media.Color.FromRgb(186, 187, 190),
                    DataSeries     = Series
                });
            }

            if (Data != null && Series != null)
            {
                XList.Clear();
                YList.Clear();

                XList = Data.Keys.ToList();
                YList = Data.Values.ToList();

                try
                {
                    Series.Clear();
                    Series.InsertRange(0, XList, YList);
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Пример #8
0
        int GetXPos(int index, int space, XList <int> items, Vector4 vector)
        {
            int pos = 0;

            for (int i = 0, n = items.Count; i < n; ++i)
            {
                if (vector == Vector4.Left)
                {
                    if (i > 0)
                    {
                        pos += space;
                    }
                    pos += items[i];
                }
                if (vector == Vector4.Right)
                {
                    if (i > 0)
                    {
                        pos += space;
                    }
                    if (i < index)
                    {
                        pos += items[i];
                    }
                }
                if (i >= index)
                {
                    break;
                }
            }
            return(pos);
        }
Пример #9
0
 public Topic()
 {
     Style    = new TopicStyle();
     Lines    = new List <TopicLine>();
     Links    = new XList <Link>();
     Children = new XList <Topic>();
     Widgets  = new XList <Widget>();
 }
Пример #10
0
        public ChartThemeFolder()
        {
            Themes              = new XList <ChartTheme>();
            Themes.ItemAdded   += new XListEventHandler <ChartTheme>(Themes_ItemAdded);
            Themes.ItemRemoved += new XListEventHandler <ChartTheme>(Themes_ItemRemoved);

            Folders = new XList <ChartThemeFolder>();
        }
Пример #11
0
        public XList BuildXListWithOnlyOneValue()
        {
            XList list = new XList("xlStates", "States", "List of United States", false, XUserIds.Admin);

            list.AddValue(new XListValue(list.Id, "AL", "Alabama", 0, XUserIds.Admin));

            return(list);
        }
Пример #12
0
 public void DoTransLation(int input)
 {
     if (m_Inputs == null)
     {
         m_Inputs = new XList <int>();
     }
     m_Inputs.Add(input);
 }
Пример #13
0
        // construct an object 'tree' of the XML document elements
        internal static dynamic Parse(ref XNode root, XmlNode Node)
        {
            // Add attributes list if present
            if (Node.Attributes != null && Node.Attributes.Count > 0)
            {
                XNode Attrs = new XNode {
                };
                foreach (XmlAttribute Attr in Node.Attributes)
                {
                    Attrs[Attr.Name] = Attr.Value;
                }
                root["attr"] = Attrs;
            }

            // add children: branches or elements
            foreach (XmlNode Child in Node.ChildNodes)
            {
                string  name  = Child.Name;
                dynamic Value = null;

                // extract the node Value
                if (Child.ChildNodes.Count == 0)
                {
                    root[name] = Element(Child.Value);
                }
                else if (Child.ChildNodes.Count == 1 && Child.FirstChild.Name == "#text")
                {
                    root[name] = Element(Child.FirstChild.Value);
                }
                else
                {
                    XNode branch = new XNode {
                    };
                    Value = Parse(ref branch, Child);

                    // add the item to the tree
                    if (!root.ContainsKey(name))
                    {
                        root[name] = Value;
                    }
                    // if multiple items of this name convert then to XList item
                    else if (root[name].GetType().Name != "XList")
                    {
                        dynamic First = root[name];
                        root.Remove(name);
                        root[name] = new XList {
                            First, Value
                        };
                    }
                    else
                    {
                        root[name].Add(Value);
                    }
                }
            }
            return(root);
        }
Пример #14
0
        public void TestXListAdd()
        {
            var list = new XList <MyStruct>();

            for (int i = 0; i < LoopLength; i++)
            {
                list.Add(_sample);
            }
        }
Пример #15
0
        public void TestXListAdd()
        {
            var list = new XList <int>();

            for (int i = 0; i < LoopLength; i++)
            {
                list.Add(i);
            }
        }
Пример #16
0
 public TestsOnIntegers()
 {
     _intTestXList = new XList <int>();
     _intTestList  = new List <int>();
     for (int i = 0; i < LoopLength; i++)
     {
         _intTestList.Add(i);
         _intTestXList.Add(i);
     }
 }
Пример #17
0
        public void CreateXList_WithHeadParameterAsXNode_Works()
        {
            XNode first = new XNode("1st");

            first.Next = null;

            XList list = new XList(first);

            Assert.IsNotNull(list);
        }
Пример #18
0
        public Document()
        {
            Charts              = new XList <ChartPage>();
            Charts.ItemAdded   += new XListEventHandler <ChartPage>(Charts_ItemAdded);
            Charts.ItemRemoved += new XListEventHandler <ChartPage>(Charts_ItemRemoved);

            Attributes = new Dictionary <string, object>();

            Version = "3.0";
        }
Пример #19
0
        public ChartTooltipLayer(Chart owner)
            : base(owner)
        {
            ToolTips              = new XList <ChartToolTip>();
            ToolTips.ItemAdded   += new XListEventHandler <ChartToolTip>(ToolTips_ItemAdded);
            ToolTips.ItemRemoved += new XListEventHandler <ChartToolTip>(ToolTips_ItemRemoved);

            TheTimer          = new Timer();
            TheTimer.Interval = 100;
            TheTimer.Tick    += TheTimer_Tick;
        }
Пример #20
0
 public static Tensor <T> Create(Dim[] shape, XList <XSlice, Slice> slices, Tensor <T> content)
 {
     if (slices[0].IsSingleton)
     {
         if (slices.Values.Skip(1).All(s => s == XSlicer._))
         {
             return(Op.OneHot(shape, slices[0].Start, content));
         }
     }
     return(new OneHotSlice <T>(shape, slices, content));
 }
Пример #21
0
        /// <param name="x">the array to read values from</param>
        /// <param name="shape">the shape of the original array</param>
        /// <param name="indices">the indices of each values from `x`</param>
        public static Tensor <T> Create(Tensor <T> x, XList <Scalar <int>, int> shape, TensorList indices)
        {
            switch (x)
            {
            case Fill <T> fill:
                return(Dispatch <T> .Create(fill.x, shape, indices));

            default:
                return(new Deindexing <T>(x, shape, indices));
            }
        }
Пример #22
0
        public void AsReadOnly_Returns_List_With_Same_Items()
        {
            var items = new List <int> {
                4, 8, 15, 16, 23, 42
            };

            // Use as a static method, because full .NET already has a AsReadOnly instance method
            var result = XList.AsReadOnly(items);

            result.Should().Equal(items);
        }
Пример #23
0
 public TestsOnStructs()
 {
     _intTestXList = new XList <MyStruct>();
     _intTestList  = new List <MyStruct>();
     for (int i = 0; i < LoopLength; i++)
     {
         var s = new MyStruct(i);
         _intTestList.Add(s);
         _intTestXList.Add(s);
     }
 }
Пример #24
0
        Rectangle LayoutRoot(Topic root, MindMapLayoutArgs args)
        {
            Size  size = root.Bounds.Size; // CalculateNodeSize(root, args); // datnq TODO Update calculateNodeSize
            Point pt   = new Point(0, 0);

            root.Bounds = new Rectangle(pt.X - size.Width / 2, pt.Y - size.Height / 2, size.Width, size.Height);
            var rootFullSize = LayoutAttachments(root, args);

            Vector4[] vectors = new Vector4[] { Vector4.Left, Vector4.Top, Vector4.Right };
            //int def = 0;
            //int sideCount = Math.DivRem(root.Children.Count, vectors.Length, out def);

            Rectangle allBounds = root.Bounds;

            //int subTopicIndex = 0;
            root.Lines.Clear();
            Hashtable layoutInfos = new Hashtable();

            for (int vi = 0; vi < vectors.Length; vi++)
            {
                TopicType type;
                if (vi == (int)Vector4.Left)
                {
                    type = TopicType.Threat;
                }
                else if (vi == (int)Vector4.Right)
                {
                    type = TopicType.Consequence;
                }
                else
                {
                    type = TopicType.Hazard;
                }

                XList <Topic> children  = root.GetChildrenByType(type);
                Topic[]       subTopics = new Topic[children.Count];
                for (int ti = 0, n = children.Count; ti < n; ti++)
                {
                    subTopics[ti] = children[ti];
                }

                XList <int> rows     = CalculateRow(root, subTopics, args);
                XList <int> columns  = CalculateColumn(root, subTopics);
                Rectangle   rectFull = LayoutSubTopics(root, subTopics, vectors[vi], rows, columns, -1, -1, args);
                if (!rectFull.IsEmpty)
                {
                    allBounds = Rectangle.Union(allBounds, rectFull);
                }
            }

            return(allBounds);
        }
Пример #25
0
        public override void Execute()
        {
            var results = new XList <GetConfigResult>();

            Request.xForEach(item => {
                var doc = Collection.FindOne($"$.key='{item.Key}'");
                results.Add(new GetConfigResult {
                    Key     = item.Key,
                    Content = doc["value"].AsString
                });
            });
            Result = results;
        }
Пример #26
0
        XList <Topic> GetChildren(Topic parent)
        {
            XList <Topic> children = new XList <Topic>();

            if (parent.IsRoot)
            {
                children = parent.GetChildrenByType(ChildrenType);
            }
            else
            {
                children = parent.Children;
            }
            return(children);
        }
Пример #27
0
        void OnWidgetsChanged(XList <Widget> old)
        {
            if (old != null)
            {
                Widgets.ItemAdded   -= new XListEventHandler <Widget>(Widgets_ItemAdded);
                Widgets.ItemRemoved -= new XListEventHandler <Widget>(Widgets_ItemRemoved);
            }

            if (Widgets != null)
            {
                Widgets.ItemAdded   += new XListEventHandler <Widget>(Widgets_ItemAdded);
                Widgets.ItemRemoved += new XListEventHandler <Widget>(Widgets_ItemRemoved);
            }
        }
Пример #28
0
 public static XList <Expression <Func <T, T> > > Then <T>(this XList <Expression <Func <T, T> > > first, Expression <Func <T, T> > second)
 {
     if (null == first)
     {
         return(new XList <Expression <Func <T, T> > > {
             second
         });
     }
     if (null != second)
     {
         first.Add(second);
     }
     return(first);
 }
Пример #29
0
        public MyTabControl()
        {
            TabBar = new TabBar();
            TabBar.SelectedItemChanged += TabBar_SelectedItemChanged;
            TabBar.Font = SystemFonts.MessageBoxFont;
            Controls.Add(TabBar);

            //ControlContainer = new Panel();
            //Controls.Add(ControlContainer);

            TabPages              = new XList <Control>();
            TabPages.ItemAdded   += new XListEventHandler <Control>(TabPages_ItemAdded);
            TabPages.ItemRemoved += new XListEventHandler <Control>(TabPages_ItemRemoved);
        }
Пример #30
0
        public ButtonListBox()
        {
            _ButtonSize      = 32;
            ReserveIconSpace = true;
            IconSize         = new System.Drawing.Size(16, 16);

            Buttons              = new XList <ButtonInfo>();
            Buttons.ItemAdded   += Buttons_ItemAdded;
            Buttons.ItemRemoved += Buttons_ItemRemoved;

            ButtonBackColor      = SystemColors.ControlDark;
            ButtonForeColor      = SystemColors.ControlText;
            ButtonHoverBackColor = SystemColors.Highlight;
            ButtonHoverForeColor = SystemColors.HighlightText;
        }
Пример #31
0
        /// <summary>
        /// Initializes the view.
        /// </summary>
        /// <param name="e">The event args.</param>
        protected override void OnInitCore(EventArgs e)
        {
            this.Title = "silkveil.net | Administration | Mappings";

            XList mappingsList = new XList();
            this.Content.Controls.Add(mappingsList);

            mappingsList.DataTextField = "Name";
            mappingsList.DataNavigateUrlFormatString =
                this.GenerateLinkTo<MappingsController>() + "{0}/";

            mappingsList.DataNavigateUrlFields = new[] { "Name" };

            mappingsList.DataSource = this.MappingService.ReadMappings(this.CurrentlyLoggedOnUser);
            mappingsList.DataBind();
        }
Пример #32
0
        public void AsReadOnly_Returns_A_List_That_Throws_On_Attempt_To_Modify()
        {
            var items = new List <int> {
                4, 8, 15, 16, 23, 42
            };

            // Call as a static method, because full .NET already has a AsReadOnly instance method which would be used instead
            IList <int> result = XList.AsReadOnly(items);

            Assert.Throws <NotSupportedException>(result.Clear);
            Assert.Throws <NotSupportedException>(() => result.Add(99));
            Assert.Throws <NotSupportedException>(() => result.Insert(1, 99));
            Assert.Throws <NotSupportedException>(() => result.RemoveAt(0));
            Assert.Throws <NotSupportedException>(() => result.Remove(42));
            Assert.Throws <NotSupportedException>(() => result[0] = 99);
        }
Пример #33
0
        public void DownloadFile(string url, string destination)
        {
            var response = Event<GetResponseInterface>.RaiseFirst();
            if (response == null) {
                return;
            }

            _downloadQueue = _downloadQueue ?? new XList<Task<string>>();
            _downloadQueue.Add(SessionData.Current.RequireRemoteFile(url, new Uri(url).SingleItemAsEnumerable(), PackageManagerSettings.CoAppCacheDirectory, false, rrfState => {
                if (rrfState == null || string.IsNullOrEmpty(rrfState.LocalLocation) || !File.Exists(rrfState.LocalLocation)) {
                    // didn't fill in the local location? -- this happens when the client can't download.
                    return null;
                }

                if (!rrfState.LocalLocation.Equals(destination, StringComparison.CurrentCultureIgnoreCase)) {
                    File.Copy(rrfState.LocalLocation, destination);
                }
                return destination;
            }) as Task<string>);
        }
Пример #34
0
 public bool WaitForFileDownloads()
 {
     if( _downloadQueue.IsNullOrEmpty()) {
         return true;
     }
     var result = _downloadQueue.All(each => each.Result != null);
     _downloadQueue = null;
     return result;
 }
Пример #35
0
 // Elements marked with XmlIgnore won't persist in the package feed as themselves
 // they get persisted as elements in the Atom Format (so that we have a suitable Atom feed to look at)
 public PackageDetails()
 {
     Publisher = new Identity();
     Contributors = new XList<Identity>();
 }
        protected PropertySheet Parse()
        {
            var tokenStream = PropertySheetTokenizer.Tokenize(_propertySheetText);
            var state = ParseState.Global;
            var enumerator = tokenStream.GetEnumerator();
            var importFilename = string.Empty;
            var startFolder = System.Environment.CurrentDirectory;

            // first, check for a .user file to auto-import
            if(!string.IsNullOrEmpty(_filename) ) {
                var fullPath = _filename.GetFullPath();
                startFolder = Path.GetDirectoryName(fullPath) + "\\";
                Import(Path.GetFileName(fullPath) + ".user", startFolder);
            }

            Token token;

            Rule rule = null;
            string ruleName = "*";
            string ruleParameter = null;
            string ruleClass = null;
            string ruleId = null;

            PropertyRule property = null;

            var sourceLocation = new SourceLocation {
                Row=0,
                Column = 0,
                SourceFile = null,
            };

            string propertyName = null;
            string propertyLabelText = null;
            string presentlyUnknownValue = null;
            // string collectionName = null;
            List<string> multidimensionalLambda = null;

            enumerator.MoveNext();

            do {
                token = enumerator.Current;

                switch (token.Type) {
                        // regardless where we are, skip over whitespace, etc.
                    case TokenType.WhiteSpace:
                    case TokenType.LineComment:
                    case TokenType.MultilineComment:
                        continue;
                }

                // System.Console.WriteLine("Token : {0} == [{1}]", token.Type, token.Data);

                switch (state) {
                    case ParseState.Global:
                        sourceLocation = new SourceLocation { // will be the start of the next new rule.
                            Row = token.Row,
                            Column = token.Column,
                            SourceFile = _filename,
                        };

                        switch (token.Type) {
                            case TokenType.Identifier: // look for identifier as the start of a selector
                                if( token.Data == "@import" ) {
                                    // special case to handle @import rules
                                    state = ParseState.Import;
                                    continue;
                                }
                                state = ParseState.Selector;
                                ruleName = token.Data;
                                continue;

                            case TokenType.Dot:
                                state = ParseState.SelectorDot;
                                ruleName = "*";
                                // take next identifier as the classname
                                continue;

                            case TokenType.Pound:
                                state = ParseState.SelectorPound;
                                ruleName = "*";
                                // take next identifier as the id
                                continue;

                            case TokenType.Semicolon: // tolerate extra semicolons.
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 100", "Expected one of '.' , '#' or identifier");
                        }

                    case ParseState.Import :
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.Identifier:
                                state = ParseState.ImportFilename;
                                importFilename = token.Data;
                                continue;
                            default:
                                throw new EndUserParseException(token, _filename, "PSP 121", "Expected a string literal for filename (Missing semicolon?)");
                        }

                    case ParseState.ImportFilename:
                        switch (token.Type) {
                            case TokenType.Semicolon:
                                if( !Import(importFilename, startFolder)) {
                                    throw new EndUserParseException(token, _filename, "PSP 122", "Imported file '{0}' not found", importFilename);
                                }
                                state = ParseState.Global;
                                continue;
                            default:
                                throw new EndUserParseException(token, _filename, "PSP 121", "Expected a string literal for filename");
                        }

                    case ParseState.Selector:
                        switch (token.Type) {
                            case TokenType.Dot:
                                state = ParseState.SelectorDot;
                                continue;

                            case TokenType.Pound:
                                state = ParseState.SelectorPound;
                                continue;

                            case TokenType.SelectorParameter:
                                ruleParameter = token.Data;
                                if( ruleParameter.IndexOfAny("\r\n".ToCharArray()) >= 0) {
                                    throw new EndUserParseException(token, _filename, "PSP 123", "Selector parameter may not contain CR/LFs (missing close bracket?): {0} ", Rule.CreateSelectorString(ruleName, ruleParameter,ruleClass, ruleId ));
                                }
                                continue;

                            case TokenType.OpenBrace:
                                state = ParseState.InRule;

                                // property sheets now merge rules when redefined.
                                // if( _propertySheet.HasRule(ruleName, ruleParameter, ruleClass, ruleId) ) {
                                   // throw new EndUserParseException(token, _filename, "PSP 113", "Duplicate rule with identical selector not allowed: {0} ", Rule.CreateSelectorString(ruleName, ruleParameter,ruleClass, ruleId ));
                                // }

                                rule = _propertySheet.GetRule(ruleName, ruleParameter, ruleClass, ruleId);

                                ruleName = null;
                                ruleParameter = null;
                                ruleClass = null;
                                ruleId = null;

                                rule.SourceLocation = sourceLocation;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 101", "Expected one of '.' , '#' , '[' or '{{' ." );
                        }

                    case ParseState.SelectorDot:
                        switch (token.Type) {
                            case TokenType.Identifier:
                                ruleClass = token.Data;
                                state = ParseState.Selector;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 102", "Expected identifier");
                        }

                    case ParseState.SelectorPound:
                        switch (token.Type) {
                            case TokenType.Identifier:
                                ruleId = token.Data;
                                state = ParseState.Selector;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 103", "Expected identifier");
                        }

                    case ParseState.InRule:
                        switch (token.Type) {
                            case TokenType.Semicolon: // extra semicolons are tolerated.
                                continue;

                            case TokenType.StringLiteral:
                            case TokenType.Identifier:
                                propertyName = token.Data;
                                state = ParseState.HavePropertyName;
                                sourceLocation = new SourceLocation {
                                    Row = token.Row,
                                    Column = token.Column,
                                    SourceFile = _filename,
                                };

                                continue;

                            case TokenType.CloseBrace:
                                // this rule is DONE.
                                rule = null; // set this to null, so that we don't accidentally add new stuff to this rule.
                                state = ParseState.Global;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 104", "In rule, expected semi-colon ';', close-brace '}}' or value." );
                        }

                    case ParseState.HavePropertyName:
                        switch (token.Type) {
                            case TokenType.Colon:
                                state = ParseState.HavePropertySeparator;
                                property = rule.GetRuleProperty(propertyName);
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 105", "Found rule property name, expected colon ':'." );
                        }

                    case ParseState.HavePropertySeparator:
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                                state = ParseState.HavePropertyLabel;
                                if ("@Literal" == token.RawData) {
                                    propertyLabelText = token.Data;
                                }
                                else {
                                    propertyLabelText = token.Data;
                                }
                                continue;

                            case TokenType.Identifier:
                                state = ParseState.HavePropertyLabel;
                                propertyLabelText = token.Data;
                                continue;

                            case TokenType.OpenBrace:
                                state = ParseState.InPropertyCollectionWithoutLabel;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 106", "After rule property name, expected value, open-brace '{{' or open-parenthesis '('." );
                        }

                    case ParseState.InPropertyCollectionWithoutLabel:
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                            case TokenType.Identifier:
                                // at this point it could be a collection, a label, or a value.
                                presentlyUnknownValue = token.Data;
                                state = ParseState.InPropertyCollectionWithoutLabelButHaveSomething;
                                continue;

                            case TokenType.CloseBrace:
                                // state = ParseState.HavePropertyCompleted;
                                // this makes the semicolon optional.
                                state = ParseState.InRule;
                                continue;

                            case TokenType.OpenParenthesis:
                                state = ParseState.OpenBraceExpectingMultidimesionalLamda;
                                multidimensionalLambda  = new XList<string>();
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 107", "In property collection, expected value or close brace '}}'");
                        }

                    case ParseState.OpenBraceExpectingMultidimesionalLamda:
                        switch( token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                            case TokenType.Identifier:
                                // looks like we have the name of a collection for a multidimensional lambda
                                multidimensionalLambda.Add( token.Data);
                                state = ParseState.HasMultidimensionalLambdaIdentifier;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 124", "In multidimensional lambda declaration, expected identifier, found '{0}'", token.Data);
                        }

                    case ParseState.HasMultidimensionalLambdaIdentifier:
                        switch( token.Type) {
                            case TokenType.Comma:
                                state = ParseState.OpenBraceExpectingMultidimesionalLamda;
                                continue;
                            case TokenType.CloseParenthesis:
                                state = ParseState.NextTokenBetterBeLambda;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 125", "In multidimensional lambda declaration, expected close parenthesis or comma, found '{0}'", token.Data);
                        }

                    case ParseState.NextTokenBetterBeLambda:
                        switch( token.Type ) {
                            case TokenType.Lambda:
                                // we already knew that it was going to be this.
                                // the collection has all the appropriate values.
                                presentlyUnknownValue = null;
                                state = ParseState.HasLambda;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 125", "Expected lambda '=>' found '{0}'", token.Data);
                        }

                    case ParseState.InPropertyCollectionWithoutLabelButHaveSomething:
                        switch (token.Type) {
                            case TokenType.Lambda:
                                multidimensionalLambda = new XList<string> {presentlyUnknownValue};
                                presentlyUnknownValue = null;
                                state = ParseState.HasLambda;
                                continue;

                            case TokenType.Equal:
                                // looks like it's gonna be a label = value type.
                                propertyLabelText = presentlyUnknownValue;
                                presentlyUnknownValue = null;
                                state = ParseState.HasEqualsInCollection;
                                continue;

                            case TokenType.Comma: {
                                    // turns out its a simple collection item.
                                    var pv = property.GetPropertyValue(string.Empty);
                                    pv.Add(presentlyUnknownValue);
                                    pv.SourceLocation = sourceLocation;
                                    presentlyUnknownValue = null;
                                    state = ParseState.InPropertyCollectionWithoutLabel;
                                }
                                continue;

                            case TokenType.CloseBrace: {
                                    // turns out its a simple collection item.
                                    var pv = property.GetPropertyValue(string.Empty);
                                    pv.Add(presentlyUnknownValue);
                                    pv.SourceLocation = sourceLocation;
                                    presentlyUnknownValue = null;
                                    // state = ParseState.HavePropertyCompleted;
                                    // this makes the semicolon optional.
                                    state = ParseState.InRule;

                                }
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 114", "after an value or identifier in a collection expected a '=>' or '=' or ',' .");
                        }

                    case  ParseState.HasEqualsInCollection :
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                            case TokenType.Identifier: {
                                    var pv = property.GetPropertyValue(propertyLabelText);
                                    pv.Add(token.Data);
                                    pv.SourceLocation = sourceLocation;
                                    state = ParseState.InPropertyCollectionWithoutLabelWaitingForComma;
                                }
                                continue;

                            case TokenType.OpenBrace:
                                state = ParseState.InPropertyCollectionWithLabel;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 119", "after an equals '=' in a collection, expected a value or identifier.");

                        }
                    case ParseState.HasLambda:
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                            case TokenType.Identifier:
                                propertyLabelText = token.Data;
                                state = ParseState.HasLambdaAndLabel;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 115", "After the '=>' in a collection, expected value or identifier.");

                        }

                    case ParseState.HasLambdaAndLabel:
                        switch (token.Type) {
                            case TokenType.Equal:
                                state = ParseState.HasLambdaAndLabelAndEquals;
                                continue;

                            case TokenType.Semicolon:
                            case TokenType.Comma :
                            case TokenType.CloseBrace: {
                                // assumes "${DEFAULTLAMBDAVALUE}" for the lamda value
                                /* ORIG:
                                    var pv = property.GetPropertyValue(propertyLabelText, multidimensionalLambda);
                                    pv.Add("${DEFAULTLAMBDAVALUE}");
                                 */

                                    var pv = property.GetPropertyValue("", multidimensionalLambda);
                                    pv.Add(propertyLabelText);

                                    pv.SourceLocation = sourceLocation;
                                    propertyLabelText = null;
                                    multidimensionalLambda = null;
                                    state = ParseState.InPropertyCollectionWithoutLabelWaitingForComma;
                                }

                                if (token.Type == TokenType.CloseBrace) {
                                    // and, we're closing out this property.
                                    // state = ParseState.HavePropertyCompleted;
                                    // this makes the semicolon optional.
                                    state = ParseState.InRule;

                                }
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 116", "After the '{0} => {1}' in collection, expected '=' ", multidimensionalLambda.Aggregate("(", (current,each) => current+", "+each)+")" , propertyLabelText);

                        }

                    case ParseState.HasLambdaAndLabelAndEquals:
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                            case TokenType.Identifier: {
                                var pv = property.GetPropertyValue(propertyLabelText, multidimensionalLambda);
                                    pv.Add(token.Data);
                                    pv.SourceLocation = sourceLocation;
                                    propertyLabelText = null;
                                    multidimensionalLambda = null;
                                    state = ParseState.InPropertyCollectionWithoutLabelWaitingForComma;
                                }
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 117", "After the '{0} => {1} = ' in collection, expected a value or identifier", multidimensionalLambda.Aggregate("(", (current, each) => current + ", " + each) + ")", propertyLabelText);
                        }

                    case ParseState.InPropertyCollectionWithoutLabelWaitingForComma:
                        switch (token.Type) {
                            case TokenType.Comma:
                            case TokenType.Semicolon:
                                state = ParseState.InPropertyCollectionWithoutLabel;
                                continue;

                            case TokenType.CloseBrace:
                                // state = ParseState.HavePropertyCompleted;
                                // this makes the semicolon optional.
                                state = ParseState.InRule;

                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 118", "After complete expression or value in a collection, expected ',' or '}}'.");
                        }

                    case ParseState.InPropertyCollectionWithLabel:
                        switch (token.Type) {
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral:
                            case TokenType.Identifier:
                                presentlyUnknownValue = token.Data;
                                state = ParseState.HaveCollectionValue;
                                continue;

                            case TokenType.CloseBrace:
                                //state = ParseState.HavePropertyCompleted;
                                // this makes the semicolon optional.
                                state = ParseState.InPropertyCollectionWithoutLabelWaitingForComma;

                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 107", "In property collection, expected value or close brace '}}'" );
                        }

                    case ParseState.HaveCollectionValue:
                        switch (token.Type) {
                            case TokenType.Semicolon:
                            case TokenType.Comma: {
                                    var pv = property.GetPropertyValue(propertyLabelText);
                                    pv.Add(presentlyUnknownValue);
                                    pv.SourceLocation = sourceLocation;
                                    // propertyLabelText = null;
                                    state = ParseState.InPropertyCollectionWithLabel;
                                }
                                continue;

                            case TokenType.CloseBrace: {
                                    var pv = property.GetPropertyValue(propertyLabelText);
                                    pv.Add(presentlyUnknownValue);
                                    pv.SourceLocation = sourceLocation;
                                    propertyLabelText = null;
                                    // state = ParseState.HavePropertyCompleted;
                                    // this makes the semicolon optional.
                                    state = ParseState.InRule;

                                }
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 108", "With property collection value, expected comma ',' or close-brace '}}'.");
                        }

                    case ParseState.HavePropertyLabel:
                        switch (token.Type) {
                            case TokenType.Equal:
                                state = ParseState.HavePropertyEquals;
                                continue;

                            case TokenType.Dot:
                                var t = SkipToNext(ref enumerator);

                                if( !t.HasValue ) {
                                    throw new EndUserParseException(token, _filename, "PSP 109", "Unexpected end of Token stream [HavePropertyLabel]");
                                }
                                token = t.Value;
                                if (token.Type == TokenType.Identifier || token.Type == TokenType.NumericLiteral) {
                                    propertyLabelText += "." + token.Data;
                                }
                                else
                                    throw new EndUserParseException(token, _filename, "PSP 110", "Expected identifier or numeric literal after Dot '.'.");
                                continue;

                            case TokenType.Semicolon: {
                                    // it turns out that what we thought the label was, is really the property value,
                                    // the label is an empty string
                                    var pv = property.GetPropertyValue(string.Empty);
                                    pv.Add(propertyLabelText);
                                    pv.SourceLocation = sourceLocation;
                                    propertyName = propertyLabelText = null;
                                    state = ParseState.InRule;
                                }
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 111", "After property value, expected semi-colon ';' or equals '='." );
                        }

                    case ParseState.HavePropertyEquals:
                        switch (token.Type) {
                            case TokenType.Identifier:
                            case TokenType.StringLiteral:
                            case TokenType.NumericLiteral: {
                                    // found our property-value. add it, and move along.
                                    var pv = property.GetPropertyValue(propertyLabelText);
                                    pv.Add(token.Data);
                                    pv.SourceLocation = sourceLocation;
                                    propertyName = propertyLabelText = null;
                                    state = ParseState.HavePropertyCompleted;
                                }
                                continue;

                            case TokenType.OpenBrace:
                                // we're starting a new collection (where we have the label already).
                                state = ParseState.InPropertyCollectionWithLabel;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 112", "After equals in property, expected value or close-brace '{B{'." );
                        }

                    case ParseState.HavePropertyCompleted:
                        switch (token.Type) {
                            case TokenType.CloseBrace:
                            case TokenType.Semicolon:
                                state = ParseState.InRule;
                                continue;

                            default:
                                throw new EndUserParseException(token, _filename, "PSP 113", "After property completed, expected semi-colon ';'.");
                        }

                    default:
                        throw new EndUserParseException(token, _filename, "PSP 120", "CATS AND DOGS, LIVINGTOGETHER...");
                }
            } while (enumerator.MoveNext());
            return _propertySheet;
        }
Пример #37
0
        /// <summary>
        /// The (non-static) startup method
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        /// <returns>Process return code.</returns>
        /// <remarks></remarks>
        protected override int Main(IEnumerable<string> args)
        {
            _packageManager.Elevate().Wait();

            CurrentTask.Events += new DownloadProgress((remoteLocation, location, progress) => {
                if (!activeDownloads.Contains(remoteLocation)) {
                    activeDownloads.Add(remoteLocation);
                }
                "Downloading {0}".format(remoteLocation.UrlDecode()).PrintProgressBar(progress);
            });

            CurrentTask.Events += new DownloadCompleted((remoteLocation, locallocation) => {
                if (activeDownloads.Contains(remoteLocation)) {
                    Console.WriteLine();
                    activeDownloads.Remove(remoteLocation);
                }
            });

            try {
                #region command line parsing

                var options = args.Where(each => each.StartsWith("--")).Switches();
                var parameters = args.Where(each => !each.StartsWith("--")).Parameters().ToArray();

                foreach (var arg in options.Keys) {
                    var argumentParameters = options[arg];
                    var last = argumentParameters.LastOrDefault();
                    var lastAsBool = string.IsNullOrEmpty(last) || last.IsTrue();

                    switch (arg) {
                            /* options  */
                        case "min-version":
                            pkgFilter &= Package.Properties.Version.IsGreaterThanOrEqual(last);
                            break;

                        case "max-version":
                            pkgFilter &= Package.Properties.Version.IsLessThanOrEqual(last);
                            break;

                        case "installed":
                            pkgFilter &= Package.Properties.Installed.Is(lastAsBool);
                            break;

                        case "active":
                            pkgFilter &= Package.Properties.Active.Is(lastAsBool);
                            break;

                        case "wanted":
                            pkgFilter &= Package.Properties.Wanted.Is(lastAsBool);
                            break;

                        case "blocked":
                            pkgFilter &= Package.Properties.Blocked.Is(lastAsBool);
                            break;

                        case "trimable":
                            pkgFilter &= Package.Filters.Trimable;
                            break;

                        case "latest":
                            collectionFilter = collectionFilter.Then(p=> p.HighestPackages());
                            break;

                        case "force":
                            _force = lastAsBool;
                            break;

                        case "force-scan":
                        case "force-rescan":
                        case "scan":
                        case "rescan":
                            preCommandTasks.Add(_packageManager.SetAllFeedsStale());
                            break;

                        case "pretend":
                            _pretend= lastAsBool;
                            break;

                        case "auto-upgrade":
                            _autoUpgrade = lastAsBool;
                            break;

                        case "exact":
                            _autoUpgrade = false;
                            break;

                        case "use-feed":
                        case "feed":
                            _location = last;
                            break;

                        case "verbose":
                            _verbose = lastAsBool;
                            Logger.Errors = true;
                            Logger.Messages = true;
                            Logger.Warnings = true;
                            _packageManager.EnableMessageLogging();
                            _packageManager.EnableWarningLogging();
                            _packageManager.EnableErrorLogging();
                            break;

                            /* global switches */
                        case "load-config":
                            // all ready done, but don't get too picky.
                            break;

                        case "nologo":
                            this.Assembly().SetLogo(string.Empty);
                            break;

                        case "terse":
                            this.Assembly().SetLogo(string.Empty);
                            _terse = true;
                            _verbose = false;
                            break;

                        case "x64":
                            _x64 = true;
                            break;

                        case "x86":
                            _x86 = true;
                            break;

                        case "any":
                        case "cpuany":
                            _cpuany = true;
                            break;

                        case "all":
                            _x64 = true;
                            _x86 = true;
                            _cpuany = true;
                            break;

                        case "priority":
                            switch( last ) {
                                case "highest":
                                    _priority = 100;
                                    break;
                                case "high":
                                    _priority = 75;
                                    break;
                                case "normal":
                                case "default":
                                    _priority = 50;
                                    break;
                                case "low":
                                    _priority = 25;
                                    break;
                                case "lowest":
                                    _priority = 0;
                                    break;
                                default:
                                    _priority = last.ToInt32(50);
                                    break;
                            }
                            break;

                        case "help":
                            return Help();

                        default:
                            throw new ConsoleException(Resources.UnknownParameter, arg);
                    }
                }

                Logo();

                if (!parameters.Any()) {
                    throw new ConsoleException(Resources.MissingCommand);
                }

                #endregion

                Task task = null;
                if (parameters.IsNullOrEmpty()) {
                    return Help();
                }
                string command = string.Empty;

                if (parameters[0].ToLower().EndsWith(".msi")) {
                    var files = parameters.FindFilesSmarter().ToArray();
                    if( files.Length > 0 ) {
                        // assume install if just given filenames
                        command = "install";
                        parameters = files;
                    }
                }

                if (string.IsNullOrEmpty(command)) {
                    command = parameters.FirstOrDefault();
                    parameters = parameters.Skip(1).ToArray();
                }

                if (!command.StartsWith("-")) {
                    command = command.ToLower();
                }

                switch (command) {
                    case "-?":
                        return Help();

                    case "test":
                       // pkgFilter &= Package.Properties.Installed.Is(true) & Package.Properties.Active.Is(true) & Package.Properties.UpdatePackages.Any();
                          // collectionFilter = collectionFilter.Then(p => p.HighestPackages()).Then(p => p.OrderByDescending(each=> each.Version));
                        // collectionFilter = collectionFilter.Then(p => p.HighestPackages());
                        // collectionFilter = collectionFilter.Then(pkgs => pkgs.HighestPackages());

                        pkgFilter &= Package.Properties.DisplayName.Is("z*");

                         task = preCommandTasks.Continue(() => _packageManager.FindPackages(CanonicalName.AllPackages, pkgFilter, collectionFilter, _location))
                            .Continue(packages => {
                                if (packages.IsNullOrEmpty()) {
                                    PrintNoPackagesFound(parameters);
                                    return;
                                }
                               PrintPackages(packages);
                            });

                        //_packageManager.AddScheduledTask("test", "c:\\programdata\\bin\\coapp.exe", "list", 11, 28, DayOfWeek.Tuesday, 5).Wait();
                        //var tsks = _packageManager.ScheduledTasks.Result;
                        //tsks.ToTable().ConsoleOut();

                        _packageManager.SetConfigurationValue("test", null, null).Wait();
                        Console.WriteLine( _packageManager.GetConfigurationValue("test", "something").Result);
                        return 0;

                    case "show-debug":
                        var l = 5;
                        if( parameters.Any() ) {
                            l = parameters.FirstOrDefault().ToInt32();
                        }
                        Console.WriteLine(_packageManager.GetEventLog(new TimeSpan(0, l, 0)));
                        return 0;

                    case "clear-debug":
                        Logger.Clear();
                        Console.WriteLine("Debug log cleared.");
                        return 0;

                    case "post-debug":
                        l = 5;
                        if( parameters.Any() ) {
                            l = parameters.FirstOrDefault().ToInt32();
                        }

                        var token = _packageManager.UploadDebugInformation(_packageManager.GetEventLog(new TimeSpan(0, l, 0))).Result;
                        if( string.IsNullOrEmpty(token)) {
                            return Fail("Unable to upload debug log.");
                        }

                        Console.WriteLine( "Debug Log Uploaded. Token [{0}]", token);
                        return 0;

                    case "-l":
                    case "list":
                    case "list-package":
                    case "list-packages":
                        if( !parameters.Any() ) {
                            collectionFilter = collectionFilter.Then(p => p.HighestPackages());
                        }

                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters, pkgFilter, collectionFilter, _location)
                            .Continue(packages => {
                                if (packages.IsNullOrEmpty()) {
                                    PrintNoPackagesFound(parameters);
                                    return;
                                }
                                PrintPackages(packages);
                            }));
                        break;

                    case "add-publisher":
                    case "add-publishers":
                        if( !parameters.Any()) {
                            return Fail("add-publisher requires one or more public key tokens to add");
                        }

                        task = parameters.Select(each => _packageManager.AddTrustedPublisher(each)).Continue(() => _packageManager.TrustedPublishers).Continue(publishers => {
                            Console.WriteLine("Trusted publisher key tokens: ");
                            foreach( var t in publishers ) {
                                Console.WriteLine("      {0}", t);
                            }
                        });
                        break;

                    case "remove-publisher":
                    case "remove-publishers":
                        if( !parameters.Any()) {
                            return Fail("remove-publisher requires one or more public key tokens to add");
                        }

                        task = parameters.Select(each => _packageManager.RemoveTrustedPublisher(each)).Continue(() => _packageManager.TrustedPublishers).Continue(publishers => {
                            Console.WriteLine("Trusted publisher key tokens: ");
                            foreach (var t in publishers) {
                                Console.WriteLine("      {0}", t);
                            }
                        });
                        break;

                    case "list-publishers":
                    case "list-publisher":
                        task = _packageManager.TrustedPublishers.Continue(publishers => {
                            Console.WriteLine("Trusted publisher key tokens: ");
                            foreach (var t in publishers) {
                                Console.WriteLine("      {0}", t);
                            }
                        });
                        break;

                    case "-w":
                    case "wanted":
                    case "want":
                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters, pkgFilter & Package.Filters.InstalledPackages, collectionFilter, _location)
                            .Continue(packages => {
                                if (packages.IsNullOrEmpty()) {
                                    PrintNoPackagesFound(parameters);
                                    return;
                                }
                                var pkgs = packages.ToArray();

                                Console.WriteLine("Setting {0} packages to 'wanted':", pkgs.Length);

                                foreach( var p in packages ) {
                                    _packageManager.SetPackageWanted(p.CanonicalName, true);
                                }

                                // refresh
                                pkgs.Select(each => _packageManager.GetPackage(each.CanonicalName)).Continue( p => PrintPackages(p));
                            }));
                        break;

                    case "-W":
                    case "drop":
                    case "unwanted":
                    case "unwant":
                    case "donotwant":
                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters, pkgFilter & Package.Filters.InstalledPackages, collectionFilter, _location)
                            .Continue(packages => {
                                if (packages.IsNullOrEmpty()) {
                                    PrintNoPackagesFound(parameters);
                                    return;
                                }
                                var pkgs = packages.ToArray();

                                Console.WriteLine("Setting {0} packages to 'unwanted':", pkgs.Length);

                                foreach (var p in packages) {
                                    _packageManager.SetPackageWanted(p.CanonicalName, false);
                                }

                                // refresh
                                pkgs.Select(each => _packageManager.GetPackage(each.CanonicalName)).Continue(p => PrintPackages(p));
                            }));
                        break;

                    case "block":
                    case "block-package":
                    case "-b":
                        task = preCommandTasks.Continue(() => {
                                foreach (var cn in parameters.Select(v => (CanonicalName)v)) {
                                    _packageManager.SetGeneralPackageInformation(_priority, cn, "state", PackageState.Blocked.ToString());
                                    Console.WriteLine("Blocking '{0}' at priority {1}.",cn.ToString(), _priority  );
                                }
                            });
                        break;

                    case "lock-package":
                    case "lock":
                    case "-B":
                        task = preCommandTasks.Continue(() => {
                            foreach (var cn in parameters.Select(v => (CanonicalName)v)) {
                                _packageManager.SetGeneralPackageInformation(_priority, cn, "state", PackageState.DoNotChange.ToString());
                                Console.WriteLine("Locking '{0}' at priority {1}.", cn.ToString(), _priority);
                            }
                        });
                        break;

                    case "updateable":
                    case "-d":
                        task = preCommandTasks.Continue(() => {
                            foreach (var cn in parameters.Select(v => (CanonicalName)v)) {
                                _packageManager.SetGeneralPackageInformation(_priority, cn, "state", PackageState.Updatable.ToString());
                                Console.WriteLine("Setting updatable on '{0}' at priority {1}.", cn.ToString(), _priority);
                            }
                        });
                        break;

                    case "upgradable":
                    case "-G":
                        task = preCommandTasks.Continue(() => {
                            foreach (var cn in parameters.Select(v => (CanonicalName)v)) {
                                _packageManager.SetGeneralPackageInformation(_priority, cn, "state", PackageState.Updatable.ToString());
                                Console.WriteLine("Setting upgradable on '{0}' at priority {1}.", cn.ToString(), _priority);
                            }
                        });
                        break;

                    case "-i":
                    case "install":
                    case "install-package":
                    case "install-packages":
                        if (!parameters.Any()) {
                            throw new ConsoleException(Resources.InstallRequiresPackageName);
                        }
                        task = preCommandTasks.Continue(() =>InstallPackages(parameters));
                        break;

                    case "-r":
                    case "remove":
                    case "uninstall":
                    case "remove-package":
                    case "remove-packages":
                    case "uninstall-package":
                    case "uninstall-packages":
                        if (!parameters.Any()) {
                            throw new ConsoleException(Resources.RemoveRequiresPackageName);
                        }

                        task = preCommandTasks.Continue(() =>RemovePackages(parameters));
                        break;

                    case "-L":
                    case "feed":
                    case "feeds":
                    case "list-feed":
                    case "list-feeds":
                        task = preCommandTasks.Continue((Func<Task>)ListFeeds);
                        break;

                    case "-U":
                    case "upgrade":
                    case "upgrade-package":
                    case "upgrade-packages":

                        pkgFilter = pkgFilter & Package.Filters.PackagesWithUpgradeAvailable;

                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters, pkgFilter, collectionFilter, _location)
                           .Continue(packages => {
                               if (packages.IsNullOrEmpty()) {
                                   PrintNoPackagesFound(parameters);
                                   return;
                               }

                               InstallPackages(packages.Select(each => (Package)each.AvailableNewestUpdate)).Wait();
                           }));

                        break;

                    case "-u":
                    case "update":
                    case "update-package":
                    case "update-packages":
                        pkgFilter = pkgFilter & Package.Filters.PackagesWithUpdateAvailable;

                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters, pkgFilter, collectionFilter, _location)
                           .Continue(packages => {
                               if (packages.IsNullOrEmpty()) {
                                   PrintNoPackagesFound(parameters);
                                   return;
                               }

                               InstallPackages(packages.Select(each => (Package)each.AvailableNewestUpdate)).Wait();
                           }));

                        break;

                    case "-A":
                    case "add-feed":
                    case "add-feeds":
                    case "add":
                        if (!parameters.Any()) {
                            throw new ConsoleException(Resources.AddFeedRequiresLocation);
                        }
                        task =  preCommandTasks.Continue(() => AddFeed(parameters));
                        break;

                    case "-D":
                    case "-R":
                    case "delete":
                    case "delete-feed":
                    case "delete-feeds":
                        if (!parameters.Any()) {
                            throw new ConsoleException(Resources.DeleteFeedRequiresLocation);
                        }
                        task = preCommandTasks.Continue(() => DeleteFeed(parameters));
                        break;

                    case "-t":
                    case "trim-packages":
                    case "trim-package":
                    case "trim":
                        pkgFilter &= Package.Filters.Trimable;
                        task = preCommandTasks.Continue(() =>RemovePackages(parameters));
                        break;

                    case "set-feed-active":
                    case "feed-active":
                    case "activate-feed":
                        task = preCommandTasks.Continue(() => MatchFeeds(parameters)).Continue(feeds => {
                            feeds.Select(each => _packageManager.SetFeed(each, FeedState.Active)).ToArray();
                        });

                        break;
                    case "set-feed-passive":
                    case "feed-passive":
                    case "passivate-feed":
                        task = preCommandTasks.Continue(() => MatchFeeds(parameters)).Continue(feeds => {
                            feeds.Select(each => _packageManager.SetFeed(each, FeedState.Passive)).ToArray();
                        });
                        break;
                    case "set-feed-ignored":
                    case "set-feed-ignore":
                    case "feed-ignored":
                    case "feed-ignore":
                    case "disable-feed":
                        task = preCommandTasks.Continue(() => MatchFeeds(parameters)).Continue(feeds => {
                            feeds.Select(each => _packageManager.SetFeed(each, FeedState.Ignored)).ToArray();
                        });
                        break;
            #if DEPRECATED
                    case "-a":
                    case "activate":
                    case "activate-package":
                    case "activate-packages":
                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters, pkgFilter & Package.Properties.Installed.Is(true),null, _location)
                            .Continue(packages => Activate(parameters, packages)));

                        break;
            #endif
                    case "-g":
                    case "get-packageinfo":
                    case "info":
                        task = preCommandTasks.Continue(() => _packageManager.QueryPackages(parameters,pkgFilter,null, _location)
                            .Continue(packages => GetPackageInfo(parameters,packages)));
                        break;

                    case "enable-telemetry":
                        task = preCommandTasks.Continue(() => _packageManager.SetTelemetry(true)).ContinueAlways((a)=> {
                            Console.WriteLine("Telemetry is currently set to : {0}", _packageManager.GetTelemetry().Result ? "Enabled" : "Disabled");
                        });
                        break;

                    case "telemetry":
                        task = preCommandTasks.Continue(() => {
                            Console.WriteLine("Telemetry is currently set to : {0}", _packageManager.GetTelemetry().Result ? "Enabled" : "Disabled");
                        });
                        break;

                    case "disable-telemetry":
                        task = preCommandTasks.Continue(() => _packageManager.SetTelemetry(false)).ContinueAlways((a) => {
                            Console.WriteLine("Telemetry is currently set to : {0}", _packageManager.GetTelemetry().Result ? "Enabled" : "Disabled");
                        });
                        break;

                    case "create-symlink":
                        if (parameters.Count() != 2) {
                            throw new ConsoleException("Create-symlink requires two parameters: existing-location and new-link");
                        }
                        task = preCommandTasks.Continue(() =>  _packageManager.CreateSymlink(parameters.First().GetFullPath(), parameters.Last().GetFullPath()));
                        break;

                    case "create-hardlink":
                        if (parameters.Count() != 2) {
                            throw new ConsoleException("Create-hardlink requires two parameters: existing-location and new-link");
                        }
                        task = preCommandTasks.Continue(() =>  _packageManager.CreateHardlink(parameters.First().GetFullPath(), parameters.Last().GetFullPath()));
                        break;

                    case "create-shortcut":
                        if (parameters.Count() != 2) {
                            throw new ConsoleException("Create-shortcut requires two parameters: existing-location and new-link");
                        }
                        task = preCommandTasks.Continue(() =>  _packageManager.CreateShortcut(parameters.First().GetFullPath(), parameters.Last().GetFullPath()));
                        break;

                    case "-p" :
                    case "list-policies":
                    case "list-policy":
                    case "policies":
                        task = preCommandTasks.Continue(() =>  ListPolicies() );
                        break;

                    case "add-to-policy": {
                        if (parameters.Count() != 2) {
                            throw new ConsoleException("Add-to-policy requires two parameters (policy name and account)");
                        }

                        var policyName = parameters.First();
                        var account = parameters.Last();

                        task = preCommandTasks.Continue(() => {
                            _packageManager.GetPolicy(policyName).Continue(policy => {
                                // found the policy, so continue.
                                _packageManager.AddToPolicy(policyName, account).Continue(() => {
                                    Console.WriteLine("Account '{0} added to policy '{1}", account, policyName);
                                    ListPolicies(policyName);
                                });
                            });
                        });
                    }
                        break;

                    case "remove-from-policy": {
                            if (parameters.Count() != 2) {
                                throw new ConsoleException("remove-from-policy requires two parameters (policy name and account)");
                            }

                            var policyName = parameters.First();
                            var account = parameters.Last();

                            task = preCommandTasks.Continue(() => {
                                _packageManager.GetPolicy(policyName).Continue(policy => {
                                    // found the policy, so continue.
                                    _packageManager.RemoveFromPolicy(policyName, account).Continue(() => {
                                        Console.WriteLine("Account '{0} removed from policy '{1}", account, policyName);
                                        ListPolicies(policyName);
                                    });
                                });
                            });
                        }
                        break;

                    default:
                        throw new ConsoleException(Resources.UnknownCommand, command);
                }

                task.ContinueOnCanceled(() => {
                    // the task was cancelled, and presumably dealt with.
                    Fail("Operation Canceled.");
                });

                task.ContinueOnFail((exception) => {
                    exception = exception.Unwrap();
                    if (!(exception is OperationCanceledException)) {
                        var phpue = exception as PackageHasPotentialUpgradesException;
                        if (phpue != null) {
                            // we've been told something we've asked for has a newer package available, and we didn't tell it that we either wanted it or an auto-upgrade
                            PrintPotentialUpgradeInformation(phpue.UnsatisfiedPackage, phpue.SatifactionOptions);
                            phpue.Cancel(); // marks this exception as handled.
                            return;
                        }

                        // handle coapp exceptions as cleanly as possible.
                        var ce = exception as CoAppException;
                        if (ce != null) {
                            // Fail("Alternative");
                            Fail(ce.Message);

                            ce.Cancel();
                            return;
                        }
                    }

                    // hmm. The plan did not work out so well.
                    Fail("Error (???): {0}-{1}\r\n\r\n{2}", exception.GetType(), exception.Message, exception.StackTrace);

                });

                task.Continue(() => {
                    Console.WriteLine("Done.");
                }).Wait();
            }
            catch (ConsoleException failure) {
                Fail("{0}\r\n\r\n    {1}", failure.Message, Resources.ForCommandLineHelp);
                CancellationTokenSource.Cancel();
            }
            return 0;
        }
Пример #38
0
        private Task InstallPackages(IEnumerable<string> parameters)
        {
            // given what the user requested, what packages are they really asking for?
            collectionFilter = collectionFilter.Then(p => p.HighestPackages());
            return _packageManager.QueryPackages(parameters, pkgFilter, collectionFilter, _location).Continue(packages => {
                // we got back a package collection for what the user passed in.

                // but, we *can* get back an empty collection...
                if (packages.IsNullOrEmpty()) {
                    PrintNoPackagesFound(parameters);
                    return;
                }

                InstallPackages(packages).Wait();
            });
        }
Пример #39
0
        internal void ProcessBasicPackageInformation()
        {
            // -----------------------------------------------------------------------------------------------------------------------------------
            // New Step: Validate the basic information of this package
            string pkgName = Source.PackageRules.GetProperty("name").Value;
            Architecture pkgArchitecture = Architecture.Auto;
            FourPartVersion pkgVersion = Source.PackageRules.GetPropertyValue("version");
            FlavorString pkgFlavor = Source.PackageRules.GetPropertyValue("flavor");
            string pkgPublicKeyToken = Source.Certificate.PublicKeyToken;

            if (string.IsNullOrEmpty(pkgName)) {
                Event<Error>.Raise(
                    MessageCode.MissingPackageName, Source.PackageRules.Last().SourceLocation, "Missing property 'name' in 'package' rule.");
            }

            if (pkgVersion == 0) {
                // try to figure out package version from binaries.
                // check assemblies first
                foreach (var assembly in Assemblies) {
                    pkgVersion = assembly.Version;
                    if (pkgVersion == 0) {
                        Event<Error>.Raise(
                            MessageCode.AssemblyHasNoVersion, assembly.Rule.SourceLocation, "Assembly '{0}/{1}' doesn't have a version.", assembly.Name, assembly.Culture ?? "");
                    } else {
                        Event<Warning>.Raise(
                            MessageCode.AssumingVersionFromAssembly, Assemblies.First().Rule.SourceLocation,
                            "Package Version not specified, assuming version '{0}' from first assembly", pkgVersion.ToString());

                        if (pkgArchitecture == Architecture.Auto || pkgArchitecture == Architecture.Unknown) {
                            // while we're here, let's grab this as the architecture.
                            pkgArchitecture = assembly.Architecture;
                        }

                        break;
                    }
                }
                if (pkgVersion == 0) {
                    // check application next
                    foreach (var file in DestinationDirectoryFiles) {
                        var binary = Binary.Load(file.SourcePath).Result;

                        if (binary.IsPEFile) {
                            pkgVersion = binary.FileVersion;

                            Event<Warning>.Raise(
                                MessageCode.AssumingVersionFromApplicationFile, null,
                                "Package Version not specified, assuming version '{0}' from application file '{1}'", pkgVersion.ToString(),
                                file.SourcePath);

                            if (pkgArchitecture == Architecture.Auto || pkgArchitecture == Architecture.Unknown) {
                                // while we're here, let's grab this as the architecture.
                                if (binary.IsAnyCpu) {
                                    pkgArchitecture = Architecture.Any;
                                } else if (binary.Is64Bit) {
                                    pkgArchitecture = Architecture.x64;
                                } else {
                                    pkgArchitecture = Architecture.x86;
                                }
                            }

                            break;
                        }
                    }
                }

                if (pkgVersion == 0) {
                    Event<Error>.Raise(MessageCode.UnableToDeterminePackageVersion, null, "Unable to determine package version.");
                    return; // fast fail.
                }

            }

            // set any assemblies without version numbers to package version
            foreach (var assembly in Assemblies.Where(each => each.Version == 0L)) {
                assembly.Version = pkgVersion;
            }

            // make sure that all the assemblies have the same version as the package
            foreach (var assembly in Assemblies.Where(each => each.Version != pkgVersion)) {
                Event<Error>.Raise(MessageCode.AssemblyVersionDoesNotMatch, null, "Assembly '{0}' has different version ({1}) that this package ({2}) .", assembly.Name, assembly.Version, Version);
            }

            // check to see that all the assemblies are the same version.
            var versions = Assemblies.Select(each => each.Version).Distinct().ToArray();
            if (versions.Length > 1) {
                foreach (var asm in Assemblies) {
                    Event<Error>.Raise(
                        MessageCode.MultipleAssemblyVersions, asm.Rule.SourceLocation, "All Assemblies must have the same version. '{0}' Version => {1}.",
                        asm.Name, asm.Version);
                }
                // fail fast, this is pointless.
                return;
            }

            var arch = Source.PackageRules.GetPropertyValue("arch") as string;
            arch = arch ?? Source.PackageRules.GetPropertyValue("architecture") as string;
            if ((pkgArchitecture == Architecture.Auto || pkgArchitecture == Architecture.Unknown) && arch != null) {
                pkgArchitecture = arch;
            }

            // is it still not set?
            if (pkgArchitecture == Architecture.Auto || pkgArchitecture == Architecture.Unknown) {
                // figure it out from what's going in the package.
                Event<Error>.Raise(MessageCode.UnableToDeterminePackageArchitecture, null, "Unable to determine package architecture.");
            }

            var locations = Source.PackageRules.GetPropertyValues("location").Union(Source.PackageRules.GetPropertyValues("locations"));
            if( !locations.IsNullOrEmpty()) {
                Locations = new XList<Uri>();
                Locations.AddRange(locations.Select(location => location.ToUri()).Where(uri => uri != null));
            }

            var feeds = Source.PackageRules.GetPropertyValues("feed").Union(Source.PackageRules.GetPropertyValues("feeds"));
            if (!feeds.IsNullOrEmpty()) {
                Feeds = new XList<Uri>();
                Feeds.AddRange(feeds.Select(feed => feed.ToUri()).Where(uri => uri != null));
            }

            var publisher = Source.PackageRules.GetPropertyValue("publisher");

            if( !string.IsNullOrEmpty(publisher)) {
                var identityRules = Source.IdentityRules.GetRulesByParameter(publisher);
                if (!identityRules.IsNullOrEmpty()) {
                    PackageDetails.Publisher = new Identity {
                        Name = identityRules.GetPropertyValue("name"),
                        Email = identityRules.GetPropertyValue("email"),
                        Location = identityRules.GetPropertyValue("website").ToUri()
                    };
                }
            }
            CanonicalName = string.Format("coapp:{0}{1}-{2}-{3}-{4}", pkgName, pkgFlavor, pkgVersion, pkgArchitecture, pkgPublicKeyToken);
        }
Пример #40
0
 public Product()
 {
     UsedBy = new XList<string>();
     DependenciesThatNeedToUpdate = new XList<string>();
 }