示例#1
0
        public object Post(PostMessageRequest Request)
        {
            Message message = Request.GetEntity(((NHibernate.ISession)base.Request.Items["hibernateSession"]));

            message.FromUser = GetAuthenticatedUser(((NHibernate.ISession)base.Request.Items["hibernateSession"]));

            message.Save(((NHibernate.ISession)base.Request.Items["hibernateSession"]));

            message.Match.Save(((NHibernate.ISession)base.Request.Items["hibernateSession"]));

            User user = message.ToUser;

            List <DeviceToken> deviceToken = new BaseRepository <DeviceToken>(((NHibernate.ISession)base.Request.Items["hibernateSession"])).List(x =>
                                                                                                                                                  x.User.Id == user.Id).ToList();

            if (deviceToken != null && deviceToken.Any())
            {
                try
                {
                    PushHelper.SendNotification(deviceToken, "Nova mensagem de " + message.FromUser.Name, "message");
                }
                catch {
                }
            }

            return(new BaseResponse());
        }
示例#2
0
        public void RegisterAsyncUnregisterTemplateAsync()
        {
            var mobileClient = this.GetClient();
            var push         = mobileClient.GetPush();
            var template     = PushHelper.GetTemplateRegistrationForToast();

            PushHelper.ValidateTemplateRegistrationBeforeRegister(template);
            push.RegisterAsync(template).Wait();
            var registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(template.ChannelUri).Result;

            Assert.AreEqual(registrations.Count(), 1, "1 registration should exist after RegisterNativeAsync");
            var registrationAfter = registrations.First() as TemplateRegistration;

            Assert.IsNotNull(registrationAfter, "List and Deserialization of a TemplateRegistration after successful registration should have a value.");
            Assert.AreEqual(
                registrationAfter.RegistrationId,
                push.RegistrationManager.LocalStorageManager.GetRegistration(template.Name).RegistrationId,
                "Local storage should have the same RegistrationId as the one returned from service");

            PushHelper.ValidateTemplateRegistrationAfterRegister(registrationAfter, mobileClient.applicationInstallationId);

            push.UnregisterTemplateAsync(template.Name).Wait();
            registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(template.ChannelUri).Result;
            Assert.AreEqual(registrations.Count(), 0, "0 registrations should exist in service after UnregisterTemplateAsync");
            Assert.IsNull(
                push.RegistrationManager.LocalStorageManager.GetRegistration(template.Name),
                "Local storage should not contain a native registration after UnregisterTemplateAsync.");
        }
示例#3
0
        /// <summary>
        /// 发送通知
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="da">不在同一个事务中,查询不到id</param>
        /// <returns></returns>
        private bool PushMessage(int sid, TASM_SUPPORT_Da da)
        {
            if (Entites.AppConfig.IsPush == false)
            {
                Logger.LogInformation("不发送消息通知,若需要请打开配置文件");
                return(true);
            }
            try
            {
                var model = da.SelectBySid4Push(sid);

                string title = $"您有一份新的任务,问题管理表编号[{model.CODE}],请登录售后管理系统查看详情。";

                StringBuilder content = new StringBuilder();

                content.AppendLine($"项目名称:{model.PROJECTNAME}[{model.PROJECTCODE}]");
                content.AppendLine($"问题机型:{model.MACHINENAME}[{model.MACHINESERIAL}]");

                content.AppendLine($"问题类型:{ Enum.GetName(typeof(SupportProblemType), model.TYPE)}");

                content.AppendLine($"当前处理人:{model.CONDUCTORNAME}");

                content.AppendLine($"流程节点:{Enum.GetName(typeof(SupportendPoint), model.STATUS).Replace('_', '>')}");

                content.AppendLine($"问题描述:{model.CONTENT}");

                PushHelper.PushWeChat(model.ConductorWorkId, title, content.ToString());
                return(true);
            }
            catch (Exception e)
            {
                Logger.LogInformation("" + e);
                return(false);
            }
        }
示例#4
0
        public ActionResult Index()
        {
            var result = string.Empty;
            //try
            //{
            //    Console.OutputEncoding = Encoding.GetEncoding(936);
            //    Environment.SetEnvironmentVariable("gexin_pushList_needDetails", "true");
            //    result = PushHelper.PushMessageToApp();
            //}
            //catch (Exception ex)
            //{
            //    result = ex.Message;
            //}

            string     clientId = "557e5625f84c82517457c43024b03b0c";
            PushHelper message  = new PushHelper(new List <string>()
            {
                clientId
            });

            var beginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var endTime   = DateTime.Now.AddHours(2).ToString("yyyy-MM-dd HH:mm:ss");
            //string msg1 = message.PushMessageToSingleByNotificationTemplate("XXX - 单用户", "您有新的任务,点击查看!", "", "", "", beginTime, endTime);
            //string msg2 = message.PushMessageToListByNotificationTemplate("XXX  - 多用户", "您有新的任务,点击查看!", "", "", "", beginTime, endTime);
            string msg3 = message.PushTemplate(Enum_Push.All, "XXX  - APP应用", "您有新的任务,点击查看啊!", "", "", "{id:1}", beginTime, endTime);

            //解析输出结果
            //{"taskId":"OSS-0420_ZiFBb3Sx7A7Pz7YWMwJdD9","result":"ok","status":"successed_online"} 在线状态
            //{"taskId":"OSS-0420_2qtgpolflJAuYGSiGTfQ04","result":"ok","status":"successed_offline"} 离线状态

            return(Content(msg3));

            //return Content(msg1 + "</br>" + msg2 + "</br>" + msg3 + "</br>");
        }
示例#5
0
        public ActionResult Join(int id = 0)
        {
            using (var galleristContext = new GalleristComponentsDbContext())
            {
                using (var identityContext = new ApplicationDbContext())
                {
                    var gameResponse = GameManager.GetGame(id, galleristContext);

                    if (gameResponse.Success)
                    {
                        gameResponse.Game.Players.Add(new Player
                        {
                            UserId   = identityContext.Users.First(m => m.UserName == User.Identity.Name).Id,
                            UserName = User.Identity.Name
                        });

                        PushHelper singleton = PushHelper.GetPushEngine();
                        singleton.RefreshGameList(gameResponse.Game.Players.Where(m => m.UserName != User.Identity.Name).Select(p => p.UserName).ToList());

                        ViewBag.userName = User.Identity.Name;
                        galleristContext.SaveChanges();
                        return(Redirect("/Game/List"));
                    }
                    else
                    {
                        ViewBag.Message = gameResponse.Message;
                        ViewBag.Title   = gameResponse.Title;
                        return(View("GameError"));
                    }
                }
            }
        }
示例#6
0
        public void SendPush(long docID, long patID, bool sendtoPatient, bool sendtoDoctor, string message)
        {
            try
            {
                //,long patID,bool sendtoPatient, bool sendtoDoctor

                //SendPush
                pushModel pm = new pushModel();
                pm.PPushTitle    = "Consultation Request";
                pm.PPushMessage  = "";
                pm.DPushTitle    = "Consultation Request";
                pm.DPushMessage  = message;
                pm.PPushMessage  = message;
                pm.sendtoDoctor  = sendtoDoctor;
                pm.sendtoPatient = sendtoPatient;
                pm.doctorID      = docID;
                pm.patientID     = patID;

                PushHelper ph = new PushHelper();
                ph.sendPush(pm);
            }
            catch (Exception ex)
            {
                //ThrowError(ex, "Err in SendPush in Appointment Controller line # 169");
            }
        }
示例#7
0
        public string System()
        {
            ApiResult result = new ApiResult();

            try
            {
                string clientId = "557e5625f84c82517457c43024b03b0c";
                //string clientId = "54f3c1dc7795e813a8e0cdb039becb6f";
                PushHelper message = new PushHelper(new List <string>()
                {
                    clientId
                });


                var article = db.Find <Article>(x => x.Status == Enum_Status.Approved && x.ArticlePower == Enum_ArticlePower.Public);
                var num     = new Random().Next(0, article.Count);

                var    beginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var    endTime   = DateTime.Now.AddHours(5).ToString("yyyy-MM-dd HH:mm:ss");
                string msg1      = message.PushTemplate(Enum_Push.Single, "微篇文章推荐啦", article[num].Title, "", "", "0|" + article[num].ID, beginTime, endTime);
                //string msg2 = message.PushTemplate(Enum_Push.Multiple, "用户", "您有新的任务,点击查看!", "", "", "", beginTime, endTime);
                //string msg3 = message.PushTemplate(Enum_Push.All, "XXX  - APP应用", "您有新的任务,点击查看啊!", "", "", "{id:1}", beginTime, endTime);
                result.message = msg1;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("Api_UserLog_Edit" + ex.Message);
                result.message = ex.Message;
            }
            return(JsonConvert.SerializeObject(result));
        }
示例#8
0
        public string ALL()
        {
            ApiResult result = new ApiResult();

            try
            {
                var title = ZNRequest.GetString("Title");
                var text  = ZNRequest.GetString("Text");

                string     clientId = "557e5625f84c82517457c43024b03b0c";
                PushHelper message  = new PushHelper(new List <string>()
                {
                    clientId
                });

                var beginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var endTime   = DateTime.Now.AddHours(2).ToString("yyyy-MM-dd HH:mm:ss");
                //string msg1 = message.PushMessageToSingleByNotificationTemplate("XXX - 单用户", "您有新的任务,点击查看!", "", "", "", beginTime, endTime);
                //string msg2 = message.PushMessageToListByNotificationTemplate("XXX  - 多用户", "您有新的任务,点击查看!", "", "", "", beginTime, endTime);
                string msg3 = message.PushTemplate(Enum_Push.All, "XXX  - APP应用", "您有新的任务,点击查看啊!", "", "", "{id:1}", beginTime, endTime);
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("Api_UserLog_Edit" + ex.Message);
                result.message = ex.Message;
            }
            return(JsonConvert.SerializeObject(result));
        }
示例#9
0
        public override async void OnNavigatedTo(Dictionary <string, object> parameters, NavigationMode mode)
        {
            if (CurrentUser == null && AppSettings.AccessToken != null && !AppSettings.AccessToken.HasExpired)
            {
                LoadCurrentUser();
                ServiceLocator.LongPollHandler.Start();
                if (AppSettings.EnableNotifications)
                {
                    PushHelper.Start();
                }
                ServiceLocator.UserPresenceService.SetUserOnline();

                if (((App)Application.Current).LaunchArgs != null)
                {
                    var args = ((App)Application.Current).LaunchArgs;
                    if (args != null && args.ContainsKey("uid"))
                    {
                        long uid = long.Parse(args["uid"]);

                        await Task.Delay(1);

                        Navigator.Content.Navigate(typeof(ChatView), new ConversationViewModel(uid));
                    }
                }

                try
                {
                    ServiceLocator.Vkontakte.Stats.TrackVisitor();
                }
                catch { }
            }
        }
示例#10
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //Notifier notifier = new Notifier();

            // It's important not to block UI threads. Since this is a background task, we do need
            // to block on the channel operations completing
            PushHelper.getInstance().RenewAll(false).AsTask().Wait();
        }
示例#11
0
 public void Push(Vector2 direction, float force, float speed = 750f)
 {
     this.isBeingPushed = true;
     if (this.pusher != null && !this.pusher.isFinished())
     {
         this.pusher.Add(direction, force);
         return;
     }
     this.pusher = new PushHelper(this, direction, force, speed, () => this.isBeingPushed = false);
 }
示例#12
0
        public ActionResult Start(int id = 0)
        {
            using (var galleristContext = new GalleristComponentsDbContext())
            {
                using (var identityContext = new ApplicationDbContext())
                {
                    //todo: set start time of game to datetime.now
                    var gameResponse = GameManager.GetGame(id, galleristContext);
                    var game         = gameResponse.Game;
                    game.StartTime = DateTime.Now;

                    if (game.IsStarted)
                    {
                        return(Redirect("~/Game/Play/" + gameResponse.Game.Id));
                    }

                    if (gameResponse.Success)
                    {
                        game.CreateRandomSetup();
                        game.StartGame();
                        galleristContext.SaveChanges();

                        //todo make a helper in email manager for this
                        //todo also use the user and url params for signalr ajax update of game list
                        var gameUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Game/Play/" + game.Id;
                        foreach (var player in game.Players)
                        {
                            var user = identityContext.Users.Single(m => m.Id == player.UserId);
                            if (!user.AllowsEmails || string.IsNullOrWhiteSpace(user.Email))
                            {
                                continue;
                            }

                            var emailTitle = user.UserName + ", your game has started!"; //todo: get full name of player. We don't have names in the system yet
                            var emailBody  = "A game that you are a member of has started. You can play it by visiting The Gallerist Online" +
                                             " and viewing your active games or by clicking the following link: " + gameUrl;

                            EmailManager.SendEmail(emailTitle, emailBody, new List <string> {
                                user.Email
                            });
                        }
                        //todo expand module to use signalr for all game list actions
                        PushHelper singleton = PushHelper.GetPushEngine();
                        singleton.UpdateMyGamesList(game.Players.Where(p => p.UserName != User.Identity.Name).Select(p => p.UserName).ToList(), gameUrl, game.Id);
                        return(Redirect("~/Game/Play/" + gameResponse.Game.Id));
                    }
                    else
                    {
                        ViewBag.Message = gameResponse.Message;
                        ViewBag.Title   = gameResponse.Title;
                        return(View("GameError"));
                    }
                }
            }
        }
示例#13
0
        private string BindWeChat(string OpenId, string SceneId)
        {
            StringBuilder str = new StringBuilder();
            TempBind      tb  = ve.TempBind.FirstOrDefault(q => q.SceneId == SceneId);

            if (tb != null)
            {
                WeChatUser tempwcu = ve.WeChatUser.FirstOrDefault(q => q.OpenId == OpenId && q.DeviceId == tb.DeviceId);
                if (tempwcu != null)
                {
                    if (tb.Token != tempwcu.Token)
                    {
                        tempwcu.Token = tb.Token;
                        ve.SaveChanges();
                    }
                    str.Append("你的帐号已绑定【" + tempwcu.DeviceName + "】该设备!");
                }
                else
                {
                    string     js  = "";
                    Message    ms  = null;
                    WeChatUser wcu = new WeChatUser();
                    wcu.OpenId     = OpenId;
                    wcu.Token      = tb.Token;
                    wcu.DeviceId   = tb.DeviceId;
                    wcu.DeviceName = tb.DeviceId;
                    wcu.State      = true;
                    wcu.UserPhone  = "";
                    wcu.HeadImg    = "../Img/ejq.jpg";
                    wcu.CreateDate = DateTime.Now;
                    ve.WeChatUser.Add(wcu);
                    ve.SaveChanges();
                    List <WeChatUser> list = ve.WeChatUser.Where(x => x.OpenId == OpenId).ToList();
                    foreach (var item in list)
                    {
                        if (item.DeviceId == wcu.DeviceId)
                        {
                            continue;
                        }
                        item.State = false;
                        ve.SaveChanges();
                    }
                    str.Append("\n请在下方回复“绑定设备+手机号”\n如:绑定设备13212345678\n即可激活设备!");
                    js = "{\"Title\":\"绑定推送\",\"Type\":6,\"OpenId\":\"" + OpenId + "\",\"Content\":\"\"}";
                    ms = new Message("e家亲", js.Replace("&", "@1").Replace("=", "@2").Replace("%", "@3"));
                    string  returnStr = PushHelper.PushMsg(tb.Token, jsonSerializer.Serialize(ms));
                    JObject json      = JObject.Parse(returnStr);
                    returnStr = json["ret_code"].ToString();
                }
            }
            return(str.ToString());
        }
示例#14
0
 public void EDelDevice(string deviceId)
 {
     if (Context.Session["OpenIdE"] != null)
     {
         string     OpenId = Context.Session["OpenIdE"].ToString();
         WeChatUser wcu    = ve.WeChatUser.FirstOrDefault(x => x.OpenId == OpenId && x.DeviceId == deviceId);
         string     js     = "{\"Title\":\"推送消息\",\"Type\":7,\"OpenId\":\"" + OpenId + "\",\"Content\":\"\"}";
         Message    ms     = new Message("e家亲", js);
         PushHelper.PushMsg(wcu.Token, jsonSerializer.Serialize(ms));
         ve.WeChatUser.Remove(wcu);
         ve.SaveChanges();
         Write("true");
     }
 }
示例#15
0
        /// <summary>
        /// Sends the notification asynchronous.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>Task.</returns>
        private async Task SendNotificationAsync(string message)
        {
            try
            {
                Services.Log.Info("Send notification without tag");
                var resultWns = await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01(message));

                var json = JsonConvert.SerializeObject(resultWns);
                Debug.WriteLine(json);
                Services.Log.Info(string.Format("Wns-{0}", json));
                var resultGcm = await Services.Push.SendAsync(PushHelper.GetGooglePushMessage(message));

                Services.Log.Info(string.Format("Gcm-{0}", JsonConvert.SerializeObject(resultGcm)));
                var resultMpns = await Services.Push.SendAsync(PushHelper.GetMPNSMessage(message));

                Services.Log.Info(string.Format("Mnps-{0}", JsonConvert.SerializeObject(resultMpns)));
                var resultApns = await Services.Push.SendAsync(PushHelper.GetApplePushMessage(message));

                Services.Log.Info(string.Format("Apns-{0}", JsonConvert.SerializeObject(resultApns)));

                await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01(message));

                await Services.Push.SendAsync(PushHelper.GetGooglePushMessage(message));

                await Services.Push.SendAsync(PushHelper.GetMPNSMessage(message));

                await Services.Push.SendAsync(PushHelper.GetApplePushMessage(message));

                Services.Log.Info("Send notification using someTag");
                const string otherMessage = "A second tag was added in AMS.";

                resultWns = await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastText01(otherMessage), NotificationHandler.SomeTag);

                Services.Log.Info(string.Format("Wns-{0}", JsonConvert.SerializeObject(resultWns)));
                resultGcm = await Services.Push.SendAsync(PushHelper.GetGooglePushMessage(otherMessage), NotificationHandler.SomeTag);

                Services.Log.Info(string.Format("Gcm-{0}", JsonConvert.SerializeObject(resultGcm)));
                resultMpns = await Services.Push.SendAsync(PushHelper.GetMPNSMessage(otherMessage), NotificationHandler.SomeTag);

                Services.Log.Info(string.Format("Mnps-{0}", JsonConvert.SerializeObject(resultMpns)));
                resultApns = await Services.Push.SendAsync(PushHelper.GetApplePushMessage(otherMessage), NotificationHandler.SomeTag);

                Services.Log.Info(string.Format("Apns-{0}", JsonConvert.SerializeObject(resultApns)));
            }
            catch (Exception exception)
            {
                Services.Log.Error(exception);
            }
        }
示例#16
0
        //接受视频消息  备注:"&"=>"@1"  "="=>"@2"  "%"=>"@3"
        public string VideoHandle(XmlDocument xmldoc)
        {
            string  responseContent = "";
            XmlNode ToUserName      = xmldoc.SelectSingleNode("/xml/ToUserName");
            XmlNode FromUserName    = xmldoc.SelectSingleNode("/xml/FromUserName");
            XmlNode MediaId         = xmldoc.SelectSingleNode("/xml/MediaId");
            XmlNode ThumbMediaId    = xmldoc.SelectSingleNode("/xml/ThumbMediaId");

            if (MediaId != null)
            {
                WeChatUser wcu = ve.WeChatUser.FirstOrDefault(q => q.OpenId == FromUserName.InnerText && q.State == true);
                if (wcu != null)
                {
                    string url = string.Format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", ToKen, MediaId.InnerText);
                    string img = string.Format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", ToKen, ThumbMediaId.InnerText);
                    string js  = "{\"url\":\"" + url + "\",\"img\":\"" + img + "\"}";
                    js = "{\"Title\":\"推送视频\",\"Type\":4,\"OpenId\":\"" + wcu.OpenId + "\",\"Content\":" + js + "}";
                    Message ms        = new Message("e家亲", js.Replace("&", "@1").Replace("=", "@2").Replace("%", "@3"));
                    string  returnStr = PushHelper.PushMsg(wcu.Token, jsonSerializer.Serialize(ms));
                    JObject json      = JObject.Parse(returnStr);
                    returnStr = json["ret_code"].ToString();
                    if (returnStr == "0")
                    {
                        responseContent = string.Format(ReplyType.Message_Text,
                                                        FromUserName.InnerText,
                                                        ToUserName.InnerText,
                                                        DateTime.Now.Ticks,
                                                        "你向设备【" + wcu.DeviceName + "】推送了一段视频!");
                    }
                    else
                    {
                        responseContent = string.Format(ReplyType.Message_Text,
                                                        FromUserName.InnerText,
                                                        ToUserName.InnerText,
                                                        DateTime.Now.Ticks,
                                                        "推送视频失败!/:bome");
                    }
                }
                else
                {
                    responseContent = string.Format(ReplyType.Message_Text,
                                                    FromUserName.InnerText,
                                                    ToUserName.InnerText,
                                                    DateTime.Now.Ticks,
                                                    "请先绑定设备!/::)");
                }
            }
            return(responseContent);
        }
示例#17
0
        public void InitialUnregisterAllAsync()
        {
            var channelUri = PushHelper.GetChannel();
            var push       = this.GetClient().GetPush();

            push.UnregisterAllAsync(channelUri).Wait();
            var registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(channelUri).Result;

            Assert.IsFalse(registrations.Any(), "Deleting all registrations for a channel should ensure no registrations are returned by List");

            channelUri = PushHelper.GetUpdatedChannel();
            push.UnregisterAllAsync(channelUri).Wait();
            registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(channelUri).Result;
            Assert.IsFalse(registrations.Any(), "Deleting all registrations for a channel should ensure no registrations are returned by List");
        }
示例#18
0
        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            if (!e.IsApplicationInstancePreserved)
            {
                if (Settings == null)
                {
                    Settings = IsolatedStorageSettings.ApplicationSettings;
                }
                if (PushHelper == null)
                {
                    PushHelper = new PushHelper();
                }
                if (GtalkClient == null)
                {
                    GtalkClient = new GoogleTalk();
                }

                if (RecentContacts == null)
                {
                    if (!Settings.Contains("recent"))
                    {
                        Settings["recent"] = RecentContacts = new ObservableCollection <Contact>();
                    }
                    RecentContacts = Settings["recent"] as ObservableCollection <Contact>;
                }

                if (!Settings.Contains("chatlog"))
                {
                    Settings["chatlog"] = new Dictionary <string, List <Message> >();
                }

                if (!Settings.Contains("unread"))
                {
                    Settings["unread"] = new Dictionary <string, int>();
                }

                if (GtalkHelper == null)
                {
                    GtalkHelper = new GoogleTalkHelper();
                }

                InitAnalytics();

                PushHelper.RegisterPushNotifications();
            }

            Roster.Load();
        }
示例#19
0
        public void Push(NotifyAppQueue entity)
        {
            var config = ConfigGet(entity.NotifyApplicationId);

            PushJson result = new PushJson();

            switch (entity.PushType)
            {
            case PushType.SoftToken:
            {
                result = PushHelper.SendBySoftTokens(config.Authtoken, config.Email, entity.AppId, entity.Title, entity.Body,
                                                     entity.Platforms,
                                                     entity.List);
                break;
            }

            case PushType.AppId:
            {
                result = PushHelper.SendByAppId(config.Authtoken, config.Email, entity.AppId, entity.Title, entity.Body);
                entity.QueueStatusCode = result.status;
                entity.QueueStatusMsg  = result.info;
                break;
            }

            case PushType.UserId:
            {
                result = PushHelper.SendByUserIds(config.Authtoken, config.Email, entity.AppId, entity.Title, entity.Body, entity.Platforms,
                                                  entity.List);
                break;
            }

            default:
            {
                break;
            }
            }
            entity.QueueStatusMsg  = result.info;
            entity.QueueStatusCode = result.status;
            if (result.status == "ok")
            {
                entity.QueueStatus = QueueStatus.Success;
            }
            else
            {
                entity.QueueStatus = QueueStatus.Fail;
            }
            QueueSave(entity);
        }
示例#20
0
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            Settings    = IsolatedStorageSettings.ApplicationSettings;
            PushHelper  = new PushHelper();
            GtalkClient = new GoogleTalk();

            if (!Settings.Contains("chatlog"))
            {
                Settings["chatlog"] = new Dictionary <string, List <Message> >();
            }
            if (!Settings.Contains("unread"))
            {
                Settings["unread"] = new Dictionary <string, int>();
            }
            if (!Settings.Contains("recent"))
            {
                Settings["recent"] = new ObservableCollection <Contact>();
            }

            GtalkHelper = new GoogleTalkHelper();
            Roster.Load();

            RecentContacts = Settings["recent"] as ObservableCollection <Contact>;

            PushHelper.RegisterPushNotifications();

            InitAnalytics();

            if (Settings.Contains("lastError"))
            {
                RootFrame.Dispatcher.BeginInvoke(() => {
                    var result = MessageBox.Show(
                        AppResources.CrashReport_Message,
                        AppResources.CrashReport_Title,
                        MessageBoxButton.OKCancel
                        );

                    if (result == MessageBoxResult.OK)
                    {
                        GtalkClient.CrashReport(Settings["lastError"] as string, success => Settings.Remove("lastError"), error => { });
                    }
                    else
                    {
                        Settings.Remove("lastError");
                    }
                });
            }
        }
示例#21
0
        /// <summary>
        /// The patch desserts schema.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <param name="patch">
        /// The patch.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <DessertsSchema> PatchDessertsSchema(string id, Delta <DessertsSchema> patch)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }
            if (patch == null)
            {
                throw new ArgumentNullException("patch");
            }
            var dto = await UpdateAsync(id, patch);

            await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastImageAndText03("Update:", dto.Title, dto.Subtitle, dto.Image));

            return(dto);
        }
示例#22
0
        //接受图片消息 备注:"&"=>"@1"  "="=>"@2"  "%"=>"@3"
        public string ImageHandle(XmlDocument xmldoc)
        {
            string  responseContent = "";
            XmlNode ToUserName      = xmldoc.SelectSingleNode("/xml/ToUserName");
            XmlNode FromUserName    = xmldoc.SelectSingleNode("/xml/FromUserName");
            XmlNode PicUrl          = xmldoc.SelectSingleNode("/xml/PicUrl");

            if (PicUrl != null)
            {
                WeChatUser wcu = ve.WeChatUser.FirstOrDefault(q => q.OpenId == FromUserName.InnerText && q.State == true);
                if (wcu != null)
                {
                    string  js        = "{\"Title\":\"推送图片\",\"Type\":2,\"OpenId\":\"" + wcu.OpenId + "\",\"Content\":\"" + PicUrl.InnerText + "\"}";
                    Message ms        = new Message("e家亲", js.Replace("&", "@1").Replace("=", "@2").Replace("%", "@3"));
                    string  returnStr = PushHelper.PushMsg(wcu.Token, jsonSerializer.Serialize(ms));
                    JObject json      = JObject.Parse(returnStr);
                    returnStr = json["ret_code"].ToString();
                    if (returnStr == "0")
                    {
                        responseContent = string.Format(ReplyType.Message_News_Main,
                                                        FromUserName.InnerText,
                                                        ToUserName.InnerText,
                                                        DateTime.Now.Ticks,
                                                        "1",
                                                        string.Format(ReplyType.Message_News_Item, "e家亲", "你向设备【" + wcu.DeviceName + "】推送了一张图片!",
                                                                      PicUrl.InnerText, ""));
                    }
                    else
                    {
                        responseContent = string.Format(ReplyType.Message_Text,
                                                        FromUserName.InnerText,
                                                        ToUserName.InnerText,
                                                        DateTime.Now.Ticks,
                                                        "推送图片失败!/:bome");
                    }
                }
                else
                {
                    responseContent = string.Format(ReplyType.Message_Text,
                                                    FromUserName.InnerText,
                                                    ToUserName.InnerText,
                                                    DateTime.Now.Ticks,
                                                    "请先绑定设备!/::)");
                }
            }
            return(responseContent);
        }
示例#23
0
        public void RegisterRefreshRegisterWithUpdatedChannel()
        {
            var mobileClient = this.GetClient();
            var push         = mobileClient.GetPush();
            var template     = PushHelper.GetTemplateRegistrationForToast();

            PushHelper.ValidateTemplateRegistrationBeforeRegister(template);
            push.RegisterAsync(template).Wait();
            var registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(template.ChannelUri).Result;

            Assert.AreEqual(registrations.Count(), 1, "1 registration should exist after RegisterNativeAsync");
            var registrationAfter = registrations.First() as TemplateRegistration;

            Assert.IsNotNull(registrationAfter, "List and Deserialization of a TemplateRegistration after successful registration should have a value.");
            Assert.AreEqual(
                registrationAfter.RegistrationId,
                push.RegistrationManager.LocalStorageManager.GetRegistration(template.Name).RegistrationId,
                "Local storage should have the same RegistrationId as the one returned from service");

            PushHelper.ValidateTemplateRegistrationAfterRegister(registrationAfter, mobileClient.applicationInstallationId);
            push.RegistrationManager.LocalStorageManager.IsRefreshNeeded = true;
            template.ChannelUri = PushHelper.GetUpdatedChannel();

            push.RegisterAsync(template).Wait();
            registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(template.ChannelUri).Result;
            Assert.AreEqual(registrations.Count(), 1, "1 registration should exist after RegisterNativeAsync");
            var registrationAfterUpdate = registrations.First() as TemplateRegistration;

            Assert.IsNotNull(registrationAfterUpdate, "List and Deserialization of a TemplateRegistration after successful registration should have a value.");
            Assert.AreEqual(
                registrationAfterUpdate.RegistrationId,
                push.RegistrationManager.LocalStorageManager.GetRegistration(template.Name).RegistrationId,
                "Local storage should have the same RegistrationId as the one returned from service");
            Assert.AreEqual(registrationAfter.RegistrationId, registrationAfterUpdate.RegistrationId, "Expected the same RegistrationId to be used even after the refresh");
            Assert.AreEqual(registrationAfterUpdate.ChannelUri, template.ChannelUri, "Expected updated channelUri after 2nd register");
            Assert.AreEqual(push.RegistrationManager.LocalStorageManager.ChannelUri, template.ChannelUri, "Expected local storage to be updaed to the new channelUri after 2nd register");

            Assert.AreEqual(push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(registrationAfter.ChannelUri).Result.Count(), 0, "Original channel should be gone from service");

            push.UnregisterTemplateAsync(template.Name).Wait();
            registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(template.ChannelUri).Result;
            Assert.AreEqual(registrations.Count(), 0, "0 registrations should exist in service after UnregisterTemplateAsync");
            Assert.IsNull(
                push.RegistrationManager.LocalStorageManager.GetRegistration(template.Name),
                "Local storage should not contain a native registration after UnregisterTemplateAsync.");
        }
示例#24
0
        public string Single()
        {
            ApiResult result = new ApiResult();

            try
            {
                //通知用户
                var number = ZNRequest.GetString("UserNumber");
                if (string.IsNullOrWhiteSpace(number))
                {
                    return("参数异常");
                }
                var user = db.Single <User>(x => x.Number == number);
                if (user == null)
                {
                    return("用户不存在");
                }
                if (user.ShowPush == 0)
                {
                    return("未启用消息推送");
                }
                if (string.IsNullOrWhiteSpace(user.ClientID))
                {
                    return("设备号不存在");
                }
                PushHelper message = new PushHelper(new List <string>()
                {
                    user.ClientID
                });

                var article = db.Find <Article>(x => x.Status == Enum_Status.Approved && x.ArticlePower == Enum_ArticlePower.Public);
                var num     = new Random().Next(0, article.Count);

                var beginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var endTime   = DateTime.Now.AddHours(5).ToString("yyyy-MM-dd HH:mm:ss");
                result.message = message.PushTemplate(Enum_Push.Single, "微篇文章推荐啦", article[num].Title, "", "", "0|" + article[num].ID, beginTime, endTime);
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLoger.Error("Api_UserLog_Edit" + ex.Message);
                result.message = ex.Message;
            }
            return(JsonConvert.SerializeObject(result));
        }
示例#25
0
        /// <summary>
        /// The post desserts schema.
        /// </summary>
        /// <param name="item">
        /// The item.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <IHttpActionResult> PostDessertsSchema(DessertsSchema item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (string.IsNullOrEmpty(item.Title) ||
                string.IsNullOrEmpty(item.Subtitle) ||
                string.IsNullOrEmpty(item.Image) ||
                string.IsNullOrEmpty(item.Description))
            {
                return(BadRequest("There are properties that are not defined."));
            }
            var current = await InsertAsync(item);

            await Services.Push.SendAsync(PushHelper.GetWindowsPushMessageForToastImageAndText03("Insert:", current.Title, current.Subtitle, current.Image));

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
示例#26
0
        public override Task ExecuteAsync()
        {
            try
            {
                context = new TDCSPMobileServiceContext();
                var mensagem = string.Empty;

                var mensagens = context.PushMessages.Where(message => message.Enviado == false).ToList <PushMessage>();

                foreach (PushMessage pushMessage in mensagens)
                {
                    try
                    {
                        Toast toastMessage = new Toast();
                        toastMessage.Text1 = String.Format(pushMessage.Mensagem);

                        if (pushMessage.Microsoft)
                        {
                            PushHelper.SendMicrosoftPush(Services, toastMessage);
                        }

                        if (pushMessage.Android)
                        {
                            PushHelper.SendGooglePush(Services, pushMessage.Mensagem);
                        }
                    }
                    catch (System.Exception ex) { Services.Log.Info("Error Sending Push from SendPushMessageJob: " + ex.Message); }

                    Services.Log.Info(string.Format("SendPushMessageJob: Msg {0}  Microsoft{1}  Android{2}", pushMessage.Mensagem, pushMessage.Microsoft, pushMessage.Android));

                    pushMessage.Enviado = true;
                    context.Entry(pushMessage).State = EntityState.Modified;
                    context.SaveChangesAsync();
                }
            }
            catch (System.Exception ex)
            {
                Services.Log.Info("Error Sending Push from SendPushMessageJob: " + ex.Message);
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
示例#27
0
        public void RegisterNativeAsyncUnregisterNativeAsync()
        {
            var channelUri = PushHelper.GetChannel();
            var push       = this.GetClient().GetPush();

            push.RegisterNativeAsync(channelUri).Wait();
            var registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(channelUri).Result;

            Assert.AreEqual(registrations.Count(), 1, "1 registration should exist after RegisterNativeAsync");
            Assert.AreEqual(
                registrations.First().RegistrationId,
                push.RegistrationManager.LocalStorageManager.GetRegistration(Registration.NativeRegistrationName).RegistrationId,
                "Local storage should have the same RegistrationId as the one returned from service");

            push.UnregisterNativeAsync().Wait();
            registrations = push.RegistrationManager.PushHttpClient.ListRegistrationsAsync(channelUri).Result;
            Assert.AreEqual(registrations.Count(), 0, "0 registrations should exist in service after UnregisterNativeAsync");
            Assert.IsNull(
                push.RegistrationManager.LocalStorageManager.GetRegistration(Registration.NativeRegistrationName),
                "Local storage should not contain a native registration after UnregisterNativeAsync.");
        }
示例#28
0
        public ActionResult New(MessageRegisterModel model)
        {
            var accepters     = new List <UserViewModel>();
            var accepterNames = model.Accepter.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var u in accepterNames)
            {
                var accepter = _userService.GetByUserName(u);
                if (accepter == null || string.IsNullOrEmpty(accepter.Id))
                {
                    ModelState.AddModelError("Accepter", "用户" + u + "不存在");
                    return(View(model));
                }
                accepters.Add(accepter);
            }
            if (accepters.Count == 0 && model.IsDraft == false)
            {
                ModelState.AddModelError("Accepter", "收件人不能为空");
                return(View(model));
            }
            var sender = _userService.GetById(UserId);

            foreach (var m in accepters)
            {
                var message = new MessageViewModel
                {
                    Accepter = m,
                    Content  = model.Content,
                    Sender   = sender,
                    Title    = model.Title,
                    Status   = model.IsDraft ? (int)MessageStatusEnum.Draft : (int)MessageStatusEnum.New,
                    Type     = (int)MessageTypeEnum.User,
                };
                _messageService.Add(message);
                PushHelper.PushMessage(m.UserName);
            }
            return(RedirectToAction("Index", new { type = 2 }));
        }
示例#29
0
        public ActionResult Leave(int id = 0)
        {
            using (var galleristContext = new GalleristComponentsDbContext())
            {
                var gameResponse = GameManager.GetGame(id, galleristContext);
                var game         = gameResponse.Game;

                if (game.IsStarted)
                {
                    ViewBag.Message = "Cannot leave in progress game";
                    ViewBag.Title   = "Error";
                    return(View("GameError"));
                }

                var playerLeaving = game.Players.First(m => m.UserName == User.Identity.Name);
                galleristContext.Players.Remove(playerLeaving);
                galleristContext.SaveChanges();

                PushHelper singleton = PushHelper.GetPushEngine();
                singleton.RefreshGameList(game.Players.Select(p => p.UserName).ToList());
                return(Redirect("~/Game/List/"));
            }
        }
示例#30
0
 public void WeChatPushMsg(string msg, string post)
 {
     if (Context.Session["OpenIdE"] != null)
     {
         string     OpenId = Context.Session["OpenIdE"].ToString();
         WeChatUser wcu    = ve.WeChatUser.FirstOrDefault(q => q.OpenId == OpenId && q.State == true);
         if (wcu != null)
         {
             int       id = Convert.ToInt32(msg);
             Video     vi = ve.Video.FirstOrDefault(q => q.Id == id);
             VideoType vt = ve.VideoType.FirstOrDefault(q => q.Id == vi.Tid);
             string    js = "{\"video_id\":" + id + ",\"video_name\":\"" + vi.Title + "\",\"position\":" + post + ",\"type_id\":" + vi.Tid + ",\"type_title\":\"" + vt.Title + "\",\"type_cover\":\"" + vt.Cover + "\"}";
             js = "{\"Title\":\"e家亲推送\",\"Type\":5,\"Content\":" + js + "}";
             Messages ms        = new Messages("e家亲", js);
             string   returnStr = PushHelper.PushMsg(wcu.Token, jsonSerializer.Serialize(ms));
             JObject  json      = JObject.Parse(returnStr);
             returnStr = json["ret_code"].ToString();
             if (returnStr == "0")
             {
                 new WeChat1().SetMsg(wcu.OpenId, "【" + vt.Title + "-" + vi.Title + "】推送成功!/:sun");
                 Write("推送成功!");
             }
             else
             {
                 Write("推送失败!" + returnStr);
             }
         }
         else
         {
             Write("您没绑定设备!");
         }
     }
     else
     {
         Write("没有登陆,推送失败!");
     }
 }