PageRenderTime 83ms CodeModel.GetById 40ms app.highlight 11ms RepoModel.GetById 29ms app.codeStats 0ms

/SDK Sample Projects/Win8/PushSDK/TagsService.cs

https://github.com/doluyen/push-notifications-sdk
C# | 175 lines | 129 code | 33 blank | 13 comment | 17 complexity | 7c11423eb6630735badbb9aa50620192 MD5 | raw file
  1using Newtonsoft.Json.Linq;
  2using PushSDK.Classes;
  3using System;
  4using System.Collections.Generic;
  5using System.Threading.Tasks;
  6using System.Net.Http;
  7using Newtonsoft.Json;
  8using System.Linq;
  9using System.Net;
 10using System.IO;
 11using System.Diagnostics;
 12
 13namespace PushSDK
 14{
 15    public class TagsService
 16    {
 17        private readonly string _appId;
 18
 19        private readonly HttpClient _httpClient = new HttpClient();
 20
 21        public event EventHandler<CustomEventArgs<List<KeyValuePair<string, string>>>> OnSendingComplete;
 22        public event EventHandler<CustomEventArgs<string>> OnError;
 23
 24        public TagsService(string appId)
 25        {
 26            _appId = appId;
 27            //_webClient.UploadStringCompleted += UploadStringCompleted;
 28        }
 29
 30        /// <summary>
 31        /// Sending tag to server
 32        /// </summary>
 33        /// <param name="tagList">Tags list</param>
 34        public async void SendRequest(List<KeyValuePair<string, object>> tagList)
 35        {
 36            var webRequest = (HttpWebRequest)HttpWebRequest.Create(Constants.TagsUrl);
 37
 38            webRequest.Method = "POST";
 39            webRequest.ContentType = "application/x-www-form-urlencoded";
 40            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(BuildRequest(tagList)));
 41
 42            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);
 43
 44            // Write the channel URI to the request stream.
 45            Stream requestStream = await webRequest.GetRequestStreamAsync();
 46            requestStream.Write(requestBytes, 0, requestBytes.Length);
 47
 48            try
 49            {
 50                // Get the response from the server.
 51                WebResponse response = await webRequest.GetResponseAsync();
 52                StreamReader requestReader = new StreamReader(response.GetResponseStream());
 53                String webResponse = requestReader.ReadToEnd();
 54
 55                string errorMessage = String.Empty;
 56
 57                Debug.WriteLine("Response: " + webResponse);
 58
 59                JObject jRoot = JObject.Parse(webResponse);
 60                int code = JsonHelpers.GetStatusCode(jRoot);
 61                if (code == 200 || code == 103)
 62                {
 63                    UploadStringCompleted(webResponse);
 64                }
 65                else
 66                    errorMessage = JsonHelpers.GetStatusMessage(jRoot);
 67
 68                if (!String.IsNullOrEmpty(errorMessage) && OnError != null)
 69                {
 70                    Debug.WriteLine("Error: " + errorMessage);
 71                    OnError(this, new CustomEventArgs<string> { Result = errorMessage });
 72                }
 73            }
 74
 75            catch (Exception ex)
 76            {
 77                OnError(this, new CustomEventArgs<string> { Result = ex.Message });
 78            }
 79        }
 80
 81        /// <summary>
 82        /// Sending tag to server
 83        /// </summary>
 84        /// <param name="jTagList">tag format: [tagKey:tagValue]</param>
 85        public async void SendRequest(string jTagList)
 86        {
 87            var webRequest = (HttpWebRequest)HttpWebRequest.Create(Constants.TagsUrl);
 88
 89            webRequest.Method = "POST";
 90            webRequest.ContentType = "application/x-www-form-urlencoded";
 91            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(BuildRequest(jTagList)));
 92
 93            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);
 94
 95            // Write the channel URI to the request stream.
 96            Stream requestStream = await webRequest.GetRequestStreamAsync();
 97            requestStream.Write(requestBytes, 0, requestBytes.Length);
 98
 99            try
100            {
101                // Get the response from the server.
102                WebResponse response = await webRequest.GetResponseAsync();
103                StreamReader requestReader = new StreamReader(response.GetResponseStream());
104                String webResponse = requestReader.ReadToEnd();
105
106                string errorMessage = String.Empty;
107
108                Debug.WriteLine("Response: " + webResponse);
109
110                JObject jRoot = JObject.Parse(webResponse);
111                int code = JsonHelpers.GetStatusCode(jRoot);
112                if (code == 200 || code == 103)
113                {
114                    UploadStringCompleted(webResponse);
115                }
116                else
117                    errorMessage = JsonHelpers.GetStatusMessage(jRoot);
118
119                if (!String.IsNullOrEmpty(errorMessage) && OnError != null)
120                {
121                    Debug.WriteLine("Error: " + errorMessage);
122                    OnError(this, new CustomEventArgs<string> { Result = errorMessage });
123                }
124            }
125
126            catch (Exception ex)
127            {
128                OnError(this, new CustomEventArgs<string> { Result = ex.Message });
129            }
130         
131        }
132
133        private string BuildRequest(IEnumerable<KeyValuePair<string, object>> tagList)
134        {
135            JObject tags = new JObject();
136            foreach (var tag in tagList)
137            {
138                tags.Add(new JProperty(tag.Key, tag.Value));
139            }
140            return BuildRequest(tags.ToString());
141        }
142
143        private string BuildRequest(string tags)
144        {
145            return (new JObject(
146               new JProperty("request",
147                             new JObject(
148                                 new JProperty("application", _appId),
149                                 new JProperty("hwid", SDKHelpers.GetDeviceUniqueId()),
150                                 new JProperty("tags", JObject.Parse(tags)))))).ToString();
151        }
152
153        private void UploadStringCompleted(string responseBodyAsText)
154        {
155
156            JObject jRoot = JObject.Parse(responseBodyAsText);
157            if (JsonHelpers.GetStatusCode(jRoot) == 200)
158            {
159                var skippedTags = new List<KeyValuePair<string, string>>();
160
161                if (jRoot["response"].HasValues)
162                {
163                    JArray jItems = jRoot["response"]["skipped"] as JArray;
164
165                    skippedTags = jItems.Select(jItem => new KeyValuePair<string, string>(jItem.Value<string>("tag"), jItem.Value<string>("reason"))).ToList();
166                }
167
168                OnSendingComplete(this, new CustomEventArgs<List<KeyValuePair<string, string>>> { Result = skippedTags });
169            }
170            else
171                OnError(this, new CustomEventArgs<string> { Result = JsonHelpers.GetStatusMessage(jRoot) });
172        }
173    }
174    
175}