Ejemplo n.º 1
0
        public unsafe static object CreateStorage(
            string path,
            Guid riid,
            StorageMode mode     = StorageMode.ReadWrite | StorageMode.Create | StorageMode.ShareExclusive,
            StorageFormat format = StorageFormat.DocFile)
        {
            STGOPTIONS options = new STGOPTIONS
            {
                usVersion = 1,

                // If possible, we want the larger 4096 sector size
                ulSectorSize = (mode & StorageMode.Simple) != 0  ? 512u : 4096
            };

            Imports.StgCreateStorageEx(
                path,
                mode,
                format,
                0,
                format == StorageFormat.DocFile ? &options : null,
                null,
                ref riid,
                out object created).ThrowIfFailed(path);

            return(created);
        }
Ejemplo n.º 2
0
        public static void SaveFrame(string path, StorageFormat format, Frame frame)
        {
            FileWriter writer = null;

            try
            {
                writer = new FileWriter(path);
                switch (format)
                {
                case StorageFormat.Simple:
                    throw new Exception();

                case StorageFormat.TestLab:
                    SaveTestLabFrame(frame, writer);
                    break;

                case StorageFormat.Catman:
                    SaveCatmanFrame(frame, writer);
                    break;

                case StorageFormat.Mera:
                    throw new Exception();

                default:
                    throw new ArgumentOutOfRangeException("format", "Произошла попытка сохранить кадр в неизвестном формате.");
                }
            }
            finally
            {
                writer?.Close();
            }
        }
Ejemplo n.º 3
0
        public async Task CreateStorageMarkersAsync(StorageFormat newStorageFormat)
        {
            myLogger.Info($"[{DateTime.Now:s}] Creating storage markers{myId}...");
            if (!await myStorage.IsEmptyAsync())
            {
                throw new Exception("The empty storage is expected");
            }
            var files = new List <string> {
                Markers.SingleTier
            };

            switch (newStorageFormat)
            {
            case StorageFormat.Normal: break;

            case StorageFormat.LowerCase:
                files.Add(Markers.LowerCase);
                break;

            case StorageFormat.UpperCase:
                files.Add(Markers.UpperCase);
                break;

            default: throw new ArgumentOutOfRangeException(nameof(newStorageFormat), newStorageFormat, null);
            }

            foreach (var file in files)
            {
                await myStorage.CreateEmptyAsync(file, AccessMode.Private);
            }
        }
Ejemplo n.º 4
0
        public void Load(StorageFormat format)
        {
            switch (format)
            {
            case StorageFormat.Json:
                string serialized = File.ReadAllText(@"deck.json");
                _cards = JsonConvert.DeserializeObject <List <Card> >(serialized);
                break;

            case StorageFormat.Binary:
                using (FileStream input = File.OpenRead(@"deck.bin"))
                {
                    byte[] bytes = new byte[2 * 52];
                    int    read  = input.Read(bytes, 0, bytes.Length);

                    List <Card> loaded = new List <Card>();

                    int i = 0;
                    while (i + 1 < read)
                    {
                        loaded.Add(new Card((Suit)bytes[i], (Rank)bytes[i + 1]));
                        i += 2;
                    }

                    _cards = loaded;
                }
                break;

            default:
                throw new NotSupportedException($"Storage format {format} not supported");
            }
        }
Ejemplo n.º 5
0
 public CreateCommand(
     [NotNull] ILogger logger,
     [NotNull] IStorage storage,
     StorageFormat expectedStorageFormat,
     [NotNull] string toolId,
     [NotNull] string product,
     [NotNull] string version,
     bool isCompressPe,
     bool isCompressWPdb,
     bool isKeepNonCompressed,
     [NotNull] IEnumerable <KeyValuePair <string, string> > properties,
     [NotNull] IReadOnlyCollection <string> sources)
 {
     myLogger  = logger ?? throw new ArgumentNullException(nameof(logger));
     myStorage = storage ?? throw new ArgumentNullException(nameof(storage));
     myExpectedStorageFormat = expectedStorageFormat;
     myToolId              = toolId ?? throw new ArgumentNullException(nameof(toolId));
     myProduct             = product ?? throw new ArgumentNullException(nameof(product));
     myVersion             = version ?? throw new ArgumentNullException(nameof(version));
     myIsCompressPe        = isCompressPe;
     myIsCompressWPdb      = isCompressWPdb;
     myIsKeepNonCompressed = isKeepNonCompressed;
     myProperties          = properties ?? throw new ArgumentNullException(nameof(properties));
     mySources             = sources ?? throw new ArgumentNullException(nameof(sources));
 }
Ejemplo n.º 6
0
 public NDArrayView(DataType dataType, StorageFormat storageType, NDShape viewShape, DeviceDescriptor device) : this(CNTKLibPINVOKE.new_NDArrayView__SWIG_2((int)dataType, (int)storageType, NDShape.getCPtr(viewShape), DeviceDescriptor.getCPtr(device)), true)
 {
     if (CNTKLibPINVOKE.SWIGPendingException.Pending)
     {
         throw CNTKLibPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Ejemplo n.º 7
0
        public void LoadObj(StorageFormat sf)
        {
            StorageDictionary <T> dic = new StorageDictionary <T>();

            switch (sf)
            {
            case StorageFormat.sfMemory:
                if (mem != null)
                {
                    dic = BaseStorageMemory.Load <StorageDictionary <T> >(mem);
                }
                break;

            case StorageFormat.sfText:
                //if (T is Document)
                dic = BaseStorageText.LoadObj2(this);
                break;

            //XML
            default:
                dic = BaseStorageXml.LoadObj(this);
                break;
            }

            this.Clear();
            foreach (var elem in dic)
            {
                Add(elem.Key, elem.Value);
            }
        }
Ejemplo n.º 8
0
        public void Save(StorageFormat format)
        {
            switch (format)
            {
            case StorageFormat.Json:
                string serialized = JsonConvert.SerializeObject(_cards);
                File.WriteAllText(@"deck.json", serialized);
                break;

            case StorageFormat.Binary:
                using (FileStream output = File.Create(@"deck.bin"))
                {
                    byte[] bytes = _cards
                                   .SelectMany(c => new byte[2] {
                        (byte)c.Suit, (byte)c.Rank
                    })
                                   .ToArray();

                    output.Write(bytes, 0, bytes.Length);
                }
                break;

            default:
                throw new NotSupportedException($"Storage format {format} not supported");
            }
        }
Ejemplo n.º 9
0
 public NewCommand(
     [NotNull] ILogger logger,
     [NotNull] IStorage storage,
     StorageFormat newStorageFormat)
 {
     myLogger           = logger ?? throw new ArgumentNullException(nameof(logger));
     myStorage          = storage ?? throw new ArgumentNullException(nameof(storage));
     myNewStorageFormat = newStorageFormat;
 }
Ejemplo n.º 10
0
 public unsafe static extern HResult StgCreateStorageEx(
     string pwcsName,
     StorageMode grfMode,
     StorageFormat stgfmt,
     FileFlags grfAttrs,
     STGOPTIONS *pStgOptions,
     SECURITY_DESCRIPTOR **pSecurityDescriptor,
     ref Guid riid,
     [MarshalAs(UnmanagedType.IUnknown)] out object ppObjectOpen);
Ejemplo n.º 11
0
        // Called from every constructor to setup and validate the hash policy.
        private void SetPolicy(HashAlgorithm hashAlgorithm, int workFactor, StorageFormat storageFormat, int numberOfSaltBytes)
        {
            this.HashMethod        = hashAlgorithm;
            this.WorkFactor        = workFactor;
            this.HashStorageFormat = storageFormat;
            this.NumberOfSaltBytes = numberOfSaltBytes;

            this.ValidatePolicy();
        }
Ejemplo n.º 12
0
 public unsafe static extern HResult StgOpenStorageEx(
     string pwcsName,
     StorageMode grfMode,
     StorageFormat stgfmt,
     FileFlags grfAttrs,
     STGOPTIONS *pStgOptions,
     void *reserved2,
     ref Guid riid,
     [MarshalAs(UnmanagedType.IUnknown)] out object ppObjectOpen);
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of a document collection
 /// </summary>
 /// <param name="name">
 /// The name of the collection
 /// </param>
 /// <param name="provider">
 /// The database provider used in the collection
 /// </param>
 /// <param name="format">
 /// The format used to store documents in the collection
 /// </param>
 public DocumentCollection(
     string name,
     IDbProvider provider,
     StorageFormat format)
 {
     this.Name     = name;
     this.provider = provider;
     this.Format   = format;
 }
Ejemplo n.º 14
0
        public async Task <StorageFormat> CreateOrValidateStorageMarkersAsync(StorageFormat newStorageFormat)
        {
            if (!await myStorage.IsEmptyAsync())
            {
                return(await ValidateStorageMarkersAsync());
            }
            await CreateStorageMarkersAsync(newStorageFormat);

            return(newStorageFormat);
        }
Ejemplo n.º 15
0
        private StorageFormat _GetStorageFormat()
        {
            StorageFormat ret = (StorageFormat)CNTKLibPINVOKE.NDArrayView__GetStorageFormat(swigCPtr);

            if (CNTKLibPINVOKE.SWIGPendingException.Pending)
            {
                throw CNTKLibPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Creates a new collection for the specified type. The name of the
 /// collection that is created is the same as the name of the type.
 /// </summary>
 /// <typeparam name="T">
 /// The type that is stored in the collection
 /// </typeparam>
 /// <param name="format">
 /// The document format that is used for storing objects in the database
 /// </param>
 public IDocumentCollection <T> CreateCollection <T>(StorageFormat format)
 {
     if (!provider.CreateCollection <T>(format))
     {
         throw new Exception(
                   string.Format("Collection '{0}' could not be created",
                                 typeof(T).Name));
     }
     return(provider.GetCollection <T>());
 }
Ejemplo n.º 17
0
 static bool TryRead(BinaryReader reader, out MessageWithId msg)
 {
     try {
         msg = StorageFormat.Read(reader);
         return(true);
     }
     catch (EndOfStreamException) {
         msg = null;
         return(false);
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Set the storage format
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnStorageFormatChanged(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;

            OnMenuItemClick(item);

            StorageFormat type = ( StorageFormat )Enum.Parse(typeof(StorageFormat),
                                                             ( string )item.Header);

            m_storageFormat = type;
        }
Ejemplo n.º 19
0
 public UploadCommand(
     [NotNull] ILogger logger,
     [NotNull] IStorage storage,
     [NotNull] string source,
     StorageFormat newStorageFormat)
 {
     myLogger           = logger ?? throw new ArgumentNullException(nameof(logger));
     myStorage          = storage ?? throw new ArgumentNullException(nameof(storage));
     mySource           = source ?? throw new ArgumentNullException(nameof(source));
     myNewStorageFormat = newStorageFormat;
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Инициализирует новый экземпляр класса.
 /// </summary>
 /// <param name="format">
 /// Формат кадра.
 /// </param>
 /// <param name="name">
 /// Имя канала.
 /// </param>
 /// <param name="unit">
 /// Единица измерения.
 /// </param>
 /// <param name="sampling">
 /// Частота дискретизации.
 /// </param>
 /// <param name="cutoff">
 /// Частота среза фильтра.
 /// </param>
 /// <exception cref="ArgumentOutOfRangeException">
 /// Происходит в случае, если значение параметра <paramref name="sampling"/> меньше нуля.
 /// </exception>
 internal ChannelHeader(StorageFormat format, string name, string unit, double sampling, double cutoff)
 {
     Format = format;
     _Name  = name;
     _Unit  = unit;
     if (sampling < 0)
     {
         throw new ArgumentOutOfRangeException("sampling", "Произошла попытка задать отрицательную частоту дискретизации.");
     }
     _Sampling = sampling;
     _Cutoff   = cutoff;
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Creates a new dynamic collection and returns an instance of it.
 /// </summary>
 /// <param name="name">The name of the collection to create</param>
 /// <param name="format">
 /// The document format that is used for storing objects in the database
 /// </param>
 public IDocumentCollection <dynamic> CreateCollection(
     string name,
     StorageFormat format)
 {
     if (!provider.CreateCollection(name, format))
     {
         throw new Exception(
                   string.Format(
                       "Collection '{0}' could not be created",
                       name));
     }
     return(provider.GetCollection <dynamic>(name));
 }
        public IDocStorage CreateStorage(StorageFormat format)
        {
            switch (format)
            {
            case StorageFormat.Fb2:
                return(new Fb2DocStorage());

            case StorageFormat.Docx:
                return(new DocxDocStorage());

            default:
                throw new ArgumentException("An invalid format: " + format.ToString());
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Configures the property as capable of storing encrypted data.
        /// </summary>
        /// <param name="property">
        /// The <see cref="PropertyBuilder{TProperty}"/>.
        /// </param>
        /// <param name="encryptionProvider">
        /// The <see cref="IEncryptionProvider"/> to use, if any.
        /// </param>
        /// <param name="format">
        /// One of the <see cref="StorageFormat"/> values indicating how the value should be stored in the database.
        /// </param>
        /// <param name="mappingHints">
        /// The <see cref="ConverterMappingHints"/> to use, if any.
        /// </param>
        /// <returns>
        /// The updated <see cref="PropertyBuilder{TProperty}"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="property"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="format"/> is not a recognised value.
        /// </exception>
        public static PropertyBuilder <byte[]> IsEncrypted(
            this PropertyBuilder <byte[]> property,
            IEncryptionProvider encryptionProvider,
            StorageFormat format = StorageFormat.Default,
            ConverterMappingHints mappingHints = null)
        {
            if (property is null)
            {
                throw new ArgumentNullException(nameof(property));
            }

            return(format switch
            {
                StorageFormat.Default => encryptionProvider is null ? property : property.HasConversion(encryptionProvider.FromBinary().ToBinary().Build(mappingHints)),
                StorageFormat.Binary => encryptionProvider is null ? property : property.HasConversion(encryptionProvider.FromBinary().ToBinary().Build(mappingHints)),
                StorageFormat.Base64 => property.HasConversion(encryptionProvider.FromBinary().ToBase64().Build(mappingHints)),
                _ => throw new ArgumentOutOfRangeException(nameof(format)),
            });
Ejemplo n.º 24
0
        /// <summary>
        /// Возвращает заголовок канала в другом формате.
        /// </summary>
        /// <param name="format">
        /// Формат заголовка канала, в который необходимо преобразовать текущий объект.
        /// </param>
        /// <returns>
        /// Преобразованный объект.
        /// </returns>
        internal override ChannelHeader Convert(StorageFormat format)
        {
            switch (format)
            {
            case StorageFormat.TestLab:
                return(Clone());

            case StorageFormat.Catman:
            {
                CatmanChannelHeader header = new CatmanChannelHeader();
                header.Sampling = Sampling;
                header.Cutoff   = Cutoff;
                return(header);
            }

            default:
                throw new Exception();
            }
        }
Ejemplo n.º 25
0
        public void SaveObj(StorageFormat sf)
        {
            switch (sf)
            {
            case StorageFormat.sfMemory:
                mem = BaseStorageMemory.Save(this);
                break;

            case StorageFormat.sfText:
                //if (T is Document)
                //BaseStorageDocumentText.SaveObj(this);
                //break;
                BaseStorageText.SaveObj2(this);
                break;

            //XML
            default:
                BaseStorageXml.SaveObj(this);
                break;
            }
        }
Ejemplo n.º 26
0
        private void TestStorage()
        {
            StorageFormat sf;

            try
            {
                m_pProfile3.GetStorageFormat(out sf);
            }
            catch
            {
                // per the docs, this method is not implemented
            }
            try
            {
                sf = new StorageFormat();
                m_pProfile3.SetStorageFormat(sf);
            }
            catch
            {
                // per the docs, this method is not implemented
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Возвращает заголовок кадра в другом формате.
        /// </summary>
        /// <param name="format">
        /// Формат заголовка канала, в который необходимо преобразовать текущий объект.
        /// </param>
        /// <returns>
        /// Преобразованный объект.
        /// </returns>
        internal virtual ChannelHeader Convert(StorageFormat format)
        {
            if (format == Format)
            {
                return(Clone());
            }
            switch (format)
            {
            case StorageFormat.Simple:
                return(new ChannelHeader(Name, Unit, Sampling, Cutoff));

            case StorageFormat.TestLab:
            {
                TestLabChannelHeader header = new TestLabChannelHeader();
                header.Name     = Name;
                header.Unit     = Unit;
                header.Sampling = Sampling;
                header.Cutoff   = Cutoff;
                return(header);
            }

            case StorageFormat.Catman:
            {
                CatmanChannelHeader header = new CatmanChannelHeader();
                header.Name     = Name;
                header.Unit     = Unit;
                header.Sampling = Sampling;
                header.Cutoff   = Cutoff;
                return(header);
            }

            case StorageFormat.Mera:
                throw new Exception();

            default:
                throw new ArgumentOutOfRangeException("format", "Произошла попытка преобразовать заголовок канала в неизвестный формат.");
            }
        }
Ejemplo n.º 28
0
        public unsafe static object OpenStorage(
            string path,
            Guid riid,
            StorageMode mode     = StorageMode.ReadWrite | StorageMode.ShareExclusive,
            StorageFormat format = StorageFormat.Any)
        {
            STGOPTIONS options = new STGOPTIONS
            {
                // Must have version set before using
                usVersion = 1
            };

            Imports.StgOpenStorageEx(
                path,
                mode,
                format,
                0,
                format == StorageFormat.DocFile ? &options : null,
                null,
                ref riid,
                out object created).ThrowIfFailed(path);

            return(created);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Возвращает заголовок кадра в другом формате.
        /// </summary>
        /// <param name="format">
        /// Формат заголовка канала, в который необходимо преобразовать текущий объект.
        /// </param>
        /// <returns>
        /// Преобразованный объект.
        /// </returns>
        internal virtual FrameHeader Convert(StorageFormat format)
        {
            if (format == Format)
            {
                return(Clone());
            }
            switch (format)
            {
            case StorageFormat.Simple:
                return(new FrameHeader());

            case StorageFormat.TestLab:
                return(new TestLabFrameHeader());

            case StorageFormat.Catman:
                return(new CatmanFrameHeader());

            case StorageFormat.Mera:
                throw new Exception();

            default:
                throw new ArgumentOutOfRangeException("format", "Произошла попытка преобразовать заголовок кадра в неизвестный формат.");
            }
        }
Ejemplo n.º 30
0
 public static void storeLocally(Calendar cal, StorageFormat formatter)
 {
     // Stores the calender in a format specified by the storageFormat.
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EncryptedAttribute"/> class.
 /// </summary>
 /// <param name="format">
 /// The storage format.
 /// </param>
 public EncryptedAttribute(StorageFormat format)
 {
     Format = format;
 }