Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Core 3.4 in monomac and monotouch

  • Loading branch information...
commit 1863155bd09dcb137199a930d1936e1122e7a4b3 1 parent c88d2b6
@crimsonred crimsonred authored
View
341 mono-for-mac/3.4/PubNub-Messaging/PubNub-Console/Pubnub.cs
@@ -1,4 +1,4 @@
-//Build Date: Feb 18, 2013
+//Build Date: March 07, 2013
#if (__MonoCS__)
#define TRACE
#endif
@@ -122,7 +122,9 @@ public PubnubProxy Proxy
// Pubnub Core API implementation
private string origin = "pubsub.pubnub.com";
+#if (__MonoCS__)
private string domainName = "pubsub.pubnub.com";
+#endif
private string publishKey = "";
private string subscribeKey = "";
private string secretKey = "";
@@ -1304,7 +1306,7 @@ private bool ProcessRequest(List<string> urlComponents, ResponseType type)
return true;
}
- catch (System.Exception ex)
+ catch (System.Exception)
{
return false;
}
@@ -1363,6 +1365,8 @@ private bool UrlProcessRequest<T>(Uri requestUri, RequestState<T> pubnubRequestS
#endif
}
LoggingMethod.WriteToLog(string.Format("DateTime {0}, Request={1}", DateTime.Now.ToString(), requestUri.ToString()), LoggingMethod.LevelInfo);
+
+
#if (__MonoCS__)
if((pubnubRequestState.Type == ResponseType.Publish) && (RequestIsUnsafe(requestUri)))
{
@@ -1392,18 +1396,22 @@ private bool UrlProcessRequest<T>(Uri requestUri, RequestState<T> pubnubRequestS
return false;
}
}
-
- bool RequestIsUnsafe (Uri requestUri)
+
+#if (__MonoCS__)
+ bool RequestIsUnsafe(Uri requestUri)
{
bool isUnsafe = false;
- StringBuilder requestMessage = new StringBuilder ();
- if (requestUri.Segments.Length > 7) {
- for (int i = 7; i< requestUri.Segments.Length; i++) {
- requestMessage.Append (requestUri.Segments [i]);
+ StringBuilder requestMessage = new StringBuilder();
+ if (requestUri.Segments.Length > 7)
+ {
+ for (int i = 7; i < requestUri.Segments.Length; i++)
+ {
+ requestMessage.Append(requestUri.Segments[i]);
}
}
- foreach (char ch in requestMessage.ToString().ToCharArray()) {
- if(" ~`!@#$^&*()+=[]\\{}|;':\"./<>?".IndexOf(ch) >= 0)
+ foreach (char ch in requestMessage.ToString().ToCharArray())
+ {
+ if (" ~`!@#$^&*()+=[]\\{}|;':\"./<>?".IndexOf(ch) >= 0)
{
isUnsafe = true;
break;
@@ -1411,118 +1419,132 @@ bool RequestIsUnsafe (Uri requestUri)
}
return isUnsafe;
}
-
-
- string CreateRequest (Uri requestUri)
+
+ string CreateRequest(Uri requestUri)
{
- StringBuilder requestBuilder = new StringBuilder ();
- requestBuilder.Append ("GET ");
- requestBuilder.Append (requestUri.OriginalString);
-
- if (ssl) {
- requestBuilder.Append (string.Format (" HTTP/1.1\r\nConnection: close\r\nHost: {0}:443\r\n\r\n", this.domainName));
- } else {
- requestBuilder.Append (string.Format (" HTTP/1.1\r\nConnection: close\r\nHost: {0}:80\r\n\r\n", this.domainName));
+ StringBuilder requestBuilder = new StringBuilder();
+ requestBuilder.Append("GET ");
+ requestBuilder.Append(requestUri.OriginalString);
+
+ if (ssl)
+ {
+ requestBuilder.Append(string.Format(" HTTP/1.1\r\nConnection: close\r\nHost: {0}:443\r\n\r\n", this.domainName));
+ }
+ else
+ {
+ requestBuilder.Append(string.Format(" HTTP/1.1\r\nConnection: close\r\nHost: {0}:80\r\n\r\n", this.domainName));
}
return requestBuilder.ToString();
}
-
- void ConnectToHostAndSendRequest<T> (bool sslEnabled, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
+
+ void ConnectToHostAndSendRequest<T>(bool sslEnabled, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
{
- NetworkStream stream = tcpClient.GetStream ();
-
- string proxyAuth = string.Format ("{0}:{1}", _pubnubProxy.ProxyUserName, _pubnubProxy.ProxyPassword);
- byte[] proxyAuthBytes = Encoding.UTF8.GetBytes (proxyAuth);
-
+ NetworkStream stream = tcpClient.GetStream();
+
+ string proxyAuth = string.Format("{0}:{1}", _pubnubProxy.ProxyUserName, _pubnubProxy.ProxyPassword);
+ byte[] proxyAuthBytes = Encoding.UTF8.GetBytes(proxyAuth);
+
//Proxy-Authenticate: authentication mode Basic, Digest and NTLM
string connectRequest = "";
- if (sslEnabled) {
- connectRequest = string.Format ("CONNECT {0}:443 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String (proxyAuthBytes));
- } else {
- connectRequest = string.Format ("CONNECT {0}:80 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String (proxyAuthBytes));
+ if (sslEnabled)
+ {
+ connectRequest = string.Format("CONNECT {0}:443 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String(proxyAuthBytes));
}
-
- byte[] tunnelRequest = Encoding.UTF8.GetBytes (connectRequest);
- stream.Write (tunnelRequest, 0, tunnelRequest.Length);
- stream.Flush ();
-
+ else
+ {
+ connectRequest = string.Format("CONNECT {0}:80 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String(proxyAuthBytes));
+ }
+
+ byte[] tunnelRequest = Encoding.UTF8.GetBytes(connectRequest);
+ stream.Write(tunnelRequest, 0, tunnelRequest.Length);
+ stream.Flush();
+
stream.ReadTimeout = pubnubRequestState.Request.Timeout * 5;
-
+
StateObject<T> state = new StateObject<T>();
- state.tcpClient =tcpClient;
+ state.tcpClient = tcpClient;
state.RequestState = pubnubRequestState;
state.requestString = requestString;
state.netStream = stream;
-
+
//stream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), state);
-
- StringBuilder response = new StringBuilder ();
+
+ StringBuilder response = new StringBuilder();
var responseStream = new StreamReader(stream);
-
+
char[] buffer = new char[2048];
- int charsRead = responseStream.Read (buffer, 0, buffer.Length);
- bool connEstablished= false;
- while (charsRead > 0) {
- response.Append (buffer);
- if ((response.ToString ().IndexOf ("200 Connection established") > 0) || (response.ToString ().IndexOf ("200 OK") > 0))
+ int charsRead = responseStream.Read(buffer, 0, buffer.Length);
+ bool connEstablished = false;
+ while (charsRead > 0)
+ {
+ response.Append(buffer);
+ if ((response.ToString().IndexOf("200 Connection established") > 0) || (response.ToString().IndexOf("200 OK") > 0))
{
connEstablished = true;
break;
}
- charsRead = responseStream.Read (buffer, 0, buffer.Length);
+ charsRead = responseStream.Read(buffer, 0, buffer.Length);
}
-
- if (connEstablished) {
- if (sslEnabled) {
- SendSslRequest<T> (stream, tcpClient, pubnubRequestState, requestString);
- } else {
+
+ if (connEstablished)
+ {
+ if (sslEnabled)
+ {
+ SendSslRequest<T>(stream, tcpClient, pubnubRequestState, requestString);
+ }
+ else
+ {
SendRequest<T>(tcpClient, pubnubRequestState, requestString);
}
-
- } else if(response.ToString ().IndexOf("407 Proxy Authentication Required") >0 )
+
+ }
+ else if (response.ToString().IndexOf("407 Proxy Authentication Required") > 0)
{
- int pos = response.ToString().IndexOf("Proxy-Authenticate");
+ int pos = response.ToString().IndexOf("Proxy-Authenticate");
string desc = "";
- if(pos >0)
+ if (pos > 0)
{
desc = response.ToString().Substring(pos, response.ToString().IndexOf("\r\n", pos) - pos);
}
- throw new WebException (string.Format("Proxy Authentication Required. Desc: {0}", desc));
+ throw new WebException(string.Format("Proxy Authentication Required. Desc: {0}", desc));
}
- else{
- throw new WebException ("Couldn't connect to the server");
+ else
+ {
+ throw new WebException("Couldn't connect to the server");
}
}
-
- private void ConnectToHostAndSendRequestCallback<T> (IAsyncResult asynchronousResult)
+
+ private void ConnectToHostAndSendRequestCallback<T>(IAsyncResult asynchronousResult)
{
StateObject<T> asynchStateObject = asynchronousResult.AsyncState as StateObject<T>;
RequestState<T> asynchRequestState = asynchStateObject.RequestState;
-
- string channel="";
+
+ string channel = "";
if (asynchRequestState != null && asynchRequestState.Channels != null)
{
channel = string.Join(",", asynchRequestState.Channels);
}
-
- try{
+
+ try
+ {
string requestString = asynchStateObject.requestString;
TcpClient tcpClient = asynchStateObject.tcpClient;
-
+
NetworkStream netStream = asynchStateObject.netStream;
int bytesRead = netStream.EndRead(asynchronousResult);
-
- if (bytesRead > 0) {
- asynchStateObject.sb.Append(Encoding.ASCII.GetString(asynchStateObject.buffer,0,bytesRead));
+
+ if (bytesRead > 0)
+ {
+ asynchStateObject.sb.Append(Encoding.ASCII.GetString(asynchStateObject.buffer, 0, bytesRead));
netStream.BeginRead(asynchStateObject.buffer, 0, StateObject<T>.BufferSize,
- new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), asynchStateObject);
- }
+ new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), asynchStateObject);
+ }
else
{
string resp = asynchStateObject.sb.ToString();
- if(resp.IndexOf("200 Connection established") > 0)
+ if (resp.IndexOf("200 Connection established") > 0)
{
SendSslRequest<T>(netStream, tcpClient, asynchRequestState, requestString);
}
@@ -1541,57 +1563,58 @@ private void ConnectToHostAndSendRequestCallback<T> (IAsyncResult asynchronousRe
ProcessResponseCallbackExceptionHandler<T>(ex, asynchRequestState);
}
}
-
- void SendSslRequest<T> (NetworkStream netStream, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
+
+ void SendSslRequest<T>(NetworkStream netStream, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
{
//NetworkStream netStream = tcpClient.GetStream();
-
+
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient(this.domainName);
StateObject<T> state = new StateObject<T>();
- state.tcpClient =tcpClient;
+ state.tcpClient = tcpClient;
state.sslns = sslStream;
state.RequestState = pubnubRequestState;
byte[] sendBuffer = UTF8Encoding.UTF8.GetBytes(requestString);
- sslStream.Write(sendBuffer);
+ sslStream.Write(sendBuffer);
sslStream.Flush();
sslStream.ReadTimeout = pubnubRequestState.Request.Timeout;
sslStream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
}
-
- void SendRequest<T> (TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
+
+ void SendRequest<T>(TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
{
NetworkStream netStream = tcpClient.GetStream();
StateObject<T> state = new StateObject<T>();
- state.tcpClient =tcpClient;
+ state.tcpClient = tcpClient;
state.netStream = netStream;
state.RequestState = pubnubRequestState;
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(netStream);
- streamWriter.Write (requestString);
- streamWriter.Flush ();
+ streamWriter.Write(requestString);
+ streamWriter.Flush();
netStream.ReadTimeout = pubnubRequestState.Request.Timeout;
netStream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
-
+
}
- private void SendRequestUsingTcpClient<T> (Uri requestUri, RequestState<T> pubnubRequestState)
+ private void SendRequestUsingTcpClient<T>(Uri requestUri, RequestState<T> pubnubRequestState)
{
- TcpClient tcpClient = new TcpClient ();
+ TcpClient tcpClient = new TcpClient();
tcpClient.NoDelay = false;
tcpClient.SendTimeout = pubnubRequestState.Request.Timeout;
string requestString = CreateRequest(requestUri);
- if (ssl) {
+ if (ssl)
+ {
if (pubnubEnableProxyConfig && _pubnubProxy != null)
{
tcpClient.Connect(_pubnubProxy.ProxyServer, _pubnubProxy.ProxyPort);
-
+
ConnectToHostAndSendRequest<T>(ssl, tcpClient, pubnubRequestState, requestString);
}
else
@@ -1600,13 +1623,13 @@ private void SendRequestUsingTcpClient<T> (Uri requestUri, RequestState<T> pubnu
NetworkStream netStream = tcpClient.GetStream();
SendSslRequest<T>(netStream, tcpClient, pubnubRequestState, requestString);
}
- }
- else
+ }
+ else
{
if (pubnubEnableProxyConfig && _pubnubProxy != null)
{
tcpClient.Connect(_pubnubProxy.ProxyServer, _pubnubProxy.ProxyPort);
-
+
ConnectToHostAndSendRequest(ssl, tcpClient, pubnubRequestState, requestString);
}
else
@@ -1617,22 +1640,25 @@ private void SendRequestUsingTcpClient<T> (Uri requestUri, RequestState<T> pubnu
}
}
- private void SendRequestUsingTcpClientCallback<T> (IAsyncResult asynchronousResult)
+ private void SendRequestUsingTcpClientCallback<T>(IAsyncResult asynchronousResult)
{
StateObject<T> state = asynchronousResult.AsyncState as StateObject<T>;
RequestState<T> asynchRequestState = state.RequestState;
- string channel="";
+ string channel = "";
if (asynchRequestState != null && asynchRequestState.Channels != null)
{
channel = string.Join(",", asynchRequestState.Channels);
}
- try {
+ try
+ {
//StateObject<T> state = (StateObject<T>) asynchronousResult.AsyncState;
- if (ssl) {
+ if (ssl)
+ {
SslStream sslns = state.sslns;
int bytesRead = sslns.EndRead(asynchronousResult);
- if (bytesRead > 0) {
+ if (bytesRead > 0)
+ {
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(state.buffer, 0, bytesRead)];
decoder.GetChars(state.buffer, 0, bytesRead, chars, 0);
@@ -1640,21 +1666,24 @@ private void SendRequestUsingTcpClientCallback<T> (IAsyncResult asynchronousResu
sslns.BeginRead(state.buffer, 0, StateObject<T>.BufferSize,
new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
- }
+ }
else
{
HandleTcpClientResponse(state, asynchRequestState, channel, asynchronousResult);
}
- } else {
+ }
+ else
+ {
NetworkStream netStream = state.netStream;
int bytesRead = netStream.EndRead(asynchronousResult);
- if (bytesRead > 0) {
- state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
+ if (bytesRead > 0)
+ {
+ state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
netStream.BeginRead(state.buffer, 0, StateObject<T>.BufferSize,
- new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
- }
+ new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
+ }
else
{
HandleTcpClientResponse(state, asynchRequestState, channel, asynchronousResult);
@@ -1670,8 +1699,45 @@ private void SendRequestUsingTcpClientCallback<T> (IAsyncResult asynchronousResu
ProcessResponseCallbackExceptionHandler<T>(ex, asynchRequestState);
}
}
-
- void ProcessResponseCallbackExceptionHandler<T> (Exception ex, RequestState<T> asynchRequestState)
+
+ void HandleTcpClientResponse<T>(StateObject<T> state, RequestState<T> asynchRequestState, string channel, IAsyncResult asynchronousResult)
+ {
+ List<object> result = new List<object>();
+ if (state.sb.Length > 1)
+ {
+ string jsonString = ParseResponse<T>(state.sb.ToString(), asynchronousResult);
+ LoggingMethod.WriteToLog(string.Format("DateTime {0}, JSON for channel={1} ({2}) ={3}", DateTime.Now.ToString(), channel, asynchRequestState.Type.ToString(), jsonString), LoggingMethod.LevelInfo);
+
+ if (overrideTcpKeepAlive)
+ {
+ TerminateHeartbeatTimer(state.RequestState.Request.RequestUri);
+ }
+
+ if (!string.IsNullOrWhiteSpace(jsonString))
+ {
+ result = WrapResultBasedOnResponseType(asynchRequestState.Type, jsonString, asynchRequestState.Channels, asynchRequestState.Reconnect, asynchRequestState.Timetoken);
+ }
+
+ ProcessResponseCallbacks<T>(result, asynchRequestState);
+ }
+ if (state.tcpClient != null)
+ state.tcpClient.Close();
+ }
+
+ string ParseResponse<T>(string responseString, IAsyncResult asynchronousResult)
+ {
+ string json = "";
+ int pos = responseString.LastIndexOf('\n');
+ if ((responseString.StartsWith("HTTP/1.1 200 OK") || (responseString.StartsWith("HTTP/1.0 200 OK")) && (pos != -1)))
+ {
+ json = responseString.Substring(pos + 1);
+ }
+ return json;
+ }
+
+#endif
+
+ void ProcessResponseCallbackExceptionHandler<T>(Exception ex, RequestState<T> asynchRequestState)
{
//common Exception handler
if (asynchRequestState.Response != null)
@@ -1680,8 +1746,8 @@ void ProcessResponseCallbackExceptionHandler<T> (Exception ex, RequestState<T> a
LoggingMethod.WriteToLog(string.Format("DateTime {0} Exception= {1} for URL: {2}", DateTime.Now.ToString(), ex.ToString(), asynchRequestState.Request.RequestUri.ToString()), LoggingMethod.LevelError);
UrlRequestCommonExceptionHandler<T>(asynchRequestState.Type, asynchRequestState.Channels, asynchRequestState.Timeout, asynchRequestState.UserCallback, asynchRequestState.ConnectCallback, false);
}
-
- void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestState<T> asynchRequestState, string channel)
+
+ void ProcessResponseCallbackWebExceptionHandler<T>(WebException webEx, RequestState<T> asynchRequestState, string channel)
{
bool reconnect = false;
LoggingMethod.WriteToLog(string.Format("DateTime {0}, WebException: {1} for URL: {2}", DateTime.Now.ToString(), webEx.ToString(), asynchRequestState.Request.RequestUri.ToString()), LoggingMethod.LevelError);
@@ -1712,7 +1778,7 @@ void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestS
else
{
_channelInternetRetry.AddOrUpdate(channel, 1, (key, oldValue) => oldValue + 1);
- LoggingMethod.WriteToLog(string.Format("DateTime {0} {1} channel = {2} _urlRequest - Internet connection retry {3} of {4}", DateTime.Now.ToString(), asynchRequestState.Type, string.Join(",",asynchRequestState.Channels), _channelInternetRetry[channel], pubnubNetworkCheckRetries), LoggingMethod.LevelInfo);
+ LoggingMethod.WriteToLog(string.Format("DateTime {0} {1} channel = {2} _urlRequest - Internet connection retry {3} of {4}", DateTime.Now.ToString(), asynchRequestState.Type, string.Join(",", asynchRequestState.Channels), _channelInternetRetry[channel], pubnubNetworkCheckRetries), LoggingMethod.LevelInfo);
}
_channelInternetStatus[channel] = false;
@@ -1723,8 +1789,8 @@ void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestS
UrlRequestCommonExceptionHandler<T>(asynchRequestState.Type, asynchRequestState.Channels, asynchRequestState.Timeout,
asynchRequestState.UserCallback, asynchRequestState.ConnectCallback, reconnect);
}
-
- void ProcessResponseCallbacks<T> (List<object> result, RequestState<T> asynchRequestState)
+
+ void ProcessResponseCallbacks<T>(List<object> result, RequestState<T> asynchRequestState)
{
if (result != null && result.Count >= 1 && asynchRequestState.UserCallback != null)
{
@@ -1732,43 +1798,7 @@ void ProcessResponseCallbacks<T> (List<object> result, RequestState<T> asynchReq
ResponseToUserCallback<T>(result, asynchRequestState.Type, asynchRequestState.Channels, asynchRequestState.UserCallback);
}
}
-
-
- void HandleTcpClientResponse<T> (StateObject<T> state, RequestState<T> asynchRequestState, string channel, IAsyncResult asynchronousResult)
- {
- List<object> result = new List<object>();
- if (state.sb.Length > 1)
- {
- string jsonString = ParseResponse<T>(state.sb.ToString(), asynchronousResult);
- LoggingMethod.WriteToLog(string.Format("DateTime {0}, JSON for channel={1} ({2}) ={3}", DateTime.Now.ToString(), channel, asynchRequestState.Type.ToString(), jsonString), LoggingMethod.LevelInfo);
-
- if (overrideTcpKeepAlive)
- {
- TerminateHeartbeatTimer(state.RequestState.Request.RequestUri);
- }
-
- if(!string.IsNullOrWhiteSpace(jsonString))
- {
- result = WrapResultBasedOnResponseType(asynchRequestState.Type, jsonString, asynchRequestState.Channels, asynchRequestState.Reconnect, asynchRequestState.Timetoken);
- }
-
- ProcessResponseCallbacks<T>(result, asynchRequestState);
- }
- if(state.tcpClient != null)
- state.tcpClient.Close();
- }
-
- string ParseResponse<T>(string responseString, IAsyncResult asynchronousResult)
- {
- string json ="";
- int pos = responseString.LastIndexOf('\n');
- if ((responseString.StartsWith("HTTP/1.1 200 OK") || (responseString.StartsWith("HTTP/1.0 200 OK")) && (pos != -1)))
- {
- json = responseString.Substring(pos+1);
- }
- return json;
- }
-
+
private void UrlProcessResponseCallback<T>(IAsyncResult asynchronousResult)
{
List<object> result = new List<object>();
@@ -1818,9 +1848,9 @@ private void UrlProcessResponseCallback<T>(IAsyncResult asynchronousResult)
{
LoggingMethod.WriteToLog(string.Format("DateTime {0}, Request aborted for channel={1}", DateTime.Now.ToString(), asynchRequestState.Channels), LoggingMethod.LevelInfo);
}
-
+
ProcessResponseCallbacks<T>(result, asynchRequestState);
-
+
if (asynchRequestState.Type == ResponseType.Subscribe || asynchRequestState.Type == ResponseType.Presence)
{
foreach (string currentChannel in asynchRequestState.Channels)
@@ -2405,7 +2435,7 @@ private void TimeExceptionHandler<T>(bool requestTimeout, Action<T> userCallback
/// </summary>
/// <param name="type"></param>
/// <param name="jsonString"></param>
- /// <param name="channelName"></param>
+ /// <param name="channels"></param>
/// <param name="reconnect"></param>
/// <returns></returns>
private List<object> WrapResultBasedOnResponseType(ResponseType type, string jsonString, string[] channels, bool reconnect, long lastTimetoken)
@@ -2565,7 +2595,7 @@ private string EncodeUricomponent(string s, ResponseType type, bool ignoreComma)
{
string encodedUri = "";
StringBuilder o = new StringBuilder();
- foreach (char ch in s.ToCharArray())
+ foreach (char ch in s)
{
if (IsUnsafe(ch,ignoreComma))
{
@@ -4022,10 +4052,12 @@ public string ProxyPassword
}
}
}
-
+
+#if (__MonoCS__)
class StateObject<T>
{
- public RequestState<T> RequestState {
+ public RequestState<T> RequestState
+ {
get;
set;
}
@@ -4038,4 +4070,5 @@ class StateObject<T>
public StringBuilder sb = new StringBuilder();
public string requestString = null;
}
-}
+#endif
+}
View
30 mono-for-mac/3.4/PubNub-Messaging/PubNub-Messaging.userprefs
@@ -1,19 +1,21 @@
<Properties>
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug|x86" />
- <MonoDevelop.Ide.Workbench ActiveDocument="PubNubTest/PubnubUnitTest.cs">
+ <MonoDevelop.Ide.Workbench ActiveDocument="PubNub-Console/Pubnub.cs">
<Files>
- <File FileName="PubNub-Console/Pubnub.cs" Line="2569" Column="14" />
- <File FileName="PubNubTest/WhenSubscribedToAChannel.cs" Line="360" Column="29" />
- <File FileName="PubNubTest/PubnubUnitTest.cs" Line="10" Column="6" />
- <File FileName="PubNubTest/WhenDetailedHistoryIsRequested.cs" Line="43" Column="14" />
+ <File FileName="PubNub-Console/Pubnub.cs" Line="4049" Column="16" />
+ <File FileName="PubNubTest/WhenAClientIsPresented.cs" Line="142" Column="10" />
+ <File FileName="PubNubTest/PubnubUnitTest.cs" Line="21" Column="16" />
+ <File FileName="PubNub-Console/PubnubExample.cs" Line="223" Column="6" />
+ <File FileName="PubNubTest/Common.cs" Line="37" Column="47" />
</Files>
<Pads>
<Pad Id="ProjectPad">
<State expanded="True">
- <Node name="PubNub-Messaging" expanded="True" />
+ <Node name="PubNub-Messaging" expanded="True">
+ <Node name="Pubnub.cs" selected="True" />
+ </Node>
<Node name="PubNub-Messaging.Tests" expanded="True">
<Node name="References" expanded="True" />
- <Node name="PubnubUnitTest.cs" selected="True" />
</Node>
</State>
</Pad>
@@ -42,12 +44,12 @@
<Node name="PubNub-Messaging.Tests" expanded="True">
<Node name="PubNubMessaging" expanded="True">
<Node name="Tests" expanded="True">
- <Node name="WhenAClientIsPresented" expanded="True" />
+ <Node name="WhenAClientIsPresented" expanded="True">
+ <Node name="ThenPresenceShouldReturnCustomUUID" selected="True" />
+ </Node>
<Node name="WhenAMessageIsPublished" expanded="True" />
- <Node name="WhenDetailedHistoryIsRequested" selected="True" />
- <Node name="WhenGetRequestServerTime" expanded="True" />
+ <Node name="WhenDetailedHistoryIsRequested" expanded="True" />
<Node name="WhenSubscribedToAChannel" expanded="True" />
- <Node name="WhenUnsubscribedToAChannel" expanded="True" />
</Node>
</Node>
</Node>
@@ -59,7 +61,11 @@
</Pads>
</MonoDevelop.Ide.Workbench>
<MonoDevelop.Ide.DebuggingService.Breakpoints>
- <BreakpointStore />
+ <BreakpointStore>
+ <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/mono-mac-new copy/3.3.0.1/PubNub-Messaging/PubNub-Console/Pubnub.cs" line="1301" />
+ <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/mono-mac-new copy/3.3.0.1/PubNub-Messaging/PubNubTest/Common.cs" line="29" />
+ <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/mono-mac-new copy/3.3.0.1/PubNub-Messaging/PubNub-Console/Pubnub.cs" line="1504" />
+ </BreakpointStore>
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MonoDevelop.Ide.DebuggingService.PinnedWatches>
<Watch file="PubNub-Messaging/Pubnub.cs" line="549" offsetX="648" offsetY="6960" expression="result" liveUpdate="False" />
View
2  mono-for-mac/3.4/PubNub-Messaging/PubNubTest/Common.cs
@@ -21,7 +21,7 @@ public PubnubUnitTest CreateUnitTestInstance(string testClassName, string testCa
public void DisplayReturnMessageDummy(object result)
{
//deliveryStatus = true;
- Response = result;
+ //Response = result;
}
public void DisplayReturnMessage(object result)
View
1  mono-for-mac/3.4/PubNub-Messaging/PubNubTest/PubNub-Messaging.Tests.csproj
@@ -40,7 +40,6 @@
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Web" />
- <Reference Include="Mono.WebBrowser" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
View
14 mono-for-mac/3.4/PubNub-Messaging/PubNubTest/PubnubUnitTest.cs
@@ -471,12 +471,14 @@ public bool EnableStubTest
data.Add("/subscribe/demo/hello_world/0/13559006802662768", "[[\"f7wNXpx8Ys8pVJNR5ZHT9g==\"],\"13559014566792816\"]");
data.Add("/subscribe/demo/hello_world/0/13559014566792816", "[[],\"13559014566792816\"]");
#else
- data.Add("/subscribe/demo/hello_world-pnpres/0/0", "[[],\"13559007117760880\"]");
- data.Add("/subscribe/demo/hello_world-pnpres,hello_world/0/0", "[[{\"action\": \"join\", \"timestamp\": 1355929955, \"uuid\": \"CustomSessionUUIDTest\", \"occupancy\": 1}],\"13559011560379628\"]");
- data.Add("/subscribe/demo/hello_world-pnpres/0/13559011560379628", "[[],\"13559011560379628\"]");
- data.Add("/subscribe/demo/hello_world/0/0", "[[],\"13559006802662768\"]");
- data.Add("/subscribe/demo/hello_world/0/13559006802662768", "[[\"demo test for stubs\"],\"13559014566792816\"]");
- data.Add("/subscribe/demo/hello_world/0/13559014566792816", "[[],\"13559014566792816\"]");
+ data.Add("/subscribe/demo/hello_world-pnpres/0/0", "[[],\"13559007117760880\"]");
+ data.Add("/v2/presence/sub_key/demo/channel/hello_world", "{\"uuids\":[\"1b31e299-0c55-4e0b-b1da-04243dd1b4aa\",\"CustomSessionUUIDTest\"],\"occupancy\":2}");
+ data.Add("/subscribe/demo/hello_world/0/0", "[[],\"13559011560379628\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559011560379628", "[[],\"13559014566792816\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559007117760880", "[[{\"action\": \"join\", \"timestamp\": 1355929955, \"uuid\": \"CustomSessionUUIDTest\", \"occupancy\": 1}],\"13559011560379628\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559006802662768", "[[\"f7wNXpx8Ys8pVJNR5ZHT9g==\"],\"13559014566792816\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559014566792816", "[[],\"13559014566792816\"]");
+
#endif
data.Add("/v2/presence/sub_key/demo/channel/hello_world/leave", "{\"action\": \"leave\"}");
return data;
View
42 mono-for-mac/3.4/PubNub-Messaging/PubNubTest/WhenAClientIsPresented.cs
@@ -141,41 +141,33 @@ public void ThenPresenceShouldReturnCustomUUID()
{
Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);
- Common common = new Common();
- common.DeliveryStatus = false;
- common.Response = null;
+ Common commonHereNow = new Common();
+ commonHereNow.DeliveryStatus = false;
+ commonHereNow.Response = null;
- pubnub.PubnubUnitTest = common.CreateUnitTestInstance("WhenAClientIsPresented", "ThenPresenceShouldReturnCustomUUID");;
+ Common commonSubscribe = new Common();
+ commonSubscribe.DeliveryStatus = false;
+ commonSubscribe.Response = null;
+
+ pubnub.PubnubUnitTest = commonHereNow.CreateUnitTestInstance("WhenAClientIsPresented", "ThenPresenceShouldReturnCustomUUID");;
pubnub.SessionUUID = "CustomSessionUUIDTest";
string channel = "hello_world";
- pubnub.Presence(channel, common.DisplayReturnMessageDummy, common.DisplayReturnMessageDummy);
-
- pubnub.Subscribe(channel, common.DisplayReturnMessage, common.DisplayReturnMessageDummy);
+ pubnub.Subscribe(channel, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessage);
+
+ while (!commonSubscribe.DeliveryStatus);
- while (!common.DeliveryStatus) ;
-
- string response = "";
- if (common.Response.Equals (null)) {
+ pubnub.HereNow<string>(channel, commonHereNow.DisplayReturnMessage);
+
+ while (!commonHereNow.DeliveryStatus);
+
+ if (commonHereNow.Response == null) {
Assert.Fail("Null response");
}
else
{
- IList<object> responseFields = common.Response as IList<object>;
- if(responseFields != null)
- {
- foreach (object item in responseFields)
- {
- response = item.ToString();
- Console.WriteLine("Response:" + response);
- }
- Assert.True((responseFields[0].ToString()).Contains(pubnub.SessionUUID));
- }
- else
- {
- Assert.Fail("null response");
- }
+ Assert.True(commonHereNow.Response.ToString().Contains(pubnub.SessionUUID));
}
}
}
View
1  mono-for-mac/3.4/PubNub-Messaging/PubNubTest/WhenAMessageIsPublished.cs
@@ -8,7 +8,6 @@
using System.IO;
using System.Diagnostics;
using System.Text;
-using Mono.Mozilla;
using System.Net.Sockets;
namespace PubNubMessaging.Tests
View
13 monotouch/3.4/Pubnub-Messaging/Pubnub-Messaging.Tests/PubnubUnitTest.cs
@@ -8,7 +8,7 @@ namespace PubNubMessaging.Tests
{
public class PubnubUnitTest : IPubnubUnitTest
{
- private bool enableStubTest = false;
+ private bool enableStubTest = true;
private string testClassName = "";
private string testCaseName = "";
@@ -472,11 +472,12 @@ public bool EnableStubTest
data.Add("/subscribe/demo/hello_world/0/13559014566792816", "[[],\"13559014566792816\"]");
#else
data.Add("/subscribe/demo/hello_world-pnpres/0/0", "[[],\"13559007117760880\"]");
- data.Add("/subscribe/demo/hello_world-pnpres,hello_world/0/0", "[[{\"action\": \"join\", \"timestamp\": 1355929955, \"uuid\": \"CustomSessionUUIDTest\", \"occupancy\": 1}],\"13559011560379628\"]");
- data.Add("/subscribe/demo/hello_world-pnpres/0/13559011560379628", "[[],\"13559011560379628\"]");
- data.Add("/subscribe/demo/hello_world/0/0", "[[],\"13559006802662768\"]");
- data.Add("/subscribe/demo/hello_world/0/13559006802662768", "[[\"demo test for stubs\"],\"13559014566792816\"]");
- data.Add("/subscribe/demo/hello_world/0/13559014566792816", "[[],\"13559014566792816\"]");
+ data.Add("/v2/presence/sub_key/demo/channel/hello_world", "{\"uuids\":[\"1b31e299-0c55-4e0b-b1da-04243dd1b4aa\",\"CustomSessionUUIDTest\"],\"occupancy\":2}");
+ data.Add("/subscribe/demo/hello_world/0/0", "[[],\"13559011560379628\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559011560379628", "[[],\"13559014566792816\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559007117760880", "[[{\"action\": \"join\", \"timestamp\": 1355929955, \"uuid\": \"CustomSessionUUIDTest\", \"occupancy\": 1}],\"13559011560379628\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559006802662768", "[[\"f7wNXpx8Ys8pVJNR5ZHT9g==\"],\"13559014566792816\"]");
+ data.Add("/subscribe/demo/hello_world/0/13559014566792816", "[[],\"13559014566792816\"]");
#endif
data.Add("/v2/presence/sub_key/demo/channel/hello_world/leave", "{\"action\": \"leave\"}");
return data;
View
40 monotouch/3.4/Pubnub-Messaging/Pubnub-Messaging.Tests/WhenAClientIsPresented.cs
@@ -141,42 +141,34 @@ public void ThenPresenceShouldReturnCustomUUID()
{
Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);
- Common common = new Common();
- common.DeliveryStatus = false;
- common.Response = null;
+ Common commonHereNow = new Common();
+ commonHereNow.DeliveryStatus = false;
+ commonHereNow.Response = null;
- pubnub.PubnubUnitTest = common.CreateUnitTestInstance("WhenAClientIsPresented", "ThenPresenceShouldReturnCustomUUID");;
+ Common commonSubscribe = new Common();
+ commonSubscribe.DeliveryStatus = false;
+ commonSubscribe.Response = null;
+
+ pubnub.PubnubUnitTest = commonHereNow.CreateUnitTestInstance("WhenAClientIsPresented", "ThenPresenceShouldReturnCustomUUID");;
pubnub.SessionUUID = "CustomSessionUUIDTest";
string channel = "hello_world";
- pubnub.Presence(channel, common.DisplayReturnMessageDummy, common.DisplayReturnMessageDummy);
+ pubnub.Subscribe(channel, commonSubscribe.DisplayReturnMessageDummy, commonSubscribe.DisplayReturnMessage);
- pubnub.Subscribe(channel, common.DisplayReturnMessage, common.DisplayReturnMessageDummy);
+ while (!commonSubscribe.DeliveryStatus) ;
- while (!common.DeliveryStatus) ;
+ pubnub.HereNow<string>(channel, commonHereNow.DisplayReturnMessage);
- string response = "";
- if (common.Response.Equals (null)) {
+ while (!commonHereNow.DeliveryStatus) ;
+
+ if (commonHereNow.Response == null) {
Assert.Fail("Null response");
}
else
{
- IList<object> responseFields = common.Response as IList<object>;
- if(responseFields != null)
- {
- foreach (object item in responseFields)
- {
- response = item.ToString();
- Console.WriteLine("Response:" + response);
- }
- Assert.True((responseFields[0].ToString()).Contains(pubnub.SessionUUID));
- }
- else
- {
- Assert.Fail("null response");
- }
- }
+ Assert.True(commonHereNow.Response.ToString().Contains(pubnub.SessionUUID));
+ }
}
}
}
View
25 monotouch/3.4/Pubnub-Messaging/Pubnub-Messaging.userprefs
@@ -1,21 +1,22 @@
<Properties>
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug|iPhoneSimulator" />
- <MonoDevelop.Ide.Workbench ActiveDocument="Pubnub-Messaging.Tests/WhenAClientIsPresented.cs">
+ <MonoDevelop.Ide.Workbench ActiveDocument="Pubnub-Messaging/Pubnub.cs">
<Files>
- <File FileName="Pubnub-Messaging.Tests/WhenAClientIsPresented.cs" Line="125" Column="20" />
- <File FileName="Pubnub-Messaging.Tests/PubnubUnitTest.cs" Line="27" Column="66" />
- <File FileName="Pubnub-Messaging/Pubnub.cs" Line="2416" Column="27" />
- <File FileName="Pubnub-Messaging/Pubnub_MessagingSpeedTest.cs" Line="192" Column="30" />
- <File FileName="Pubnub-Messaging/Pubnub_MessagingMain.cs" Line="38" Column="40" />
- <File FileName="Pubnub-Messaging/Pubnub_MessagingSub.cs" Line="61" Column="1" />
+ <File FileName="Pubnub-Messaging.Tests/WhenAClientIsPresented.cs" Line="33" Column="52" />
+ <File FileName="Pubnub-Messaging.Tests/PubnubUnitTest.cs" Line="70" Column="9" />
+ <File FileName="Pubnub-Messaging/Pubnub_MessagingSpeedTest.cs" Line="199" Column="4" />
+ <File FileName="Pubnub-Messaging.Tests/Common.cs" Line="13" Column="82" />
+ <File FileName="Pubnub-Messaging/Pubnub_MessagingSub.cs" Line="285" Column="4" />
+ <File FileName="Pubnub-Messaging/Pubnub_MessagingMain.cs" Line="146" Column="30" />
+ <File FileName="Pubnub-Messaging/Pubnub.cs" Line="2411" Column="9" />
</Files>
<Pads>
<Pad Id="ProjectPad">
<State expanded="True">
- <Node name="Pubnub-Messaging" expanded="True" />
- <Node name="Pubnub-Messaging.Tests" expanded="True">
- <Node name="WhenAClientIsPresented.cs" selected="True" />
+ <Node name="Pubnub-Messaging" expanded="True">
+ <Node name="Pubnub.cs" selected="True" />
</Node>
+ <Node name="Pubnub-Messaging.Tests" expanded="True" />
</State>
</Pad>
</Pads>
@@ -28,7 +29,9 @@
<Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging/Pubnub_MessagingMain.cs" line="191" />
<Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging/Pubnub.cs" line="1577" />
<Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging/Pubnub.cs" line="1561" />
- <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging/Pubnub.cs" line="2415" />
+ <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging.Tests/WhenAClientIsPresented.cs" line="40" />
+ <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging/Pubnub.cs" line="1812" />
+ <Breakpoint file="/Volumes/Macintosh/Users/rajatkalsy/Projects/Client/ODesk/pubnub/MonoTouch/Pubnub-Messaging/Pubnub-Messaging/Pubnub.cs" line="2416" />
</BreakpointStore>
</MonoDevelop.Ide.DebuggingService.Breakpoints>
<MonoDevelop.Ide.DebuggingService.PinnedWatches />
View
273 monotouch/3.4/Pubnub-Messaging/Pubnub-Messaging/Pubnub.cs
@@ -1,4 +1,4 @@
-//Build Date: Feb 18, 2013
+//Build Date: March 07, 2013
#if (__MonoCS__)
#define TRACE
#endif
@@ -122,7 +122,9 @@ public PubnubProxy Proxy
// Pubnub Core API implementation
private string origin = "pubsub.pubnub.com";
+#if (__MonoCS__)
private string domainName = "pubsub.pubnub.com";
+#endif
private string publishKey = "";
private string subscribeKey = "";
private string secretKey = "";
@@ -1304,7 +1306,7 @@ private bool ProcessRequest(List<string> urlComponents, ResponseType type)
return true;
}
- catch (System.Exception ex)
+ catch (System.Exception)
{
return false;
}
@@ -1363,6 +1365,8 @@ private bool UrlProcessRequest<T>(Uri requestUri, RequestState<T> pubnubRequestS
#endif
}
LoggingMethod.WriteToLog(string.Format("DateTime {0}, Request={1}", DateTime.Now.ToString(), requestUri.ToString()), LoggingMethod.LevelInfo);
+
+
#if (__MonoCS__)
if((pubnubRequestState.Type == ResponseType.Publish) && (RequestIsUnsafe(requestUri)))
{
@@ -1393,17 +1397,21 @@ private bool UrlProcessRequest<T>(Uri requestUri, RequestState<T> pubnubRequestS
}
}
- bool RequestIsUnsafe (Uri requestUri)
+#if (__MonoCS__)
+ bool RequestIsUnsafe(Uri requestUri)
{
bool isUnsafe = false;
- StringBuilder requestMessage = new StringBuilder ();
- if (requestUri.Segments.Length > 7) {
- for (int i = 7; i< requestUri.Segments.Length; i++) {
- requestMessage.Append (requestUri.Segments [i]);
+ StringBuilder requestMessage = new StringBuilder();
+ if (requestUri.Segments.Length > 7)
+ {
+ for (int i = 7; i < requestUri.Segments.Length; i++)
+ {
+ requestMessage.Append(requestUri.Segments[i]);
}
}
- foreach (char ch in requestMessage.ToString().ToCharArray()) {
- if(" ~`!@#$^&*()+=[]\\{}|;':\"./<>?".IndexOf(ch) >= 0)
+ foreach (char ch in requestMessage.ToString().ToCharArray())
+ {
+ if (" ~`!@#$^&*()+=[]\\{}|;':\"./<>?".IndexOf(ch) >= 0)
{
isUnsafe = true;
break;
@@ -1412,117 +1420,131 @@ bool RequestIsUnsafe (Uri requestUri)
return isUnsafe;
}
-
- string CreateRequest (Uri requestUri)
+ string CreateRequest(Uri requestUri)
{
- StringBuilder requestBuilder = new StringBuilder ();
- requestBuilder.Append ("GET ");
- requestBuilder.Append (requestUri.OriginalString);
+ StringBuilder requestBuilder = new StringBuilder();
+ requestBuilder.Append("GET ");
+ requestBuilder.Append(requestUri.OriginalString);
- if (ssl) {
- requestBuilder.Append (string.Format (" HTTP/1.1\r\nConnection: close\r\nHost: {0}:443\r\n\r\n", this.domainName));
- } else {
- requestBuilder.Append (string.Format (" HTTP/1.1\r\nConnection: close\r\nHost: {0}:80\r\n\r\n", this.domainName));
+ if (ssl)
+ {
+ requestBuilder.Append(string.Format(" HTTP/1.1\r\nConnection: close\r\nHost: {0}:443\r\n\r\n", this.domainName));
+ }
+ else
+ {
+ requestBuilder.Append(string.Format(" HTTP/1.1\r\nConnection: close\r\nHost: {0}:80\r\n\r\n", this.domainName));
}
return requestBuilder.ToString();
}
- void ConnectToHostAndSendRequest<T> (bool sslEnabled, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
+ void ConnectToHostAndSendRequest<T>(bool sslEnabled, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
{
- NetworkStream stream = tcpClient.GetStream ();
+ NetworkStream stream = tcpClient.GetStream();
- string proxyAuth = string.Format ("{0}:{1}", _pubnubProxy.ProxyUserName, _pubnubProxy.ProxyPassword);
- byte[] proxyAuthBytes = Encoding.UTF8.GetBytes (proxyAuth);
+ string proxyAuth = string.Format("{0}:{1}", _pubnubProxy.ProxyUserName, _pubnubProxy.ProxyPassword);
+ byte[] proxyAuthBytes = Encoding.UTF8.GetBytes(proxyAuth);
//Proxy-Authenticate: authentication mode Basic, Digest and NTLM
string connectRequest = "";
- if (sslEnabled) {
- connectRequest = string.Format ("CONNECT {0}:443 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String (proxyAuthBytes));
- } else {
- connectRequest = string.Format ("CONNECT {0}:80 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String (proxyAuthBytes));
+ if (sslEnabled)
+ {
+ connectRequest = string.Format("CONNECT {0}:443 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String(proxyAuthBytes));
+ }
+ else
+ {
+ connectRequest = string.Format("CONNECT {0}:80 HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this.domainName, Convert.ToBase64String(proxyAuthBytes));
}
- byte[] tunnelRequest = Encoding.UTF8.GetBytes (connectRequest);
- stream.Write (tunnelRequest, 0, tunnelRequest.Length);
- stream.Flush ();
+ byte[] tunnelRequest = Encoding.UTF8.GetBytes(connectRequest);
+ stream.Write(tunnelRequest, 0, tunnelRequest.Length);
+ stream.Flush();
stream.ReadTimeout = pubnubRequestState.Request.Timeout * 5;
StateObject<T> state = new StateObject<T>();
- state.tcpClient =tcpClient;
+ state.tcpClient = tcpClient;
state.RequestState = pubnubRequestState;
state.requestString = requestString;
state.netStream = stream;
//stream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), state);
- StringBuilder response = new StringBuilder ();
+ StringBuilder response = new StringBuilder();
var responseStream = new StreamReader(stream);
char[] buffer = new char[2048];
- int charsRead = responseStream.Read (buffer, 0, buffer.Length);
- bool connEstablished= false;
- while (charsRead > 0) {
- response.Append (buffer);
- if ((response.ToString ().IndexOf ("200 Connection established") > 0) || (response.ToString ().IndexOf ("200 OK") > 0))
+ int charsRead = responseStream.Read(buffer, 0, buffer.Length);
+ bool connEstablished = false;
+ while (charsRead > 0)
+ {
+ response.Append(buffer);
+ if ((response.ToString().IndexOf("200 Connection established") > 0) || (response.ToString().IndexOf("200 OK") > 0))
{
connEstablished = true;
break;
}
- charsRead = responseStream.Read (buffer, 0, buffer.Length);
+ charsRead = responseStream.Read(buffer, 0, buffer.Length);
}
- if (connEstablished) {
- if (sslEnabled) {
- SendSslRequest<T> (stream, tcpClient, pubnubRequestState, requestString);
- } else {
+ if (connEstablished)
+ {
+ if (sslEnabled)
+ {
+ SendSslRequest<T>(stream, tcpClient, pubnubRequestState, requestString);
+ }
+ else
+ {
SendRequest<T>(tcpClient, pubnubRequestState, requestString);
}
- } else if(response.ToString ().IndexOf("407 Proxy Authentication Required") >0 )
+ }
+ else if (response.ToString().IndexOf("407 Proxy Authentication Required") > 0)
{
- int pos = response.ToString().IndexOf("Proxy-Authenticate");
+ int pos = response.ToString().IndexOf("Proxy-Authenticate");
string desc = "";
- if(pos >0)
+ if (pos > 0)
{
desc = response.ToString().Substring(pos, response.ToString().IndexOf("\r\n", pos) - pos);
}
- throw new WebException (string.Format("Proxy Authentication Required. Desc: {0}", desc));
+ throw new WebException(string.Format("Proxy Authentication Required. Desc: {0}", desc));
}
- else{
- throw new WebException ("Couldn't connect to the server");
+ else
+ {
+ throw new WebException("Couldn't connect to the server");
}
}
- private void ConnectToHostAndSendRequestCallback<T> (IAsyncResult asynchronousResult)
+ private void ConnectToHostAndSendRequestCallback<T>(IAsyncResult asynchronousResult)
{
StateObject<T> asynchStateObject = asynchronousResult.AsyncState as StateObject<T>;
RequestState<T> asynchRequestState = asynchStateObject.RequestState;
- string channel="";
+ string channel = "";
if (asynchRequestState != null && asynchRequestState.Channels != null)
{
channel = string.Join(",", asynchRequestState.Channels);
}
- try{
+ try
+ {
string requestString = asynchStateObject.requestString;
TcpClient tcpClient = asynchStateObject.tcpClient;
NetworkStream netStream = asynchStateObject.netStream;
int bytesRead = netStream.EndRead(asynchronousResult);
- if (bytesRead > 0) {
- asynchStateObject.sb.Append(Encoding.ASCII.GetString(asynchStateObject.buffer,0,bytesRead));
+ if (bytesRead > 0)
+ {
+ asynchStateObject.sb.Append(Encoding.ASCII.GetString(asynchStateObject.buffer, 0, bytesRead));
netStream.BeginRead(asynchStateObject.buffer, 0, StateObject<T>.BufferSize,
new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), asynchStateObject);
- }
+ }
else
{
string resp = asynchStateObject.sb.ToString();
- if(resp.IndexOf("200 Connection established") > 0)
+ if (resp.IndexOf("200 Connection established") > 0)
{
SendSslRequest<T>(netStream, tcpClient, asynchRequestState, requestString);
}
@@ -1542,7 +1564,7 @@ private void ConnectToHostAndSendRequestCallback<T> (IAsyncResult asynchronousRe
}
}
- void SendSslRequest<T> (NetworkStream netStream, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
+ void SendSslRequest<T>(NetworkStream netStream, TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
{
//NetworkStream netStream = tcpClient.GetStream();
@@ -1550,44 +1572,45 @@ void SendSslRequest<T> (NetworkStream netStream, TcpClient tcpClient, RequestSta
sslStream.AuthenticateAsClient(this.domainName);
StateObject<T> state = new StateObject<T>();
- state.tcpClient =tcpClient;
+ state.tcpClient = tcpClient;
state.sslns = sslStream;
state.RequestState = pubnubRequestState;
byte[] sendBuffer = UTF8Encoding.UTF8.GetBytes(requestString);
- sslStream.Write(sendBuffer);
+ sslStream.Write(sendBuffer);
sslStream.Flush();
sslStream.ReadTimeout = pubnubRequestState.Request.Timeout;
sslStream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
}
- void SendRequest<T> (TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
+ void SendRequest<T>(TcpClient tcpClient, RequestState<T> pubnubRequestState, string requestString)
{
NetworkStream netStream = tcpClient.GetStream();
StateObject<T> state = new StateObject<T>();
- state.tcpClient =tcpClient;
+ state.tcpClient = tcpClient;
state.netStream = netStream;
state.RequestState = pubnubRequestState;
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(netStream);
- streamWriter.Write (requestString);
- streamWriter.Flush ();
+ streamWriter.Write(requestString);
+ streamWriter.Flush();
netStream.ReadTimeout = pubnubRequestState.Request.Timeout;
netStream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
}
- private void SendRequestUsingTcpClient<T> (Uri requestUri, RequestState<T> pubnubRequestState)
+ private void SendRequestUsingTcpClient<T>(Uri requestUri, RequestState<T> pubnubRequestState)
{
- TcpClient tcpClient = new TcpClient ();
+ TcpClient tcpClient = new TcpClient();
tcpClient.NoDelay = false;
tcpClient.SendTimeout = pubnubRequestState.Request.Timeout;
string requestString = CreateRequest(requestUri);
- if (ssl) {
+ if (ssl)
+ {
if (pubnubEnableProxyConfig && _pubnubProxy != null)
{
tcpClient.Connect(_pubnubProxy.ProxyServer, _pubnubProxy.ProxyPort);
@@ -1600,8 +1623,8 @@ private void SendRequestUsingTcpClient<T> (Uri requestUri, RequestState<T> pubnu
NetworkStream netStream = tcpClient.GetStream();
SendSslRequest<T>(netStream, tcpClient, pubnubRequestState, requestString);
}
- }
- else
+ }
+ else
{
if (pubnubEnableProxyConfig && _pubnubProxy != null)
{
@@ -1617,22 +1640,25 @@ private void SendRequestUsingTcpClient<T> (Uri requestUri, RequestState<T> pubnu
}
}
- private void SendRequestUsingTcpClientCallback<T> (IAsyncResult asynchronousResult)
+ private void SendRequestUsingTcpClientCallback<T>(IAsyncResult asynchronousResult)
{
StateObject<T> state = asynchronousResult.AsyncState as StateObject<T>;
RequestState<T> asynchRequestState = state.RequestState;
- string channel="";
+ string channel = "";
if (asynchRequestState != null && asynchRequestState.Channels != null)
{
channel = string.Join(",", asynchRequestState.Channels);
}
- try {
+ try
+ {
//StateObject<T> state = (StateObject<T>) asynchronousResult.AsyncState;
- if (ssl) {
+ if (ssl)
+ {
SslStream sslns = state.sslns;
int bytesRead = sslns.EndRead(asynchronousResult);
- if (bytesRead > 0) {
+ if (bytesRead > 0)
+ {
Decoder decoder = Encoding.UTF8.GetDecoder();
char[] chars = new char[decoder.GetCharCount(state.buffer, 0, bytesRead)];
decoder.GetChars(state.buffer, 0, bytesRead, chars, 0);
@@ -1640,21 +1666,24 @@ private void SendRequestUsingTcpClientCallback<T> (IAsyncResult asynchronousResu
sslns.BeginRead(state.buffer, 0, StateObject<T>.BufferSize,
new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
- }
+ }
else
{
HandleTcpClientResponse(state, asynchRequestState, channel, asynchronousResult);
}
- } else {
+ }
+ else
+ {
NetworkStream netStream = state.netStream;
int bytesRead = netStream.EndRead(asynchronousResult);
- if (bytesRead > 0) {
- state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
+ if (bytesRead > 0)
+ {
+ state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
netStream.BeginRead(state.buffer, 0, StateObject<T>.BufferSize,
new AsyncCallback(SendRequestUsingTcpClientCallback<T>), state);
- }
+ }
else
{
HandleTcpClientResponse(state, asynchRequestState, channel, asynchronousResult);
@@ -1671,7 +1700,44 @@ private void SendRequestUsingTcpClientCallback<T> (IAsyncResult asynchronousResu
}
}
- void ProcessResponseCallbackExceptionHandler<T> (Exception ex, RequestState<T> asynchRequestState)
+ void HandleTcpClientResponse<T>(StateObject<T> state, RequestState<T> asynchRequestState, string channel, IAsyncResult asynchronousResult)
+ {
+ List<object> result = new List<object>();
+ if (state.sb.Length > 1)
+ {
+ string jsonString = ParseResponse<T>(state.sb.ToString(), asynchronousResult);
+ LoggingMethod.WriteToLog(string.Format("DateTime {0}, JSON for channel={1} ({2}) ={3}", DateTime.Now.ToString(), channel, asynchRequestState.Type.ToString(), jsonString), LoggingMethod.LevelInfo);
+
+ if (overrideTcpKeepAlive)
+ {
+ TerminateHeartbeatTimer(state.RequestState.Request.RequestUri);
+ }
+
+ if (!string.IsNullOrWhiteSpace(jsonString))
+ {
+ result = WrapResultBasedOnResponseType(asynchRequestState.Type, jsonString, asynchRequestState.Channels, asynchRequestState.Reconnect, asynchRequestState.Timetoken);
+ }
+
+ ProcessResponseCallbacks<T>(result, asynchRequestState);
+ }
+ if (state.tcpClient != null)
+ state.tcpClient.Close();
+ }
+
+ string ParseResponse<T>(string responseString, IAsyncResult asynchronousResult)
+ {
+ string json = "";
+ int pos = responseString.LastIndexOf('\n');
+ if ((responseString.StartsWith("HTTP/1.1 200 OK") || (responseString.StartsWith("HTTP/1.0 200 OK")) && (pos != -1)))
+ {
+ json = responseString.Substring(pos + 1);
+ }
+ return json;
+ }
+
+#endif
+
+ void ProcessResponseCallbackExceptionHandler<T>(Exception ex, RequestState<T> asynchRequestState)
{
//common Exception handler
if (asynchRequestState.Response != null)
@@ -1681,7 +1747,7 @@ void ProcessResponseCallbackExceptionHandler<T> (Exception ex, RequestState<T> a
UrlRequestCommonExceptionHandler<T>(asynchRequestState.Type, asynchRequestState.Channels, asynchRequestState.Timeout, asynchRequestState.UserCallback, asynchRequestState.ConnectCallback, false);
}
- void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestState<T> asynchRequestState, string channel)
+ void ProcessResponseCallbackWebExceptionHandler<T>(WebException webEx, RequestState<T> asynchRequestState, string channel)
{
bool reconnect = false;
LoggingMethod.WriteToLog(string.Format("DateTime {0}, WebException: {1} for URL: {2}", DateTime.Now.ToString(), webEx.ToString(), asynchRequestState.Request.RequestUri.ToString()), LoggingMethod.LevelError);
@@ -1712,7 +1778,7 @@ void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestS
else
{
_channelInternetRetry.AddOrUpdate(channel, 1, (key, oldValue) => oldValue + 1);
- LoggingMethod.WriteToLog(string.Format("DateTime {0} {1} channel = {2} _urlRequest - Internet connection retry {3} of {4}", DateTime.Now.ToString(), asynchRequestState.Type, string.Join(",",asynchRequestState.Channels), _channelInternetRetry[channel], pubnubNetworkCheckRetries), LoggingMethod.LevelInfo);
+ LoggingMethod.WriteToLog(string.Format("DateTime {0} {1} channel = {2} _urlRequest - Internet connection retry {3} of {4}", DateTime.Now.ToString(), asynchRequestState.Type, string.Join(",", asynchRequestState.Channels), _channelInternetRetry[channel], pubnubNetworkCheckRetries), LoggingMethod.LevelInfo);
}
_channelInternetStatus[channel] = false;
@@ -1724,7 +1790,7 @@ void ProcessResponseCallbackWebExceptionHandler<T> (WebException webEx, RequestS
asynchRequestState.UserCallback, asynchRequestState.ConnectCallback, reconnect);
}
- void ProcessResponseCallbacks<T> (List<object> result, RequestState<T> asynchRequestState)
+ void ProcessResponseCallbacks<T>(List<object> result, RequestState<T> asynchRequestState)
{
if (result != null && result.Count >= 1 && asynchRequestState.UserCallback != null)
{
@@ -1733,42 +1799,6 @@ void ProcessResponseCallbacks<T> (List<object> result, RequestState<T> asynchReq
}
}
-
- void HandleTcpClientResponse<T> (StateObject<T> state, RequestState<T> asynchRequestState, string channel, IAsyncResult asynchronousResult)
- {
- List<object> result = new List<object>();
- if (state.sb.Length > 1)
- {
- string jsonString = ParseResponse<T>(state.sb.ToString(), asynchronousResult);
- LoggingMethod.WriteToLog(string.Format("DateTime {0}, JSON for channel={1} ({2}) ={3}", DateTime.Now.ToString(), channel, asynchRequestState.Type.ToString(), jsonString), LoggingMethod.LevelInfo);
-
- if (overrideTcpKeepAlive)
- {
- TerminateHeartbeatTimer(state.RequestState.Request.RequestUri);
- }
-
- if(!string.IsNullOrWhiteSpace(jsonString))
- {
- result = WrapResultBasedOnResponseType(asynchRequestState.Type, jsonString, asynchRequestState.Channels, asynchRequestState.Reconnect, asynchRequestState.Timetoken);
- }
-
- ProcessResponseCallbacks<T>(result, asynchRequestState);
- }
- if(state.tcpClient != null)
- state.tcpClient.Close();
- }
-
- string ParseResponse<T>(string responseString, IAsyncResult asynchronousResult)
- {
- string json ="";
- int pos = responseString.LastIndexOf('\n');
- if ((responseString.StartsWith("HTTP/1.1 200 OK") || (responseString.StartsWith("HTTP/1.0 200 OK")) && (pos != -1)))
- {
- json = responseString.Substring(pos+1);
- }
- return json;
- }
-
private void UrlProcessResponseCallback<T>(IAsyncResult asynchronousResult)
{
List<object> result = new List<object>();
@@ -2405,7 +2435,7 @@ private void TimeExceptionHandler<T>(bool requestTimeout, Action<T> userCallback
/// </summary>
/// <param name="type"></param>
/// <param name="jsonString"></param>
- /// <param name="channelName"></param>
+ /// <param name="channels"></param>
/// <param name="reconnect"></param>
/// <returns></returns>
private List<object> WrapResultBasedOnResponseType(ResponseType type, string jsonString, string[] channels, bool reconnect, long lastTimetoken)
@@ -2565,7 +2595,7 @@ private string EncodeUricomponent(string s, ResponseType type, bool ignoreComma)
{
string encodedUri = "";
StringBuilder o = new StringBuilder();
- foreach (char ch in s.ToCharArray())
+ foreach (char ch in s)
{
if (IsUnsafe(ch,ignoreComma))
{
@@ -4023,9 +4053,11 @@ public string ProxyPassword
}
}
+#if (__MonoCS__)
class StateObject<T>
{
- public RequestState<T> RequestState {
+ public RequestState<T> RequestState
+ {
get;
set;
}
@@ -4038,4 +4070,5 @@ class StateObject<T>
public StringBuilder sb = new StringBuilder();
public string requestString = null;
}
-}
+#endif
+}
Please sign in to comment.
Something went wrong with that request. Please try again.