コード例 #1
0
        /// <summary>
        /// Метод вызывается для получения допустимых и подавляемых команд контекстного меню для выделенных
        /// элементов навигации одной категории и типа.
        /// Например, если в «Навигаторе» выделены элементы навигации нескольких разных категорий и типов,
        /// то данная команда будет вызываться для каждой из подгрупп этих элементов, сгруппированных по их
        /// категориям и типам.
        /// Это наиболее применяемый метод даного интерфейса. Позволяет перекрывать команды контекстного меню
        /// для элементов навигации определённых категорий, типов, задавая более высокий приоритет описаниям
        /// этих команд.
        /// </summary>
        /// <param name="items">
        /// Коллекция выделенных элементов пространства навигации, для которых выполняется
        /// поиск допустимых команд контекстного меню.
        /// </param>
        /// <param name="viewServices">
        /// Контейнер сервисов (контекст) для выделенных элементов пространства навигации.
        /// </param>
        public CommandsInfo GetMergedCommands(ISelectedItems items, IServiceProvider viewServices)
        {
            // ВНИМАНИЕ! Основное требование к данному методу – нельзя выполнять обращения к базе даных
            // для того, чтобы проверить, можно ли отображать команду меню или нет!

            // Список добавленных или перекрытых команд контекстного меню
            CommandsInfo commandsInfo = new CommandsInfo();

            // Есть один выделенный элемент
            if (items != null && items.Count == 1)
            {
                // Пробуем получить описание выделенного объекта
                IDBTypedObjectID objID = items.GetItemData(0, typeof(IDBTypedObjectID)) as IDBTypedObjectID;

                // Выделен объект
                if (objID != null)
                {
                    // Получаем идентификатор типа объектов "Рабочий стол"
                    // Разрешать создавать его копию не будем
                    Int32 desktopObjectTypeID = MetaDataHelper.GetObjectTypeID(SystemGUIDs.objtypeWorkspace);

                    // Можем добавить команду "Создать\Копию объекта"
                    if (objID.ObjectType != desktopObjectTypeID)
                    {
                        // Команда "Создать\Копию объекта"
                        commandsInfo.Add("CreateCopyyyyyyy",
                                         new CommandInfo(TriggerPriority.ItemCategory,
                                                         new ClickEventHandler(CommandProvider.CreateObjectCopyyy)));
                    }
                }
            }

            // Вернём список
            return(commandsInfo);
        }
コード例 #2
0
 private void SetItemType(IEnumerable list)
 {
     if (ItemType == null & list != null)
     {
         ItemType = MetaDataHelper.GetEnumerableItemType(list);
     }
 }
コード例 #3
0
        public void ToBindingListViewTest()
        {
            TestToBindingListView(MetaDataHelper.GetPropertiesToDisplay(typeof(AddressTypeEntity)));
            TestToBindingListView(((IEntity)MetaSingletons.MetaData.AddressType.First()).CustomPropertiesOfType);
            var addressTypeEntityCollection = MetaSingletons.MetaData.AddressType.ToEntityCollection();
            var list = TestToBindingListView(addressTypeEntityCollection.DefaultView);

            Assert.AreEqual(addressTypeEntityCollection.DefaultView, list);

            Assert.AreEqual(addressTypeEntityCollection.DefaultView, TestToBindingListView(addressTypeEntityCollection));
            CollectionAssert.AreEqual(addressTypeEntityCollection, TestToBindingListView(addressTypeEntityCollection.AsQueryable()));
            CollectionAssert.AreEqual(addressTypeEntityCollection, TestToBindingListView(addressTypeEntityCollection.Cast <CommonEntityBase>()));

            TestToBindingListView(MetaSingletons.MetaData.AddressType);

            var dataTable = TestData.GetAddressTypeDataTable();

            Assert.AreEqual(dataTable.DefaultView, TestListSourceToBindingListView(dataTable));

            var enumerable = Enumerable.Range(1, 100);
            var actual     = TestToBindingListView(enumerable);

            CollectionAssert.AreEqual(enumerable.ToList(), actual);

            Assert.IsNull("A string".ToBindingListView());

            Assert.IsNull((new[] { "s1", "s2", "s3" }).ToBindingListView());

            TestToBindingListView(SerializableClass.GenerateList().ToBindingListView());
        }
コード例 #4
0
 public IEnumerable <Type> GetEntitiesTypes()
 {
     if (_baseType != null)
     {
         return(MetaDataHelper.GetDescendance(_baseType));
     }
     return(_entityAssembly == null?MetaDataHelper.GetAllLoadedDescendance(typeof(IEntityCore)) : typeof(IEntityCore).GetAssignable(_entityAssembly.GetExportedTypes()));
 }
コード例 #5
0
        private static void AssertCopyToDataTable(Type type, DataTable actual)
        {
            var propertyDescriptors = MetaDataHelper.GetPropertiesToSerialize(type);

            Assert.AreEqual(propertyDescriptors.Count(), actual.Columns.Count);
            var expectedPropertyDescriptorNames = propertyDescriptors.Select(pd => pd.Name).ToList();
            var actualNames = actual.Columns.Cast <DataColumn>().Select(dc => dc.ColumnName).ToList();

            CollectionAssert.AreEquivalent(expectedPropertyDescriptorNames, actualNames);
        }
        public void DataTableSurrogateSerializeDeserializeTest()
        {
            TestDataTableSurrogateSerializeDeserialize(GeneralHelper.CopyToDataTable(NonSerializableClass.GenerateList()));
            TestDataTableSurrogateSerializeDeserialize(GeneralHelper.CopyToDataTable(SerializableClass.GenerateList()));
            var dt = new DataSet();
            var addressTypeEntityCollection = MetaSingletons.MetaData.AddressType.ToEntityCollection();

            addressTypeEntityCollection.CreateHierarchicalProjection(dt);
            TestDataTableSurrogateSerializeDeserialize(dt.Tables[0]);
            TestDataTableSurrogateSerializeDeserialize(GeneralHelper.CopyToDataTable(MetaDataHelper.GetPropertiesToDisplay(typeof(AddressTypeEntity))));
            //TestDataTableSurrogateSerializeDeserialize(GeneralHelper.CopyToDataTable(MetaSingletons.MetaData.AddressType));
        }
コード例 #7
0
        public void NonSerializableItemTest()
        {
            var listofNonSerializableClasses = NonSerializableClass.GenerateList();

            TestSerialize(listofNonSerializableClasses);
            listofNonSerializableClasses.Insert(0, new SerializableClass {
                DateTimeField = DateTime.Now, IntField = listofNonSerializableClasses.Count, StringField = listofNonSerializableClasses.Count.ToString()
            });
            TestSerialize(listofNonSerializableClasses);
            TestSerialize(new ArrayList(listofNonSerializableClasses));
            TestShow(MetaDataHelper.GetPropertiesToDisplay(typeof(AddressTypeEntity)));
        }
コード例 #8
0
        private void Fill_ImbaseTable(long newSelectedID, DataTable dt)
        {
            using (SessionKeeper keeper = new SessionKeeper())
            {
                DataSet   ds;
                DataTable tb2;
                DataRow   row1;
                try
                {
                    ds = TableLoadHelper.GetTables(keeper.Session, newSelectedID, true);

                    tb2 = ds.Tables[Intermech.Imbase.Consts.IMS_DATA];
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Таблицы с tableID = " + newSelectedID.ToString() + " не найдено");
                    throw ex;
                }

                Dictionary <string, Guid> columnNamesAndGuids = new Dictionary <string, Guid>();

                byte          columnsCount       = Convert.ToByte(dt.Columns.Count); // количество колонок в табллице
                List <string> columnNamesinExcel = new List <string>(columnsCount);
                for (byte i = 0; i < columnsCount; i++)
                {
                    columnNamesinExcel.Add(dt.Columns[i].ColumnName);                                                                       // создали список наименований колонок в таблице
                    columnNamesAndGuids.Add(dt.Columns[i].ColumnName, MetaDataHelper.GetAttributeByTypeNameGuid(dt.Columns[i].ColumnName)); // имя аттрибута и его Guid
                }

                string tempGuid;
                string tempName;
                foreach (var item in dt.AsEnumerable()) // по всем рядкам
                {
                    row1 = tb2.NewRow();

                    for (byte i = 0; i < columnsCount; i++) // по каждой колонке
                    {
                        tempName = columnNamesinExcel[i];
                        tempGuid = "" + columnNamesAndGuids[tempName] + "";

                        row1.SetField(tempGuid, item[tempName].ToString());
                    }
                    tb2.Rows.Add(row1);
                    tb2.AcceptChanges();
                }

                TableLoadHelper.StoreData(keeper.Session, newSelectedID, ds, keeper.Session.GetCustomService(typeof(Intermech.Interfaces.Imbase.ITablesIndexer)) as Intermech.Interfaces.Imbase.ITablesIndexer);
            }
        }
        public void FieldsToPropertiesTypeDescriptionProviderTest()
        {
            var properties = MetaDataHelper.GetPropertiesToDisplay(typeof(NonSerializableClass));

            Assert.AreEqual(3, properties.Count());
            AddFieldsToPropertiesTypeDescriptionProvider(typeof(NonSerializableClass));
            try
            {
                properties = MetaDataHelper.GetPropertiesToDisplay(typeof(NonSerializableClass));
                Assert.AreEqual(6, properties.Count());
            }
            finally
            {
                TidyUp(typeof(NonSerializableClass));
            }
        }
コード例 #10
0
        ///<summary>
        ///	Gets data from the specified object and serializes it into the outgoing data stream
        ///	This class implements the debugee side of the visualizer. It is responsible for running the commands against the server.
        ///</summary>
        ///<remarks>
        ///	Straegy is: if the items are serializable then
        ///	if the enumerable is also serializable
        ///	serialize the enumerable
        ///	else
        ///	create a ObjectListView to contains the items and serialize that instead.
        ///	Full back is to copy the enumerable to a data table and serialize that instead.
        ///</remarks>
        ///<param name = "target">Object being visualized.</param>
        ///<param name = "outgoingData">Outgoing data stream.</param>
        public override void GetData(object target, Stream outgoingData)
        {
            var enumerable = target as IEnumerable;

            if (enumerable != null)
            {
                var itemType  = MetaDataHelper.GetEnumerableItemType(enumerable);
                var queryable = enumerable as IQueryable;
                if (queryable != null)
                {
                    enumerable = queryable.Take(100);
                }
                var enumerableType = enumerable.GetType();
                if (itemType.IsSerializable)
                {
                    if (enumerableType.IsSerializable)
                    {
                        Serialize(outgoingData, enumerable);
                    }
                    else
                    {
                        try
                        {
                            var bindingListView = enumerable.ToBindingListView();
                            if (!bindingListView.GetType().IsSerializable)                             // If the IBindingListView is not serializable use a ObjectListView
                            {
                                bindingListView = new ObjectListView(bindingListView);
                            }
                            Serialize(outgoingData, bindingListView);
                        }
                        catch (Exception)
                        {
                            Serialize(outgoingData, enumerable.CopyToDataTable());
                        }
                    }
                }
                else
                {
                    Serialize(outgoingData, enumerable.CopyToDataTable());
                }
            }
            else if (target is DataTable)
            {
                Serialize(outgoingData, (DataTable)target);
            }
        }
コード例 #11
0
        private static IBindingListView ToObjectListView(this IEnumerable enumerable)
        {
            var itemType = MetaDataHelper.GetEnumerableItemType(enumerable);

            if (itemType == typeof(string))
            {
                return(null);
            }
            enumerable = (IEnumerable)ListBindingHelper.GetList(enumerable);
            if (enumerable is IList)
            {
                var objectListView = ((IList)enumerable).ToObjectListView();
                if (objectListView != null)
                {
                    return(objectListView);
                }
            }
            return(CreateObjectListViewViaBindingSource(enumerable));
        }
コード例 #12
0
        public void GetEnumerableItemTypeTest()
        {
            Assert.AreEqual(typeof(int), MetaDataHelper.GetEnumerableItemType(new List <int>()));
            Assert.AreEqual(typeof(int), MetaDataHelper.GetEnumerableItemType((new List <int> {
                1, 2, 3, 4
            }).Where(i => i > 2)));
            Assert.AreEqual(typeof(AddressTypeEntity), MetaDataHelper.GetEnumerableItemType(new AddressTypeCollection()));
            Assert.AreEqual(typeof(AddressTypeEntity), MetaDataHelper.GetEnumerableItemType(MetaSingletons.MetaData.AddressType));
            Assert.AreEqual(typeof(int), MetaDataHelper.GetEnumerableItemType(new ArrayList {
                1, 2, 3
            }));
            Assert.AreEqual(typeof(object), MetaDataHelper.GetEnumerableItemType(new ArrayList()));

            Assert.AreEqual(typeof(string), MetaDataHelper.GetEnumerableItemType(new string[0]));
            var emptySerializableClasses = new SerializableClass[0];

            Assert.AreEqual(typeof(SerializableClass), MetaDataHelper.GetEnumerableItemType(emptySerializableClasses));
            Assert.AreEqual(typeof(SerializableClass), MetaDataHelper.GetEnumerableItemType(emptySerializableClasses.Take(30)));
        }
コード例 #13
0
        public void CopyToDataTableTest()
        {
            var listofNonSerializableClasses = NonSerializableClass.GenerateList();

            CopyToDataTableAndAssert(listofNonSerializableClasses);
            CopyToDataTableAndAssert(MetaSingletons.MetaData.AddressType);
            listofNonSerializableClasses.Add(new SerializableClass {
                DateTimeField = DateTime.Now, IntField = listofNonSerializableClasses.Count, StringField = listofNonSerializableClasses.Count.ToString()
            });
            CopyToDataTableAndAssert(listofNonSerializableClasses, typeof(SerializableClass));
            var d = new DataGridView {
                AutoGenerateColumns = true, DataSource = listofNonSerializableClasses
            };

            listofNonSerializableClasses.Insert(0, new SerializableClass {
                DateTimeField = DateTime.Now, IntField = listofNonSerializableClasses.Count, StringField = listofNonSerializableClasses.Count.ToString()
            });
            CopyToDataTableAndAssert(listofNonSerializableClasses, typeof(SerializableClass));
            CopyToDataTableAndAssert(MetaDataHelper.GetPropertiesToSerialize(typeof(AddressTypeEntity)));
        }
コード例 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="DocObj">При записи в БД нового обьекта, DocObj это новый обьект созданный предварительным вызовом CreateDoc(); при добавлении файла к существующей сборке, DocObj - обьект сборки"</param>
        /// <param name="filePath"></param>
        private void Blob(ref IDBObject DocObj, MyStruct _object)
        {
            if (_object.Flag == 5)// пишем Blob не в новый документ, а в сборку
            {
                DocObj = createdDocs.Where(x => x.Key.Equals(_object.RefAsmName)).Select(y => y.Value).First();
            }

            int          attrFile = MetaDataHelper.GetAttributeTypeID(new Guid(SystemGUIDs.attributeFile));// атрибут "Файл"
            IDBAttribute fileAtr  = DocObj.GetAttributeByID(attrFile);

            if (fileAtr.Values.Count() >= 1)
            {
                fileAtr.AddValue(_object.Path);
            }
            using (var ms = new MemoryStream(File.ReadAllBytes(_object.Path)))
            {
                BlobInformation blInfo = new BlobInformation(0, 0, DateTime.Now, _object.Path, ArcMethods.NotPacked, null);
                BlobProcWriter  writer = new BlobProcWriter(fileAtr, (int)AttributableElements.Object, blInfo, ms, null, null);

                writer.WriteData();
            }
        }
コード例 #15
0
 public Manage(
     SignInManager <ApplicationUser> signInManager, IStringLocalizer <Manage> localizer,
     Axuno.Tools.DateAndTime.TimeZoneConverter timeZoneConverter,
     Axuno.BackgroundTask.IBackgroundQueue queue,
     UserEmailTask userEmailTask,
     MetaDataHelper metaData, SiteContext siteContext,
     RegionInfo regionInfo, PhoneNumberService phoneNumberService,
     ILogger <Manage> logger)
 {
     _userManager        = signInManager.UserManager;
     _signInManager      = signInManager;
     _localizer          = localizer;
     _timeZoneConverter  = timeZoneConverter;
     _queue              = queue;
     _userEmailTask1     = userEmailTask;
     _userEmailTask2     = userEmailTask.CreateNew();
     _metaData           = metaData;
     _siteContext        = siteContext;
     _phoneNumberService = phoneNumberService;
     _regionInfo         = regionInfo;
     _logger             = logger;
 }
コード例 #16
0
 public Manage(
     SignInManager <ApplicationUser> signInManager, IStringLocalizer <Manage> localizer,
     Axuno.Tools.DateAndTime.TimeZoneConverter timeZoneConverter,
     Axuno.BackgroundTask.IBackgroundQueue queue,
     SendEmailTask sendEmailTask,
     IOptions <DataProtectionTokenProviderOptions> dataProtectionTokenProviderOptions,
     MetaDataHelper metaData, ITenantContext tenantContext,
     RegionInfo regionInfo, PhoneNumberService phoneNumberService,
     ILogger <Manage> logger)
 {
     _userManager       = signInManager.UserManager;
     _signInManager     = signInManager;
     _localizer         = localizer;
     _timeZoneConverter = timeZoneConverter;
     _queue             = queue;
     _sendEmailTask     = sendEmailTask;
     _dataProtectionTokenProviderOptions = dataProtectionTokenProviderOptions;
     _metaData           = metaData;
     _tenantContext      = tenantContext;
     _phoneNumberService = phoneNumberService;
     _regionInfo         = regionInfo;
     _logger             = logger;
 }
コード例 #17
0
        //private void ReadBlob()
        //{
        //    using (SessionKeeper sk = new SessionKeeper())
        //    {
        //        IDBObject iDBObject = sk.Session.GetObject(1962223);
        //        IDBAttributable iDBAttributable = iDBObject as IDBAttributable;
        //        IDBAttribute[] iDBAttributeCollection = iDBAttributable.Attributes.GetAttributesByType(FieldTypes.ftFile);//получили аттрибут File

        //        if (iDBAttributeCollection != null)

        //            foreach (IDBAttribute fileAtr in iDBAttributeCollection)
        //            {
        //                if (fileAtr.ValuesCount < 2)
        //                {
        //                    MemoryStream m = new MemoryStream();
        //                    BlobProcReader reader = new BlobProcReader(fileAtr, (int)fileAtr.AsInteger, m, null, null);
        //                    MessageBox.Show("ElementID" + reader.ElementID.ToString() + "DataBlockSize =  " + reader.DataBlockSize.ToString() + "fileAtr.AsInteger  " + fileAtr.AsInteger.ToString() + "  fileAtr.AsDouble  " + fileAtr.AsDouble.ToString());
        //                    BlobInformation info = reader.BlobInformation;
        //                    reader.ReadData();
        //                    byte[] @byte = m.GetBuffer();
        //                    MessageBox.Show(@byte.Length.ToString());
        //                    //BlobProcReader reader = new BlobProcReader((long)info.BlobID, (int)AttributableElements.Object, fileAtr.AttributeID, 0, 0, 0);



        //                    //try
        //                    //{
        //                    //    IVaultFileReaderService serv = sk.Session.GetCustomService(typeof( IVaultFileReaderService)) as IVaultFileReaderService;
        //                    //    IVaultFileReader fileReader = serv.GetVaultFileReader(sk.Session.SessionID);
        //                    //    if (fileReader != null) MessageBox.Show("file reader exist       RealFileSize:" + info.RealFileSize.ToString() + Environment.NewLine + "PackedFileSize:" + info.PackedFileSize.ToString() + Environment.NewLine + iDBObject.ObjectID.ToString() + Environment.NewLine + fileAtr.AsInteger.ToString());

        //                    //    BlobInformation item = fileReader.OpenBlob(0, 1962223, 0, 8);
        //                    //    MessageBox.Show("Blob is open");

        //                    //    byte[] @byt = fileReader.ReadDataBlock((int)item.PackedFileSize);
        //                    //    MessageBox.Show(@byt.GetLength(@byt.Rank).ToString());
        //                    //}
        //                    //catch { MessageBox.Show("No service found"); }
        //                    //return;
        //                }
        //            }
        //    }
        //}

        public DataTable GetIMBASETable(long tableID, out DataSet ds, out Dictionary <string, string> dictionary)
        {
            using (SessionKeeper keeper = new SessionKeeper())
            {
                ds = TableLoadHelper.GetTables(keeper.Session, tableID, true);
                DataTable tb1     = ds.Tables[0];
                DataTable tb2     = ds.Tables[1];
                string    colName = "";
                dictionary = new Dictionary <string, string>();
                for (int i = 0; i < tb1.Columns.Count; i++)
                {
                    try
                    {
                        colName = MetaDataHelper.GetAttributeTypeName(new Guid(tb1.Columns[i].ToString()));
                        dictionary.Add(colName, tb1.Columns[i].ToString());
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("There is no such attribute:  " + colName.ToString() + "  " + tableID.ToString());
                    }
                }
                return(tb1);
            }
        }
コード例 #18
0
 private void frmMain_Load(object sender, EventArgs e)
 {
     MetaDataHelper.AddAssociatedMetadataProviders(MetaDataHelper.GetDescendance(typeof(CommonEntityBase)));
 }
 public void EditPropertiesInDataGridViewTest()
 {
     TestShowInGrid(((IEntity)MetaSingletons.MetaData.AddressType.First()).CustomPropertiesOfType);
     TestShowInGrid(MetaDataHelper.GetPropertiesToDisplay(typeof(AddressTypeEntity)));
 }
コード例 #20
0
        public async Task CreateDBCacheIfNeededAsync(IEnumerable <string> filePaths)
        {
            // DBに存在しないものだけキャッシュ作成を行う
            foreach (var filePath in filePaths.Except(await _context.Photos.Select(p => p.FilePath).ToListAsync().ConfigureAwait(true)))
            {
                var photo = new Photo
                {
                    FilePath = filePath
                };

                // サムネイル作成
                // サムネイルは初表示時に作成する
                //photo.Thumbnail = await ImageHelper.CreateThumbnailAsync(filePath);

                // metaデータ読み込み
                if (!VrcMetaDataReader.TryRead(filePath, out VrcMetaData meta))
                {
                    // ファイル名から日付を取得
                    photo.Date = MetaDataHelper.GetDateTimeFromPhotoName(filePath);
                }
                else
                {
                    // 日付情報設定
                    photo.Date = meta.Date;

                    // ワールド情報設定
                    if (string.IsNullOrEmpty(meta.World))
                    {
                        photo.World = null;
                    }
                    else
                    {
                        if (!ExistsWorldByWorldName(meta.World, out var world))
                        {
                            photo.World = CreateWorld(meta.World);
                        }
                        else
                        {
                            photo.World = world;
                        }
                    }

                    // 撮影者情報設定
                    if (string.IsNullOrEmpty(meta.Photographer))
                    {
                        photo.Photographer = null;
                    }
                    else
                    {
                        var(exists, photographer) = await ExistsUserByUserNameAsync(meta.Photographer).ConfigureAwait(true);

                        if (!exists)
                        {
                            photo.Photographer = await CreateUserAsync(meta.Photographer).ConfigureAwait(true);
                        }
                        else
                        {
                            photo.Photographer = photographer;
                        }
                    }

                    // ユーザ情報設定
                    if (meta.Users.Any())
                    {
                        foreach (var metaUser in meta.Users)
                        {
                            var(exists, user) = await ExistsUserByUserNameAsync(metaUser.UserName).ConfigureAwait(true);

                            // TODO:TwitterのDisplaynameを入れていない
                            if (!exists)
                            {
                                user = await CreateUserAsync(metaUser.UserName).ConfigureAwait(true);
                            }

                            var photoUser = CreatePhotoUser(photo, user);

                            photo.PhotoUsers.Add(photoUser);
                        }
                    }
                }

                await _context.Photos.AddAsync(photo);

                await _context.SaveChangesAsync().ConfigureAwait(true);
            }
        }
コード例 #21
0
        /// <summary>
        /// 非同期で画像を読み込む
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public async Task LoadVRCPhotoListAsync(string[] folderPaths, CancellationToken cancelToken)
        {
            _db.CreateDBCacheIfNeeded();

            if (folderPaths.Any(f => !Directory.Exists(f)))
            {
                throw new DirectoryNotFoundException($"{string.Join(',',folderPaths.Where(f => !Directory.Exists(f)))} is not exist.");
            }

            Collection.Clear();

            try
            {
                // UIスレッドと分離させる
                await Task.Run(async() =>
                {
                    var filePaths = folderPaths.SelectMany(f => Directory.GetFiles(f, "*.png", SearchOption.TopDirectoryOnly))
                                    .Where(x => !x.StartsWith(AppCache.Instance.CacheFolderPath, StringComparison.Ordinal))
                                    .ToList();

                    var metaSets = _db.GetVrcMetaDataIfExists(filePaths);

                    var photos = metaSets
                                 .Select(m =>
                                         new Photo(m.filePath)
                    {
                        MetaData = m.vrcMetaData
                    })
                                 .ToList();

                    Collection.AddRangeOnScheduler(photos);

                    var tasks = filePaths
                                .Except(metaSets.Select(m => m.filePath))
                                .Select(fp =>
                                        new Task(async() =>
                    {
                        var meta = await MetaDataHelper.GetVrcMetaDataAsync(fp, cancelToken).ConfigureAwait(true);
                        if (cancelToken.IsCancellationRequested)
                        {
                            return;
                        }
                        Collection.AddOnScheduler(
                            new Photo(fp)
                        {
                            MetaData = meta
                        });

                        try
                        {
                            await _db.InsertAsync(fp, meta, cancelToken).ConfigureAwait(false);
                        }
                        catch (InvalidOperationException e)
                        {
                            // A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
                            // The instance of entity type 'Photo' cannot be tracked because another instance with the same key value for {'FilePath'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
                            FileHelper.OutputErrorLogFile(e);
                        }
                        catch (ArgumentException e)
                        {
                            FileHelper.OutputErrorLogFile(e);
                        }
                        catch (Microsoft.EntityFrameworkCore.DbUpdateException e)
                        {
                            // An error occurred while updating the entries. See the inner exception for details.
                            FileHelper.OutputErrorLogFile(e);
                        }
                        catch (TaskCanceledException e) { }
                    }, cancelToken));

                    Debug.Print($"{tasks.Count()}/{filePaths.Count}");

                    foreach (var task in tasks)
                    {
                        if (cancelToken.IsCancellationRequested)
                        {
                            return;
                        }
                        task.Start();
                    }
                }, cancelToken).ConfigureAwait(true);

                _db.SaveChanges();
            }
            catch (Exception e)
            {
                Debug.Print($"{e.GetType().Name}: {e.Message}");
            }
        }
コード例 #22
0
 public LLBLMemberProvider(object objectToWrite, Type itemType)
 {
     _objectToWrite = objectToWrite;
     _propsToWrite  = MetaDataHelper.GetPropertiesToDisplay(itemType).ToList();
 }
コード例 #23
0
ファイル: NFMapGenerate.cs プロジェクト: lowonion/DataShow
        public static string GenerateClass(Type type)
        {
            StringBuilder sb   = new StringBuilder();
            var           meta = MetaDataHelper.GetMetaData(type);

            if (meta.TableName.IsNullOrWhiteSpace() || meta.KeyColumn == null)
            {
                throw new Exception(type.FullName + ":没有配置主键或者表名");
            }
            sb.Append("public   class   ").Append(type.Name).Append("Map : ClassMap<").Append(type.FullName).Append(">  \n");
            sb.AppendLine("{");
            var tableName = meta.TableName;

            sb.Append("public ").Append(type.Name).AppendLine("Map (){ ");
            //bool cache=type.GetCustAttr<CacheAttribute>()!=null;
            //if (cache)
            //sb.AppendLine("this.Cache.ReadWrite();");
            sb.Append("Table(\"").Append(tableName).AppendLine("\"); ");


            foreach (var prop in meta.Properties.Values)
            {
                if (prop.IsNotMapped)
                {
                    continue;
                }
                string linq = "(m=>m." + prop.Name + ")";
                if (prop.HasManyAttribute != null)
                {
                    sb.Append("HasMany").Append(linq);
                    //if (TypeHelper.GetElementType(prop.PropertyDescriptor.PropertyType).IsValueType)
                    //    sb.AppendFormat(".Element(\"{0}\").KeyColumn(\"{1}\").Table(\"{2}\")", hasMany.ChildKey, hasMany.ParentKey, hasMany.Table);
                    //else
                    sb.Append(".KeyColumn(\"" + prop.HasManyAttribute.ParentKey + "\")");
                    if (prop.HasManyAttribute.OrderBy.IsNotNull())
                    {
                        sb.AppendFormat(".OrderBy(\"{0}\")", prop.HasManyAttribute.OrderBy);
                    }
                    //else if (typeof(ISortable).IsAssignableFrom(prop.HasManyAttribute.ItemType))
                    //{

                    //    sb.AppendFormat(".OrderBy(\"Sort\")");
                    //}


                    //if (cache)
                    //    sb.Append(".Cache.ReadWrite()");
                    sb.Append(";\n");
                    continue;
                }

                if (prop.HasOneAttribute != null)
                {
                    sb.Append("References").Append(linq).Append(".Column(\"" + prop.HasOneAttribute.ReferenceID + "\")");
                    //if (cache)
                    //    sb.Append(".Cache.ReadWrite()");
                    sb.Append(";\n");
                    continue;
                }
                var manyToMany = prop.HasMany2ManyAttribute;
                if (manyToMany != null)
                {
                    sb.Append("HasManyToMany").Append(linq);
                    //    if (manyToMany.OrderBy.IsNotNull())
                    //    sb.AppendFormat(".AsMap(\"{0}\")", manyToMany.OrderBy);

                    string temp = ".Table(\"{0}\").ParentKeyColumn(\"{1}\").ChildKeyColumn(\"{2}\")";

                    sb.Append(string.Format(temp, manyToMany.MidTable, manyToMany.ParentKey, manyToMany.ChildKey));
                    if (manyToMany.OrderBy.IsNotNull())
                    {
                        sb.AppendFormat(".OrderBy(\"{0}\")", manyToMany.OrderBy);
                    }
                    //else if (typeof(ISortable).IsAssignableFrom(manyToMany.ItemType))
                    //{

                    //    sb.AppendFormat(".OrderBy(\"Sort\")");
                    //}
                    //if (cache)
                    //    sb.Append(".Cache.ReadWrite()");
                    sb.Append(";\n");
                    continue;
                }


                if (prop.IsKeyColumn)
                {
                    sb.Append("Id").Append(linq).Append(".GeneratedBy");
                    //   GuidComb Assigned
                    if (prop.PropertyDescriptor.PropertyType == typeof(Guid))
                    {
                        sb.Append(".GuidComb()");
                    }
                    else
                    {
                        sb.Append(".Assigned()");
                    }
                }
                else
                {
                    sb.Append("Map").Append(linq);
                }
                if (prop.RequiredAttribute != null)
                {
                    sb.Append(".Not.Nullable()");
                }

                if (prop.PropertyDescriptor.PropertyType == typeof(string))
                {
                    var maxLen = 0;
                    if (prop.StringLengthAttribute != null)
                    {
                        maxLen = prop.StringLengthAttribute.MaximumLength;
                    }
                    if (maxLen == 0)
                    {
                        maxLen = 255;
                    }
                    sb.AppendFormat(".Length({0})", maxLen);
                }
                if (prop.IndexAttribute != null)
                {
                    var indexName = "ix_" + meta.TableName + "_" + prop.Name;
                    if (!indexNameSet.Contains(indexName))
                    {
                        indexNameSet.Add(indexName);
                        if (prop.IndexAttribute.IsUnique)
                        {
                            sb.AppendFormat(".UniqueKey(\"{0}\")", indexName);
                        }
                        else
                        {
                            sb.AppendFormat(".Index(\"{0}\")", indexName);
                        }
                    }
                }
                if (prop.ColumnName != prop.Name)
                {
                    sb.AppendFormat(".Column(\"{0}\")", prop.ColumnName);
                }
                sb.AppendLine(";");
            }
            sb.AppendLine("}} ");
            //   sb.Append(@"public class usermap { public string userid {get;set;} }");
            return(sb.ToString());
        }
コード例 #24
0
ファイル: IEntity.cs プロジェクト: lowonion/DataShow
        public object GetId()
        {
            var meta = MetaDataHelper.GetMetaData(this.GetType());

            return(this.GetValue(meta.KeyColumn.ColumnName));
        }
コード例 #25
0
 /// <summary>
 /// Gets the properties to display in LINQPad's Dump method. They should be the same as would appear in a DataGridView with AutoGenerateColumns.
 /// </summary>
 /// <returns>The properties to display in LINQPad's Dump</returns>
 private IEnumerable <PropertyDescriptor> GetPropertiesToDisplay()
 {
     return(MetaDataHelper.GetPropertiesToDisplay(GetType()));
 }
コード例 #26
0
 /// <summary>
 /// Gets the validation attributes of a field in an entity.
 /// </summary>
 /// <param name="involvedEntity">The involved entity.</param>
 /// <param name="fieldName">Name of the field.</param>
 /// <returns>The validation attributes.</returns>
 public static IEnumerable <ValidationAttribute> GetValidationAttributes(IEntityCore involvedEntity, string fieldName)
 {
     return(MetaDataHelper.GetValidationAttributes(involvedEntity.GetType(), fieldName));
 }
コード例 #27
0
 public static Form CreateForm(Type formType, params Object[] args)
 {
     return(MetaDataHelper.CreateInstanceOf(typeof(Form), formType, args) as Form);
 }