예제 #1
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     push            = new PushClient(txtServerAddress.Text.Trim(), 8000, DATA_MODE.ASYNC, "Danis_C#_Test");
     push.OnStatus  += this.OnStatus;
     push.OnRcvData += this.OnReceiveData;
     push.Connect();
 }
예제 #2
0
        private void Start( )
        {
            //Check to ensure everything's setup right
            PushClient.CheckDevice(Application.Context);
            PushClient.CheckManifest(Application.Context);

            PushClient.Register(Application.Context, PushHandlerBroadcastReceiver.SENDER_IDS);

            SetContentView(Resource.Layout.Auth);
            activityIsVisible = true;

            MenuId    = Resource.Menu.EmptyMenu;
            LegacyBar = FindViewById <LegacyBar.Library.Bar.LegacyBar>(Resource.Id.ActionBar);
            LegacyBar.SetHomeLogo(Resource.Drawable.Icon);

            txtLicense  = FindViewById <EditText>(Resource.Id.txtLicense);
            txtPassword = FindViewById <EditText>(Resource.Id.txtPassword);
            lblError    = FindViewById <TextView>(Resource.Id.lblError);
            btnLogin    = FindViewById <Button>(Resource.Id.btnLogin);

            txtLicense.Text = GetSharedPreferences(Application.Context.PackageName, FileCreationMode.Private).GetString("License", String.Empty);

            var encryptedPassword = GetSharedPreferences(Application.Context.PackageName, FileCreationMode.Private).GetString("Password", null);

            txtPassword.Text = encryptedPassword != null
                                                                   ? Crypto.DecryptStringAES(encryptedPassword, SharedSecret)
                                                                   : String.Empty;

            lblError.Text   = String.Empty;
            btnLogin.Click += btnLogin_Click;

            LegacyBar.ProgressBarVisibility = ViewStates.Visible;
            ThreadPool.QueueUserWorkItem(o => GetAreas( ));
        }
예제 #3
0
        public MastodonClient(Credential credential, HttpClientHandler innerHandler = null) : base(credential, new OAuth2HttpClientHandler(innerHandler), RequestMode.FormUrlEncoded)
        {
            BinaryParameters = new List <string> {
                "avatar", "header", "file"
            };

            Account           = new AccountsClient(this);
            Apps              = new AppsClient(this);
            Auth              = new AuthClient(this);
            Blocks            = new BlocksClient(this);
            Conversations     = new ConversationsClient(this);
            CustomEmojis      = new CustomEmojisClient(this);
            DomainBlocks      = new DomainBlocksClient(this);
            Endorsements      = new EndorsementsClient(this);
            Favorites         = new FavoritesClient(this);
            Filters           = new FiltersClient(this);
            FollowRequests    = new FollowRequestsClient(this);
            Follows           = new FollowsClient(this);
            Instance          = new InstanceClient(this);
            Lists             = new ListsClient(this);
            Media             = new MediaClient(this);
            Notifications     = new NotificationsClient(this);
            Push              = new PushClient(this);
            Reports           = new ReportsClient(this);
            ScheduledStatuses = new ScheduledStatusesClient(this);
            SearchV1          = new SearchV1Client(this);
            SearchV2          = new SearchV2Client(this);
            Statuses          = new StatusesClient(this);
            Streaming         = new StreamingClient(this);
            Suggestions       = new SuggestionsClient(this);
            Timelines         = new TimelinesClient(this);
        }
예제 #4
0
        public async Task <IActionResult> SendPushReminders()
        {
            try
            {
                var reminders = await _notificationService.GetActivePushReminders();

                if (reminders.Count > 0)
                {
                    var client = new PushClient();

                    var notificationList = new List <PushMessage>();

                    foreach (var reminder in reminders)
                    {
                        notificationList.Add(new PushMessage(reminder.Token, title: "Reminder", body: reminder.Message));
                    }
                    try
                    {
                        var response = await client.PublishMultiple(notificationList);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        return(Json(new { sent = reminders.Count, error = ex.Message }));
                    }
                }

                return(Json(new { sent = reminders.Count, error = "" }));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(BadRequest());
            }
        }
예제 #5
0
        public async Task AddUserRegistrationOrganizationAsync(IEnumerable <string> deviceIds, string organizationId)
        {
            if (!deviceIds.Any())
            {
                return;
            }

            var tokenStateResponse = await HandleTokenStateAsync();

            if (!tokenStateResponse)
            {
                return;
            }

            var requestModel = new PushUpdateRequestModel(deviceIds, organizationId);
            var message      = new TokenHttpRequestMessage(requestModel, AccessToken)
            {
                Method     = HttpMethod.Put,
                RequestUri = new Uri(string.Concat(PushClient.BaseAddress, "/push/add-organization"))
            };

            try
            {
                await PushClient.SendAsync(message);
            }
            catch (Exception e)
            {
                _logger.LogError(12337, e, "Unable to add user org push registration.");
            }
        }
예제 #6
0
 private async Task DisablePush(PushClient helper, Uri uri)
 {
     LoadingText = "Disabling...";
     await Utils.SuppressAsync <TimeoutException>(async() => {
         await AsyncTasks.Within2(helper.Deregister(uri), TimeSpan.FromSeconds(5));
     });
 }
        public async Task Publish_ShouldThrowArgumentExceptionWhenExpoTokenIsInvalid(string token)
        {
            var pushClient = new PushClient();
            var message    = new PushMessage(token);

            await Assert.ThrowsAsync <ArgumentException>(async() => await pushClient.Publish(message));
        }
예제 #8
0
        public async Task CreateOrUpdateRegistrationAsync(string pushToken, string deviceId, string userId,
                                                          string identifier, DeviceType type)
        {
            var tokenStateResponse = await HandleTokenStateAsync();

            if (!tokenStateResponse)
            {
                return;
            }

            var requestModel = new PushRegistrationRequestModel
            {
                DeviceId   = deviceId,
                Identifier = identifier,
                PushToken  = pushToken,
                Type       = type,
                UserId     = userId
            };

            var message = new TokenHttpRequestMessage(requestModel, AccessToken)
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(string.Concat(PushClient.BaseAddress, "/push/register"))
            };

            try
            {
                await PushClient.SendAsync(message);
            }
            catch (Exception e)
            {
                _logger.LogError(12335, e, "Unable to create push registration.");
            }
        }
예제 #9
0
        public static bool PushMessage(PushMessageViewModel message, IList <string> phones)
        {
            var result      = false;
            var pushMessage = ConverToMessageModel(message);

            pushMessage.Type         = MessageType.AppNotification;
            pushMessage.PhoneNumbers = phones;

            try
            {
                using (var client = new PushClient())
                {
                    var pushResult = client.PushMessages(pushMessage);
                    if (pushResult != null)
                    {
                        if (!string.IsNullOrEmpty(pushResult.ErrorMessage))
                        {
                            logger.Log(Level.Error, pushResult.ErrorMessage, "Error occurred in PushMessage");
                        }
                        else
                        {
                            result = pushResult.Result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Log(Level.Error, ex, "Error occurred in PushMessage");
            }

            return(result);
        }
예제 #10
0
        public MastodonClient(string domain) : base($"https://{domain}", AuthMode.OAuth2, RequestMode.FormUrlEncoded)
        {
            Domain           = domain;
            BinaryParameters = new List <string> {
                "avatar", "header", "file"
            };

            Account        = new AccountsClient(this);
            Apps           = new AppsClient(this);
            Auth           = new AuthClient(this);
            Blocks         = new BlocksClient(this);
            CustomEmojis   = new CustomEmojisClient(this);
            DomainBlocks   = new DomainBlocksClient(this);
            Endorsements   = new EndorsementsClient(this);
            Favorites      = new FavoritesClient(this);
            Filters        = new FiltersClient(this);
            FollowRequests = new FollowRequestsClient(this);
            Follows        = new FollowsClient(this);
            Instance       = new InstanceClient(this);
            Lists          = new ListsClient(this);
            Media          = new MediaClient(this);
            Notifications  = new NotificationsClient(this);
            Push           = new PushClient(this);
            Reports        = new ReportsClient(this);
            SearchV1       = new SearchV1Client(this);
            SearchV2       = new SearchV2Client(this);
            Statuses       = new StatusesClient(this);
            Streaming      = new StreamingClient(this);
            Suggestions    = new SuggestionsClient(this);
            Timelines      = new TimelinesClient(this);
        }
예제 #11
0
        void updateView()
        {
            //Get the stored latest registration id
            var registrationId = PushClient.GetRegistrationId(this);

            //If it's empty, we need to register
            if (string.IsNullOrEmpty(registrationId))
            {
                registered = false;
                this.textRegistrationStatus.Text = "Registered: No";
                this.textRegistrationId.Text     = "Id: N/A";
                this.buttonRegister.Text         = "Register...";

                Log.Info("C2DM-Sharp", "Not registered...");
            }
            else
            {
                registered = true;
                this.textRegistrationStatus.Text = "Registered: Yes";
                this.textRegistrationId.Text     = "Id: " + registrationId;
                this.buttonRegister.Text         = "Unregister...";

                Log.Info("C2DM-Sharp", "Already Registered: " + registrationId);
            }

            var prefs = GetSharedPreferences("c2dm.client.sample", FileCreationMode.Private);

            this.textLastMsg.Text = "Last Msg: " + prefs.GetString("last_msg", "N/A");

            //Enable the button as it was normally disabled
            this.buttonRegister.Enabled = true;
        }
예제 #12
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            textRegistrationStatus = FindViewById <TextView>(Resource.Id.textRegistrationStatus);
            textRegistrationId     = FindViewById <TextView>(Resource.Id.textRegistrationId);
            textLastMsg            = FindViewById <TextView>(Resource.Id.textLastMessage);
            buttonRegister         = FindViewById <Button>(Resource.Id.buttonRegister);

            Log.Info("C2DM-Sharp-UI", "Hello World");

            this.buttonRegister.Click += delegate
            {
                if (!registered)
                {
                    Log.Info("C2DM-Sharp", "Registering...");
                    PushClient.Register(this, senderIdEmail);
                }
                else
                {
                    Log.Info("C2DM-Sharp", "Unregistering...");
                    PushClient.UnRegister(this);
                }

                RunOnUiThread(() =>
                {
                    //Disable the button so that we can't click it again
                    //until we get back to the activity from a notification
                    this.buttonRegister.Enabled = false;
                });
            };
        }
        public async Task Publish_ShouldThrowPushServerExceptionWhenHttpClientReturnsAnError()
        {
            var handler    = new TestHandler((message, token) => throw new InvalidOperationException());
            var httpClient = new HttpClient(handler);
            var pushClient = new PushClient(httpClient: httpClient);

            await Assert.ThrowsAsync <PushServerException>(async() => await pushClient.Publish(new PushMessage(Token)));
        }
예제 #14
0
 private async Task TryEnablePush(PushClient helper, Uri uri, bool silent = false)
 {
     if (!silent)
     {
         LoadingText = "Enabling...";
     }
     await AsyncTasks.Within2(helper.Register(uri), TimeSpan.FromSeconds(10));
 }
예제 #15
0
        private Task WithClient(MusicEndpoint endpoint, Func <PushClient, Task> f)
        {
            var client = new PushClient(endpoint);
            var task   = f(client);
            var t      = task.ContinueWith(t2 => client.Dispose());

            return(task);
        }
        public async Task Publish_ShouldThrowHttpRequestExceptionWhenStatusCodeIsNot200()
        {
            var handler    = new TestHandler((message, token) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden)));
            var httpClient = new HttpClient(handler);
            var pushClient = new PushClient(httpClient: httpClient);

            await Assert.ThrowsAsync <HttpRequestException>(async() => await pushClient.Publish(new PushMessage(Token)));
        }
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);

            if (pushClient == null)
            {
                pushClient = this.Configuration.GetPushClient();
            }
        }
예제 #18
0
        public static void SetPushClient(this HttpConfiguration config, PushClient client)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            config.Properties[PushClientKey] = client;
        }
예제 #19
0
        /// <summary>
        /// 带两个参数的构造函数,该状态下,ApnsProduction默认为true
        /// </summary>
        /// <param name="app_key">Portal上产生的app_key</param>
        /// <param name="masterSecret">你的API MasterSecret</param>
        public JPushClient(String app_key, String masterSecret)
        {
            HashSet <DeviceEnum> devices = new HashSet <DeviceEnum>();

            devices.Add(DeviceEnum.IOS);
            devices.Add(DeviceEnum.Android);
            _pushClient   = new PushClient(masterSecret, app_key, MessageParams.NO_TIME_TO_LIVE, null, true);
            _reportClient = new ReportClient(app_key, masterSecret);
        }
예제 #20
0
 private static async void SendPush(ApiServices service, IPushMessage message)
 {
     try
     {
         PushClient cliente = new PushClient(service);
         await cliente.SendAsync(message);
     }
     catch (System.Exception ex)
     {
     }
 }
예제 #21
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            if (!PushClient.IsRegistered(this))
            {
                PushClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
            }

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new GroeneTeam.App());
        }
        public void Push_three_messages_to_a_chat()
        {
            var pushClient = new PushClient(_apiToken);
            var tasks = new List<Task>();

            for (var i = 0; i < 3; i++)
            {
                pushClient.PushToChatAsync("Hello from integration test #" + i, "int_test");
            }

            Task.WaitAll(tasks.ToArray());
        }
 public void Push_three_messages_to_a_team_room()
 {
     var pushClient = new PushClient(_apiToken);
     var tasks = new List<Task>();
     
     for (var i = 0; i < 3; i++)
     {
         pushClient.PushToTeamAsync("PushClientTest", "*****@*****.**", "Tester", "Test from integration test. #" + i);
     }
     
     Task.WaitAll(tasks.ToArray());
 }
예제 #24
0
        static void Main(string[] args)
        {
            _ResetEvent = new ManualResetEvent(false);

            Console.WriteLine("-------------------------------------------------------");
            Console.WriteLine(" THE DUMMY PROGRAMMER - TEST PUSH NOTIFICATIONS CLIENT ");
            Console.WriteLine("-------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine($"Insert your client ID (How do you identify yourself, 0-{int.MaxValue})");

            bool   IsValidClientID = false;
            string ClientID        = string.Empty;

            while (!IsValidClientID)
            {
                ClientID        = Console.ReadLine();
                IsValidClientID = System.Text.RegularExpressions.Regex.Match(ClientID, @"\d{1,4}").Success;
                if (!IsValidClientID)
                {
                    Console.WriteLine("Invalid client number");
                }
            }

            AuthenticationToken <int> AuthToken = new AuthenticationToken <int>(int.Parse(ClientID), DateTime.Now, DateTime.Now.AddHours(24), null);

            Console.WriteLine("Starting push notification client...");
            _PushClient = new PushClient <int>();
            _PushClient.RegisterClientStarted += _PushClient_RegisterClientStarted;
            _PushClient.RegisterClientEnded   += _PushClient_RegisterClientEnded;
            _PushClient.PushMessageReceived   += _PushClient_PushMessageReceived;
            _PushClient.ConnectionClosed      += _PushClient_ConnectionClosed;
            _PushClient.ConnectAsync(AuthToken);

            _ResetEvent.WaitOne();

            if (!_RegistrationOk)
            {
                Console.WriteLine("Press a key to exit...");
                Console.ReadKey();
                return;
            }

            while (true)
            {
                Console.WriteLine("Waiting for some push message... type EXIT to close this program");
                string Command = Console.ReadLine();

                if (Command == "EXIT")
                {
                    break;
                }
            }
        }
예제 #25
0
        public void Push_three_messages_to_a_chat()
        {
            var pushClient = new PushClient(_apiToken);
            var tasks      = new List <Task>();

            for (var i = 0; i < 3; i++)
            {
                pushClient.PushToChatAsync("Hello from integration test #" + i, "int_test");
            }

            Task.WaitAll(tasks.ToArray());
        }
예제 #26
0
        public void Push_three_messages_to_a_team_room()
        {
            var pushClient = new PushClient(_apiToken);
            var tasks      = new List <Task>();

            for (var i = 0; i < 3; i++)
            {
                pushClient.PushToTeamAsync("PushClientTest", "*****@*****.**", "Tester", "Test from integration test. #" + i);
            }

            Task.WaitAll(tasks.ToArray());
        }
예제 #27
0
        public async Task SendNotificationFromTask(byte[] data)
        {
            try {
                string       strData       = System.Text.Encoding.UTF8.GetString(data);
                Notification notification  = JsonConvert.DeserializeObject <Notification>(strData);
                var          subscriptions = await PushSubscriptionsRepository.GetAllAsync();

                await subscriptions.ForEachAsync(async (subscription) => {
                    await PushClient.SendNotificationsAsync(subscription, notification);
                });
            } catch (Exception ex) {
                _logger.LogError($"{ex.Message}; {ex.StackTrace}");
            }
        }
예제 #28
0
        /// <summary>
        /// Used to disconnect from Push Service
        /// </summary>
        /// <returns>0 for success, other values for failure</returns>
        public int PushDisconnect()
        {
            Console.WriteLine("Push Disconnect");
            try
            {
                PushClient.PushServiceDisconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e.ToString());
                return(-1);
            }

            return(0);
        }
        private async Task SendExpoMessage(string token, string title, string message)
        {
            try
            {
                var client = new PushClient();

                var notification = new PushMessage(token, title: title, body: message);

                await client.Publish(notification);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task Publish_ShouldThrowPushServerExceptionWhenResponseHasNoData()
        {
            var handler = new TestHandler((message, token) => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    "{\r\n  \"data\": null\r\n}",
                    Encoding.UTF8, "application/json")
            }));
            var httpClient = new HttpClient(handler);
            var pushClient = new PushClient(httpClient: httpClient);

            var ex = await Record.ExceptionAsync(async() => await pushClient.Publish(new PushMessage(Token)));

            Assert.Equal("Invalid server response.", ex.Message);
        }
        public async Task Publish_ShouldThrowPushServerExceptionWhenResponseHasAMismatchedAmoundOfData()
        {
            var handler = new TestHandler((message, token) => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    "{\r\n  \"data\": [\r\n    {\"status\": \"ok\"},\r\n    {\"status\": \"ok\"}\r\n  ]\r\n}",
                    Encoding.UTF8, "application/json")
            }));
            var httpClient = new HttpClient(handler);
            var pushClient = new PushClient(httpClient: httpClient);

            var ex = await Record.ExceptionAsync(async() => await pushClient.Publish(new PushMessage(Token)));

            Assert.Equal("Mismatched response length. Expected 1, but only 2 received.", ex.Message);
        }
        public async Task Publish_ShouldReturnOkResponse()
        {
            var handler = new TestHandler((message, token) => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(
                    "{\r\n  \"data\": [\r\n    {\"status\": \"ok\"}\r\n  ]\r\n}",
                    Encoding.UTF8, "application/json")
            }));
            var httpClient = new HttpClient(handler);
            var pushClient = new PushClient(httpClient: httpClient);

            var response = await pushClient.Publish(new PushMessage(Token));

            Assert.Equal(PushResponseStatuses.Ok, response.Status);
        }
 public when_pushing_integration_to_api()
 {
     _push = PushClient.PushWithBasic(_url, _api, _key, _keyValue, _username, _password);
     
 }