Inheritance: IDisposable
示例#1
0
        static void Main(string[] args)
        {
            string source;
            string destination;
            Options options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                source = options.Source;
                destination = options.Destination;
            }
            else
            {
                Console.WriteLine("Source: ");
                source = Console.ReadLine();
                Console.WriteLine("Destination: ");
                destination = Console.ReadLine();
            }

            Importer importer = new Importer();
            importer.ImportFiles(source, destination);

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
        public void StandardExportInterfacesShouldWork()
        {
            // Export all interfaces except IDisposable, Export contracts on types without interfaces. except for disposable types
            var builder = new ConventionBuilder();
            builder.ForTypesMatching((t) => true).ExportInterfaces();
            builder.ForTypesMatching((t) => t.GetTypeInfo().ImplementedInterfaces.Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();

            var container = new ContainerConfiguration()
                .WithPart<Standard>(builder)
                .WithPart<Dippy>(builder)
                .WithPart<Derived>(builder)
                .WithPart<BareClass>(builder)
                .CreateContainer();

            var importer = new Importer();
            container.SatisfyImports(importer);

            Assert.NotNull(importer.First);
            Assert.True(importer.First.Count() == 3);
            Assert.NotNull(importer.Second);
            Assert.True(importer.Second.Count() == 3);
            Assert.NotNull(importer.Third);
            Assert.True(importer.Third.Count() == 3);
            Assert.NotNull(importer.Fourth);
            Assert.True(importer.Fourth.Count() == 3);
            Assert.NotNull(importer.Fifth);
            Assert.True(importer.Fifth.Count() == 3);

            Assert.Null(importer.Base);
            Assert.Null(importer.Derived);
            Assert.Null(importer.Dippy);
            Assert.Null(importer.Standard);
            Assert.Null(importer.Disposable);
            Assert.NotNull(importer.BareClass);
        }
 public static ImportNotificationOverview Load(ImportNotification notification,
     ImportNotificationAssessment assessment,
     Exporter exporter,
     Importer importer,
     Producer producer,
     FacilityCollection facilities,
     Shipment shipment,
     TransportRoute transportRoute,
     WasteOperation wasteOperation,
     WasteType wasteType)
 {
     return new ImportNotificationOverview
     {
         Notification = notification,
         Assessment = assessment,
         Exporter = exporter,
         Importer = importer,
         Producer = producer,
         Facilities = facilities,
         Shipment = shipment,
         TransportRoute = transportRoute,
         WasteOperation = wasteOperation,
         WasteType = wasteType
     };
 }
示例#4
0
        public void BinaryTreeMustSortTheSameAsSortedDictionary()
        {
            // Arrange
            var asm = Assembly.GetExecutingAssembly();
            var importer = new Importer(asm.GetManifestResourceStream("ClientImport.Tests.records.txt"), ',');
            var dictionary = new SortedDictionary<string, IPerson>();
            var tree = new BinarySearchTree<string, IPerson>();

            //Act
            importer.Data
                           .ToList()
                           .ForEach(record =>
                           {
                               var person = new Person
                               {
                                   FirstName = record.FirstName,
                                   Surname = record.Surname,
                                   Age = Convert.ToInt16(record.Age)
                               };
                               var key = PersonRepository.BuildKey(person, SortKey.SurnameFirstNameAge);
                               if (tree.Find(key) == null)
                                   tree.Add(key, person);
                           }
                              );

            tree
                .ToList()
                .Shuffle() //Shuffle result from binary tree, to test sorting
                .ForEach(r => dictionary.Add(PersonRepository.BuildKey(r.KeyValue.Value, SortKey.SurnameFirstNameAge), r.KeyValue.Value));

            var expected = dictionary.Select(r => r.Value).ToList();
            var actual = tree.Select(n => n.KeyValue.Value).ToList();
            // Assert
            CollectionAssert.AreEqual(expected, actual);
        }
        internal static bool ScanMediaDirectories
            (
            string[] mediaFolders, 
            ref IList<string> extensionsToIgnore, 
            string[] filmLocations, string[] tvShowsLocations,string[] musicLocations,
            string[] videoExtensions, string[] audioExtensions,
            IEnumerable<string> combinedSceneTags,
            IEnumerable<string> videoExtensionsCommon, Importer importer 
            )
        {


            string pluginpath = Debugger.GetPluginPath();

            foreach (string importRootFolder in mediaFolders)

                if (
                    !CalculateExaminationtimeAndScanMediaFolder
                    (MediaSectionsAllocator.MoviesSection,
                    MediaSectionsAllocator.TvEpisodesSection,
                    MediaSectionsAllocator.MusicSection,
                    ref extensionsToIgnore, filmLocations, 
                    tvShowsLocations,  musicLocations,
                    videoExtensions, audioExtensions,
                    importRootFolder, pluginpath, combinedSceneTags,
                    videoExtensionsCommon )
                    )
                    return false;
            

            return true;
        }
示例#6
0
 public Parser(int optimization, IStylizer stylizer, Importer importer, bool noCache = false)
 {
     Stylizer = stylizer;
     Importer = importer;
     Tokenizer = new Tokenizer(optimization);
     NoCache = noCache;
 }
		/// <summary>
		/// Create the DevirtualizedAttribute TypeDef, with a "default .ctor" that
		/// calls the base type's .ctor (System.Attribute).
		/// </summary>
		/// <returns>TypeDef</returns>
		TypeDef CreateDevirtualizedAttribute()
		{
			var importer = new Importer(this.Module);
			var attributeRef = this.Module.CorLibTypes.GetTypeRef("System", "Attribute");
			var attributeCtorRef = importer.Import(attributeRef.ResolveTypeDefThrow().FindMethod(".ctor"));

			var devirtualizedAttr = new TypeDefUser(
				"eazdevirt.Injected", "DevirtualizedAttribute", attributeRef);
			//devirtualizedAttr.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout
			//	| TypeAttributes.Class | TypeAttributes.AnsiClass;

			var emptyCtor = new MethodDefUser(".ctor", MethodSig.CreateInstance(this.Module.CorLibTypes.Void),
				MethodImplAttributes.IL | MethodImplAttributes.Managed,
				MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName |
				MethodAttributes.ReuseSlot | MethodAttributes.HideBySig);

			var instructions = new List<Instruction>();
			instructions.Add(OpCodes.Ldarg_0.ToInstruction());
			instructions.Add(OpCodes.Call.ToInstruction(attributeCtorRef)); // Call the constructor .ctor
			instructions.Add(OpCodes.Ret.ToInstruction());
			emptyCtor.Body = new CilBody(false, instructions, new List<ExceptionHandler>(), new List<Local>());

			devirtualizedAttr.Methods.Add(emptyCtor);

			return devirtualizedAttr;
		}
示例#8
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Showes process results with details in message window.
        /// </summary>
        /// <param name="importer">Importer object.</param>
        /// <param name="geocoder">Geocoder object (can be NULL).</param>
        /// <param name="storage">Storage object</param>
        /// <param name="status">Status text.</param>
        public void Inform(Importer importer, Geocoder geocoder, Storage storage, string status)
        {
            Debug.Assert(!string.IsNullOrEmpty(status)); // not empty
            Debug.Assert(null != importer); // created
            Debug.Assert(null != storage); // created

            var details = new List<MessageDetail>();

            // add statistic
            string statistic = _CreateStatistic(importer, geocoder, storage);
            Debug.Assert(!string.IsNullOrEmpty(statistic));
            var statisticDetail = new MessageDetail(MessageType.Information, statistic);
            details.Add(statisticDetail);

            // add geocoder exception
            if ((null != geocoder) &&
                (null != geocoder.Exception))
            {
                details.Add(_GetServiceMessage(geocoder.Exception));
            }

            // add steps deatils
            details.AddRange(importer.Details);
            if (null != geocoder)
                details.AddRange(geocoder.Details);
            details.AddRange(storage.Details);

            // show status with details
            App.Current.Messenger.AddMessage(status, details);
        }
        public void ImporterCallsConverterOnce()
        {
            var importer = new Importer(_source, _converter, _destination);

            importer.Run();

            _converter.Received(1).ConvertData(Arg.Any<DataTable>());
        }
 public ImporterViewModel(Importer importer)
 {
     Address = new AddressViewModel(importer.Address);
     BusinessName = importer.BusinessName;
     Contact = new ContactViewModel(importer.Contact);
     RegistrationNumber = importer.RegistrationNumber;
     Type = importer.Type;
 }
        /// <summary>
        /// 
        /// </summary>
        protected void btnAddExampleContent_Click(object sender, EventArgs e)
        {
            Importer z = new Importer();
            // z.ExportContentTree(1068, "HelpandExample.content");
            z.ImportContentTree("HelpandExample.content");

            importMessage.Text = "Example Content Imported - You should see this on the content node.";
        }
        public void CanCreateImporter()
        {
            var business = ObjectFactory.CreateEmptyBusiness();
            var address = ObjectFactory.CreateDefaultAddress();
            var contact = ObjectFactory.CreateEmptyContact();

            var importer = new Importer(Guid.NewGuid(), address, business, contact);

            Assert.NotNull(importer);
        }
 public ImporterViewModel(Importer importer)
 {
     Name = importer.Business.Name;
     address = new AddressViewModel(importer.Address);
     ContactPerson = importer.Contact.FullName;
     Telephone = importer.Contact.Telephone.ToFormattedContact();
     Fax = importer.Contact.Fax.ToFormattedContact();
     Email = importer.Contact.Email;
     RegistrationNumber = importer.Business.RegistrationNumber;
 }
示例#14
0
        private Import(string path, Importer importer)
        {
            Importer = importer;
            var regex = new Regex(@"\.(le|c)ss$");

            Path = regex.IsMatch(path) ? path : path + ".less";

            Css = Path.EndsWith("css");

            if(!Css)
                Importer.Import(this);
        }
示例#15
0
        public void AllDataIsLoadedFromTextFileIntoPersonBinaryTree()
        {
            // Arrange
            var repository = new PersonRepository(SortKey.SurnameFirstName);
            var asm = Assembly.GetExecutingAssembly();
            var importer = new Importer(asm.GetManifestResourceStream("ClientImport.Tests.records.txt"), Delimiter);

            //Act
            repository.Import(importer.Data);

            // Assert
            Assert.AreEqual(49817, repository.Count());
        }
        public void DestinationReceivesConvertedData()
        {
            DataTable originalData = new DataTable("table1");
            DataTable convertedData = new DataTable("table2");
            _source.GetData().Returns(originalData);
            _converter.ConvertData(originalData).Returns(convertedData);

            var importer = new Importer(_source, _converter, _destination);
            importer.Run();

            Assert.NotEqual(originalData, convertedData);
            _destination.Received(1).Receive(convertedData);
        }
示例#17
0
        public void ShouldLoadTextFileDataEvenWhenFileLayoutIsChanged()
        {
            //Arrange
            var asm = Assembly.GetExecutingAssembly();

            //Act
            var importer = new Importer(asm.GetManifestResourceStream("ClientImport.Tests.recordsColumnChange.txt"), Delimiter);

            //Assert
            var data = importer.Data.ToList();

            Assert.AreEqual("Adrie", data.First().FirstName);
            Assert.AreEqual("Ballingall", data.First().Surname);
            Assert.AreEqual("111", data.First().Age);
        }
        public void ImportValues()
        {
            var container = ContainerFactory.Create();
            Importer importer = new Importer();
            Exporter exporter42 = new Exporter(42);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            batch.AddPart(exporter42);

            CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotSetImport,
                                          ErrorId.ReflectionModel_ImportNotAssignableFromExport, RetryMode.DoNotRetry, () =>
            {
                container.Compose(batch);
            });            
        }
示例#19
0
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite(@"http://*****:*****@"C:\taxonomy.xml");

                XElement termStoreCollectionElement = XElement.Parse(text);

                Importer importer = new Importer();
                XElement termStoreElement = termStoreCollectionElement.Elements().First();
                importer.ImportTermStore(session.TermStores, termStoreElement , true);

            }
        }
        public void UpdateImporterReplacesFirst()
        {
            var business = Business.CreateBusiness("first", BusinessType.SoleTrader, "123", "456");
            var address = ObjectFactory.CreateDefaultAddress();
            var contact = ObjectFactory.CreateEmptyContact();

            var importer = new Importer(Guid.NewGuid(), address, business, contact);

            var newBusiness = Business.CreateBusiness("second", BusinessType.SoleTrader, "123", "456");
            var newAddress = ObjectFactory.CreateDefaultAddress();
            var newContact = ObjectFactory.CreateEmptyContact();

            importer.Update(newAddress, newBusiness, newContact);

            Assert.Equal("second", importer.Business.Name);
        }
示例#21
0
        private Import(string path, Importer importer)
        {
            Importer = importer;
            Path = path;

            if (path.EndsWith(".css"))
            {
                Css = true;
            } else
            {
                Css = !Importer.Import(this); // it is assumed to be css if it cannot be found as less

                if (Css && path.EndsWith(".less"))
                {
                    throw new FileNotFoundException("You are importing a file ending in .less that cannot be found.", path);
                }
            }
        }
示例#22
0
文件: Import.cs 项目: bgrins/dotless
        private Import(string path, Importer importer)
        {
            Importer = importer;
            var regex = new Regex(@"\.(le|c)ss$");

            Path = regex.IsMatch(path) ? path : path + ".less";

            Css = Path.EndsWith("css");

            if (Css && Path.StartsWith(FORCE_IMPORT_PREFIX))
            {
                Css = false;
                Path = Path.Substring(FORCE_IMPORT_PREFIX.Length);
            }

            if(!Css)
                Importer.Import(this);
        }
        internal static bool DoImport(Importer importer,
            IMLSection section, IMLImportProgress progress)
        {
            try
            {

                #region INIT
                string pluginPath = Helpers.GetPluginPath();
                string debugLogPath = pluginPath + "Debug.log";

                //TODO: Replace ThisProgress with ImportProgress.CurrentProgress
                ThisProgress = progress;
                Settings.ImportingStarted = false;
                Settings.ImportingCompleted = false;

                ImportProgress.GeneralStatus = String.Empty;
                ImportProgress.SpecialStatus = String.Empty;
                ImportProgress.CurrentProgress = 0;

                #endregion

                Helpers.DeleteDebugLog(debugLogPath);

                if (!InternetConnectionDiagnostic.CheckOsDbAvailability())
                    return true;

                MediaSectionUpdater.UpdateMediaSection(section, pluginPath);

                ImportProgress.FinishImport();

                return true;

            }
            catch (Exception e)
            {

                Helpers.LogMessageToFile(
                    "An unexpected error ocurred " +
                    "in Main Import Engine. " +
                    "The error was: " + e);
            }

            return true;
        }
        public static Importer Create(Guid notiificationId, Guid id, Business business = null, Address address = null, string name = "AnyName")
        {
            if (business == null)
            {
                business = ComplexTypeFactory.Create<Business>();
                ObjectInstantiator<Business>.SetProperty(x => x.Name, name, business);
            }

            if (address == null)
            {
                address = ComplexTypeFactory.Create<Address>();
            }

            var importer = new Importer(notiificationId, address, business, ComplexTypeFactory.Create<Contact>());

            EntityHelper.SetEntityId(importer, id);

            return importer;
        }
        internal static void StartMainImportingEngine
            (Importer importer, IMLSection section,
            IEnumerable<string> combinedSceneTags)
        {


            #region Media Importers


            GeneralStatus = "Performing media importing...";
            SpecialStatus = String.Empty;

            //LibrarySynchronizerRestore
            //    .LibrarySynchronizerRestoreFromBackup
            //    (Settings.XmlBackupsDirectory);

            MediaImportingEngine.ImportMediaFilesMAIN(combinedSceneTags, importer);

            //var connectionresult = MediaImportingEngineHelpers.InitConnectionresult();
            var connectionresult = Helpers.CheckInternetConnectionAndConnectToOSDb();

            RssNewsImporter.ImportRssFeeds(connectionresult);

            #endregion


            #region Media Updaters

            if (MediaImportingEngineHelpers.RunMediaSectionsUpdatingEngine(importer, section,
                combinedSceneTags, connectionresult)) 
                return;

            #endregion


            //#region Import Secquencer
            //ImportSequencer
            //    .RunImports();
            //#endregion



        }
        public async Task<ActionResult> Index(Guid id, ImporterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var importer = new Importer(id)
            {
                Address = model.Address.AsAddress(),
                BusinessName = model.BusinessName,
                Type = model.Type,
                RegistrationNumber = model.RegistrationNumber,
                Contact = model.Contact.AsContact()
            };

            await mediator.SendAsync(new SetDraftData<Importer>(id, importer));

            return RedirectToAction("Index", "Producer");
        } 
        private TypeDef GetArrayType(long size)
        {
            CreateOurType();

            TypeDef arrayType;
            if (_arrayTypeDictionary.TryGetValue(size, out arrayType))
                return arrayType;

            var importer = new Importer(_module);
            var valueTypeRef = importer.Import(typeof (ValueType));

            arrayType = new TypeDefUser("", $"__StaticArrayInitTypeSize={size}", valueTypeRef);
            _module.UpdateRowId(arrayType);
            arrayType.Attributes = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout |
                                   TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass;
            _ourType.NestedTypes.Add(arrayType);
            _arrayTypeDictionary[size] = arrayType;
            arrayType.ClassLayout = new ClassLayoutUser(1, (uint) size);
            return arrayType;
        }
 public static NotificationApplicationOverview Load(NotificationApplication notification,
     NotificationAssessment assessment,
     WasteRecovery.WasteRecovery wasteRecovery,
     WasteDisposal wasteDisposal,
     Exporter.Exporter exporter,
     Importer.Importer importer,
     int charge,
     NotificationApplicationCompletionProgress progress)
 {
     return new NotificationApplicationOverview
     {
         Exporter = exporter,
         Importer = importer,
         Notification = notification,
         NotificationAssessment = assessment,
         WasteRecovery = wasteRecovery,
         WasteDisposal = wasteDisposal,
         Charge = charge,
         Progress = progress
     };
 }
 public ActionResult Create(Importer importer)
 {
     if (ModelState.IsValid)
     {
         var is_exist = (from i in db.Importers where i.importer_mob_no == importer.importer_mob_no select i).Count();
         if (is_exist > 0)
         {
             TempData["errorMessage"] = "This Mobile Number Already Exist";
         }
         else
         {
             importer.status_id = 1;
             importer.created_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
             importer.updated_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
             db.Importers.Add(importer);
             db.SaveChanges();
             TempData["errorMessage"] = "Importer Added Successfully";
         }
         return RedirectToAction("Index");
     }
     return RedirectToAction("Index");
 }
示例#30
0
        public static ContentVersionRepository CreateVersionRepository(ref IPersister persister, ref ContentActivator activator, ref IRepository <ContentVersion> versionRepository, params Type[] definedTypes)
        {
            if (persister == null)
            {
                persister = SetupFakePersister();
            }
            var definitions  = SetupDefinitions(definedTypes);
            var parser       = new UrlParser(persister, new ThreadContext(), new Host(new ThreadContext(), new HostSection()), new ConnectionMonitor(), new HostSection());
            var proxyFactory = new InterceptingProxyFactory();

            if (activator == null)
            {
                activator = new ContentActivator(new StateChanger(), new ItemNotifier(), proxyFactory);
                activator.Initialize(definitions.GetDefinitions());
            }
            if (versionRepository == null)
            {
                versionRepository = new FakeRepository <ContentVersion>();
            }
            var importer = new Importer(persister,
                                        new ItemXmlReader(definitions,
                                                          activator,
                                                          persister.Repository),
                                        new Fakes.FakeMemoryFileSystem());
            var exporter = new Exporter(
                new ItemXmlWriter(
                    definitions,
                    parser,
                    new FakeMemoryFileSystem()));

            return(new ContentVersionRepository(
                       versionRepository,
                       exporter,
                       importer,
                       parser,
                       proxyFactory));
        }
示例#31
0
        internal void Run()
        {
            var target = Context.TargetModule;

            if (_source.HasResources)
            {
                foreach (var r in _source.Resources)
                {
                    if (r is LinkedResource lr &&
                        Context.MappedResources.TryGetValue(DnextFactory.NewTypeKey(_source, r), out var mapping) &&
                        mapping.Target is LinkedResource tlr && tlr.File == lr.File)
                    {
                        tlr.File = Clone(lr.File);
                    }
                }
            }


            if (_source == Context.MainSourceModule)
            {
                if (_source.Win32Resources != null)
                {
                    target.Win32Resources = _source.Win32Resources;
                }
                var sourceAssembly = _source.Assembly;
                var targetAssembly = target.Assembly;
                CopyCustomAttributes(_source, target);
                CopyCustomAttributes(sourceAssembly, targetAssembly);
                CopyCustomDebugInfo(_source, target);
                CopyCustomDebugInfo(sourceAssembly, targetAssembly);
                CopyDeclSecurities(sourceAssembly, targetAssembly);
                if (_source.IsEntryPointValid)
                {
                    target.EntryPoint = Importer.Import(_source.EntryPoint).ResolveMethodDef();
                }
            }
        }
示例#32
0
        public void StandardExportInterfacesShouldWork()
        {
            // Export all interfaces except IDisposable, Export contracts on types without interfaces. except for disposable types
            var builder = new ConventionBuilder();

            builder.ForTypesMatching((t) => true).ExportInterfaces();
            builder.ForTypesMatching((t) => t.GetTypeInfo().ImplementedInterfaces.Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();

            var container = new ContainerConfiguration()
                            .WithPart <Standard>(builder)
                            .WithPart <Dippy>(builder)
                            .WithPart <Derived>(builder)
                            .WithPart <BareClass>(builder)
                            .CreateContainer();

            var importer = new Importer();

            container.SatisfyImports(importer);

            Assert.IsNotNull(importer.First);
            Assert.IsTrue(importer.First.Count() == 3);
            Assert.IsNotNull(importer.Second);
            Assert.IsTrue(importer.Second.Count() == 3);
            Assert.IsNotNull(importer.Third);
            Assert.IsTrue(importer.Third.Count() == 3);
            Assert.IsNotNull(importer.Fourth);
            Assert.IsTrue(importer.Fourth.Count() == 3);
            Assert.IsNotNull(importer.Fifth);
            Assert.IsTrue(importer.Fifth.Count() == 3);

            Assert.IsNull(importer.Base);
            Assert.IsNull(importer.Derived);
            Assert.IsNull(importer.Dippy);
            Assert.IsNull(importer.Standard);
            Assert.IsNull(importer.Disposable);
            Assert.IsNotNull(importer.BareClass);
        }
        public void StandardExportInterfacesInterfaceFilterDefaultContractShouldWork()
        {
            //Same test as above only using default export builder
            var builder = new ConventionBuilder();

            builder.ForTypesMatching((t) => true).ExportInterfaces((iface) => iface != typeof(System.IDisposable));
            builder.ForTypesMatching((t) => t.GetTypeInfo().ImplementedInterfaces.Where((iface) => iface != typeof(System.IDisposable)).Count() == 0).Export();

            var container = new ContainerConfiguration()
                            .WithPart <Standard>(builder)
                            .WithPart <Dippy>(builder)
                            .WithPart <Derived>(builder)
                            .WithPart <BareClass>(builder)
                            .CreateContainer();

            var importer = new Importer();

            container.SatisfyImports(importer);

            Assert.NotNull(importer.First);
            Assert.True(importer.First.Count() == 3);
            Assert.NotNull(importer.Second);
            Assert.True(importer.Second.Count() == 3);
            Assert.NotNull(importer.Third);
            Assert.True(importer.Third.Count() == 3);
            Assert.NotNull(importer.Fourth);
            Assert.True(importer.Fourth.Count() == 3);
            Assert.NotNull(importer.Fifth);
            Assert.True(importer.Fifth.Count() == 3);

            Assert.Null(importer.Base);
            Assert.Null(importer.Derived);
            Assert.Null(importer.Dippy);
            Assert.Null(importer.Standard);
            Assert.Null(importer.Disposable);
            Assert.NotNull(importer.BareClass);
        }
示例#34
0
        public void InitializeAssimp()
        {
            var flags = (ppsteps |
                         aiPostProcessSteps.aiProcess_GenSmoothNormals |    // generate smooth normal vectors if not existing
                         aiPostProcessSteps.aiProcess_SplitLargeMeshes |    // split large, unrenderable meshes into submeshes
                         aiPostProcessSteps.aiProcess_Triangulate |         // triangulate polygons with more than 3 edges
                         aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                         aiPostProcessSteps.aiProcess_SortByPType |         // make 'clean' meshes which consist of a single typ of primitives
                         (aiPostProcessSteps)0);

            // default model
            var path = "../../../../../../test/models/3DS/test1.3ds";

            importer = new Importer();
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                path = args[1];
            }


            //var path = "man.3ds";
            scene = importer.ReadFile(path, flags);
            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
                CacheMaterials(scene.mMaterials);
                CacheMeshes(scene.mMeshes);
                SetupCamera(scene.mCameras);
            }
            else
            {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }
        }
示例#35
0
        public string ImporterToString(Importer imp)
        {
            if (imp == Importer.Wav)
            {
                return("WawImporter");
            }

            if (imp == Importer.Effect)
            {
                return("EffectImporter");
            }

            if (imp == Importer.Font)
            {
                return("FontDescriptionImporter");
            }

            if (imp == Importer.Texture)
            {
                return("TextureImporter");
            }

            return("[UnknownImporter]");
        }
示例#36
0
        private void DoImport()
        {
            XmlDocument doc = GetMindMapFromUser();

            if (doc == null)
            {
                return;
            }

            var            imp     = new Importer(doc, _fb);
            ImportAnalysis results = imp.Analyze();

            if (results.NothingToDo)
            {
                MessageBox.Show(@"No changes were detected. Nothing to import.", @"Import Mind Map",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var dlg = new ImportConfirmationDlg(results);

            if (dlg.ShowDialog() == DialogResult.Yes)
            {
                foreach (Case c in results.CaseToNewParent.Keys)
                {
                    try
                    {
                        _fb.SetParent(c, results.CaseToNewParent[c].ID);
                    }
                    catch (Exception x)
                    {
                        Utils.LogError(x.ToString());
                    }
                }
            }
        }
示例#37
0
        static void Main(string[] args)
        {
            try
            {
                var    specParser = new SpecParser();
                var    errorCount = 0;
                string outputFile = args[1] + ".output.csv";
                using (var sr = new StreamReader(args[0]))
                    using (var data = new FileStream(args[1], FileMode.Open, FileAccess.Read))
                        using (var output = new StreamWriter(args[1] + ".output.csv"))
                        {
                            var importer = new Importer(specParser.Parse(sr));
                            var listener = new CsvOutputListener(output);
                            importer.Import(data, listener);
                            listener.Task.Wait();
                            errorCount = listener.Errors;
                        }
                if (errorCount > 0)
                {
                    File.Delete(outputFile);
                    WriteLine("No output created.");
                }
                else
                {
                    WriteLine($"Output in in \"{outputFile}\"");
                }
            }
            catch (Exception ex)
            {
                WriteLine($"Error: {ex.Message}");
            }
#if DEBUG
            WriteLine("Press any key to continue");
            ReadKey();
#endif
        }
示例#38
0
        private void ImportResourcesTest(string fileNameInCloud, Dictionary <string, string> settings)
        {
            Trace.WriteLine($"Processing {fileNameInCloud}.");

            string baseResourcePath = "resource";

            using (ShimsContext.Create())
            {
                ShiminRiverContext.AllInstances.SettingsGet = settingsGet => settings;

                ShiminRiverContext.AllInstances.LogLogLevelString = (cx, logLevel, message) =>
                {
                    Trace.WriteLine($"{logLevel.ToString().ToUpper().PadRight(12, ' ')} {message}");
                };

                ShiminRiverContext context = new ShiminRiverContext();

                //Act
                Importer importer = new Importer(context);
                importer.ImportResources(fileNameInCloud, baseResourcePath, string.Empty);

                //Assert
            }
        }
示例#39
0
        private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //change cursor back
            Cursor = Cursors.Arrow;

            //unsubscribe from the importer's progress updates
            _importer.OnProgressUpdate -= ImportStatusUpdate;

            if (e.Error != null)
            {
                //MessageBox.Show(string.Format("An error prevented the job from executing: {0}", e.Error.Message), "Fatal job error", MessageBoxButton.OK, MessageBoxImage.Error);
                JobError errorbox = new JobError();
                errorbox.SetDetails(string.Format("An error prevented the job from executing: {0}", e.Error.Message), e.Error.ToString());
                errorbox.Owner = this;
                errorbox.ShowDialog();
            }
            else
            {
                int errorCount = _importer.ErrorCount;

                _importer = null;
                //clear the status label
                ImportStatusUpdate("");


                //show a message to the user
                if (errorCount == 0)
                {
                    MessageBox.Show("Job finished with no errors.", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("Job finished with errors. See the RecordError.log file for more details.", "Import errors", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
示例#40
0
        private bool HandleUnassignedThreat(IThreatModel target, Threat threat, IThreatType threatType, IPropertySchema schema)
        {
            bool result = false;

            using (var dialog = new ThreatAssignmentDialog(target))
            {
                dialog.Initialize(threat.ToString(), threat.GetValueFromLabel("Description"));
                if (dialog.ShowDialog(Form.ActiveForm) == DialogResult.OK)
                {
                    var identity = dialog.SelectedIdentity;
                    if (identity != null)
                    {
                        if (identity is IEntity entity)
                        {
                            var threatEvent = entity.AddThreatEvent(threatType);
                            if (threatEvent != null)
                            {
                                Importer.AddProperties(threatEvent, threat, schema);
                                result = true;
                            }
                        }
                        else if (identity is IDataFlow dataFlow)
                        {
                            var threatEvent = dataFlow.AddThreatEvent(threatType);
                            if (threatEvent != null)
                            {
                                Importer.AddProperties(threatEvent, threat, schema);
                                result = true;
                            }
                        }
                    }
                }
            }

            return(result);
        }
示例#41
0
        private Dictionary <GroupInfo, List <UserInfo> > GetGroupsUsers(List <GroupInfo> ldapGroups,
                                                                        out List <UserInfo> uniqueLdapGroupUsers)
        {
            uniqueLdapGroupUsers = new List <UserInfo>();

            var listGroupsUsers = new Dictionary <GroupInfo, List <UserInfo> >();

            foreach (var ldapGroup in ldapGroups)
            {
                var ldapGroupUsers = Importer.GetGroupUsers(ldapGroup);

                listGroupsUsers.Add(ldapGroup, ldapGroupUsers);

                foreach (var ldapGroupUser in ldapGroupUsers)
                {
                    if (!uniqueLdapGroupUsers.Any(u => u.Sid.Equals(ldapGroupUser.Sid)))
                    {
                        uniqueLdapGroupUsers.Add(ldapGroupUser);
                    }
                }
            }

            return(listGroupsUsers);
        }
示例#42
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void letImporterDecideAboutDatabaseExistence() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void LetImporterDecideAboutDatabaseExistence()
        {
            File          report        = _testDir.file("report");
            Path          homeDir       = _testDir.directory("home").toPath();
            PrintStream   nullOutput    = new PrintStream(NULL_OUTPUT_STREAM);
            OutsideWorld  outsideWorld  = new RealOutsideWorld(nullOutput, nullOutput, new MemoryStream(new sbyte[0]));
            Path          confPath      = _testDir.directory("conf").toPath();
            ImportCommand importCommand = new ImportCommand(homeDir, confPath, outsideWorld);
            File          nodesFile     = CreateTextFile("nodes.csv", ":ID", "1", "2");

            string[] arguments = new string[] { "--mode=csv", "--database=existing.db", "--nodes=" + nodesFile.AbsolutePath, "--report-file=" + report.AbsolutePath };

            // First run an import so that a database gets created
            importCommand.Execute(arguments);

            // When
            ImporterFactory importerFactory = mock(typeof(ImporterFactory));
            Importer        importer        = mock(typeof(Importer));

            when(importerFactory.GetImporterForMode(any(), any(), any(), any())).thenReturn(importer);
            (new ImportCommand(homeDir, confPath, outsideWorld, importerFactory)).Execute(arguments);

            // Then no exception about database existence should be thrown
        }
示例#43
0
        public async Task <Guid> HandleAsync(SetImporterForNotification message)
        {
            var country = await context.Countries.SingleAsync(c => c.Id == message.Address.CountryId);

            var business = ValueObjectInitializer.CreateBusiness(message.Business);
            var address  = ValueObjectInitializer.CreateAddress(message.Address, country.Name);
            var contact  = ValueObjectInitializer.CreateContact(message.Contact);

            var importer = await repository.GetImporterOrDefaultByNotificationId(message.NotificationId);

            if (importer == null)
            {
                importer = new Importer(message.NotificationId, address, business, contact);
                repository.Add(importer);
            }
            else
            {
                importer.Update(address, business, contact);
            }

            await context.SaveChangesAsync();

            return(importer.Id);
        }
示例#44
0
        public void LoadModel(string fileName)
        {
            var dialogViewModel     = new DialogViewModel();
            HelixToolkitScene scene = null;

            dialogViewModel.AddTask
            (
                (taskContext) =>
            {
                taskContext.UpdateMessage($"Loading model {Path.GetFileNameWithoutExtension(fileName)}");
                var loader = new Importer();
                scene      = loader.Load(fileName);
                taskContext.UpdateProgress(100);
            }
            );
            this.windowManager.ShowDialog(dialogViewModel);
            GroupModel.Clear();
            if (scene != null)
            {
                this.sceneNode = scene.Root;
                GroupModel.AddNode(this.sceneNode);
                this.SetSceneMaterials();
            }
        }
示例#45
0
        public void ImporterTests_ShortcutsWork()
        {
            string oldXml =
                "<folder version=\"36\" creator=\"Apsim 7.5-r3183\" name=\"simulations\">" +
                "  <folder name=\"shared\">" +
                "    <clock>" +
                "      <start_date type=\"date\" description=\"Enter the start date of the simulation\">01/01/1940</start_date>" +
                "      <end_date type=\"date\" description=\"Enter the end date of the simulation\">31/12/1950</end_date> " +
                "    </clock>" +
                "  </folder>" +
                "  <simulation name=\"Continuous Wheat\">" +
                "    <clock shortcut=\"/simulations/shared/Clock\">" +
                "    </clock>" +
                "  </simulation>" +
                "</folder>";

            var         importer = new Importer();
            Simulations sims     = importer.CreateSimulationsFromXml(oldXml);

            Clock c = sims.Children[1].Children[0] as Clock;

            Assert.AreEqual(c.StartDate, new DateTime(1940, 1, 1));
            Assert.AreEqual(c.EndDate, new DateTime(1950, 12, 31));
        }
示例#46
0
        public static void Import(XdImportSettings xdSettings, string[] xdFilePaths)
        {
            var stopWatch = Stopwatch.StartNew();

            Logger = new AkyuiLogger("Akyui.Xd", xdSettings.LogType);
            var loaders = new List <IAkyuiLoader>();

            Settings = xdSettings;
            using (Disposable.Create(() => Settings = null))
                using (var progressBar = new AkyuiProgressBar("Akyui.Xd"))
                {
                    progressBar.SetTotal(xdFilePaths.Length);
                    foreach (var xdFilePath in xdFilePaths)
                    {
                        using (var progress = progressBar.TaskStart(Path.GetFileName(xdFilePath)))
                            using (Logger.SetCategory(Path.GetFileName(xdFilePath)))
                            {
                                var(imported, skipped) = ImportedArtboards(xdSettings, Logger, xdFilePath, progress, loaders);
                                if (imported == 0 && skipped == 0)
                                {
                                    Logger.Warning($"The artboard to be imported was not found. Please set Mark for Export.");
                                }
                            }
                    }
                }

            Importer.Import(xdSettings, loaders.ToArray());
            ExportAkyui(xdSettings, loaders, Logger);
            foreach (var loader in loaders)
            {
                loader.Dispose();
            }

            Logger.Log($"Xd Import Finish", ("Time", $"{stopWatch.Elapsed.TotalSeconds:0.00}s"));
            Logger = null;
        }
示例#47
0
        public void ImportCsv_ConversionRequired_ConverterSpecified_ImportSuccess()
        {
            // arrange
            var uut = new Importer();

            // act
            var testFile = Path.Combine(TestContext.CurrentContext.TestDirectory, @"Data\TestDataCurrency.csv");
            var data     = uut.ImportCsv <TestDataStructure, TestDataStructureClassMap>(testFile).ToArray();

            // assert
            Assert.AreEqual(4, data.Length);

            Assert.AreEqual("Alice", data[0].Name);
            Assert.AreEqual(100.0, data[0].Value);

            Assert.AreEqual("Bob", data[1].Name);
            Assert.AreEqual(20.0, data[1].Value);

            Assert.AreEqual("Charlotte", data[2].Name);
            Assert.AreEqual(45.0, data[2].Value);

            Assert.AreEqual("Dean", data[3].Name);
            Assert.AreEqual(89.7, data[3].Value);
        }
示例#48
0
        private void Import(Importer importer, IImportRecord record)
        {
            try
            {
                if (pnlNewName.Visible)
                {
                    record.RootItem.Name = txtNewName.Text;
                }

                if (chkSkipRoot.Checked)
                {
                    importer.Import(record, Selection.SelectedItem, ImportOption.Children);
                    Refresh(Selection.SelectedItem, ToolbarArea.Both);
                }
                else
                {
                    importer.Import(record, Selection.SelectedItem, ImportOption.All);
                    Refresh(record.RootItem, ToolbarArea.Both);
                }

                ShowErrors(record);
            }
            catch (N2Exception ex)
            {
                cvImport.ErrorMessage     = ex.Message;
                cvImport.IsValid          = false;
                btnImportUploaded.Enabled = false;
            }
            finally
            {
                if (File.Exists(UploadedFilePath))
                {
                    File.Delete(UploadedFilePath);
                }
            }
        }
示例#49
0
        private static int[] GetAge(Image <Bgr, byte> face)
        {
            try
            {
                if (!isNetAgePopulated)
                {
                    importerAge.PopulateNet(netAge);
                    isNetAgePopulated = true;
                    importerAge       = null;
                }

                Blob inputBlob = new Blob(face.Resize(227, 227, Emgu.CV.CvEnum.Inter.Cubic));

                lock (netAge)
                {
                    netAge.SetBlob(".data", inputBlob);

                    netAge.Forward();

                    Blob prob = netAge.GetBlob("prob");

                    int[] outData = new int[2];

                    GetMaxClass(prob, out outData[0], out outData[1]);

                    inputBlob.Dispose();
                    prob.Dispose();

                    return(outData);
                }
            }
            catch
            {
                return(new int[0]);
            }
        }
示例#50
0
        public static void StructGenerator(MethodDef method, ref int i)
        {
            ITypeDefOrRef        valueTypeRef = new Importer(method.Module).Import(typeof(System.ValueType));
            TypeDef              structDef    = new TypeDefUser(Guid.NewGuid().ToString(), valueTypeRef);
            Tuple <TypeDef, int> outTuple;

            structDef.ClassLayout = new ClassLayoutUser(1, 0);
            structDef.Attributes |= TypeAttributes.Sealed | TypeAttributes.SequentialLayout | TypeAttributes.Public;
            List <Type> retList = new List <Type>();
            int         rand    = rndsizevalues[rnd.Next(0, 6)];

            retList.Add(GetType(rand));
            retList.ForEach(x => structDef.Fields.Add(new FieldDefUser(Guid.NewGuid().ToString(), new FieldSig(new Importer(method.Module).Import(x).ToTypeSig()), FieldAttributes.Public)));
            int operand = method.Body.Instructions[i].GetLdcI4Value();

            if (abc < 25)
            {
                method.Module.Types.Add(structDef);
                Dick.Add(abc++, new Tuple <TypeDef, int>(structDef, rand));
                int conta = operand - rand;
                method.Body.Instructions[i].Operand = conta;
                method.Body.Instructions[i].OpCode  = OpCodes.Ldc_I4;
                method.Body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, structDef));
                method.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Add));
            }
            else
            {
                Dick.TryGetValue(rnd.Next(1, 24), out outTuple);
                int conta = operand - outTuple.Item2;
                method.Body.Instructions[i].Operand = conta;
                method.Body.Instructions[i].OpCode  = OpCodes.Ldc_I4;
                method.Body.Instructions.Insert(i + 1, Instruction.Create(OpCodes.Sizeof, outTuple.Item1));
                method.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Add));
            }
            i += 2;
        }
示例#51
0
        // Import Button
        private void button5_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Filter = "csv files (*.csv)|*.csv";
            Nullable <bool> result = fileDialog.ShowDialog();

            if (result == true)
            {
                string path         = fileDialog.FileName;
                bool   importResult = Importer.ImportArticleFromCsv(db, path);
                if (importResult)
                {
                    MessageBox.Show("Artikel wurden importiert", "",
                                    MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show("Beim Importieren trat ein Fehler auf", "",
                                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            updateGrid();
        }
示例#52
0
        public void Preprocess()
        {
            preprocessThread = new Thread(() =>
            {
                sw.Start();
                Importer.CreateLog();

                Importer.WriteLog("salam");

                Importer importer = new Importer();

                importer.ReadFiles();

                DatabaseController.Instance.WriteTokensToDatabase();

                DatabaseController.Instance.writer.Wait();

                DatabaseController.Instance.CreateIndex();

                sw.Stop();
                preprocessTime = sw.ElapsedMilliseconds;
            });
            preprocessThread.Start();
        }
        private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //change cursor back
            Cursor = Cursors.Default;

            //unsubscribe from the importer's progress updates
            _importer.OnProgressUpdate -= ImportStatusUpdate;

            int errorCount = _importer.ErrorCount;

            _importer = null;
            //clear the status label
            ImportStatusUpdate("");

            //show a message to the user
            if (errorCount == 0)
            {
                MessageBox.Show("Job finished with no errors.");
            }
            else
            {
                MessageBox.Show("Job finished with errors. See the RecordError.log file for more details.");
            }
        }
示例#54
0
        public static void LoadSavedSchemaInto(ISchemaProvider provider, IZetboxContext targetCtx)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (targetCtx == null)
            {
                throw new ArgumentNullException("targetCtx");
            }

            string schema = provider.GetSavedSchema().TrimEnd((char)0); // Trim possible C++/Database/whatever ending 0 char

            if (!string.IsNullOrEmpty(schema))
            {
                // Migration from Kist -> Zetbox
                schema = schema.Replace("Kistl", "Zetbox");

                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(schema)))
                {
                    Importer.LoadFromXml(targetCtx, ms, "saved schema from " + provider.GetSafeConnectionString());
                }
            }
        }
示例#55
0
        public static void Import(string excelFolder)
        {
            Gems = new Dictionary <string, Gem>();

            var table = Importer.ReadTxtFileToDictionaryList(excelFolder + "/Gems.txt");

            foreach (var row in table)
            {
                var numMods = Utility.ToNullableInt(row["nummods"]);
                if (!numMods.HasValue)
                {
                    ExceptionHandler.LogException(new Exception($"Invalid nummods for '{row["name"]}' in Gems.txt"));
                }

                var gem = new Gem
                {
                    Index   = row["name"],
                    Letter  = row["letter"],
                    Code    = row["code"],
                    NumMods = numMods.Value,
                };

                // Add the properties
                var propList = new List <PropertyInfo>();
                for (int i = 1; i <= 3; i++)
                {
                    propList.Add(new PropertyInfo(row[$"weaponMod{i}Code"], row[$"weaponMod{i}Param"], row[$"weaponMod{i}Min"], row[$"weaponMod{i}Max"]));
                }

                try
                {
                    var properties = ItemProperty.GetProperties(propList).OrderByDescending(x => x.ItemStatCost == null ? 0 : x.ItemStatCost.DescriptionPriority).ToList();
                    gem.WeaponProperties = properties;
                }
                catch (Exception e)
                {
                    ExceptionHandler.LogException(new Exception($"Could not get weapon properties for gem '{gem.Index}' in Gems.txt", e));
                }

                // Add the properties
                propList = new List <PropertyInfo>();
                for (int i = 1; i <= 3; i++)
                {
                    propList.Add(new PropertyInfo(row[$"helmMod{i}Code"], row[$"helmMod{i}Param"], row[$"helmMod{i}Min"], row[$"helmMod{i}Max"]));
                }

                try
                {
                    var properties = ItemProperty.GetProperties(propList).OrderByDescending(x => x.ItemStatCost == null ? 0 : x.ItemStatCost.DescriptionPriority).ToList();
                    gem.HelmProperties = properties;
                }
                catch (Exception e)
                {
                    ExceptionHandler.LogException(new Exception($"Could not get helm properties for gem '{gem.Index}' in Gems.txt", e));
                }


                // Add the properties
                propList = new List <PropertyInfo>();
                for (int i = 1; i <= 3; i++)
                {
                    propList.Add(new PropertyInfo(row[$"shieldMod{i}Code"], row[$"shieldMod{i}Param"], row[$"shieldMod{i}Min"], row[$"shieldMod{i}Max"]));
                }

                try
                {
                    var properties = ItemProperty.GetProperties(propList).OrderByDescending(x => x.ItemStatCost == null ? 0 : x.ItemStatCost.DescriptionPriority).ToList();
                    gem.ShieldProperties = properties;
                }
                catch (Exception e)
                {
                    ExceptionHandler.LogException(new Exception($"Could not get shield properties for gem '{gem.Index}' in Gems.txt", e));
                }

                Gems[gem.Index] = gem;
            }
        }
示例#56
0
        /// <summary>
        /// Link in the new created document to parent document.
        /// </summary>
        /// <param name="baseFileName">The full path to the IFC file.</param>
        /// <param name="ifcDocument">The newly imported IFC file document.</param>
        /// <param name="originalDocument">The document to contain the IFC link.</param>
        /// <param name="useExistingType">True if the RevitLinkType already exists.</param>
        /// <param name="doSave">True if we should save the document.  This should only be false if we are reusing a cached document.</param>
        /// <returns>The element id of the RevitLinkType for this link operation.</returns>
        public static ElementId LinkInFile(string baseFileName, Document ifcDocument, Document originalDocument, bool useExistingType, bool doSave)
        {
            bool   saveSucceded = true;
            string fileName     = GenerateRevitFileName(baseFileName);

            if (doSave)
            {
                SaveAsOptions saveAsOptions = new SaveAsOptions();
                saveAsOptions.OverwriteExistingFile = true;

                try
                {
                    ifcDocument.SaveAs(fileName, saveAsOptions);
                }
                catch (Exception ex)
                {
                    // We still want to close the document to prevent having a corrupt model in memory.
                    Importer.TheLog.LogError(-1, ex.Message, false);
                    saveSucceded = false;
                }
            }

            if (!ifcDocument.IsLinked)
            {
                ifcDocument.Close(false);
            }

            ElementId revitLinkTypeId = ElementId.InvalidElementId;

            if (!saveSucceded)
            {
                return(revitLinkTypeId);
            }

            bool doReloadFrom = useExistingType && !Importer.TheOptions.CreateLinkInstanceOnly;

            if (Importer.TheOptions.RevitLinkFileName != null)
            {
                FilePath originalRevitFilePath = new FilePath(Importer.TheOptions.RevitLinkFileName);
                revitLinkTypeId = RevitLinkType.GetTopLevelLink(originalDocument, originalRevitFilePath);
            }

            if (!doReloadFrom)
            {
                Transaction linkTransaction = new Transaction(originalDocument);
                linkTransaction.Start(Resources.IFCLinkFile);

                try
                {
                    if (revitLinkTypeId == ElementId.InvalidElementId)
                    {
                        RevitLinkOptions    options    = new RevitLinkOptions(true);
                        RevitLinkLoadResult loadResult = RevitLinkType.CreateFromIFC(originalDocument, baseFileName, fileName, false, options);
                        if ((loadResult != null) && (loadResult.ElementId != ElementId.InvalidElementId))
                        {
                            revitLinkTypeId = loadResult.ElementId;
                        }
                    }

                    if (revitLinkTypeId != ElementId.InvalidElementId)
                    {
                        RevitLinkInstance.Create(originalDocument, revitLinkTypeId);
                    }

                    Importer.PostDelayedLinkErrors(originalDocument);
                    linkTransaction.Commit();
                }
                catch (Exception ex)
                {
                    linkTransaction.RollBack();
                    throw ex;
                }
            }
            else // reload from
            {
                // For the reload from case, we expect the transaction to have been created in the UI.
                if (revitLinkTypeId != ElementId.InvalidElementId)
                {
                    RevitLinkType existingRevitLinkType = originalDocument.GetElement(revitLinkTypeId) as RevitLinkType;
                    if (existingRevitLinkType != null)
                    {
                        existingRevitLinkType.UpdateFromIFC(originalDocument, baseFileName, fileName, false);
                    }
                }
            }

            return(revitLinkTypeId);
        }
示例#57
0
        public void TestThatImporterThrowsCorruptedFileExceptionOnWrongImageFileWithSupportedExtension(string fileName)
        {
            string imagePath = $"{Environment.CurrentDirectory}\\..\\..\\..\\ModelsTests\\IO\\{fileName}";

            Assert.Throws <CorruptedFileException>(() => { Importer.ImportSurface(imagePath); });
        }
示例#58
0
 public void TestThatImporterThrowsCorruptedFileExceptionOnWrongPixiFileWithSupportedExtension()
 {
     Assert.Throws <CorruptedFileException>(() => { Importer.ImportDocument(testCorruptedPixiImagePath); });
 }
示例#59
0
 public void TestThatIsSupportedFile(string file)
 {
     Assert.True(Importer.IsSupportedFile(file));
 }
示例#60
0
        public void InitializeAssimp()
        {
            var flags = ( ppsteps |
                aiPostProcessSteps.aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
                aiPostProcessSteps.aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
                aiPostProcessSteps.aiProcess_Triangulate | // triangulate polygons with more than 3 edges
                aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                aiPostProcessSteps.aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
                (aiPostProcessSteps)0);

            // default model
            var path = "../../../../../../test/models/3DS/test1.3ds";

            importer = new Importer();
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1) {
                path = args[1];
            }

            //var path = "man.3ds";
            scene = importer.ReadFile(path, flags);
            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
                CacheMaterials(scene.mMaterials);
                CacheMeshes(scene.mMeshes);
                SetupCamera(scene.mCameras);
            }
            else {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }
        }