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#-windows-phone
  • Loading branch information...
commit d73dab3d4b1f51c0f5a75a000035e1fdc1e4fd16 1 parent e965351
priyanka authored
92 csharp-windows-phone/README.txt
View
@@ -96,22 +96,11 @@ TUTORIAL: HOW TO USE
## --------------------
//Subscribe messages of type string,json array and json object
System.Diagnostics.Debug.WriteLine("Subscribed to channel " + channel);
- Pubnub.ResponseCallback respCallback = delegate(object message)
- {
- object[] messages = (object[])message;
-
- if (messages != null && messages.Count() > 0)
- {
- for (int i = 0; i < messages.Count(); i++)
- {
- System.Diagnostics.Debug.WriteLine(messages[i]);
- }
- }
- };
+
//Subscribe messages
Dictionary<string, object> args = new Dictionary<string, object>();
args.Add("channel", channel);
- args.Add("callback", respCallback);
+ args.Add("callback", new Receiver());
pubnub.Subscribe(args);
## --------------------------------------------------------------------------------
@@ -155,4 +144,81 @@ TUTORIAL: HOW TO USE
// Get UUID
System.Diagnostics.Debug.WriteLine("UUID - > " + pubnub.UUID());
+
+## ------------------------------------------------------------------------------------
+## C#-WP7 : (Unsubscribe)
+## ----------------------
+ //Subscribe messages of type string,json array and json object
+
+ System.Diagnostics.Debug.WriteLine("Subscribed to channel " + channel);
+ Dictionary<string, object> args = new Dictionary<string, object>();
+ args.Add("channel", channel);
+ args.Add("callback", new Receiver());
+ pubnub.Subscribe(args);
+
+ // Publish string message
+ Dictionary<string, object> strArgs = new Dictionary<string, object>();
+ string message = "Hello Windows Phone 7";
+ strArgs.Add("channel", channel);
+ strArgs.Add("message", message);
+ strArgs.Add("callback", respCallback);
+ pubnub.Publish(strArgs);
+
+ Dictionary<string, object> arg = new Dictionary<string, object>();
+ arg.Add("channel", channel);
+ //Unsubscribe messages
+ pubnub.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);
+ }
=====================================================================================
15 csharp-windows-phone/examples/PubnubTest.xaml.cs
View
@@ -83,22 +83,11 @@ private void btnPublish_Click(object sender, RoutedEventArgs e)
private void btnSubscribe_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Subscribed to channel " + channel);
- Pubnub.ResponseCallback respCallback = delegate(object message)
- {
- object[] messages = (object[])message;
-
- if (messages != null && messages.Count() > 0)
- {
- for (int i = 0; i < messages.Count(); i++)
- {
- System.Diagnostics.Debug.WriteLine(messages[i]);
- }
- }
- };
+
//Subscribe messages
Dictionary<string, object> args = new Dictionary<string, object>();
args.Add("channel", channel);
- args.Add("callback", respCallback);
+ args.Add("callback", new Receiver());
pubnub.Subscribe(args);
}
16 csharp-windows-phone/examples/SubscribeExample.xaml.cs
View
@@ -35,22 +35,10 @@ public SubscribeExample()
private void btnSubscribe_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Subscribed to channel " + channel);
- Pubnub.ResponseCallback respCallback = delegate(object message)
- {
- object[] messages = (object[])message;
-
- if (messages != null && messages.Count() > 0)
- {
- for (int i = 0; i < messages.Count(); i++)
- {
- System.Diagnostics.Debug.WriteLine(messages[i]);
- }
- }
-
- };
+
Dictionary<string, object> args = new Dictionary<string, object>();
args.Add("channel", channel);
- args.Add("callback", respCallback);
+ args.Add("callback", new Receiver());
pubnub.Subscribe(args);
}
}
53 csharp-windows-phone/examples/UnsubscribeExample.xaml
View
@@ -0,0 +1,53 @@
+<phone:PhoneApplicationPage
+ x:Class="CSharp_WP7.UnsubscribeExample"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
+ xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+ FontFamily="{StaticResource PhoneFontFamilyNormal}"
+ FontSize="{StaticResource PhoneFontSizeNormal}"
+ Foreground="{StaticResource PhoneForegroundBrush}"
+ SupportedOrientations="Portrait" Orientation="Portrait"
+ mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
+ shell:SystemTray.IsVisible="True">
+
+ <!--LayoutRoot is the root grid where all page content is placed-->
+ <Grid x:Name="LayoutRoot" Background="Transparent">
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto"/>
+ <RowDefinition Height="*"/>
+ </Grid.RowDefinitions>
+
+ <!--TitlePanel contains the name of the application and page title-->
+ <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
+ <TextBlock x:Name="PageTitle" Text="Example to publish and receive messages" Margin="9,7,0,0" Height="40" HorizontalAlignment="Center" VerticalAlignment="Center"/>
+ </StackPanel>
+
+ <!--ContentPanel - place additional content here-->
+ <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
+ <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,34,0,0" Name="textBlock1" Text="Publish messages :" VerticalAlignment="Top" />
+ <Button Content="Publish" Height="70" HorizontalAlignment="Left" Margin="26,70,0,0" Name="btnPublish" VerticalAlignment="Top" Width="160" Click="btnPublish_Click" />
+ <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,146,0,0" Name="textBlock2" Text="Receive messages :" VerticalAlignment="Top" />
+ <Button Content="Subscribe" Height="70" HorizontalAlignment="Left" Margin="26,180,0,0" Name="btnSubscribe" VerticalAlignment="Top" Width="160" Click="btnSubscribe_Click" />
+ <Button Content="Unsubscribe" Height="70" HorizontalAlignment="Left" Margin="26,260,0,0" Name="btnUnsubscribe" VerticalAlignment="Top" Width="190" Click="btnUnsubscribe_Click" />
+ <TextBlock Height="30" HorizontalAlignment="Left" Margin="26,146,0,0" Name="lblDisconnect" VerticalAlignment="Top" />
+
+
+ </Grid>
+ </Grid>
+
+ <!--Sample code showing usage of ApplicationBar-->
+ <!--<phone:PhoneApplicationPage.ApplicationBar>
+ <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
+ <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
+ <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
+ <shell:ApplicationBar.MenuItems>
+ <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
+ <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
+ </shell:ApplicationBar.MenuItems>
+ </shell:ApplicationBar>
+ </phone:PhoneApplicationPage.ApplicationBar>-->
+
+</phone:PhoneApplicationPage>
74 csharp-windows-phone/examples/UnsubscribeExample.xaml.cs
View
@@ -0,0 +1,74 @@
+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 Microsoft.Phone.Controls;
+
+namespace CSharp_WP7
+{
+ public partial class UnsubscribeExample : PhoneApplicationPage
+ {
+ //Channel name
+ string channel = "hello_world";
+
+ // Initialize pubnub state
+ Pubnub pubnub = new Pubnub(
+ "demo", // PUBLISH_KEY
+ "demo", // SUBSCRIBE_KEY
+ "demo", // SECRET_KEY
+ "", // CIPHER_KEY (Cipher key is Optional)
+ false // SSL_ON?
+ );
+
+ public UnsubscribeExample()
+ {
+ InitializeComponent();
+ }
+
+ private void btnUnsubscribe_Click(object sender, RoutedEventArgs e)
+ {
+ Dictionary<string, object> arg = new Dictionary<string, object>();
+ arg.Add("channel", channel);
+ //Unsubscribe messages
+ pubnub.Unsubscribe(arg);
+ }
+
+ private void btnSubscribe_Click(object sender, RoutedEventArgs e)
+ {
+ System.Diagnostics.Debug.WriteLine("Subscribed to channel " + channel);
+
+ Dictionary<string, object> args = new Dictionary<string, object>();
+ args.Add("channel", channel);
+ args.Add("callback", new Receiver());
+ pubnub.Subscribe(args);
+ }
+
+ private void btnPublish_Click(object sender, RoutedEventArgs e)
+ {
+ Pubnub.ResponseCallback respCallback = delegate(object response)
+ {
+ List<object> result = (List<object>)response;
+
+ if (result != null && result.Count() > 0)
+ {
+ System.Diagnostics.Debug.WriteLine("[" + result[0].ToString() + "," + result[1].ToString() + "," + result[2].ToString() + "]");
+ }
+ };
+
+ // Publish string message
+ Dictionary<string, object> strArgs = new Dictionary<string, object>();
+ string message = "Hello Windows Phone 7";
+ strArgs.Add("channel", channel);
+ strArgs.Add("message", message);
+ strArgs.Add("callback", respCallback);
+ pubnub.Publish(strArgs);
+ }
+ }
+}
26 csharp-windows-phone/src/Callback.cs
View
@@ -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 CSharp_WP7
+{
+ 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);
+ }
+}
350 csharp-windows-phone/src/Pubnub.cs
View
@@ -16,9 +16,15 @@
using System.IO;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.GZip;
+using System.Diagnostics;
namespace CSharp_WP7
{
+public class Channel_status
+ {
+ public string channel;
+ public bool connected, first;
+}
public class Pubnub
{
public enum ResponseType
@@ -36,8 +42,11 @@ public enum ResponseType
private string CIPHER_KEY = "";
private bool SSL = false;
const int BUFFER_SIZE = 1024;
- private ManualResetEvent webRequestDone;
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
@@ -48,43 +57,114 @@ public List<object> subscribe
}
set
{
+ string channel = value[2].ToString();
PubnubCrypto pc = new PubnubCrypto(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>();
@@ -217,7 +297,6 @@ bool ssl_on
{
this.ORIGIN = "http://" + this.ORIGIN;
}
- webRequestDone = new ManualResetEvent(true);
}
/**
* Publish
@@ -299,9 +378,66 @@ public void Publish(Dictionary<string, object> args)
*/
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)
+ {
+ //is_alreadyConnect = false;
+ 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);
- }
+ }
/**
* _subscribe - Private Interface
@@ -311,12 +447,12 @@ public void Subscribe(Dictionary<string, object> args)
*/
private void _subscribe(Dictionary<string, object> args)
{
+ is_disconnect = false;
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
- string channel = args["channel"].ToString();
- ResponseCallback respCallback = (ResponseCallback)args["callback"];
+ string channel = args["channel"].ToString();
object timetoken = args["timestamp"];
- // Begin Recusive Subscribe
+ // Begin Subscribe
try
{
// Build URL
@@ -326,12 +462,11 @@ private void _subscribe(Dictionary<string, object> args)
url.Add(channel);
url.Add("0");
url.Add(timetoken.ToString());
- _request(url, respCallback, ResponseType.Subscribe);
+ _request(url, null, ResponseType.Subscribe);
}
catch
{
System.Threading.Thread.Sleep(1000);
- this._subscribe(args);
}
}
@@ -358,7 +493,30 @@ public void History(Dictionary<string, object> args)
url.Add(limit.ToString());
_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;
+ }
+ }
+ }
/**
* Time
*
@@ -407,18 +565,18 @@ private void _request(List<string> url_components, ResponseCallback respCallback
url.Append(_encodeURIcomponent(url_bit));
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
+ request.Method = "GET";
request.UserAgent = "C#-WP7";
request.Headers["V"] = "3.1";
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
RequestState myRequestState = new RequestState();
myRequestState.request = request;
- myRequestState.cb = respCallback;
+ 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);
}
catch (Exception)
@@ -431,48 +589,110 @@ 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.
- Stream stream = myRequestState.response.GetResponseStream();
- if (myRequestState.response.Headers[HttpRequestHeader.ContentEncoding].ToLower().Contains("gzip"))
- myRequestState.streamResponse = new GZipInputStream(stream);
- else
- myRequestState.streamResponse = stream;
- // 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);
+ try
+ {
+ myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asyncResult);
+ // Read the response into a Stream object.
+ Stream stream = myRequestState.response.GetResponseStream();
+ if (myRequestState.response.Headers[HttpRequestHeader.ContentEncoding].ToLower().Contains("gzip"))
+ myRequestState.streamResponse = new GZipInputStream(stream);
+ else
+ myRequestState.streamResponse = stream;
+ // 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);
-
- if (myRequestState.respType == ResponseType.History)
+ int read = responseStream.EndRead(asyncResult);
+ // Read the HTML page and then do something with it
+ if (read > 0)
{
- history = JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString());
- myRequestState.cb(history);
+ 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)
+ {
+ 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()));
+ }
}
- else if (myRequestState.respType == ResponseType.Subscribe)
+ }
+ catch (Exception)
+ {
+ List<object> error = new List<object>();
+ if (myRequestState.respType == ResponseType.Time)
{
- 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("0");
}
- else
+ else if (myRequestState.respType == ResponseType.History)
{
- myRequestState.cb(JsonConvert.DeserializeObject<List<object>>(myRequestState.requestData.ToString()));
+ 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");
+ }
+ myRequestState.cb(error);
}
}
-
private string _encodeURIcomponent(string s)
{
StringBuilder o = new StringBuilder();
@@ -519,7 +739,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;
2  csharp-windows-phone/src/PubnubCrypto.cs
View
@@ -176,7 +176,7 @@ public JObject decrypt(JObject cipherObj)
}
else
{
- cipherObj.Add(((JProperty)jtoken).Name.ToString(), decrypt((JObject)((JProperty)jtoken).Value));
+ objPlain.Add(((JProperty)jtoken).Name.ToString(), decrypt((JObject)((JProperty)jtoken).Value));
}
jtoken = jtoken.Next;
}
59 csharp-windows-phone/src/Receiver.cs
View
@@ -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 CSharp_WP7
+{
+ 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("Reconnected to channel :" + channel);
+ }
+
+ public void disconnectCallback(string channel)
+ {
+ Debug.WriteLine("Disconnected to channel :" + channel);
+ }
+ }
+
+}
47 csharp-windows-phone/test/unit-test.xaml
View
@@ -0,0 +1,47 @@
+<phone:PhoneApplicationPage
+ x:Class="CSharp_WP7.unit_test"
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
+ xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+ FontFamily="{StaticResource PhoneFontFamilyNormal}"
+ FontSize="{StaticResource PhoneFontSizeNormal}"
+ Foreground="{StaticResource PhoneForegroundBrush}"
+ SupportedOrientations="Portrait" Orientation="Portrait"
+ mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
+ shell:SystemTray.IsVisible="True">
+
+ <!--LayoutRoot is the root grid where all page content is placed-->
+ <Grid x:Name="LayoutRoot" Background="Transparent">
+ <Grid.RowDefinitions>
+ <RowDefinition Height="Auto"/>
+ <RowDefinition Height="*"/>
+ </Grid.RowDefinitions>
+
+ <!--TitlePanel contains the name of the application and page title-->
+ <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
+ <TextBlock x:Name="PageTitle" Text="Example to publish and receive messages" Margin="9,7,0,0" Height="40" HorizontalAlignment="Center" VerticalAlignment="Center"/>
+ </StackPanel>
+
+ <!--ContentPanel - place additional content here-->
+ <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
+ <Button Content="Unit Test" Height="70" HorizontalAlignment="Left" Margin="14,68,0,0" Name="btnUnitTest" VerticalAlignment="Top" Width="160" Click="btnUnitTest_Click" />
+ <TextBlock Height="30" HorizontalAlignment="Left" Margin="14,32,0,0" Name="textBlock1" Text="Test All :" VerticalAlignment="Top" />
+ </Grid>
+ </Grid>
+
+ <!--Sample code showing usage of ApplicationBar-->
+ <!--<phone:PhoneApplicationPage.ApplicationBar>
+ <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
+ <shell:ApplicationBarIconButton IconUri="/Images/appbar_button1.png" Text="Button 1"/>
+ <shell:ApplicationBarIconButton IconUri="/Images/appbar_button2.png" Text="Button 2"/>
+ <shell:ApplicationBar.MenuItems>
+ <shell:ApplicationBarMenuItem Text="MenuItem 1"/>
+ <shell:ApplicationBarMenuItem Text="MenuItem 2"/>
+ </shell:ApplicationBar.MenuItems>
+ </shell:ApplicationBar>
+ </phone:PhoneApplicationPage.ApplicationBar>-->
+
+</phone:PhoneApplicationPage>
392 csharp-windows-phone/test/unit-test.xaml.cs
View
@@ -0,0 +1,392 @@
+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 Microsoft.Phone.Controls;
+using System.Diagnostics;
+using System.Threading;
+
+namespace CSharp_WP7
+{
+ public partial class unit_test : PhoneApplicationPage
+ {
+ public unit_test()
+ {
+ InitializeComponent();
+ }
+
+ private void btnUnitTest_Click(object sender, RoutedEventArgs e)
+ {
+ UnitTestAll(pubnub_high_security);
+
+ //UnitTestAll(pubnub_user_supplied_options);
+ //test_subscribe();
+ //test_uuid();
+ //test_time();
+ //test_publish();
+ //test_history();
+ }
+ // -----------------------------------------------------------------------
+ // 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);
+ }
+ }
+
+ 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 CSharp_WP7.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.