コード例 #1
0
        public async Task TestInitialize()
        {
            if (File.Exists(MasterFileName + ".bak"))
            {
                File.Delete(MasterFileName + ".bak");
            }

            if (File.Exists(MasterFileName))
            {
                File.Copy(MasterFileName, MasterFileName + ".bak");
                File.Delete(MasterFileName);
            }

            if (File.Exists(FileName + ".bak"))
            {
                File.Delete(FileName + ".bak");
            }

            if (File.Exists(FileName))
            {
                File.Copy(FileName, FileName + ".bak");
                File.Delete(FileName);
            }

            if (File.Exists(BlobFileName + ".bak"))
            {
                File.Delete(BlobFileName + ".bak");
            }

            if (File.Exists(BlobFileName))
            {
                File.Copy(BlobFileName, BlobFileName + ".bak");
                File.Delete(BlobFileName);
            }

            if (File.Exists(NamesFileName + ".bak"))
            {
                File.Delete(NamesFileName + ".bak");
            }

            if (File.Exists(NamesFileName))
            {
                File.Copy(NamesFileName, NamesFileName + ".bak");
                File.Delete(NamesFileName);
            }

            this.provider = new FilesProvider(Folder, CollectionName, this.BlockSize, BlocksInCache, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000, true);
            this.file     = await this.provider.GetFile(CollectionName);

            this.start = DateTime.Now;
        }
コード例 #2
0
ファイル: LanguageTests.cs プロジェクト: iamr8/IoTGateway
        public static async Task AssemblyInitialize(TestContext _)
        {
            Types.Initialize(
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(LanguageTests).Assembly,
                typeof(Expression).Assembly);

            Log.Register(consoleEventSink = new ConsoleEventSink());

            filesProvider = await FilesProvider.CreateAsync("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);

            Database.Register(filesProvider);
        }
コード例 #3
0
        internal IndexBTreeFileEnumerator(IndexBTreeFile File, IndexRecords RecordHandler)
        {
            this.file                = File;
            this.locked              = false;
            this.recordHandler       = RecordHandler;
            this.provider            = this.file.ObjectFile.Provider;
            this.hasCurrent          = false;
            this.currentObjectId     = Guid.Empty;
            this.current             = default(T);
            this.currentSerializer   = null;
            this.timeoutMilliseconds = File.IndexFile.TimeoutMilliseconds;

            this.e = new ObjectBTreeFileEnumerator <object>(this.file.IndexFile, RecordHandler);
        }
コード例 #4
0
        public void CopyTo(object[] array, int arrayIndex)
        {
            Task <ObjectBTreeFileEnumerator <KeyValuePair <string, object> > > Task = this.dictionary.GetEnumerator(LockType.Read);

            FilesProvider.Wait(Task, this.dictionary.DictionaryFile.TimeoutMilliseconds);

            using (ObjectBTreeFileEnumerator <KeyValuePair <string, object> > e = Task.Result)
            {
                while (e.MoveNext())
                {
                    array[arrayIndex++] = e.Current.Value;
                }
            }
        }
コード例 #5
0
        public static void AssemblyCleanup()
        {
            if (filesProvider != null)
            {
                filesProvider.Dispose();
                filesProvider = null;
            }

            if (consoleEventSink != null)
            {
                Log.Unregister(consoleEventSink);
                consoleEventSink = null;
            }
        }
コード例 #6
0
        /// <summary>
        /// <see cref="ICollection{T}.CopyTo(T[], int)"/>
        /// </summary>
        public void CopyTo(KeyValuePair <string, object>[] array, int arrayIndex)
        {
            Task <ObjectBTreeFileEnumerator <KeyValuePair <string, object> > > Task = this.GetEnumerator(true);

            FilesProvider.Wait(Task, this.timeoutMilliseconds);

            using (ObjectBTreeFileEnumerator <KeyValuePair <string, object> > e = Task.Result)
            {
                while (e.MoveNext())
                {
                    array[arrayIndex++] = e.Current;
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Gets or sets the element with the specified key.
        /// </summary>
        /// <param name="key">The key of the element to get or set.</param>
        /// <returns>The element with the specified key.</returns>
        /// <exception cref="ArgumentNullException">key is null.</exception>
        /// <exception cref="KeyNotFoundException">The property is retrieved and key is not found.</exception>
        public object this[string key]
        {
            get
            {
                Task <KeyValuePair <string, object> > Task = this.GetValueAsync(key);
                FilesProvider.Wait(Task, this.timeoutMilliseconds);
                return(Task.Result.Value);
            }

            set
            {
                FilesProvider.Wait(this.AddAsync(key, value, true), this.timeoutMilliseconds);
            }
        }
コード例 #8
0
        public static async Task ClassInitialize(TestContext Context)
        {
            try
            {
                IDatabaseProvider p = Database.Provider;
            }
            catch
            {
#if LW
                Database.Register(await FilesProvider.CreateAsync("Data", "Default", 8192, 8192, 8192, Encoding.UTF8, 10000));
#else
                Database.Register(await FilesProvider.CreateAsync("Data", "Default", 8192, 8192, 8192, Encoding.UTF8, 10000, true));
#endif
            }
        }
コード例 #9
0
        public static void AssemblyInitialize(TestContext Context)
        {
            Waher.Runtime.Inventory.Types.Initialize(
                typeof(MarkdownPlainTextTests).Assembly,
                typeof(Expression).Assembly,
                typeof(Graph).Assembly,
                typeof(MarkdownDocument).Assembly,
                typeof(CommonTypes).Assembly,
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ImageCodec).Assembly);

            filesProvider = new FilesProvider("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);
            Database.Register(filesProvider);
        }
コード例 #10
0
        /// <summary>
        /// This class manages an index file to a <see cref="ObjectBTreeFile"/>.
        /// </summary>
        /// <param name="FileName">File name of index file.</param>
        /// <param name="ObjectFile">Object file storing actual objects.</param>
        /// <param name="Provider">Files provider.</param>
        /// <param name="FieldNames">Field names to build the index on. By default, sort order is ascending.
        /// If descending sort order is desired, prefix the corresponding field name by a hyphen (minus) sign.</param>
        internal IndexBTreeFile(string FileName, ObjectBTreeFile ObjectFile, FilesProvider Provider,
                                params string[] FieldNames)
        {
            this.objectFile     = ObjectFile;
            this.collectionName = this.objectFile.CollectionName;
            this.encoding       = this.objectFile.Encoding;

            this.recordHandler     = new IndexRecords(this.collectionName, this.encoding, this.objectFile.InlineObjectSizeLimit, FieldNames);
            this.genericSerializer = new GenericObjectSerializer(this.objectFile.Provider);

            this.indexFile = new ObjectBTreeFile(FileName, string.Empty, string.Empty, this.objectFile.BlockSize,
                                                 this.objectFile.BlobBlockSize, Provider, this.encoding, this.objectFile.TimeoutMilliseconds,
                                                 this.objectFile.Encrypted, this.recordHandler);
            this.recordHandler.Index = this;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: robinreigns/IoTGateway
		private async static Task<IDatabaseProvider> GetDatabase(XmlElement DatabaseConfig)
		{
			if (!CommonTypes.TryParse(DatabaseConfig.Attributes["encrypted"].Value, out bool Encrypted))
				Encrypted = true;

			FilesProvider Result = await FilesProvider.CreateAsync(Gateway.AppDataFolder + DatabaseConfig.Attributes["folder"].Value,
				DatabaseConfig.Attributes["defaultCollectionName"].Value,
				int.Parse(DatabaseConfig.Attributes["blockSize"].Value),
				int.Parse(DatabaseConfig.Attributes["blocksInCache"].Value),
				int.Parse(DatabaseConfig.Attributes["blobBlockSize"].Value), Encoding.UTF8,
				int.Parse(DatabaseConfig.Attributes["timeoutMs"].Value),
				Encrypted, true);

			return Result;
		}
コード例 #12
0
        public void Delete(InternetShopFilter filter)
        {
            List <InternetShop> currentCollections = Get(new InternetShopFilter()); // gets ALL the Collections, because the filter is empty here

            FilesProvider.OpenWriter("InternetShop", false);
            foreach (InternetShop Collection in currentCollections)
            {
                if (Collection.Id != filter.Id)
                {
                    FilesProvider.WriteMusicCollection(Collection);
                }
            }

            FilesProvider.CloseWriter();
        }
コード例 #13
0
        public async Task TestInitialize()
        {
            if (!File.Exists(DBFilesBTreeTests.MasterFileName + ".bak") ||
                !File.Exists(DBFilesBTreeTests.DefaultFileName + ".bak") ||
                !File.Exists(DBFilesBTreeTests.DefaultBlobFileName + ".bak") ||
                !File.Exists(DBFilesBTreeTests.DefaultLabelsFileName + ".bak"))
            {
                Assert.Inconclusive("No backup files to test against.");
            }

            if (File.Exists(DBFilesBTreeTests.MasterFileName))
            {
                File.Delete(DBFilesBTreeTests.MasterFileName);
            }

            if (File.Exists(DBFilesBTreeTests.DefaultFileName))
            {
                File.Delete(DBFilesBTreeTests.DefaultFileName);
            }

            if (File.Exists(DBFilesBTreeTests.DefaultBlobFileName))
            {
                File.Delete(DBFilesBTreeTests.DefaultBlobFileName);
            }

            if (File.Exists(DBFilesBTreeTests.DefaultLabelsFileName))
            {
                File.Delete(DBFilesBTreeTests.DefaultLabelsFileName);
            }

            File.Copy(DBFilesBTreeTests.MasterFileName + ".bak", DBFilesBTreeTests.MasterFileName);
            File.Copy(DBFilesBTreeTests.DefaultFileName + ".bak", DBFilesBTreeTests.DefaultFileName);
            File.Copy(DBFilesBTreeTests.DefaultBlobFileName + ".bak", DBFilesBTreeTests.DefaultBlobFileName);
            File.Copy(DBFilesBTreeTests.DefaultLabelsFileName + ".bak", DBFilesBTreeTests.DefaultLabelsFileName);

            int BlockSize = this.LoadBlockSize();

#if LW
            this.provider = await FilesProvider.CreateAsync(DBFilesBTreeTests.Folder, DBFilesBTreeTests.CollectionName, BlockSize, 10000, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000);
#else
            this.provider = await FilesProvider.CreateAsync(DBFilesBTreeTests.Folder, DBFilesBTreeTests.CollectionName, BlockSize, 10000, Math.Max(BlockSize / 2, 1024), Encoding.UTF8, 10000, true);
#endif
            this.file = await this.provider.GetFile(DBFilesBTreeTests.CollectionName);

            this.start = DateTime.Now;

            await DBFilesBTreeTests.ExportXML(this.file, "Data\\BTreeBefore.xml");
        }
コード例 #14
0
ファイル: App.xaml.cs プロジェクト: robinreigns/IoTGateway
        private static async Task <IDatabaseProvider> GetDatabase(XmlElement DatabaseConfig)
        {
            if (CommonTypes.TryParse(DatabaseConfig.Attributes["encrypted"].Value, out bool Encrypted) && Encrypted)
            {
                throw new Exception("Encrypted database storage not supported on this platform.");
            }

            FilesProvider Result = await FilesProvider.CreateAsync(Gateway.AppDataFolder + DatabaseConfig.Attributes["folder"].Value,
                                                                   DatabaseConfig.Attributes["defaultCollectionName"].Value,
                                                                   int.Parse(DatabaseConfig.Attributes["blockSize"].Value),
                                                                   int.Parse(DatabaseConfig.Attributes["blocksInCache"].Value),
                                                                   int.Parse(DatabaseConfig.Attributes["blobBlockSize"].Value), Encoding.UTF8,
                                                                   int.Parse(DatabaseConfig.Attributes["timeoutMs"].Value));

            return(Result);
        }
コード例 #15
0
        public static void AssemblyInitialize(TestContext Context)
        {
            Types.Initialize(
                typeof(IContentDecoder).Assembly,
                typeof(Waher.Content.Xml.Text.XmlCodec).Assembly,
                typeof(CoapEndpoint).Assembly,
                typeof(Lwm2mClient).Assembly,
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ICipher).Assembly);

            Log.Register(consoleEventSink = new ConsoleEventSink());

            filesProvider = new FilesProvider("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);
            Database.Register(filesProvider);
        }
コード例 #16
0
        public void TestCleanup()
        {
            Console.Out.WriteLine("Elapsed time: " + (DateTime.Now - this.start).ToString());

            if (this.file != null)
            {
                this.file.Dispose();
                this.file = null;
            }

            if (this.provider != null)
            {
                this.provider.Dispose();
                this.provider = null;
            }
        }
コード例 #17
0
        /// <summary>
        /// Reads a string value.
        /// </summary>
        /// <param name="Reader">Binary reader.</param>
        /// <param name="FieldDataType">Field data type.</param>
        /// <returns>String value.</returns>
        /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception>
        public static string ReadString(BinaryDeserializer Reader, uint FieldDataType)
        {
            switch (FieldDataType)
            {
            case ObjectSerializer.TYPE_STRING: return(Reader.ReadString());

            case ObjectSerializer.TYPE_ENUM: return(Reader.ReadString());

            case ObjectSerializer.TYPE_NULL: return(null);

            case ObjectSerializer.TYPE_CHAR: return(new string(Reader.ReadChar(), 1));

            case ObjectSerializer.TYPE_BOOLEAN: return(Reader.ReadBoolean().ToString());

            case ObjectSerializer.TYPE_BYTE: return(Reader.ReadByte().ToString());

            case ObjectSerializer.TYPE_INT16: return(Reader.ReadInt16().ToString());

            case ObjectSerializer.TYPE_INT32: return(Reader.ReadInt32().ToString());

            case ObjectSerializer.TYPE_INT64: return(Reader.ReadInt64().ToString());

            case ObjectSerializer.TYPE_SBYTE: return(Reader.ReadSByte().ToString());

            case ObjectSerializer.TYPE_UINT16: return(Reader.ReadUInt16().ToString());

            case ObjectSerializer.TYPE_UINT32: return(Reader.ReadUInt32().ToString());

            case ObjectSerializer.TYPE_UINT64: return(Reader.ReadUInt64().ToString());

            case ObjectSerializer.TYPE_DECIMAL: return(Reader.ReadDecimal().ToString());

            case ObjectSerializer.TYPE_DOUBLE: return(Reader.ReadDouble().ToString());

            case ObjectSerializer.TYPE_SINGLE: return(Reader.ReadSingle().ToString());

            case ObjectSerializer.TYPE_DATETIME: return(Reader.ReadDateTime().ToString());

            case ObjectSerializer.TYPE_GUID: return(Reader.ReadSingle().ToString());

            case ObjectSerializer.TYPE_TIMESPAN: return(Reader.ReadSingle().ToString());

            default:
                throw new ArgumentException("Expected a char value, but was a " +
                                            FilesProvider.GetFieldDataTypeName(FieldDataType) + ".", nameof(FieldDataType));
            }
        }
コード例 #18
0
        public List <InternetShop> Get(InternetShopFilter filter)
        {
            List <InternetShop> ResultInternetShop = new List <InternetShop>();

            FilesProvider.OpenReader("InternetShop");

            int peek = FilesProvider.Peek();

            while (peek != -1)
            {
                string IdRow = FilesProvider.ReadRow();
                if (string.IsNullOrEmpty(IdRow))
                {
                    break;                              // means that if file is empty
                }
                string[] IdParts = IdRow.Split(':');
                int      id      = Convert.ToInt32(IdParts[1].Trim());


                string   NameRow   = FilesProvider.ReadRow();
                string[] NameParts = NameRow.Split(':');
                string   name      = NameParts[1].Trim();


                string   CategoryRow   = FilesProvider.ReadRow();
                string[] CategoryParts = NameRow.Split(':');
                string   category      = CategoryParts[1].Trim();

                string   PriceRow   = FilesProvider.ReadRow();
                string[] PriceParts = PriceRow.Split(':');
                string   price      = PriceParts[1].Trim();


                InternetShop Collection = new InternetShop(id, name, category, price);
                ResultInternetShop.Add(Collection);

                peek = FilesProvider.Peek();
                if (FilesProvider.ReadRow() == "")
                {
                    continue;
                }
            } // while

            FilesProvider.CloseReader();
            return(ResultInternetShop);
        }
コード例 #19
0
ファイル: SerialFile.cs プロジェクト: iamr8/IoTGateway
        /// <summary>
        /// Gets keys for the serial file, or decendant.
        /// </summary>
        /// <param name="SerialFile">SerialFile reference, or decendant.</param>
        /// <param name="Provider">Provider of encryption keys.</param>
        protected static async Task GetKeys(SerialFile SerialFile, FilesProvider Provider)
        {
            if (SerialFile.encrypted)
            {
                SerialFile.aes           = Aes.Create();
                SerialFile.aes.BlockSize = 128;
                SerialFile.aes.KeySize   = 256;
                SerialFile.aes.Mode      = CipherMode.CBC;
                SerialFile.aes.Padding   = PaddingMode.None;

                KeyValuePair <byte[], byte[]> P = await Provider.GetKeys(SerialFile.fileName, SerialFile.fileExists);

                SerialFile.aesKey    = P.Key;
                SerialFile.ivSeed    = P.Value;
                SerialFile.ivSeedLen = SerialFile.ivSeed.Length;
            }
        }
コード例 #20
0
        public static void AssemblyInitialize(TestContext _)
        {
            Types.Initialize(
                typeof(Database).Assembly,
                typeof(FilesProvider).Assembly,
                typeof(ObjectSerializer).Assembly,
                typeof(LoginAuditor).Assembly);

            filesProvider = new FilesProvider("Data", "Default", 8192, 10000, 8192, Encoding.UTF8, 10000, true);
            Database.Register(filesProvider);

            auditor = new LoginAuditor("Login Auditor",
                                       new LoginInterval(5, TimeSpan.FromHours(1)), // Maximum 5 failed login attempts in an hour
                                       new LoginInterval(2, TimeSpan.FromDays(1)),  // Maximum 2x5 failed login attempts in a day
                                       new LoginInterval(2, TimeSpan.FromDays(7)),  // Maximum 2x2x5 failed login attempts in a week
                                       new LoginInterval(2, TimeSpan.MaxValue));    // Maximum 2x2x2x5 failed login attempts in total, then blocked.
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: kalayaphat/IoTGateway
        private static Task <IDatabaseProvider> GetDatabase(XmlElement DatabaseConfig)
        {
            if (!CommonTypes.TryParse(DatabaseConfig.Attributes["encrypted"].Value, out bool Encrypted))
            {
                Encrypted = true;
            }

            FilesProvider Result = new FilesProvider(Gateway.AppDataFolder + DatabaseConfig.Attributes["folder"].Value,
                                                     DatabaseConfig.Attributes["defaultCollectionName"].Value,
                                                     int.Parse(DatabaseConfig.Attributes["blockSize"].Value),
                                                     int.Parse(DatabaseConfig.Attributes["blocksInCache"].Value),
                                                     int.Parse(DatabaseConfig.Attributes["blobBlockSize"].Value), Encoding.UTF8,
                                                     int.Parse(DatabaseConfig.Attributes["timeoutMs"].Value),
                                                     Encrypted, false, true);

            return(Task.FromResult <IDatabaseProvider>(Result));
        }
コード例 #22
0
        /// <summary>
        /// Reads a char value.
        /// </summary>
        /// <param name="Reader">Binary reader.</param>
        /// <param name="FieldDataType">Field data type.</param>
        /// <returns>Char value.</returns>
        /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception>
        public static char ReadChar(BinaryDeserializer Reader, uint FieldDataType)
        {
            switch (FieldDataType)
            {
            case ObjectSerializer.TYPE_CHAR: return(Reader.ReadChar());

            case ObjectSerializer.TYPE_BOOLEAN: return(Reader.ReadBoolean() ? (char)1 : (char)0);

            case ObjectSerializer.TYPE_BYTE: return((char)Reader.ReadByte());

            case ObjectSerializer.TYPE_INT16: return((char)Reader.ReadInt16());

            case ObjectSerializer.TYPE_INT32: return((char)Reader.ReadInt32());

            case ObjectSerializer.TYPE_INT64: return((char)Reader.ReadInt64());

            case ObjectSerializer.TYPE_SBYTE: return((char)Reader.ReadSByte());

            case ObjectSerializer.TYPE_UINT16: return((char)Reader.ReadUInt16());

            case ObjectSerializer.TYPE_UINT32: return((char)Reader.ReadUInt32());

            case ObjectSerializer.TYPE_UINT64: return((char)Reader.ReadUInt64());

            case ObjectSerializer.TYPE_DECIMAL: return((char)Reader.ReadDecimal());

            case ObjectSerializer.TYPE_DOUBLE: return((char)Reader.ReadDouble());

            case ObjectSerializer.TYPE_SINGLE: return((char)Reader.ReadSingle());

            case ObjectSerializer.TYPE_STRING:
                string s = Reader.ReadString();
                if (string.IsNullOrEmpty(s))
                {
                    return((char)0);
                }
                else
                {
                    return(s[0]);
                }

            default:
                throw new ArgumentException("Expected a char value, but was a " +
                                            FilesProvider.GetFieldDataTypeName(FieldDataType) + ".", nameof(FieldDataType));
            }
        }
コード例 #23
0
        /// <summary>
        /// Writes an array.
        /// </summary>
        /// <param name="T">Element type.</param>
        /// <param name="Provider">Database provider object.</param>
        /// <param name="Writer">Binary writer.</param>
        /// <param name="Value">Value to serialize.</param>
        public static void WriteArray(Type T, FilesProvider Provider, BinarySerializer Writer, Array Value)
        {
            if (Value == null)
            {
                Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6);
            }
            else
            {
                Type LastType       = T;
                IObjectSerializer S = Provider.GetObjectSerializer(LastType);
                Type ItemType;
                bool Nullable;

                Writer.WriteBits(ObjectSerializer.TYPE_ARRAY, 6);
                Writer.WriteVariableLengthUInt64((ulong)Value.Length);

                if (Nullable = S.IsNullable)
                {
                    Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6);
                }
                else
                {
                    Writer.WriteBits(FilesProvider.GetFieldDataTypeCode(LastType), 6);
                }

                foreach (object Item in Value)
                {
                    if (Item == null)
                    {
                        Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6);
                    }
                    else
                    {
                        ItemType = Item.GetType();
                        if (ItemType != LastType)
                        {
                            S        = Provider.GetObjectSerializer(ItemType);
                            LastType = ItemType;
                        }

                        S.Serialize(Writer, Nullable, true, Item);
                    }
                }
            }
        }
コード例 #24
0
 public RootDirectoryViewModel(NativeDirectoryInfo nativeDirectoryInfo, IDirectoryViewModel parent)
     : base(nativeDirectoryInfo, parent)
 {
     NativeSystemInfo = nativeDirectoryInfo;
     var directoryUnfo = new DirectoryInfo(nativeDirectoryInfo.Path);
     var subDirectoryProvider = new SubDirectoriesProvider(directoryUnfo, this);
     var filesProvider = new FilesProvider(directoryUnfo,this);
     DisplayName = nativeDirectoryInfo.DisplayName;
     Path = nativeDirectoryInfo.Path;
     VisualPath = Parent.VisualPath + "\\" + DisplayName;
     //is drive?
     DriveInfo driveInfo =  Drives.FirstOrDefault(info => PathHelper.NormalizePath(info.Name) == PathHelper.NormalizePath(Path));
     HasItems = driveInfo?.IsReady ?? directoryUnfo.EnumerateDirectories().Any();
     SubDirectories = new AsyncLoadCollection<IDirectoryViewModel>(subDirectoryProvider);
     SubDirectories.CollectionChanged += _subDirectories_CollectionChanged;
     Files = new AsyncLoadCollection<ISystemObjectViewModel>(filesProvider);
     Children = new UnionCollectionEx<IDirectoryViewModel, ISystemObjectViewModel, ISystemObjectViewModel>(SubDirectories, Files);
 }
コード例 #25
0
        async void init()
        {
            Types.Initialize(
                typeof(FilesProvider).GetTypeInfo().Assembly,
                typeof(ObjectSerializer).GetTypeInfo().Assembly,
                typeof(RuntimeSettings).GetTypeInfo().Assembly,
                typeof(Waher.Content.IContentEncoder).GetTypeInfo().Assembly,
                typeof(XmppClient).GetTypeInfo().Assembly,
                typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                typeof(XML).GetTypeInfo().Assembly,
                typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly,
                typeof(Waher.Script.Persistence.SQL.Select).GetTypeInfo().Assembly,
                typeof(TheClientV).Assembly);
            db = await FilesProvider.CreateAsync(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                                                 Path.DirectorySeparatorChar + "IoT-DEMO-APP", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000);

            Database.Register(db);

            await db.RepairIfInproperShutdown(null);

            await db.Start();

            this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

            if (string.IsNullOrEmpty(this.deviceId))
            {
                this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
            }

            Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                              Path.DirectorySeparatorChar + "IoT-DEMO-APP");
            Console.WriteLine(this.deviceId);

            this.xmppClient = new XmppClient(this.Host, this.Port, this.UserName, this.PasswordHash, "en", typeof(TheClientV).Assembly);
            this.xmppClient.AllowRegistration(Key, Secret);
            this.xmppClient.OnConnectionError   += this.ConnectionError;
            this.xmppClient.OnStateChanged      += this.OnStateChanged;
            this.xmppClient.OnRosterItemAdded   += OnRosterItemAdded;
            this.xmppClient.OnRosterItemUpdated += OnRosterItemUpdated;
            this.xmppClient.OnRosterItemRemoved += OnRosterItemRemoved;
            this.xmppClient.Connect();
        }
コード例 #26
0
        public async Task TestInitialize()
        {
            if (File.Exists(DBFilesBTreeTests.MasterFileName + ".bak"))
            {
                File.Delete(DBFilesBTreeTests.MasterFileName + ".bak");
            }

            if (File.Exists(DBFilesBTreeTests.MasterFileName))
            {
                File.Copy(DBFilesBTreeTests.MasterFileName, DBFilesBTreeTests.MasterFileName + ".bak");
                File.Delete(DBFilesBTreeTests.MasterFileName);
            }

            if (File.Exists(FileName + ".bak"))
            {
                File.Delete(FileName + ".bak");
            }

            if (File.Exists(FileName))
            {
                File.Copy(FileName, FileName + ".bak");
                File.Delete(FileName);
            }

            if (File.Exists(BlobFileName + ".bak"))
            {
                File.Delete(BlobFileName + ".bak");
            }

            if (File.Exists(BlobFileName))
            {
                File.Copy(BlobFileName, BlobFileName + ".bak");
                File.Delete(BlobFileName);
            }

#if LW
            this.provider = await FilesProvider.CreateAsync(Folder, CollectionName, 8192, BlocksInCache, 8192, Encoding.UTF8, 10000);
#else
            this.provider = await FilesProvider.CreateAsync(Folder, CollectionName, 8192, BlocksInCache, 8192, Encoding.UTF8, 10000, true);
#endif
            this.file = await StringDictionary.Create(FileName, BlobFileName, CollectionName, this.provider, false);

            this.start = DateTime.Now;
        }
コード例 #27
0
        /// <inheritdoc />
        public async Task TryRepairDatabase(ProfilerThread Thread)
        {
            if (await this.uiDispatcher.DisplayAlert(AppResources.DatabaseIssue, AppResources.DatabaseCorruptInfoText, AppResources.RepairAndContinue, AppResources.ContinueAnyway))
            {
                string method = "Delete database file(s) and create new empty database";
                try
                {
                    Thread?.NewState("Delete");

                    // 3. Delete and create a new empty database
                    Directory.Delete(dataFolder, true);

                    Thread?.NewState("Recreate");

                    this.databaseProvider = await CreateDatabaseFile();

                    Thread?.NewState("Repair3");

                    await this.databaseProvider.RepairIfInproperShutdown(string.Empty);

                    // If we had to repair, we must register the provider 'again', as one hasn't been provided yet.
                    if (!Database.HasProvider)
                    {
                        method = $"{nameof(Database)}.{nameof(Database.Register)}";
                        Database.Register(databaseProvider, false);
                    }
                    // All is good.
                    this.SetState(StorageState.Ready);
                }
                catch (Exception e3)
                {
                    e3 = Log.UnnestException(e3);
                    Thread?.Exception(e3);

                    // Delete and create new failed. We're out of options.
                    this.logService.LogException(e3, this.GetClassAndMethod(MethodBase.GetCurrentMethod(), method));

                    Thread?.NewState("DisplayAlert2");

                    await this.uiDispatcher.DisplayAlert(AppResources.DatabaseIssue, AppResources.DatabaseRepairFailedInfoText, AppResources.Ok);
                }
            }
        }
コード例 #28
0
        public RootDirectoryViewModel(NativeDirectoryInfo nativeDirectoryInfo, IDirectoryViewModel parent) : base(nativeDirectoryInfo, parent)
        {
            NativeSystemInfo = nativeDirectoryInfo;
            var directoryUnfo        = new DirectoryInfo(nativeDirectoryInfo.Path);
            var subDirectoryProvider = new SubDirectoriesProvider(directoryUnfo, this);
            var filesProvider        = new FilesProvider(directoryUnfo, this);

            DisplayName = nativeDirectoryInfo.DisplayName;
            Path        = nativeDirectoryInfo.Path;
            VisualPath  = Parent.VisualPath + "\\" + DisplayName;
            //is drive?
            DriveInfo driveInfo = Drives.FirstOrDefault(info => PathHelper.NormalizePath(info.Name) == PathHelper.NormalizePath(Path));

            HasItems       = driveInfo?.IsReady ?? directoryUnfo.EnumerateDirectories().Any();
            SubDirectories = new AsyncLoadCollection <IDirectoryViewModel>(subDirectoryProvider);
            SubDirectories.CollectionChanged += _subDirectories_CollectionChanged;
            Files    = new AsyncLoadCollection <ISystemObjectViewModel>(filesProvider);
            Children = new UnionCollectionEx <IDirectoryViewModel, ISystemObjectViewModel, ISystemObjectViewModel>(SubDirectories, Files);
        }
コード例 #29
0
        /// <inheritdoc />
        public async Task Shutdown()
        {
            this.currentState = StorageState.NotInitialized;

            try
            {
                if (!(this.databaseProvider is null))
                {
                    await this.databaseProvider.Flush();

                    this.databaseProvider.Dispose();
                    this.databaseProvider = null;
                }
            }
            catch (Exception e)
            {
                this.logService.LogException(e);
            }
        }
コード例 #30
0
        /// <summary>
        /// Serializes binary blocks into a file, possibly encrypted. Blocks are accessed in the order they were persisted.
        /// </summary>
        /// <param name="FileName">Name of file</param>
        /// <param name="CollectionName">Collection Name</param>
        /// <param name="TimeoutMilliseconds">Timeout, in milliseconds.</param>
        /// <param name="Encrypted">If file is encrypted.</param>
        /// <param name="Provider">Provider of encryption keys.</param>
        public SerialFile(string FileName, string CollectionName, int TimeoutMilliseconds, bool Encrypted, FilesProvider Provider)
        {
            if (TimeoutMilliseconds <= 0)
            {
                throw new ArgumentOutOfRangeException("The timeout must be positive.", nameof(TimeoutMilliseconds));
            }

            this.provider            = Provider;
            this.fileName            = FileName;
            this.collectionName      = CollectionName;
            this.timeoutMilliseconds = TimeoutMilliseconds;
            this.encrypted           = Encrypted;

            bool FileExists = File.Exists(this.fileName);

            string Folder = Path.GetDirectoryName(this.fileName);

            if (!string.IsNullOrEmpty(Folder) && !Directory.Exists(Folder))
            {
                Directory.CreateDirectory(Folder);
            }

            if (FileExists)
            {
                this.file = File.Open(this.fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            else
            {
                this.file = File.Open(this.fileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
            }

            if (this.encrypted)
            {
                this.aes      = Aes.Create();
                aes.BlockSize = 128;
                aes.KeySize   = 256;
                aes.Mode      = CipherMode.CBC;
                aes.Padding   = PaddingMode.None;

                this.provider.GetKeys(this.fileName, FileExists, out this.aesKey, out this.ivSeed);
                this.ivSeedLen = this.ivSeed.Length;
            }
        }
コード例 #31
0
ファイル: StringDictionary.cs プロジェクト: iamr8/IoTGateway
        /// <summary>
        /// This class manages a string dictionary in a persisted file.
        /// </summary>
        /// <param name="CollectionName">Collection Name.</param>
        /// <param name="Provider">Files provider.</param>
        /// <param name="RetainInMemory">Retain the dictionary in memory.</param>
        private StringDictionary(string CollectionName, FilesProvider Provider, bool RetainInMemory)
        {
            this.provider            = Provider;
            this.collectionName      = CollectionName;
            this.encoding            = this.provider.Encoding;
            this.timeoutMilliseconds = this.provider.TimeoutMilliseconds;
            this.genericSerializer   = new GenericObjectSerializer(this.provider);
            this.keyValueSerializer  = new KeyValueSerializer(this.provider, this.genericSerializer);

            this.recordHandler = new StringDictionaryRecords(this.collectionName, this.encoding, this.genericSerializer, this.provider);

            if (RetainInMemory)
            {
                this.inMemory = new Dictionary <string, object>();
            }
            else
            {
                this.inMemory = null;
            }
        }