public PowerLauncherViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, int defaultKeyCode, Func <bool> isDark)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));
            this.isDark    = isDark;

            // To obtain the general Settings configurations of PowerToys
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            callback      = (PowerLauncherSettings settings) =>
            {
                // Propagate changes to Power Launcher through IPC
                // Using InvariantCulture as this is an IPC message
                SendConfigMSG(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
                        PowerLauncherSettings.ModuleName,
                        JsonSerializer.Serialize(settings)));
            };

            if (_settingsUtils.SettingsExists(PowerLauncherSettings.ModuleName))
            {
                settings = _settingsUtils.GetSettingsOrDefault <PowerLauncherSettings>(PowerLauncherSettings.ModuleName);
            }
            else
            {
                settings = new PowerLauncherSettings();
                settings.Properties.OpenPowerLauncher.Alt  = true;
                settings.Properties.OpenPowerLauncher.Code = defaultKeyCode;
                settings.Properties.MaximumNumberOfResults = 4;
                callback(settings);
            }

            switch (settings.Properties.Theme)
            {
            case Theme.Light:
                _isLightThemeRadioButtonChecked = true;
                break;

            case Theme.Dark:
                _isDarkThemeRadioButtonChecked = true;
                break;

            case Theme.System:
                _isSystemThemeRadioButtonChecked = true;
                break;
            }

            foreach (var plugin in Plugins)
            {
                plugin.PropertyChanged += OnPluginInfoChange;
            }
        }
        public PowerLauncherViewModel(Func <string, int> ipcMSGCallBackFunc, int defaultKeyCode)
        {
            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;

            callback = (PowerLauncherSettings settings) =>
            {
                // Propagate changes to Power Launcher through IPC
                SendConfigMSG(
                    string.Format("{{ \"powertoys\": {{ \"{0}\": {1} }} }}", PowerLauncherSettings.ModuleName, JsonSerializer.Serialize(settings)));
            };

            if (SettingsUtils.SettingsExists(PowerLauncherSettings.ModuleName))
            {
                settings = SettingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.ModuleName);
            }
            else
            {
                settings = new PowerLauncherSettings();
                settings.Properties.OpenPowerLauncher.Alt  = true;
                settings.Properties.OpenPowerLauncher.Code = defaultKeyCode;
                settings.Properties.MaximumNumberOfResults = 4;
                callback(settings);
            }

            if (SettingsUtils.SettingsExists())
            {
                generalSettings = SettingsUtils.GetSettings <GeneralSettings>();
            }
            else
            {
                generalSettings = new GeneralSettings();
            }
        }
        public PowerLauncherViewModel(ISettingsUtils settingsUtils, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, int defaultKeyCode)
        {
            _settingsUtils = settingsUtils ?? throw new ArgumentNullException(nameof(settingsUtils));

            // To obtain the general Settings configurations of PowerToys
            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            callback      = (PowerLauncherSettings settings) =>
            {
                // Propagate changes to Power Launcher through IPC
                SendConfigMSG(
                    string.Format("{{ \"powertoys\": {{ \"{0}\": {1} }} }}", PowerLauncherSettings.ModuleName, JsonSerializer.Serialize(settings)));
            };

            if (_settingsUtils.SettingsExists(PowerLauncherSettings.ModuleName))
            {
                settings = _settingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.ModuleName);
            }
            else
            {
                settings = new PowerLauncherSettings();
                settings.Properties.OpenPowerLauncher.Alt  = true;
                settings.Properties.OpenPowerLauncher.Code = defaultKeyCode;
                settings.Properties.MaximumNumberOfResults = 4;
                callback(settings);
            }
        }
Exemple #4
0
        public PowerLauncherViewModel()
        {
            callback = (PowerLauncherSettings settings) =>
            {
                // Propagate changes to Power Launcher through IPC
                ShellPage.DefaultSndMSGCallback(
                    string.Format("{{ \"powertoys\": {{ \"{0}\": {1} }} }}", PowerLauncherSettings.POWERTOYNAME, JsonSerializer.Serialize(settings)));
            };
            if (SettingsUtils.SettingsExists(PowerLauncherSettings.POWERTOYNAME))
            {
                settings = SettingsUtils.GetSettings <PowerLauncherSettings>(PowerLauncherSettings.POWERTOYNAME);
            }
            else
            {
                settings = new PowerLauncherSettings();
                settings.properties.open_powerlauncher.Alt    = true;
                settings.properties.open_powerlauncher.Code   = (int)Windows.System.VirtualKey.Space;
                settings.properties.maximum_number_of_results = 4;
                callback(settings);
            }

            if (SettingsUtils.SettingsExists())
            {
                generalSettings = SettingsUtils.GetSettings <GeneralSettings>();
            }
            else
            {
                generalSettings = new GeneralSettings();
            }
        }
Exemple #5
0
 /// <summary>
 /// 独立模式发送数据
 /// </summary>
 /// <param name="host"></param>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 /// <param name="content"></param>
 /// <param name="callback"></param>
 public static void Send(IHost host, string ip, int port, string content, SendCallback callback = null)
 {
     // 建立客户端并连接服务器
     using (Client client = new Client(host, ip, port)) {
         // 发送测试数据
         client.Send(content, callback);
     }
 }
Exemple #6
0
 /// <summary>
 /// 独立模式发送数据
 /// </summary>
 /// <param name="host"></param>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 /// <param name="content"></param>
 /// <param name="callback"></param>
 public static void Send(IHost host, string ip, int port, string content, SendCallback callback = null)
 {
     // 建立客户端并连接服务器
     using (ssr.Client client = new ssr.Client(host, "127.0.0.1", 8888)) {
         // 发送测试数据
         client.Send(content, callback);
     }
 }
Exemple #7
0
        //////////// Methods for sending ////////////////////////


        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        ///
        ///    ss.BeginSend("Hello world", callback, payload);
        ///
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has
        /// successfully written the string to the underlying Socket, or failed in the
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="callback"></param>
        /// <param name="payload"></param>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            //Place the Callback on the Queue.
            sendQueue.Enqueue(new SendRequest(s, callback, payload));

            // For the first sendRequest start sending. Otherwise sending is in progress.
            if (sendQueue.Count == 1)
            {
                SendBytes();
            }
        }
Exemple #8
0
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 ///
 ///    ss.BeginSend("Hello world", callback, payload);
 ///
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has
 /// successfully written the string to the underlying Socket, or failed in the
 /// attempt, it invokes the callback.  The parameters to the callback are a
 /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
 /// the Exception that caused the send attempt to fail.
 ///
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 ///
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying about synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     lock (sendKey)
     {
         sends.Enqueue(new SendInteraction(s, callback, payload));
         if (sends.Count == 1)
         {
             loopSendsQueue();
         }
     }
 }
Exemple #9
0
        /// <summary>
        /// Called when a message has been successfully sent
        /// </summary>
        private void SendAsync(IAsyncResult result)
        {
            lock (sendLock)
            {
                var          internalPayload = (Tuple <byte[], SendCallback, object>)result.AsyncState;
                byte[]       stringBytes     = internalPayload.Item1;
                SendCallback callback        = internalPayload.Item2;
                object       outgoingPayload = internalPayload.Item3;

                Task task = new Task(() => callback(true, outgoingPayload));
                task.Start();
            }
        }
Exemple #10
0
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 ///
 ///    ss.BeginSend("Hello world", callback, payload);
 ///
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has
 /// successfully written the string to the underlying Socket it invokes the callback.
 /// The parameters to the callback are true and the payload.
 ///
 /// If it is impossible to send because the underlying Socket has closed, the callback
 /// is invoked with false and the payload as parameters.
 ///
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 ///
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     lock (sendLock)
     {
         byte[] stringBytes = encoding.GetBytes(s);
         //SendQueue.Enqueue(callback);
         //SendPayLoadQueue.Enqueue(payload);
         //SendCallback returncallback = SendQueue.Dequeue();
         //object returnpayload = SendPayLoadQueue.Dequeue();
         object outgoingPayload = new Tuple <byte[], SendCallback, object>(stringBytes, callback, payload);
         socket.BeginSend(stringBytes, 0, stringBytes.Length, SocketFlags.None, SendAsync, outgoingPayload);
     }
 }
Exemple #11
0
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        ///
        ///    ss.BeginSend("Hello world", callback, payload);
        ///
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has
        /// successfully written the string to the underlying Socket, or failed in the
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            SendRequest sendRequest = new SendRequest(s, callback, payload);

            SendQueue.Enqueue(sendRequest);

            SendMessage(SendQueue.Peek());
            SendRequest currnetSR = SendQueue.Dequeue();

            lock (sendSync)
            {
                ThreadPool.QueueUserWorkItem(x => currnetSR.sendCallBack(null, currnetSR.payload));
            }
        }
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        ///
        ///    ss.BeginSend("Hello world", callback, payload);
        ///
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has
        /// successfully written the string to the underlying Socket, or failed in the
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            lock (sendLock)
            {
                //Create a new request and add it to the queue
                Request newRequest = new Request(encoding.GetBytes(s), callback, payload);
                sendQueue.Enqueue(newRequest);

                Request currentRequest = sendQueue.Dequeue();

                //Begin sending with the MessageBuffer attached to the request class instance
                byte[] currentRequestMessage = currentRequest.MessageBuffer;
                client.BeginSend(currentRequestMessage, 0, currentRequestMessage.Length, SocketFlags.None, BeginSendCallback, currentRequest);
            }
        }
Exemple #13
0
        private void ProcessSend(object sender, SocketAsyncEventArgs e)
        {
            logger?.Info($"Session.ProcessSend: this={GetHashCode()}, e.SocketError={e?.SocketError}");

            if (e.SocketError == SocketError.Success && 0 < e.BytesTransferred)
            {
                SendCallback?.Invoke(sender, new SessionEventArgs {
                    BytesTransferred = e.BytesTransferred
                });
            }
            else
            {
                CloseSocket(e);
            }
        }
Exemple #14
0
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 ///
 ///    ss.BeginSend("Hello world", callback, payload);
 ///
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has
 /// successfully written the string to the underlying Socket, or failed in the
 /// attempt, it invokes the callback.  The parameters to the callback are a
 /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
 /// the Exception that caused the send attempt to fail.
 ///
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 ///
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     // Add the request to the queue and launch the sending process if the queue
     // was previously empty.  Otherwise, the sending process is in process and
     // this new entry will be dealt with.
     lock (sendRequests)
     {
         sendRequests.Enqueue(new SendRequest {
             Text = s, Callback = callback, Payload = payload
         });
         if (sendRequests.Count == 1)
         {
             ProcessSendQueue();
         }
     }
 }
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="state">标识码</param>
        /// <param name="data">数据</param>
        /// <param name="action"></param>
        public bool Send(int state, byte[] data, Action <bool, byte[]> action, int sheep = 2000)
        {
            bool stateTemp = false;

            lock (sendLock)
            {
                lock (ClassStatic.sendCallbackLock)
                {
                    if (socketConnect && socketClient != null && data.Length < 999999999)
                    {
                        // 为回调函数生成唯一标识
                        string      token      = Guid.NewGuid().ToString().Replace("-", "");
                        List <byte> byteSource = new List <byte>();
                        byte[]      byteState  = Encoding.UTF8.GetBytes(state.ToString().PadLeft(3, '0'));

                        byte[] byteCallbackId = Encoding.UTF8.GetBytes(token);

                        byteSource.AddRange(byteState);
                        byteSource.AddRange(new byte[] { 1 });
                        byteSource.AddRange(byteCallbackId);
                        byteSource.AddRange(data);

                        data = byteSource.ToArray();

                        try
                        {
                            socketClient.Send(data);

                            SendCallback sendCallback = new SendCallback();
                            sendCallback.date   = DateTime.Now.AddMilliseconds(sheep);
                            sendCallback.action = action;

                            lock (ClassStatic.sendCallbackLock)
                            {
                                sendCallbackList.Add(token, sendCallback);
                            }
                            stateTemp = true;
                        }
                        catch
                        {
                        }
                    }
                }
            }// sendLock锁
            return(stateTemp);
        }
Exemple #16
0
        /// <summary>
        ///
        /// We can write a string to a StringSocket ss by doing
        ///
        ///    ss.BeginSend("Hello world", callback, payload);
        ///
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has
        /// successfully written the string to the underlying Socket, or failed in the
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            lock (sendQueue) // lock on to the sendQueue (the lock object is arbitrary)
            {
                // create a new SendMessage with the data and add it to the queue
                sendQueue.Enqueue(new SendMessage {
                    message = s, callback = callback, payload = payload
                });

                // if the second thread for processing send message is not running,
                // then start a new thread to process the messages
                if (!isSending)
                {
                    isSending = true;
                    SendNextMessage();
                }
            }
        }
Exemple #17
0
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        ///
        ///    ss.BeginSend("Hello world", callback, payload);
        ///
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has
        /// successfully written the string to the underlying Socket, or failed in the
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            // Protect SendQueue
            lock (SendQueue)
            {
                // Create and store the send request.
                SendRequest sendRequest = new SendRequest(s, callback, payload);
                SendQueue.Enqueue(sendRequest);

                // If there's not a send ongoing, start one.
                if (SendQueue.Count() == 1)
                {
                    // Append the message to the unsent string
                    outgoing += s;

                    SendBytes();
                }
            }
        }
Exemple #18
0
        /// <summary>
        /// Runs the client sending messages example.
        /// </summary>
        /// <param name="cancellationToken">A token used to end the client example.</param>
        /// <param name="args">A single string should be used for the server url.</param>
        public async Task Run(CancellationToken cancellationToken, string[] args)
        {
            var serverUrl = args[0];
            var session   = Diffusion.Sessions.Principal("control").Password("password").Open(serverUrl);
            var messaging = session.Messaging;

            var topicPath    = ">random/messages";
            var sendCallback = new SendCallback(topicPath);

            while (!cancellationToken.IsCancellationRequested)
            {
                var newMessage = $"Sending message {DateTime.Now.TimeOfDay.ToString( "g" )} to topic path {topicPath}";
                messaging.Send(topicPath, newMessage, sendCallback);

                await Task.Delay(500);
            }

            // Close the session
            session.Close();
        }
Exemple #19
0
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        ///
        ///    ss.BeginSend("Hello world", callback, payload);
        ///
        /// where callback is a SendCallback (see above) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has
        /// successfully written the string to the underlying Socket, or failed in the
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail.
        ///
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        ///
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            // Get exclusive access
            lock (sendQueue)
            {
                // Enqueue the received 'send' request with its parameters
                sendQueue.Enqueue(new SendRequest()
                {
                    Text     = s,
                    SendBack = callback,
                    Payload  = payload
                });
                if (sendQueue.Count != 1)
                {
                    return;
                }

                // Call the helper method to properly take care of sending the queued strings
                HandleSendQueue();
            }
        }
Exemple #20
0
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 /// 
 ///    ss.BeginSend("Hello world", callback, payload);
 ///    
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
 /// successfully written the string to the underlying Socket, or failed in the 
 /// attempt, it invokes the callback.  The parameters to the callback are a
 /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
 /// the Exception that caused the send attempt to fail. 
 /// 
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 /// 
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     // create and queue up dictionary with s, callback and payload
     Dictionary<string, object> dict = new Dictionary<string, object>(3);
     dict.Add("message", s);
     dict.Add("callback", callback);
     dict.Add("payload", payload);
     sendQueue.Enqueue(dict);
 }
Exemple #21
0
 /*-----------Flatbuffer相关-----------*/
 public void SendMsg(SendCallback callback)
 {
     sendStack.Push(callback);
     //var msg = ScPlayerBasic.GetRootAsScPlayerBasic(new ByteBuffer(fb.SizedByteArray()));
     //CLog.Info(msg.MsgID.ToString());
 }
Exemple #22
0
 public SendInteraction(string _message, SendCallback _sendCB, object _Payload)
 {
     Message = _message;
     sendCB = _sendCB;
     payload = _Payload;
 }
Exemple #23
0
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 /// 
 ///    ss.BeginSend("Hello world", callback, payload);
 ///    
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
 /// successfully written the string to the underlying Socket, or failed in the 
 /// attempt, it invokes the callback.  The parameters to the callback are a
 /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
 /// the Exception that caused the send attempt to fail. 
 /// 
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 /// 
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying about synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     lock (sendKey)
     {
         sends.Enqueue(new SendInteraction(s, callback, payload));
         if(sends.Count==1)
             loopSendsQueue();
     }
 }
Exemple #24
0
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 /// 
 ///    ss.BeginSend("Hello world", callback, payload);
 ///    
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
 /// successfully written the string to the underlying Socket, or failed in the 
 /// attempt, it invokes the callback.  The parameters to the callback are a
 /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
 /// the Exception that caused the send attempt to fail. 
 /// 
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 /// 
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     lock (SendLock)
     {
         // Enqueue the SendRequest. If the request is the first, start processing
         // the request. Otherwise simply enqueue it and it will be taken care of
         // later.
         SendRequests.Enqueue(new SendRequest { TextToSend = s, Callback = callback, Payload = payload });
         if (SendRequests.Count == 1)
             ProcessSend();
     }
 }
 /// <summary>
 /// Sends an email to the specified users who have the application.
 /// </summary>
 /// <example>
 /// <code>
 /// private static void RunDemoAsync()
 /// {
 ///     List&lt;long&gt; notificationList = new List&lt;long&gt;();
 ///     notificationList.Add(Constants.UserId);
 ///     string fbml = string.Format("&lt;fb:switch&gt;&lt;fb:profile-pic uid=\"{0}\" /&gt;&lt;fb:default&gt;Unable to show profile pic&lt;/fb:default&gt;&lt;/fb:switch&gt;", Constants.UserId);
 ///     Api api = new Api(new DesktopSession(Constants.ApplicationKey, Constants.ApplicationSecret, Constants.ApplicationSecret, Constants.SessionKey));
 ///
 ///     // This action will require the user to have granted this app "email" Extended Permission.
 ///     //var result = api.Notifications.SendEmail(notificationList, "email test", "here is plain text", string.Empty);
 ///     api.Notifications.SendEmailAsync(notificationList, "email test", string.Empty, fbml, AsyncDemoCompleted, null);
 /// }
 ///
 /// private static void AsyncDemoCompleted(string result, Object state, FacebookException e)
 /// {
 ///     var actual = result;
 /// }
 /// </code>
 /// </example>
 /// <param name="recipients">A List of recipient IDs. The recipients must be people who have already added your application. You can email up to 100 people at a time.</param>
 /// <param name="subject">The subject of the email message. As of 10/28/2008, the subject will accept a limited set of FBML tags, including names, and tags related to internationalization.</param>
 /// <param name="plainText">The plain text version of the email content. You must include a non-empty value for at least one of either the fbml or text parameters. The FBML input takes precedence, but if the given FBML value is invalid or cannot be rendered, then the text will be used instead. There is currently no character limit on the length of either the text or FBML body.</param>
 /// <param name="fbml">The FBML version of the email. You must include a non-empty value for at least one of either the fbml or text parameters. The fbml parameter is a stripped-down set of FBML that allows only HTML/FBML tags that result in text, links, linebreaks, as well as tags related to internationalization.</param>
 /// <param name="callback">The AsyncCallback delegate</param>
 /// <param name="state">An object containing state information for this asynchronous request</param>        
 /// <returns>This returns a comma-separated list of user ids for whom notifications were successfully sent. We will throw an error if an error occurred.</returns>
 public void SendEmailAsync(List<long> recipients, string subject, string plainText, string fbml, SendCallback callback, Object state)
 {
     SendEmailAsync(StringHelper.ConvertToCommaSeparated(recipients), subject, plainText, fbml, callback, state);
 }
Exemple #26
0
 /// <summary>
 /// 发送带换行标志的数据
 /// </summary>
 /// <param name="content">待发送的操作命令,以\r\n结尾</param>
 /// <param name="callback">回调函数</param>
 public void Sendln(string content, SendCallback callback = null)
 {
     Send(content + "\r\n", callback);
 }
 /// <summary>
 /// We can write a string to a StringSocket ss by doing
 /// 
 ///    ss.BeginSend("Hello world", callback, payload);
 ///    
 /// where callback is a SendCallback (see below) and payload is an arbitrary object.
 /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
 /// successfully written the string to the underlying Socket, or failed in the 
 /// attempt, it invokes the callback.  The parameters to the callback are a
 /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
 /// the Exception that caused the send attempt to fail. 
 /// 
 /// This method is non-blocking.  This means that it does not wait until the string
 /// has been sent before returning.  Instead, it arranges for the string to be sent
 /// and then returns.  When the send is completed (at some time in the future), the
 /// callback is called on another thread.
 /// 
 /// This method is thread safe.  This means that multiple threads can call BeginSend
 /// on a shared socket without worrying around synchronization.  The implementation of
 /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
 /// string arriving via a BeginSend method call must be sent (in its entirety) before
 /// a later arriving string can be sent.
 /// </summary>
 public void BeginSend(String s, SendCallback callback, object payload)
 {
     // Add the request to the queue and launch the sending process if the queue
     // was previously empty.  Otherwise, the sending process is in process and
     // this new entry will be dealt with.
     lock (sendRequests)
     {
         sendRequests.Enqueue(new SendRequest { Text = s, Callback = callback, Payload = payload });
         if (sendRequests.Count == 1)
         {
             ProcessSendQueue();
         }
     }
 }
        private string Send(string to_ids, string notification, string type, bool isAsync, SendCallback callback, Object state)
        {
            var parameterList = new Dictionary<string, string>
                                    {
                                        {"method", "facebook.notifications.send"},
                                        {"to_ids", to_ids}
                                    };
            Utilities.AddFBMLParameter(parameterList, "notification", notification);
            Utilities.AddOptionalParameter(parameterList, "type", type);

            if (isAsync)
            {
                SendRequestAsync<notifications_send_response, string>(parameterList, !string.IsNullOrEmpty(Session.SessionKey), new FacebookCallCompleted<string>(callback), state);
                return null;
            }

            var response = SendRequest<notifications_send_response>(parameterList, !string.IsNullOrEmpty(Session.SessionKey));
            return response == null ? null : response.TypedValue;
        }
Exemple #29
0
 /// <summary>
 /// 独立模式发送带换行标志数据
 /// </summary>
 /// <param name="host"></param>
 /// <param name="ip"></param>
 /// <param name="port"></param>
 /// <param name="content"></param>
 /// <param name="callback"></param>
 public static void Sendln(IHost host, string ip, int port, string content, SendCallback callback = null)
 {
     Send(host, ip, port, content + "\r\n", callback);
 }
        private string SendEmail(string recipients, string subject, string text, string fbml, bool isAsync, SendCallback callback, Object state)
        {
            var parameterList = new Dictionary<string, string>
                                    {
                                        {"method", "facebook.notifications.sendEmail"},
                                        {"recipients", recipients},
                                        {"subject", subject},
                                        {"text", text}
                                    };

            Utilities.AddFBMLParameter(parameterList, "fbml", fbml);

            if (isAsync)
            {
                SendRequestAsync<notifications_sendEmail_response, string>(parameterList, !string.IsNullOrEmpty(Session.SessionKey), new FacebookCallCompleted<string>(callback), state);
                return null;
            }

            var response = SendRequest<notifications_sendEmail_response>(parameterList, !string.IsNullOrEmpty(Session.SessionKey));
            return response == null ? null : response.TypedValue;
        }
Exemple #31
0
 public RealtimeDataCache(SendCallback callback)
 {
     SetNotifyCallback(callback);
 }
 /// <summary>
 /// Sends a notification to a set of users.
 /// </summary>
 /// <example>
 /// <code>
 /// private static void RunDemoAsync()
 /// {
 ///     Api api = new Api(new DesktopSession(Constants.ApplicationKey, Constants.ApplicationSecret, Constants.ApplicationSecret, Constants.SessionKey));
 ///     api.Notifications.SendAsync(Constants.UserId.ToString(), "my notification from samples app", "app_to_user", AsyncDemoCompleted, null);
 /// }
 ///
 /// private static void AsyncDemoCompleted(string result, Object state, FacebookException e)
 /// {
 ///     var actual = result;
 /// }
 /// </code>
 /// </example>
 /// <param name="to_ids">List recipient IDs. These must be either friends of the logged-in user or people who have added your application. To send a notification to the current logged-in user without a name prepended to the message, set to_ids to empty List.</param>
 /// <param name="notification">The content of the notification. The notification uses a stripped down version of FBML and HTML, allowing only text and links (see the list of allowed tags). The notification can contain up to 2,000 characters.</param>
 /// <param name="type">Specify whether the notification is a user_to_user one or an app_to_user. (Default value is user_to_user.)</param>
 /// <param name="callback">The AsyncCallback delegate</param>
 /// <param name="state">An object containing state information for this asynchronous request</param>        
 /// <returns>This returns a list of user ids for whom notifications were successfully sent. We will throw an error if an error occurred.</returns>
 /// <remarks>The notification parameter is a very stripped-down set of FBML which allows only tags that result in just text and links.</remarks>
 public void SendAsync(string to_ids, string notification, string type, SendCallback callback, Object state)
 {
     Send(to_ids, notification, type, true, callback, state);
 }
Exemple #33
0
 public void SetNotifyCallback(SendCallback callback)
 {
     m_callback = callback;
 }
 /// <summary>
 /// Sends an email to the specified users who have the application.
 /// </summary>
 /// <example>
 /// <code>
 /// private static void RunDemoAsync()
 /// {
 ///     string fbml = string.Format("&lt;fb:switch&gt;&lt;fb:profile-pic uid=\"{0}\" /&gt;&lt;fb:default&gt;Unable to show profile pic&lt;/fb:default&gt;&lt;/fb:switch&gt;", Constants.UserId);
 ///     Api api = new Api(new DesktopSession(Constants.ApplicationKey, Constants.ApplicationSecret, Constants.ApplicationSecret, Constants.SessionKey));
 ///
 ///     // This action will require the user to have granted this app "email" Extended Permission.
 ///     //var result = api.Notifications.SendEmail(Constants.UserId.ToString(), "email test", "here is plain text", string.Empty);
 ///     api.Notifications.SendEmailAsync(Constants.UserId.ToString(), "email test", string.Empty, fbml, AsyncDemoCompleted, null);
 /// }
 ///
 /// private static void AsyncDemoCompleted(string result, Object state, FacebookException e)
 /// {
 ///     var actual = result;
 /// }
 /// </code>
 /// </example>
 /// <param name="recipients">A comma-separated list of recipient IDs. The recipients must be people who have already added your application. You can email up to 100 people at a time.</param>
 /// <param name="subject">The subject of the email message. As of 10/28/2008, the subject will accept a limited set of FBML tags, including names, and tags related to internationalization.</param>
 /// <param name="plainText">The plain text version of the email content. You must include a non-empty value for at least one of either the fbml or text parameters. The FBML input takes precedence, but if the given FBML value is invalid or cannot be rendered, then the text will be used instead. There is currently no character limit on the length of either the text or FBML body.</param>
 /// <param name="fbml">The FBML version of the email. You must include a non-empty value for at least one of either the fbml or text parameters. The fbml parameter is a stripped-down set of FBML that allows only HTML/FBML tags that result in text, links, linebreaks, as well as tags related to internationalization.</param>
 /// <param name="callback">The AsyncCallback delegate</param>
 /// <param name="state">An object containing state information for this asynchronous request</param>        
 /// <returns>This returns a comma-separated list of user ids for whom notifications were successfully sent. We will throw an error if an error occurred.</returns>
 public void SendEmailAsync(string recipients, string subject, string plainText, string fbml, SendCallback callback, Object state)
 {
     SendEmail(recipients, subject, plainText, fbml, true, callback, state);
 }
Exemple #35
0
        public PowerLauncherViewModel(PowerLauncherSettings settings, ISettingsRepository <GeneralSettings> settingsRepository, Func <string, int> ipcMSGCallBackFunc, Func <bool> isDark)
        {
            if (settings == null)
            {
                throw new ArgumentException("settings argument can not be null");
            }

            this.settings = settings;
            this.isDark   = isDark;

            // To obtain the general Settings configurations of PowerToys
            if (settingsRepository == null)
            {
                throw new ArgumentNullException(nameof(settingsRepository));
            }

            GeneralSettingsConfig = settingsRepository.SettingsConfig;

            // set the callback functions value to hangle outgoing IPC message.
            SendConfigMSG = ipcMSGCallBackFunc;
            callback      = (PowerLauncherSettings s) =>
            {
                // Propagate changes to Power Launcher through IPC
                // Using InvariantCulture as this is an IPC message
                SendConfigMSG(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{{ \"powertoys\": {{ \"{0}\": {1} }} }}",
                        PowerLauncherSettings.ModuleName,
                        JsonSerializer.Serialize(s)));
            };

            switch (settings.Properties.Theme)
            {
            case Theme.Dark:
                _themeIndex = 0;
                break;

            case Theme.Light:
                _themeIndex = 1;
                break;

            case Theme.System:
                _themeIndex = 2;
                break;
            }

            switch (settings.Properties.Position)
            {
            case StartupPosition.Cursor:
                _monitorPositionIndex = 0;
                break;

            case StartupPosition.PrimaryMonitor:
                _monitorPositionIndex = 1;
                break;

            case StartupPosition.Focus:
                _monitorPositionIndex = 2;
                break;
            }

            foreach (var plugin in Plugins)
            {
                plugin.PropertyChanged += OnPluginInfoChange;
            }

            SearchPluginsCommand = new RelayCommand(SearchPlugins);
        }
 /// <summary>
 /// Sends a notification to a set of users.
 /// </summary>
 /// <example>
 /// <code>
 /// private static void RunDemoAsync()
 /// {
 ///     List&lt;long&gt; notificationList = new List&lt;long&gt;();
 ///     notificationList.Add(Constants.UserId);
 ///     Api api = new Api(new DesktopSession(Constants.ApplicationKey, Constants.ApplicationSecret, Constants.ApplicationSecret, Constants.SessionKey));
 ///     api.Notifications.SendAsync(notificationList, "my notification from samples app", "app_to_user", AsyncDemoCompleted, null);
 /// }
 ///
 /// private static void AsyncDemoCompleted(string result, Object state, FacebookException e)
 /// {
 ///     var actual = result;
 /// }
 /// </code>
 /// </example>
 /// <param name="to_ids">List recipient IDs. These must be either friends of the logged-in user or people who have added your application. To send a notification to the current logged-in user without a name prepended to the message, set to_ids to empty List.</param>
 /// <param name="notification">The content of the notification. The notification uses a stripped down version of FBML and HTML, allowing only text and links (see the list of allowed tags). The notification can contain up to 2,000 characters.</param>
 /// <param name="type">Specify whether the notification is a user_to_user one or an app_to_user. (Default value is user_to_user.)</param>
 /// <param name="callback">The AsyncCallback delegate</param>
 /// <param name="state">An object containing state information for this asynchronous request</param>        
 /// <returns>This returns a list of user ids for whom notifications were successfully sent. We will throw an error if an error occurred.</returns>
 /// <remarks>The notification parameter is a very stripped-down set of FBML which allows only tags that result in just text and links.</remarks>
 public void SendAsync(List<long> to_ids, string notification, string type, SendCallback callback, Object state)
 {
     SendAsync(StringHelper.ConvertToCommaSeparated(to_ids), notification, type, callback, state);
 }
Exemple #37
0
 public PowerLauncherViewModel(PowerLauncherSettings settings, SendCallback callback)
 {
     this.settings = settings;
     this.callback = callback;
 }
Exemple #38
0
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        /// 
        ///    ss.BeginSend("Hello world", callback, payload);
        ///    
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
        /// successfully written the string to the underlying Socket, or failed in the 
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail. 
        /// 
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
       {
            // Protect SendQueue
            lock (SendQueue)
            {
                // Create and store the send request.
                SendRequest sendRequest = new SendRequest(s, callback, payload);
                SendQueue.Enqueue(sendRequest);

                // If there's not a send ongoing, start one.
                if (SendQueue.Count() == 1)
                {
                    // Append the message to the unsent string
                    outgoing += s;

                    SendBytes();
                }

            }
        }
Exemple #39
0
 /// <summary>
 /// 发送数据
 /// </summary>
 /// <param name="content">待发送的操作命令,以\r\n结尾</param>
 /// <param name="callback">回调函数</param>
 public void Send(string content, SendCallback callback = null)
 {
     // 发送信息
     Send(Encoding.UTF8.GetBytes(content), callback);
 }
Exemple #40
0
 public SendRequest(String m, SendCallback cb, Object o)
 {
     message = m;
     sendCallBack = cb;
     payload = o;
 }
Exemple #41
0
        private string Send(string to_ids, string notification, string type, bool isAsync, SendCallback callback, Object state)
        {
            var parameterList = new Dictionary <string, string>
            {
                { "method", "facebook.notifications.send" },
                { "to_ids", to_ids }
            };

            Utilities.AddFBMLParameter(parameterList, "notification", notification);
            Utilities.AddOptionalParameter(parameterList, "type", type);

            if (isAsync)
            {
                SendRequestAsync <notifications_send_response, string>(parameterList, !string.IsNullOrEmpty(Session.SessionKey), new FacebookCallCompleted <string>(callback), state);
                return(null);
            }

            var response = SendRequest <notifications_send_response>(parameterList, !string.IsNullOrEmpty(Session.SessionKey));

            return(response == null ? null : response.TypedValue);
        }
 /// <summary>
 /// Sends a notification to a set of users.
 /// </summary>
 /// <example>
 /// <code>
 /// private static void RunDemoAsync()
 /// {
 ///     Api api = new Api(new DesktopSession(Constants.ApplicationKey, Constants.ApplicationSecret, Constants.ApplicationSecret, Constants.SessionKey));
 ///     api.Notifications.SendAsync(Constants.UserId.ToString(), "my notification from samples app", AsyncDemoCompleted, null);
 /// }
 ///
 /// private static void AsyncDemoCompleted(string result, Object state, FacebookException e)
 /// {
 ///     var actual = result;
 /// }
 /// </code>
 /// </example>
 /// <param name="to_ids">Comma-separated list of recipient IDs. These must be either friends of the logged-in user or people who have added your application. To send a notification to the current logged-in user without a name prepended to the message, set to_ids to empty List.</param>
 /// <param name="notification">The content of the notification. The notification uses a stripped down version of FBML and HTML, allowing only text and links (see the list of allowed tags). The notification can contain up to 2,000 characters.</param>
 /// <param name="callback">The AsyncCallback delegate</param>
 /// <param name="state">An object containing state information for this asynchronous request</param>        
 /// <returns>This returns a list of user ids for whom notifications were successfully sent. We will throw an error if an error occurred.</returns>
 /// <remarks>The notification parameter is a very stripped-down set of FBML which allows only tags that result in just text and links.</remarks>
 public void SendAsync(string to_ids, string notification, SendCallback callback, Object state)
 {
     SendAsync(to_ids, notification, null, callback, state);
 }
Exemple #43
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="bytes">待发送的字节数组</param>
        /// <param name="callback">回调函数</param>
        public void Send(byte[] bytes, SendCallback callback = null)
        {
            // 发送信息
            _stream.Write(bytes);
            _stream.Flush();

            // 当设置了回调后,开始等待接收数据
            if (callback != null)
            {
                // 结束和超时标志
                bool isEnd = false;

                // 设置回车标志
                bool r = false;

                // 设置字节列表
                _command = new List <byte>();

                // 设置当未满足结束和未超时时进行循环
                while (!isEnd)
                {
                    // 根据当前模式读取数据
                    if (this.DataMode)
                    {
                        #region [=====数据模式=====]

                        // 根据缓存大小读取数据
                        int len = _stream.Read(_buffer, _offset, _buffer.Length - _offset);

                        // 增加数据偏移
                        _offset += len;

                        // 判断数据是否读取完毕,如已读取完毕,则开始处理业务
                        if (_offset >= _buffer.Length)
                        {
                            // 获取数据字符串
                            string data = System.Text.Encoding.UTF8.GetString(_buffer);

                            // 执行业务调用
                            using (ClientHostRecieveEventArgs e = new ClientHostRecieveEventArgs()) {
                                e.Client  = this;
                                e.Content = data;

                                //执行宿主事件
                                _host.OnRecieve(e);

                                if (e.Result == HostEventResults.Finished)
                                {
                                    // 设置回调
                                    callback(e.ResultData);

                                    // 设置结束标志
                                    isEnd = true;
                                }
                            }

                            // 设置为命令模式
                            SetCommandMode();
                        }

                        #endregion
                    }
                    else
                    {
                        #region [=====命令模式=====]
                        //命令模式,判断换行标志提取命令

                        // 读取一个字节
                        int bs = _stream.ReadByte();

                        if (bs >= 0)
                        {
                            // 读入正常数据后进行数据解析
                            switch (bs)
                            {
                            case 13:    //回车(\r)

                                // 出现两个连续的回车标志则视为非常规
                                if (r)
                                {
                                    //调试输出错误信息
                                    Debug.WriteLine("-> Error:规则外的回车符");
                                }

                                r = true;
                                break;

                            case 10:    //换行(\n)

                                if (r)
                                {
                                    //获取行命令并重置回车标志
                                    string cmd = System.Text.Encoding.UTF8.GetString(_command.ToArray());
                                    r = false;

                                    //执行业务调用
                                    using (ClientHostRecieveEventArgs e = new ClientHostRecieveEventArgs()) {
                                        e.Client  = this;
                                        e.Content = cmd;

                                        //执行宿主事件
                                        _host.OnRecieve(e);

                                        if (e.Result == HostEventResults.Finished)
                                        {
                                            // 设置回调
                                            callback(e.ResultData);

                                            // 设置结束标志
                                            isEnd = true;
                                        }
                                    }
                                }
                                else
                                {
                                    //调试输出错误信息
                                    Debug.WriteLine("-> Error:规则外的换行符");
                                }

                                // 清除命令字节列表
                                _command.Clear();
                                break;

                            default:

                                // 正常情况下,不应该在此处出现回车标志
                                if (r)
                                {
                                    //调试输出错误信息
                                    Debug.WriteLine("-> Error:规则外的换行符");

                                    // 清除命令字节列表并重置回车标志
                                    _command.Clear();
                                    r = false;
                                }

                                // 将命令字符加入命令字节列表中
                                _command.Add((byte)bs);
                                break;
                            }
                        }
                        else
                        {
                            // 未读取数据,则线程等待毫秒,防止线程阻塞
                            System.Threading.Thread.Sleep(10);
                        }

                        #endregion
                    }
                }
            }
        }
Exemple #44
0
        private string SendEmail(string recipients, string subject, string text, string fbml, bool isAsync, SendCallback callback, Object state)
        {
            var parameterList = new Dictionary <string, string>
            {
                { "method", "facebook.notifications.sendEmail" },
                { "recipients", recipients },
                { "subject", subject },
                { "text", text }
            };

            Utilities.AddFBMLParameter(parameterList, "fbml", fbml);

            if (isAsync)
            {
                SendRequestAsync <notifications_sendEmail_response, string>(parameterList, !string.IsNullOrEmpty(Session.SessionKey), new FacebookCallCompleted <string>(callback), state);
                return(null);
            }

            var response = SendRequest <notifications_sendEmail_response>(parameterList, !string.IsNullOrEmpty(Session.SessionKey));

            return(response == null ? null : response.TypedValue);
        }
Exemple #45
0
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        /// 
        ///    ss.BeginSend("Hello world", callback, payload);
        ///    
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
        /// successfully written the string to the underlying Socket, or failed in the 
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail. 
        /// 
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {

            SendRequest sendRequest = new SendRequest(s, callback, payload);
            SendQueue.Enqueue(sendRequest);

            SendMessage(SendQueue.Peek());
            SendRequest currnetSR = SendQueue.Dequeue();
            lock (sendSync)
            {
                ThreadPool.QueueUserWorkItem(x => currnetSR.sendCallBack(null, currnetSR.payload));
            }
        }
Exemple #46
0
        /// <summary>
        /// We can write a string to a StringSocket ss by doing
        /// 
        ///    ss.BeginSend("Hello world", callback, payload);
        ///    
        /// where callback is a SendCallback (see below) and payload is an arbitrary object.
        /// This is a non-blocking, asynchronous operation.  When the StringSocket has 
        /// successfully written the string to the underlying Socket, or failed in the 
        /// attempt, it invokes the callback.  The parameters to the callback are a
        /// (possibly null) Exception and the payload.  If the Exception is non-null, it is
        /// the Exception that caused the send attempt to fail. 
        /// 
        /// This method is non-blocking.  This means that it does not wait until the string
        /// has been sent before returning.  Instead, it arranges for the string to be sent
        /// and then returns.  When the send is completed (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginSend
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginSend must take care of synchronization instead.  On a given StringSocket, each
        /// string arriving via a BeginSend method call must be sent (in its entirety) before
        /// a later arriving string can be sent.
        /// 
        /// **reminder: payload never goes out over the internet, only between string socket and original program / server**
        /// </summary>
        public void BeginSend(String s, SendCallback callback, object payload)
        {
            // Enqueue the incoming message as a message object, lock so we don't mess up the queue
            lock (lockSend)
            {
                _messagesToSend.Enqueue(new Message(s, callback, payload));

                if (!_sendIsOngoing)
                {
                    _sendIsOngoing = true;
                    SendMessage();
                }
            }
        }