Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Events (connect, disconnect and reconnect) implementation in

c#-Silverlight
  • Loading branch information...
commit e965351eaf4b02855452b288a199e8ca088de80f 1 parent a7f3fd6
priyanka authored
View
92 csharp-silverlight/README
@@ -99,26 +99,9 @@
## C#-Silverlight : (Subscribe)
## ----------------------------
//Subscribe messages of type string,json array and json object
- pubnub.ResponseCallback respCallback = delegate(object message)
- {
- object[] messages = (object[])message;
- UIThread.Invoke(() =>
- {
- if (messages != null && messages.Count() > 0)
- {
- for (int i = 0; i < messages.Count(); i++)
- {
- if (!(lSubscribe.Items.Contains(messages[i].ToString())))
- {
- lSubscribe.Items.Add(messages[i].ToString());
- }
- }
- }
- });
- };
Dictionary<string, object> args = new Dictionary<string, object>();
args.Add("channel", channel);
- args.Add("callback", respCallback);
+ args.Add("callback", new Receiver());
objPubnub.Subscribe(args);
## ------------------------------------------------------------------------------------
@@ -166,5 +149,78 @@
## -----------------------
// Get UUID
lblUUID.Text = "Generated UUID - > " + objPubnub.UUID();
+
+## ------------------------------------------------------------------------------------
+## C#-Silverlight : (Unsubscribe)
+## ------------------------------
+ //Subscribe messages of type string,json array and json object
+ Dictionary<string, object> args = new Dictionary<string, object>();
+ args.Add("channel", channel);
+ args.Add("callback", new Receiver());
+ objPubnub.Subscribe(args);
+
+ // Publish string
+ Dictionary<string, object> strArgs = new Dictionary<string, object>();
+ string message = "Hello Silverlight";
+ strArgs.Add("channel", channel);
+ strArgs.Add("message", message);
+ strArgs.Add("callback", respCallback);
+ objPubnub.Publish(strArgs);
+
+ Dictionary<string, object> arg = new Dictionary<string, object>();
+ arg.Add("channel", channel);
+ //Unsubscribe messages
+ objPubnub.Unsubscribe(arg);
+ ## ------------------------------------------------------------------------------------
+
+ // Receiver for callback
+ public class Receiver : Callback
+ {
+ public bool responseCallback(string channel, object message)
+ {
+ object[] messages = (object[])message;
+
+ if (messages != null && messages.Length > 0)
+ {
+ for (int i = 0; i < messages.Length; i++)
+ {
+ Debug.WriteLine("[Subscribed data] " + messages[i]);
+ }
+ }
+ return true;
+ }
+
+ public void errorCallback(string channel, object message)
+ {
+ Debug.WriteLine("Channel:" + channel + "-" + message.ToString());
+ }
+
+ public void connectCallback(string channel)
+ {
+ Debug.WriteLine("Connected to channel :" + channel);
+ }
+
+ public void reconnectCallback(string channel)
+ {
+ Debug.WriteLine("Reconnecting to channel :" + channel);
+ }
+
+ public void disconnectCallback(string channel)
+ {
+ Debug.WriteLine("Disconnected to channel :" + channel);
+ }
+ }
+
+ public interface Callback
+ {
+ bool responseCallback(string channel, object message);
+
+ void errorCallback(String channel, Object message);
+
+ void connectCallback(String channel);
+
+ void reconnectCallback(String channel);
+ void disconnectCallback(String channel);
+ }
=========================================================================================
View
36 csharp-silverlight/examples/PubnubTest.xaml.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
@@ -11,12 +11,13 @@
using System.Windows.Shapes;
using System.Windows.Navigation;
using Newtonsoft.Json.Linq;
+using System.Diagnostics;
namespace silverlight
{
public partial class PubnubTest : Page
{
- string channel = "hello-world";
+ string channel = "hello_world";
// Initialize Pubnub state
pubnub objPubnub = new pubnub(
"demo", // PUBLISH_KEY
@@ -38,31 +39,13 @@ protected override void OnNavigatedTo(NavigationEventArgs e)
private void Subscribe_Click(object sender, RoutedEventArgs e)
{
- lblSubscribe.Text = "Subscribe to the channel " + channel;
- pubnub.ResponseCallback respCallback = delegate(object message)
- {
- object[] messages = (object[])message;
- UIThread.Invoke(() =>
- {
- if (messages != null && messages.Count() > 0)
- {
- subMessage.Visibility = Visibility.Visible;
- for (int i = 0; i < messages.Count(); i++)
- {
- if (!(lSubscribe.Items.Contains(messages[i].ToString())))
- {
- lSubscribe.Items.Add(messages[i].ToString());
- }
- }
- }
- });
- };
+ lblSubscribe.Text = "Subscribe to the channel " + channel;
Dictionary<string, object> args = new Dictionary<string, object>();
args.Add("channel", channel);
- args.Add("callback", respCallback);
+ args.Add("callback", new Receiver());
+
objPubnub.Subscribe(args);
}
-
private void Publish_Click(object sender, RoutedEventArgs e)
{
lblPublish.Text = "";
@@ -104,12 +87,15 @@ private void Publish_Click(object sender, RoutedEventArgs e)
Dictionary<string, object> objArgs = new Dictionary<string, object>();
+ JObject objDict = new JObject();
JObject obj = new JObject();
- obj.Add("Name", "Jhon");
+ objDict.Add("Student", "Male");
+ obj.Add("Name", "John");
obj.Add("age", "25");
+ objDict.Add("Info", obj);
objArgs.Add("channel", channel);
- objArgs.Add("message", obj);
+ objArgs.Add("message", objDict);
objArgs.Add("callback", respCallback);
objPubnub.Publish(objArgs);
}
View
22 csharp-silverlight/examples/SubscribeExample.xaml.cs
@@ -36,28 +36,10 @@ protected override void OnNavigatedTo(NavigationEventArgs e)
private void Subscribe_Click(object sender, RoutedEventArgs e)
{
- lblSubscribe.Text = "Subscribe to the channel " + channel;
- pubnub.ResponseCallback respCallback = delegate(object message)
- {
- object[] messages = (object[])message;
- UIThread.Invoke(() =>
- {
- if (messages != null && messages.Count() > 0)
- {
- subMessage.Visibility = Visibility.Visible;
- for (int i = 0; i < messages.Count(); i++)
- {
- if (!(lSubscribe.Items.Contains(messages[i].ToString())))
- {
- lSubscribe.Items.Add(messages[i].ToString());
- }
- }
- }
- });
- };
+ lblSubscribe.Text = "Subscribe to the channel " + channel;
Dictionary<string, object> args = new Dictionary<string, object>();
args.Add("channel", channel);
- args.Add("callback", respCallback);
+ args.Add("callback", new Receiver());
objPubnub.Subscribe(args);
}
}
View
29 csharp-silverlight/examples/UnsubscribeExample.xaml
@@ -0,0 +1,29 @@
+<navigation:Page x:Class="silverlight.UnsubscribeExample"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+ mc:Ignorable="d"
+ xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
+ d:DesignWidth="640" d:DesignHeight="480"
+ Title="UnsubscribeExample Page">
+ <Grid x:Name="LayoutRoot">
+ <StackPanel>
+ <TextBlock Text=" * Example to receive published messages * " HorizontalAlignment="Left" FontWeight="Bold" FontSize="11" Margin="10,10,0,0"></TextBlock>
+ <Button x:Name="Subscribe" Content="Subscribe" Click="Subscribe_Click" Height="25" Width="100" HorizontalAlignment="Left" Margin="10,10,0,0"></Button>
+ <TextBlock x:Name="lblSubscribe" Margin="10,10,0,0"></TextBlock>
+ <TextBlock x:Name="subMessage" Text="Received messages - >" Visibility="Collapsed" Margin="10,10,0,0"></TextBlock>
+ <ListBox Name="lSubscribe" Margin="10,10,0,0"></ListBox>
+
+ <TextBlock Text=" * Example to publish messages * " HorizontalAlignment="Left" FontWeight="Bold" FontSize="11" Margin="10,10,0,0"></TextBlock>
+ <Button x:Name="Publish" Content="Publish" Click="Publish_Click" HorizontalAlignment="Left" Height="25" Width="100" Margin="10,10,0,0"></Button>
+ <TextBlock x:Name="publishedData" Text="Published messages - > " Visibility="Collapsed" Margin="10,10,0,0"></TextBlock>
+ <TextBlock x:Name="lblPublish" Margin="10,10,0,0"></TextBlock>
+
+ <TextBlock Text=" * Example to unsubscribe/disconnect from channel * " HorizontalAlignment="Left" FontWeight="Bold" FontSize="11" Margin="10,10,0,0"></TextBlock>
+ <Button x:Name="Unsubscribe" Content="Unsubscribe" Click="Unsubscribe_Click" Height="25" Width="100" HorizontalAlignment="Left" Margin="10,10,0,0"></Button>
+ <TextBlock x:Name="lblDisConnect" Margin="10,10,10,10"></TextBlock>
+
+ </StackPanel>
+ </Grid>
+</navigation:Page>
View
81 csharp-silverlight/examples/UnsubscribeExample.xaml.cs
@@ -0,0 +1,81 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Shapes;
+using System.Windows.Navigation;
+using System.Diagnostics;
+using System.Threading;
+
+namespace silverlight
+{
+ public partial class UnsubscribeExample : Page
+ {
+ string channel = "hello_world";
+ // Initialize Pubnub state
+ pubnub objPubnub = new pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY
+ false // SSL_ON?
+ );
+
+ public UnsubscribeExample()
+ {
+ InitializeComponent();
+ }
+
+ // Executes when the user navigates to this page.
+ protected override void OnNavigatedTo(NavigationEventArgs e)
+ {
+ }
+ private void Unsubscribe_Click(object sender, RoutedEventArgs e)
+ {
+ Dictionary<string, object> arg = new Dictionary<string, object>();
+ arg.Add("channel", channel);
+ //Unsubscribe messages
+ objPubnub.Unsubscribe(arg);
+ }
+
+ private void Subscribe_Click(object sender, RoutedEventArgs e)
+ {
+ lblSubscribe.Text = "Subscribe to the channel " + channel;
+ Dictionary<string, object> args = new Dictionary<string, object>();
+ args.Add("channel", channel);
+ args.Add("callback", new Receiver());
+ objPubnub.Subscribe(args);
+ }
+ private void Publish_Click(object sender, RoutedEventArgs e)
+ {
+ lblPublish.Text = "";
+ pubnub.ResponseCallback respCallback = delegate(object response)
+ {
+ List<object> result = (List<object>)response;
+
+ UIThread.Invoke(() =>
+ {
+ if (result != null && result.Count() > 0)
+ {
+ publishedData.Visibility = Visibility.Visible;
+ lblPublish.Text += "\n[" + result[0].ToString() + "," + result[1].ToString() + "," + result[2].ToString() + "]";
+ }
+ });
+ };
+
+ Dictionary<string, object> strArgs = new Dictionary<string, object>();
+ string message = "Hello Silverlight";
+ strArgs.Add("channel", channel);
+ strArgs.Add("message", message);
+ strArgs.Add("callback", respCallback);
+ objPubnub.Publish(strArgs);
+ }
+ }
+
+}
View
0  csharp-silverlight/Newtonsoft.Json.Silverlight.XML → ...verlight/resource/Newtonsoft.Json.Silverlight.XML
File renamed without changes
View
0  csharp-silverlight/Newtonsoft.Json.Silverlight.dll → ...verlight/resource/Newtonsoft.Json.Silverlight.dll
File renamed without changes
View
BIN  csharp-silverlight/resource/Newtonsoft.Json.dll
Binary file not shown
View
6,905 csharp-silverlight/resource/Newtonsoft.Json.xml
6,905 additions, 0 deletions not shown
View
26 csharp-silverlight/src/Callback.cs
@@ -0,0 +1,26 @@
+using System;
+using System.Net;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Documents;
+using System.Windows.Ink;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Shapes;
+
+namespace silverlight
+{
+ public interface Callback
+ {
+ bool responseCallback(string channel, object message);
+
+ void errorCallback(String channel, Object message);
+
+ void connectCallback(String channel);
+
+ void reconnectCallback(String channel);
+
+ void disconnectCallback(String channel);
+ }
+}
View
343 csharp-silverlight/Pubnub.cs → csharp-silverlight/src/Pubnub.cs
@@ -17,10 +17,16 @@
using System.Threading;
using System.Windows.Threading;
using System.Net.Browser;
+using System.Reflection;
+using System.Diagnostics;
namespace silverlight
{
-
+ public class Channel_status
+ {
+ public string channel;
+ public bool connected, first;
+ }
public class pubnub
{
public enum ResponseType
@@ -38,7 +44,12 @@ public enum ResponseType
private string CIPHER_KEY = "";
private bool SSL = false;
const int BUFFER_SIZE = 1024;
+
public delegate void ResponseCallback(object response);
+ Callback callback;
+ bool is_reconnected = false, is_disconnect = false;
+ Int64 previousTimeToken = 0;
+ private List<Channel_status> subscriptions = new List<Channel_status>();
private List<object> _Subscribe = new List<object>();
public List<object> subscribe
@@ -49,43 +60,114 @@ public List<object> subscribe
}
set
{
+ string channel = value[2].ToString();
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
- object message = "";
- JArray val = (JArray)value[0];
- object[] valObj = new object[val.Count];
- for (int i = 0; i < val.Count; i++)
+
+ // Problem?
+ if (value == null || value[1].ToString() == "0")
{
- if (this.CIPHER_KEY.Length > 0)
+
+ for (int i = 0; i < subscriptions.Count; i++)
{
- if (val[i].Type == JTokenType.String)
+ Channel_status cs = subscriptions[i];
+ if (cs.channel == channel)
{
- message = pc.decrypt((string)val[i]);
- valObj[i] = message;
+ subscriptions.RemoveAt(i);
+ callback.disconnectCallback(channel);
}
- else if (val[i].Type == JTokenType.Object)
+ }
+
+ // Ensure Connected (Call Time Function)
+ while (true)
+ {
+ string time_token = 0.ToString();
+ Time(
+ delegate(object response)
+ {
+ List<object> result = (List<object>)response;
+ time_token = result[0].ToString();
+ });
+
+ Thread.Sleep(2000);
+ if (time_token == "0")
{
- message = pc.decrypt((JObject)val[i]);
- valObj[i] = message;
+ // Reconnect Callback
+ callback.reconnectCallback(channel);
+ Thread.Sleep(5000);
}
- else if (val[i].Type == JTokenType.Array)
+ else
{
- message = pc.decrypt((JArray)val[i]);
- valObj[i] = message;
+ is_reconnected = true;
+ break;
}
}
- else
+ }
+ else
+ {
+ previousTimeToken = Int64.Parse(value[1].ToString());
+ foreach (Channel_status cs in subscriptions)
+ {
+ if (cs.channel == channel)
+ {
+ // Connect Callback
+ if (!cs.first)
+ {
+ cs.first = true;
+ callback.connectCallback(channel);
+ break;
+ }
+ }
+ }
+ }
+ if (is_reconnected)
+ {
+ is_reconnected = false;
+ Dictionary<string, object> tempArgs = new Dictionary<string, object>();
+ tempArgs.Add("channel", channel);
+ tempArgs.Add("timestamp", "0");
+ tempArgs.Add("callback", callback);
+ Subscribe(tempArgs);
+ }
+ else
+ {
+ object message = "";
+ JArray val = (JArray)value[0];
+ object[] valObj = new object[val.Count];
+ for (int i = 0; i < val.Count; i++)
{
- valObj[i] = val[i];
+ if (this.CIPHER_KEY.Length > 0)
+ {
+ if (val[i].Type == JTokenType.String)
+ {
+ message = pc.decrypt((string)val[i]);
+ valObj[i] = message;
+ }
+ else if (val[i].Type == JTokenType.Object)
+ {
+ message = pc.decrypt((JObject)val[i]);
+ valObj[i] = message;
+ }
+ else if (val[i].Type == JTokenType.Array)
+ {
+ message = pc.decrypt((JArray)val[i]);
+ valObj[i] = message;
+ }
+ }
+ else
+ {
+ valObj[i] = val[i];
+ }
}
+ value[0] = valObj;
+ _Subscribe = value;
+ Dictionary<string, object> args = new Dictionary<string, object>();
+ args.Add("channel", channel);
+ args.Add("timestamp", Int64.Parse(value[1].ToString()));
+ args.Add("callback", callback);
+ if (Int64.Parse(value[1].ToString()) > 0)
+ _subscribe(args);
}
- value[0] = valObj;
- _Subscribe = value;
- Dictionary<string, object> args = new Dictionary<string, object>();
- args.Add("channel", value[2].ToString());
- args.Add("timestamp", Int64.Parse(value[1].ToString()) - 1);
- args.Add("callback",(ResponseCallback)value[3]);
- if (Int64.Parse(value[1].ToString()) > 0)
- _subscribe(args);
+
}
}
private List<object> _History = new List<object>();
@@ -300,9 +382,66 @@ public void Publish(Dictionary<string, object> args)
* @param Dictionary<string, object> args .
* args contains channel name and a delegate to get response back
*/
+
public void Subscribe(Dictionary<string, object> args)
{
- args.Add("timestamp", 0);
+ bool is_alreadyConnect = false;
+
+ if(!args.ContainsKey("timestamp"))
+ args.Add("timestamp", 0);
+ string channel = args["channel"].ToString();
+ // Validate Arguments
+ if (args["callback"] != null)
+ {
+ callback = (Callback)args["callback"];
+ }
+ else
+ {
+ Debug.WriteLine("Invalid Callback.");
+ }
+ if (channel == null || channel == "")
+ {
+ callback.errorCallback(channel, "Invalid channel.");
+ return;
+ }
+
+ // Ensure Single Connection
+ if (subscriptions != null && subscriptions.Count > 0)
+ {
+ bool channel_exist = false;
+ foreach (Channel_status cs in subscriptions)
+ {
+ if (cs.channel == channel)
+ {
+ channel_exist = true;
+ if (!cs.connected)
+ cs.connected = true;
+ else
+ is_alreadyConnect = true;
+ break;
+ }
+ }
+ if (!channel_exist)
+ {
+ Channel_status cs = new Channel_status();
+ cs.channel = channel;
+ cs.connected = true;
+ subscriptions.Add(cs);
+ }
+ else if (is_alreadyConnect)
+ {
+ callback.errorCallback(channel ," Already Connected");
+ return;
+ }
+ }
+ else
+ {
+ // New Channel
+ Channel_status cs = new Channel_status();
+ cs.channel = channel;
+ cs.connected = true;
+ subscriptions.Add(cs);
+ }
this._subscribe(args);
}
@@ -314,12 +453,12 @@ public void Subscribe(Dictionary<string, object> args)
*/
private void _subscribe(Dictionary<string, object> args)
{
- clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
-
+ is_disconnect = false;
+ clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
string channel = args["channel"].ToString();
- ResponseCallback respCallback = (ResponseCallback)args["callback"];
object timetoken = args["timestamp"];
- // Begin Recusive Subscribe
+
+ // Begin Subscribe
try
{
// Build URL
@@ -328,13 +467,13 @@ private void _subscribe(Dictionary<string, object> args)
url.Add(this.SUBSCRIBE_KEY);
url.Add(channel);
url.Add("0");
- url.Add(timetoken.ToString());
- _request(url, respCallback,ResponseType.Subscribe);
+ url.Add(timetoken.ToString());
+ _request(url, null, ResponseType.Subscribe);
+
}
catch
{
System.Threading.Thread.Sleep(1000);
- this._subscribe(args);
}
}
@@ -364,12 +503,11 @@ private void _request(List<string> url_components, ResponseCallback respCallback
myRequestState.request = request;
myRequestState.cb = respCallback;
myRequestState.respType = type;
- if (url_components.Count > 2)
+ if (type == ResponseType.Subscribe)
{
myRequestState.channel = url_components[2];
}
- request.Method = "GET";
- IAsyncResult result = (IAsyncResult)request.BeginGetResponse(requestCallBack, myRequestState);
+ IAsyncResult result = (IAsyncResult)request.BeginGetResponse(requestCallBack, myRequestState);
}
catch (Exception)
{
@@ -380,42 +518,106 @@ private void requestCallBack(IAsyncResult asyncResult)
{
// State of request is asynchronous.
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
- HttpWebRequest myHttpWebRequest2 = myRequestState.request;
- myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asyncResult);
- // Read the response into a Stream object.
- myRequestState.streamResponse = myRequestState.response.GetResponseStream();
- // Begin the Reading of the contents of the HTML page and print it to the console.
- IAsyncResult asynchronousInputRead = myRequestState.streamResponse.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, ReadCallBack, myRequestState);
+ HttpWebRequest myHttpWebRequest2 = myRequestState.request;
+ try
+ {
+ myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asyncResult);
+ // Read the response into a Stream object.
+ myRequestState.streamResponse = myRequestState.response.GetResponseStream();
+ // Begin the Reading of the contents of the HTML page and print it to the console.
+ IAsyncResult asynchronousInputRead = myRequestState.streamResponse.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, ReadCallBack, myRequestState);
+ }
+ catch (Exception)
+ {
+ List<object> error = new List<object>();
+ if (myRequestState.respType == ResponseType.Time)
+ {
+ error.Add("0");
+ }
+ else if (myRequestState.respType == ResponseType.History)
+ {
+ error.Add("Error: Failed JSONP HTTP Request.");
+ }
+ else if (myRequestState.respType == ResponseType.Publish)
+ {
+ error.Add("0");
+ error.Add("Error: Failed JSONP HTTP Request.");
+ }
+ else if (myRequestState.respType == ResponseType.Subscribe)
+ {
+ error.Add("0");
+ error.Add("0");
+ error.Add(myRequestState.channel);
+ subscribe = error;
+ }
+ }
}
private void ReadCallBack(IAsyncResult asyncResult)
{
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
Stream responseStream = myRequestState.streamResponse;
- int read = responseStream.EndRead(asyncResult);
- // Read the HTML page and then do something with it
- if (read > 0)
+ try
{
- myRequestState.requestData.Append(Encoding.UTF8.GetString(myRequestState.BufferRead, 0, read));
- IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, ReadCallBack, myRequestState);
+ int read = responseStream.EndRead(asyncResult);
+ // Read the HTML page and then do something with it
+ if (read > 0)
+ {
+ myRequestState.requestData.Append(Encoding.UTF8.GetString(myRequestState.BufferRead, 0, read));
+ IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, ReadCallBack, myRequestState);
- if (myRequestState.respType == ResponseType.History)
+ if (myRequestState.respType == ResponseType.History)
+ {
+ history = JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString());
+ myRequestState.cb(history);
+ }
+ else if (myRequestState.respType == ResponseType.Subscribe)
+ {
+ List<object> lstObj = JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString());
+ lstObj.Add(myRequestState.channel);
+ foreach (Channel_status cs in subscriptions)
+ {
+ if (cs.channel == myRequestState.channel && !cs.connected && !is_disconnect)
+ {
+ callback.disconnectCallback(myRequestState.channel);
+ is_disconnect = true;
+ break;
+ }
+ }
+ if (is_disconnect)
+ return;
+
+ subscribe = lstObj;
+ callback.responseCallback(myRequestState.channel, subscribe[0]);
+ }
+ else
+ {
+ myRequestState.cb(JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString()));
+ }
+ }
+ }
+ catch (Exception)
+ {
+ List<object> error = new List<object>();
+ if (myRequestState.respType == ResponseType.Time)
{
- history = JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString());
- myRequestState.cb(history);
+ error.Add("0");
}
- else if (myRequestState.respType == ResponseType.Subscribe)
+ else if (myRequestState.respType == ResponseType.History)
{
- List<object> lstObj = JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString());
- lstObj.Add(myRequestState.channel);
- lstObj.Add(myRequestState.cb);
- subscribe = lstObj;
- myRequestState.cb(subscribe[0]);
+ error.Add("Error: Failed JSONP HTTP Request.");
}
- else
+ else if (myRequestState.respType == ResponseType.Publish)
{
- myRequestState.cb(JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString()));
+ error.Add("0");
+ error.Add("Error: Failed JSONP HTTP Request.");
}
+ else if (myRequestState.respType == ResponseType.Subscribe)
+ {
+ error.Add("0");
+ error.Add("0");
+ }
+ myRequestState.cb(error);
}
}
@@ -461,6 +663,29 @@ public void History(Dictionary<string, object> args)
_request(url, respCallback,ResponseType.History);
}
+ /**
+ * Unsubscribe
+ *
+ * Unsubscribe/Disconnect to channel.
+ *
+ * @param Dictionary<String, Object> containing channel name.
+ *
+ **/
+ public void Unsubscribe(Dictionary<String, Object> args)
+ {
+ String channel = args["channel"].ToString();
+ foreach (Channel_status cs in subscriptions)
+ {
+ if (cs.channel == channel && cs.connected)
+ {
+ cs.connected = false;
+ cs.first = false;
+ callback.disconnectCallback(channel);
+ is_disconnect = true;
+ break;
+ }
+ }
+ }
private string _encodeURIcomponent(string s)
{
StringBuilder o = new StringBuilder();
@@ -515,7 +740,7 @@ public class RequestState
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
- public pubnub.ResponseCallback cb;
+ public pubnub.ResponseCallback cb;
public pubnub.ResponseType respType;
public string channel;
View
0  csharp-silverlight/PubnubCrypto.cs → csharp-silverlight/src/PubnubCrypto.cs
File renamed without changes
View
59 csharp-silverlight/src/Receiver.cs
@@ -0,0 +1,59 @@
+using System;
+using System.Net;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Documents;
+using System.Windows.Ink;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Shapes;
+using System.Diagnostics;
+
+namespace silverlight
+{
+ public class Receiver : Callback
+ {
+ public bool responseCallback(string channel, object message)
+ {
+ object[] messages = (object[])message;
+ //UIThread.Invoke(() =>
+ //{
+ if (messages != null && messages.Length> 0)
+ {
+ //pt.subMessage.Visibility = Visibility.Visible;
+ for (int i = 0; i < messages.Length; i++)
+ {
+ Debug.WriteLine("[Subscribed data] " + messages[i]);
+ //if (!(pt.lSubscribe.Items.Contains(messages[i].ToString())))
+ //{
+ // pt.lSubscribe.Items.Add(messages[i].ToString());
+ //}
+ }
+ }
+ //});
+ return true;
+ }
+
+ public void errorCallback(string channel, object message)
+ {
+ Debug.WriteLine("Channel:" + channel + "-" + message.ToString());
+ }
+
+ public void connectCallback(string channel)
+ {
+ Debug.WriteLine("Connected to channel :" + channel);
+ }
+
+ public void reconnectCallback(string channel)
+ {
+ Debug.WriteLine("Reconnecting to channel :" + channel);
+ }
+
+ public void disconnectCallback(string channel)
+ {
+ Debug.WriteLine("Disconnected to channel :" + channel);
+ }
+ }
+
+}
View
0  csharp-silverlight/UIThread.cs → csharp-silverlight/src/UIThread.cs
File renamed without changes
View
19 csharp-silverlight/test/unit-test.xaml
@@ -0,0 +1,19 @@
+<navigation:Page x:Class="silverlight.unit_test"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+ mc:Ignorable="d"
+ xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
+ d:DesignWidth="640" d:DesignHeight="480"
+ Title="unit_test Page">
+ <Grid x:Name="LayoutRoot">
+ <ScrollViewer>
+ <StackPanel>
+
+ <TextBlock Text=" * Unit Test Example * " HorizontalAlignment="Left" FontWeight="Bold" FontSize="11" Margin="10,10,0,0"></TextBlock>
+ <Button x:Name="unitTest" Content="Unit Test" Click="unitTest_Click" Height="25" Width="100" HorizontalAlignment="Left" Margin="10,10,0,0"></Button>
+ </StackPanel>
+ </ScrollViewer>
+ </Grid>
+</navigation:Page>
View
397 csharp-silverlight/test/unit-test.xaml.cs
@@ -0,0 +1,397 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Shapes;
+using System.Windows.Navigation;
+using System.Diagnostics;
+using System.Threading;
+
+namespace silverlight
+{
+ public partial class unit_test : Page
+ {
+ public unit_test()
+ {
+ InitializeComponent();
+ }
+
+ // Executes when the user navigates to this page.
+ protected override void OnNavigatedTo(NavigationEventArgs e)
+ {
+ }
+
+ // -----------------------------------------------------------------------
+ // unit-test-all
+ // -----------------------------------------------------------------------
+
+ static String publish_key = "demo", subscribe_key = "demo";
+ static String secret_key = "demo", cipher_key = "";
+ static Boolean ssl_on = false;
+
+ // -----------------------------------------------------------------------
+ // Command Line Options Supplied PubNub
+ // -----------------------------------------------------------------------
+
+ static pubnub pubnub_user_supplied_options = new pubnub(publish_key, // OPTIONAL (supply None to disable)
+ subscribe_key, // REQUIRED
+ secret_key, // OPTIONAL (supply None to disable)
+ cipher_key, // OPTIONAL (supply None to disable)
+ ssl_on // OPTIONAL (supply None to disable)
+ );
+
+ // -----------------------------------------------------------------------
+ // High Security PubNub
+ // -----------------------------------------------------------------------
+ static pubnub pubnub_high_security = new pubnub(
+ // Publish Key
+ "pub-c-a30c030e-9f9c-408d-be89-d70b336ca7a0",
+
+ // Subscribe Key
+ "sub-c-387c90f3-c018-11e1-98c9-a5220e0555fd",
+
+ // Secret Key
+ "sec-c-MTliNDE0NTAtYjY4Ni00MDRkLTllYTItNDhiZGE0N2JlYzBl",
+
+ // Cipher Key
+ "YWxzamRmbVjFaa05HVnGFqZHM3NXRBS73jxmhVMkjiwVVXV1d5UrXR1JLSkZFRr"
+ + "WVd4emFtUm1iR0TFpUZvbiBoYXMgYmVlbxWkhNaF3uUi8kM0YkJTEVlZYVFjBYi"
+ + "jFkWFIxSkxTa1pGUjd874hjklaTFpUwRVuIFNob3VsZCB5UwRkxUR1J6YVhlQWa"
+ + "V1ZkNGVH32mDkdho3pqtRnRVbTFpUjBaeGUgYXNrZWQtZFoKjda40ZWlyYWl1eX"
+ + "U4RkNtdmNub2l1dHE2TTA1jd84jkdJTbFJXYkZwWlZtRnKkWVrSRhhWbFpZVmFz"
+ + "c2RkZmTFpUpGa1dGSXhTa3hUYTFwR1Vpkm9yIGluZm9ybWFNfdsWQdSiiYXNWVX"
+ + "RSblJWYlRGcFVqQmFlRmRyYUU0MFpXbHlZV2wxZVhVNFJrTnR51YjJsMWRIRTJU"
+ + "W91ciBpbmZvcm1hdGliBzdWJtaXR0ZWQb3UZSBhIHJlc3BvbnNlLCB3ZWxsIHJl"
+ + "VEExWdHVybiB0am0aW9uIb24gYXMgd2UgcG9zc2libHkgY2FuLuhcFe24ldWVns"
+ + "dSaTFpU3hVUjFKNllWaFdhRmxZUWpCaQo34gcmVxdWlGFzIHNveqQl83snBfVl3",
+
+ // 2048bit SSL ON - ENABLED TRUE
+ false);
+
+ // -----------------------------------------------------------------------
+ // Channel | Message Test Data (UTF-8)
+ // -----------------------------------------------------------------------
+ static string Message = " ~`â¦â§!@#$%^&*(???)+=[]\\{}|;\':,./<>?abcd";
+ static pubnub _pubnub;
+ static List<String> many_channels = new List<String>(10);
+ static Dictionary<string, Int32> status = new Dictionary<string, int>(3);
+ static Dictionary<String, Dictionary<string, Int32>> channelStatus = new Dictionary<String, Dictionary<string, Int32>>(many_channels.Capacity);
+
+
+ static Dictionary<String, Object> threads = new Dictionary<String, Object>(4);
+
+ static Dictionary<string, bool> channelConnected = new Dictionary<string, bool>();
+
+ static int max_retries = 10;
+ static int planned_tests = 2;
+ static int runthroughs = 0;
+ static int delivery_retries = 0;
+
+ // -----------------------------------------------------------------------
+ // Unit Test Function
+ // -----------------------------------------------------------------------
+
+ static void test(Boolean trial, String name)
+ {
+ if (trial)
+ Debug.WriteLine("PASS " + name);
+ else
+ Debug.WriteLine("- FAIL - " + name);
+ }
+ static void UnitTestAll(pubnub pubnub)
+ {
+ status.Clear();
+ threads.Clear();
+ many_channels.Clear();
+ if (runthroughs >= 2)
+ {
+ runthroughs = 0;
+ }
+ _pubnub = pubnub;
+
+ if (!status.ContainsKey("sent"))
+ status.Add("sent", 0);
+ if (!status.ContainsKey("received"))
+ status.Add("received", 0);
+ if (!status.ContainsKey("connections"))
+ status.Add("connections", 0);
+
+ for (int i = 0; i < many_channels.Capacity; i++)
+ {
+ many_channels.Add("channel_" + i);
+ channelConnected[many_channels[i]] = false;
+ channelStatus[many_channels[i]] = status;
+ }
+ subscribeChannels(_pubnub);
+ }
+ static void subscribeChannels(pubnub pubnub)
+ {
+ foreach (string _channel in many_channels)
+ {
+ Thread t = new Thread(delegate()
+ {
+ Dictionary<String, Object> argsSub = new Dictionary<String, Object>(2);
+ argsSub.Add("channel", _channel);
+ argsSub.Add("callback", new Receiver()); // callback to get response
+ // Listen for Messages (Subscribe)
+ pubnub.Subscribe(argsSub);
+ });
+ t.Start();
+ if (threads.ContainsKey(_channel))
+ threads[_channel] = t;
+ else
+ threads.Add(_channel, t);
+ try
+ {
+ Thread.Sleep(1000);
+ }
+ catch (ThreadAbortException e)
+ {
+ Debug.WriteLine(e.Message);
+ }
+ }
+ }
+ class Receiver : Callback
+ {
+
+ public bool responseCallback(string channel, object message)
+ {
+ object[] results = (object[])message;
+ if (results.Length > 0)
+ {
+ int sent = Convert.ToInt32((channelStatus[channel])["sent"]);
+ int received = Convert.ToInt32((channelStatus[channel])["received"]);
+ test(received <= sent, "many sends");
+ received = received + 1;
+ (channelStatus[channel]).Remove("received");
+ (channelStatus[channel]).Add("received", received);
+
+ Dictionary<String, Object> args = new Dictionary<String, Object>(1);
+ args.Add("channel", channel);
+ if (channelConnected[channel])
+ {
+ _pubnub.Unsubscribe(args);
+ }
+ //int allReceived = 0;
+ //foreach(var status in channelStatus)
+ //{
+ // allReceived += Convert.ToInt32(status.Value["received"]);
+ //}
+ //if (allReceived == many_channels.Count)
+ //{
+ // runthroughs += 1;
+ // if (runthroughs < planned_tests)
+ // {
+ // //UnitTestAll(_pubnub);
+ // }
+ //}
+ return true;
+ }
+ else
+ return false;
+ }
+
+ public void errorCallback(string channel, object message)
+ {
+ //Debug.WriteLine("Channel:" + channel + "-" + message.ToString());
+ }
+
+ public void connectCallback(string channel)
+ {
+ if (!channelConnected[channel])
+ {
+ pubnub.ResponseCallback histCallback = delegate(object response)
+ {
+ List<object> result = (List<object>)response;
+ test(result != null && result.Count > 0, "history");
+ };
+ Debug.WriteLine("Connected to channel :" + channel);
+ int connections = Convert.ToInt32(status["connections"]);
+ status.Remove("connections");
+ status.Add("connections", connections + 1);
+ publishAndSetStatus(channel, Message);
+
+ Dictionary<string, object> argshist = new Dictionary<string, object>();
+ argshist.Add("channel", channel);
+ argshist.Add("limit", 1.ToString());
+ argshist.Add("callback", histCallback);
+ _pubnub.History(argshist);
+ }
+ }
+ public void reconnectCallback(string channel)
+ {
+ Debug.WriteLine("Reconnected to channel :" + channel);
+ }
+ public void disconnectCallback(string channel)
+ {
+ Debug.WriteLine("Disconnected to channel :" + channel);
+ }
+ }
+ private void unitTest_Click(object sender, RoutedEventArgs e)
+ {
+ UnitTestAll(pubnub_high_security);
+
+ //UnitTestAll(pubnub_user_supplied_options);
+ //test_subscribe();
+ //test_publish();
+ //test_uuid();
+ //test_time();
+ //test_history();
+ }
+
+ static public void test_publish()
+ {
+ // Initialize pubnub state
+ pubnub objPubnub = new pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY (Cipher key is Optional)
+ false // SSL_ON?
+ );
+
+ //define channel
+ string channel = "hello-world";
+ pubnub.ResponseCallback respCallback = delegate(object response)
+ {
+ List<object> messages = (List<object>)response;
+ if (messages != null && messages.Count > 0)
+ {
+ Debug.WriteLine("[" + messages[0] + " , " + messages[1] + "]");
+ }
+ };
+ Dictionary<string, object> strArgs = new Dictionary<string, object>();
+ string message = "Hello Silverlight";
+ strArgs.Add("channel", channel);
+ strArgs.Add("message", message);
+ strArgs.Add("callback", respCallback);
+ objPubnub.Publish(strArgs);
+ }
+ static public void test_subscribe()
+ {
+ // Initialize pubnub state
+ pubnub objPubnub = new pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY (Cipher key is Optional)
+ false // SSL_ON?
+ );
+
+ //define channel
+ string channel = "hello-world";
+
+ Dictionary<string, object> args = new Dictionary<string, object>();
+ args = new Dictionary<string, object>();
+ args.Add("channel", channel);
+ args.Add("callback", new silverlight.Receiver()); // callback to get response
+ objPubnub.Subscribe(args);
+ }
+ static public void test_history()
+ {
+ pubnub.ResponseCallback histCallback = delegate(object response)
+ {
+ List<object> result = (List<object>)response;
+ Debug.WriteLine("[History data]");
+ foreach (object data in result)
+ {
+ Debug.WriteLine(data);
+ }
+ };
+
+ // Initialize pubnub state
+ pubnub objPubnub = new pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY (Cipher key is Optional)
+ false // SSL_ON?
+ );
+
+ //define channel
+ string channel = "hello-world";
+
+ // History
+ Dictionary<string, object> argsHist = new Dictionary<string, object>();
+ argsHist.Add("channel", channel);
+ argsHist.Add("limit", 3.ToString());
+ argsHist.Add("callback", histCallback);
+ objPubnub.History(argsHist);
+
+ }
+ static public void test_uuid()
+ {
+ // Initialize pubnub state
+ pubnub objPubnub = new pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY (Cipher key is Optional)
+ false // SSL_ON?
+ );
+
+ //Get UUID
+ string uuid = objPubnub.UUID();
+ Debug.WriteLine("Generated UUID - > - " + uuid);
+ }
+ static public void test_time()
+ {
+
+ // Initialize pubnub state
+ pubnub objPubnub = new pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY (Cipher key is Optional)
+ false // SSL_ON?
+ );
+
+ // Get PubNub Server Time
+ objPubnub.Time(timedelegate);
+ }
+ public static void timedelegate(object response)
+ {
+ List<object> result = (List<object>)response;
+ Debug.WriteLine(" Time is : " + result[0].ToString());
+ }
+ public static void publishAndSetStatus(string channel, object message)
+ {
+ pubnub.ResponseCallback publishCallback = delegate(object response)
+ {
+ List<object> messages = (List<object>)response;
+ if (messages != null && messages.Count > 2)
+ {
+ int sent = Convert.ToInt32((channelStatus[channel])["sent"]);
+ (channelStatus[channel]).Remove("sent");
+ (channelStatus[channel]).Add("sent", sent + 1);
+ test(messages != null, "publish complete");
+ test(messages != null && messages.Count > 2, "publish responce");
+ channelConnected[channel] = true;
+ }
+ if (messages == null || messages.Count <= 0)
+ {
+ delivery_retries += 1;
+ if (max_retries > delivery_retries)
+ {
+ publishAndSetStatus(channel, message);
+ }
+ }
+ };
+
+ // Publish message
+ Dictionary<string, object> args = new Dictionary<string, object>(2);
+ args.Add("channel", channel);
+ args.Add("message", message);
+ args.Add("callback", publishCallback);
+ // publish Response
+ _pubnub.Publish(args);
+ }
+
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.