WriteInt32() public method

public WriteInt32 ( int value ) : void
value int
return void
Example #1
0
        public async Task SendAsync(string text)
        {
            try
            {
                // DataWriter to send message to client
                var writer = new DataWriter(_socket.OutputStream);
                //Encrypt message
                byte[] data = Cryptographic.Encrypt(text, "123");

                //Write Lenght message in buffer
                writer.WriteInt32(data.Length);
                //Write message in buffer
                writer.WriteBytes(data);

                //Send buffer
                await writer.StoreAsync();
                //Clear buffer
                await writer.FlushAsync();

            }
            catch (Exception e)
            {
                InvokeOnError(e.Message);
            }
        }
Example #2
0
        //send song data over the socket
        //this uses an app specific socket protocol: send title, artist, then song data
        public async Task<bool> SendSongOverSocket(StreamSocket socket, string fileName, string songTitle, string songFileSize)
        {
            try
            {
                // Create DataWriter for writing to peer.
                _dataWriter = new DataWriter(socket.OutputStream);

                //send song title
                await SendStringOverSocket(songTitle);

                //send song file size
                await SendStringOverSocket(songFileSize);

                // read song from Isolated Storage and send it
                using (var fileStream = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, IsolatedStorageFile.GetUserStoreForApplication()))
                {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    int readCount = 0;
                    _length = fileStream.Length;

                    //Initialize the User Interface elements
                    InitializeUI(fileName);

                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        readCount += bytesRead;
                        //UpdateUI
                        UpdateProgressBar(readCount);
                        //size of the packet
                        _dataWriter.WriteInt32(bytesRead);
                        //packet data sent
                        _dataWriter.WriteBytes(buffer);
                        try
                        {
                            await _dataWriter.StoreAsync();
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                        }
                    }
                }

                return true;
            }
            catch
            {
                return false;
            }

        }
Example #3
0
		public static async void SaveTo ( ObservableCollection<RecentData> datas )
		{
			StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync ( "data.dat",
				Windows.Storage.CreationCollisionOption.ReplaceExisting );
			FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.ReadWrite ) as FileRandomAccessStream;
			DataWriter dw = new DataWriter ( stream );

			dw.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
			dw.ByteOrder = ByteOrder.LittleEndian;

			dw.WriteInt32 ( datas.Count );
			foreach ( RecentData data in datas )
			{
				dw.WriteUInt32 ( ( uint ) dw.MeasureString ( data.Source ) );
				dw.WriteString ( data.Source );
				dw.WriteInt32 ( data.SourceIndex );
				dw.WriteInt32 ( data.TargetIndex );
			}

			await dw.StoreAsync ();
			await dw.FlushAsync ();
			stream.Dispose ();
		}
Example #4
0
 public void Write(DataWriter writer)
 {
     writer.WriteInt32((int)t);
     writer.WriteDateTime(time);
     writer.WriteInt64(cc);
     writer.WriteInt64(asdf);
     writer.WriteInt64(peak);
     writer.WriteUInt64(max0);
     writer.WriteUInt64(max1);
     writer.WriteUInt64(ave0);
     writer.WriteUInt64(ave1);
     writer.WriteUInt64(ave);
     writer.WriteUInt64(beat);
     writer.WriteUInt64(noAudio);
     writer.WriteUInt64(audio);
 }
        private async void TransferImage(StreamSocket socket)
        {
            var writer = new DataWriter(socket.OutputStream);

            UpdateStatus("Übertrage Bild...");

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.ImageBytesToTransfer.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.ImageBytesToTransfer);
            await writer.StoreAsync();
            await writer.FlushAsync();

            // Ressourcen freigeben
            writer.Dispose();
            UpdateStatus("Übertragung abgeschlossen");
        }
        public async Task Should_detect_corrupt_block_length()
        {
            using (var input = new InMemoryRandomAccessStream())
            {
                await CopyData(input, "IO.HashedBlockStream.bin");

                input.Seek(36);

                var writer = new DataWriter(input)
                {
                    ByteOrder = ByteOrder.LittleEndian,
                };
                writer.WriteInt32(-100);
                await writer.StoreAsync();

                input.Seek(0);
                await Assert.ThrowsAsync<InvalidDataException>(
                    () => HashedBlockFileFormat.Read(input));
            }
        }
        private async void TransferPicture(StreamSocket socket)
        {
            // DataWriter erzeugen, um Byte-Umwandlung erledigen zu lassen...
            var writer = new DataWriter(socket.OutputStream);

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.PhotoBytesToShare.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.PhotoBytesToShare);
            await writer.StoreAsync();
            await writer.FlushAsync();
            UpdateStatus("Übertragung abgeschlossen.");

            // Ressourcen freigeben
            writer.Dispose();
            socket.Dispose();

            // Beenden der Annahme von Client-Verbindungen
            _listener.Dispose();
        }
        private async void TransferPicture_Click(object sender, RoutedEventArgs e)
        {
            var selectedPeer = PeersList.SelectedItem as PeerInformation;
            if (selectedPeer == null)
            {
                MessageBox.Show("Bitte Emfängergerät wählen");
                return;
            }

            try
            {
                Status.Text = "Verbinde mit Peer...";
                var peerSocket = await PeerFinder.ConnectAsync(selectedPeer);
                var writer = new DataWriter(peerSocket.OutputStream);

                Status.Text = "Verbunden. Übertrage Bild...";

                // Anzahl der zu übertragenden Bytes übertragen
                writer.WriteInt32(App.ImageBytesToTransfer.Length);
                await writer.StoreAsync();

                // Image-Bytes übertragen
                writer.WriteBytes(App.ImageBytesToTransfer);
                await writer.StoreAsync();
                await writer.FlushAsync();

                // Ressourcen freigeben
                writer.Dispose();
                peerSocket.Dispose();
                Status.Text = "Übertragung abgeschlossen";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
Example #9
0
        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);
            
        }
Example #10
0
        /// <summary>
        /// Broadcast clients number changed
        /// </summary>
        /// <param name="clientSocket"></param>
        /// <param name="userName"></param>
        /// <param name="changedUser"></param>
        /// <param name="state"></param>
        public async void SendUsersList(StreamSocket clientSocket, string userName, string changedUser, string state)
        {
            var data = new Data
            {
                Command = Command.Broadcast,
                To = userName,
                Message = string.Format("{0}|{1}|{2}|{3}",
                    string.Join(",", clients.Select(u => u.UserName).Where(name => name != userName)), changedUser, state,
                    serverName)
            };
            var dataWriter = new DataWriter(clientSocket.OutputStream);
            var bytes = data.ToByte();

            dataWriter.WriteInt32(bytes.Length);
            dataWriter.WriteBytes(bytes);
            await dataWriter.StoreAsync();
        }
Example #11
0
        /// <summary>
        /// Saves the current progress state for the current dictionary
        /// </summary>
        public void saveState()
        {
            if (string.IsNullOrEmpty(mCrammerDict.StateFile))
                throw new Exception("No state file available");

            try
            {
                using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
                {
                    using (DataWriter dataWriter = new DataWriter(memoryStream))
                    {
                        dataWriter.WriteInt32(mTotalWords);
                        dataWriter.WriteInt32(mKnownWords);
                        dataWriter.WriteInt32(mStart);
                        dataWriter.WriteInt32(mCurrentWord);
                        dataWriter.WriteBoolean(mNewWordsInUse);
                        dataWriter.WriteInt32(mInSystem);
                        dataWriter.WriteBoolean(mSwapSequence);
                        dataWriter.WriteBoolean(mReachedEnd);

                        mNewWordsChamber.saveState(dataWriter);
                        mFirstChamber.saveState(dataWriter);
                        mSecondChamber.saveState(dataWriter);
                        mThirdChamber.saveState(dataWriter);
                        mFourthChamber.saveState(dataWriter);
                        mFifthChamber.saveState(dataWriter);
                        mCompletedChamber.saveState(dataWriter);

                        IBuffer stateBuffer = dataWriter.DetachBuffer();
                        string stateString = BinaryBufferConverter.getStringFromBuffer(stateBuffer);

                        mCrammerDict.setStateFile(stateString);
                    }
                }
            }
            catch (Exception)
            {
                // Assume mismatch with chamber-size config and contents of .STA file.
                // Delete it so that the dictionary will load successfully next time.
                mCrammerDict.removeStateFile();
            }

            mRestoredState = true;
        }
Example #12
0
        public async void Send(byte[] fileBytes)
        {
            try
            {
                if (Speakers != null && Speakers.Count > 0 && fileBytes != null)
                {
                    //iterate through the speakers and send out the media file to each speaker
                    foreach (Speaker speaker in Speakers)
                    {
                        StreamSocket socket = speaker.Socket;

                        if (socket != null)
                        {
                            IOutputStream outStream = socket.OutputStream;
                            using (DataWriter dataWriter = new DataWriter(outStream))
                            {
                                //write header bytes to indicate to the subscriber 
                                //information about the file to be sent
                                dataWriter.WriteInt16((short)MessageType.Media);
                                dataWriter.WriteInt32(fileBytes.Length);
                                await dataWriter.StoreAsync();
                                //start from 0 and increase by packet size
                                int partNumber = 0;
                                int sourceIndex = 0;
                                int bytesToWrite = fileBytes.Length;
                                while (bytesToWrite > 0)
                                {
                                    dataWriter.WriteInt32(partNumber);
                                    int packetSize = bytesToWrite;
                                    if (packetSize > MAX_PACKET_SIZE)
                                    {
                                        packetSize = MAX_PACKET_SIZE;
                                    }
                                    byte[] fragmentedPixels = new byte[packetSize];
                                    Array.Copy(fileBytes, sourceIndex, fragmentedPixels, 0, packetSize);
                                    dataWriter.WriteBytes(fragmentedPixels);
                                    Debug.WriteLine("sent byte packet length " + packetSize);
                                    await dataWriter.StoreAsync();
                                    sourceIndex += packetSize;
                                    bytesToWrite -= packetSize;
                                    partNumber++;
                                    Debug.WriteLine("sent total bytes " + (fileBytes.Length - bytesToWrite));
                                }
                                //Finally DetachStream
                                dataWriter.DetachStream();
                            }
                        }
                    }


                    //check the speakers have all received the file
                    foreach (Speaker speaker in Speakers)
                    {
                        StreamSocket socket = speaker.Socket;
                        if (socket != null)
                        {
                            //wait for the 'I got it' message
                            DataReader reader = new DataReader(socket.InputStream);
                            uint x = await reader.LoadAsync(sizeof(short));
                            MessageType t = (MessageType)reader.ReadInt16();
                            if (MessageType.Ready == t)
                            {
                                await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                () =>
                                {
                                    Speakers.Remove(speaker);
                                    speaker.Status = "Ready";
                                    Speakers.Add(speaker);
                                });
                            }
                            reader.DetachStream();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
		public async Task<IRandomAccessStream> BeepBeep(int Amplitude, int Frequency, int Duration)
		{
			double A = ((Amplitude * (System.Math.Pow(2, 15))) / 1000) - 1;
			double DeltaFT = 2 * Math.PI * Frequency / 44100.0;

			int Samples = 441 * Duration / 10;
			int Bytes = Samples * 4;
			int[] Hdr = { 0X46464952, 36 + Bytes, 0X45564157, 0X20746D66, 16, 0X20001, 44100, 176400, 0X100004, 0X61746164, Bytes };

			InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
			IOutputStream outStream = ims.GetOutputStreamAt(0);
			DataWriter dw = new DataWriter(outStream);
			dw.ByteOrder = ByteOrder.LittleEndian;

			for (int I = 0; I < Hdr.Length; I++)
			{
				dw.WriteInt32(Hdr[I]);
			}
			for (int T = 0; T < Samples; T++)
			{
				short Sample = System.Convert.ToInt16(A * Math.Sin(DeltaFT * T));
				dw.WriteInt16(Sample);
				dw.WriteInt16(Sample);
			}
			await dw.StoreAsync();
			await outStream.FlushAsync();
			return ims;
		}
Example #14
0
 // Отправка сообщения
 async private void SendMessage(StreamSocket socket, string message)
 {
     var writer = new DataWriter(socket.OutputStream);
     var len = writer.MeasureString(message); // Gets the UTF-8 string length.
     writer.WriteInt32((int)len);
     writer.WriteString(message);
     var ret = await writer.StoreAsync();
     writer.DetachStream();
 }
        /// <summary>
        /// Save the model (family and their notes) to the app's isolated storage
        /// </summary>
        /// <remarks>
        /// The data format for notes data:
        /// 
        ///     Serialized model data (the people and the sticky notes)
        ///     For each sticky note
        ///     {
        ///         int32 number of inkstrokes for the note
        ///     }
        ///     All ink stroke data (for all notes) combined into one container
        /// </remarks>
        /// <returns></returns>
        public async Task SaveModelAsync()
        {
            // Persist the model
            StorageFile notesDataFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(NOTES_MODEL_FILE, CreationCollisionOption.ReplaceExisting);
            using (Stream notesDataStream = await notesDataFile.OpenStreamForWriteAsync())
            {
                // Serialize the model which contains the people and the stickyNote collection
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model));
                serializer.WriteObject(notesDataStream, Model);
            }

            /* For each sticky note, save the number of inkstrokes it contains.
               The function on the InkStrokeContainer that persists its contents is not designed
               to save persist containers to the one stream. We also don't want to manage one
               backing file per note. So combine the ink strokes into one container and persist that.
               We'll seperate out the ink strokes to the right ink control by keeping track of how
               many ink strokes belongs to each note */

            InkStrokeContainer CombinedStrokes = new InkStrokeContainer();
            StorageFile inkFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(NOTES_INK_FILE, CreationCollisionOption.ReplaceExisting);
            using (var randomAccessStream = await inkFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream inkStream = randomAccessStream.GetOutputStreamAt(0)) // DataWriter requires an IOutputStream
                {
                    bool combinedStrokesHasContent = false; // whether we had any ink to save across all of the notes
                    DataWriter writer = new DataWriter(inkStream);
                    foreach (StickyNote Note in Model.StickyNotes)
                    {
                        // Save # strokes for this note
                        if (Note.Ink != null && Note.Ink.GetStrokes().Count > 0)
                        {
                            IReadOnlyList<InkStroke> InkStrokesInNote = Note.Ink.GetStrokes();
                            writer.WriteInt32(InkStrokesInNote.Count);
                            // capture the ink strokes into the combined container which will be saved at the end of the notes data file
                            foreach (InkStroke s in InkStrokesInNote)
                            {
                                CombinedStrokes.AddStroke(s.Clone());
                            }
                            combinedStrokesHasContent = true;
                        }
                        else
                        {
                            writer.WriteInt32(0); // not all notes have ink
                        }
                    }
                    await writer.StoreAsync(); // flush the data in the writer to the inkStream

                    // Persist the ink data
                    if (combinedStrokesHasContent ) 
                    {
                        await CombinedStrokes.SaveAsync(inkStream);
                    }
                }
            }
        }
Example #16
0
        async void ProcessOnOpenCommandSessionComplete(IMbnDeviceService deviceService, int status, uint requestId)
        {
            // Dispatch to UI thread
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
            {
                try
                {
                    string deviceServiceID = deviceService.DeviceServiceID;
                    deviceServicesOutputStr += "\nOnOpenCommandSessionComplete event received for DS: " + deviceServiceID + " request ID: " + requestId.ToString() + " status: 0x" + status.ToString("X");
                    if (deviceService.IsCommandSessionOpen == 1)
                    {
                        uint queryRequestID = 0;
                        // Generate query data
                        // Create the MBIM_PHONEBOOK_READ_REQ structure to get all entries in the phonebook
                        // We use the DataWriter object for this purpose
                        DataWriter dataWriter = new DataWriter();
                        dataWriter.ByteOrder = ByteOrder.LittleEndian;  // MBIM byte ordering is Little Endian

                        dataWriter.WriteInt32(0);   // FilterFlag = MBIMPhonebookFlagAll
                        dataWriter.WriteInt32(0);   // FilterMessageIndex = 0

                        // Get the raw bytes out so that we can send it down to the API
                        byte[] data = dataWriter.DetachBuffer().ToArray();

                        uint commandID = 2;  // MBIM_CID_PHONEBOOK_READ
                        // Query command
                        deviceService.QueryCommand(commandID, data, out queryRequestID);
                        deviceServicesOutputStr += "\n\nWaiting for QueryCommand to complete for requestId: " + queryRequestID.ToString() + "\n";
                    }
                    rootPage.NotifyUser(deviceServicesOutputStr, NotifyType.StatusMessage);
                }
                catch (Exception e)
                {
                    deviceServicesOutputStr = "";
                    rootPage.NotifyUser(ParseExceptionCode(e), NotifyType.ErrorMessage);
                    if (deviceService.IsCommandSessionOpen == 1)
                    {
                        // Close command session
                        uint closeRequestID = 0;
                        deviceService.CloseCommandSession(out closeRequestID);
                        rootPage.NotifyUser("Waiting for CloseCommandSession to complete for requestId: " + closeRequestID.ToString(), NotifyType.StatusMessage);
                    }
                }
            }));
        }
        private void Save(DataWriter textWriter)
        {
            textWriter.WriteStringWithLength(UserId);

            textWriter.WriteInt32(DiscoveryInfoForServices.Count);

            foreach (var i in DiscoveryInfoForServices)
            {
                textWriter.WriteStringWithLength(i.Key);
                textWriter.WriteStringWithLength(i.Value.ServiceResourceId);
                textWriter.WriteStringWithLength(i.Value.ServiceEndpointUri.ToString());
                textWriter.WriteStringWithLength(i.Value.ServiceApiVersion);
            }
        }
Example #18
0
        public static async Task DisconnectAsync()
        {
            if (imageComparisonServer != null)
            {
                try
                {
                    // Properly sends a message notifying we want to close the connection
                    using (var dataWriter = new DataWriter(imageComparisonServer.OutputStream))
                    {
                        dataWriter.WriteInt32((int)ImageServerMessageType.ConnectionFinished);
                        await dataWriter.StoreAsync();
                        await dataWriter.FlushAsync();
                        dataWriter.DetachStream();
                    }
			
                    imageComparisonServer.Dispose();
                }
                catch (Exception)
                {
                }
                imageComparisonServer = null;
            }
        }
 private async void Button_Click_5(object sender, RoutedEventArgs e)
 {
     IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
     StorageFile file = await applicationFolder.CreateFileAsync("text.dat", CreationCollisionOption.ReplaceExisting);
     if (file != null)
     {
         try
         {
             string userContent = "测试的文本消息";
             IBuffer buffer;
             using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
             {
                 using (DataWriter dataWriter = new DataWriter(memoryStream))
                 {
                     dataWriter.WriteInt32(Encoding.UTF8.GetByteCount(userContent));
                     dataWriter.WriteString(userContent);
                     buffer = dataWriter.DetachBuffer();
                 }
             }
             await FileIO.WriteBufferAsync(file, buffer);
             display.Text = "长度为 " + buffer.Length + " bytes 的文本信息写入到了文件 '" + file.Name + "':" + Environment.NewLine + Environment.NewLine + userContent;
         }
         catch (Exception exce)
         {
             display.Text = "异常:" + exce.Message;
         }
     }
     else
     {
         display.Text = "请先创建文件";
     }
 }
        public async Task Should_verify_block_index()
        {
            using (var input = new InMemoryRandomAccessStream())
            {
                await CopyData(input, "IO.HashedBlockStream.bin");

                input.Seek(97390);
                var writer = new DataWriter(input);
                writer.WriteInt32(5);
                await writer.StoreAsync();

                input.Seek(0);
                await Assert.ThrowsAsync<InvalidDataException>(
                    () => HashedBlockFileFormat.Read(input));
            }
        }
Example #21
0
 public void saveState(DataWriter dw)
 {
     dw.WriteInt32(mCurrentWord);
     dw.WriteInt32(mInChamber);
     dw.WriteInt32(mWordsKnownCount);
     for (int i = 0; i < mInChamber; i++)
     {
         dw.WriteInt32(mWordIndices[i]);
     }
 }
Example #22
0
        private static async Task SaveQueueInternalAsync(IotHubClient client)
        {
            try
            {
                System.Collections.Generic.Queue<DataPoint> tmp = null;
                lock (client.thisLock)
                {
                    tmp = new System.Collections.Generic.Queue<DataPoint>(client.queue);
                }
                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                StorageFile file = await storageFolder.CreateFileAsync(FILE_NAME, CreationCollisionOption.ReplaceExisting);
                var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteInt32(tmp.Count);
                        foreach (var item in tmp) { item.Write(dataWriter); }
                        await dataWriter.StoreAsync();
                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
            }
            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;
            }                                         
        }