Example #1
0
        public void SourceItem_CaseInsensitive_ParsedSuccessfully()
        {
            // Arrange
            var config = @"
<configuration>
    <PACkagEsourCEs>
        <AdD key='nugetorg' value='http://serviceIndexorg.test/api/index.json' />
    </PACkagEsourCEs>
</configuration>";

            var expectedValue = new SourceItem("nugetorg", "http://serviceIndexorg.test/api/index.json");

            var nugetConfigPath = "NuGet.Config";

            using (var mockBaseDirectory = TestDirectory.Create())
            {
                ConfigurationFileTestUtility.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);

                // Act and Assert
                var settingsFile = new SettingsFile(mockBaseDirectory);
                settingsFile.Should().NotBeNull();

                var section = settingsFile.GetSection("PACkagEsourCEs");
                section.Should().NotBeNull();

                var children = section.Items.ToList();

                children.Should().NotBeEmpty();
                children.Count.Should().Be(1);

                children[0].DeepEquals(expectedValue).Should().BeTrue();
            }
        }
Example #2
0
        /// <summary>
        ///     Writes the provided value to the Item's <see cref="SourceItem"/> or <see cref="Provider"/>, depending on the value
        ///     of the <see cref="Source"/> property.
        /// </summary>
        /// <param name="value">The value to write.</param>
        /// <returns>A value indicating whether the write operation succeeded.</returns>
        /// <threadsafety instance="true"/>
        public virtual bool WriteToSource(object value)
        {
            bool result = false;

            ItemSource source = Source;

            sourceItemLock.EnterWriteLock();
            providerLock.EnterWriteLock();

            try
            {
                if (source == ItemSource.Item)
                {
                    result = SourceItem.WriteToSource(value);
                }
                else if (source == ItemSource.Provider && Provider is IWriteable)
                {
                    result = ((IWriteable)Provider).Write(this, value);
                }
            }
            finally
            {
                providerLock.ExitWriteLock();
                sourceItemLock.ExitWriteLock();
            }

            if (result)
            {
                ChangeValue(value);
            }

            return(result);
        }
Example #3
0
        public void SourceItem_Equals_WithSameProtocolDifferentKey_ReturnsFalse()
        {
            var source1 = new SourceItem("key1", "value1", "3");
            var source2 = new SourceItem("keyN", "value1", "3");

            source1.Equals(source2).Should().BeFalse();
        }
Example #4
0
        public void SourcesCommandTest_AddSource(string source, bool shouldWarn)
        {
            using (SimpleTestPathContext pathContext = new SimpleTestPathContext())
            {
                TestDirectory             workingPath = pathContext.WorkingDirectory;
                SimpleTestSettingsContext settings    = pathContext.Settings;

                // Arrange
                string nugetexe = Util.GetNuGetExePath();
                var    args     = new string[] {
                    "sources",
                    "Add",
                    "-Name",
                    "test_source",
                    "-Source",
                    source,
                    "-ConfigFile",
                    settings.ConfigPath
                };

                // Act
                CommandRunnerResult result = CommandRunner.Run(nugetexe, workingPath, string.Join(" ", args), true);

                // Assert
                Assert.Equal(0, result.ExitCode);
                ISettings      loadedSettings        = Configuration.Settings.LoadDefaultSettings(workingPath, null, null);
                SettingSection packageSourcesSection = loadedSettings.GetSection("packageSources");
                SourceItem     sourceItem            = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source");
                Assert.Equal(source, sourceItem.GetValueAsPath());
                Assert.Equal(shouldWarn, result.Output.Contains("WARNING: You are running the 'add source' operation with an 'HTTP' source"));
            }
        }
        private Parser GetParser()
        {
            if (_parser == null)
                {
                    using (var options = new CompilerOptions())
                    {
                        var sourceItems = new SourceItem[]{
                            new TextItem()
                            {

                                Name = "GdlGrammer", ContentType = TextItemType.MGrammar, Reader = new StringReader(Language)
                            }
                        };

                        options.AddSourceItems(sourceItems);

                        CompilationResults results = Compiler.Compile(options);
                        if (results.HasErrors)
                        {
                            //TODO: show meaningful error message
                            throw new Exception("Failed to compile GDL ....");
                        }
                        else
                        {
                            foreach (var parserFactory in results.ParserFactories)
                            {
                                //TODO: Why inside foreach loop!!!
                                _parser = parserFactory.Value.Create();
                            }
                        }
                    }
                }
                return _parser;
        }
        public void ShouldWorkWithASingleInputSchemaComponent()
        {
            var mapForceMapping = new MapForceMapping(new List <SchemaComponent>
            {
                new SchemaComponent("Schema1.xsd", "{http://www.ebinterface.at/schema/3p0/}Entry1", new[] { new Namespace("http://www.ebinterface.at/schema/3p0/"), },
                                    new Entry("Entry1", InputOutputKey.None, XsdObjectType.Element,
                                              new[]
                {
                    new Entry("Entry2", InputOutputKey.Output(null, "2"), XsdObjectType.Element,
                              new[]
                    {
                        new Entry("Entry3", InputOutputKey.Output(null, "3"), XsdObjectType.Element),
                    }),
                })),
            },
                                                      new List <ConstantComponent>(),
                                                      new List <FunctionComponent>(),
                                                      new Graph(new Vertex[0]));
            var expectedRoot   = new SourceItem("Entry1", null, XsdObjectType.Element, null);
            var expectedChild1 = new SourceItem("Entry2", null, XsdObjectType.Element, null);
            var expectedChild2 = new SourceItem("Entry3", null, XsdObjectType.Element, null);

            expectedRoot.AddChild(expectedChild1);
            expectedChild1.AddChild(expectedChild2);

            var          xsdFileName  = TestUtils.PathToTestResource(@"XSDImporterTest\mapping\mapForceSourceElementTreeTests\Schema1.xsd");
            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();

            xmlSchemaSet.Add(XmlSchema.Read(XmlReader.Create(xsdFileName), null));

            var sourceElementTree = new MapForceSourceItemTree(mapForceMapping, xmlSchemaSet);

            AssertTreesAreEqual(expectedRoot, sourceElementTree.RootSourceItem, string.Empty);
        }
Example #7
0
 private void Clipboard_Copy(object sender, EventArgs e)
 {
     if (SourceItem != null)
     {
         Clipboard.SetText(SourceItem.GetClipboardString());
     }
 }
Example #8
0
 public Source(SourceItem sourceItem)
 {
     this.Value    = sourceItem.Value;
     this.Ordering = sourceItem.Ordering;
     this.Enabled  = sourceItem.Enabled;
     this.GetTags  = sourceItem.GetTags;
 }
Example #9
0
 public OutputItem(
     SourceItem viewFileInfo,
     RazorCSharpDocument cSharpDocument)
 {
     ViewFileInfo   = viewFileInfo;
     CSharpDocument = cSharpDocument;
 }
Example #10
0
        private static SourceItem[] GetSourceItems(List <string> sources, List <string> outputs, List <string> relativePath, List <string> fileKinds, List <string> cssScopeSources, List <string> cssScopeValues)
        {
            var cssScopeAssociations = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);

            for (var cssScopeSourceIndex = 0; cssScopeSourceIndex < cssScopeSources.Count; cssScopeSourceIndex++)
            {
                cssScopeAssociations.Add(cssScopeSources[cssScopeSourceIndex], cssScopeSourceIndex);
            }

            var items = new SourceItem[sources.Count];

            for (var i = 0; i < items.Length; i++)
            {
                var fileKind = fileKinds.Count > 0 ? fileKinds[i] : "mvc";
                if (Language.FileKinds.IsComponent(fileKind))
                {
                    fileKind = Language.FileKinds.GetComponentFileKindFromFilePath(sources[i]);
                }

                var cssScopeValue = cssScopeAssociations.TryGetValue(sources[i], out var cssScopeIndex)
                    ? cssScopeValues[cssScopeIndex]
                    : null;

                items[i] = new SourceItem(sources[i], outputs[i], relativePath[i], fileKind, cssScopeValue);
            }

            return(items);
        }
Example #11
0
        public void Sources_WarnWhenAdding(string source, bool shouldWarn)
        {
            using (SimpleTestPathContext pathContext = new SimpleTestPathContext())
            {
                TestDirectory             workingPath = pathContext.WorkingDirectory;
                SimpleTestSettingsContext settings    = pathContext.Settings;

                // Arrange
                var args = new string[]
                {
                    "nuget",
                    "add",
                    "source",
                    source,
                    "--name",
                    "test_source",
                    "--configfile",
                    settings.ConfigPath
                };

                // Act
                CommandRunnerResult result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true);

                // Assert
                Assert.True(result.Success, result.Output + " " + result.Errors);

                ISettings loadedSettings = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null);

                SettingSection packageSourcesSection = loadedSettings.GetSection("packageSources");
                SourceItem     sourceItem            = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source");
                Assert.Equal(source, sourceItem.GetValueAsPath());
                Assert.Equal(shouldWarn, result.Output.Contains("warn : You are running the 'add source' operation with an 'HTTP' source"));
            }
        }
Example #12
0
        private void moveImageFiles(SourceItem rootItem, ZipFileSettings settings, int volumeNumber)
        {
            var seq             = 1;
            var fileCountLength = rootItem.Children.Count.ToString().Length;

            foreach (var imageItem in rootItem.Children.OrderBy(c => c.FileName))
            {
                if (!File.Exists(imageItem.ItemPath))
                {
                    continue;
                }

                var destinationPath = this.getImageFileName(settings, volumeNumber, seq, fileCountLength, imageItem, rootItem);

                if (!imageItem.IsSplit)
                {
                    File.Move(imageItem.ItemPath, destinationPath);
                    seq++;
                }
                else
                {
                    seq++;
                    var leftImagePath = this.getImageFileName(settings, volumeNumber, seq, fileCountLength, imageItem, rootItem);
                    ImageFile.SplitVerticalToFile(imageItem.ItemPath, leftImagePath, destinationPath);
                    seq++;
                }
            }
        }
Example #13
0
        public void SourceItem_Equals_WithSameKeyAndProtocol_ReturnsTrue()
        {
            var source1 = new SourceItem("key1", "value1", "3");
            var source2 = new SourceItem("key1", "valueN", "3");

            source1.Equals(source2).Should().BeTrue();
        }
        public void ShouldBuildCompleteSourceElementTree()
        {
            var mappingFileName = TestUtils.PathToTestResource(@"XSDImporterTest\mapping\mapForceSourceElementTreeTests\BuildCompleteSourceElementTree\mapping.mfd");
            var mapForceMapping = LinqToXmlMapForceMappingImporter.ImportFromFiles(mappingFileName);

            var          xsdFileName  = TestUtils.PathToTestResource(@"XSDImporterTest\mapping\mapForceSourceElementTreeTests\BuildCompleteSourceElementTree\source.xsd");
            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();

            xmlSchemaSet.Add(XmlSchema.Read(XmlReader.Create(xsdFileName), null));

            var person              = new SourceItem("Person", null, XsdObjectType.Element, null);
            var personNameElement   = new SourceItem("Name", null, XsdObjectType.Element, null);
            var personNameAttribute = new SourceItem("Name", null, XsdObjectType.Attribute, null);
            var personHomeAddress   = new SourceItem("HomeAddress", null, XsdObjectType.Element, null);
            var addressTown         = new SourceItem("Town", null, XsdObjectType.Element, null);

            person.AddChild(personNameElement);
            person.AddChild(personHomeAddress);
            person.AddChild(personNameAttribute);
            personHomeAddress.AddChild(addressTown);

            var sourceElementTree = new MapForceSourceItemTree(mapForceMapping, xmlSchemaSet);

            AssertTreesAreEqual(person, sourceElementTree.RootSourceItem, string.Empty);
        }
Example #15
0
 public OutputItem(
     SourceItem inputItem,
     RazorCSharpDocument cSharpDocument)
 {
     InputItem      = inputItem;
     CSharpDocument = cSharpDocument;
 }
Example #16
0
 public SourceForm(SourceItem item)
 {
     InitializeComponent();
     Item          = item;
     tbSource.Text = item.Source;
     tbLink.Text   = item.Link;
     tbDate.Text   = item.Date;
 }
 private static void AssertTreesAreEqual(SourceItem expected, SourceItem actual, string path)
 {
     Assert.AreEqual(expected.Name, actual.Name, "Name mismatch at " + path);
     Assert.AreEqual(expected.Children.Count, actual.Children.Count, "Unequal number of children at " + path + "/" + expected.Name);
     for (int i = 0; i < expected.Children.Count; i++)
     {
         AssertTreesAreEqual(expected.Children[i], actual.Children[i], path + "/" + expected.Name);
     }
 }
Example #18
0
        public void Sources_WarnWhenUpdatingHttpSource(string updateSource, bool shouldWarn)
        {
            using (TestDirectory configFileDirectory = _fixture.CreateTestDirectory())
            {
                string configFileName = "nuget.config";
                string configFilePath = Path.Combine(configFileDirectory, configFileName);

                var nugetConfig =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources>
    <add key=""test_source"" value=""http://source.test.initial"" />
  </packageSources>
</configuration>";
                CreateXmlFile(configFilePath, nugetConfig);

                ISettings settings = Settings.LoadDefaultSettings(
                    configFileDirectory,
                    configFileName,
                    null);

                PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);
                var sources = packageSourceProvider.LoadPackageSources().ToList();
                Assert.Single(sources);

                PackageSource source = sources.Single();
                Assert.Equal("test_source", source.Name);
                Assert.Equal("http://source.test.initial", source.Source);

                // Arrange
                var args = new string[]
                {
                    "nuget",
                    "update",
                    "source",
                    "test_source",
                    "--source",
                    updateSource,
                    "--configfile",
                    configFilePath
                };

                // Act
                CommandRunnerResult result = _fixture.RunDotnet(configFileDirectory, string.Join(" ", args), ignoreExitCode: true);

                // Assert
                Assert.True(result.Success, result.Output + " " + result.Errors);

                ISettings loadedSettings = Settings.LoadDefaultSettings(root: configFileDirectory, configFileName: null, machineWideSettings: null);

                SettingSection packageSourcesSection = loadedSettings.GetSection("packageSources");
                SourceItem     sourceItem            = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source");
                Assert.Equal(updateSource, sourceItem.GetValueAsPath());
                Assert.Equal(shouldWarn, result.Output.Contains("warn : You are running the 'update source' operation with an 'HTTP' source"));
            }
        }
		public void Verify()
		{
			var source = new SourceItem { SourceProperty = 6776 };
			var repository = GlobalServiceProvider.GetService<IServiceRepository>();
			repository.Add( source );

			var copy = new SourceItem();
			Assert.Equal( source.SourceProperty, copy.SourceProperty );
			Assert.NotEqual( 0, copy.SourceProperty );
		}
            public override void AddSource(SourceClass source, string name)
            {
                ReadValue.Add(name, false);
                Dictionary.Add(name, source);

                if (!SourceItem.Contains(source))
                {
                    SourceItem.Add(source);
                    source.ReadValue += OnReadValue;
                }
            }
        public void AsSourceItem_WorksCorrectly()
        {
            var source = new PackageSource("Source", "SourceName", isEnabled: false)
            {
                ProtocolVersion = 43
            };

            var expectedItem = new SourceItem("SourceName", "Source", "43");

            SettingsTestUtils.DeepEquals(source.AsSourceItem(), expectedItem).Should().BeTrue();
        }
        // When source is clicked on in UI Feedback of True is sent back
        private void SourceDevice_Selected(object sender, UIEventArgs e)
        {
            if (e.SigArgs.Sig.BoolValue)
            {
                ClearSourceSelection();

                SourceItem source = (SourceItem)((Selector.Source)sender).UserObject;
                source.IsSelected = true;

                ((Selector.Source)sender).SourceIsSelected((sig, component) => { sig.BoolValue = source.IsSelected; });
            }
        }
Example #23
0
        private SourceItem[] GetInputItems(string projectDirectory, List <string> sources, List <string> outputs, List <string> relativePath)
        {
            var items = new SourceItem[sources.Count];

            for (var i = 0; i < items.Length; i++)
            {
                var outputPath = Path.Combine(projectDirectory, outputs[i]);
                items[i] = new SourceItem(sources[i], outputs[i], relativePath[i]);
            }

            return(items);
        }
 public int FindItemPosition(SourceItem source)
 {
     Gtk.Widget [] children = this.Children;
     for (int i = 0; i < children.Length; i++)
     {
         if (children [i] == source)
         {
             return(i);
         }
     }
     return(-1);
 }
Example #25
0
 public override EvaluateSource GetNewValues(EvaluateSource initValues)
 {
     SourceItem conceptValues = InternalValues as SourceItem;
     if (conceptValues == null)
     {
         return ReturnFailure(initValues);
     }
     return new EvaluateSource
     {
         // PROPERTIES SET
         // PROPERTIES SET
     };
 }
Example #26
0
        private string getImageFileName(ZipFileSettings settings,
                                        int volumeNumber,
                                        int pageSequence,
                                        int fileCountLength,
                                        SourceItem imageItem,
                                        SourceItem rootItem)
        {
            var newFileName = settings.GetImageFileName(volumeNumber,
                                                        pageSequence,
                                                        fileCountLength) + Path.GetExtension(imageItem.ItemPath);

            return(Path.Combine(rootItem.DestinationFolderPath, newFileName));
        }
Example #27
0
        private void createDestinationFolder(SourceItem volumeRoot, ZipFileSettings settings, int volumeNumber)
        {
            if (!string.IsNullOrEmpty(volumeRoot.DestinationFolderPath))
            {
                return;
            }

            volumeRoot.DestinationFolderPath = Path.Combine(settings.ImageFilesExtractedFolder.Value, settings.GetVolumeRootFolderName(volumeNumber));
            if (!Directory.Exists(volumeRoot.DestinationFolderPath))
            {
                Directory.CreateDirectory(volumeRoot.DestinationFolderPath);
            }
        }
Example #28
0
        public SourceItem[] QueryItems(int revision, string[] paths, Recursion recursion)
        {
            List <ItemSpec> itemSpecs = new List <ItemSpec>();

            foreach (string path in paths)
            {
                ItemSpec itemspec = new ItemSpec();
                itemspec.item    = GetServerPath(path);
                itemspec.recurse = RecursionType.None;
                switch (recursion)
                {
                case Recursion.OneLevel:
                    itemspec.recurse = RecursionType.OneLevel;
                    break;

                case Recursion.Full:
                    itemspec.recurse = RecursionType.Full;
                    break;
                }
                itemSpecs.Add(itemspec);
            }
            ItemSet[] items = sourceControlService.QueryItems(serverUrl, credentials, VersionSpec.FromChangeset(revision), itemSpecs.ToArray());

            SortedList <string, SourceItem> result = new SortedList <string, SourceItem>();

            foreach (ItemSet itemset in items)
            {
                foreach (Item item in itemset.Items)
                {
                    SourceItem sourceItem = new SourceItem();
                    sourceItem.RemoteChangesetId = item.cs;
                    sourceItem.RemoteDate        = item.date.ToUniversalTime();
                    sourceItem.ItemType          = item.type;
                    sourceItem.ItemId            = item.itemid;
                    sourceItem.RemoteName        = item.item;
                    var downloadUrlExtension = serverUrl.Contains("/tfs/") ? "ashx" : "asmx";
                    sourceItem.DownloadUrl = serverUrl + "/VersionControl/v1.0/item." + downloadUrlExtension + "?" + item.durl;
                    if (!result.ContainsKey(sourceItem.RemoteName))
                    {
                        result.Add(sourceItem.RemoteName, sourceItem);
                    }
                }
            }
            List <SourceItem> result2 = new List <SourceItem>();

            foreach (SourceItem sourceItem in result.Values)
            {
                result2.Add(sourceItem);
            }
            return(result2.ToArray());
        }
Example #29
0
 public void Setup()
 {
     dataFetcher = new Mock <IDataFetcher>();
     scraper     = new Scraper(dataFetcher.Object, 5);
     postItem    = new SourceItem
     {
         By          = "adams",
         Title       = "hitchhiker's guide to the galaxy",
         Descendants = 10,
         Score       = 123,
         Url         = "http://thesite.com/2019/11/article"
     };
     dataFetcher.Setup(x => x.GetPostItem(It.IsAny <int>())).Returns(Task.FromResult(postItem));
 }
Example #30
0
        private SourceItem[] GetSourceItems(string projectDirectory, List <string> sources, List <string> outputs, List <string> relativePath, List <string> documentKinds)
        {
            var items = new SourceItem[sources.Count];

            for (var i = 0; i < items.Length; i++)
            {
                var outputPath   = Path.Combine(projectDirectory, outputs[i]);
                var documentKind = documentKinds.Count > 0 ? documentKinds[i] : "mvc";

                items[i] = new SourceItem(sources[i], outputs[i], relativePath[i], documentKind);
            }

            return(items);
        }
Example #31
0
 public RenamedSourceItem(SourceItem item,
                          string originalRemoteName,
                          int originalRevision)
 {
     ItemId             = item.ItemId;
     ItemType           = item.ItemType;
     RemoteName         = item.RemoteName;
     RemoteDate         = item.RemoteDate;
     DownloadUrl        = item.DownloadUrl;
     RemoteChangesetId  = item.RemoteChangesetId;
     LocalChangesetId   = item.LocalChangesetId;
     OriginalRemoteName = originalRemoteName;
     OriginalRevision   = originalRevision;
 }
Example #32
0
        private ListViewItem AddListViewItem(SourceItem props)
        {
            const string toolTipText = "Source {0} is a special built-in source that copies these messages\r\nto a log. As there is no mechanism to to set severity for these sources,\r\nthere are no severity levels, logging is either On (All) or Off.";
            var          item        = new ListViewItem(props.Name);

            item.Name = props.Name;
            item.Tag  = props;
            if (SpecialSources.Any(m => m.EqualsI(props.Name)))
            {
                item.ToolTipText = string.Format(toolTipText, props.Name);
            }

            props.NamePropertyChanging += (s, e) =>
            {
                if (m_lvSources.Items.Cast <ListViewItem>().Any(m => m.Text.EqualsI(e.NewValue)))
                {
                    MiniMessageBox.ShowDialog(m_cmbName, "Duplicate Source Name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;

                    //Callstack to this point:
                    // m_cmbName.TextUpdate => props.Name => props.NamePropertyChanging
                    // m_cmbName.SelectedValueChanged => props.Name => props.NamePropertyChanging

                    m_cmbName.Text = e.CurrentValue; //This works when the source is from TextUpdate, but not from SelectedValueChanged.
                    //To revert from SelectedValueChanged we need to update AFTER the event. Not within it. For TextUpdate this is merely redundent.
                    System.Threading.ThreadPool.QueueUserWorkItem((arg) =>
                    {
                        System.Threading.Thread.Sleep(5);
                        m_cmbName.BeginInvoke(new Action(() => { m_cmbName.Text = e.CurrentValue; }));
                    });
                    return;
                }

                if (SpecialSources.Any(m => m.EqualsI(e.NewValue)))
                {
                    item.ToolTipText = string.Format(toolTipText, e.NewValue);
                }
                else
                {
                    item.ToolTipText = "";
                }

                item.Text = e.NewValue;
            };

            m_lvSources.Items.Add(item);
            return(item);
        }
Example #33
0
        public void AddSource(string path)
        {
            TextBox linkTextBox = new TextBox();
            TextBox pathTextBox = new TextBox();
            StackPanel stackPanel = new StackPanel();
            SourceItem sourceItem = new SourceItem(path, linkTextBox, pathTextBox);
            sourceItem.LinkChanged += LinkChangedHandler;
            sourceItem.PathChanged += PathChangedHandler;
            sourceItem.NeedUpdate += NeedUpdateHandler;
            sourcesCollection.Add(sourceItem);

            stackPanel.Width = sourceList.Width - 10;
            stackPanel.Orientation = Orientation.Horizontal;
            stackPanel.Children.Add(linkTextBox);
            stackPanel.Children.Add(pathTextBox);

            linkTextBox.Width = 30;
            pathTextBox.Width = stackPanel.Width - linkTextBox.Width - pathLeftMargin;
            Thickness margin = new Thickness();
            margin.Left = pathLeftMargin;
            pathTextBox.Margin = margin;

            sourceList.Items.Add(stackPanel);
        }
Example #34
0
        internal static Parser GetParser()
        {
            using (var options = new CompilerOptions())
            {
                var sourceItems = new SourceItem[]{

                    new TextItem()
                    {
                        Name = "GdlGrammar", ContentType = TextItemType.MGrammar, Reader = new StringReader(GDL)
                    }
                };

                options.AddSourceItems(sourceItems);

                CompilationResults results = null;
                results = Compiler.Compile(options);
                if (results.HasErrors)
                {
                    throw new Exception("Failed to compile GDL ...."
                                      + Environment.NewLine
                                      + results.Errors[0]);
                }
                else
                {
                    foreach (var parserFactory in results.ParserFactories)
                    {
                        return parserFactory.Value.Create();
                    }

                }

            }

            return null;
        }
 public bool Equals(SourceItem sourceItem)
 {
     return (sourceItem.StartIndex == this.StartIndex) && (sourceItem.Source == this.Source);
 }
	public int ImportFromFile (PhotoStore store, string path)
	{
		this.store = store;
		this.CreateDialog ("import_dialog");
		
		this.Dialog.TransientFor = main_window;
		this.Dialog.WindowPosition = Gtk.WindowPosition.CenterOnParent;
		this.Dialog.Response += HandleDialogResponse;

	        AllowFinish = false;
		
		this.Dialog.DefaultResponse = ResponseType.Ok;
		
		//import_folder_entry.Activated += HandleEntryActivate;
		recurse_check.Toggled += HandleRecurseToggled;
		copy_check.Toggled += HandleRecurseToggled;

		menu = new SourceMenu (this);
		source_option_menu.Menu = menu;

		collection = new FSpot.PhotoList (new Photo [0]);
		tray = new FSpot.ScalingIconView (collection);
		tray.Selection.Changed += HandleTraySelectionChanged;
		icon_scrolled.SetSizeRequest (200, 200);
		icon_scrolled.Add (tray);
		//icon_scrolled.Visible = false;
		tray.DisplayTags = false;
		tray.Show ();

		photo_view = new FSpot.PhotoImageView (collection);
		photo_scrolled.Add (photo_view);
		photo_scrolled.SetSizeRequest (200, 200);
		photo_view.Show ();

		//FSpot.Global.ModifyColors (frame_eventbox);
		FSpot.Global.ModifyColors (photo_scrolled);
		FSpot.Global.ModifyColors (photo_view);

		photo_view.Pixbuf = PixbufUtils.LoadFromAssembly ("f-spot-48.png");
		photo_view.Fit = true;
			
		tag_entry = new FSpot.Widgets.TagEntry (MainWindow.Toplevel.Database.Tags, false);
		tag_entry.UpdateFromTagNames (new string []{});
		tagentry_box.Add (tag_entry);

		tag_entry.Show ();

		this.Dialog.Show ();
		//source_option_menu.Changed += HandleSourceChanged;
		if (path != null) {
			SetImportPath (path);
			int i = menu.FindItemPosition (path);

			if (i > 0) {
				source_option_menu.SetHistory ((uint)i);
			} else if (Directory.Exists (path)) {
				SourceItem path_item = new SourceItem (new VfsSource (path));
				menu.Prepend (path_item);
				path_item.ShowAll ();
				SetImportPath (path);
				source_option_menu.SetHistory (0);
			} 
			idle_start.Start ();
		}
						
		ResponseType response = (ResponseType) this.Dialog.Run ();
		
		while (response == ResponseType.Ok) {
			try {
				if (Directory.Exists (this.ImportPath))
					break;
			} catch (System.Exception e){
				System.Console.WriteLine (e);
				break;
			}

			HigMessageDialog md = new HigMessageDialog (this.Dialog,
			        DialogFlags.DestroyWithParent,
				MessageType.Error,
				ButtonsType.Ok,
				Catalog.GetString ("Directory does not exist."),
				String.Format (Catalog.GetString ("The directory you selected \"{0}\" does not exist.  " + 
								  "Please choose a different directory"), this.ImportPath));

			md.Run ();
			md.Destroy ();

			response = (Gtk.ResponseType) this.Dialog.Run ();
		}

		if (response == ResponseType.Ok) {
			this.UpdateTagStore (tag_entry.GetTypedTagNames ());
			this.Finish ();

			if (tags_selected != null && tags_selected.Count > 0) {
				for (int i = 0; i < collection.Count; i++) {
					Photo p = collection [i] as Photo;
					
					if (p == null)
						continue;
					
					p.AddTag ((Tag [])tags_selected.ToArray(typeof(Tag)));
					store.Commit (p);
				}
			}

			this.Dialog.Destroy ();
			return collection.Count;
		} else {
			this.Cancel ();
			//this.Dialog.Destroy();
			return 0;
		}
	}
		public int FindItemPosition (SourceItem source)
		{
			Gtk.Widget [] children = this.Children;
			for (int i = 0; i < children.Length; i++) {
				if (children [i] == source) {
					return i;
				}
			}
			return -1;
		}
		public SourceMenu (ImportCommand command) {
			this.command = command;
			source_count = 0;
			
			SourceItem item = new SourceItem (new BrowseSource ());
			item.Activated += HandleActivated;
			this.Append (item);
			this.Append (new Gtk.SeparatorMenuItem ());

			// Add external hard drives to the menu
			foreach (Gnome.Vfs.Volume vol in monitor.MountedVolumes) {
				 if (!vol.IsUserVisible || vol.DeviceType == Gnome.Vfs.DeviceType.Unknown)
					 continue;
				
				 System.Console.WriteLine ("{0} - {1} - {2} {3} {4} {5} {6}",
							  vol.DisplayName, 
							  vol.Icon, 
							  vol.VolumeType.ToString (), 
							  vol.ActivationUri, 
							  vol.IsUserVisible,
							  vol.IsMounted,
							  vol.DeviceType);
				 
				 if (vol.Drive != null)
					 System.Console.WriteLine (vol.Drive.DeviceType.ToString ());

				 ImportSource source = new VolumeSource (vol);
				 item = new SourceItem (source);
				 item.Activated += HandleActivated;
				 this.Append (item);
				 source_count++;

			}


			GPhotoCamera cam = new GPhotoCamera ();
			cam.DetectCameras ();
			int camera_count = cam.CameraList.Count ();

			if (camera_count > 0) {
				source_count += camera_count;
				for (int i = 0; i < camera_count; i++) {
					string handle = cam.CameraList.GetValue (i);
					if (camera_count == 1 || handle != "usb:") {
						if (handle.StartsWith ("disk:")) {
							string path = handle.Substring ("disk:".Length);

							if (FindItemPosition (path) != -1)
								continue;
						}
			
						ImportSource source = new CameraSource (cam, i);
						item = new SourceItem (source);
						item.Activated += HandleActivated;
						this.Append (item);
					}
				}
			} else {
				ImportSource source = new BrowseSource (Catalog.GetString ("(No Cameras Detected)"),
									"emblem-camera");
				item = new SourceItem (source);
				item.Activated += HandleActivated;
				item.Sensitive = false;
				this.Append (item);
			}
			/*
			this.Append (new Gtk.SeparatorMenuItem ());
			
			foreach (Gnome.Vfs.Drive drive in monitor.ConnectedDrives) {
				ImportSource source = new DriveSource (drive);
				
				Gtk.ImageMenuItem item = new SourceItem (source);
				item.Sensitive = drive.IsMounted;
				this.Append (item);
			}
			*/

			this.ShowAll ();
		}