public Codec(ICodecFactory cf, Analyzer a) { decoder = cf.GetDecoder (); encoder = cf.GetEncoder (); analyzer = a; analyzer.BindListDelegate (this.GetDataFromAnalyzer); }
public void TestSetup() { const int Seed = 13; this.Stream = new MemoryStream(); this.Encoder = this.CreateEncoder(this.Stream); this.Decoder = this.CreateDecoder(this.Stream); this.random = new Random(Seed); }
public void encode(IEncoder enc) { enc.WriteStr8(PackageName) ; enc.WriteStr8(ClassName) ; enc.WriteUint32(Hash[0]) ; enc.WriteUint32(Hash[1]) ; enc.WriteUint32(Hash[2]) ; enc.WriteUint32(Hash[3]) ; }
private static void TestEncoder(UInt32 imageDimension, IEncoder enc) { var i = new Bitmap((int)imageDimension, (int)imageDimension, PixelFormat.Format24bppRgb); var g = Graphics.FromImage(i); g.FillRectangle(new SolidBrush(Color.Transparent), 0, 0, i.Width, i.Height); g.DrawEllipse(new Pen(Color.IndianRed), 1, 1, i.Width / 2, i.Height / 2); g.DrawRectangle(new Pen(Color.GreenYellow, 4), i.Width / 2, i.Width / 2, i.Width / 2 - 4, i.Width / 2 - 4); var ihdr = new Ihdr(imageDimension, imageDimension, BitDepth._8, ColorType.Rgb); var apng = new APNG(ihdr); apng.RegisterDecoder(new SimpleDecoder()); apng.Encoder = enc; apng.AddDefaultImageFromObject(i); var frames = new Frame[i.Height / 2]; for(int j = 0; j < i.Height / 2; j++) { var bmp = new Bitmap((int)imageDimension, (int)imageDimension, PixelFormat.Format24bppRgb); var gr = Graphics.FromImage(bmp); gr.Clear(Color.Blue); gr.DrawEllipse(new Pen(Color.Lime), bmp.Width / 4, j, bmp.Width / 2, bmp.Height / 2); frames[j] = new Frame() { Delay = new Rational(10, 100), FrameObject = bmp }; } apng.SetFrames(frames); String fileName = String.Format("{0}_{1}x{2}_{3}.png", enc.GetType().Name, imageDimension, imageDimension, 0); if(File.Exists(fileName)) File.Delete(fileName); apng.ToFile(fileName); ihdr = new Ihdr(imageDimension, imageDimension, BitDepth._8, ColorType.Rgb); apng = new APNG(ihdr); apng.RegisterDecoder(new SimpleDecoder()); apng.Encoder = enc; String nowString = DateTime.UtcNow.ToString(@"yyyy\-MM\-dd HH:mm"); g.Clear(Color.Blue); g.DrawString(nowString, new Font("Consolas", 7), new SolidBrush(Color.Lime), 5, i.Height / 2f); apng.AddDefaultImageFromObject(i); frames = new Frame[i.Height / 2-10]; for(int j = 10; j < i.Height / 2; j++) { var bmp = new Bitmap((int)imageDimension, (int)imageDimension, PixelFormat.Format24bppRgb); var gr = Graphics.FromImage(bmp); gr.Clear(Color.Blue); gr.DrawString(nowString, new Font("Consolas", 7), new SolidBrush(Color.Lime), 5, j); frames[j-10] = new Frame() { Delay = new Rational(10, 100), FrameObject = bmp }; } apng.SetFrames(frames); fileName = String.Format("{0}_{1}x{2}_{3}.png", enc.GetType().Name, imageDimension, imageDimension, 1); if(File.Exists(fileName)) File.Delete(fileName); apng.ToFile(fileName); }
public void TestInitialize() { _mockPort = Substitute.For<ISerialPort>(); _mockEncoder = Substitute.For<IEncoder>(); _arduino = new ArduinoController(_mockPort, _mockEncoder) { RodType = eRod.GoalKeeper }; _arduino.MaxTicks = MAX_TICKS; }
/// <summary> /// Load codecs from assembly /// </summary> /// <param name="encoder"></param> /// <param name="assembly"></param> /// <param name="typeMatch"></param> private static void LoadCodecs(IEncoder encoder, Assembly assembly, Regex typeMatch) { Debug.Assert(encoder != null); Debug.Assert(assembly != null); Debug.Assert(typeMatch != null); foreach (Type type in assembly.GetTypes()) { if (typeMatch.IsMatch(type.FullName)) { LoadCodec(encoder, type); } } }
public virtual void WriteAsset(Bundle bundle, IEncoder encoder) { response.ContentType = bundle.ContentType; CacheLongTime(bundle.Hash.ToHexString(), bundle.BrowserTtl); using (var stream = bundle.Content) { stream.CopyTo(response.OutputStream); } encoder.Encode(response); }
/// <summary> /// 使用默认配置参数的构造函数 /// </summary> /// <param name="handler"></param> public SocketServer(IServerHandler handler,IEncoder encoder, IDecoder decoder) : base(DefaultConfigure.SocketBufferSize, DefaultConfigure.MessageBufferSize) { if (handler == null) throw new ArgumentNullException("handler"); if (encoder == null) throw new ArgumentNullException("encoder"); if (decoder == null) throw new ArgumentNullException("decoder"); this._handler = handler; this._protocol = new DefaultBinaryProtocol(); this._encoder = encoder; this._decoder = decoder; this._maxMessageSize = DefaultConfigure.MaxMessageSize; this._maxConnections = DefaultConfigure.MaxConnections; }
public HttpRequest(IEncoder encoder) { RawHeaders = new Dictionary<string, object>(); ClientCertificates = new X509CertificateCollection(); UserAgent = String.Format("EasyHttp HttpClient v{0}", Assembly.GetAssembly(typeof (HttpClient)).GetName().Version); Accept = String.Join(";", HttpContentTypes.TextHtml, HttpContentTypes.ApplicationXml, HttpContentTypes.ApplicationJson); _encoder = encoder; Timeout = 100000; //http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.aspx }
/// <summary> /// Load codec instance /// </summary> /// <param name="encoder">Encoder instance</param> /// <param name="codec">Codec type</param> /// <returns></returns> private static bool LoadCodec(IEncoder encoder,Type codec) { Debug.Assert(encoder != null); Debug.Assert(codec != null); bool loaded = false; object[] attrs = codec.GetCustomAttributes(typeof(CodecAttribute), false); if (attrs != null && attrs.Length > 0) { CodecAttribute codecAttr = (CodecAttribute)attrs[0]; if (codecAttr.AutoLoad) { encoder.AddCodec(codecAttr.Name, ObjectBuilder.Build<ICodec>(codec)); loaded = true; } } return loaded; }
/// <summary> /// Initializes a new instance of the <see cref="Computer"/> class. /// </summary> /// <param name="stack">The stack.</param> /// <param name="encoder">The instruction encoder.</param> /// <param name="decoder">The instruction decoder.</param> public ExecutionUnit(IStack stack, IEncoder encoder, IDecoder decoder, IArithmeticLogicUnit alu) { _context = new ExecutionContext { Stack = stack, Encoder = encoder, Decoder = decoder, Alu = alu, Executing = true }; _dispatcher = new Dictionary<InstructionType, Action<ExecutionContext, Instruction>> { { InstructionType.Mult, Multiply.GetAction() }, { InstructionType.Call, Call.GetAction() }, { InstructionType.Ret, Return.GetAction() }, { InstructionType.Stop, Stop.GetAction() }, { InstructionType.Print, Print.GetAction() }, { InstructionType.Push, Push.GetAction() } }; }
public override void Encode(IEncoder encoder) { encoder.F32copysign(); }
private void WriteAnimatedGif(Bitmap src, Stream output, IEncoder ios, ResizeSettings queryString) { //http://www.fileformat.info/format/gif/egff.htm //http://www.fileformat.info/format/gif/spec/44ed77668592476fb7a682c714a68bac/view.htm //Heavily modified and patched from comments on http://bloggingabout.net/blogs/rick/archive/2005/05/10/3830.aspx MemoryStream memoryStream = null; BinaryWriter writer = null; //Variable declaration try { writer = new BinaryWriter(output); memoryStream = new MemoryStream(4096); //Write the GIF 89a sig writer.Write(new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a' }); //We parse this from the source image int loops = GetLoops(src.PropertyItems); int[] delays = GetDelays(src.PropertyItems);//20736 (delays) 20737 (loop); int frames = src.GetFrameCount(FrameDimension.Time); for (int frame = 0; frame < frames; frame++) { //Select the frame src.SelectActiveFrame(FrameDimension.Time, frame); // http://radio.weblogs.com/0122832/2005/10/20.html //src.MakeTransparent(); This call makes some GIFs replicate the first image on all frames.. i.e. SelectActiveFrame doesn't work. using (Bitmap b = c.CurrentImageBuilder.Build(src,queryString,false)){ //Useful to check if animation is occuring - sometimes the problem isn't the output file, but the input frames are //all the same. //for (var i = 0; i < b.Height; i++) b.SetPixel(frame * 10, i, Color.Green); // b.Save(memoryStream, ImageFormat.Gif); ios.Write(b, memoryStream); //Allows quantization and dithering } GifClass gif = new GifClass(); gif.LoadGifPicture(memoryStream); if (frame == 0) { //Only one screen descriptor per file. Steal from the first image writer.Write(gif.m_ScreenDescriptor.ToArray()); //How many times to loop the image (unless it is 1) IE and FF3 loop endlessley if loop=1 if (loops != 1) writer.Write(GifCreator.CreateLoopBlock(loops)); } //Restore frame delay int delay = 0; if (delays != null && delays.Length > frame) delay = delays[frame]; writer.Write(GifCreator.CreateGraphicControlExtensionBlock(delay)); //The delay/transparent color block writer.Write(gif.m_ImageDescriptor.ToArray()); //The image desc writer.Write(gif.m_ColorTable.ToArray()); //The palette writer.Write(gif.m_ImageData.ToArray()); //Image data memoryStream.SetLength(0); //Clear the mem stream, but leave it allocated for now memoryStream.Seek(0, SeekOrigin.Begin); //Reset memory buffer } writer.Write((byte)0x3B); //End file } finally { if (memoryStream != null) memoryStream.Dispose(); //if (writer != null) writer.Close } }
public virtual void Encode(IEncoder encoder) { encoder.PushNamespace("http://opcfoundation.org/UA/2008/02/Types.xsd"); encoder.WriteEncodable<ResponseHeader>("ResponseHeader", ResponseHeader); encoder.WriteEncodableArray<EndpointDescription>("Endpoints", Endpoints); encoder.PopNamespace(); }
public void EncodeValue(IEncoder enc, short type, object val) { try { switch ((int)type) { case 1: enc.WriteUint8((short) val) ; break; // U8 case 2: enc.WriteUint16((int) val) ; break; // U16 case 3: enc.WriteUint32((long) val) ; break; // U32 case 4: enc.WriteUint64((long) val) ; break; // U64 case 6: enc.WriteStr8((string) val) ; break; // SSTR case 7: enc.WriteStr16((string) val) ; break; // LSTR case 8: enc.WriteDatetime((long) val); break; // ABSTIME case 9: enc.WriteUint32((long) val); break; // DELTATIME case 10: ((ObjectID)val).encode(enc) ; break; // ref case 11: if ((bool) val) { enc.WriteUint8(1) ; } else { enc.WriteUint8(0) ; } break ; case 12: enc.WriteFloat((float) val); break; // FLOAT case 13: enc.WriteDouble((double) val); break; // DOUBLE case 14: enc.WriteUuid((UUID) val) ; break ; // UUID case 15: enc.WriteMap((Dictionary<string, object>) val) ; break ; // Ftable case 16: enc.WriteInt8((short) val) ; break; // int8 case 17: enc.WriteInt16((int) val) ; break; // int16 case 18: enc.WriteInt32(long.Parse(""+ val)) ; break; // int32 case 19: enc.WriteInt64(long.Parse("" + val)) ; break; // int64 case 20: // Object // Check that the object has a session, if not // take ownership of it QMFObject qObj = (QMFObject) val ; if (qObj.Session == null) { qObj.Session = this ; } qObj.Encode(enc) ; break; case 21: // List List<object> items = (List<object>) val ; MSEncoder lEnc = new MSEncoder(1) ; lEnc.Init() ; lEnc.WriteUint32(items.Count) ; foreach (object obj in items) { short innerType = Util.QMFType(obj) ; lEnc.WriteUint8(innerType) ; this.EncodeValue(lEnc,innerType,obj) ; } enc.WriteVbin32(lEnc.Segment().ToArray()) ; break ; case 22: // Array List<object> aItems = (List<object>) val ; MSEncoder aEnc = new MSEncoder(1) ; aEnc.Init() ; long aCount = aItems.Count ; aEnc.WriteUint32(aCount) ; if (aCount > 0) { Object anObj = aItems[0] ; short innerType = Util.QMFType(anObj) ; aEnc.WriteUint8(innerType) ; foreach (object obj in aItems) { this.EncodeValue(aEnc,innerType,obj) ; } } enc.WriteVbin32(aEnc.Segment().ToArray()) ; break ; default: throw new Exception(String.Format("Invalid Type Code: {0}", type)) ; } } catch (System.InvalidCastException e) { string msg = String.Format("Class cast exception for typecode {0}, type {1} ", type, val.GetType()) ; log.Error(msg) ; throw new Exception(msg + type, e) ; } }
protected internal virtual void printEncoded(System.String details, IEncoder encoder, System.Object obj) { System.IO.MemoryStream outputStream = new System.IO.MemoryStream(); encoder.encode(obj, outputStream); System.Console.Out.WriteLine("Encoded by " + encoder.ToString() + " (" + details + ") : " + ByteTools.byteArrayToHexString(outputStream.ToArray())); }
public override void Write(IEncoder enc) { enc.WriteUint16(packing_flags); }
public static HmacResult ToHmac(this string data, IEncoder encoder, uint keySize = HmacKeySize, HashAlgorithm algorithm = HashAlgorithm.Sha512) { return(ToHmac(data.ToByteArray(), RandomManager.Next((int)keySize), encoder, algorithm)); }
/// <inheritdoc/> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Namespaces.OpcUa); encoder.PushNamespace(Namespaces.OpcUaXsd); encoder.WriteString(kTypeFieldName, Node.GetType().Name); encoder.WriteNodeId(nameof(Node.NodeId), Node.NodeId); encoder.WriteString(nameof(Node.SymbolicName), Node.SymbolicName); encoder.WriteQualifiedName(nameof(Node.BrowseName), Node.BrowseName); encoder.WriteLocalizedText(nameof(Node.DisplayName), Node.DisplayName); encoder.WriteLocalizedText(nameof(Node.Description), Node.Description); encoder.WriteEnumerated(nameof(Node.WriteMask), Node.WriteMask); encoder.WriteEnumerated(nameof(Node.UserWriteMask), Node.UserWriteMask); switch (Node) { case InstanceNodeModel instanceState: encoder.WriteNodeId(nameof(instanceState.ReferenceTypeId), instanceState.ReferenceTypeId); encoder.WriteNodeId(nameof(instanceState.TypeDefinitionId), instanceState.TypeDefinitionId); encoder.WriteNodeId(nameof(instanceState.ModellingRuleId), instanceState.ModellingRuleId); encoder.WriteUInt32(nameof(instanceState.NumericId), instanceState.NumericId); switch (instanceState) { case ObjectNodeModel objectState: encoder.WriteByte(nameof(objectState.EventNotifier), objectState.EventNotifier ?? EventNotifiers.None); break; case VariableNodeModel variableState: encoder.WriteVariant(nameof(variableState.Value), variableState.Value ?? Variant.Null); encoder.WriteStatusCode(nameof(variableState.StatusCode), variableState.StatusCode ?? StatusCodes.Good); encoder.WriteNodeId(nameof(variableState.DataType), variableState.DataType); encoder.WriteInt32(nameof(variableState.ValueRank), variableState.ValueRank ?? -1); encoder.WriteUInt32Array(nameof(variableState.ArrayDimensions), variableState.ArrayDimensions); encoder.WriteByte(nameof(variableState.AccessLevel), variableState.AccessLevel ?? 0); encoder.WriteUInt32(nameof(variableState.AccessLevelEx), variableState.AccessLevelEx ?? 0); encoder.WriteByte(nameof(variableState.UserAccessLevel), variableState.UserAccessLevel ?? 0); encoder.WriteDouble(nameof(variableState.MinimumSamplingInterval), variableState.MinimumSamplingInterval ?? 0.0); encoder.WriteBoolean(nameof(variableState.Historizing), variableState.Historizing ?? false); break; case MethodNodeModel methodState: encoder.WriteBoolean(nameof(methodState.Executable), methodState.Executable); encoder.WriteBoolean(nameof(methodState.UserExecutable), methodState.UserExecutable); break; } break; case TypeNodeModel typeState: encoder.WriteBoolean(nameof(typeState.IsAbstract), typeState.IsAbstract ?? false); encoder.WriteNodeId(nameof(typeState.SuperTypeId), typeState.SuperTypeId); switch (Node) { case VariableTypeNodeModel variableTypeState: encoder.WriteVariant(nameof(variableTypeState.Value), variableTypeState.Value ?? Variant.Null); encoder.WriteNodeId(nameof(variableTypeState.DataType), variableTypeState.DataType); encoder.WriteInt32(nameof(variableTypeState.ValueRank), variableTypeState.ValueRank ?? -1); encoder.WriteUInt32Array(nameof(variableTypeState.ArrayDimensions), variableTypeState.ArrayDimensions); break; case ReferenceTypeNodeModel refTypeState: encoder.WriteBoolean(nameof(refTypeState.Symmetric), refTypeState.Symmetric ?? false); encoder.WriteLocalizedText(nameof(refTypeState.InverseName), refTypeState.InverseName); break; case DataTypeNodeModel dataTypeState: encoder.WriteString(kDefinitionTypeFieldName, dataTypeState.Definition?.GetType().Name); encoder.WriteEncodeable(nameof(dataTypeState.Definition), dataTypeState.Definition); encoder.WriteEnumerated(nameof(dataTypeState.Purpose), dataTypeState.Purpose); break; case ObjectTypeNodeModel objectTypeState: break; } break; case ViewNodeModel viewState: encoder.WriteByte(nameof(viewState.EventNotifier), viewState.EventNotifier ?? EventNotifiers.None); encoder.WriteBoolean(nameof(viewState.ContainsNoLoops), viewState.ContainsNoLoops ?? false); break; } var ctx = encoder.Context.ToSystemContext(); var children = Node.GetChildren(ctx); encoder.WriteEncodeableArray(kChildrenFieldName, children.Select(i => new EncodeableNodeModel(i))); var references = Node.GetBrowseReferences(ctx); encoder.WriteEncodeableArray(kReferencesFieldName, references.Select(r => new EncodeableReferenceModel(r))); encoder.PopNamespace(); encoder.PopNamespace(); }
/// <summary cref="IEncodeable.Encode" /> public virtual void Encode(IEncoder encoder) {}
public Translator(IMapper mapper, ISerializer serializer, IEncoder encoder) { _mapper = mapper; _serializer = serializer; _encoder = encoder; }
public virtual void Encode(IEncoder encoder) { encoder.PushNamespace("http://opcfoundation.org/UA/2008/02/Types.xsd"); encoder.WriteEncodable<RequestHeader>("RequestHeader", RequestHeader); encoder.WriteEncodable<RegisteredServer>("Server", Server); encoder.PopNamespace(); }
public virtual void Encode(IEncoder encoder) { encoder.PushNamespace("http://opcfoundation.org/UA/2008/02/Types.xsd"); encoder.WriteString("ServerUri", ServerUri); encoder.WriteString("ProductUri", ProductUri); encoder.WriteLocalizedTextArray("ServerNames", ServerNames); encoder.WriteEnumeration<ApplicationType>("ServerType", ServerType); encoder.WriteString("GatewayServerUri", GatewayServerUri); encoder.WriteStringArray("DiscoveryUrls", DiscoveryUrls); encoder.WriteString("SemaphoreFilePath", SemaphoreFilePath); encoder.WriteBoolean("IsOnline", IsOnline); encoder.PopNamespace(); }
public EncodableWrapper(IEncoder encoder, IEncodeable wrapped) { _encoder = encoder; _wrapped = wrapped; }
/// <inheritdoc /> public void Encode(IEncoder encoder) => _wrapped.Encode(_encoder);
public static HmacResult ToHmac(string data, string key, IEncoder encoder, HashAlgorithm algorithm = HashAlgorithm.Sha512) { return(ToHmac(data.ToByteArray(), encoder.Decode(key), encoder, algorithm)); }
public void GivenAnEncoder() { Encoder = new CustomEncoder(); }
public static ScryptResult ToScrypt(this string data, string salt, IEncoder encoder, uint iterations = ScryptIterations, uint blockSize = ScryptBlockSize, uint parallelism = ScryptParallelism, uint derivedKeyLength = ScryptDerivedKeyLength) { return(ToScrypt(data.ToByteArray(), encoder.Decode(salt), encoder, iterations, blockSize, parallelism, derivedKeyLength)); }
public HttpClient(IContainerConfiguration containerConfiguration) { var registry = containerConfiguration.InitializeContainer(); ObjectFactory.Initialize(x => x.AddRegistry(registry)); _encoder = ObjectFactory.GetInstance<IEncoder>(); _decoderFactory = ObjectFactory.GetInstance<IDecoderFactory>(); Request = new HttpRequest(_encoder); }
public static ScryptResult ToScrypt(this string data, IEncoder encoder, uint saltSize = ScryptSaltSize, uint iterations = ScryptIterations, uint blockSize = ScryptBlockSize, uint parallelism = ScryptParallelism, uint derivedKeyLength = ScryptDerivedKeyLength) { byte[] salt = RandomManager.Next((int)saltSize); return(ToScrypt(data.ToByteArray(), salt, encoder, iterations, blockSize, parallelism, derivedKeyLength)); }
/// <summary> /// Encode this histogram into a <see cref="ByteBuffer"/> /// </summary> /// <param name="targetBuffer">The buffer to encode into</param> /// <param name="encoder">The encoder to use</param> /// <returns>The number of bytes written to the buffer</returns> public int Encode(ByteBuffer targetBuffer, IEncoder encoder) { var data = GetData(); return encoder.Encode(data, targetBuffer); }
public static Argon2Result ToArgon2(this string data, string salt, IEncoder encoder, uint iterations, uint memorySizeKiB, uint parallelism, Argon2Variant variant = Argon2Variant.Argon2id, uint derivedKeyLength = Argon2DerivedKeyLength) { return(ToArgon2(data.ToByteArray(), salt.ToByteArray(), encoder, iterations, memorySizeKiB, parallelism, variant, derivedKeyLength)); }
public HttpClient(IEncoderDecoderConfiguration encoderDecoderConfiguration) { _encoder = encoderDecoderConfiguration.GetEncoder(); _decoder = encoderDecoderConfiguration.GetDecoder(); _decoder.ShouldRemoveAtSign = ShouldRemoveAtSign; _uriComposer = new UriComposer(); Request = new HttpRequest(_encoder); }
public static Argon2Result ToArgon2(this string data, IEncoder encoder, uint iterations, uint memorySizeKiB, uint parallelism, uint saltSize = Argon2SaltSize, Argon2Variant variant = Argon2Variant.Argon2id, uint derivedKeyLength = Argon2DerivedKeyLength) { byte[] salt = RandomManager.Next((int)saltSize); return(ToArgon2(data.ToByteArray(), salt, encoder, iterations, memorySizeKiB, parallelism, variant, derivedKeyLength)); }
public Highlighter(IFormatter formatter, IEncoder encoder, IScorer fragmentScorer) { _formatter = formatter; _encoder = encoder; _fragmentScorer = fragmentScorer; }
public static string ToHash(this string data, IEncoder encoder, HashAlgorithm algorithm = HashAlgorithm.Sha512) { return(encoder.Encode(ToHash(data.ToByteArray(), algorithm))); }
public override void Encode(IEncoder encoder) { encoder.F32demote_f64(); }
/// <summary>Create a new LocalVoiceAudio<T> instance.</summary> /// <param name="voiceClient">The VoiceClient to use for this outgoing stream.</param> /// <param name="voiceId">Numeric ID for this voice.</param> /// <param name="encoder">Encoder to use for this voice.</param> /// <param name="channelId">Voice transport channel ID to use for this voice.</param> /// <returns>The new LocalVoiceAudio<T> instance.</returns> public static LocalVoiceAudio <T> Create(VoiceClient voiceClient, byte voiceId, IEncoder encoder, VoiceInfo voiceInfo, int channelId) { if (typeof(T) == typeof(float)) { if (encoder == null || encoder is IEncoderDataFlow <float> ) { return(new LocalVoiceAudioFloat(voiceClient, encoder as IEncoderDataFlow <float>, voiceId, voiceInfo, channelId) as LocalVoiceAudio <T>); } else { throw new Exception("[PV] CreateLocalVoice: encoder for LocalVoiceAudio<float> is not IEncoderDataFlow<float>: " + encoder.GetType()); } } else if (typeof(T) == typeof(short)) { if (encoder == null || encoder is IEncoderDataFlow <short> ) { return(new LocalVoiceAudioShort(voiceClient, encoder as IEncoderDataFlow <short>, voiceId, voiceInfo, channelId) as LocalVoiceAudio <T>); } else { throw new Exception("[PV] CreateLocalVoice: encoder for LocalVoiceAudio<short> is not IEncoderDataFlow<short>: " + encoder.GetType()); } } else { throw new UnsupportedSampleTypeException(typeof(T)); } }
private IDictionary <String, Object> GetParams(MethodInfo method, IDictionary <String, Object> args, IEncoder encoder) { // 该方法没有参数,无视外部传入参数 var pis = method.GetParameters(); if (pis == null || pis.Length < 1) { return(null); } var ps = new Dictionary <String, Object>(); foreach (var pi in pis) { var name = pi.Name; Object v = null; if (args != null && args.ContainsKey(name)) { v = args[name]; } if (Type.GetTypeCode(pi.ParameterType) == TypeCode.Object && v is IDictionary <String, Object> ) { ps[name] = encoder.Convert(v, pi.ParameterType); } else { ps[name] = v.ChangeType(pi.ParameterType); } } return(ps); }
/// <inheritdoc/> public virtual void Encode(IEncoder encoder) { }
/// <summary> /// Create wrapper /// </summary> /// <param name="wrapped"></param> /// <param name="callback"></param> public ModelEncoder(IEncoder wrapped, Action <ExpandedNodeId> callback = null) { _wrapped = wrapped ?? throw new ArgumentNullException(nameof(wrapped)); _callback = callback; }
public override void Encode(IEncoder encoder) { encoder.I64Load32s(Alignment, Offset); }
protected override void SerializeSafe(IEncoder encoder, object @object) { encoder.Encode((byte[])@object); }
public override void Write(IEncoder enc) { enc.WriteSequenceNo(_CommandId); enc.WriteByteRanges(_ByteRanges); }
public void Encode (IEncoder enc) { int mask = 0 ; int bit = 0 ; List<SchemaProperty> propsToEncode = new List<SchemaProperty>() ; log.Debug(String.Format("Encoding class {0}:{1}", Schema.PackageName, Schema.ClassName)) ; enc.WriteUint8(20) ; Schema.Key.encode(enc) ; foreach (SchemaProperty prop in Schema.GetAllProperties()) { if (prop.Optional) { if (bit == 0) { bit =1 ; } if ((Properties.ContainsKey(prop.Name)) && (Properties[prop.Name] != null)) { mask |= bit ; propsToEncode.Add(prop) ; } else { } bit = bit << 1 ; if (bit == 256) { bit = 0 ; enc.WriteUint8((short)mask) ; mask = 0 ; } } else { propsToEncode.Add(prop) ; } } if (bit != 0) { enc.WriteUint8((short)mask) ; } foreach (SchemaProperty prop in propsToEncode) { object obj = Properties[prop.Name] ; //log.Debug(String.Format("Encoding property {0}", prop.Name)) ; Session.EncodeValue(enc, prop.Type, obj) ; } foreach (SchemaStatistic stat in Schema.Statistics) { object obj = Statistics[stat.Name] ; Session.EncodeValue(enc, stat.Type, obj) ; } log.Debug("Done") ; }
public NullableEncoder(IEncoder <TType, TRoot> baseEncoder, IEncoder <TRoot, TRoot> rootEncoder) : base(baseEncoder, rootEncoder) { }
public HttpRequest(IEncoder encoder) { RawHeaders = new Dictionary<string, object>(); UserAgent = String.Format("EasyHttp HttpClient v{0}", Assembly.GetAssembly(typeof(HttpClient)).GetName().Version); Accept = String.Join(";", HttpContentTypes.TextHtml, HttpContentTypes.ApplicationXml, HttpContentTypes.ApplicationJson); _encoder = encoder; }
public DefaultSocketClient(IPAddress address, int port, IClientHandler handler, IEncoder encoder) : base(address, port, handler) { if (encoder == null) { throw new ArgumentNullException("encoder"); } this._encoder = encoder; }
public RenderBufferToEncodedImageStreamConverter(IEncoder encoder) { _encoder = encoder; }
public override void Encode(IEncoder encoder) { encoder.I32le_u(); }
public ConversionManager(IResourceHandler fileHandler, IResourceHandler registryHandler, IEncoder encoder) { _fileHandler = fileHandler; _registryHandler = registryHandler; _encoder = encoder; }
public virtual void Encode(IEncoder encoder) { encoder.PushNamespace("http://opcfoundation.org/UA/2008/02/Types.xsd"); encoder.WriteString("EndpointUrl", EndpointUrl); encoder.WriteEncodable<ApplicationDescription>("Server", Server); encoder.WriteByteString("ServerCertificate", ServerCertificate); encoder.WriteEnumeration<MessageSecurityMode>("SecurityMode", SecurityMode); encoder.WriteString("SecurityPolicyUri", SecurityPolicyUri); encoder.WriteEncodableArray<UserTokenPolicy>("UserIdentityTokens", UserIdentityTokens); encoder.WriteString("TransportProfileUri", TransportProfileUri); encoder.WriteByte("SecurityLevel", SecurityLevel); encoder.PopNamespace(); }
public override void Encode(IEncoder encoder) { encoder.Br(LabelIndex); }
public override void Encode(IEncoder encoder) { encoder.Return(); }
public EncoderViewModel(IEncoder encoder) { _encoder = encoder; }
/// <summary> /// Helper for encoding of built in types. /// </summary> protected void Encode(IEncoder encoder, BuiltInType builtInType, string fieldName, object value) { bool isArray = (value?.GetType().IsArray ?? false) && (builtInType != BuiltInType.ByteString); bool isCollection = (value is IList) && (builtInType != BuiltInType.ByteString); if (!isArray && !isCollection) { switch (builtInType) { case BuiltInType.Null: { encoder.WriteVariant(fieldName, new Variant(value)); return; } case BuiltInType.Boolean: { encoder.WriteBoolean(fieldName, (bool)value); return; } case BuiltInType.SByte: { encoder.WriteSByte(fieldName, (sbyte)value); return; } case BuiltInType.Byte: { encoder.WriteByte(fieldName, (byte)value); return; } case BuiltInType.Int16: { encoder.WriteInt16(fieldName, (short)value); return; } case BuiltInType.UInt16: { encoder.WriteUInt16(fieldName, (ushort)value); return; } case BuiltInType.Int32: { encoder.WriteInt32(fieldName, (int)value); return; } case BuiltInType.UInt32: { encoder.WriteUInt32(fieldName, (uint)value); return; } case BuiltInType.Int64: { encoder.WriteInt64(fieldName, (long)value); return; } case BuiltInType.UInt64: { encoder.WriteUInt64(fieldName, (ulong)value); return; } case BuiltInType.Float: { encoder.WriteFloat(fieldName, (float)value); return; } case BuiltInType.Double: { encoder.WriteDouble(fieldName, (double)value); return; } case BuiltInType.String: { encoder.WriteString(fieldName, (string)value); return; } case BuiltInType.DateTime: { encoder.WriteDateTime(fieldName, (DateTime)value); return; } case BuiltInType.Guid: { encoder.WriteGuid(fieldName, (Uuid)value); return; } case BuiltInType.ByteString: { encoder.WriteByteString(fieldName, (byte[])value); return; } case BuiltInType.XmlElement: { encoder.WriteXmlElement(fieldName, (XmlElement)value); return; } case BuiltInType.NodeId: { encoder.WriteNodeId(fieldName, (NodeId)value); return; } case BuiltInType.ExpandedNodeId: { encoder.WriteExpandedNodeId(fieldName, (ExpandedNodeId)value); return; } case BuiltInType.StatusCode: { encoder.WriteStatusCode(fieldName, (StatusCode)value); return; } case BuiltInType.QualifiedName: { encoder.WriteQualifiedName(fieldName, (QualifiedName)value); return; } case BuiltInType.LocalizedText: { encoder.WriteLocalizedText(fieldName, (LocalizedText)value); return; } case BuiltInType.ExtensionObject: { encoder.WriteExtensionObject(fieldName, (ExtensionObject)value); return; } case BuiltInType.DataValue: { encoder.WriteDataValue(fieldName, (DataValue)value); return; } case BuiltInType.Enumeration: { if (value.GetType().IsEnum) { encoder.WriteEnumerated(fieldName, (Enum)value); } else { encoder.WriteEnumerated(fieldName, (Enumeration)value); } return; } case BuiltInType.Variant: { encoder.WriteVariant(fieldName, (Variant)value); return; } case BuiltInType.DiagnosticInfo: { encoder.WriteDiagnosticInfo(fieldName, (DiagnosticInfo)value); return; } } } else { Type arrayType = value.GetType().GetElementType(); IEnumerable enumerable = value as IEnumerable; Array array = value as Array; switch (builtInType) { case BuiltInType.Variant: { encoder.WriteVariantArray(fieldName, (VariantCollection)value); return; } case BuiltInType.Enumeration: { encoder.WriteEnumeratedArray(fieldName, array, arrayType); return; } } } Assert.Fail($"Unknown BuiltInType {builtInType}"); }
public void encode(IEncoder enc) { enc.WriteUint64((long)first) ; enc.WriteUint64((long)second) ; }
public void Encode(IEncoder encoder) { encoder.PushNamespace(ApplicationUri); encoder.WriteString(nameof(Foo), Foo); encoder.PopNamespace(); }
/// <summary> /// Reads the passed JToken default value field and writes it in the specified encoder /// </summary> /// <param name="enc">encoder to use for writing</param> /// <param name="schema">schema object for the current field</param> /// <param name="jtok">default value as JToken</param> public static void EncodeDefaultValue(IEncoder enc, Schema.Schema schema, JToken jtok) { if (null == jtok) { return; } switch (schema.Type) { case SchemaType.Boolean: if (jtok.Type != JTokenType.Boolean) { throw new BaijiException("Default boolean value " + jtok + " is invalid, expected is json boolean."); } enc.WriteBoolean((bool)jtok); break; case SchemaType.Int: if (jtok.Type != JTokenType.Integer) { throw new BaijiException("Default int value " + jtok + " is invalid, expected is json integer."); } enc.WriteInt(Convert.ToInt32((int)jtok)); break; case SchemaType.Long: if (jtok.Type != JTokenType.Integer) { throw new BaijiException("Default long value " + jtok + " is invalid, expected is json integer."); } enc.WriteLong(Convert.ToInt64((long)jtok)); break; case SchemaType.Float: if (jtok.Type != JTokenType.Float) { throw new BaijiException("Default float value " + jtok + " is invalid, expected is json number."); } enc.WriteFloat((float)jtok); break; case SchemaType.Double: if (jtok.Type == JTokenType.Integer) { enc.WriteDouble(Convert.ToDouble((int)jtok)); } else if (jtok.Type == JTokenType.Float) { enc.WriteDouble(Convert.ToDouble((float)jtok)); } else { throw new BaijiException("Default double value " + jtok + " is invalid, expected is json number."); } break; case SchemaType.Bytes: if (jtok.Type != JTokenType.String) { throw new BaijiException("Default bytes value " + jtok + " is invalid, expected is json string."); } var en = Encoding.GetEncoding("iso-8859-1"); enc.WriteBytes(en.GetBytes((string)jtok)); break; case SchemaType.String: if (jtok.Type != JTokenType.String) { throw new BaijiException("Default string value " + jtok + " is invalid, expected is json string."); } enc.WriteString((string)jtok); break; case SchemaType.Enumeration: if (jtok.Type != JTokenType.String) { throw new BaijiException("Default enum value " + jtok + " is invalid, expected is json string."); } enc.WriteEnum((schema as EnumSchema).Ordinal((string)jtok)); break; case SchemaType.Null: if (jtok.Type != JTokenType.Null) { throw new BaijiException("Default null value " + jtok + " is invalid, expected is json null."); } enc.WriteNull(); break; case SchemaType.Array: if (jtok.Type != JTokenType.Array) { throw new BaijiException("Default array value " + jtok + " is invalid, expected is json array."); } JArray jarr = jtok as JArray; enc.WriteArrayStart(); enc.SetItemCount(jarr.Count); foreach (JToken jitem in jarr) { enc.StartItem(); EncodeDefaultValue(enc, (schema as ArraySchema).ItemSchema, jitem); } enc.WriteArrayEnd(); break; case SchemaType.Record: if (jtok.Type != JTokenType.Object) { throw new BaijiException("Default record value " + jtok + " is invalid, expected is json object."); } RecordSchema rcs = schema as RecordSchema; JObject jo = jtok as JObject; foreach (Field field in rcs) { JToken val = jo[field.Name]; if (null == val) { val = field.DefaultValue; } if (null == val) { throw new BaijiException("No default value for field " + field.Name); } EncodeDefaultValue(enc, field.Schema, val); } break; case SchemaType.Map: if (jtok.Type != JTokenType.Object) { throw new BaijiException("Default map value " + jtok + " is invalid, expected is json object."); } jo = jtok as JObject; enc.WriteMapStart(); enc.SetItemCount(jo.Count); foreach (KeyValuePair <string, JToken> jp in jo) { enc.StartItem(); enc.WriteString(jp.Key); EncodeDefaultValue(enc, (schema as MapSchema).ValueSchema, jp.Value); } enc.WriteMapEnd(); break; case SchemaType.Union: enc.WriteUnionIndex(0); EncodeDefaultValue(enc, (schema as UnionSchema).Schemas[0], jtok); break; default: throw new BaijiException("Unsupported schema type " + schema.Type); } }
public virtual void Encode(IEncoder encoder) { encoder.PushNamespace("http://opcfoundation.org/UA/2008/02/Types.xsd"); encoder.WriteEncodable<RequestHeader>("RequestHeader", RequestHeader); encoder.WriteString("EndpointUrl", EndpointUrl); encoder.WriteStringArray("LocaleIds", LocaleIds); encoder.WriteStringArray("ProfileUris", ProfileUris); encoder.PopNamespace(); }