/// <summary> /// Function called to handle the reading of the stream /// </summary> /// <param name="stm">The reading stream</param> protected override void OnRead(PipelineStream stm) { try { while (!stm.Eof) { DynamicStreamDataKey2 key = new DynamicStreamDataKey2("Root", Container, Graph.Logger, State); DataReader reader = new DataReader(stm); key.FromReader(reader); // Only fill in the frame if we read something, should this exit if it continues to read nothing? if (reader.ByteCount > 0) { WriteOutput(new DataFrame(key)); } } } catch (ThreadAbortException) { throw; } catch (EndOfStreamException) { // End of stream, do nothing } catch (Exception e) { LogException(e); } }
public void GetDayLineTest() { DataReader dataReader = new DataReader(); dataReader.AnalyseDayLineFiles(new[] { TestData.ShanghaiDay, TestData.ShenzhenDay }); IKlineData klineData = dataReader.GetDaylineData("432534", DateTime.MinValue); Assert.IsNull(klineData); }
public override void Populate(DataReader dataReader) { base.Populate(dataReader); Nivel = dataReader.GetValue<int>("p_Nivel"); Descricao = dataReader.GetValue<string>("p_Descricao"); }
public static void IndexUimfFile(string uimfFileLocation) { bool indexed = false; using (var uimfReader = new DataReader(uimfFileLocation)) { if (uimfReader.DoesContainBinCentricData()) { indexed = true; Console.WriteLine("Bin centric data found in dataset {0}.", uimfFileLocation); } else { Console.WriteLine("No bin centric data found for file {0}.", uimfFileLocation); } uimfReader.Dispose(); } if (!indexed) { Console.WriteLine("Creating bin centric data for {0}.", uimfFileLocation); using (DataWriter dataWriter = new DataWriter(uimfFileLocation)) { dataWriter.CreateBinCentricTables(); dataWriter.Dispose(); } } }
private void learnFormAssetBundle(string path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); DataReader br = new DataReader(fs); SerializeBundle bundle = new SerializeBundle(); bundle.DeSerialize(br); foreach (var bundleEntry in bundle.entrys) { int version = AssetToolUtility.GetAssetsFileVersion(bundleEntry.assetData); var serializeAssets = SerializeAssetFactory.CreateWithVersion(version); if (serializeAssets != null) { MemoryStream ms = new MemoryStream(bundleEntry.assetData); DataReader dr = new DataReader(ms); serializeAssets.DeSerialize(dr); var assetTypeTreeDB = AssetToolUtility.GenerateTypeTreeDataBase(serializeAssets); if (assetTypeTreeDB != null) { var allType = assetTypeTreeDB.GetAllType(version); foreach (var type in allType) { Console.WriteLine("AddType:Version:{0},ClassID{1},Name:{2}", version, type.Key, type.Value.type); } } typeTreeDatabase = assetTypeTreeDB.Merage(typeTreeDatabase); } else { Debug.LogError("can't deserialize bundle entry " + bundleEntry.name); } fs.Dispose(); } }
public DomainParticipantTransportSource(DomainParticipant participant, string senderTopic, string receiverTopic) { _participant = participant; var senderTopicQos = new TopicQos(); participant.get_default_topic_qos(senderTopicQos); var receiverTopicQos = new TopicQos(); participant.get_default_topic_qos(receiverTopicQos); _sender = participant.create_topic(senderTopic, BytesTypeSupport.TYPENAME, senderTopicQos, null, StatusMask.STATUS_MASK_NONE); _receiver = participant.create_topic(receiverTopic, BytesTypeSupport.TYPENAME, receiverTopicQos, null, StatusMask.STATUS_MASK_NONE); var writerQos = new DataWriterQos(); //writerQos.publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS; writerQos.publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME; participant.get_default_datawriter_qos(writerQos); var readerQos = new DataReaderQos(); participant.get_default_datareader_qos(readerQos); _writer = participant.create_datawriter(_sender, writerQos, null, StatusMask.STATUS_MASK_NONE); _reader = participant.create_datareader(_receiver, readerQos, this, StatusMask.STATUS_MASK_ALL); }
/// <summary> /// Método utilizado para preencher esta instância com os dados do dataReader /// </summary> /// <param name="dataReader">DataReader com os dados que deverão ser passados para esta instância</param> public override void Populate(DataReader dataReader) { base.Populate(dataReader); Descricao = dataReader.GetValue<String>("p_Descricao"); Administrador = dataReader.GetValue<Boolean>("p_Administrador"); }
public void Generate(XElement startTableElement, XElement endTableElement, DataReader dataReader) { var coreParser = new CoreTableParser(true); var tag = coreParser.Parse(startTableElement, endTableElement); var processor = new TableProcessor() { DataReader = dataReader, TableTag = tag }; processor.Process(); }
/// <summary> /// Método utilizado para preencher esta instância com os dados do dataReader /// </summary> /// <param name="dataReader">DataReader com os dados que deverão ser passados para esta instância</param> public override void Populate(DataReader dataReader) { #region base base.Populate(dataReader); #endregion #region desta classe Descricao = dataReader.GetValue<string>("p_Descricao"); #region Filtros Filtros = new TributoRegraFiltro().Find<ITributoRegraFiltro, ITributoRegra>(new Where() { {"cad_TributoRegraFiltro.GUIDTributoRegra", GUID.ToString() } }, this); #endregion #region Aliquotas Aliquotas = new TributoRegraAliquota().Find<ITributoRegraAliquota, ITributoRegra>(new Where() { {"cad_TributoRegraAliquota.GUIDTributoRegra",GUID.ToString() } }, this); #endregion #endregion }
/// <summary> /// Constructor /// </summary> public UdgerParser() { dt = new DataReader(); this.ua = ""; this.ip = ""; }
public void GetDividendDataTest() { DataReader dataReader = new DataReader(); dataReader.AnalyseDividendFile(TestData.DividendFile); IDividendData info = dataReader.GetDividendData("432534", DateTime.MinValue); Assert.IsNull(info); }
public FeatureSet GetFeatures(int targetBin, DataReader.FrameType frameType) { List<IntensityPoint> intensityPointList = _uimfUtil.GetXic(targetBin, frameType); var features = new FeatureSet(intensityPointList); return features; }
internal HttpResponseHeader(DataReader reader, IEnumerable<KeyDataPair<string>> headers, int responseCode, string message, HttpVersion version) { _reader = reader; Headers = new List<KeyDataPair<string>>(headers); ResponseCode = responseCode; Message = message; Version = version; if (ResponseCode != 304) { ContentLength = HttpParser.GetContentLength(Headers); ChunkedEncoding = HttpParser.IsChunkedEncoding(Headers); HasBody = true; } // Always trust a content-length if it exists if (Headers.Count(p => p.Name.Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) == 0) { // Otherwise if version unknown, 1.0 or connection will close set then indicate we will read to the end if (Version.IsVersionUnknown || Version.IsVersion10 || (Headers.Count(p => p.Name.Equals("Connection", StringComparison.OrdinalIgnoreCase) && p.Value.Equals("close", StringComparison.OrdinalIgnoreCase)) > 0)) { ReadToEnd = true; } } }
public static AlternateStreamEntry ReadFrom(DataReader reader) { long startPos = reader.Position; long length = reader.ReadInt64(); if (length == 0) { return null; } reader.Skip(8); AlternateStreamEntry result = new AlternateStreamEntry(); result.Length = length; result.Hash = reader.ReadBytes(20); int nameLength = reader.ReadUInt16(); if (nameLength > 0) { result.Name = Encoding.Unicode.GetString(reader.ReadBytes(nameLength + 2)).TrimEnd('\0'); } else { result.Name = string.Empty; } if (startPos + length > reader.Position) { int toRead = (int)(startPos + length - reader.Position); reader.Skip(toRead); } return result; }
public MemberMap(DataReader reader) { Id = reader.ReadInt16(); Name = reader.ReadString(); DbType = DbType.Read(reader); MemberType = DbType.Type; }
public FeatureSet GetFeatures(double mz, Tolerance tolerance, DataReader.FrameType frameType) { var intensityBlock = _uimfUtil.GetXic(mz, tolerance.GetValue(), frameType, tolerance.GetUnit() == ToleranceUnit.Ppm ? DataReader.ToleranceType.PPM : DataReader.ToleranceType.Thomson); var features = new FeatureSet(intensityBlock); return features; }
private void ProcessItemRepeaterElement(RepeaterElement itemRepeaterElement, DataReader reader, int index, XElement previous) { var readers = reader.GetReaders(itemRepeaterElement.Expression); var itemRepeaterTag = GenerateItemRepeaterTag(itemRepeaterElement); var parser = new ItemRepeaterParser(); parser.Parse(itemRepeaterTag, readers.ToList()); }
public override void Populate(DataReader dataReader) { base.Populate(dataReader); Nivel = 1; Descricao = dataReader.GetValue<string>("p_Descricao"); Regras = new NivelAcessoRegra().Find<INivelAcessoRegra>("cad_NivelAcessoRegra.GUIDNivelAcesso", GUID.ToString()); }
/// <summary> /// 角色实体数据映射 /// </summary> /// <param name="reader"></param> /// <returns></returns> public static TeamRole Role_Map(DataReader reader) { TeamRole role = new TeamRole(reader.GetString("RoleID"), reader.GetStringNullable("RoleName")) { RoleDescription = reader.GetString("Description") }; return role; }
public DataReader ExecuteReader() { var cursor = MongoConnection.MongoDatabase.GetCollection(CollectionName).FindAll(); Result result = new Result(cursor); ResultSet resultSet = new ResultSet(); resultSet.Add(result); DataReader reader = new DataReader(resultSet); return reader; }
public DataLinker(DataManagerSettings settings, DataReader reader, DataSaver saver, DataUpdater updater, DataChecker checker, EntityLinker linker) { Settings = settings; Linker = linker; Reader = reader; Saver = saver; Updater = updater; Checker = checker; }
protected override void LoadBody(IDataReader reader, IMessage message) { Console.WriteLine("Receive Data length:" + reader.Length); using (GZipStream compStream = new GZipStream((Stream)reader, CompressionMode.Decompress)) { DataReader dw = new DataReader(compStream, reader.LittleEndian); base.LoadBody(dw, message); } }
/// <summary> /// 角色实体数据映射 /// </summary> /// <param name="reader"></param> /// <returns></returns> private static UserRoleMap UsersInRoles_Map(DataReader reader) { UserRoleMap usersinroles = new UserRoleMap() { UserID = reader.GetString("UserID"), RoleID = reader.GetString("RoleID") }; return usersinroles; }
public static void Main(String[] args) { String filename = "../../../../examples/data/openshop_default.data"; int failLimit = 10000; if (args.Length > 0) filename = args[0]; if (args.Length > 1) failLimit = Convert.ToInt32(args[1]); CP cp = new CP(); DataReader data = new DataReader(filename); int nbJobs = data.Next(); int nbMachines = data.Next(); List<IIntervalVar>[] jobs = new List<IIntervalVar>[nbJobs]; for (int i = 0; i < nbJobs; i++) jobs[i] = new List<IIntervalVar>(); List<IIntervalVar>[] machines = new List<IIntervalVar>[nbMachines]; for (int j = 0; j < nbMachines; j++) machines[j] = new List<IIntervalVar>(); List<IIntExpr> ends = new List<IIntExpr>(); for (int i = 0; i < nbJobs; i++) { for (int j = 0; j < nbMachines; j++) { int pt = data.Next(); IIntervalVar ti = cp.IntervalVar(pt); jobs[i].Add(ti); machines[j].Add(ti); ends.Add(cp.EndOf(ti)); } } for (int i = 0; i < nbJobs; i++) cp.Add(cp.NoOverlap(jobs[i].ToArray())); for (int j = 0; j < nbMachines; j++) cp.Add(cp.NoOverlap(machines[j].ToArray())); IObjective objective = cp.Minimize(cp.Max(ends.ToArray())); cp.Add(objective); cp.SetParameter(CP.IntParam.FailLimit, failLimit); Console.WriteLine("Instance \t: " + filename); if (cp.Solve()) { Console.WriteLine("Makespan \t: " + cp.ObjValue); } else { Console.WriteLine("No solution found."); } }
/// <summary> /// Método utilizado para preencher esta instância com os dados do dataReader /// </summary> /// <param name="dataReader">DataReader com os dados que deverão ser passados para esta instância</param> public override void Populate(DataReader dataReader) { #region base base.Populate(dataReader); #endregion #region desta classe Nome = dataReader.GetValue<string>("p_Nome"); #endregion }
// Populate a datakey with data from a stream public void FromReader(DataReader reader, DataKey root, Logger logger) { // Read up to five bytes and reverse them byte[] data = reader.ReadBytes(5, false).Reverse().ToArray(); logger.LogInfo("Read {0} bytes from stream", data.Length); // Add to key root.AddValue("data", data); }
/// <summary> /// Método utilizado para preencher esta instância com os dados do dataReader /// </summary> /// <param name="dataReader">DataReader com os dados que deverão ser passados para esta instância</param> public override void Populate(DataReader dataReader) { #region base base.Populate(dataReader); #endregion #region desta classe DataMovimentacao = dataReader.GetValue<DateTime>("p_DataMovimentacao"); #endregion }
/// <summary> /// Método utilizado para preencher esta instância com os dados do dataReader /// </summary> /// <param name="dataReader">DataReader com os dados que deverão ser passados para esta instância</param> public override void Populate(DataReader dataReader) { #region base base.Populate(dataReader); #endregion #region desta classe Impressora = new Impressora(dataReader.GetValue<string>("p_GUIDImpressora")); #endregion }
/// <summary> /// 角色实体数据映射 /// </summary> /// <param name="reader"></param> /// <returns></returns> public static UserBind UserBind_Map(DataReader reader) { return new UserBind() { ID = reader.GetString("ID"), UserID = reader.GetString("UserID"), BindID = reader.GetStringNullable("BindID"), BindProvider = reader.GetStringNullable("BindProvider"), }; }
private void ProcessItemIfElement(RepeaterElement ifElement, DataReader dataReader, ref XElement endIfElement) { var expression = ifElement.Expression; var condition = bool.Parse(dataReader.ReadText(expression)); if (!condition) { endIfElement = ifElement.EndTag; } }
/// <summary> /// Turns this into an excel data reader /// </summary> /// <returns></returns> private SimpleColumnInfo[] HeaderInformation() { if (_firstRead == false) { return(_cols); } _firstRead = false; var first = true; var cols = new List <SimpleColumnInfo>(); //if not using header rows then just generate new names, don't bother reading from the reader. if (_configuration.UseHeaderRow == false) { for (var i = 0; i < DataReader.FieldCount; i++) { var name = _configuration.EmptyColumnNamePrefix + i; // if a column already exists with the name append _i to the duplicates var columnName = GetUniqueColumnName(cols, name); var column = new SimpleColumnInfo { ColumnName = columnName, ColumnDescription = name, Index = i }; cols.Add(column); } } else { //otherwise yes we are finding a header row to apply if (_configuration.UseHeaderRow && _configuration.ReadHeaderRow != null) { _configuration.ReadHeaderRow(DataReader); } else if (_configuration.UseHeaderRow) { var headerRows = _configuration.HeaderRow; for (int i = 0; i < headerRows; i++) { DataReader.Read(); } } for (var i = 0; i < DataReader.FieldCount; i++) { var name = Convert.ToString(DataReader.GetValue(i)); if (string.IsNullOrEmpty(name)) { name = _configuration.EmptyColumnNamePrefix + i; } // if a column already exists with the name append _i to the duplicates var columnName = GetUniqueColumnName(cols, name); var column = new SimpleColumnInfo { ColumnName = columnName, ColumnDescription = name, Index = i }; cols.Add(column); } } _cols = cols.ToArray(); return(_cols); }
public bool TryCreateBodyReader(uint bodyRva, uint mdToken, out DataReader reader) { reader = default; // bodyRva can be 0 if it's a dynamic module. this.module.Address will also be 0. if (!module.IsDynamic && bodyRva == 0) { return(false); } var func = module.CorModule.GetFunctionFromToken(mdToken); var ilCode = func?.ILCode; if (ilCode is null) { return(false); } Debug2.Assert(func is not null); ulong addr = ilCode.Address; if (addr == 0) { return(false); } Debug.Assert(addr >= FAT_HEADER_SIZE); if (addr < FAT_HEADER_SIZE) { return(false); } if (module.IsDynamic) { // It's always a fat header, see COMDynamicWrite::SetMethodIL() (coreclr/src/vm/comdynamic.cpp) addr -= FAT_HEADER_SIZE; var procReader = new ProcessBinaryReader(new CorProcessReader(module.Process), 0); Debug.Assert((procReader.Position = (long)addr) == (long)addr); Debug.Assert((procReader.ReadByte() & 7) == 3); Debug.Assert((procReader.Position = (long)addr + 4) == (long)addr + 4); Debug.Assert(procReader.ReadUInt32() == ilCode.Size); procReader.Position = (long)addr; reader = new DataReader(new ProcessDataStream(procReader), 0, uint.MaxValue); return(true); } else { uint codeSize = ilCode.Size; // The address to the code is returned but we want the header. Figure out whether // it's the 1-byte or fat header. var procReader = new ProcessBinaryReader(new CorProcessReader(module.Process), 0); uint locVarSigTok = func.LocalVarSigToken; bool isBig = codeSize >= 0x40 || (locVarSigTok & 0x00FFFFFF) != 0; if (!isBig) { procReader.Position = (long)addr - 1; byte b = procReader.ReadByte(); var type = b & 7; if ((type == 2 || type == 6) && (b >> 2) == codeSize) { // probably small header isBig = false; } else { procReader.Position = (long)addr - (long)FAT_HEADER_SIZE + 4; uint headerCodeSize = procReader.ReadUInt32(); uint headerLocVarSigTok = procReader.ReadUInt32(); bool valid = headerCodeSize == codeSize && (locVarSigTok & 0x00FFFFFF) == (headerLocVarSigTok & 0x00FFFFFF) && ((locVarSigTok & 0x00FFFFFF) == 0 || locVarSigTok == headerLocVarSigTok); Debug.Assert(valid); if (!valid) { return(false); } isBig = true; } } procReader.Position = (long)addr - (long)(isBig ? FAT_HEADER_SIZE : 1); reader = new DataReader(new ProcessDataStream(procReader), 0, uint.MaxValue); return(true); } }
public virtual void Load(Stream stream) { stream.Position = 0; var reader = new DataReader(stream, Endianess.BigEndian); while (reader.Position < reader.Length) { var identInt = reader.ReadUInt32(); var ident = (PsoSection)identInt; var length = reader.ReadInt32(); reader.Position -= 8; var sectionData = reader.ReadBytes(length); var sectionStream = new MemoryStream(sectionData); var sectionReader = new DataReader(sectionStream, Endianess.BigEndian); switch (ident) { case PsoSection.PSIN: DataSection = new PsoDataSection(); DataSection.Read(sectionReader); break; case PsoSection.PMAP: DataMappingSection = new PsoDataMappingSection(); DataMappingSection.Read(sectionReader); break; case PsoSection.PSCH: DefinitionSection = new PsoDefinitionSection(); DefinitionSection.Read(sectionReader); break; case PsoSection.STRF: STRFSection = new PsoSTRFSection(); STRFSection.Read(sectionReader); break; case PsoSection.STRS: STRSSection = new PsoSTRSSection(); STRSSection.Read(sectionReader); break; case PsoSection.STRE: STRESection = new PsoSTRESection(); STRESection.Read(sectionReader); break; case PsoSection.PSIG: PSIGSection = new PsoPSIGSection(); PSIGSection.Read(sectionReader); break; case PsoSection.CHKS: CHKSSection = new PsoCHKSSection(); CHKSSection.Read(sectionReader); break; default: break; } } }
private async void ConnectToTape(DeviceInformation device) { if (device == null) { return; // Nothing useful here } var myTape = await GattDeviceService.FromIdAsync(device.Id); myTape.Device.ConnectionStatusChanged += Device_ConnectionStatusChanged; if (myTape.Device.ConnectionStatus == Windows.Devices.Bluetooth.BluetoothConnectionStatus.Connected) { foreach (var s in myTape.Device.GattServices) { // TODO: Clean the service Uuid thing if (!s.Uuid.ToString().StartsWith("23455100-")) { continue; // Not the right service } foreach (var s2 in s.GetAllCharacteristics()) { var c = s2.Uuid.ToString(); if (c.StartsWith("23455107-")) { // Tape configuration var r = await s2.ReadValueAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached); var b = DataReader.FromBuffer(r.Value); var bytes = new byte[b.UnconsumedBufferLength]; b.ReadBytes(bytes); var bits = new BitArray(bytes); if (_currentConfiguration.Length > 0) { _currentConfiguration += "\n"; } _currentConfiguration += "eTape16 Bluetooth\n" + $" Battery low: {bits[15]}\n" + $" Inside measurement: {bits[14]}\n" + $" Offset measurement: {bits[13]}\n" + $" Centerline: {bits[12]}\n" + $" Display units: {(bits[2] ? "Metric" : (bits[0] && bits[1] ? "Decimal feet" : (bits[1] ? "Decimal inches" : (bits[0] ? "Fractional inches" : "Feet and inches"))))}\n\n" + "The application uses Metric and ignores all the other settings from this tape. The information displayed was received when connecting to the tape and it might not be updated."; } if (c.StartsWith("23455102-")) { if (s2.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { buttonConnect.Icon = new SymbolIcon(Symbol.FourBars); }); if ((_currentDevice == null) || (_currentDevice.Uuid != s2.Uuid)) { _currentDevice = s2; _currentDevice.ValueChanged += S_ValueChanged; } //break; } } } } } }
public async Task <bool> Connect() { bool bOK = false; string msg = string.Empty; try { var devices = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector( RfcommServiceId.SerialPort)); if (devices.Count > 0) { lock (this) { if (_socket != null && _socket.Information.LocalAddress == null) { //Old socket is sad. Finish it off Disconnect("Socket was abandoned."); } if (_socket == null) { _socket = new StreamSocket(); _socket.Control.KeepAlive = true; //Kill the old stream reader _socketReader = null; //_socket.Control.QualityOfService = SocketQualityOfService.LowLatency; } } var device = devices.Single(x => x.Name == BluetoothDeviceName); if (_service == null) { _service = await RfcommDeviceService.FromIdAsync(device.Id); } //if (_listener == null) //{ // //To listen for a connection on the StreamSocketListener object, an app must assign the ConnectionReceived event to an // //event handler and then call either the BindEndpointAsync or BindServiceNameAsync method to bind the StreamSocketListener // //to a local service name or TCP port on which to listen.To listen for Bluetooth RFCOMM, the bind is to the Bluetooth Service ID. // _listener = new StreamSocketListener(); // _listener.ConnectionReceived += _listener_ConnectionReceived; // //If you get an "Access is denied" error on this next line, be sure to set PrivateNetworkClientServer capability in the app manifest // await _listener.BindServiceNameAsync(_service.ServiceId.AsString()); //} try { await _socket.ConnectAsync( _service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); //_socketReader = new DataReader(_socket.InputStream); //_socketWriter = new DataWriter(_socket.OutputStream); //start the receive loop. Runs as an asyc task... ReceiveLoop(); bOK = true; } catch (Exception ex) when((uint)ex.HResult == 0x80070490) // ERROR_ELEMENT_NOT_FOUND { msg += "Please verify that you are connecting to the Camera Slider."; } catch (Exception ex) when((uint)ex.HResult == 0x80072740) // WSAEADDRINUSE { msg += "Please verify that there is no other RFCOMM connection to the same device."; } catch (Exception ex) when((uint)ex.HResult == 0x800710DF) { msg += "Make sure your Bluetooth Radio is on: " + ex.Message; } } else { msg += "No serial port devices found."; } } catch (Exception ex) { msg += ex.Message; FireCommError(msg); } return(bOK); }
public async void Disconnect(string disconnectReason) { string msg = string.Empty; try { if (_listener != null) { _listener.Dispose(); } } catch (Exception ex) { msg += "Disposing _listener: " + ex.Message; } try { if (_socketWriter != null) { try { _socketWriter.DetachStream(); } catch (Exception exDetachWriter) { msg += "Detaching _socketWriter: " + exDetachWriter.Message; } try { _socketWriter.Dispose(); } catch (Exception exDisposeWriter) { msg += "Disposing _socketWriter: " + exDisposeWriter.Message; } _socketWriter = null; } } catch (Exception ex) { msg += "General error Disposing _socketWriter: " + ex.Message; } try { if (_socketReader != null) { try { _socketReader.DetachStream(); } catch (Exception exDetachReader) { msg += "Detaching _socketReader: " + exDetachReader.Message; } try { _socketReader.Dispose(); } catch (Exception exDisposeReader) { msg += "Disposing _socketReader: " + exDisposeReader.Message; } _socketReader = null; } } catch (Exception ex) { msg += "General error Disposing _socketReader: " + ex.Message; } try { if (_socket != null) { try { await _socket.CancelIOAsync(); } catch (Exception exCancelIO) { msg += "Cancelling _socket IO: " + exCancelIO.Message; } _socket.Dispose(); _socket = null; } } catch (Exception ex) { msg += "Disposing _socket: " + ex.Message; } try { if (_service != null) { _service.Dispose(); _service = null; } } catch (Exception ex) { msg += "Disposing _service: " + ex.Message; } FireCommInfoMessage("Disconnected. " + disconnectReason + " " + msg); }
public GameItemVestAsset(DataReader data, DataReader local, string dirName, string name, ushort id, Guid guid, string type, EGameAssetOrigin origin) : base(data, local, dirName, name, id, guid, type, origin) { }
/// <summary> /// Constructor /// </summary> /// <param name="stream">The stream whose data will be copied to the new metadata file</param> public DataReaderHeap(DotNetStream stream) { OptionalOriginalStream = stream ?? throw new ArgumentNullException(nameof(stream)); heapReader = stream.CreateReader(); Name = stream.Name; }
private void WriteStructureContentXml(RbfStructure value, XmlWriter writer) { foreach (var child in value.Children) { if (child is RbfBytes) { var bytesChild = (RbfBytes)child; var contentField = (RbfString)null; foreach (var xyz in value.Children) { if (xyz.Name != null && xyz.Name.Equals("content")) { contentField = (RbfString)xyz; } } if (contentField != null) { if (contentField.Value.Equals("char_array")) { var sb = new StringBuilder(); sb.AppendLine(""); foreach (var k in bytesChild.Value) { sb.AppendLine(k.ToString()); } writer.WriteString(sb.ToString()); } else if (contentField.Value.Equals("short_array")) { var sb = new StringBuilder(); var valueReader = new DataReader(new MemoryStream(bytesChild.Value)); while (valueReader.Position < valueReader.Length) { var y = valueReader.ReadUInt16(); sb.AppendLine(y.ToString()); } writer.WriteString(sb.ToString()); } else { throw new Exception("Unexpected content type"); } } else { string stringValue = Encoding.ASCII.GetString(bytesChild.Value); writer.WriteString(stringValue.Substring(0, stringValue.Length - 1)); } } if (child is RbfFloat) { writer.WriteStartElement(child.Name); var floatChild = (RbfFloat)child; var s1 = string.Format(CultureInfo.InvariantCulture, "{0:0.0###########}", floatChild.Value); writer.WriteAttributeString("value", s1); writer.WriteEndElement(); } if (child is RbfString) { var stringChild = (RbfString)child; if (stringChild.Name.Equals("content")) { writer.WriteAttributeString("content", stringChild.Value); } else if (stringChild.Name.Equals("type")) { writer.WriteAttributeString("type", stringChild.Value); } else { throw new Exception("Unexpected string content"); } } if (child is RbfStructure) { writer.WriteStartElement(child.Name); WriteStructureContentXml((RbfStructure)child, writer); writer.WriteEndElement(); } if (child is RbfUint32) { var intChild = (RbfUint32)child; writer.WriteStartElement(child.Name); writer.WriteAttributeString("value", "0x" + intChild.Value.ToString("X8")); writer.WriteEndElement(); } if (child is RbfBoolean) { var booleanChild = (RbfBoolean)child; writer.WriteStartElement(child.Name); writer.WriteAttributeString("value", booleanChild.Value ? "true" : "false"); writer.WriteEndElement(); } if (child is RbfFloat3) { writer.WriteStartElement(child.Name); var floatVectorChild = (RbfFloat3)child; var s1 = string.Format(CultureInfo.InvariantCulture, "{0:0.0###########}", floatVectorChild.X); var s2 = string.Format(CultureInfo.InvariantCulture, "{0:0.0###########}", floatVectorChild.Y); var s3 = string.Format(CultureInfo.InvariantCulture, "{0:0.0###########}", floatVectorChild.Z); writer.WriteAttributeString("x", s1); writer.WriteAttributeString("y", s2); writer.WriteAttributeString("z", s3); writer.WriteEndElement(); } } }
private async Task ProcessImage(SoftwareBitmap image) { try { Func <Task <Stream> > imageStreamCallback; using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetSoftwareBitmap(image); await encoder.FlushAsync(); // Read the pixel bytes from the memory stream using (var reader = new DataReader(stream.GetInputStreamAt(0))) { var bytes = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(bytes); imageStreamCallback = () => Task.FromResult <Stream>(new MemoryStream(bytes)); } } Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ComputerVisionClient visionClient = new Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ComputerVisionClient( new Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ApiKeyServiceClientCredentials(settings.ComputerVisionKey), new System.Net.Http.DelegatingHandler[] { }); // Create a prediction endpoint, passing in the obtained prediction key CustomVisionPredictionClient customVisionClient = null; if (!string.IsNullOrEmpty(settings.CustomVisionKey)) { customVisionClient = new CustomVisionPredictionClient(new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.ApiKeyServiceClientCredentials(settings.CustomVisionKey), new System.Net.Http.DelegatingHandler[] { }) { Endpoint = $"https://{settings.CustomVisionRegion}.api.cognitive.microsoft.com" }; } Microsoft.Azure.CognitiveServices.Vision.Face.FaceClient faceClient = new Microsoft.Azure.CognitiveServices.Vision.Face.FaceClient( new Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ApiKeyServiceClientCredentials(settings.FaceKey), new System.Net.Http.DelegatingHandler[] { }); visionClient.Endpoint = settings.ComputerVisionEndpoint; faceClient.Endpoint = settings.FaceEndpoint; List <Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models.VisualFeatureTypes?> features = new List <VisualFeatureTypes?>() { VisualFeatureTypes.Categories, VisualFeatureTypes.Description, VisualFeatureTypes.Tags, VisualFeatureTypes.Faces, VisualFeatureTypes.Brands }; // The list of Face attributes to return. IList <FaceAttributeType> faceAttributes = new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Emotion, FaceAttributeType.Glasses, FaceAttributeType.Hair }; try { if (!imageAnalysisRunning && DateTime.Now.Subtract(imageAnalysisLastDate).TotalMilliseconds > 1000) { imageAnalysisRunning = true; _ = Task.Run(async() => { ImageAnalysis analysis = await visionClient.AnalyzeImageInStreamAsync(await imageStreamCallback(), features); ImagePrediction analysisCV = null; try { if (customVisionClient != null) { analysisCV = await customVisionClient.DetectImageWithNoStoreAsync(new Guid(settings.CustomVisionProjectId), settings.CustomVisionIterationName, await imageStreamCallback()); } } catch (Exception) { // Throw away error } UpdateWithAnalysis(analysis, analysisCV); imageAnalysisLastDate = DateTime.Now; imageAnalysisRunning = false; }); } var analysisFace = await faceClient.Face.DetectWithStreamWithHttpMessagesAsync(await imageStreamCallback(), returnFaceId : true, returnFaceAttributes : faceAttributes); imageWidth = image.PixelWidth; imageHeight = image.PixelHeight; facesControl.UpdateEvent(new CognitiveEvent() { Faces = analysisFace.Body, ImageWidth = image.PixelWidth, ImageHeight = image.PixelHeight }); if (analysisFace.Body.Count() > 0 && settings.DoFaceDetection) { var groups = await faceClient.PersonGroup.ListWithHttpMessagesAsync(); var group = groups.Body.FirstOrDefault(x => x.Name == settings.GroupName); if (group != null) { var results = await faceClient.Face.IdentifyWithHttpMessagesAsync(analysisFace.Body.Select(x => x.FaceId.Value).ToArray(), group.PersonGroupId); foreach (var identifyResult in results.Body) { var cand = identifyResult.Candidates.FirstOrDefault(x => x.Confidence > settings.FaceThreshold / 100d); if (cand == null) { Console.WriteLine("No one identified"); } else { // Get top 1 among all candidates returned var candidateId = cand.PersonId; var person = await faceClient.PersonGroupPerson.GetWithHttpMessagesAsync(group.PersonGroupId, candidateId); tagsControl.UpdateEvent(new CognitiveEvent() { IdentifiedPerson = person.Body, IdentifiedPersonPrediction = cand.Confidence }); Console.WriteLine("Identified as {0}", person.Body.Name); } } } } } catch (Exception) { // Eat exception } } catch (Exception) { // eat this exception too } }
public void RefreshUI(GangFightBattleResult gfbr) { if (gfbr == null) { return; } this.ImageWinsDefeatRight.get_gameObject().SetActive(false); this.ImageWinsDefeatLeft.get_gameObject().SetActive(false); this.TextAllLose.get_gameObject().SetActive(false); AvatarModel avatarModel = DataReader <AvatarModel> .Get(EntityWorld.Instance.EntSelf.FixModelID); if (avatarModel != null) { ResourceManager.SetSprite(this.ImageHeadLeft, GameDataUtils.GetIcon(avatarModel.pic)); } AvatarModel avatarModel2 = DataReader <AvatarModel> .Get(GangFightManager.Instance.gangFightMatchRoleSummary.modelId); if (avatarModel2 != null) { ResourceManager.SetSprite(this.ImageHeadRight, GameDataUtils.GetIcon(avatarModel2.pic)); } this.SetRewardItems(gfbr.reward, gfbr.rewardExt); if (gfbr.winnerId == 0L) { this.ShowLoseUIs(); this.TextNameLeft.set_text(EntityWorld.Instance.EntSelf.Name); this.TextNumLeft.set_text(gfbr.fromCurrCombatWinCount + GameDataUtils.GetChineseContent(510108, false)); this.TextNumRight.set_text(gfbr.toCurrCombatWinCount + GameDataUtils.GetChineseContent(510108, false)); this.TextNameRight.set_text(gfbr.toName); if (gfbr.fromLastCombatWinCount > 1) { this.ImageWinsDefeatLeft.get_gameObject().SetActive(true); } if (gfbr.toLastCombatWinCount > 1) { this.ImageWinsDefeatRight.get_gameObject().SetActive(true); } this.ImageDefeatLeft.get_gameObject().SetActive(false); this.ImageDefeatRight.get_gameObject().SetActive(false); this.TextAllLose.get_gameObject().SetActive(true); this.TextSelfLose.get_gameObject().SetActive(false); } else { bool flag = false; if (gfbr.winnerId == EntityWorld.Instance.EntSelf.ID) { flag = true; } if (flag) { this.ShowWinUIs(); this.ImageDefeatLeft.get_gameObject().SetActive(false); this.ImageDefeatRight.get_gameObject().SetActive(true); this.TextNameLeft.set_text(EntityWorld.Instance.EntSelf.Name); this.TextNumLeft.set_text(gfbr.fromCurrCombatWinCount + GameDataUtils.GetChineseContent(510108, false)); this.TextNumRight.set_text(gfbr.toCurrCombatWinCount + GameDataUtils.GetChineseContent(510108, false)); this.TextNameRight.set_text(gfbr.toName); if (gfbr.toLastCombatWinCount > 1) { this.ImageWinsDefeatRight.get_gameObject().SetActive(true); } } else { this.ShowLoseUIs(); this.TextAllLose.get_gameObject().SetActive(false); this.TextSelfLose.get_gameObject().SetActive(true); this.ImageDefeatLeft.get_gameObject().SetActive(true); this.ImageDefeatRight.get_gameObject().SetActive(false); this.TextNameLeft.set_text(EntityWorld.Instance.EntSelf.Name); this.TextNumLeft.set_text(gfbr.fromCurrCombatWinCount + GameDataUtils.GetChineseContent(510108, false)); this.TextNumRight.set_text(gfbr.toCurrCombatWinCount + GameDataUtils.GetChineseContent(510108, false)); this.TextNameRight.set_text(gfbr.toName); if (gfbr.fromLastCombatWinCount > 1) { this.ImageWinsDefeatLeft.get_gameObject().SetActive(true); } } } }
public HTTPData(DataReader stm, Logger logger) { string header = stm.ReadLine(); int contentLength = -1; bool chunked = false; byte[] body = null; bool connClose = false; if (header.Length == 0) { throw new EndOfStreamException(); } HttpVersion ver = OnReadHeader(header.Trim(), logger); ReadHeaders(stm, logger); foreach (KeyDataPair <string> value in Headers) { if (value.Name.Equals("content-length", StringComparison.OrdinalIgnoreCase)) { contentLength = int.Parse(value.Value.ToString()); break; } else if (value.Name.Equals("transfer-encoding", StringComparison.OrdinalIgnoreCase)) { if (value.Value.ToString().Equals("chunked", StringComparison.OrdinalIgnoreCase)) { chunked = true; break; } } else if (value.Name.Equals("connection", StringComparison.OrdinalIgnoreCase)) { // If the server indicates it will close the connection afterwards if (value.Value.ToString().Equals("close", StringComparison.OrdinalIgnoreCase)) { connClose = true; } } } body = new byte[0]; if (CanHaveBody()) { if (chunked) { List <byte> bodyData = new List <byte>(); byte[] data = ReadChunk(stm, logger); while (data.Length > 0) { bodyData.AddRange(data); data = ReadChunk(stm, logger); } body = bodyData.ToArray(); } else if (contentLength > 0) { body = stm.ReadBytes(contentLength); } else if ((contentLength < 0) && ((ver == HttpVersion.Http1_0) || connClose) && !IsRequest) { // HTTP1.0 waits till end of stream (need to only do this on response though) // Also sometimes happen on v1.1 if the client indicates that it is closing the connection body = stm.ReadToEnd(); } } Body = body; }
// // // private void MidiInputDevice_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args) { IMidiMessage receivedMidiMessage = args.Message; // Build the received MIDI message into a readable format StringBuilder outputMessage = new StringBuilder(); outputMessage.Append(receivedMidiMessage.Timestamp.ToString()).Append(", Type: ").Append(receivedMidiMessage.Type); // Add MIDI message parameters to the output, depending on the type of message switch (receivedMidiMessage.Type) { case MidiMessageType.NoteOff: var noteOffMessage = (MidiNoteOffMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(noteOffMessage.Channel).Append(", Note: ").Append(noteOffMessage.Note).Append(", Velocity: ").Append(noteOffMessage.Velocity); break; case MidiMessageType.NoteOn: var noteOnMessage = (MidiNoteOnMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(noteOnMessage.Channel).Append(", Note: ").Append(noteOnMessage.Note).Append(", Velocity: ").Append(noteOnMessage.Velocity); break; case MidiMessageType.PolyphonicKeyPressure: var polyphonicKeyPressureMessage = (MidiPolyphonicKeyPressureMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(polyphonicKeyPressureMessage.Channel).Append(", Note: ").Append(polyphonicKeyPressureMessage.Note).Append(", Pressure: ").Append(polyphonicKeyPressureMessage.Pressure); break; case MidiMessageType.ControlChange: var controlChangeMessage = (MidiControlChangeMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(controlChangeMessage.Channel).Append(", Controller: ").Append(controlChangeMessage.Controller).Append(", Value: ").Append(controlChangeMessage.ControlValue); break; case MidiMessageType.ProgramChange: var programChangeMessage = (MidiProgramChangeMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(programChangeMessage.Channel).Append(", Program: ").Append(programChangeMessage.Program); break; case MidiMessageType.ChannelPressure: var channelPressureMessage = (MidiChannelPressureMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(channelPressureMessage.Channel).Append(", Pressure: ").Append(channelPressureMessage.Pressure); break; case MidiMessageType.PitchBendChange: var pitchBendChangeMessage = (MidiPitchBendChangeMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(pitchBendChangeMessage.Channel).Append(", Bend: ").Append(pitchBendChangeMessage.Bend); break; case MidiMessageType.SystemExclusive: var systemExclusiveMessage = (MidiSystemExclusiveMessage)receivedMidiMessage; outputMessage.Append(", "); // Read the SysEx bufffer var sysExDataReader = DataReader.FromBuffer(systemExclusiveMessage.RawData); while (sysExDataReader.UnconsumedBufferLength > 0) { byte byteRead = sysExDataReader.ReadByte(); // Pad with leading zero if necessary outputMessage.Append(byteRead.ToString("X2")).Append(" "); } break; case MidiMessageType.MidiTimeCode: var timeCodeMessage = (MidiTimeCodeMessage)receivedMidiMessage; outputMessage.Append(", FrameType: ").Append(timeCodeMessage.FrameType).Append(", Values: ").Append(timeCodeMessage.Values); break; case MidiMessageType.SongPositionPointer: var songPositionPointerMessage = (MidiSongPositionPointerMessage)receivedMidiMessage; outputMessage.Append(", Beats: ").Append(songPositionPointerMessage.Beats); break; case MidiMessageType.SongSelect: var songSelectMessage = (MidiSongSelectMessage)receivedMidiMessage; outputMessage.Append(", Song: ").Append(songSelectMessage.Song); break; case MidiMessageType.TuneRequest: var tuneRequestMessage = (MidiTuneRequestMessage)receivedMidiMessage; // break; case MidiMessageType.TimingClock: var timingClockMessage = (MidiTimingClockMessage)receivedMidiMessage; // break; case MidiMessageType.Start: var startMessage = (MidiStartMessage)receivedMidiMessage; // break; case MidiMessageType.Continue: var continueMessage = (MidiContinueMessage)receivedMidiMessage; // break; case MidiMessageType.Stop: var stopMessage = (MidiStopMessage)receivedMidiMessage; // break; case MidiMessageType.ActiveSensing: var activeSensingMessage = (MidiActiveSensingMessage)receivedMidiMessage; // break; case MidiMessageType.SystemReset: var systemResetMessage = (MidiSystemResetMessage)receivedMidiMessage; // break; case MidiMessageType.None: throw new InvalidOperationException(); default: break; } // // // midiMessagesReceived = outputMessage.ToString(); // EventArgs e = new EventArgs(); MidiInputMessageReceived(this, e); }
private async void ChoosePhoto() { var fileOpenPicker = new FileOpenPicker(); fileOpenPicker.ViewMode = PickerViewMode.Thumbnail; fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileOpenPicker.FileTypeFilter.Add(".png"); fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.FileTypeFilter.Add(".jpeg"); fileOpenPicker.FileTypeFilter.Add(".bmp"); fileOpenPicker.FileTypeFilter.Add(".tiff"); fileOpenPicker.FileTypeFilter.Add(".ico"); var storageFile = await fileOpenPicker.PickSingleFileAsync(); if (storageFile == null) { return; } var pointer = Window.Current.CoreWindow.PointerCursor; Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(Windows.UI.Core.CoreCursorType.Wait, 1); using (IRandomAccessStream stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read)) { byte[] fileBytes = new byte[stream.Size]; using (DataReader reader = new DataReader(stream)) { await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(fileBytes); try { this.iContractor.Photo = await UIFunctions.RawToImage(fileBytes); } catch (Exception e) { if (e.HResult == -2003292336) { Window.Current.CoreWindow.PointerCursor = pointer; var dialog = new MessageDialog("То что вы пытаетесь присвоить - технически не совсем изображение"); dialog.Commands.Add(new UICommand("Закрыть")); dialog.DefaultCommandIndex = 0; dialog.CancelCommandIndex = 0; await dialog.ShowAsync(); return; } else { throw; } } this.iContractor.PhotoRaw = fileBytes; this.ImageHint = ZoomImageHint; } } Window.Current.CoreWindow.PointerCursor = pointer; }
PortablePdbCustomDebugInfoReader(ModuleDef module, TypeDef typeOpt, CilBody bodyOpt, GenericParamContext gpContext, ref DataReader reader) { this.module = module; this.typeOpt = typeOpt; this.bodyOpt = bodyOpt; this.gpContext = gpContext; this.reader = reader; }
public NodeContainerFormat Convert(BinaryFormat source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } NodeContainerFormat container = new NodeContainerFormat(); source.Stream.Position = 0; DataReader reader = new DataReader(source.Stream) { DefaultEncoding = Encoding.GetEncoding("utf-16"), }; // Header if (reader.ReadString(4, Encoding.ASCII) != "darc") { throw new FormatException("Invalid magic stamp"); } if (reader.ReadUInt16() != 0xFEFF) { throw new FormatException("Unknown endianness"); // big endian } uint headerSize = reader.ReadUInt32(); if (reader.ReadUInt16() != 0x0100) { throw new FormatException("Unknown version"); } reader.ReadUInt32(); // file size uint fatOffset = reader.ReadUInt32(); // we are skipping "fat size" and "data offset" source.Stream.Position = fatOffset; // We expect that the first node is a root node source.Stream.Position += 8; // skip empty name ptr and offset Node current = container.Root; uint lastId = reader.ReadUInt32(); current.Tags["darc.lastId"] = lastId; // From the last ID we can get the name table offset. uint nameTableOffset = fatOffset + (lastId * 0x0C); int currentId = 1; do { if (currentId >= current.Tags["darc.lastId"]) { current = current.Parent; continue; } // Read the entry string name = string.Empty; source.Stream.RunInPosition( () => name = reader.ReadString(), nameTableOffset + reader.ReadInt24()); bool isFolder = reader.ReadByte() == 1; uint offset = reader.ReadUInt32(); uint size = reader.ReadUInt32(); Node node = new Node(name); current.Add(node); if (isFolder) { node.Tags["darc.lastId"] = size; current = node; } else { node.ChangeFormat(new BinaryFormat(source.Stream, offset, size)); } currentId++; } while (current != null); return(container); }
public static PdbCustomDebugInfo Read(ModuleDef module, TypeDef typeOpt, CilBody bodyOpt, GenericParamContext gpContext, Guid kind, ref DataReader reader) { try { var cdiReader = new PortablePdbCustomDebugInfoReader(module, typeOpt, bodyOpt, gpContext, ref reader); var cdi = cdiReader.Read(kind); Debug.Assert(cdiReader.reader.Position == cdiReader.reader.Length); return(cdi); } catch (ArgumentException) { } catch (OutOfMemoryException) { } catch (IOException) { } return(null); }
private bool IsItemCanShow(int itemId) { Items items = DataReader <Items> .Get(itemId); return(items != null && items.show == 1); }
public BrushSide(byte[] data) : base(data) { face = DataReader.readInt(data[0], data[1], data[2], data[3]); plane = DataReader.readInt(data[4], data[5], data[6], data[7]); }
private async void OnGetUploadLinkCompleted(LiveOperationResult result) { if (this.Status == OperationStatus.Cancelled) { base.OnCancel(); return; } if (result.Error != null || result.IsCancelled) { this.OnOperationCompleted(result); return; } var uploadUrl = new Uri(result.RawResult, UriKind.Absolute); // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes, // and suppress_redirect query parameters set. Debug.Assert(uploadUrl.Query != null); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects)); Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes)); var uploader = new BT.BackgroundUploader(); uploader.Group = LiveConnectClient.LiveSDKUploadGroup; uploader.SetRequestHeader( ApiOperation.AuthorizationHeader, AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken); uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue()); uploader.Method = HttpMethods.Put; this.uploadOpCts = new CancellationTokenSource(); Exception webError = null; LiveOperationResult opResult = null; try { if (this.InputStream != null) { this.uploadOp = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream); } else { this.uploadOp = uploader.CreateUpload(uploadUrl, this.InputFile); } var progressHandler = new Progress <BT.UploadOperation>(this.OnUploadProgress); this.uploadOp = await this.uploadOp.StartAsync().AsTask(this.uploadOpCts.Token, progressHandler); } catch (TaskCanceledException exception) { opResult = new LiveOperationResult(exception, true); } catch (Exception exp) { // This might be an server error. We will read the response to determine the error message. webError = exp; } if (opResult == null) { try { IInputStream responseStream = this.uploadOp.GetResultStreamAt(0); if (responseStream == null) { var error = new LiveConnectException( ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("ConnectionError")); opResult = new LiveOperationResult(error, false); } else { var reader = new DataReader(responseStream); uint length = await reader.LoadAsync(MaxUploadResponseLength); opResult = this.CreateOperationResultFrom(reader.ReadString(length)); if (webError != null && opResult.Error != null && !(opResult.Error is LiveConnectException)) { // If the error did not come from the api service, // we'll just return the error thrown by the uploader. opResult = new LiveOperationResult(webError, false); } } } catch (COMException exp) { opResult = new LiveOperationResult(exp, false); } catch (FileNotFoundException exp) { opResult = new LiveOperationResult(exp, false); } } this.OnOperationCompleted(opResult); }
void ReceiveLoop() { if (!LoopTaskIsDead()) { return; } //...if it was dead, make a new one _receiveLoopTask = Task.Run(async() => { while (true) { try { if (_socketReader == null) { _socketReader = new DataReader(_socket.InputStream); } uint buf; buf = await _socketReader.LoadAsync(1); if (_socketReader.UnconsumedBufferLength > 0) { //this chokes on weird characters like the degree symbol //string s = _socketReader.ReadString(1); //Do this to avoid "No mapping for the Unicode character exists in the target multi-byte code page." byte[] streamContent = new byte[1]; _socketReader.ReadBytes(streamContent); string s = Encoding.UTF8.GetString(streamContent, 0, streamContent.Length); _receiveBuffer.Append(s); if (s.Equals("\n") || s.Equals("\r")) { try { //fire line received event string line = _receiveBuffer.ToString(); Debug.Write("Message Received:" + line); //already has the lline feed :) FireLineReceived(line); _receiveBuffer.Clear(); } catch (Exception exc) { //Log(exc.Message); FireCommError(exc.Message); } } } else { await Task.Delay(TimeSpan.FromSeconds(0)); } } catch (Exception ex) { lock (this) { if (_socket == null) { // Do not print anything here - the user closed the socket. if ((uint)ex.HResult == 0x80072745) { FireCommError("Disconnect triggered by remote device"); } else if ((uint)ex.HResult == 0x800703E3) { FireCommError("The I/O operation has been aborted because of either a thread exit or an application request."); } else if ((uint)ex.HResult == 0x800710DF) { FireCommError("Make sure your Bluetooth Radio is on: ."); } } else { FireCommInfoMessage("Disconnecting socket..."); Disconnect("Read stream failed with error: " + ex.Message); } } //dump out of the loop and kill the task. Do a return instead? return; } } }); FireCommInfoMessage("Listening..."); }
public void parse() { character = Constants.IDtoCharacter[DataReader.ReadShort(dataStream)]; }
public void BubbleDialogueByuuid(long uuid, MonsterRefresh dataMR, int bubbleType2Key) { if (dataMR == null) { return; } if (uuid <= 0L) { return; } if (uuid > 0L && BillboardManager.Instance.IsBillboardInfoOff(uuid, BillboardManager.BillboardInfoOffOption.BubbleDialogue)) { return; } EntityMonster entity = EntityWorld.Instance.GetEntity <EntityMonster>(uuid); if (entity != null) { AvatarModel avatarModel = DataReader <AvatarModel> .Get(entity.FixModelID); if (avatarModel != null) { List <int> list = new List <int>(); List <int> list2 = new List <int>(); for (int i = 0; i < dataMR.dialogueNpc.get_Count(); i++) { if (dataMR.dialogueNpc.get_Item(i).key == bubbleType2Key) { string[] array = dataMR.dialogueNpc.get_Item(i).value.Split(",".ToCharArray()); if (array != null) { for (int j = 0; j < array.Length; j++) { list.Add(Convert.ToInt32(array[j])); } } break; } } for (int k = 0; k < dataMR.dialogueLastTime.get_Count(); k++) { if (dataMR.dialogueLastTime.get_Item(k).key == bubbleType2Key) { string[] array2 = dataMR.dialogueLastTime.get_Item(k).value.Split(",".ToCharArray()); if (array2 != null) { for (int l = 0; l < array2.Length; l++) { list2.Add(Convert.ToInt32(array2[l])); } } break; } } if (list.get_Count() > 0 && list2.get_Count() > 0) { this.AddBubbleDialogue(entity.Actor.FixTransform, (float)avatarModel.height_HP, uuid); this.SetContentsBySequence(uuid, list, list2, 0); } } } }
public override DateTimeOffset GetDateTimeOffset(int i) { return(DataReader.GetDateTimeOffset(i)); }
private IEnumerator LoadControllerModel(InteractionSource source) { loadingControllers.Add(source.id); GameObject controllerModelGameObject; if (source.handedness == InteractionSourceHandedness.Left && LeftControllerOverride != null) { controllerModelGameObject = Instantiate(LeftControllerOverride); } else if (source.handedness == InteractionSourceHandedness.Right && RightControllerOverride != null) { controllerModelGameObject = Instantiate(RightControllerOverride); } else { byte[] fileBytes; if (GLTFMaterial == null) { Debug.Log("If using glTF, please specify a material on " + name + "."); loadingControllers.Remove(source.id); yield break; } #if !UNITY_EDITOR // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported. IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync(); if (modelTask == null) { Debug.Log("Model task is null."); loadingControllers.Remove(source.id); yield break; } while (modelTask.Status == AsyncStatus.Started) { yield return(null); } IRandomAccessStreamWithContentType modelStream = modelTask.GetResults(); if (modelStream == null) { Debug.Log("Model stream is null."); loadingControllers.Remove(source.id); yield break; } if (modelStream.Size == 0) { Debug.Log("Model stream is empty."); loadingControllers.Remove(source.id); yield break; } fileBytes = new byte[modelStream.Size]; using (DataReader reader = new DataReader(modelStream)) { DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size); while (loadModelOp.Status == AsyncStatus.Started) { yield return(null); } reader.ReadBytes(fileBytes); } #else IntPtr controllerModel = new IntPtr(); uint outputSize = 0; if (TryGetMotionControllerModel(source.id, out outputSize, out controllerModel)) { fileBytes = new byte[Convert.ToInt32(outputSize)]; Marshal.Copy(controllerModel, fileBytes, 0, Convert.ToInt32(outputSize)); } else { Debug.Log("Unable to load controller models."); loadingControllers.Remove(source.id); yield break; } #endif controllerModelGameObject = new GameObject(); controllerModelGameObject.name = "glTFController"; GLTFComponentStreamingAssets gltfScript = controllerModelGameObject.AddComponent <GLTFComponentStreamingAssets>(); gltfScript.ColorMaterial = GLTFMaterial; gltfScript.NoColorMaterial = GLTFMaterial; gltfScript.GLTFData = fileBytes; yield return(gltfScript.LoadModel()); } FinishControllerSetup(controllerModelGameObject, source.handedness.ToString(), source.id); }
public IntakeAirTemperature(DataReader reader, DataWriter writer) : base(reader, writer) { }
public override object GetValue(int i) { return(DataReader.GetValue(i)); }
private IEnumerator LoadSourceControllerModel(InteractionSource source) { byte[] fileBytes; GameObject controllerModelGameObject; if (GLTFMaterial == null) { Debug.Log("If using glTF, please specify a material on " + name + "."); yield break; } #if !UNITY_EDITOR // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported. IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync(); if (modelTask == null) { Debug.Log("Model task is null; loading alternate."); LoadAlternateControllerModel(source); yield break; } while (modelTask.Status == AsyncStatus.Started) { yield return(null); } IRandomAccessStreamWithContentType modelStream = modelTask.GetResults(); if (modelStream == null) { Debug.Log("Model stream is null; loading alternate."); LoadAlternateControllerModel(source); yield break; } if (modelStream.Size == 0) { Debug.Log("Model stream is empty; loading alternate."); LoadAlternateControllerModel(source); yield break; } fileBytes = new byte[modelStream.Size]; using (DataReader reader = new DataReader(modelStream)) { DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size); while (loadModelOp.Status == AsyncStatus.Started) { yield return(null); } reader.ReadBytes(fileBytes); } #else IntPtr controllerModel = new IntPtr(); uint outputSize = 0; if (TryGetMotionControllerModel(source.id, out outputSize, out controllerModel)) { fileBytes = new byte[Convert.ToInt32(outputSize)]; Marshal.Copy(controllerModel, fileBytes, 0, Convert.ToInt32(outputSize)); } else { Debug.Log("Unable to load controller models; loading alternate."); LoadAlternateControllerModel(source); yield break; } #endif controllerModelGameObject = new GameObject { name = "glTFController" }; GLTFComponent gltfScript = controllerModelGameObject.AddComponent <GLTFComponent>(); gltfScript.GLTFConstant = gltfScript.GLTFStandard = gltfScript.GLTFStandardSpecular = GLTFMaterial.shader; gltfScript.UseStream = true; gltfScript.GLTFStream = new MemoryStream(fileBytes); yield return(gltfScript.WaitForModelLoad()); FinishControllerSetup(controllerModelGameObject, source.handedness, GenerateKey(source)); }
protected void HandleEffect(bool isRepeat, EffectMessage message) { EntityParent caster = message.caster; if (caster == null) { return; } if (caster.IsDead || !caster.IsFighting) { return; } Actor casterActor = message.casterActor; if (casterActor == null) { return; } Effect effectData = message.effectData; XPoint basePoint = message.basePoint; List <EffectTargetInfo> list = new List <EffectTargetInfo>(); switch (effectData.type1) { case 3: case 8: case 9: case 10: goto IL_484; } if (basePoint != null) { List <EntityParent> list2 = this.CheckCandidateByType(caster, casterActor, effectData.targetType, effectData.forcePickup == 1, effectData.antiaircraft); if (list2.get_Count() != 0) { Hashtable hashtable = this.CheckCandidatesByEffectShape(list2, ContainerGear.containers.Values, casterActor, basePoint, effectData); if (hashtable.get_Count() != 0) { List <EntityParent> list3 = hashtable.get_Item("Entity") as List <EntityParent>; List <ContainerGear> list4 = hashtable.get_Item("Container") as List <ContainerGear>; if (list3.get_Count() > 0) { List <float> list5 = new List <float>(); for (int i = 0; i < list3.get_Count(); i++) { if (!SystemConfig.IsEffectOn) { break; } if (list3.get_Item(i) != null) { if (list3.get_Item(i).Actor) { list.Add(new EffectTargetInfo { targetId = list3.get_Item(i).ID }); if (caster.IsEntitySelfType && (effectData.type1 == 1 || effectData.type1 == 5 || effectData.type1 == 11)) { BattleBlackboard.Instance.ContinueCombo = true; } AvatarModel avatarModel = DataReader <AvatarModel> .Get(list3.get_Item(i).FixModelID); if ((!isRepeat || effectData.cycleHit != 0) && (!list3.get_Item(i).IsUnconspicuous || effectData.forcePickup != 0) && effectData.hitFx != 0) { if (casterActor is ActorParent) { list3.get_Item(i).Actor.PlayHitFx((casterActor as ActorParent).FixTransform, effectData.hitFx, avatarModel.undAtkFxScale, avatarModel.undAtkFxOffset); } else { list3.get_Item(i).Actor.PlayHitFx(casterActor.get_transform(), effectData.hitFx, avatarModel.undAtkFxScale, avatarModel.undAtkFxOffset); } } if (InstanceManager.IsServerBattle) { list3.get_Item(i).Actor.PlayHitSound(effectData.hitAudio); } list5.Add(avatarModel.frameRatio); } } } if (!isRepeat) { if ((message.caster.IsEntitySelfType || message.caster.OwnerID == EntityWorld.Instance.EntSelf.ID || message.caster.IsEntityMonsterType) && effectData.cameraRelyPickup == 1) { for (int j = 0; j < message.effectData.cameraEffect.get_Count(); j++) { int cameraEffectID = message.effectData.cameraEffect.get_Item(j); this.effectCameraTimerList.Add(TimerHeap.AddTimer((uint)(20 * j), 0, delegate { this.HandleCameraEffect(cameraEffectID); })); } } list5.Sort(); CommandCenter.ExecuteCommand(casterActor.get_transform(), new FrozeFrameCmd { count = list3.get_Count(), rate = effectData.frameFroze, time = effectData.frameTime, timeRateList = list5, interval = effectData.frameInterval, callback = null }); } } if (list4.get_Count() > 0 && effectData.type1 == 1 && effectData.targetType == 1) { for (int k = 0; k < list4.get_Count(); k++) { list4.get_Item(k).OnHit(effectData.id); } } if (casterActor is ActorFX && (list3.get_Count() > 0 || list4.get_Count() > 0)) { (casterActor as ActorFX).bulletLife--; } } } } IL_484: if (isRepeat) { GlobalBattleNetwork.Instance.SendUpdateEffect(message.caster.ID, (message.skillData != null) ? message.skillData.id : 0, message.effectData.id, list, message.UID, message.basePoint, message.isClientHandle); } else { GlobalBattleNetwork.Instance.SendAddEffect(message.caster.ID, (message.skillData != null) ? message.skillData.id : 0, message.effectData.id, list, message.UID, message.basePoint, message.isClientHandle); } }
public void Read(DataReader reader) { }