push-notifications-sdk /SDK Sample Projects/Win8/PushSDK/TagsService.cs

Language C# Lines 176
MD5 Hash 7c11423eb6630735badbb9aa50620192 Estimated Cost $3,146 (why?)
Repository https://github.com/doluyen/push-notifications-sdk.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
using Newtonsoft.Json.Linq;
using PushSDK.Classes;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using System.Linq;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace PushSDK
{
    public class TagsService
    {
        private readonly string _appId;

        private readonly HttpClient _httpClient = new HttpClient();

        public event EventHandler<CustomEventArgs<List<KeyValuePair<string, string>>>> OnSendingComplete;
        public event EventHandler<CustomEventArgs<string>> OnError;

        public TagsService(string appId)
        {
            _appId = appId;
            //_webClient.UploadStringCompleted += UploadStringCompleted;
        }

        /// <summary>
        /// Sending tag to server
        /// </summary>
        /// <param name="tagList">Tags list</param>
        public async void SendRequest(List<KeyValuePair<string, object>> tagList)
        {
            var webRequest = (HttpWebRequest)HttpWebRequest.Create(Constants.TagsUrl);

            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(BuildRequest(tagList)));

            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);

            // Write the channel URI to the request stream.
            Stream requestStream = await webRequest.GetRequestStreamAsync();
            requestStream.Write(requestBytes, 0, requestBytes.Length);

            try
            {
                // Get the response from the server.
                WebResponse response = await webRequest.GetResponseAsync();
                StreamReader requestReader = new StreamReader(response.GetResponseStream());
                String webResponse = requestReader.ReadToEnd();

                string errorMessage = String.Empty;

                Debug.WriteLine("Response: " + webResponse);

                JObject jRoot = JObject.Parse(webResponse);
                int code = JsonHelpers.GetStatusCode(jRoot);
                if (code == 200 || code == 103)
                {
                    UploadStringCompleted(webResponse);
                }
                else
                    errorMessage = JsonHelpers.GetStatusMessage(jRoot);

                if (!String.IsNullOrEmpty(errorMessage) && OnError != null)
                {
                    Debug.WriteLine("Error: " + errorMessage);
                    OnError(this, new CustomEventArgs<string> { Result = errorMessage });
                }
            }

            catch (Exception ex)
            {
                OnError(this, new CustomEventArgs<string> { Result = ex.Message });
            }
        }

        /// <summary>
        /// Sending tag to server
        /// </summary>
        /// <param name="jTagList">tag format: [tagKey:tagValue]</param>
        public async void SendRequest(string jTagList)
        {
            var webRequest = (HttpWebRequest)HttpWebRequest.Create(Constants.TagsUrl);

            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(BuildRequest(jTagList)));

            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);

            // Write the channel URI to the request stream.
            Stream requestStream = await webRequest.GetRequestStreamAsync();
            requestStream.Write(requestBytes, 0, requestBytes.Length);

            try
            {
                // Get the response from the server.
                WebResponse response = await webRequest.GetResponseAsync();
                StreamReader requestReader = new StreamReader(response.GetResponseStream());
                String webResponse = requestReader.ReadToEnd();

                string errorMessage = String.Empty;

                Debug.WriteLine("Response: " + webResponse);

                JObject jRoot = JObject.Parse(webResponse);
                int code = JsonHelpers.GetStatusCode(jRoot);
                if (code == 200 || code == 103)
                {
                    UploadStringCompleted(webResponse);
                }
                else
                    errorMessage = JsonHelpers.GetStatusMessage(jRoot);

                if (!String.IsNullOrEmpty(errorMessage) && OnError != null)
                {
                    Debug.WriteLine("Error: " + errorMessage);
                    OnError(this, new CustomEventArgs<string> { Result = errorMessage });
                }
            }

            catch (Exception ex)
            {
                OnError(this, new CustomEventArgs<string> { Result = ex.Message });
            }
         
        }

        private string BuildRequest(IEnumerable<KeyValuePair<string, object>> tagList)
        {
            JObject tags = new JObject();
            foreach (var tag in tagList)
            {
                tags.Add(new JProperty(tag.Key, tag.Value));
            }
            return BuildRequest(tags.ToString());
        }

        private string BuildRequest(string tags)
        {
            return (new JObject(
               new JProperty("request",
                             new JObject(
                                 new JProperty("application", _appId),
                                 new JProperty("hwid", SDKHelpers.GetDeviceUniqueId()),
                                 new JProperty("tags", JObject.Parse(tags)))))).ToString();
        }

        private void UploadStringCompleted(string responseBodyAsText)
        {

            JObject jRoot = JObject.Parse(responseBodyAsText);
            if (JsonHelpers.GetStatusCode(jRoot) == 200)
            {
                var skippedTags = new List<KeyValuePair<string, string>>();

                if (jRoot["response"].HasValues)
                {
                    JArray jItems = jRoot["response"]["skipped"] as JArray;

                    skippedTags = jItems.Select(jItem => new KeyValuePair<string, string>(jItem.Value<string>("tag"), jItem.Value<string>("reason"))).ToList();
                }

                OnSendingComplete(this, new CustomEventArgs<List<KeyValuePair<string, string>>> { Result = skippedTags });
            }
            else
                OnError(this, new CustomEventArgs<string> { Result = JsonHelpers.GetStatusMessage(jRoot) });
        }
    }
    
}
Back to Top