public static async Task<bool> LoadFrom ( ObservableCollection<RecentData> datas ) { try { StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync ( "data.dat" ); FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.Read ) as FileRandomAccessStream; DataReader dr = new DataReader ( stream ); dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dr.ByteOrder = ByteOrder.LittleEndian; await dr.LoadAsync ( ( uint ) stream.Size ); int len = dr.ReadInt32 (); for ( int i = 0; i < len; i++ ) { RecentData data = new RecentData (); uint srclen = dr.ReadUInt32 (); data.Source = dr.ReadString ( srclen ); data.SourceIndex = dr.ReadInt32 (); data.TargetIndex = dr.ReadInt32 (); datas.Add ( data ); } stream.Dispose (); } catch { return false; } return true; }
private async void read_data() { ifListening = true; // int read_msg_counter = 2; using (var reader = new Windows.Storage.Streams.DataReader(streamSocket.InputStream)){ reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.ReadAhead; reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; reader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; await reader.LoadAsync(4); while (reader.UnconsumedBufferLength > 0) { // read_msg_counter--; int bytesToRerad = reader.ReadInt32(); // Debug.Log("bytes to read: " + bytesToRerad); if (bytesToRerad <= 0) { return; } await reader.LoadAsync(Convert.ToUInt32(bytesToRerad)); byte[] buffer = new byte[bytesToRerad]; reader.ReadBytes(buffer); processReceivedData(buffer, bytesToRerad); await reader.LoadAsync(4); } reader.DetachStream(); } ifListening = false; }
private async void ReceiveImage(StreamSocket socket) { UpdateStatus("Empfange Daten..."); // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen var reader = new DataReader(socket.InputStream); // Anzahl der Bytes abrufen, aus denen das Bild besteht // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden await reader.LoadAsync(4); int imageSize = reader.ReadInt32(); // Bytearray des Bildes laden await reader.LoadAsync((uint)imageSize); byte[] imageBytes = new byte[imageSize]; reader.ReadBytes(imageBytes); // Bytearray in Stream laden und anzeigen Dispatcher.BeginInvoke(() => { using (var ms = new MemoryStream(imageBytes)) { var image = new BitmapImage(); image.SetSource(ms); ReceivedImage.Source = image; } }); UpdateStatus("Bild empfangen."); // Ressourcen freigeben reader.Dispose(); }
public async Task WaitForData() { var mainPageViewModel = MainPageViewModel.GetInstance(); using (var dr = new DataReader(ServerProxy.TcpSocket.InputStream)) { while (mainPageViewModel.ConnectionStatus) { var stringHeader = await dr.LoadAsync(4); if (stringHeader == 0) { mainPageViewModel.ConnectionStatus = false; return; } int messageLength = dr.ReadInt32(); uint numBytes = await dr.LoadAsync((uint)messageLength); var packetBaseBuffer = new byte[numBytes]; dr.ReadBytes(packetBaseBuffer); var packetBase = new PacketBase(); using (var stream = new MemoryStream(packetBaseBuffer)) { try { var reader = new BinaryReader(stream); packetBase.Read(reader); } catch (Exception e) { #if DEBUG throw; #endif } } var incomingMessage = IncomingMessageFactory.GetMessage( packetBase.Data as PacketV1); incomingMessage.HandleMessage(); } } }
public void Read(DataReader reader) { t = (HeartBeatType)reader.ReadInt32(); time = reader.ReadDateTime().UtcDateTime; cc = reader.ReadInt64(); asdf = reader.ReadInt64(); peak = reader.ReadInt64(); max0 = reader.ReadUInt64(); max1 = reader.ReadUInt64(); ave0 = reader.ReadUInt64(); ave1 = reader.ReadUInt64(); ave = reader.ReadUInt64(); beat = reader.ReadUInt64(); audio = reader.ReadUInt64(); noAudio = reader.ReadUInt64(); }
private async void ReceiveImage(PeerInformation peer) { try { Status.Text = "Verbinde mit Peer..."; StreamSocket peerSocket = await PeerFinder.ConnectAsync(peer); Status.Text = "Verbunden. Empfange Daten..."; // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen var reader = new DataReader(peerSocket.InputStream); // Anzahl der Bytes abrufen, aus denen das Bild besteht // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden await reader.LoadAsync(4); int imageSize = reader.ReadInt32(); // Bytearray des Bildes laden await reader.LoadAsync((uint)imageSize); byte[] imageBytes = new byte[imageSize]; reader.ReadBytes(imageBytes); // Bytearray in Stream laden und anzeigen using (var ms = new MemoryStream(imageBytes)) { var image = new BitmapImage(); image.SetSource(ms); ReceivedImage.Source = image; } Status.Text = "Bild empfangen."; // Ressourcen freigeben reader.Dispose(); peerSocket.Dispose(); // Wieder Verbindungen akzeptieren PeerFinder.Start(); } catch (Exception ex) { MessageBox.Show("Fehler: " + ex.Message); Status.Text = "Bereit."; } }
public async void WriteString(string HostName, string Message) { HostName remoteHostName = new HostName(HostName); using (StreamSocket socket = new StreamSocket()) { socket.Control.KeepAlive = false; await socket.ConnectAsync(remoteHostName, "6"); using (DataWriter writer = new DataWriter(socket.OutputStream)) { // set payload length writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteUInt32(writer.MeasureString(Message)); // set payload type writer.WriteByte((byte)PayloadType.String); // set payload writer.WriteString(Message); // transmit await writer.StoreAsync(); writer.DetachStream(); } using (DataReader reader = new DataReader(socket.InputStream)) { int length; string response; // receive payload length reader.ByteOrder = ByteOrder.LittleEndian; await reader.LoadAsync(4); length = reader.ReadInt32(); // receive payload await reader.LoadAsync((uint)length); response = reader.ReadString((uint)length); Debug.WriteLine(string.Format("response: {0}", response)); reader.DetachStream(); } } }
async void beginexecblock() { RenderContext mtext = new RenderContext(); maincontext = mtext; StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFile file = await folder.GetFileAsync("DXInteropLib\\VertexShader.cso"); var stream = (await file.OpenAsync(FileAccessMode.Read)); Windows.Storage.Streams.DataReader mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); byte[] dgram = new byte[file.Size]; await mreader.LoadAsync((uint)dgram.Length); mreader.ReadBytes(dgram); file = await folder.GetFileAsync("DXInteropLib\\PixelShader.cso"); stream = await file.OpenAsync(FileAccessMode.Read); mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0)); byte[] mgram = new byte[file.Size]; await mreader.LoadAsync((uint)file.Size); mreader.ReadBytes(mgram); defaultshader = mtext.CreateShader(dgram, mgram); mtext.InitializeLayout(dgram); defaultshader.Apply(); mtext.OnRenderFrame += onrenderframe; IStorageFile[] files = (await folder.GetFilesAsync()).ToArray(); bool founddata = false; foreach (IStorageFile et in files) { if (et.FileName.Contains("rawimage.dat")) { stream = await et.OpenAsync(FileAccessMode.Read); founddata = true; } } int width; int height; byte[] rawdata; if (!founddata) { file = await folder.GetFileAsync("TestProgram\\test.jpg"); stream = await file.OpenAsync(FileAccessMode.Read); var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream); var pixeldata = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.IgnoreExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage); width = (int)decoder.PixelWidth; height = (int)decoder.PixelHeight; rawdata = pixeldata.DetachPixelData(); file = await folder.CreateFileAsync("rawimage.dat"); stream = (await file.OpenAsync(FileAccessMode.ReadWrite)); var realstream = stream.GetOutputStreamAt(0); DataWriter mwriter = new DataWriter(realstream); mwriter.WriteInt32(width); mwriter.WriteInt32(height); mwriter.WriteBytes(rawdata); await mwriter.StoreAsync(); await realstream.FlushAsync(); } else { DataReader treader = new DataReader(stream.GetInputStreamAt(0)); await treader.LoadAsync((uint)stream.Size); rawdata = new byte[stream.Size-(sizeof(int)*2)]; width = treader.ReadInt32(); height = treader.ReadInt32(); treader.ReadBytes(rawdata); } Texture2D mtex = maincontext.createTexture2D(rawdata, width, height); mtex.Draw(); #region Cube List<VertexPositionNormalTexture> triangle = new List<VertexPositionNormalTexture>(); float z = 0; triangle.Add(new VertexPositionNormalTexture(new Vector3(0,0,z),new Vector3(1,1,1),new Vector2(0,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1,1,z),new Vector3(1,1,1),new Vector2(1,1))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0,1,z),new Vector3(1,1,1),new Vector2(0,1))); //Triangle 2 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0, z), new Vector3(1, 1, 1), new Vector2(0, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1,0,z),new Vector3(1,1,1),new Vector2(1,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, z), new Vector3(1, 1, 1), new Vector2(1, 1))); // Triangle 3 triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 0, z),new Vector3(1,1,1),new Vector2(0,0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, z+1), new Vector3(1, 1, 1), new Vector2(1, 1))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 0, z + 1), new Vector3(1, 1, 1), new Vector2(0, 1))); //Triangle 4 triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 0, z), new Vector3(1, 1, 1), new Vector2(0, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, z), new Vector3(1, 1, 1), new Vector2(1, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, z + 1), new Vector3(1, 1, 1), new Vector2(1, 1))); //Triangle 5 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0, z), new Vector3(1, 1, 1), new Vector2(0, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, z + 1), new Vector3(1, 1, 1), new Vector2(1, 1))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0, z + 1), new Vector3(1, 1, 1), new Vector2(0, 1))); //Triangle 6 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0, z), new Vector3(1, 1, 1), new Vector2(0, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, z), new Vector3(1, 1, 1), new Vector2(1, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, z + 1), new Vector3(1, 1, 1), new Vector2(1, 1))); //Triangle 7 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0, z+1), new Vector3(1, 1, 1), new Vector2(0, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, z+1), new Vector3(1, 1, 1), new Vector2(1, 1))); triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, z+1), new Vector3(1, 1, 1), new Vector2(0, 1))); //Triangle 8 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0, z+1), new Vector3(1, 1, 1), new Vector2(0, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 0, z+1), new Vector3(1, 1, 1), new Vector2(1, 0))); triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, z+1), new Vector3(1, 1, 1), new Vector2(1, 1))); //Top face //Triangle 9 //0,0 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, 0), new Vector3(1, 0, 1), new Vector2(0, 0))); //1,1 triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, 1), new Vector3(1, 0, 0), new Vector2(1, 1))); //0,1 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, 1), new Vector3(0, 1, 1), new Vector2(0, 1))); //Triangle 10 //0,0 triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 1, 0), new Vector3(1, 1, 1), new Vector2(0, 0))); //1,0 triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, 0), new Vector3(1, 1, 1), new Vector2(1, 0))); //1,1 triangle.Add(new VertexPositionNormalTexture(new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(1, 1))); #endregion byte[] gpudata = VertexPositionNormalTexture.Serialize(triangle.ToArray()); VertexBuffer mbuffer = maincontext.createVertexBuffer(gpudata,VertexPositionNormalTexture.Size); mbuffer.Apply(VertexPositionNormalTexture.Size); vertcount = triangle.Count; defaultmatrix = maincontext.createMatrix(true); defaultmatrix.SetCameraProperties(new Vector3D(0, 2, -1.5f), new Vector3D(0, 0, 0)); defaultmatrix.Activate(0); }
// Ожидаем получения данных async private void WaitForData(StreamSocket socket) { var dr = new DataReader(socket.InputStream); //dr.InputStreamOptions = InputStreamOptions.Partial; var stringHeader = await dr.LoadAsync(4); int strLength = dr.ReadInt32(); uint numStrBytes = await dr.LoadAsync((uint)strLength); string msg = dr.ReadString(numStrBytes); if (socket.Information.RemoteHostName.DisplayName == this.getSyncServer()) { InsertSingleData(this.Code(msg)); } else { DT = Convert.ToDateTime(msg); this.sync_reply(); } WaitForData(socket); }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { DataReader reader = new DataReader(args.Socket.InputStream); reader.ByteOrder = ByteOrder.LittleEndian; //WTF Microsoft ? try { while (true) { capture.GetFrame(); // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } int actualStringLength = reader.ReadInt32(); //System.Diagnostics.Debug.WriteLine("Expecting " + actualStringLength + " bytes from socket"); byte[] data = new byte[actualStringLength]; sizeFieldCount = await reader.LoadAsync((uint)actualStringLength); reader.ReadBytes(data); //System.Diagnostics.Debug.WriteLine("read " + sizeFieldCount + " bytes from socket"); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() => { WriteableBitmap bm = new WriteableBitmap((int)Preview.Width, (int)Preview.Height); data.AsBuffer().CopyTo(bm.PixelBuffer); Preview.Source = bm; }); // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal // the text back to the UI thread. //NotifyUserFromAsyncThread( // String.Format("Received data: bytes {0} frame {1}", actualStringLength, ++frameCounter)); } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } NotifyUserFromAsyncThread(exception.ToString()); } }
/// <summary> /// Wait for data on a given socket. /// </summary> /// <param name="socket">Socket which will be monitored for incoming data</param> private async void WaitForData(StreamSocket socket) { //System.Diagnostics.Debug.WriteLine("Waiting for header on socket from " + socket.Information.RemoteAddress.CanonicalName); DataReader reader = new DataReader(socket.InputStream); reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; // Load the first four bytes (32-bit int header) var stringHeader = await reader.LoadAsync(4); if (stringHeader == 0) { //System.Diagnostics.Debug.WriteLine("Disconnected from " + socket.Information.RemoteAddress.CanonicalName); socket.Dispose(); return; } // Read the header of the stream (the first 4 bytes) which indicate how much bytes are expected after the header Int32 strLength = reader.ReadInt32(); //System.Diagnostics.Debug.WriteLine("Waiting for data of length " + strLength + " on socket from " + socket.Information.RemoteAddress.CanonicalName); // Asynchronously load the next "strLenght" bytes uint byteCount = await reader.LoadAsync((uint)strLength); // Prepare an array to read the bytes in byte[] bytes = new byte[byteCount]; reader.ReadBytes(bytes); // Convert the array of bytes to an UTF8 encoded string string data = System.Text.Encoding.UTF8.GetString(bytes, 0, (int) byteCount); System.Diagnostics.Debug.WriteLine(String.Format("Received data from {0}: {1}", socket.Information.RemoteAddress.CanonicalName, data)); // Trigger the registered callback requestHandlerCallback(data, socket.Information.RemoteHostName.CanonicalName); // Wait for more data on the same socket WaitForData(socket); }
/// <summary> /// Load the family and their notes from local storage /// </summary> /// <returns>Null if there was no model to load, otherwise, the deserialized model</returns> private async Task<Model> LoadModelAsync() { Model model = null; InkStrokeContainer combinedStrokes = new InkStrokeContainer(); // To avoid managing individual files for every InkCanvas, we will combine all ink stroke information into one container List<int> InkStrokesPerCanvas = new List<int>(); try { StorageFile modelDataFile = await ApplicationData.Current.LocalFolder.GetFileAsync(NOTES_MODEL_FILE); using (IRandomAccessStream randomAccessStream = await modelDataFile.OpenAsync(FileAccessMode.ReadWrite)) { // Load the model which contains the people and the note collection try { DataContractJsonSerializer modelSerializer = new DataContractJsonSerializer(typeof(Model)); model = (Model)modelSerializer.ReadObject(randomAccessStream.AsStream()); } catch (System.Runtime.Serialization.SerializationException) { System.Diagnostics.Debug.Assert(false, "Failed to load serialized model"); return null; } } // For each sticky note, load the number of inkstrokes it contains StorageFile inkDataFile = await ApplicationData.Current.LocalFolder.GetFileAsync(NOTES_INK_FILE); using (IInputStream inkStream = await inkDataFile.OpenSequentialReadAsync()) { bool combinedStrokesExist = false; DataReader reader = new DataReader(inkStream); foreach (StickyNote n in model.StickyNotes) { await reader.LoadAsync(sizeof(int)); // You need to buffer the data before you can read from a DataReader. int numberOfInkStrokes = reader.ReadInt32(); InkStrokesPerCanvas.Add(numberOfInkStrokes); combinedStrokesExist |= numberOfInkStrokes > 0; } // Load the ink data if (combinedStrokesExist) { await combinedStrokes.LoadAsync(inkStream); } } // using inkStream } // try catch (FileNotFoundException) { // No data to load. We'll start with a fresh model return null; } // Factor out the inkstrokes from the big container into each note int allStrokesIndex = 0, noteIndex = 0; IReadOnlyList<InkStroke> allStrokes = combinedStrokes.GetStrokes(); foreach (StickyNote n in model.StickyNotes) { // InkStrokeContainers can't be serialized using the default xml/json serialization. // So create a new one and fill it up from the data we restored n.Ink = new InkStrokeContainer(); // pull out the ink strokes that belong to this note for (int i = 0; i < InkStrokesPerCanvas[noteIndex]; i++) { n.Ink.AddStroke(allStrokes[allStrokesIndex++].Clone()); } ++noteIndex; } return model; }
public async Task<IStorageFile> ReadFileAsync(StreamSocket socket, StorageFolder folder, string outputFilename = null) { StorageFile file; using (var rw = new DataReader(socket.InputStream)) { // 1. Read the filename length await rw.LoadAsync(sizeof(Int32)); var filenameLength = (uint)rw.ReadInt32(); // 2. Read the filename await rw.LoadAsync(filenameLength); var originalFilename = rw.ReadString(filenameLength); if (outputFilename == null) { outputFilename = originalFilename; } //3. Read the file length await rw.LoadAsync(sizeof(UInt64)); var fileLength = rw.ReadUInt64(); // 4. Reading file var buffer = rw.ReadBuffer((uint)fileLength); file = await ApplicationData.Current.LocalFolder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting); await FileIO.WriteBufferAsync(file, buffer); //using (var memStream = await DownloadFile(rw, fileLength)) //{ // file = await folder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting); // using (var fileStream1 = await file.OpenAsync(FileAccessMode.ReadWrite)) // { // await RandomAccessStream.CopyAndCloseAsync(memStream.GetInputStreamAt(0), fileStream1.GetOutputStreamAt(0)); // } // rw.DetachStream(); //} } return file; }
/// <summary> /// Reads the specified hashed block stream into a memory stream. /// </summary> /// <param name="input">The hashed block stream.</param> /// <returns>The de-hashed stream.</returns> public static async Task<Stream> Read(IInputStream input) { if (input == null) throw new ArgumentNullException("input"); var blockIndex = 0; var result = new MemoryStream(); var hash = WindowsRuntimeBuffer.Create(32); var reader = new DataReader(input) { ByteOrder = ByteOrder.LittleEndian, }; var sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256); try { while (true) { // Detect end of file var read = await reader.LoadAsync(4); if (read == 0) break; // Verify block index var index = reader.ReadInt32(); if (index != blockIndex) { throw new InvalidDataException(string.Format( "Wrong block ID detected, expected: {0}, actual: {1}", blockIndex, index)); } blockIndex++; // Block hash hash = await input.ReadAsync(hash, 32); if (hash.Length != 32) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } read = await reader.LoadAsync(4); if (read != 4) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } // Validate block size (< 10MB) var blockSize = reader.ReadInt32(); if (blockSize == 0) { // Terminator block var isTerminator = hash .ToArray() .All(x => x == 0); if (!isTerminator) { throw new InvalidDataException( "Data corruption detected (invalid hash for terminator block)"); } break; } if (0 > blockSize || blockSize > 10485760) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } // Check data truncate var loaded = await reader.LoadAsync((uint)blockSize); if (loaded < blockSize) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } var buffer = reader.ReadBuffer((uint)blockSize); // Verify block integrity var actual = sha.HashData(buffer); if (!CryptographicBuffer.Compare(hash, actual)) { throw new InvalidDataException( "Data corruption detected (content corrupted)"); } await result.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length); } result.Position = 0; return result; } catch { result.Dispose(); throw; } }
private async Task ReadMediaFileAsync(DataReader reader) { //a media file will always start with an int32 containing the file length await reader.LoadAsync(sizeof(int)); int messageLength = reader.ReadInt32(); Debug.WriteLine("Message Length " + messageLength); _totalBytesRead = 0; uint bytesRead = 0; IBuffer readBuffer = new Windows.Storage.Streams.Buffer(MAX_PACKET_SIZE); // read as many blocks as are in the incoming stream - this prevents blocks getting dropped do { await reader.LoadAsync(sizeof(int)); int partNumber = reader.ReadInt32(); Debug.WriteLine("Part " + partNumber); readBuffer = await _socket.InputStream.ReadAsync(readBuffer, MAX_PACKET_SIZE, InputStreamOptions.Partial); bytesRead = readBuffer.Length; Debug.WriteLine("Bytes read " + bytesRead); if (bytesRead > 0) { _incomingStream.WriteAsync(readBuffer).GetResults(); _totalBytesRead += bytesRead; } Debug.WriteLine("Total bytes read: " + _totalBytesRead); } while (_totalBytesRead < messageLength); Debug.WriteLine("Incoming stream length " + _incomingStream.Size); if (_totalBytesRead >= messageLength) { if (_writer == null) { _writer = new DataWriter(_socket.OutputStream); } _writer.WriteUInt16((UInt16)MessageType.Ready); await _writer.StoreAsync(); messageLength = 0; } }
private ActivityDataDoc LoadData(DataReader reader) { //read signature int signature = reader.ReadInt32(); //read head ActivityDataDoc ret = new ActivityDataDoc(); ret.version = (int)reader.ReadByte(); ret.year = (int)reader.ReadByte(); ret.month = (int)reader.ReadByte(); ret.day = (int)reader.ReadByte(); //read data while (reader.UnconsumedBufferLength > 0) { var row = new ActivityDataRow(); //row head row.mode = reader.ReadByte(); row.hour = reader.ReadByte(); row.minute = reader.ReadByte(); //row meta int size = (int)reader.ReadByte(); byte[] meta = new byte[4]; reader.ReadBytes(meta); //row data for (int i = 0, j = 0; meta[i] != 0 && i < 4 && j < size; ++i) { int lvalue = meta[i] >> 4; int rvalue = meta[i] & 0x0f; if (j < size) { int rawValue = reader.ReadInt32(); ActivityDataRow.DataType dtype = dataTypeMap[lvalue]; double value = GetValue(rawValue, dtype); row.data.Add(dtype, value); j++; } if (j < size) { int rawValue = reader.ReadInt32(); ActivityDataRow.DataType dtype = dataTypeMap[rvalue]; double value = GetValue(rawValue, dtype); row.data.Add(dtype, value); j++; } } ret.data.Add(row); } return ret; }
private static DiscoveryServiceCache Load(DataReader textReader) { var cache = new DiscoveryServiceCache(); cache.UserId = textReader.ReadString(); var entryCount = textReader.ReadInt32(); cache.DiscoveryInfoForServices = new Dictionary<string, CapabilityDiscoveryResult>(entryCount); for (var i = 0; i < entryCount; i++) { var key = textReader.ReadString(); var serviceResourceId = textReader.ReadString(); var serviceEndpointUri = new Uri(textReader.ReadString()); var serviceApiVersion = textReader.ReadString(); cache.DiscoveryInfoForServices.Add(key, new CapabilityDiscoveryResult(serviceEndpointUri, serviceResourceId, serviceApiVersion)); } return cache; }
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { OnCaptureStarted(); DataReader reader = new DataReader(args.Socket.InputStream); reader.ByteOrder = ByteOrder.LittleEndian; //WTF Microsoft ? try { while (true) { uwpCapture.GetFrame(); // Read first 4 bytes (length of the subsequent data). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { throw new ArgumentException("bad data from capture socket"); } int actualLength = reader.ReadInt32(); byte[] data = new byte[actualLength]; sizeFieldCount = await reader.LoadAsync((uint)actualLength); reader.ReadBytes(data); OnSample(data); } } finally { uwpCapture.Stop(); OnCaptureStopped(); } }
public void restoreState(DataReader dr) { mCurrentWord = dr.ReadInt32(); mInChamber = dr.ReadInt32(); if (mInChamber > mWordIndices.Count()) throw new Exception("Unexpected size for amount of words in chamber. Expected " + mWordIndices.Count() + " but found " + mInChamber); mWordsKnownCount = dr.ReadInt32(); for (int i = 0; i < mInChamber; i++) { mWordIndices[i] = dr.ReadInt32(); } }
private static async Task LoadQueueInternalAsync(IotHubClient client) { System.Collections.Generic.Queue<DataPoint> tmp = new System.Collections.Generic.Queue<DataPoint>(); try { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile file = await storageFolder.GetFileAsync(FILE_NAME); var stream = await file.OpenAsync(FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); int count = dataReader.ReadInt32(); for (int i = 0; i < count; i++) { DataPoint p = new DataPoint(); p.Read(dataReader); tmp.Enqueue(p); } } } stream.Dispose(); lock (client.thisLock) { client.queue.Clear(); client.queue = null; client.queue = new System.Collections.Generic.Queue<DataPoint>(tmp); } } catch (Exception) { } }
public async void OperateResponse() { SQLiteAsyncConnection con; switch(this.operateContent) { case "LoginOperate": int code= await Login(); if (code == 0) LoginOK(); else LoginErr(code.ToString()); break; case "GetNewInfoOperator": string pattern; StorageFolder localFolderStorage = ApplicationData.Current.LocalFolder; StorageFile infoStorageIcon; try { infoStorageIcon = await localFolderStorage.GetFileAsync(LoginInfo.UserName + "\\" + "PersonIcon.jpg"); IRandomAccessStream iconStream = await infoStorageIcon.OpenAsync(FileAccessMode.Read); await PageInit.homePage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { BitmapImage newImage = new BitmapImage(); newImage.SetSource(iconStream); PageInit.homePage.SetIcon(ref newImage); }); } catch(Exception err) { infoStorageIcon = null; } if (infoStorageIcon == null) { pattern = "fakeid=(\\d*)"; var m = Regex.Match(responseInfo, pattern); LoginInfo.FakeId = m.Groups[1].Value.ToString(); //无法检测到fakeid if (string.IsNullOrEmpty(LoginInfo.FakeId)) { // home.toast.Message = "无法查找到到您的Fakeid,可能是登陆超时"; home.toast.Show(); //此处添加通知 } else { string responseInfoUri = "https://mp.weixin.qq.com/misc/getheadimg?fakeid=" + LoginInfo.FakeId + "&token=" + LoginInfo.Token + "&lang=zh_CN"; string responseInfoRefer = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=" + LoginInfo.Token; HttpImageGet getIcon = new HttpImageGet(); getIcon.Operate = "GetPersonalIcon"; getIcon.GetImageOperate(responseInfoUri, responseInfoRefer); } } StorageFile infoStorageText; try { infoStorageText = await localFolderStorage.GetFileAsync(LoginInfo.UserName + "\\" + "PersonalInfo.txt"); using (IRandomAccessStream readStream = await infoStorageText.OpenAsync(FileAccessMode.Read)) { using (DataReader dataReader = new DataReader(readStream)) { UInt64 size = readStream.Size; if (size <= UInt32.MaxValue) { await dataReader.LoadAsync(sizeof(Int32)); Int32 stringSize = dataReader.ReadInt32(); await dataReader.LoadAsync((UInt32)stringSize); string fileContent = dataReader.ReadString((uint)stringSize); string[] splitString = fileContent.Split('\n'); LoginInfo.Type = splitString[0].Split(':')[0] == "type" ? splitString[0].Split(':')[1] : splitString[1].Split(':')[1]; LoginInfo.NickName = splitString[1].Split(':')[0] == "nickname" ? splitString[1].Split(':')[1] : splitString[0].Split(':')[1]; await PageInit.homePage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.homePage.SetInfo(LoginInfo.Type, LoginInfo.NickName); }); } else { // OutputTextBlock.Text = "文件 " + file.Name + " 太大,不能再单个数据块中读取"; } } } } catch (Exception err) { infoStorageText = null; } if (infoStorageText == null) { pattern = "nickname\">(\\S+)</a>"; var m = Regex.Match(responseInfo, pattern); LoginInfo.NickName = m.Groups[1].Value; pattern = "type icon_subscribe_label\">(\\S+)</a>"; m = Regex.Match(responseInfo, pattern); LoginInfo.Type = m.Groups[1].Value; await PageInit.homePage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.homePage.SetInfo(LoginInfo.Type,LoginInfo.NickName); }); string dataContent = "type:" + LoginInfo.Type + '\n' + "nickname:" + LoginInfo.NickName; StorageFolder accountInfoStorage = ApplicationData.Current.LocalFolder; var localFolder = await localFolderStorage.CreateFolderAsync(LoginInfo.UserName, CreationCollisionOption.OpenIfExists); var localFile = await localFolder.CreateFileAsync("PersonalInfo.txt", CreationCollisionOption.ReplaceExisting); using (StorageStreamTransaction transaction = await localFile.OpenTransactedWriteAsync()) { using(DataWriter dataWriter= new DataWriter(transaction.Stream)) { dataWriter.WriteInt32(Encoding.UTF8.GetByteCount(dataContent)); dataWriter.WriteString(dataContent); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); } } } pattern = "<em class=\"number\">(\\d+)</em>"; var ms = Regex.Matches(responseInfo, pattern); int i = 1; foreach (Match match in ms) { if (i == 1) { Global.NewMessage = int.Parse(match.Groups[1].Value.ToString()); if (Global.NewMessage > 0) Global.NewMessagesCnt = Global.NewMessage; else Global.NewMessagesCnt = 0; } if (i == 2) { Global.NewPerson=int.Parse( match.Groups[1].Value.ToString()); if (Global.NewPerson > 0) { Global.HasNewPeople = true; } else { Global.HasNewPeople = false; } //home.NavigationService.Navigate(new Uri("AllPeopleInfo.xaml",UriKind.Relative)); } if (i == 3) Global.AllPeople= int.Parse(match.Groups[1].Value.ToString()); i++; } await PageInit.homePage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.homePage.SetNum(); }); #region // StorageFile infoStorageText = await localFolderStorage.GetFileAsync(LoginInfo.UserName + "\\" + "PersonalInfo.txt"); ////if (infoStorageText!=null&& Sto.File.FileExists(loginInfo.UserName + "\\ico.jpg")) ////{ //// try //// { //// //读取本地资料 //// var aFile = new IsolatedStorageFileStream(loginInfo.UserName + "\\Info.txt", FileMode.Open, Sto.File); //// StreamReader sr = new StreamReader(aFile); //// string strLine = sr.ReadLine(); //// while (strLine != null) //// { //// if (strLine.Split(':')[0] == "type") //// loginInfo.Type = strLine.Split(':')[1]; //// else //// loginInfo.NickName = strLine.Split(':')[1]; //// strLine = sr.ReadLine(); //// } //// sr.Close(); //// } //// catch (Exception err) //// { //// Global.StoErr("ExsistsFile", err); //// home.toast.Message = "读取文本资料出错"; //// home.toast.Show(); //// } //// //读取本地图片 //// try //// { //// var readstream = Sto.File.OpenFile(loginInfo.UserName + "\\ico.jpg", FileMode.Open, FileAccess.Read); //// BitmapImage jpg = new BitmapImage(); //// jpg.SetSource(readstream); //// home.ico.Source = jpg; //// readstream.Close(); //// } //// catch (Exception err) //// { //// Global.StoErr("ExsistsFile", err); //// home.toast.Message = "读取头像出错"; //// home.toast.Show(); //// } //// home.nickname.Text = loginInfo.NickName; //// home.type.Text = loginInfo.Type; //// if (Sto.Info.Contains(loginInfo.UserName + "LaunchTimes")) //// Sto.Info[loginInfo.UserName + "LaunchTimes"] = Convert.ToInt32(Sto.Info[loginInfo.UserName + "LaunchTimes"]) + 1; //// else //// Sto.Info[loginInfo.UserName + "LaunchTimes"] = 1; //// Sto.Info.Save(); ////} ////else ////{ //// if (!Sto.File.DirectoryExists(loginInfo.UserName)) //// Sto.File.CreateDirectory(loginInfo.UserName); //// Match m; //// try //// { //// pattern = "fakeid=(\\d*)"; //// m = Regex.Match(responseInfo, pattern); //// loginInfo.Fakeid = m.Groups[1].Value.ToString(); //// //无法检测到fakeid //// if (string.IsNullOrEmpty(loginInfo.Fakeid)) //// { home.toast.Message = "无法查找到到您的Fakeid,可能是登陆超时"; home.toast.Show(); return; } //// //获取头像 //// string responseInfoUri = "https://mp.weixin.qq.com/misc/getheadimg?fakeid=" + loginInfo.Fakeid + "&token=" + loginInfo.Token + "&lang=zh_CN"; //// string responseInfoRefer = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=" + loginInfo.Token; //// GetIco getIco = new GetIco(); //// getIco.getImage(responseInfoUri, responseInfoRefer, home); //// } //// catch (Exception err) //// { //// Global.StoErr("CreateIco", err); //// if (Sto.File.FileExists(loginInfo.UserName + "\\ico.jpg")) //// Sto.File.DeleteFile(loginInfo.UserName + "\\ico.jpg"); //// home.toast.Message = "创建头像出错,请刷新"; //// home.toast.Show(); //// } //// pattern = "nickname\">(\\S+)</a>"; //// m = Regex.Match(responseInfo, pattern); //// home.nickname.Text = loginInfo.NickName = m.Groups[1].Value; //// pattern = "type icon_subscribe_label\">(\\S+)</a>"; //// m = Regex.Match(responseInfo, pattern); //// home.type.Text = loginInfo.Type = m.Groups[1].Value; //// try //// { //// var aFile = new IsolatedStorageFileStream(loginInfo.UserName + "\\Info.txt", FileMode.OpenOrCreate, Sto.File); //// StreamWriter sw = new StreamWriter(aFile); //// sw.WriteLine("type:" + loginInfo.Type); //// sw.WriteLine("nickname:" + loginInfo.NickName); //// sw.Close(); //// } //// catch (Exception err) //// { //// Global.StoErr("CreateInf", err); //// if (Sto.File.FileExists(loginInfo.UserName + "\\Info.txt")) //// Sto.File.DeleteFile(loginInfo.UserName + "\\Info.txt"); //// if (home != null) //// { //// //home.t.Text = err.Message; //// home.toast.Message = "写入资料出错"; //// home.toast.Show(); //// } //// if (that != null) //// { //// that.state.Text = "写入资料出错"; //// } //// if (newMessage != null) //// { //// newMessage.toast.Message = "写入资料出错"; //// newMessage.toast.Show(); //// } //// } ////} ////try ////{ //// pattern = "<em class=\"number\">(\\d+)</em>"; //// var ms = Regex.Matches(responseInfo, pattern); //// int i = 1; //// foreach (Match match in ms) //// { //// if (i == 1) //// Global.newAddMessage = home.talk.Text = match.Groups[1].Value.ToString(); //// if (i == 2) //// { //// home.newperson.Text = match.Groups[1].Value.ToString(); //// if (int.Parse(home.newperson.Text) > 0) //// Global.hasNewPeople = true; //// //home.NavigationService.Navigate(new Uri("AllPeopleInfo.xaml",UriKind.Relative)); //// } //// if (i == 3) //// home.allpeople.Text = match.Groups[1].Value.ToString(); //// i++; //// } //// home.pb.Visibility = Visibility.Collapsed; //// Global.homeOK = true; //// Global.isFirstLoad = false; ////} ////catch (Exception err) ////{ //// Global.StoErr("RefreshPeopleNum", err); //// if (home != null) //// { //// //home.t.Text = err.Message; //// home.toast.Message = "写入资料出错"; //// home.toast.Show(); //// } ////} #endregion break; case "GetMessages": //SQLiteAsyncConnection(ApplicationData.Current.LocalFolder.Path + "\\note.db"); pattern = "\"msg_item\":((\\S|\\s)*).msg_item,"; var mm = Regex.Match(responseInfo, pattern); string temp = mm.Groups[1].Value.ToString(); pattern = "\"id\":(?<id>[\\d]*),\"type\":[\\d]*,\"fakeid\":\"(?<fakeid>[\\d]*)\",\"nick_name\":\"(?<nickname>[^\"]*)\",\"date_time\":(?<time>[\\d]*),\"content\":\"(?<content>[^\"]*)\",\"source\":\"[^\"]*\",(|\"is_starred_msg\":(?<isstar>[\\d]*),)\"msg_status\":[\\d]*,(|\"remark_name\":\"(?<remarkname>[^\"]*)\",)\"has_reply\":(?<hasreply>[\\d]*),\"refuse_reason\":\"[^\"]*\","; //pattern = @""id":(?<id>[\S]*),"type":\S*,"fakeid":"(?<fakeid>[\S]*)","nick_name":"(?<nickname>[\S]*)","date_time":(?<time>[\S]*),"content":"(?<content>[\S]*)","source":"\S*","msg_status":\S*,"has_reply":(?<hasreply>[\S]*),"refuse_reason":"\S*","multi_item":\[\S*\],"to_uin":\S*"; ms = Regex.Matches(temp, pattern); if (ms.Count > 0) { con = new SQLiteAsyncConnection(ApplicationData.Current.LocalFolder.Path + "\\"+LoginInfo.UserName + "\\NewMessage.db"); // if (con.Table<NewMessagesTable>() == null) await con.CreateTableAsync<NewMessagesTable>(); foreach (Match match in ms) { Global.NewMessagesCnt--; string showName = match.Groups["nickname"].Value; if (!String.IsNullOrEmpty(match.Groups["remarkname"].Value.ToString())) showName = match.Groups["remarkname"].Value.ToString(); //创建一条表的数据 //MessageTable newmessage = new MessageTable { Num = loginInfo.UserName + ":" + match.Groups["id"].Value, TalkId = match.Groups["id"].Value, ownId = loginInfo.UserName, FakeId = match.Groups["fakeid"].Value, NickName = showName, Time = match.Groups["time"].Value, Content = match.Groups["content"].Value, has_Reply = match.Groups["hasreply"].Value, is_star = match.Groups["isstar"].Value }; await con.InsertAsync(new NewMessagesTable { Talkid = match.Groups["id"].Value, Username = LoginInfo.UserName, FakeId = match.Groups["fakeid"].Value, Nickname = showName, Time = match.Groups["time"].Value, Content = match.Groups["content"].Value, Hasreply = match.Groups["hasreply"].Value, Isstar = match.Groups["isstar"].Value}); if (Global.NewMessagesCnt <= 0) break; }//做好截至 await PageInit.newMessagesPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.newMessagesPage.LongDataBind(); }); } break; case "GetAllPeopleInfo": List<string> group = new List<string>(); List<string> cnt = new List<string>(); List<string> name = new List<string>(); pattern = "\"id\":(?<id>[\\d]*),\"name\":\"(?<name>[^\"]*)\",\"cnt\":(?<cnt>[\\d]*)}"; ms = Regex.Matches(responseInfo, pattern); foreach (Match match in ms) { if (int.Parse(match.Groups["cnt"].Value.ToString()) != 0) { group.Add(match.Groups["id"].Value); name.Add(match.Groups["name"].Value); cnt.Add(match.Groups["cnt"].Value); } } string[] groupidList = group.ToArray(); string[] nameList = name.ToArray(); string[] cntList = cnt.ToArray(); int peopleNum = 0; for (int j = 0; j < groupidList.Length; j++) { peopleNum += int.Parse(cnt[j]); } Global.PeopleSum = peopleNum; Global.PerPersonProgress = 90.000 / peopleNum; await PageInit.downloadInfoPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.downloadInfoPage.SetProgressValue(10); PageInit.downloadInfoPage.FindInfo(groupidList,nameList,cntList); }); break; case "GetInfoWithIcon": con = new SQLiteAsyncConnection(ApplicationData.Current.LocalFolder.Path + "\\"+LoginInfo.UserName + "\\NewMessage.db"); await con.CreateTableAsync<PersonalInfoTable>(); // string pattern; pattern = "\"id\":(?<id>[\\d]*),\"nick_name\":\"(?<nickname>[^\"]*)\",\"remark_name\":\"(?<remarkname>[^\"]*)\",\"group_id\":(?<groupid>[\\d]*)"; ms = Regex.Matches(responseInfo, pattern); foreach (Match match in ms) { StorageFile infoStorageImage; try { infoStorageImage = await ApplicationData.Current.LocalFolder.GetFileAsync(LoginInfo.UserName + "\\ICO" + "\\ico" + match.Groups["id"].Value + ".jpg"); await PageInit.downloadInfoPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.downloadInfoPage.AddProgressValue((int)Global.PerPersonProgress); }); } catch { infoStorageImage = null; } if (infoStorageImage == null) { //sw.WriteLine("fakeid:" + match.Groups["id"].Value + ":nickname:" + match.Groups["nickname"] + ":remarkname:" + match.Groups["remarkname"].Value + ":grupid:" + match.Groups["groupid"].Value); await con.InsertAsync(new PersonalInfoTable { Username=LoginInfo.UserName,Fakeid = match.Groups["id"].Value, Nickname = match.Groups["nickname"].Value, Remarkname = match.Groups["remarkname"].Value, Groupid = match.Groups["groupid"].Value }); string tempUri = "https://mp.weixin.qq.com/misc/getheadimg?fakeid=" + match.Groups["id"].Value + "&token=" + LoginInfo.Token + "&lang=zh_CN"; string tempRefer = "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize="+Global.PeopleSum+"&pageidx=0&type=0&token="+LoginInfo.Token+"&lang=zh_CN"; // Global.jpgName = "allico"; //getImage(tempUri, tempRefer); HttpImageGet getInfoWithIcon = new HttpImageGet(); getInfoWithIcon.Operate = "GetInfoWithIcon"; getInfoWithIcon.GetImageOperate(tempUri,tempRefer); } } await PageInit.downloadInfoPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.downloadInfoPage.SetProgressValue(100); PageInit.downloadInfoPage.SetState("完成"); PageInit.downloadInfoPage.SetButtonContent("继续"); //begin.Content = "继续"; //82,376,0,0 //begin.Margin = new Thickness(82, 376, 0, 0); //begin.Visibility = Visibility.Visible; PageInit.downloadInfoPage.SetButtonVisibility(Visibility.Visible); }); break; case "RefreshPersonMessage": ItemInGroup1 tmp =new ItemInGroup1(); tmp.Key = DateTime.Now.ToString(); pattern = "\"id\":(?<id>[\\d]*),\"type\":(?<type>[\\d]*),\"fakeid\":\"(?<fakeid>[\\d]*)\",\"nick_name\":\"(?<nickname>[^\"]*)\",\"date_time\":(?<time>[\\d]*),(\"content\":\"(?<content>[^\"]*)\"|)"; //pattern="\"id\":(?<id>[\\d]*),\"type\":(?<type>[\\d]*),\"fakeid\":\"(?<fakeid>[\\d]*)\",\"nick_name\":\"(?<nickname>[^\"]*)\",\"date_time\":(?<time>[\\d]*),(\"content\":\"(?<content>[^\"]*)\"|),\"source\":\"[^\"]*\",\"msg_status\":[\\d]*,\"has_reply\":[\\d]*,\"refuse_reason\":\"[^\"]*\",\"multi_item\":\\[[^\"]*\\],\"to_uin\":(?<tofakeid>[\\d]*),"; ms = Regex.Matches(responseInfo, pattern); if (ms.Count != 0) { bool isRun = false; int index = 0; long tempMax = -1; con = new SQLiteAsyncConnection(ApplicationData.Current.LocalFolder.Path + "\\" + LoginInfo.UserName + "\\NewMessage.db"); await con.CreateTableAsync<TalkMessageTable>(); string vv = new StorageOperate().SettingStorage(LoginInfo.UserName + "MaxTalkId" + Global.PageFakeid).ToString(); if (new StorageOperate().SettingStorage(LoginInfo.UserName + "MaxTalkId" + Global.PageFakeid).ToString() == "") new StorageOperate().SettingStorage(LoginInfo.UserName + "MaxTalkId" + Global.PageFakeid, "0"); try { long fff= long.Parse(new StorageOperate().SettingStorage(LoginInfo.UserName + "MaxTalkId" + Global.PageFakeid).ToString()); while (long.Parse(ms[index].Groups["id"].Value.ToString()) >fff) { isRun = true; if (index == 0) tempMax = long.Parse(ms[index].Groups["id"].Value.ToString()); await con.InsertAsync(new TalkMessageTable { Talkid = ms[index].Groups["id"].Value, Username = LoginInfo.UserName, Fromfakeid = ms[index].Groups["fakeid"].Value, Tofakeid = ms[index].Groups["fakeid"].Value==Global.PageFakeid?LoginInfo.UserName:Global.PageFakeid, Time = ms[index].Groups["time"].Value, Content = ms[index].Groups["content"].Value }); //Item1 item = new Item1(); //item.Key = tmp.Key; string content= ms[index].Groups["content"].Value; string fakeid= Global.PageFakeid; DateTime time = TimeStamp.GetTime(ms[index].Groups["time"].Value); string url = ""; if (ms[index].Groups["fakeid"].Value.ToString() == Global.PageFakeid) url = LoginInfo.UserName + "\\ICO" + "\\ico" + ms[index].Groups["fakeid"].Value .ToString()+ ".jpg"; else url = LoginInfo.UserName + "\\PersonIcon.jpg"; await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { // if(tmp.ItemContent!=null) if(!String.IsNullOrEmpty(content)) PageInit.talkPage.AppendToLong(content, ms[index].Groups["fakeid"].Value, url, time); // Item1 tmp = new Item1(); //PageInit.talkPage.LongDataBind(); }); //BitmapImage newJpg = new BitmapImage(); //try //{ // var Icon = await ApplicationData.Current.LocalFolder.GetFileAsync(url); // IRandomAccessStream iconStream = await Icon.OpenAsync(FileAccessMode.Read); // newJpg.SetSource(iconStream); //} //catch //{ // string l = "ms-appx:///Design/getheadimg.png"; // newJpg.UriSource = new Uri(l); //} //item.l_imagesource = newJpg; //item.l_imagesource = null; // tmp.ItemContent.Add(item); index++; if (index == ms.Count) break; } if (tempMax > long.Parse(new StorageOperate().SettingStorage(LoginInfo.UserName + "MaxTalkId" + Global.PageFakeid).ToString())) new StorageOperate().SettingStorage(LoginInfo.UserName + "MaxTalkId" + Global.PageFakeid, tempMax.ToString()); if (isRun) { await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.talkPage.ScrollToBottom(); }); } } catch (Exception err) { // int ddd; } } //await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => // { // if(tmp.ItemContent!=null) // PageInit.talkPage.AppendToLong(tmp); // Item1 tmp = new Item1(); //PageInit.talkPage.LongDataBind(); // }); break; case "RefreshSpan": break; case "SendGroup": pattern = " data:{(?<data>[^}]*)},"; Match m1 = Regex.Match(responseInfo,pattern); temp = m1.Groups["data"].Value.ToString(); pattern = "ticket:\"(?<ticket>[^\"]*)\""; m1 = Regex.Match(temp,pattern); LoginInfo.Ticket = m1.Groups["ticket"].Value.ToString(); pattern = " user_name:\"(?<username>[^\"]*)\""; m1 = Regex.Match(temp,pattern); LoginInfo.UniformUserName = m1.Groups["username"].Value.ToString(); pattern = "wx.cgiData = {(?<info>[\\S\\s]*)seajs.use"; //可以匹配更多信息 m1 = Regex.Match(responseInfo, pattern); temp = m1.Groups["info"].Value.ToString(); pattern = "operation_seq: \"(?<seq>[\\d]*)\""; m1 = Regex.Match(temp, pattern); LoginInfo.Seq = m1.Groups["seq"].Value.ToString(); pattern = "\"id\":(?<id>[\\d]*),\"name\":\"(?<name>[^\"]*)\",\"cnt\":(?<cnt>[\\d]*)"; ms = Regex.Matches(temp,pattern); Global.groupsInfo = new Dictionary<string, string>(); Global.groupsInfo.Add("全部","-1"); foreach(Match a in ms) { Global.groupsInfo.Add(a.Groups["name"].Value.ToString() + " " + a.Groups["cnt"].Value.ToString()+"人",a.Groups["id"].Value.ToString()); } await PageInit.sendGroup.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.sendGroup.SetListPicker(); PageInit.sendGroup.SetState(1); }); break; case "send": JArray ja = new JArray(JsonConvert.DeserializeObject(responseInfo)); string ret = ja[0]["base_resp"]["ret"].ToString(); string msg = ja[0]["base_resp"]["err_msg"].ToString(); await PageInit.sendGroup.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.sendGroup.SendResult(ret,msg); }); break; case "SendMessage": try { ja = new JArray(JsonConvert.DeserializeObject(responseInfo)); string returnValue= ja[0]["base_resp"]["ret"].ToString(); string Result = ja[0]["base_resp"]["err_msg"].ToString(); if (returnValue=="0"||Result == "ok") { await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.talkPage.ShowTip("发送成功"); PageInit.talkPage.ClearMyMessage(); }); // tmr.Stop(); // tmr.Start(); } else if (returnValue=="10706"||Result == "customer block") { await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.talkPage.ShowTip("48小时未联系"); }); // tmr.Stop(); // tmr.Start(); } else if (returnValue=="-1"||Result == "system error") { await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.talkPage.ShowTip("系统错误"); }); //tmr.Stop(); // tmr.Start(); } else { await PageInit.talkPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { PageInit.talkPage.ShowTip("发送失败"+Result); }); // tmr.Stop(); // tmr.Start(); } } catch (Exception err) { } break; } }