Esempio n. 1
0
        public void Write(WriteStream stream, StreamContext context)
        {
            if (context.fullModel)
            {
                // Active state
                stream.WriteVarint32((uint)Properties.ActiveState, _activeState);

                // Device type
                stream.WriteVarint32((uint)Properties.DeviceType, _deviceType);
            }
            else
            {
                // Active state
                if (context.reliableChannel)
                {
                    // If we're going to send an update. Push the cache to inflight.
                    LocalCacheEntry entry = _cache.localCache;
                    if (entry.activeStateSet || entry.deviceTypeSet)
                    {
                        _cache.PushLocalCacheToInflight(context.updateID);
                    }

                    if (entry.activeStateSet)
                    {
                        stream.WriteVarint32((uint)Properties.ActiveState, entry.activeState);
                    }
                    if (entry.deviceTypeSet)
                    {
                        stream.WriteVarint32((uint)Properties.DeviceType, entry.deviceType);
                    }
                }
            }
        }
Esempio n. 2
0
        // Serialization
        public int WriteLength(StreamContext context)
        {
            int length = 0;

            if (context.fullModel)
            {
                // Flatten cache
                _clientID = clientID;
                _streamID = streamID;
                _cache.Clear();

                // ClientID/StreamID
                length += WriteStream.WriteVarint32Length(1, WriteStream.ConvertNegativeOneIntToUInt(_clientID));
                length += WriteStream.WriteVarint32Length(2, WriteStream.ConvertNegativeOneIntToUInt(_streamID));
            }
            else
            {
                // ClientID/StreamID
                if (context.reliableChannel)
                {
                    LocalCacheEntry entry = _cache.localCache;
                    if (entry.clientIDSet)
                    {
                        length += WriteStream.WriteVarint32Length(1, WriteStream.ConvertNegativeOneIntToUInt(entry.clientID));
                    }
                    if (entry.streamIDSet)
                    {
                        length += WriteStream.WriteVarint32Length(2, WriteStream.ConvertNegativeOneIntToUInt(entry.streamID));
                    }
                }
            }

            return(length);
        }
Esempio n. 3
0
        public void Read(ReadStream stream, StreamContext context)
        {
            // Remove from in-flight
            if (context.deltaUpdatesOnly && context.reliableChannel)
            {
                _cache.RemoveUpdateFromInflight(context.updateID);
            }

            // Read properties
            uint propertyID;

            while (stream.ReadNextPropertyID(out propertyID))
            {
                switch (propertyID)
                {
                case (uint)Properties.ActiveState:
                    _activeState = stream.ReadVarint32();
                    FireActiveStateChanged();
                    break;

                case (uint)Properties.DeviceType:
                    _deviceType = stream.ReadVarint32();
                    break;

                default:
                    stream.SkipProperty();
                    break;
                }
            }
        }
Esempio n. 4
0
        public void Open_should_throw_FileNotFoundException()
        {
            var ss = StreamContext.FromFile(RootDirectory + "Content/missing.p");
            var ex = Record.Exception(() => ss.OpenRead());

            Assert.IsInstanceOf <FileNotFoundException>(ex);
        }
Esempio n. 5
0
        /// <summary>
        /// Deletes a file using a StreamWrapper corresponding to the given URL.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="path">An URL of a file to be deleted.</param>
        /// <param name="context">StreamContext.</param>
        /// <returns>True in case of success.</returns>
        public static bool unlink(Context ctx, string path, PhpResource context = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "path"));
                //return false;
                throw new ArgumentException(nameof(path));
            }

            var sc = StreamContext.GetValid(context, true);

            if (sc == null) // PHP warning is thrown by StreamContext.GetValid
            {
                return(false);
            }

            StreamWrapper wrapper;

            if (!PhpStream.ResolvePath(ctx, ref path, out wrapper, CheckAccessMode.FileExists, CheckAccessOptions.Empty))
            {
                return(false);
            }

            // Clear the cache (the currently deleted file may have been cached)
            clearstatcache();

            //
            return(wrapper.Unlink(path, 0, sc));
        }
Esempio n. 6
0
        public static void TestTextEncoder()
        {
            var values = new object[]
            {
                2,
                '\n',
                TextEncodingEscaper.DefaultSeparator,
                long.MaxValue,
                int.MinValue,
                double.MaxValue / 2,
                -double.Epsilon,
                DateTime.Now,
                "\ne#$",
                "\t"
            };

            foreach (var value in values)
            {
                foreach (var type in new[] { IoType.Key, IoType.Value })
                {
                    var stream = new StreamContext();
                    var encoder = new TextEncoder(stream.writer);
                    var decoder = new TextDecoder(stream.reader);
                    Action f = () => encoder.WriteChar(TextEncodingEscaper.DefaultSeparator, IoType.Raw);

                    TestEncoderHelper(value, encoder, decoder, stream, type, f);
                }
            }
        }
Esempio n. 7
0
        public void FromSource_when_relative_uri_treat_as_file()
        {
            var s = StreamContext.FromSource(new Uri("./Build", UriKind.Relative));

            Assert.IsInstanceOf <FileSystemStreamContext>(s);
            Assert.Equal(new Uri("./Build", UriKind.Relative), s.Uri);
        }
Esempio n. 8
0
        public static PhpResource fopen(Context ctx, string path, string mode, FileOpenOptions flags = FileOpenOptions.Empty, PhpResource context = null)
        {
            StreamContext sc = StreamContext.GetValid(context, true);

            if (sc == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(path))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "path"));
                //return null;
                throw new ArgumentException(nameof(path));
            }

            if (string.IsNullOrEmpty(mode))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "mode"));
                //return null;
                throw new ArgumentException(nameof(mode));
            }

            return(PhpStream.Open(ctx, path, mode, ProcessOptions(ctx, flags), sc));
        }
Esempio n. 9
0
        public void BuildPipeline(StreamContext context, EncoderUnit.LogStream log)
        {
            // input
            bool doInputReader = context.Source.NeedsInputReaderUnit;

            if (doInputReader)
            {
                context.Pipeline.AddDataUnit(context.Source.GetInputReaderUnit(), 1);
            }

            // get parameters
            VLCParameters vlcparam = GenerateVLCParameters(context);
            string        path     = @"\#OUT#";
            string        sout     = vlcparam.Sout.Replace("#OUT#", path);

            // generate vlc argument string
            var    quotedArgList = vlcparam.Arguments.Select(x => x.Replace("\"", "\\\""));
            string vlcArguments  = "\"" + String.Join("\" \"", quotedArgList) + "\"";
            string arguments     = GenerateArguments(vlcparam.Input, sout, vlcArguments);

            // add the unit
            EncoderUnit.TransportMethod input        = doInputReader ? EncoderUnit.TransportMethod.NamedPipe : EncoderUnit.TransportMethod.Other;
            EncoderUnit.TransportMethod outputMethod = readOutputStream ? EncoderUnit.TransportMethod.NamedPipe : EncoderUnit.TransportMethod.Other;
            // waiting for output pipe is meaningless for VLC as it opens it way earlier then that it actually writes to it. Instead, log parsing
            // in VLCWrapped handles the delay (yes, this class is standalone probably useless but is provided for debugging).
            EncoderUnit unit = new EncoderUnit(context.Profile.CodecParameters["path"], arguments, input, outputMethod, log);

            unit.DebugOutput = false; // change this for debugging
            context.Pipeline.AddDataUnit(unit, 5);
        }
        public int WriteLength(StreamContext context)
        {
            int length = 0;

            // Meta model
            length += WriteStream.WriteModelLength(0, _metaModel, context);

            if (context.fullModel)
            {
                // Write all properties
                if (_sceneViewUUID != null && _sceneViewUUID.Length > 0)
                {
                    length += WriteStream.WriteBytesLength((uint)PropertyID.SceneViewUUID, _sceneViewUUID.Length);
                }
                if (_prefabName != null && _prefabName.Length > 0)
                {
                    length += WriteStream.WriteStringLength((uint)PropertyID.PrefabName, _prefabName);
                }
            }

            // Components
            if (_componentsModel != null)
            {
                length += WriteStream.WriteModelLength((uint)PropertyID.Components, _componentsModel, context);
            }

            // Child Views
            if (_childViewsModel != null)
            {
                length += WriteStream.WriteModelLength((uint)PropertyID.ChildViews, _childViewsModel, context);
            }

            return(length);
        }
Esempio n. 11
0
        public void Write(WriteStream stream, StreamContext context)
        {
            if (context.fullModel)
            {
                // ClientID/StreamID
                stream.WriteVarint32(1, WriteStream.ConvertNegativeOneIntToUInt(_clientID));
                stream.WriteVarint32(2, WriteStream.ConvertNegativeOneIntToUInt(_streamID));
            }
            else
            {
                // ClientID/StreamID
                if (context.reliableChannel)
                {
                    // If we're going to send an update. Push the cache to inflight.
                    LocalCacheEntry entry = _cache.localCache;
                    if (entry.clientIDSet || entry.streamIDSet)
                    {
                        _cache.PushLocalCacheToInflight(context.updateID);
                    }

                    if (entry.clientIDSet)
                    {
                        stream.WriteVarint32(1, WriteStream.ConvertNegativeOneIntToUInt(entry.clientID));
                    }
                    if (entry.streamIDSet)
                    {
                        stream.WriteVarint32(2, WriteStream.ConvertNegativeOneIntToUInt(entry.streamID));
                    }
                }
            }
        }
Esempio n. 12
0
        /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Stat"]/*'/>
        public override StatStruct Stat(string path, StreamStatOptions options, StreamContext context, bool streamStat)
        {
            StatStruct invalid = new StatStruct();

            invalid.st_size = -1;
            Debug.Assert(path != null);

            // Note: path is already absolute w/o the scheme, the permissions have already been checked.
            return(HandleNewFileSystemInfo(invalid, path, (p) =>
            {
                FileSystemInfo info = null;

                info = new DirectoryInfo(p);
                if (!info.Exists)
                {
                    info = new FileInfo(p);
                    if (!info.Exists)
                    {
                        return invalid;
                    }
                }

                return BuildStatStruct(info, info.Attributes, p);
            }));
        }
Esempio n. 13
0
        public void BuildPipeline(StreamContext context)
        {
            // add input
            bool doInputReader = context.Source.NeedsInputReaderUnit;

            if (doInputReader)
            {
                context.Pipeline.AddDataUnit(context.Source.GetInputReaderUnit(), 1);
            }

            // calculate stream mappings (no way I'm going to add subtitle support; it's just broken)
            string mappings = "";

            if (context.AudioTrackId != null)
            {
                mappings = String.Format("-map v:0 -map a:{0}", context.MediaInfo.AudioStreams.First(x => x.ID == context.AudioTrackId).Index);
            }

            // calculate full argument string
            string arguments;

            if (context.Profile.HasVideoStream)
            {
                arguments = String.Format(
                    "-y {0} -i \"#IN#\" -s {1} -aspect {2}:{3} {4} {5} \"#OUT#\"",
                    context.StartPosition != 0 ? "-ss " + (context.StartPosition / 1000) : "",
                    context.OutputSize, context.OutputSize.Width, context.OutputSize.Height,
                    mappings, context.Profile.CodecParameters["codecParameters"]
                    );
            }
            else
            {
                arguments = String.Format(
                    "-y {0} -i \"#IN#\" {1} {2} \"#OUT#\"",
                    context.StartPosition != 0 ? "-ss " + (context.StartPosition / 1000) : "",
                    mappings, context.Profile.CodecParameters["codecParameters"]
                    );
            }

            // fix input thing
            if (!doInputReader)
            {
                arguments = arguments.Replace("#IN#", context.Source.GetPath());
            }

            // add unit
            EncoderUnit.TransportMethod input = doInputReader ? EncoderUnit.TransportMethod.NamedPipe : EncoderUnit.TransportMethod.Other;
            EncoderUnit unit = new EncoderUnit(Configuration.Streaming.FFMpegPath, arguments, input, EncoderUnit.TransportMethod.NamedPipe, EncoderUnit.LogStream.StandardError);

            unit.DebugOutput = false; // change this for debugging
            context.Pipeline.AddDataUnit(unit, 5);

            // setup output parsing
            var einfo = new Reference <WebTranscodingInfo>(() => context.TranscodingInfo, x => { context.TranscodingInfo = x; });
            FFMpegLogParsingUnit logunit = new FFMpegLogParsingUnit(einfo, context.StartPosition);

            logunit.LogMessages = true;
            logunit.LogProgress = true;
            context.Pipeline.AddLogUnit(logunit, 6);
        }
        /// <summary>
        /// Removes a directory.
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="dirname"></param>
        /// <param name="context">Stream context. Can be <c>null</c> to use default context.</param>
        /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns>
        public static bool rmdir(Context ctx, string dirname, StreamContext context = null)
        {
            StreamWrapper wrapper;

            return(PhpStream.ResolvePath(ctx, ref dirname, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty) &&
                   wrapper.RemoveDirectory(dirname, StreamRemoveDirectoryOptions.Empty, (context as StreamContext) ?? StreamContext.Default));
        }
Esempio n. 15
0
        public void RealAllText_should_allow_optional_content_type_and_uri_encoding()
        {
            var sc = StreamContext.FromSource(new Uri("data:,A%20brief%20note"));

            Assert.Equal("text/plain", sc.ContentType.ToString());
            Assert.Equal("A brief note", sc.ReadAllText());
        }
Esempio n. 16
0
        public void RealAllText_should_allow_non_standard_non_uri()
        {
            var sc = StreamContext.FromSource(new Uri("data:text/html,Encode s p aces"));

            Assert.Equal("Encode s p aces", sc.ReadAllText());
            Assert.Equal("data:text/html,Encode%20s%20p%20aces", sc.Uri.OriginalString);
        }
Esempio n. 17
0
 public VLCManagedEncoder(string sout, string[] arguments, StreamContext context, InputMethod inputMethod)
 {
     this.sout        = sout;
     this.arguments   = arguments;
     this.inputMethod = inputMethod;
     this.context     = context;
 }
        protected override void Read(ReadStream stream, StreamContext context)
        {
            while (stream.ReadNextPropertyID(out uint propertyID))
            {
                switch (propertyID)
                {
                case (uint)PropertyID.ClientID: {
                    int previousValue = _clientID;
                    _clientID = (int)stream.ReadVarint32();
                    bool clientIDExistsInChangeCache = _cache.ValueExistsInCache(entry => entry.clientIDSet);
                    if (!clientIDExistsInChangeCache && _clientID != previousValue)
                    {
                        FireClientIDDidChange(_clientID);
                    }
                    break;
                }

                case (uint)PropertyID.StreamID: {
                    int previousValue = _streamID;
                    _streamID = (int)stream.ReadVarint32();
                    bool streamIDExistsInChangeCache = _cache.ValueExistsInCache(entry => entry.streamIDSet);
                    if (!streamIDExistsInChangeCache && _streamID != previousValue)
                    {
                        FireStreamIDDidChange(_streamID);
                    }
                    break;
                }

                default: {
                    stream.SkipProperty();
                    break;
                }
                }
            }
        }
Esempio n. 19
0
 protected override Tuple <string, string> GetEncoderMuxerParameters(StreamContext context)
 {
     return(new Tuple <string, string>(
                context.Profile.CodecParameters["encoder"],
                context.Profile.CodecParameters["muxer"].Replace("#ADDRESS#", String.Format(address, ""))
                ));
 }
        public void Write(WriteStream stream, StreamContext context)
        {
            if (context.fullModel)
            {
                // Write all properties
                stream.WriteString((uint)PropertyID.Name, _name);
                stream.WriteVarint32((uint)PropertyID.Pointer, _pointer ? 1u : 0u);
            }
            else
            {
                // Reliable properties
                if (context.reliableChannel)
                {
                    LocalCacheEntry entry = _cache.localCache;
                    if (entry.nameSet || entry.pointerSet)
                    {
                        _cache.PushLocalCacheToInflight(context.updateID);
                    }

                    if (entry.nameSet)
                    {
                        stream.WriteString((uint)PropertyID.Name, entry.name);
                    }
                    if (entry.pointerSet)
                    {
                        stream.WriteVarint32((uint)PropertyID.Pointer, entry.pointer ? 1u : 0u);
                    }
                }
            }
        }
        public void FromStream_when_file_stream_should_have_Uri()
        {
            var    sc       = StreamContext.FromStream(new FileStream(".gitignore", FileMode.Append));
            string expected = "file://" + Path.GetFullPath(".gitignore");

            Assert.Equal(expected, sc.Uri.ToString());
        }
Esempio n. 22
0
        /// <include file='Doc/Wrappers.xml' path='docs/method[@name="Unlink"]/*'/>
        public override bool Unlink(string path, StreamUnlinkOptions options, StreamContext context)
        {
            Debug.Assert(path != null);
            Debug.Assert(Path.IsPathRooted(path));

            try
            {
                File.Delete(path);
                return(true);
            }
            catch (DirectoryNotFoundException)
            {
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_unlink_file_not_found",
                                                                             FileSystemUtils.StripPassword(path)));
            }
            catch (UnauthorizedAccessException)
            {
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied",
                                                                             FileSystemUtils.StripPassword(path)));
            }
            catch (IOException e)
            {
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_unlink_io_error",
                                                                             FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message)));
            }
            catch (Exception)
            {
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_unlink_error",
                                                                             FileSystemUtils.StripPassword(path)));
            }

            return(false);
        }
Esempio n. 23
0
        public static PhpString file_get_contents(Context ctx, QueryValue <LocalVariables> localsData, string path, FileOpenOptions flags = FileOpenOptions.Empty, PhpResource context = null, int offset = -1, int maxLength = -1)
        {
            var sc = StreamContext.GetValid(context, true);

            if (sc == null)
            {
                return(default(PhpString));
            }

            using (PhpStream stream = PhpStream.Open(ctx, path, "rb", ProcessOptions(ctx, flags), sc))
            {
                if (stream == null)
                {
                    return(default(PhpString));
                }

                // when HTTP protocol requested, store responded headers into local variable $http_response_header:
                if (string.Compare(stream.Wrapper.Scheme, HttpStreamWrapper.scheme, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var headers = stream.WrapperSpecificData as PhpArray;
                    localsData.Value.Locals.SetItemValue(new IntStringKey(HttpResponseHeaderName), (PhpValue)headers);
                }

                //
                //return Core.Convert.Quote(stream.ReadContents(maxLength, offset), ScriptContext.CurrentContext);
                return(stream.ReadContents(maxLength, offset).ToPhpString());
            }
        }
Esempio n. 24
0
        public void __construct(string file_name, string open_mode = "r", bool use_include_path = false, PhpResource context = null)
        {
            _root         = _ctx.RootPath;
            _originalPath = file_name;

            // fopen:
            var sc        = StreamContext.GetValid(context, allowNull: true) ?? StreamContext.Default;
            var openFlags = StreamOpenOptions.ReportErrors;

            if (use_include_path)
            {
                openFlags |= StreamOpenOptions.UseIncludePath;
            }

            _stream = PhpStream.Open(_ctx, file_name, open_mode, openFlags, sc);

            if (_stream != null)
            {
                _fullpath = _stream.OpenedPath;
            }
            else
            {
                throw new RuntimeException(string.Format(Resources.Resources.file_cannot_open, file_name));
            }
        }
Esempio n. 25
0
        public override PropertyTreeMetaObject BindStreamingSource(StreamContext input, IServiceProvider serviceProvider)
        {
            var ss   = StreamingSource.Create(this.ComponentType);
            var comp = ss.Load(input, this.ComponentType);

            return(PropertyTreeMetaObject.Create(comp));
        }
        public void Write(WriteStream stream, StreamContext context)
        {
            // Meta model
            stream.WriteModel(0, _metaModel, context);

            if (context.fullModel)
            {
                // Write all properties
                if (_sceneViewUUID != null && _sceneViewUUID.Length > 0)
                {
                    stream.WriteBytes((uint)PropertyID.SceneViewUUID, _sceneViewUUID);
                }
                if (_prefabName != null && _prefabName.Length > 0)
                {
                    stream.WriteString((uint)PropertyID.PrefabName, _prefabName);
                }
            }

            // Components
            if (_componentsModel != null)
            {
                stream.WriteModel((uint)PropertyID.Components, _componentsModel, context);
            }

            // Child Views
            if (_childViewsModel != null)
            {
                stream.WriteModel((uint)PropertyID.ChildViews, _childViewsModel, context);
            }
        }
 public void Write(WriteStream stream, StreamContext context)
 {
     foreach (Component component in _components)
     {
         stream.WriteModel((uint)component.componentID, component.model, context);
     }
 }
Esempio n. 28
0
        public void ReadAllText_should_get_read_stream_twice_from_text()
        {
            StreamContext sc = StreamContext.FromText("abc");

            Assert.Equal("abc", sc.ReadAllText());
            Assert.Equal("abc", sc.ReadAllText());
        }
Esempio n. 29
0
        public override void BuildPipeline(StreamContext context)
        {
            SetupAssemblyLoader();

            // input
            bool doInputReader = context.Source.NeedsInputReaderUnit;

            if (doInputReader)
            {
                context.Pipeline.AddDataUnit(context.Source.GetInputReaderUnit(), 1);
            }

            // get parameters
            VLCParameters vlcparam = GenerateVLCParameters(context);
            int           duration = (int)Math.Round((decimal)context.MediaInfo.Duration / 1000);

            // add the unit
            VLCManagedEncoder unit;

            if (doInputReader)
            {
                unit = new VLCManagedEncoder(vlcparam.Sout, vlcparam.Arguments, context, VLCManagedEncoder.InputMethod.NamedPipe);
            }
            else
            {
                unit = new VLCManagedEncoder(vlcparam.Sout, vlcparam.Arguments, context, VLCManagedEncoder.InputMethod.File, context.Source.GetPath());
            }
            context.Pipeline.AddDataUnit(unit, 5);
        }
Esempio n. 30
0
 protected virtual Tuple <string, string> GetEncoderMuxerParameters(StreamContext context)
 {
     return(new Tuple <string, string>(
                context.Profile.CodecParameters["encoder"],
                context.Profile.CodecParameters["muxer"]
                ));
 }
        public int WriteLength(StreamContext context)
        {
            int length = 0;

            if (context.fullModel)
            {
                // Mark unreliable properties as clean and flatten the in-flight cache.
                // TODO: Move this out of WriteLength() once we have a prepareToWrite method.
                _name    = name;
                _pointer = pointer;
                _cache.Clear();

                // Write all properties
                length += WriteStream.WriteStringLength((uint)PropertyID.Name, _name);
                length += WriteStream.WriteVarint32Length((uint)PropertyID.Pointer, _pointer ? 1u : 0u);
            }
            else
            {
                // Reliable properties
                if (context.reliableChannel)
                {
                    LocalCacheEntry entry = _cache.localCache;
                    if (entry.nameSet)
                    {
                        length += WriteStream.WriteStringLength((uint)PropertyID.Name, entry.name);
                    }
                    if (entry.pointerSet)
                    {
                        length += WriteStream.WriteVarint32Length((uint)PropertyID.Pointer, entry.pointer ? 1u : 0u);
                    }
                }
            }

            return(length);
        }
        public override object Load(StreamContext inputSource,
                                    Type instanceType)
        {
            if (instanceType == null)
                throw new ArgumentNullException("instanceType"); // $NON-NLS-1

            return Activation.FromStreamContext(instanceType, inputSource);
        }
        public virtual void Load(StreamContext inputSource, object instance)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource");
            if (instance == null)
                throw new ArgumentNullException("instance");

            LoadByHydration(inputSource, instance);
        }
        public static PropertyTree FromStreamContext(StreamContext streamContext, Encoding encoding)
        {
            if (streamContext == null)
                throw new ArgumentNullException("streamContext"); // $NON-NLS-1

            using (PropertyTreeReader reader = PropertyTreeReader.CreateXml(streamContext, encoding, null)) {
                return reader.ReadPropertyTree();
            }
        }
        public override void Load(StreamContext inputSource, object instance)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource");
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (!(instance is IProperties))
                throw Failure.NotInstanceOf("instance", instance, typeof(IProperties));

            var props = (Properties) Load(inputSource, typeof(Properties));
            props.CopyTo((IProperties) instance);
        }
        public override void Save(StreamContext outputTarget,
                                  object value)
        {
            if (outputTarget == null)
                throw new ArgumentNullException("outputTarget"); // $NON-NLS-1

            using (Stream s = outputTarget.OpenWrite()) {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(s, value);
                s.Flush();
            }
        }
        public static PropertyTreeXmlReader CreateXml(StreamContext streamContext,
                                                      Encoding encoding = null,
                                                      PropertyTreeXmlReaderSettings settings = null)
        {
            if (streamContext == null)
                throw new ArgumentNullException("streamContext"); // $NON-NLS-1

            XmlReaderSettings xsettings = new XmlReaderSettings {};
            // TODO Use the encoding
            XmlReader xr = XmlReader.Create(streamContext.OpenRead(), xsettings);
            return new PropertyTreeXmlReader(xr);
        }
        public override void Save(StreamContext outputTarget,
		                          object value)
        {
            if (outputTarget == null)
                throw new ArgumentNullException("outputTarget"); // $NON-NLS-1

            using (Stream s = outputTarget.OpenWrite()) {
                using (Stream bs = new CryptoStream(s, new ToBase64Transform(), CryptoStreamMode.Write)) {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(bs, value);
                    s.Flush();
                }
            }
        }
        public override bool IsValidInput(StreamContext inputSource)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource"); // $NON-NLS-1

            using (Stream s = inputSource.OpenRead()) {
                byte[] b = new byte[BINARY_MAGIC.Length];
                s.Read(b, 0, BINARY_MAGIC.Length);
                if (b.SequenceEqual(BINARY_MAGIC))
                    return true;
                else
                    return false;
            }
        }
        public override object Load(StreamContext inputSource,
                                    Type instanceType)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource"); // $NON-NLS-1
            instanceType = instanceType ?? typeof(object);

            using (Stream s = inputSource.OpenRead()) {
                BinaryFormatter bf = new BinaryFormatter();
                object result = bf.Deserialize(s);
                if (!instanceType.IsInstanceOfType(result))
                    throw Failure.NotInstanceOf("instanceType", instanceType, result.GetType());

                return result;
            }
        }
        public static PropertyTreeReader Create(StreamContext streamContext,
                                                Encoding encoding = null,
                                                PropertyTreeReaderSettings settings = null)
        {
            if (streamContext == null)
                throw new ArgumentNullException("streamContext"); // $NON-NLS-1

            string lp = string.Empty;
            if (streamContext.Uri.IsAbsoluteUri) {
                lp = streamContext.Uri.LocalPath;
            }

            var result = GetFactoryFunc(lp)(streamContext,
                                            encoding,
                                            settings);
            return result;
        }
        public override object Load(StreamContext inputSource,
		                            Type instanceType)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource"); // $NON-NLS-1
            instanceType = instanceType ?? typeof(object);

            using (Stream s = inputSource.OpenRead()) {
                using (Stream bs = new CryptoStream(s, new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces), CryptoStreamMode.Read)) {
                    BinaryFormatter bf = new BinaryFormatter();
                    object result = bf.Deserialize(bs);
                    if (!instanceType.IsInstanceOfType(result))
                        throw Failure.NotInstanceOf("result", result, instanceType);

                    return result;
                }
            }
        }
        public override void Save(StreamContext outputTarget,
                                  object value)
        {
            if (value == null)
                throw new ArgumentNullException("value"); // $NON-NLS-1

            string contentType = outputTarget.ContentType.ToString();
            TypeConverter tc = TypeDescriptor.GetConverter(value);

            string text;
            if (tc.CanConvertTo(typeof(string))) {
                text = tc.ConvertToString(null,
                                          outputTarget.Culture ?? CultureInfo.InvariantCulture,
                                          value);
            } else {
                text = value.ToString();
            }

            TextWriter writer = outputTarget.AppendText();
            writer.Write(text);
        }
        public override bool IsValidInput(StreamContext inputSource)
        {
            if (inputSource == null)
                throw new ArgumentNullException("inputSource"); // $NON-NLS-1

            using (TextReader tr = inputSource.OpenText()) {
                int i;
                int count = 0;
                while (count++ < OPTIMISTIC_STOP && (i = tr.Read()) >= 0) {
                    if (i >= 'A' && i <= 'F')
                        continue;
                    else if (i >= 'a' && i <= 'f')
                        continue;
                    else if (i >= '0' && i <= '9')
                        continue;
                    else if (char.IsWhiteSpace((char) i))
                        continue;
                    else
                        return false;
                }
            }

            return true;
        }
 internal void LoadByHydration(StreamContext inputSource, object instance)
 {
     var copyFrom = Load(inputSource, instance.GetType());
     Template.Copy(copyFrom, instance);
 }
        public void Load(StreamContext streamContext, Encoding encoding)
        {
            if (streamContext == null)
                throw new ArgumentNullException("streamContext");  // $NON-NLS-1

            using (PropertiesReader pr = new PropertiesReader(streamContext, encoding)) {
                LoadCore(pr);
            }
        }
Esempio n. 47
0
        public NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, DokanFileInfo info)
        {
            var context = info.Context as StreamContext;
            if (context == null) {
                var item = GetItem(fileName) as CloudFileNode;
                if (item == null) {
                    bytesRead = 0;
                    return Trace(nameof(ReadFile), fileName, info, DokanResult.FileNotFound);
                }

                info.Context = context = new StreamContext(item, FileAccess.ReadData) { Stream = Stream.Synchronized(item.GetContent(drive)) };
            }

            context.Stream.Position = offset;
            bytesRead = context.Stream.Read(buffer, 0, buffer.Length);

            return Trace(nameof(ReadFile), fileName, info, DokanResult.Success, $"out {bytesRead}", offset.ToString(CultureInfo.InvariantCulture));
        }
 public virtual InterfaceUsageInfo GetInterfaceUsage(StreamContext inputSource)
 {
     return null;
 }
 public PropertiesReader(TextReader source)
 {
     this.streamContext = StreamContext.Null;
     this.BaseReader = source;
 }
        public override PropertyTreeMetaObject BindStreamingSource(StreamContext input, IServiceProvider serviceProvider)
        {
            var ss = StreamingSource.Create(this.ComponentType) ?? new PropertyTreeSource();

            if (ss == null) {
                var errors = serviceProvider.TryGetService(PropertyTreeBinderErrors.Default);
                errors.CouldNotBindStreamingSource(this.ComponentType, PropertyTreeBinderImpl.FindFileLocation(serviceProvider));
                return this;
            }

            // Hydrate the existing instance
            ss.Load(input, this.Component);
            return this;
        }
 public virtual PropertyTreeMetaObject BindStreamingSource(StreamContext input, IServiceProvider serviceProvider)
 {
     return this;
 }
        public static PropertyTreeSchema FromStreamContext(StreamContext source)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            throw new NotImplementedException();
        }
 public override PropertyTreeMetaObject BindStreamingSource(StreamContext input, IServiceProvider serviceProvider)
 {
     var ss = StreamingSource.Create(this.ComponentType);
     var comp = ss.Load(input, this.ComponentType);
     return PropertyTreeMetaObject.Create(comp);
 }
Esempio n. 54
0
        private static void TestEncoderHelper(object value, IEncoder encoder, IDecoder decoder, StreamContext stream, IoType type, Action afterEncode = null)
        {
            var inMethod = typeof(IEncoder).GetMethods()
                .First(m => m.Name.StartsWith("Write") && m.GetParameters()[0].ParameterType == value.GetType());
            var outMethod = typeof(IDecoder).GetMethods()
                .First(m => m.Name.StartsWith("Read") && m.ReturnType == value.GetType());

            // write it in
            inMethod.Invoke(encoder, new[] { value, type });
            if (afterEncode != null)
            {
                afterEncode();
            }

            // reset the stream for reading
            stream.writer.Flush();
            stream.stream.Flush();
            stream.stream.Seek(0, SeekOrigin.Begin);

            // read it out
            var outValue = outMethod.Invoke(decoder, new object[] { type });

            outValue.ShouldEqual(value);
        }
 public abstract void Save(StreamContext outputTarget, object value);
 public abstract object Load(StreamContext inputSource, Type instanceType);
 public virtual bool IsValidInput(StreamContext inputSource)
 {
     return true;
 }
        public static Properties FromStreamContext(StreamContext source, Encoding encoding = null)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            Properties p = new Properties();
            p.Load(source.OpenRead(), encoding ?? source.Encoding);
            return p;
        }
 public PropertiesReader(StreamContext source, Encoding encoding = null)
 {
     this.streamContext = source;
     this.BaseReader = source.OpenText(encoding);
 }