public EncoderParameter(Encoder encoder, byte[] value) { this.encoder = encoder.Guid; this.numberOfValues = value.Length; this.type = EncoderParameterValueType.ValueTypeByte; this.value = value; }
public void OrderProcessingFun(OrderClass obj_1) { Encoder encode = new Encoder(); senderId = obj_1.get_senderId(); cardNo = obj_1.get_cardNo(); receiverId = obj_1.get_receiverId(); amount = obj_1.get_amount(); unitprice = obj_1.get_unitprice(); string encodedString; if (!IsValidCardNo(cardNo) || amount == 0) { obj_1.set_confirmationstatus(false); obj_1.set_totalamount(0); encodedString = encode.encryptString(obj_1); // ConfirmationBuffer.setOneCell(encodedString); } else { CalculatePrice(); obj_1.set_confirmationstatus(true); obj_1.set_totalamount(TotalAmount); encodedString = encode.encryptString(obj_1); // ConfirmationBuffer.setOneCell(encodedString); } if (encodedString != null) { OrderConfirmation(encodedString); } }
private IPlaylistWriter writer; // playlist writer #endregion Fields #region Constructors //======================================================================================== // Constructor //======================================================================================== /// <summary> /// Initialize a new instance of this scanner. /// </summary> /// <param name="itunes">The iTunesAppClass to use.</param> /// <param name="exportPIDs"> /// The list of persistent track IDs. When exporting multiple playlists, this list /// should include all tracks from all playlists where each track indicates its own /// source playlist. This allows comprehensive/overall feedback for UI progress bars. /// </param> /// <param name="encoder">The encoder to use to convert tracks.</param> /// <param name="playlistFormat"> /// The playlist output format or PlaylistFactory.NoFormat for no playlist file. /// </param> /// <param name="location"> /// The target root directory path to which all entries will be copied or converted. /// </param> /// <param name="pathFormat"> /// The path format string as specified in FolderFormts.xml or null for title only. /// </param> /// <param name="isSynchronized"> /// True if target location should be synchronized, removing entries in the target /// location that are not included in the exportPIDs collection. /// </param> public ExportScanner( Controller controller, PersistentIDCollection exportPIDs, Encoder encoder, string playlistFormat, string location, string pathFormat, bool isSynchronized) { base.name = Resx.I_ScanExport; base.description = isSynchronized ? Resx.ScanSynchronize : Resx.ScanExport; base.controller = controller; this.exportPIDs = exportPIDs; this.encoder = encoder; this.expectedType = encoder.ExpectedType; this.playlistFormat = playlistFormat; this.playlistName = exportPIDs.Name; this.location = location; this.createSubdirectories = (pathFormat != null); this.pathFormat = pathFormat ?? PathHelper.GetPathFormat(FlatPathFormat); this.isSynchronized = isSynchronized; this.exports = null; this.writer = null; this.slim = new ReaderWriterLockSlim(); this.waitSyncRoot = null; }
/// <summary> /// Encodes a frame. /// </summary> /// <param name="frame">The video buffer.</param> /// <returns></returns> public override byte[] Encode(VideoBuffer frame) { if (Encoder == null) { Encoder = new Encoder(); Encoder.Quality = 0.5; Encoder.Bitrate = 320; //Encoder.Scale = 1.0; } if (frame.ResetKeyFrame) { Encoder.ForceKeyframe(); } // frame -> vp8 int width, height; var rotate = frame.Rotate; if (rotate % 180 == 0) { width = frame.Width; height = frame.Height; } else { height = frame.Width; width = frame.Height; } return Encoder.Encode(width, height, frame.Plane.Data, frame.FourCC, rotate); }
/// <summary> /// Ctor. /// </summary> /// <param name="format">The pixel format to use for conversion.</param> /// <param name="encoder">The encoder to use.</param> /// <param name="rotate">Degrees of rotation to apply (counterclock whise).</param> public BitmapSourceConverter(PixelFormat format, Encoder encoder, int rotate = 0) { _format = format; _encoder = encoder; Rotate = rotate; }
public TomP2POutbound(bool preferDirect, ISignatureFactory signatureFactory, CompByteBufAllocator alloc) { _preferDirect = preferDirect; _signatureFactory = signatureFactory; _encoder = new Encoder(signatureFactory); _alloc = alloc; //Logger.Info("Instantiated with object identity: {0}.", RuntimeHelpers.GetHashCode(this)); }
public EncoderParameter(Encoder encoder, short[] value) { this.encoder = encoder; this.valuesCount = value.Length; this.type = EncoderParameterValueType.ValueTypeShort; this.valuePtr = Marshal.AllocHGlobal(2 * valuesCount); Marshal.Copy(value, 0, this.valuePtr, valuesCount); }
public EncoderParameter(Encoder encoder, short value) { this.encoder = encoder; this.valuesCount = 1; this.type = EncoderParameterValueType.ValueTypeShort; this.valuePtr = Marshal.AllocHGlobal(2); Marshal.WriteInt16(this.valuePtr, value); }
public EncoderParameter(Encoder encoder, byte value) { this.encoder = encoder; this.valuesCount = 1; this.type = EncoderParameterValueType.ValueTypeByte; this.valuePtr = Marshal.AllocHGlobal(1); Marshal.WriteByte(this.valuePtr, value); }
public override void Encode(Stream stream, Encoding encoding = null) { if (_writeEncoder != null) return; var encoder = new Encoder(stream, encoding ?? _encoding, _options, NodeFormat, _type); _writeRows.ForEach(encoder.Write); }
public EncoderParameter(Encoder encoder, byte[] value, bool undefined) { this.encoder = encoder.Guid; this.numberOfValues = value.Length; this.type = (undefined ? EncoderParameterValueType.ValueTypeUndefined : EncoderParameterValueType.ValueTypeByte); this.value = value; }
public FakeEncoderFixture(DioCrossConnectFixture dio1, DioCrossConnectFixture dio2) { Assert.NotNull(dio1); Assert.NotNull(dio2); m_dio1 = dio1; m_dio2 = dio2; m_allocated = false; m_source = new FakeEncoderSource(dio1.GetOutput(), dio2.GetOutput()); m_encoder = new Encoder(dio1.GetInput(), dio2.GetInput()); }
public void Encode(Encoder rangeEncoder, byte symbol) { uint context = 1; for (int i = 7; i >= 0; i--) { uint bit = (uint)((symbol >> i) & 1); m_Encoders[context].Encode(rangeEncoder, bit); context = (context << 1) | bit; } }
public void Encode(Encoder rangeEncoder, UInt32 symbol) { UInt32 m = 1; for (int bitIndex = NumBitLevels; bitIndex > 0; ) { bitIndex--; UInt32 bit = (symbol >> bitIndex) & 1; Models[m].Encode(rangeEncoder, bit); m = (m << 1) | bit; } }
/** * Constructor for WebService * @param prefix string where the server should listen. Example "http://localhost:8080/" */ public WebService(string prefix, Encoder encoder, Streaming streaming) { log.Debug("Creating Web Service"); this.dvrbConfig = null; this.uriPrefixes = new string[] { prefix }; this.encoder = encoder; this.streaming = streaming; // Create a listener. this.listener = new HttpListener(); }
private void button1_Click(object sender, EventArgs e) { Encoder encoder = new Encoder(); encoder.Indent = true; Test o = new Test(); string s = encoder.Encode(o); richTextBox1.Clear(); richTextBox1.AppendText(s); }
public PgmSender(IOThread ioThread, Options options, Address addr) : base(ioThread) { m_options = options; m_addr = addr; m_encoder = null; m_outBuffer = null; m_outBufferSize = 0; m_writeSize = 0; m_encoder = new Encoder(0, m_options.Endian); }
public void ReverseEncode(Encoder rangeEncoder, UInt32 symbol) { UInt32 m = 1; for (UInt32 i = 0; i < NumBitLevels; i++) { UInt32 bit = symbol & 1; Models[m].Encode(rangeEncoder, bit); m = (m << 1) | bit; symbol >>= 1; } }
// Service start protected override void OnStart(string[] args) { log.Trace("-------------------------------"); log.Trace("DVRB STARTING APPLICATION..."); log.Trace("-------------------------------"); this.policyServer = new FlashPolicyServer(); this.encoder = new Encoder(); this.stream = new Streaming(); this.webService = new WebService("http://+:8080/", this.encoder, this.stream); this.policyServer.Start(); this.webService.StartWebServiceListener(); }
//Test method to verify encode/decode service with orderclass static Boolean testOrder() { OrderClass order = new OrderClass(); order.setAmt(123); order.setID("test"); order.setCardNo(456418); Encoder enc = new Encoder(order); String encoded = enc.getOrder(); Decoder dec = new Decoder(encoded); return order == dec.getOrder(); }
public void TestChannelChannelReverseInit() { using (Encoder x = new Encoder(1, 2, true)) { Assert.IsTrue(SimData.Encoder[0].Initialized); CheckConfig(SimData.Encoder[0].Config, 0, 1, false, 0, 2, false); Assert.IsTrue(SimData.Encoder[0].ReverseDirection); Assert.IsTrue(SimData.DIO[1].Initialized); Assert.IsTrue(SimData.DIO[2].Initialized); } Assert.IsFalse(SimData.Encoder[0].Initialized); Assert.IsFalse(SimData.DIO[1].Initialized); Assert.IsFalse(SimData.DIO[2].Initialized); }
public void EncodeTest() { //Arrange var cloudStorageConfiguration = new CloudStorageConfiguration(CloudStorageAccount.DevelopmentStorageAccount, new Version()); var queueVideoRepository = new QueueVideoRepository(cloudStorageConfiguration.StorageAccount.CreateCloudQueueClient()); var videoRepository = new FakeVideoRepository(_blobSource, _blobDestination); var screenshotRepository = new FakeScreenshotRepository(_blobDestination); var mediaInfoReader = new MediaInfoReader(); var encoder = new Encoder(); var fileSystemWrapper = new FileSystemWrapper(); var queueProcess = new QueueProcess(1000, queueVideoRepository); var downloadProcess = new DownloadProcess(5, videoRepository, fileSystemWrapper); var encoderProcess = new EncodeProcess(5, encoder, videoRepository, mediaInfoReader, queueVideoRepository, fileSystemWrapper); var uploadProcess = new UploadProcess(5, videoRepository, screenshotRepository, fileSystemWrapper); var finishProcess = new FinishProcess(queueVideoRepository, videoRepository, fileSystemWrapper); var queueContainer = new ProcessContainer<object, QueueInformation, DownloadInformation>(queueProcess, downloadProcess); var downloadContainer = new ProcessContainer<QueueInformation, DownloadInformation, EncodeInformation>(downloadProcess, encoderProcess); var encoderContainer = new ProcessContainer<DownloadInformation, EncodeInformation, UploadInformation>(encoderProcess, uploadProcess); var uploadContainer = new ProcessContainer<EncodeInformation, UploadInformation, object>(uploadProcess, finishProcess); var processManager = new EncodeProcessManager(queueVideoRepository.DeleteMessageLocal); processManager.Add(queueContainer); processManager.Add(downloadContainer); processManager.Add(encoderContainer); processManager.Add(uploadContainer); var timer = new Timer(UpdateMessages, queueVideoRepository, (int) queueVideoRepository.InvisibleTime.TotalMilliseconds/2, (int) queueVideoRepository.InvisibleTime.TotalMilliseconds/2); //Act & Assert Task task = processManager.Start(); StartQueueWork(); Thread.Sleep(30000); while (queueVideoRepository.ApproximateMessageCount > 0) { Thread.Sleep(60000); } //Thread.Sleep(50*60*1000); processManager.Stop(); task.Wait(); }
private void button3_Click(object sender, EventArgs e) { Encoder encoder = new Encoder(); encoder.Indent = true; Test o = new Test(); string s = encoder.Encode(o); Decoder decoder = new Decoder(); Test o2 = (Test)decoder.Decode(s); string s2 = encoder.Encode(o2); if (s == s2) richTextBox1.AppendText("OK\n"); else richTextBox1.AppendText("FAIL\n"); }
public TravelAgency() { //instantiating necessary objects randDemand = new Random(); queuedOrders = new List<OrderClass>(); sentOrders = new List<OrderClass>(); confirmedOrders = new List<OrderClass>(); currentOrder = new OrderClass(); orderEncoder = new Encoder(); orderStart = new DateTime[10]; orderFinish = new DateTime[10]; orderNumber = 0; startNumber = 0; roomDemand = randDemand.Next(50, 100); mcb = new MultiCellBuffer(); }
public FakeEncoderFixture(int inputA, int outputA, int inputB, int outputB, EncodingType type) { Assert.AreNotEqual(outputA, outputB); Assert.AreNotEqual(outputA, inputA); Assert.AreNotEqual(outputA, inputB); Assert.AreNotEqual(outputB, inputA); Assert.AreNotEqual(outputB, inputB); Assert.AreNotEqual(inputA, inputB); m_dio1 = new DioCrossConnectFixture(inputA, outputA); m_dio2 = new DioCrossConnectFixture(inputB, outputB); m_allocated = true; m_sourcePort[0] = outputA; m_sourcePort[1] = outputB; m_encoderPort[0] = inputA; m_encoderPort[1] = inputB; m_source = new FakeEncoderSource(m_dio1.GetOutput(), m_dio2.GetOutput()); m_encoder = new Encoder(m_dio1.GetInput(), m_dio2.GetInput(), false, type); }
public static byte[] Compress(byte[] bytes) { Encoder coder = new Encoder(); using (MemoryStream input = new MemoryStream(bytes)) { using (MemoryStream output = new MemoryStream()) { // Write the encoder properties coder.WriteCoderProperties(output); // Write the decompressed file size. output.Write(BitConverter.GetBytes(input.Length), 0, 8); // Encode the file. coder.Code(input, output, input.Length, -1, null); return output.ToArray(); } } }
void Awake() { _encoder = new Encoder(); _decoder = new Decoder(); _parser = new Parser(); _handlers = new Dictionary<string, List<Action<SocketIOEvent>>>(); _ackList = new List<Ack>(); _packetId = 0; _eventQueueLock = new object(); _eventQueue = new Queue<SocketIOEvent>(); _ackQueueLock = new object(); _ackQueue = new Queue<Packet>(); #if SOCKET_IO_DEBUG if (_debugMethod == null) { _debugMethod = Debug.Log; }; #endif }
void TestData(Schema schema, Encoder encoder, Decoder decoder, object[] data) { for (int i = 0; i < data.Length; i++) { object expected = data[i]; Type expectedType = data[i].GetType(); using (MemoryStream iostr = new MemoryStream()) { Serializer.Serialize(PrefixStyle.None, schema, iostr, encoder, expected); iostr.Position = 0; object actual = Serializer.Deserialize(PrefixStyle.None, schema, iostr, decoder, expectedType); Assert.AreEqual(expected, actual); } } }
static void Main(string[] args) { var jsonParser = new JsonParser() { CamelizeProperties = false }; dynamic config = jsonParser.Parse(System.IO.File.ReadAllText("config.txt")); Dispatcher dispatcher = new Dispatcher(); Database database = new Database(dispatcher, config); Decoder decoder = new Decoder(dispatcher); Receiver receiver = new Receiver("450052", "VR2C-69", dispatcher); Encoder encoder = new Encoder("*450052.0#16,", config); ConsoleLogger consoleLogger = new ConsoleLogger(dispatcher); dispatcher.addModule(database); dispatcher.addModule(decoder); dispatcher.addModule(consoleLogger); dispatcher.run(); testUnparsedMessages(dispatcher, receiver, config); //testEncoder(encoder); //testDecoder(decoder); //testDatabase(database); }
public void TestEncoderOverAllocation() { List<Encoder> encoders = new List<Encoder>(); for (int i = 0; i < NumEncoders; i++) { encoders.Add(new Encoder(i, i + NumEncoders)); } Encoder enc = null; Assert.Throws<AllocationException>(() => { enc = new Encoder(NumEncoders, NumEncoders + NumEncoders); }); enc?.Dispose(); foreach (var encoder in encoders) { encoder.Dispose(); } }
public string Decrypt(string encrypted) { byte[] buff = Decrypt(HttpServerUtility.UrlTokenDecode(encrypted)); return(Encoder.GetString(buff)); }
public static void CompressImage(Stream sourcePath, string targetPath, String fileName) { try { using (var image = Image.FromStream(sourcePath)) { float maxHeight = 900.0f; float maxWidth = 400.0f; int newWidth; int newHeight; string extension; Bitmap originalBMP = new Bitmap(sourcePath); int originalWidth = originalBMP.Width; int originalHeight = originalBMP.Height; if (originalWidth > maxWidth || originalHeight > maxHeight) { // To preserve the aspect ratio float ratioX = (float)maxWidth / (float)originalWidth; float ratioY = (float)maxHeight / (float)originalHeight; float ratio = Math.Min(ratioX, ratioY); newWidth = (int)(originalWidth * ratio); newHeight = (int)(originalHeight * ratio); } else { newWidth = (int)originalWidth; newHeight = (int)originalHeight; } Bitmap bitMAP1 = new Bitmap(originalBMP, newWidth, newHeight); Graphics imgGraph = Graphics.FromImage(bitMAP1); extension = Path.GetExtension(targetPath); if (extension == ".png" || extension == ".gif") { imgGraph.SmoothingMode = SmoothingMode.AntiAlias; imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight); bitMAP1.Save(targetPath, image.RawFormat); bitMAP1.Dispose(); imgGraph.Dispose(); originalBMP.Dispose(); } else if (extension == ".jpg") { imgGraph.SmoothingMode = SmoothingMode.AntiAlias; imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight); ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); Encoder myEncoder = Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; bitMAP1.Save(targetPath, jpgEncoder, myEncoderParameters); bitMAP1.Dispose(); imgGraph.Dispose(); originalBMP.Dispose(); } } } catch { throw; } }
private async void ToggleButton_Checked(object sender, RoutedEventArgs e) { var button = (ToggleButton)sender; // Get our encoder properties var frameRateItem = (FrameRateItem)FrameRateComboBox.SelectedItem; var resolutionItem = (ResolutionItem)ResolutionComboBox.SelectedItem; var bitrateItem = (BitrateItem)BitrateComboBox.SelectedItem; if (UseCaptureItemToggleSwitch.IsOn) { resolutionItem.IsZero(); } var width = resolutionItem.Resolution.Width; var height = resolutionItem.Resolution.Height; var bitrate = bitrateItem.Bitrate; var frameRate = frameRateItem.FrameRate; if (UseCaptureItemToggleSwitch.IsOn) { resolutionItem.IsZero(); } // Get our capture item var picker = new GraphicsCapturePicker(); var item = await picker.PickSingleItemAsync(); if (item == null) { button.IsChecked = false; return; } // Use the capture item's size for the encoding if desired if (UseCaptureItemToggleSwitch.IsOn) { width = (uint)item.Size.Width; height = (uint)item.Size.Height; // Even if we're using the capture item's real size, // we still want to make sure the numbers are even. // Some encoders get mad if you give them odd numbers. width = EnsureEven(width); height = EnsureEven(height); } // Put videos in the temp folder var tempFile = await GetTempFileAsync(); _tempFile = tempFile; // Tell the user we've started recording var visual = ElementCompositionPreview.GetElementVisual(Ellipse); var animation = visual.Compositor.CreateScalarKeyFrameAnimation(); animation.InsertKeyFrame(0, 1); animation.InsertKeyFrame(1, 0); animation.Duration = TimeSpan.FromMilliseconds(1500); animation.IterationBehavior = AnimationIterationBehavior.Forever; visual.StartAnimation("Opacity", animation); RecordIcon.Visibility = Visibility.Collapsed; StopIcon.Visibility = Visibility.Visible; Ellipse.Visibility = Visibility.Visible; ToolTip toolTip = new ToolTip(); toolTip.Content = "Stop recording"; ToolTipService.SetToolTip(MainButton, toolTip); AutomationProperties.SetName(MainButton, "Stop recording"); MainTextBlock.Text = "recording..."; var originalBrush = MainTextBlock.Foreground; MainTextBlock.Foreground = new SolidColorBrush(Colors.Red); // Kick off the encoding try { using (var stream = await tempFile.OpenAsync(FileAccessMode.ReadWrite)) using (_encoder = new Encoder(_device, item)) { var encodesuccess = await _encoder.EncodeAsync( stream, width, height, bitrate, frameRate); if (encodesuccess == false) { ContentDialog errorDialog = new ContentDialog { Title = "Recording failed", Content = "Windows cannot encode your video", CloseButtonText = "OK" }; await errorDialog.ShowAsync(); } } MainTextBlock.Foreground = originalBrush; } catch (Exception ex) { Crashes.TrackError(ex); Debug.WriteLine(ex.Message); Debug.WriteLine(ex); var message = GetMessageForHResult(ex.HResult); if (message == null) { message = $"Whoops, something went wrong!\n0x{ex.HResult:X8} - {ex.Message}"; } ContentDialog errorDialog = new ContentDialog { Title = "Recording failed", Content = message, CloseButtonText = "OK" }; await errorDialog.ShowAsync(); button.IsChecked = false; visual.StopAnimation("Opacity"); Ellipse.Visibility = Visibility.Collapsed; MainTextBlock.Text = "failure"; MainTextBlock.Foreground = originalBrush; RecordIcon.Visibility = Visibility.Visible; StopIcon.Visibility = Visibility.Collapsed; toolTip.Content = "Start recording"; ToolTipService.SetToolTip(MainButton, toolTip); AutomationProperties.SetName(MainButton, "Start recording"); await _tempFile.DeleteAsync(); return; } // At this point the encoding has finished, // tell the user we're now saving MainButton.IsChecked = false; MainTextBlock.Text = ""; visual.StopAnimation("Opacity"); Ellipse.Visibility = Visibility.Collapsed; RecordIcon.Visibility = Visibility.Visible; StopIcon.Visibility = Visibility.Collapsed; ToolTip newtoolTip = new ToolTip(); toolTip.Content = "Start recording"; ToolTipService.SetToolTip(MainButton, toolTip); AutomationProperties.SetName(MainButton, "Start recording"); if (PreviewToggleSwitch.IsOn) { CoreApplicationView newView = CoreApplication.CreateNewView(); int newViewId = 0; await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var preview = new VideoPreviewPage(_tempFile); ApplicationViewTitleBar formattableTitleBar = ApplicationView.GetForCurrentView().TitleBar; formattableTitleBar.ButtonBackgroundColor = Colors.Transparent; CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar; coreTitleBar.ExtendViewIntoTitleBar = true; Window.Current.Content = preview; Window.Current.Activate(); newViewId = ApplicationView.GetForCurrentView().Id; }); bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId); } else { ContentDialog dialog = new SaveDialog(_tempFile); await dialog.ShowAsync(); } }
public static async Task <Result> CreateClientConnectionAndStream( StreamState state, ILoggerProvider loggerProvider, IBufferedPipe iPipe, IBufferedPipe oPipe, Settings?localSettings = null, Settings?remoteSettings = null, HuffmanStrategy huffmanStrategy = HuffmanStrategy.Never) { if (state == StreamState.Idle) { throw new Exception("Not supported"); } var hEncoder = new Encoder(); var conn = await Http2ConnectionUtils.BuildEstablishedConnection( false, iPipe, oPipe, loggerProvider, null, localSettings : localSettings, remoteSettings : remoteSettings, huffmanStrategy : huffmanStrategy); var endOfStream = false; if (state == StreamState.HalfClosedLocal || state == StreamState.Closed) { endOfStream = true; } var stream = await conn.CreateStreamAsync( DefaultGetHeaders, endOfStream : endOfStream); await oPipe.ReadAndDiscardHeaders(1u, endOfStream); if (state == StreamState.HalfClosedRemote || state == StreamState.Closed) { var outBuf = new byte[Settings.Default.MaxFrameSize]; var result = hEncoder.EncodeInto( new ArraySegment <byte>(outBuf), DefaultStatusHeaders); await iPipe.WriteFrameHeaderWithTimeout( new FrameHeader { Type = FrameType.Headers, Flags = (byte)(HeadersFrameFlags.EndOfHeaders | HeadersFrameFlags.EndOfStream), StreamId = 1u, Length = result.UsedBytes, }); await iPipe.WriteAsync(new ArraySegment <byte>(outBuf, 0, result.UsedBytes)); var readHeadersTask = stream.ReadHeadersAsync(); var combined = await Task.WhenAny(readHeadersTask, Task.Delay( Http2ReadableStreamTestExtensions.ReadTimeout)); Assert.True(readHeadersTask == combined, "Expected to receive headers"); var headers = await readHeadersTask; Assert.True(headers.SequenceEqual(DefaultStatusHeaders)); } else if (state == StreamState.Reset) { await iPipe.WriteResetStream(1u, ErrorCode.Cancel); } return(new Result { hEncoder = hEncoder, conn = conn, stream = stream, }); }
/// <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(Encoder enc, Schema schema, JToken jtok) { if (null == jtok) { return; } switch (schema.Tag) { case Schema.Type.Boolean: if (jtok.Type != JTokenType.Boolean) { throw new AvroException("Default boolean value " + jtok.ToString() + " is invalid, expected is json boolean."); } enc.WriteBoolean((bool)jtok); break; case Schema.Type.Int: if (jtok.Type != JTokenType.Integer) { throw new AvroException("Default int value " + jtok.ToString() + " is invalid, expected is json integer."); } enc.WriteInt(Convert.ToInt32((int)jtok)); break; case Schema.Type.Long: if (jtok.Type != JTokenType.Integer) { throw new AvroException("Default long value " + jtok.ToString() + " is invalid, expected is json integer."); } enc.WriteLong(Convert.ToInt64((long)jtok)); break; case Schema.Type.Float: if (jtok.Type != JTokenType.Float) { throw new AvroException("Default float value " + jtok.ToString() + " is invalid, expected is json number."); } enc.WriteFloat((float)jtok); break; case Schema.Type.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 AvroException("Default double value " + jtok.ToString() + " is invalid, expected is json number."); } break; case Schema.Type.Bytes: if (jtok.Type != JTokenType.String) { throw new AvroException("Default bytes value " + jtok.ToString() + " is invalid, expected is json string."); } var en = System.Text.Encoding.GetEncoding("iso-8859-1"); enc.WriteBytes(en.GetBytes((string)jtok)); break; case Schema.Type.Fixed: if (jtok.Type != JTokenType.String) { throw new AvroException("Default fixed value " + jtok.ToString() + " is invalid, expected is json string."); } en = System.Text.Encoding.GetEncoding("iso-8859-1"); int len = (schema as FixedSchema).Size; byte[] bb = en.GetBytes((string)jtok); if (bb.Length != len) { throw new AvroException("Default fixed value " + jtok.ToString() + " is not of expected length " + len); } enc.WriteFixed(bb); break; case Schema.Type.String: if (jtok.Type != JTokenType.String) { throw new AvroException("Default string value " + jtok.ToString() + " is invalid, expected is json string."); } enc.WriteString((string)jtok); break; case Schema.Type.Enumeration: if (jtok.Type != JTokenType.String) { throw new AvroException("Default enum value " + jtok.ToString() + " is invalid, expected is json string."); } enc.WriteEnum((schema as EnumSchema).Ordinal((string)jtok)); break; case Schema.Type.Null: if (jtok.Type != JTokenType.Null) { throw new AvroException("Default null value " + jtok.ToString() + " is invalid, expected is json null."); } enc.WriteNull(); break; case Schema.Type.Array: if (jtok.Type != JTokenType.Array) { throw new AvroException("Default array value " + jtok.ToString() + " 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 Schema.Type.Record: case Schema.Type.Error: if (jtok.Type != JTokenType.Object) { throw new AvroException("Default record value " + jtok.ToString() + " 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 AvroException("No default value for field " + field.Name); } EncodeDefaultValue(enc, field.Schema, val); } break; case Schema.Type.Map: if (jtok.Type != JTokenType.Object) { throw new AvroException("Default map value " + jtok.ToString() + " 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 Schema.Type.Union: enc.WriteUnionIndex(0); EncodeDefaultValue(enc, (schema as UnionSchema).Schemas[0], jtok); break; case Schema.Type.Logical: EncodeDefaultValue(enc, (schema as LogicalSchema).BaseSchema, jtok); break; default: throw new AvroException("Unsupported schema type " + schema.Tag); } }
void GetSet_WIG_LIG_options(int bitness) { var encoder = Encoder.Create(bitness, new CodeWriterImpl()); encoder.VEX_LIG = 1; encoder.VEX_WIG = 0; Assert.Equal(0U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 1; Assert.Equal(1U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 0xFFFFFFFE; Assert.Equal(0U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 0xFFFFFFFF; Assert.Equal(1U, encoder.VEX_WIG); Assert.Equal(1U, encoder.VEX_LIG); encoder.VEX_WIG = 1; encoder.VEX_LIG = 0; Assert.Equal(0U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.VEX_LIG = 1; Assert.Equal(1U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.VEX_LIG = 0xFFFFFFFE; Assert.Equal(0U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.VEX_LIG = 0xFFFFFFFF; Assert.Equal(1U, encoder.VEX_LIG); Assert.Equal(1U, encoder.VEX_WIG); encoder.EVEX_LIG = 3; encoder.EVEX_WIG = 0; Assert.Equal(0U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 1; Assert.Equal(1U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 0xFFFFFFFE; Assert.Equal(0U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 0xFFFFFFFF; Assert.Equal(1U, encoder.EVEX_WIG); Assert.Equal(3U, encoder.EVEX_LIG); encoder.EVEX_WIG = 1; encoder.EVEX_LIG = 0; Assert.Equal(0U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 1; Assert.Equal(1U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 2; Assert.Equal(2U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 3; Assert.Equal(3U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFC; Assert.Equal(0U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFD; Assert.Equal(1U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFE; Assert.Equal(2U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); encoder.EVEX_LIG = 0xFFFFFFFF; Assert.Equal(3U, encoder.EVEX_LIG); Assert.Equal(1U, encoder.EVEX_WIG); }
public async Task <FabricPrincipal> FindUserBySubjectIdAsync(string subjectId, string tenantId = null) { if (!subjectId.Contains(@"\")) { return(null); } var subjectIdParts = subjectId.Split('\\'); var domain = subjectIdParts[0]; var accountName = subjectIdParts[subjectIdParts.Length - 1]; var subject = await Task.Run(() => _activeDirectoryProxy.SearchForUser(Encoder.LdapFilterEncode(domain), Encoder.LdapFilterEncode(accountName))).ConfigureAwait(false); if (subject == null) { return(null); } var principal = CreateUserPrincipal(subject); return(principal); }
public string ReadLine(int byteCount, Encoding encoding) { int remaining = Math.Min(byteCount, Math.Max(0, (int)Length - position)); if (remaining == 0) { return(string.Empty); } if (remaining < 0) { return(null); } unsafe { var bytes = (byte *)(this.DataPtr().Add(position)); Decoder dec = encoding.GetDecoder(); int charCount = dec.GetCharCount(bytes, remaining, false); if (charCount == 0) { return(string.Empty); } var resultChars = new char[charCount]; fixed(char *chars = resultChars) { charCount = dec.GetChars(bytes, remaining, chars, charCount, true); int i = -1, z = 0; while (i < charCount) { ++i; if (chars[i] == '\n') { charCount = i; ++z; if (i - 1 > -1 && chars[i - 1] == '\r') { --charCount; ++z; } break; } if (chars[i] == '\0') { charCount = i; ++z; break; } } Encoder enc = encoding.GetEncoder(); position += enc.GetByteCount(chars, charCount + z, true); if (charCount == 0) { return(string.Empty); } return(new string(chars, 0, charCount)); } } }
void CheckModified(ByteBuffer oldBuf) { if (this.failedCount == 0 && this.MessageAnnotations == null) { return; } ByteBuffer newBuf = new ByteBuffer(oldBuf.Size, true); Header header = new Header(); MessageAnnotations annotations = this.MessageAnnotations; int offset = oldBuf.Offset; while (oldBuf.Length > 0) { offset = oldBuf.Offset; var described = (RestrictedDescribed)Encoder.ReadDescribed(oldBuf, Encoder.ReadFormatCode(buffer)); if (described.Descriptor.Code == 0x70UL) { header = (Header)described; this.WriteHeader(ref header, newBuf); } else if (described.Descriptor.Code == 0x71UL) { this.WriteHeader(ref header, newBuf); AmqpBitConverter.WriteBytes(newBuf, oldBuf.Buffer, offset, oldBuf.Offset - offset); } else if (described.Descriptor.Code == 0x72UL) { this.WriteHeader(ref header, newBuf); this.WriteMessageAnnotations(ref annotations, (MessageAnnotations)described, newBuf); } else { this.WriteHeader(ref header, newBuf); this.WriteMessageAnnotations(ref annotations, null, newBuf); AmqpBitConverter.WriteBytes(newBuf, oldBuf.Buffer, offset, oldBuf.WritePos - offset); break; } } this.buffer = newBuf; this.messageOffset = 0; }
public static void Enqueue(object context, Encoder encoder, object user) { throw new NotImplementedException(); }
public EncodedStore(ResourceStore <TExternal> store, Encoder <TInternal, TExternal> encoder) { this.store = store; this.encoder = encoder; }
public static void Encoder_Convert_Invalid(Encoder encoder, bool flush) { int charsUsed = 0; int bytesUsed = 0; bool completed = false; Action verifyOutParams = () => { Assert.Equal(0, charsUsed); Assert.Equal(0, bytesUsed); Assert.False(completed); }; // Chars is null AssertExtensions.Throws <ArgumentNullException>("chars", () => encoder.Convert(null, 0, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // CharIndex is invalid AssertExtensions.Throws <ArgumentOutOfRangeException>("charIndex", () => encoder.Convert(new char[4], -1, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws <ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 5, 0, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // CharCount is invalid AssertExtensions.Throws <ArgumentOutOfRangeException>("charCount", () => encoder.Convert(new char[4], 0, -1, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws <ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 0, 5, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws <ArgumentOutOfRangeException>("chars", () => encoder.Convert(new char[4], 1, 4, new byte[4], 0, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // Bytes is null AssertExtensions.Throws <ArgumentNullException>("bytes", () => encoder.Convert(new char[1], 0, 1, null, 0, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // ByteIndex is invalid AssertExtensions.Throws <ArgumentOutOfRangeException>("byteIndex", () => encoder.Convert(new char[1], 0, 0, new byte[4], -1, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws <ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 5, 0, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // ByteCount is invalid AssertExtensions.Throws <ArgumentOutOfRangeException>("byteCount", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, -1, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws <ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 0, 5, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); AssertExtensions.Throws <ArgumentOutOfRangeException>("bytes", () => encoder.Convert(new char[1], 0, 0, new byte[4], 1, 4, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); // Bytes does not have enough space int byteCount = encoder.GetByteCount(new char[] { 'a' }, 0, 1, flush); AssertExtensions.Throws <ArgumentException>("bytes", () => encoder.Convert(new char[] { 'a' }, 0, 1, new byte[byteCount - 1], 0, byteCount - 1, flush, out charsUsed, out bytesUsed, out completed)); verifyOutParams(); }
/// <summary> /// javascript 문을 동적으로 생성할 때 script 코드 내용을 javascript 문법에 맞게끔 인코딩한다. /// </summary> /// <param name="value">인코딩할 문자열</param> /// <param name="flagForQuote">인용문구를 씌울 것인가?</param> /// <returns>javascript 형식에 맞는 문자열</returns> public static string JavaScriptEncode(this string value, bool flagForQuote = true) { return(Encoder.JavaScriptEncode(value, flagForQuote)); }
static bool GetNextValue(string charset, Encoder encoder, HexEncoder hex, char[] chars, ref int index, ref byte[] bytes, ref byte[] encoded, int maxLength, out string value) { int length = chars.Length - index; if (length < maxLength) { switch (GetEncodeMethod(chars, index, length)) { case EncodeMethod.Quote: value = MimeUtils.Quote(new string (chars, index, length)); index += length; return(false); case EncodeMethod.None: value = new string (chars, index, length); index += length; return(false); } } length = Math.Min(maxLength, length); int ratio, count, n; do { count = encoder.GetByteCount(chars, index, length, true); if (count > maxLength && length > 1) { ratio = (int)Math.Round((double)count / (double)length); length -= Math.Max((count - maxLength) / ratio, 1); continue; } if (bytes.Length < count) { Array.Resize <byte> (ref bytes, count); } count = encoder.GetBytes(chars, index, length, bytes, 0, true); // Note: the first chunk needs to be encoded in order to declare the charset if (index > 0 || charset == "us-ascii") { var method = GetEncodeMethod(bytes, count); if (method == EncodeMethod.Quote) { value = MimeUtils.Quote(Encoding.ASCII.GetString(bytes, 0, count)); index += length; return(false); } if (method == EncodeMethod.None) { value = Encoding.ASCII.GetString(bytes, 0, count); index += length; return(false); } } n = hex.EstimateOutputLength(count); if (encoded.Length < n) { Array.Resize <byte> (ref encoded, n); } // only the first value gets a charset declaration int charsetLength = index == 0 ? charset.Length + 2 : 0; n = hex.Encode(bytes, 0, count, encoded); if (n > 3 && (charsetLength + n) > maxLength) { int x = 0; for (int i = n - 1; i >= 0 && charsetLength + i >= maxLength; i--) { if (encoded[i] == (byte)'%') { x--; } else { x++; } } ratio = (int)Math.Round((double)count / (double)length); length -= Math.Max(x / ratio, 1); continue; } if (index == 0) { value = charset + "''" + Encoding.ASCII.GetString(encoded, 0, n); } else { value = Encoding.ASCII.GetString(encoded, 0, n); } index += length; return(true); } while (true); }
/// <summary> /// Collect the observations (internal punch) /// </summary> public override void CollectObservations() { AddVectorObs(!punchAction.IsOnCooldown() && !punchAction.IsRunning()); AddVectorObs(!dodgeAction.IsOnCooldown() && !dodgeAction.IsRunning()); bool[] move; int opponentComboState = 0; if (opponent != null) { move = new bool[] { opponent.currentAction == MLAction.PUNCH_RIGHT, opponent.currentAction == MLAction.PUNCH_LEFT, opponent.currentAction == MLAction.DODGE_LEFT, opponent.currentAction == MLAction.DODGE_RIGHT }; opponentComboState = opponent.comboTracker.GetState(); } else { move = new bool[] { false, false, false, false }; opponentComboState = 0; } AddVectorObs(Encoder.encodeInt(comboTracker.GetState(), 0, comboTracker.GetTotalStates())); foreach (var m in move) { AddVectorObs(m); } AddVectorObs(currentAction == MLAction.PUNCH_LEFT); AddVectorObs(currentAction == MLAction.PUNCH_RIGHT); AddVectorObs(currentAction == MLAction.DODGE_LEFT); AddVectorObs(currentAction == MLAction.DODGE_RIGHT); if (bufferSize >= maxBufferSize) { SetTextObs((isTeacher && isFighting && MLActionFactory.GetAction(lastActions) != MLAction.NOTHING) + "," + true); bufferSize = 0; } else { if (MLActionFactory.IsPunch(MLActionFactory.GetAction(lastActions))) { punchCount++; } else if (MLActionFactory.IsDodge(MLActionFactory.GetAction(lastActions))) { dodgeCount++; } if (isTeacher) { //Debug.Log(punchCount + ", " + dodgeCount); } var training = isTeacher && isFighting && (MLActionFactory.GetAction(lastActions) != MLAction.NOTHING || nothingBuffer < nothingBufferSize) && IsGoodMove(); if (training) { bufferSize++; } if (MLActionFactory.GetAction(lastActions) == MLAction.NOTHING) { nothingBuffer++; } SetTextObs(training + "," + false); } }
private static bool TryParseNewFormat(string str, out LightningConnectionString connectionString, out string error) { connectionString = null; error = null; var parts = str.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); Dictionary <string, string> keyValues = new Dictionary <string, string>(); foreach (var part in parts.Select(p => p.Trim())) { var idx = part.IndexOf('='); if (idx == -1) { error = "The format of the connectionString should a list of key=value delimited by semicolon"; return(false); } var key = part.Substring(0, idx).Trim().ToLowerInvariant(); var value = part.Substring(idx + 1).Trim(); if (keyValues.ContainsKey(key)) { error = $"Duplicate key {key}"; return(false); } keyValues.Add(key, value); } var possibleTypes = String.Join(", ", typeMapping.Select(k => k.Key).ToArray()); LightningConnectionString result = new LightningConnectionString(); var type = Take(keyValues, "type"); if (type == null) { error = $"The key 'type' is mandatory, possible values are {possibleTypes}"; return(false); } if (!typeMapping.TryGetValue(type.ToLowerInvariant(), out var connectionType)) { error = $"The key 'type' is invalid, possible values are {possibleTypes}"; return(false); } result.ConnectionType = connectionType; switch (connectionType) { case LightningConnectionType.Charge: { var server = Take(keyValues, "server"); if (server == null) { error = $"The key 'server' is mandatory for charge connection strings"; return(false); } if (!Uri.TryCreate(server, UriKind.Absolute, out var uri) || (uri.Scheme != "http" && uri.Scheme != "https")) { error = $"The key 'server' should be an URI starting by http:// or https://"; return(false); } parts = uri.UserInfo.Split(':'); if (!string.IsNullOrEmpty(uri.UserInfo) && parts.Length == 2) { result.Username = parts[0]; result.Password = parts[1]; } else { var apiToken = Take(keyValues, "api-token"); if (apiToken == null) { error = "The key 'api-token' is not found"; return(false); } result.Username = "******"; result.Password = apiToken; } result.BaseUri = new UriBuilder(uri) { UserName = "", Password = "" }.Uri; } break; case LightningConnectionType.CLightning: { var server = Take(keyValues, "server"); if (server == null) { error = $"The key 'server' is mandatory for charge connection strings"; return(false); } if (server.StartsWith("//", StringComparison.OrdinalIgnoreCase)) { server = "unix:" + str; } else if (server.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { server = "unix:/" + str; } if (!Uri.TryCreate(server, UriKind.Absolute, out var uri) || (uri.Scheme != "tcp" && uri.Scheme != "unix")) { error = $"The key 'server' should be an URI starting by tcp:// or unix:// or a path to the 'lightning-rpc' unix socket"; return(false); } result.BaseUri = uri; } break; case LightningConnectionType.LndREST: case LightningConnectionType.LndGRPC: { var server = Take(keyValues, "server"); if (server == null) { error = $"The key 'server' is mandatory for lnd connection strings"; return(false); } if (!Uri.TryCreate(server, UriKind.Absolute, out var uri) || (uri.Scheme != "http" && uri.Scheme != "https")) { error = $"The key 'server' should be an URI starting by http:// or https://"; return(false); } parts = uri.UserInfo.Split(':'); if (!string.IsNullOrEmpty(uri.UserInfo) && parts.Length == 2) { result.Username = parts[0]; result.Password = parts[1]; } result.BaseUri = new UriBuilder(uri) { UserName = "", Password = "" }.Uri; var macaroon = Take(keyValues, "macaroon"); if (macaroon != null) { try { result.Macaroon = Encoder.DecodeData(macaroon); } catch { error = $"The key 'macaroon' format should be in hex"; return(false); } } var macaroonFilePath = Take(keyValues, "macaroonfilepath"); if (macaroonFilePath != null) { if (macaroon != null) { error = $"The key 'macaroon' is already specified"; return(false); } if (!macaroonFilePath.EndsWith(".macaroon", StringComparison.OrdinalIgnoreCase)) { error = $"The key 'macaroonfilepath' should point to a .macaroon file"; return(false); } result.MacaroonFilePath = macaroonFilePath; } string securitySet = null; var certthumbprint = Take(keyValues, "certthumbprint"); if (certthumbprint != null) { try { var bytes = Encoders.Hex.DecodeData(certthumbprint.Replace(":", string.Empty)); if (bytes.Length != 32) { error = $"The key 'certthumbprint' has invalid length: it should be the SHA256 of the PEM format of the certificate (32 bytes)"; return(false); } result.CertificateThumbprint = bytes; } catch { error = $"The key 'certthumbprint' has invalid format: it should be the SHA256 of the PEM format of the certificate"; return(false); } securitySet = "certthumbprint"; } var allowinsecureStr = Take(keyValues, "allowinsecure"); if (allowinsecureStr != null) { var allowedValues = new[] { "true", "false" }; if (!allowedValues.Any(v => v.Equals(allowinsecureStr, StringComparison.OrdinalIgnoreCase))) { error = $"The key 'allowinsecure' should be true or false"; return(false); } bool allowInsecure = allowinsecureStr.Equals("true", StringComparison.OrdinalIgnoreCase); if (securitySet != null && allowInsecure) { error = $"The key 'allowinsecure' conflict with '{securitySet}'"; return(false); } result.AllowInsecure = allowInsecure; } if (!result.AllowInsecure && result.BaseUri.Scheme == "http") { error = $"The key 'allowinsecure' is false, but server's Uri is not using https"; return(false); } } break; default: throw new NotSupportedException(connectionType.ToString()); } if (keyValues.Count != 0) { error = $"Unknown keys ({String.Join(", ", keyValues.Select(k => k.Key).ToArray())})"; return(false); } connectionString = result; return(true); }
public static async Task <Result> CreateServerConnectionAndStream(HeaderField[] getHeaders, StreamState state, ILoggerProvider loggerProvider, IBufferedPipe iPipe, IBufferedPipe oPipe, Settings?localSettings = null, Settings?remoteSettings = null, HuffmanStrategy huffmanStrategy = HuffmanStrategy.Never) { IStream stream = null; var handlerDone = new SemaphoreSlim(0); if (state == StreamState.Idle) { throw new Exception("Not supported"); } Func <IStream, bool> listener = (s) => { Task.Run(async() => { stream = s; try { await s.ReadHeadersAsync(); if (state == StreamState.Reset) { s.Cancel(); return; } if (state == StreamState.HalfClosedRemote || state == StreamState.Closed) { await s.ReadAllToArrayWithTimeout(); } if (state == StreamState.HalfClosedLocal || state == StreamState.Closed) { await s.WriteHeadersAsync( DefaultStatusHeaders, true); } } finally { handlerDone.Release(); } }); return(true); }; var conn = await Http2ConnectionUtils.BuildEstablishedConnection( true, iPipe, oPipe, loggerProvider, listener, localSettings : localSettings, remoteSettings : remoteSettings, huffmanStrategy : huffmanStrategy); var hEncoder = new Encoder(); await iPipe.WriteHeaders( hEncoder, 1, false, getHeaders); if (state == StreamState.HalfClosedRemote || state == StreamState.Closed) { await iPipe.WriteData(1u, 0, endOfStream : true); } var ok = await handlerDone.WaitAsync( Http2ReadableStreamTestExtensions.ReadTimeout); if (!ok) { throw new Exception("Stream handler did not finish"); } if (state == StreamState.HalfClosedLocal || state == StreamState.Closed) { // Consume the sent headers and data await oPipe.ReadAndDiscardHeaders(1u, true); } else if (state == StreamState.Reset) { // Consume the sent reset frame await oPipe.AssertResetStreamReception(1, ErrorCode.Cancel); } return(new Result { conn = conn, stream = stream, hEncoder = hEncoder, }); }
public static object Decode(ByteBuffer buffer) { return(Encoder.ReadDescribed(buffer, Encoder.ReadFormatCode(buffer))); }
public override object Deserialize(byte[] data, Type type) { try { using (XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(data, XmlDictionaryReaderQuotas.Max)) { DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type); object obj = dcjs.ReadObject(jsonReader); return(obj); } } catch (Exception ex) { logger.Error("JsonSerialize Deserialize Error! " + ex.Message + " json:" + Encoder.GetString(data) + " type:" + type.FullName); throw ex; } }
public OutputSettings() { _encoder = _encoding.GetEncoder(); }
public abstract string?TryEncode(Encoder encoder, out ConstantOffsets constantOffsets, out bool isOriginalInstruction);
//public static List<ErrorData> ErrorList { get; } = new List<ErrorData>(); /* * /// <summary> * /// Gets the can talon. * /// </summary> * /// <param name="id">The identifier.</param> * /// <returns></returns> * public static CanTalonData GetCanTalon(int id) * { * CanTalonData data; * bool retVal = s_canTalon.TryGetValue(id, out data); * if (retVal) * { * //Contains key. Just return it * return data; * } * else * { * //CAN Talon does not exist yet. Return null. * return null; * } * } * * /// <summary> * /// Initializes the can talon. * /// </summary> * /// <param name="id">The identifier.</param> * /// <returns></returns> * public static bool InitializeCanTalon(int id) * { * CanTalonData data; * bool retVal = s_canTalon.TryGetValue(id, out data); * if (retVal) * { * //Contains key. return false saying we did not initialize a new one. * return false; * } * else * { * //Create a new Can Talon data and return true. * data = new CanTalonData(); * s_canTalon.Add(id, data); * OnTalonSRXAddedOrRemoved?.Invoke(id, new TalonSRXEventArgs(true)); * return true; * } * } * * /// <summary> * /// Removes the can talon. * /// </summary> * /// <param name="id">The identifier.</param> * public static void RemoveCanTalon(int id) * { * s_canTalon.Remove(id); * OnTalonSRXAddedOrRemoved?.Invoke(id, new TalonSRXEventArgs(false)); * } * * /// <summary> * /// Gets the PCM. * /// </summary> * /// <param name="id">The identifier.</param> * /// <returns></returns> * public static PCMData GetPCM(int id) * { * PCMData data; * bool retVal = s_pcm.TryGetValue(id, out data); * if (retVal) * { * //Contains key. Just return it * return data; * } * else * { * data = new PCMData(); * s_pcm.Add(id, data); * OnPCMAdded?.Invoke(data, null); * return data; * } * } * * /// <summary> * /// Initializes the PCM. * /// </summary> * /// <param name="id">The identifier.</param> * /// <returns></returns> * public static bool InitializePCM(int id) * { * PCMData data; * bool retVal = s_pcm.TryGetValue(id, out data); * if (retVal) * { * //Contains key. return false saying we did not initialize a new one. * return false; * } * else * { * //Create a new PCM data and return true. * data = new PCMData(); * s_pcm.Add(id, data); * OnPCMAdded?.Invoke(data, null); * return true; * } * } * * /// <summary> * /// Gets the PDP. * /// </summary> * /// <param name="id">The identifier.</param> * /// <returns></returns> * public static PDPData GetPDP(int id) * { * PDPData data; * bool retVal = s_pdp.TryGetValue(id, out data); * if (retVal) * { * //Contains key. Just return it * return data; * } * else * { * data = new PDPData(); * s_pdp.Add(id, data); * OnPDPAdded?.Invoke(data, null); * return data; * } * } * * /// <summary> * /// Initializes a new PDP. * /// </summary> * /// <param name="id">The identifier.</param> * /// <returns>True if new PDP was created, otherwise false</returns> * public static bool InitializePDP(int id) * { * PDPData data; * bool retVal = s_pdp.TryGetValue(id, out data); * if (retVal) * { * //Contains key. return false saying we did not initialize a new one. * return false; * } * else * { * //Create a new PCM data and return true. * data = new PDPData(); * s_pdp.Add(id, data); * OnPDPAdded?.Invoke(data, null); * return true; * } * } * * /// <summary> * /// Occurs on talon SRX added or removed. * /// </summary> * public static event EventHandler<TalonSRXEventArgs> OnTalonSRXAddedOrRemoved; * /// <summary> * /// Occurs when a PCM is added. * /// </summary> * public static event EventHandler OnPCMAdded; * /// <summary> * /// Occurs when a PDP is added. * /// </summary> * public static event EventHandler OnPDPAdded; * */ static SimData() { for (int i = 0; i < HAL_GetNumPCMModules(); i++) { PCM.Add(new HALSimPCMData(i)); } for (int i = 0; i < HAL_GetNumPDPModules(); i++) { PDP.Add(new HALSimPDPData(i)); } for (int i = 0; i < HAL_GetNumAccumulators(); i++) { AnalogGyro.Add(new HALSimAnalogGyroData(i)); } for (int i = 0; i < HAL_GetNumAnalogOutputs(); i++) { AnalogOut.Add(new HALSimAnalogOutData(i)); } for (int i = 0; i < HAL_GetNumAnalogInputs(); i++) { AnalogIn.Add(new HALSimAnalogInData(i)); } for (int i = 0; i < HAL_GetNumAnalogTriggers(); i++) { AnalogTrigger.Add(new HALSimAnalogTriggerData(i)); } for (int i = 0; i < HAL_GetNumDigitalChannels(); i++) { DIO.Add(new HALSimDIOData(i)); } for (int i = 0; i < HAL_GetNumDigitalPWMOutputs(); i++) { DigitalPWM.Add(new HALSimDigitalPWMData(i)); } for (int i = 0; i < 4; i++) { //DigitalGlitchFilter.Add(new DigitalGlitchFilterData()); } for (int i = 0; i < HAL_GetNumPWMChannels(); i++) { PWM.Add(new HALSimPWMData(i)); } for (int i = 0; i < 4; i++) { Relay.Add(new HALSimRelayData(i)); } for (int i = 0; i < 8; i++) { //Counter.Add(new CounterData()); } for (int i = 0; i < 8; i++) { Encoder.Add(new HALSimEncoderData(i)); } for (int i = 0; i < 5; i++) { SPIAccelerometer.Add(new HALSimSPIAccelerometerData(i)); } for (int i = 0; i < 5; i++) { //SPIAccumulator.Add(new SPIAccumulatorData()); } //InitializePDP(0); //ErrorList.Clear(); }
internal void AppendEncodedChars(char[] data, int offset, int size, Encoder encoder, bool flushEncoder) { int num = encoder.GetBytes(data, offset, size, _data, _size - _free, flushEncoder); _free -= num; }
public void AmqpSerializerMapEncodingTest() { // serializer test { var specification = new ComputerSpecification() { Cores = 2, RamSize = 4, Description = "netbook" }; var product = new Product() { Name = "Computer", Price = 499.98, Weight = 30, Specification = specification, Category = Category.Electronic }; var buffer = new ByteBuffer(1024, true); AmqpSerializer.Serialize(buffer, product); Assert.AreEqual(product.Properties["OnSerializing"], "true"); Assert.AreEqual(product.Properties["OnSerialized"], "true"); var product2 = AmqpSerializer.Deserialize <Product>(buffer); Assert.AreEqual(product2.Properties["OnDeserializing"], "true"); Assert.AreEqual(product2.Properties["OnDeserialized"], "true"); Assert.AreEqual(product.Name, product2.Name); Assert.AreEqual(product.Price, product2.Price); Assert.AreEqual(product.Weight, product2.Weight); Assert.AreEqual(product.Category, product2.Category); var specification2 = product2.Specification as ComputerSpecification; Assert.IsTrue(specification2 != null); Assert.AreEqual(specification.Cores, specification2.Cores); Assert.AreEqual(specification.RamSize, specification2.RamSize); Assert.AreEqual(specification.Description, specification2.Description); } // serializer - amqp { var specification = new CarSpecification() { Engine = "V6", HorsePower = 239, Description = "SUV" }; var product = new Product() { Name = "Car", Price = 34998, Weight = 5500, Specification = specification }; var buffer = new ByteBuffer(1024, true); AmqpSerializer.Serialize(buffer, product); var value = Encoder.ReadObject(buffer) as DescribedValue; Assert.IsTrue(value != null); Assert.AreEqual(new Symbol("test.amqp:product"), value.Descriptor); var map = value.Value as Map; Assert.IsTrue(map != null); Assert.AreEqual(product.Name, map[new Symbol("Name")]); Assert.AreEqual(product.Price, map[new Symbol("Price")]); Assert.AreEqual(product.Weight, map[new Symbol("Weight")]); var specValue = map[new Symbol("Specification")] as DescribedValue; Assert.IsTrue(specValue != null); Assert.AreEqual(new Symbol("test.amqp:automotive-specification"), specValue.Descriptor); var specMap = specValue.Value as Map; Assert.IsTrue(specMap != null); Assert.AreEqual(specification.Engine, specMap[new Symbol("Engine")]); Assert.AreEqual(specification.HorsePower, specMap[new Symbol("HorsePower")]); Assert.AreEqual(specification.Description, specMap[new Symbol("Description")]); } // amqp - serializer (symbols keys) { // keys MUST be symbols or strings // the value types MUST match the field/property types in the class var specification = new DescribedValue( new Symbol("test.amqp:automotive-specification"), new Map() { { new Symbol("Engine"), "V8" }, { new Symbol("HorsePower"), 222 }, { new Symbol("Description"), "AWD SUV" }, }); var product = new DescribedValue( new Symbol("test.amqp:product"), new Map() { { new Symbol("Name"), "Car" }, { new Symbol("Price"), 41200.0 }, { new Symbol("Weight"), 5600L }, { new Symbol("Specification"), specification }, { new Symbol("Category"), (sbyte)Category.Automotive } }); var buffer = new ByteBuffer(1024, true); Encoder.WriteObject(buffer, product); var product2 = AmqpSerializer.Deserialize <Product>(buffer); Assert.AreEqual("Car", product2.Name); Assert.AreEqual(41200.0, product2.Price); Assert.AreEqual(5600L, product2.Weight); Assert.AreEqual(Category.Automotive, product2.Category); var specification2 = product2.Specification as CarSpecification; Assert.IsTrue(specification2 != null); Assert.AreEqual("V8", specification2.Engine); Assert.AreEqual(222, specification2.HorsePower); Assert.AreEqual("AWD SUV", specification2.Description); } // amqp - serializer (string keys) { // keys MUST be symbols or strings // the value types MUST match the field/property types in the class var specification = new DescribedValue( new Symbol("test.amqp:automotive-specification"), new Map() { { "Engine", "V8" }, { "HorsePower", 222 }, { "Description", "AWD SUV" }, }); var product = new DescribedValue( new Symbol("test.amqp:product"), new Map() { { "Name", "Car" }, { "Price", 41200.0 }, { "Weight", 5600L }, { "Specification", specification }, { "Category", (sbyte)Category.Automotive } }); var buffer = new ByteBuffer(1024, true); Encoder.WriteObject(buffer, product); var product2 = AmqpSerializer.Deserialize <Product>(buffer); Assert.AreEqual("Car", product2.Name); Assert.AreEqual(41200.0, product2.Price); Assert.AreEqual(5600L, product2.Weight); Assert.AreEqual(Category.Automotive, product2.Category); var specification2 = product2.Specification as CarSpecification; Assert.IsTrue(specification2 != null); Assert.AreEqual("V8", specification2.Engine); Assert.AreEqual(222, specification2.HorsePower); Assert.AreEqual("AWD SUV", specification2.Description); } }
public abstract void Encode(Encoder encoder, in Instruction instruction, int operand);
public void AmqpSerializerSimpleListEncodingTest() { // serializer test { var add = new ListAddOperation() { Version = 2, Name = "add", Param1 = 4, Param2 = 2 }; var buffer = new ByteBuffer(1024, true); AmqpSerializer.Serialize(buffer, add); var add2 = AmqpSerializer.Deserialize <ListAddOperation>(buffer); Assert.AreEqual(add2.Name, add.Name); Assert.AreEqual(add2.Version, add.Version); Assert.AreEqual(add2.Param1, add.Param1); Assert.AreEqual(add2.Param2, add.Param2); } // serializer - amqp { var sqrt = new ListSquareRootOperation() { Version = 3, Name = "sqrt", Param = 64 }; var buffer = new ByteBuffer(1024, true); AmqpSerializer.Serialize(buffer, sqrt); var list = Encoder.ReadObject(buffer) as List; Assert.IsTrue(list != null); Assert.AreEqual(sqrt.Version, list[0]); Assert.AreEqual(sqrt.Name, list[1]); Assert.AreEqual(sqrt.Param, list[2]); } // amqp - serializer { var list = new List() { 4, "multi-op", "Do add first and then SQRT", new Map() { { "Param1", 100 }, { "Param2", 200 } }, new Map() { { "Param", 81L } } }; var buffer = new ByteBuffer(1024, true); Encoder.WriteObject(buffer, list); var multi = AmqpSerializer.Deserialize <ListMultiOperation>(buffer); Assert.AreEqual(multi.Version, list[0]); Assert.AreEqual(multi.Name, list[1]); Assert.AreEqual(multi.Instruction, list[2]); var map1 = (Map)list[3]; Assert.AreEqual(multi.Add.Param1, map1["Param1"]); Assert.AreEqual(multi.Add.Param2, map1["Param2"]); var map2 = (Map)list[4]; Assert.AreEqual(multi.SquareRoot.Param, map2["Param"]); } }
public string Encrypt(string unencrypted) { byte[] buff = Encrypt(Encoder.GetBytes(unencrypted)); return(HttpServerUtility.UrlTokenEncode(buff)); }
public void AmqpSerializerSimpleMapEncodingTest() { // serializer test { var add = new AddOperation() { Version = 2, Name = "add", Param1 = 4, Param2 = 2 }; var buffer = new ByteBuffer(1024, true); AmqpSerializer.Serialize(buffer, add); var add2 = AmqpSerializer.Deserialize <AddOperation>(buffer); Assert.AreEqual(add2.Name, add.Name); Assert.AreEqual(add2.Version, add.Version); Assert.AreEqual(add2.Param1, add.Param1); Assert.AreEqual(add2.Param2, add.Param2); } // serializer - amqp { var sqrt = new SquareRootOperation() { Version = 3, Name = "sqrt", Param = 64 }; var buffer = new ByteBuffer(1024, true); AmqpSerializer.Serialize(buffer, sqrt); var map = Encoder.ReadObject(buffer) as Map; Assert.IsTrue(map != null); Assert.AreEqual(sqrt.Version, map["Version"]); Assert.AreEqual(sqrt.Name, map["Name"]); Assert.AreEqual(sqrt.Param, map["Param"]); } // amqp - serializer { var map = new Map() { { "Version", 4 }, { "Name", "multi-op" }, { "Instruction", "Do add first and then SQRT" }, { "Add", new Map() { { "Param1", 100 }, { "Param2", 200 } } }, { "SquareRoot", new Map() { { "Param", 81L } } }, }; var buffer = new ByteBuffer(1024, true); Encoder.WriteObject(buffer, map); var multi = AmqpSerializer.Deserialize <MultiOperation>(buffer); Assert.AreEqual(multi.Version, map["Version"]); Assert.AreEqual(multi.Name, map["Name"]); Assert.AreEqual(multi.Instruction, map["Instruction"]); var map1 = (Map)map["Add"]; Assert.AreEqual(multi.Add.Param1, map1["Param1"]); Assert.AreEqual(multi.Add.Param2, map1["Param2"]); var map2 = (Map)map["SquareRoot"]; Assert.AreEqual(multi.SquareRoot.Param, map2["Param"]); } }
public void Search(string username, string password) { //string search = "(&(uid="; /* Testing */ search = "(&(uid=" + username + ")(userPassword="******"))"; DirectorySearcher directorySearch1 = new DirectorySearcher { Filter = search }; directorySearch1.FindOne(); DirectorySearcher directorySearch2 = new DirectorySearcher("(&(uid=" + username + ")(userPassword="******"))"); directorySearch2.FindOne(); DirectorySearcher directorySearch3 = new DirectorySearcher("(&(uid=" + Encoder.LdapFilterEncode(username) + ")(userPassword="******"))"); directorySearch3.FindOne(); username = Encoder.LdapFilterEncode(username); password = Encoder.LdapFilterEncode(password); string search4 = "(&(uid=" + username + ")(userPassword="******"))"; DirectorySearcher directorySearch4 = new DirectorySearcher(search4); directorySearch4.Filter = "(&(uid=" + Encoder.LdapFilterEncode(username) + ")(userPassword="******"))"; directorySearch4.FindAll(); }
/// <summary> /// Visual Basic Script 문을 동적으로 생성시, script 코드 내용을 vb script 문법에 맞게끔 인코딩한다. /// </summary> /// <param name="value">대상 문자열</param> /// <returns>Visual Basic Script 로 인코딩한 문자열</returns> public static string VBScriptEncode(this string value) { return(Encoder.VisualBasicScriptEncode(value)); }