Example #1
0
        public Audience CreateAudience(string name, string[] segmentIds)
        {
            JObject audienceCreate = new JObject();
            audienceCreate["name"] = name;
            audienceCreate["segment_ids"] =  new JArray {segmentIds};
            var audience = new Audience();

            OAuthResponse response = null;
            try
            {
                response = _manager.GetOAuthResponse("POST", "audience/audiences", audienceCreate.ToString());
                if (response.ErrorFlag) throw response.Error;
                else
                {
                    Audience a = JsonConvert.DeserializeObject<Audience>(response.ResponseString);
                    audience = a;
                }
            }
            catch (Exception ex)
            {
                audience.ErrorFlag = true;
                audience.Error = ex;
                if (response != null) audience.ErrorMessage = response.ResponseString;
            }
            return audience;
        }
 protected virtual void Awake()
 {
     _audience = GetComponent<Audience>();
     controller = GetComponentInChildren<Animator>();
     controller.runtimeAnimatorController = AudienceAnimWarehouse.curr.basicController;
     RandomizeBasicClips();
 }
 public DayRow()
 {
     this.audience = new Audience();
     this.teacher = "NoTeacher";
     this.subject = new Subject();
     this.KindOfWeek = SheduleRedactor.KindOfWeek.Numerator;
 }
 public DayRow(Audience audience, string teacher, Subject subject,
      SheduleRedactor.KindOfWeek kindOfWeek)
 {
     this.audience = audience;
     this.teacher = teacher;
     this.subject = subject;
     this.KindOfWeek = kindOfWeek;
 }
        public static Audience AddAudience(string name)
        {
            var clientId = Guid.NewGuid().ToString("N");

            var key = new byte[32];
            RNGCryptoServiceProvider.Create().GetBytes(key);
            var base64Secret = TextEncodings.Base64Url.Encode(key);

            Audience newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name };
            AudiencesList.TryAdd(clientId, newAudience);
            return newAudience;
        }
Example #6
0
        public async Task<Audience> AddAudience(string name)
        {   
            //create clientId
            var clientId = Guid.NewGuid().ToString("N");
            var secret = Utilities.GetHash(name);

            var newAudience = new Audience { Id = clientId, Secret = secret, Name = name };
            if (_audiencesList.TryAdd(clientId, newAudience))
            {
                var peng = await _rep.AddAsync(newAudience);
            }

            return newAudience;
        }
Example #7
0
    public async Task<IHttpActionResult> AddAudience(AudienceModel audienceModel)
    {
      if (!ModelState.IsValid)
      {
        return BadRequest(ModelState);
      }
      var clientId = Guid.NewGuid().ToString("N");
      var name = audienceModel.Name;
      var secret = Utilities.GetHash(name);

      var newAudience = new Audience(clientId, secret, name);
      await this.AppRepository.Audiences.AddAsync(newAudience);
      return Ok();
    }
Example #8
0
        public IHttpActionResult PutAudience(int id, Audience audience)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != audience.AudienceId)
            {
                return(BadRequest());
            }

            var dbAudience = db.Audiences.Find(id);

            dbAudience.UserId      = audience.UserId;
            dbAudience.FirstName   = audience.FirstName;
            dbAudience.LastName    = audience.LastName;
            dbAudience.PhoneNumber = audience.PhoneNumber;
            dbAudience.City        = audience.City;
            dbAudience.Zip         = audience.Zip;
            dbAudience.Gender      = audience.Gender;

            db.Entry(audience).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AudienceExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public void ConfigureOAuth(IAppBuilder app)
        {
            var      audience  = "199153c2315149bc9ecb3e85e03f1144";
            Audience oAudience = AudiencesStore.FindAudience(audience);
            var      issuer    = "http://Chr.WebApi.Core";
            var      secret    = TextEncodings.Base64Url.Decode(oAudience.Base64Secret);

            app.CreatePerOwinContext(() => new CSSUsersEntities());

            //Server generacion del token
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/oauth2/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                Provider          = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat(issuer)
            };

            //Validacion del token por Controllador
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                Provider = new OAuthBearerAuthenticationProvider
                {
                    OnValidateIdentity = context =>
                    {
                        //context.Ticket.Identity.AddClaim(new System.Security.Claims.Claim("newCustomClaim", "newValue"));
                        return(Task.FromResult <object>(null));
                    }
                }
            });

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
        }
        /// <summary>
        /// 发起推送
        /// </summary>
        /// <returns></returns>
        public bool SendPush()
        {
            JPushClient[] clients = CreateClient();
            foreach (var client in clients)
            {
                PushPayload pushPayload = new PushPayload();
                pushPayload.platform = Platform.android_ios();
                pushPayload.audience = Audience.s_tag(Tags);
                pushPayload.options  = new Options {
                    apns_production = !IsDevModel
                };

                AddKeyContentAndExtras(pushPayload);

                try
                {
                    MessageResult result = client.SendPush(pushPayload);

                    if (!result.isResultOK())
                    {
                        LogHelper.WriteInfo("JPush key:" + Key);
                        LogHelper.WriteInfo("JPush tag:" + Tags);
                        LogHelper.WriteInfo("JPush message error:" + result.ResponseResult);
                        return(false);
                    }
                }
                catch (APIRequestException ex)
                {
                    //没有满足条件的推送目标,jpush发送了但是没发成功,也返回true
                    if (ex.Status == HttpStatusCode.BadRequest && ex.ErrorCode == 1011)
                    {
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteError("JPush异常", ex);
                    return(false);
                }
            }
            return(true);
        }
Example #11
0
        public void Push(JPushPlatForms platform, string content, string alias = "")
        {
            PushPayload payload;

            switch (platform)
            {
            case JPushPlatForms.All:
                payload = PushAllPlatform(content);
                break;

            case JPushPlatForms.IOS:
                payload = PushIOSPlatform(content);
                break;

            case JPushPlatForms.Android:
                payload = PushAndroidPlatform(content);
                break;

            default:
                return;
            }
            if (alias == "")
            {
                payload.audience = Audience.all();
            }
            else
            {
                payload.audience = Audience.s_alias(alias);
            }
            try
            {
                m_Client.SendPush(payload);
            }
            catch (APIRequestException e)
            {
                TraceLog.WriteError("Error response from JPush server.\nHTTP Status: {0}\nError Code: {1}\nError Message: {2}", e.Status, e.ErrorCode, e.ErrorMessage);
            }
            catch (APIConnectionException e)
            {
                TraceLog.WriteError(e.Message);
            }
        }
Example #12
0
        /// <summary>
        ///  向指定安卓手机推送一条
        /// </summary>
        /// <param name="registrationId">注册ID </param>
        /// <param name="Data">数据</param>
        /// <param name="TaskID">任务ID</param>
        /// <returns></returns>
        public static void PushObject_Android(string RegistrationId, string Data, string TaskID, TaskType TaskType, string Extra = "")
        {
            var pushPayload = new PushPayload();

            pushPayload.platform = Platform.android();
            pushPayload.audience = Audience.s_registrationId(RegistrationId);

            //入值发送内容,然后将任务ID作为附加ID传递过去
            Message Info = Message.content("{\"Data\":" + Data + "}").AddExtras("Operation", (int)TaskType).AddExtras("TaskID", TaskID);

            Info.title          = Extra;
            pushPayload.message = Info;
            Options Option = new Options();

            Option.time_to_live    = 0;    //如果当前用户离线,则不接收任何消息
            Option.apns_production = true; //当前所有推送都是正式环境下进行
            pushPayload.options    = Option;
            JPushClient   client = new JPushClient(AppKey, Master_Secret);
            MessageResult Result = client.SendPush(pushPayload);
        }
        protected override void Seed(LesApp0Context db)
        {
            // create data
            Audience[] audiences = new Audience[10];

            for (int i = 0; i < audiences.Length; i++)
            {
                audiences[i] = new Audience()
                {
                    Number           = 500 + i,
                    Category         = ((char)rnd.Next(65, 91)).ToString(),
                    CountOfWorkPlace = rnd.Next(10, 36),
                    Id = i + 1,
                };
            }

            // save data
            db.Audiences.AddRange(audiences);
            db.SaveChanges();
        }
Example #14
0
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Audience audience = value as Audience;

            if (audience == null)
            {
                return;
            }
            audience.Check();
            if (audience.isAll())
            {
                writer.WriteValue(audience.allAudience);
                //writer.WriteValue("alll");
            }
            else
            {
                var json = JsonConvert.SerializeObject(audience.dictionary);
                writer.WriteRawValue(json);
            }
        }
        /// <summary>
        /// Just needed for SAML2 library to get to work
        /// </summary>
        public static Saml2Section Create(Audience audience)
        {
            var section = new Saml2Section
            {
                ServiceProvider =
                {
                    Id     = "https://workaround.com",
                    Server = "http://",
                },
                AllowedAudienceUris =
                {
                    new AudienceUriElement
                    {
                        Uri = audience.Value
                    },
                },
            };

            return(section);
        }
Example #16
0
        public IActionResult List(Audience audience)
        {
            var test  = _Context.Audience.ToList();
            var model = new List <Audience>();

            foreach (var i in test)
            {
                var s = new Audience();
                {
                    s.Date   = i.Date;
                    s.Name   = i.Name;
                    s.Phone  = i.Phone;
                    s.Type   = i.Type;
                    s.SeatNo = i.SeatNo;
                    s.Gameno = i.Gameno;
                    model.Add(s);
                }
            }
            return(View(model));
        }
Example #17
0
        public void invalidParams_notification_ios()
        {
            JObject payload = new JObject();

            payload.Add("platform", JToken.FromObject(JsonConvert.SerializeObject(Platform.all(), new PlatformConverter())));
            payload.Add("audience", JToken.FromObject(JsonConvert.SerializeObject(Audience.all(), new AudienceConverter())));

            JObject notification = new JObject();

            notification.Add("ios", JToken.FromObject(ALERT));
            payload.Add("notification", notification);

            Console.WriteLine("json string: " + payload.ToString());

            try {
                _client.SendPush(payload.ToString());
            } catch (APIRequestException e) {
                Assert.AreEqual(INVALID_PARAMS, e.ErrorCode);
            }
        }
Example #18
0
 public ActionResult Create(string name)
 {
     try
     {
         int      currentAccountId = AppHelpers.GetCurrentUser().AccountId;
         Account  currentAccount   = db.Accounts.FirstOrDefault((a) => a.AccountId == currentAccountId);
         Audience audienceToAdd    = new Audience(name, currentAccount);
         db.Audiences.Add(audienceToAdd);
         db.SaveChanges();
         return(Json(new
         {
             success = true,
             id = audienceToAdd.AudienceId
         }));
     }
     catch (Exception)
     {
         return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
     }
 }
Example #19
0
        public void sendMessageContentAndTitle()
        {
            //PushPayload payload = PushPayload.newBuilder()
            //        .setAudience(Audience.all())
            //        .setPlatform(Platform.all())
            //        .setMessage(Message.newBuilder()
            //                .setTitle("message title")
            //                .setContentType("content type")
            //                .setMsgContent(MSG_CONTENT).build())
            //        .build();
            PushPayload payload = new PushPayload();

            payload.platform = Platform.all();
            payload.audience = Audience.all();
            payload.message  = Message.content(MSG_CONTENT).setTitle("message title").setContentType("ontent type");

            var result = _client.SendPush(payload);

            Assert.IsTrue(result.isResultOK());
        }
Example #20
0
        public async Task <IHttpActionResult> GetUserByName(string username)
        {
            Audience ad = null;

            try
            {
                ad = await this.AppUserManager.FindByNameAsync(username);

                if (ad != null)
                {
                    return(Ok(this.TheModelFactory.Create(ad)));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }

            return(NotFound());
        }
        /// <summary>
        /// Get the format of the
        /// </summary>
        /// <param name="audience"></param>
        /// <param name="cloudUrl"></param>
        /// <param name="tenantInformation"></param>
        /// <returns></returns>
        private string GetAuthority(Audience audience, string cloudUrl, string tenantInformation)
        {
            switch (audience)
            {
            case Audience.AccountsInSpecificDirectoryOnly:
                return($"{cloudUrl}/{tenantInformation}/");

            case Audience.AcountsInAnyAzureAdDirectory:
                return($"{cloudUrl}/organizations/");

            case Audience.MicrosoftPersonalAcountsOnly:
                return($"{cloudUrl}/consumers/");

            case Audience.AccountsInAnyAzureAdDirectoryAndPersonalMicrosoftsAccounts:
                return($"{cloudUrl}/common/");

            default:
                throw new ArgumentException("Unsupported tenantInformation");
            }
        }
Example #22
0
        public static PushPayload PushObject_android_and_ios()
        {
            PushPayload pushPayload = new PushPayload();

            pushPayload.platform = Platform.android_ios();
            var audience = Audience.s_tag("tag1");

            pushPayload.audience = audience;
            var notification = new Notification().setAlert("alert content");

            notification.AndroidNotification = new AndroidNotification().setTitle("Android Title");
            notification.IosNotification     = new IosNotification();
            notification.IosNotification.incrBadge(1);
            notification.IosNotification.AddExtra("extra_key", "extra_value");

            pushPayload.notification = notification.Check();


            return(pushPayload);
        }
Example #23
0
        /// <summary>
        /// 极光推送
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public PushResponse SendPush(PushRequest request)
        {
            var client   = new JPushClientV3(AppKey, MasterSecret);
            var audience = new Audience();

            if (request.type == 0)
            {
                audience.Add(PushTypeV3.Broadcast, null);
            }
            else
            {
                audience.Add(PushTypeV3.ByTagWithinAnd, new List <string>(new[] { request.userId, request.userId }));
            }
            var customizedValues = new Dictionary <string, object>
            {
                { "JPushValue", request.value }
            };
            var notification = new Notification
            {
                AndroidNotification = new AndroidNotificationParameters
                {
                    Title            = request.title,
                    Alert            = request.content,
                    CustomizedValues = customizedValues
                }
            };
            var response = client.SendPushMessage(new PushMessageRequestV3
            {
                Audience          = audience,
                Platform          = PushPlatform.AndroidAndiOS,
                Notification      = notification,
                IsTestEnvironment = true,
                AppMessage        = new AppMessage
                {
                    Content         = request.value,
                    CustomizedValue = customizedValues
                },
            });

            return(response);
        }
        public bool Validate(string expectedClientId, string expectedAlgorithm, string expectedIssuer, string accessToken = null)
        {
            // verify signature
            if (!Algorithm.Equals(expectedAlgorithm, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(Algorithm), $"The id_token 'alg' does not match the expected algorithm value.  Expected '{expectedAlgorithm}' but found '{Algorithm}'.");
            }

            //TODO: Validate signature

            // Verify expiration claim
            if (Expiration < DateTime.UtcNow)
            {
                throw new ArgumentOutOfRangeException(nameof(Expiration), $"The id_token is expired");
            }

            // Verify issuer claim
            if (!Issuer.Equals(expectedIssuer, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(Issuer), $"The id_token 'iss' claim does not match expected issuer value.  Expected '{expectedIssuer}' but fond '{Issuer}'.");
            }

            // Verify audience claim
            if (!Audience.Equals(expectedClientId, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(Audience), $"The id_token 'aud' claim does not match the provided clientId value.")
                ;
            }
            // Verify Access Token Hash claim (if provided)
            if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(AccessTokenHash))
            {
                var atHash = Util.Sha256AtHash(accessToken);

                if (!AccessTokenHash.Equals(atHash, StringComparison.Ordinal))
                {
                    throw new ArgumentOutOfRangeException(nameof(AccessTokenHash), $"The id_token 'at_hash' claim does not match the expected hash of the given token.  Expected {atHash} but found {AccessTokenHash}");
                }
            }

            return(true);
        }
Example #25
0
        public void TestAfter()
        {
            /*var features = JsonConvert.DeserializeObject<IDictionary<string, FeatureControl>>(EvaluateTest.features);
             * var user = new User("user1");
             *
             * features.TryGetValue("example-feature", out var feature);
             * var evaluate = new Evaluate(feature, user, "off");
             * Equal("red", evaluate.Value());*/
            //construct the feature an rule
            var control = new FeatureControl();
            var rule    = new Rule {
                VariantSplits = OnSplit()
            };
            var audience  = new Audience();
            var condition = new Condition();


            control.Enabled       = true;
            control.OffVariantKey = "off";

            condition.Operator = "before";
            condition.Target   = "signupDate";
            condition.Values.Add(new DateTime(2017, 1, 17));

            audience.Conditions.Add(condition);
            rule.Audience      = audience;
            rule.VariantSplits = OnSplit();

            control.Rules.Add(rule);
            control.Rules.Add(DefaultOffRule());


            //create a matching user
            var user = new User("123");

            user.WithAttribute("signupDate", new DateTime(2017, 1, 18));

            var evaluate = new Evaluate(control, user, "on");

            Equal(true, evaluate.IsOn());
        }
Example #26
0
        /// <summary>
        /// IOS文档消息推送
        /// </summary>
        /// <param name="message"></param>
        /// <param name="notificationType"></param>
        /// <param name="tag"></param>
        /// <param name="updateDocumentTypeId"></param>
        /// <param name="updateCity"></param>
        /// <param name="updateDocumentType"></param>
        /// <param name="updateCityId"></param>
        /// <returns></returns>
        private static PushPayload PushAndroid_IosDocument(string message, int notificationType, string tag, int updateDocumentTypeId, string updateCity, string updateDocumentType, int updateCityId)
        {
            var pushPayload = new PushPayload
            {
                platform = Platform.android_ios(),
                audience = tag == "all" ? Audience.all() : Audience.s_tag(tag)
            };

            var notification = new Notification().setAlert(message);

            notification.AndroidNotification =
                new AndroidNotification().setAlert(message)
                .AddExtra("UpdateDocumentTypeID", updateDocumentTypeId)
                .AddExtra("NotificationType", notificationType)
                .AddExtra("message", message);
            notification.IosNotification =
                new IosNotification().setAlert(message)
                .AddExtra("UpdateDocumentTypeID", updateDocumentTypeId)
                .AddExtra("NotificationType", notificationType)
                .AddExtra("message", message)
                .setSound("default")
                .setContentAvailable(true);

            if (!string.IsNullOrEmpty(updateCity))
            {
                notification.IosNotification.AddExtra("UpdateCity", updateCity);
                notification.AndroidNotification.AddExtra("UpdateCity", updateCity);
            }
            if (!string.IsNullOrEmpty(updateDocumentType))
            {
                notification.IosNotification.AddExtra("UpdateDocumentType", updateDocumentType);
                notification.AndroidNotification.AddExtra("UpdateDocumentType", updateDocumentType);
            }
            if (updateCityId > 0)
            {
                notification.IosNotification.AddExtra("UpdateCityId", updateCityId);
                notification.AndroidNotification.AddExtra("UpdateCityId", updateCityId);
            }
            pushPayload.notification = notification;
            return(pushPayload);
        }
Example #27
0
        public static SimpleResultModel SendToAll(string msg)
        {
            PushPayload pushPayload = new PushPayload();

            pushPayload.platform     = Platform.android();
            pushPayload.audience     = Audience.all();
            pushPayload.notification = new Notification().setAlert(msg);
            AndroidNotification androidnotification = new AndroidNotification();

            androidnotification.setTitle(TITLE);
            pushPayload.notification.AndroidNotification = androidnotification;


            try {
                var result = client.SendPush(pushPayload);
                //由于统计数据并非非是即时的,所以等待一小段时间再执行下面的获取结果方法
                //System.Threading.Thread.Sleep(10000);
                //如需查询上次推送结果执行下面的代码
                //var apiResult = client.getReceivedApi(result.msg_id.ToString());
                //var apiResultv3 = client.getReceivedApi_v3(result.msg_id.ToString());
                //如需查询某个messageid的推送结果执行下面的代码
                //var queryResultWithV2 = client.getReceivedApi("1739302794");
                //var querResultWithV3 = client.getReceivedApi_v3("1739302794");
                return(new SimpleResultModel()
                {
                    suc = true, msg = result.msg_id.ToString()
                });
            }
            catch (APIRequestException e) {
                return(new SimpleResultModel()
                {
                    suc = false, msg = "HTTP Status: " + e.Status + ";Error Code: " + e.ErrorCode + ";Error Message: " + e.ErrorMessage
                });
            }
            catch (APIConnectionException e) {
                return(new SimpleResultModel()
                {
                    suc = false, msg = e.message
                });
            }
        }
        public static PushPayload PushObject_All_All_Alert(string alert, string title, string alias, string activity = "")
        {
            string[] aliass = alias.Split(',');

            PushPayload pushPayload = new PushPayload();

            pushPayload.platform = Platform.all();
            if (alias == "")
            {
                pushPayload.audience = Audience.all();
            }
            else
            {
                pushPayload.audience = Audience.s_alias(aliass);
            }

            pushPayload.notification = Notification.android(alert, title);
            pushPayload.notification.AndroidNotification.AddExtra("activity", activity);
            pushPayload.notification.AndroidNotification.setBuilderID(2);
            return(pushPayload);
        }
 private void btnAdd_Click(object sender, EventArgs e)
 {
     if (flag == 1)
     {
         Instructor next = new Instructor();
         this.Hide();
         next.Show();
     }
     else if (flag == 2)
     {
         Guest next = new Guest();
         this.Hide();
         next.Show();
     }
     else
     {
         Audience next = new Audience();
         this.Hide();
         next.Show();
     }
 }
Example #30
0
        public void lackOfParams_platform()
        {
            JsonSerializer jsonSerializer = new JsonSerializer();

            jsonSerializer.DefaultValueHandling = DefaultValueHandling.Ignore;
            JObject payload = new JObject();

            payload.Add("audience", JToken.FromObject(JsonConvert.SerializeObject(Audience.all(), new AudienceConverter())));

            payload.Add("notification", JToken.FromObject(new Notification().setAlert(ALERT), jsonSerializer));

            Console.WriteLine("json string: " + payload.ToString());
            try
            {
                _client.SendPush(payload.ToString());
            }
            catch (APIRequestException e)
            {
                Assert.AreEqual(LACK_OF_PARAMS, e.ErrorCode);
            }
        }
Example #31
0
 public string ToPrettyString()
 {
     return("Conversation {" +
            ($"\n{nameof(Id)}: {Id}," +
             $"\n{nameof(Subject)}: {Subject}," +
             $"\n{nameof(ReadState)}: {ReadState}," +
             $"\n{nameof(LastMessage)}: {LastMessage}," +
             $"\n{nameof(LastMessageAt)}: {LastMessageAt}," +
             $"\n{nameof(MessageCount)}: {MessageCount}," +
             $"\n{nameof(Subscribed)}: {Subscribed}," +
             $"\n{nameof(Private)}: {Private}," +
             $"\n{nameof(Starred)}: {Starred}," +
             $"\n{nameof(Properties)}: {Properties.ToPrettyString()}," +
             $"\n{nameof(Audience)}: {Audience.ToPrettyString()}," +
             $"\n{nameof(AudienceContexts)}: {AudienceContexts.ToPrettyString()}," +
             $"\n{nameof(AvatarUrl)}: {AvatarUrl}," +
             $"\n{nameof(Participants)}: {Participants.ToPrettyString()}," +
             $"\n{nameof(Visible)}: {Visible}," +
             $"\n{nameof(ContextName)}: {ContextName}").Indent(4) +
            "\n}");
 }
        public static PushPayload PushObject_ios_alert_json()
        {
            PushPayload pushPayload = new PushPayload();

            pushPayload.platform = Platform.all();
            pushPayload.audience = Audience.all();
            var       notification = new Notification();
            Hashtable alert        = new Hashtable();

            alert["title"]               = "JPush Title";
            alert["subtitle"]            = "JPush Subtitle";
            alert["body"]                = "JPush Body";
            notification.IosNotification = new IosNotification()
                                           .setAlert(alert)
                                           .setBadge(5)
                                           .setSound("happy")
                                           .AddExtra("from", "JPush");
            pushPayload.notification = notification;
            pushPayload.message      = Message.content(MSG_CONTENT);
            return(pushPayload);
        }
Example #33
0
        private PushPayload PushSendSmsMessage(string msg, string smsMsg, string[] alias = null)
        {
            var pushPayload = new PushPayload();

            pushPayload.platform = Platform.all();
            if (alias != null)
            {
                pushPayload.audience = Audience.s_alias(alias);
            }
            else
            {
                pushPayload.audience = Audience.all();
            }
            pushPayload.notification = new Notification().setAlert(msg);
            SmsMessage sms_message = new SmsMessage();

            sms_message.setContent(smsMsg);
            sms_message.setDelayTime(DELAY_TIME);
            pushPayload.sms_message = sms_message;
            return(pushPayload);
        }
Example #34
0
        public static void Push_all_tag_notification(string[] tag, string alert, Dictionary <string, object> extras)
        {
            PushPayload pushPayload = new PushPayload();

            pushPayload.platform = Platform.android_ios();

            pushPayload.audience = Audience.s_tag(tag);

            pushPayload.notification = new Notification();
            pushPayload.notification.AndroidNotification = new AndroidNotification().setAlert(alert).setBuilderID(1);
            pushPayload.notification.IosNotification     = new IosNotification().setAlert(alert).incrBadge(1);
            if (extras != null)
            {
                foreach (string key in extras.Keys)
                {
                    pushPayload.notification.AndroidNotification.AddExtra(key, extras[key]);
                    pushPayload.notification.IosNotification.AddExtra(key, extras[key]);
                }
            }
            Push(pushPayload);
        }
        public void testNotification()
        {
            int number = ServiceHelper.generateSendno();

            PushPayload payload = new PushPayload();

            payload.platform = Platform.all();
            payload.audience = Audience.all();
            payload.options  = new Options()
            {
                sendno = number
            };
            payload.notification = new Notification().setAlert("alert");
            payload.Check();

            JObject json = new JObject();

            json.Add("platform", JToken.FromObject("all"));
            json.Add("audience", JToken.FromObject("all"));


            JObject noti = new JObject();

            noti.Add("alert", JToken.FromObject("alert"));
            json.Add("notification", noti);

            JObject options = new JObject();

            options.Add("sendno", JToken.FromObject(number));
            options.Add("apns_production", JToken.FromObject(false));
            json.Add("options", options);

            var jSetting = new JsonSerializerSettings();

            jSetting.DefaultValueHandling = DefaultValueHandling.Ignore;
            var jsonString = JsonConvert.SerializeObject(payload, jSetting);
            var jsonObject = json.ToString(Formatting.None);

            Assert.AreEqual(jsonObject, jsonString);
        }
Example #36
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null;

            if (string.IsNullOrWhiteSpace(audienceId))
            {
                throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");
            }

            Audience audience = AudiencesStore.FindAudience(audienceId);

            string symmetricKeyAsBase64 = audience.Base64Secret;

            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            var signingKey         = new SymmetricSecurityKey(keyByteArray);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var issued  = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;

            //Optional: Map Identity Claims names to JWT names (using jwtClaims instead of 'data.Identity.Claims' in JwtSecurityToken constructor)
            var jwtClaims = new List <Claim>();

            jwtClaims.Add(new Claim("sub", data.Identity.Name));
            jwtClaims.AddRange(data.Identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => new Claim("roles", c.Value)));

            var token = new JwtSecurityToken(_issuer, audienceId, jwtClaims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);

            var handler = new JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Example #37
0
    public Fight1v1(Character fighter1, Character fighter2, string fightType, GameObject fightPlanButton)
    {
        gameController  = GameObject.Find("GameController").GetComponent <GameController> ();
        inputController = GameObject.Find("InputController").GetComponent <InputController> ();
        TickCount       = 1;
        f1 = fighter1;
        f2 = fighter2;
        FightPlanButton = fightPlanButton;
        Audience        = new Audience();
        if (f1.Team == gameController.PlayerManager.PlayerTeam || f2.Team == GameObject.Find("GameController").GetComponent <GameController>().PlayerManager.PlayerTeam)
        {
            PlayerInFight       = true;
            PlayerWatchingFight = true;
        }

        FirstFighterTitle = SetTitleBasedOnType(f1, false, fightType);
        f1.SelfIntroduction(FirstFighterTitle, PlayerInFight);
        SecondFighterTitle = SetTitleBasedOnType(f1, true, fightType);
        f2.SelfIntroduction(SecondFighterTitle, PlayerInFight);

        if (!PlayerWatchingFight)
        {
            while (!FightOver)
            {
                FightRoundTick();
            }
            gameController.UnPauseTicks();
        }
        else
        {
            gameController.UIController.GetComponent <UIController> ().ActivateFightScreen(f1, f2, this);
        }

        f1.CurrentEnergy = f1.MaxEnergy;
        f2.CurrentEnergy = f2.MaxEnergy;
        if (PlayerWatchingFight)
        {
            fightPanel.UpdateTextLog(f1.FirstName + " " + f1.LastName + " will fight " + f2.FirstName + " " + f2.LastName);
        }
    }
Example #38
0
 public void AddToAudiences(Audience audience)
 {
     base.AddObject("Audiences", audience);
 }
 public Boolean HasAudience(Audience audience)
 {
     return this.audience.Equals(audience);
 }
Example #40
0
        /// <summary>
        /// 创建消息实体
        /// </summary>
        /// <param name="title">消息标题</param>
        /// <param name="content">内容</param>
        /// <returns>消息实体</returns>
        private PushMessageRequestV3 CreatePushMsg(string title, string content, Dictionary<string, object> objs, string registId = null,List<string> alias = null, string tagAnd = null, string tagOr = null)
        {
            var customzedValues = new Dictionary<string, string>();
            if (objs != null)
            {
                foreach (var obj in objs)
                {
                    customzedValues.Add(obj.Key, obj.Value.ToString());
                }
            }
            Audience audience = new Audience();
            if (!string.IsNullOrEmpty(registId))
            {
                var registIdList = new List<string>();
                registIdList.Add(registId);
                audience.Add(PushTypeV3.ByRegistrationId, registIdList);
            }
            else if (!string.IsNullOrEmpty(tagAnd))
            {
                audience.Add(PushTypeV3.ByTagWithinAnd, new List<string>(new string[] { tagAnd }));
            }
            else if (!string.IsNullOrEmpty(tagOr))
            {
                audience.Add(PushTypeV3.ByTagWithinOr, new List<string>(new string[] { tagOr }));
            }
            else if (alias != null)
            {
                audience.Add(PushTypeV3.ByAlias, alias);
            }else
            {
                audience.Add(PushTypeV3.Broadcast, null);
            }

            // In JPush V3, Notification would not be display on screen, it would be transferred to app instead.
            // And different platform can provide different notification data.
            Notification notification = new Notification
            {
                AndroidNotification = new AndroidNotificationParameters
                {
                    Title = title,
                    Alert = content,
                    CustomizedValues = customzedValues,
                },
                iOSNotification = new iOSNotificationParameters
                {
                    Badge = "+1",
                    Alert = content,
                    Sound = "YourSound",
                    CustomizedValues = customzedValues,
                }
            };

            PushMessageRequestV3 newPush = new PushMessageRequestV3
            {
                Audience = audience,
                IsTestEnvironment = true,
                AppMessage = new AppMessage
                {
                    Content = content
                },
                Notification = notification
            };

            return newPush;
        }
    //private void Update()
    //{
    //    //sample usage
    //    //if (Input.GetKeyDown(KeyCode.O))
    //    //    StartToFollow(GameObject.Find("Target").transform);
    //    //if (Input.GetKeyDown(KeyCode.P))
    //    //    StopToFollow();
    //}

    private void Awake()
    {
        _audience = GetComponent<Audience>();
        controller.SetLayerWeight(defaultLayerIdx, 1f);
    }
Example #42
0
 public Audience DeleteAudience(string audienceId)
 {
     Audience audience = new Audience();
     OAuthResponse response = null;
     try
     {
         response = _manager.GetOAuthResponse("DELETE", "audience/audiences/" + audienceId);
         if (response.ErrorFlag) throw response.Error;
         else
         {
             audience.id = audienceId;
             audience.state = "Deleted";
             audience.last_modified = DateTime.Now;
         }
     }
     catch (Exception ex)
     {
         audience.ErrorFlag = true;
         audience.Error = ex;
         if (response != null) audience.ErrorMessage = response.ResponseString;
     }
     return audience;
 }
Example #43
0
 public Audience GetAudience(string id)
 {
     Audience audience = new Audience();
     OAuthResponse response = null;
     try
     {
         response = _manager.GetOAuthResponse("GET", "audience/audiences/" + id);
         if (response.ErrorFlag) throw response.Error;
         else
         {
             Audience s = JsonConvert.DeserializeObject<Audience>(response.ResponseString);
             audience = s;
         }
     }
     catch (Exception ex)
     {
         audience.ErrorFlag = true;
         audience.Error = ex;
         if (response != null) audience.ErrorMessage = response.ResponseString;
     }
     return audience;
 }
Example #44
0
 public static Audience CreateAudience(int ID, string title, byte[] rowVersion)
 {
     Audience audience = new Audience();
     audience.Id = ID;
     audience.Title = title;
     audience.RowVersion = rowVersion;
     return audience;
 }
        /// <summary>
        /// Exports the audience.
        /// </summary>
        /// <param name="xmlWriter">The XML writer.</param>
        /// <param name="audience">The audience.</param>
        /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param>
        private static void ExportAudience(XmlWriter xmlWriter, Audience audience, bool includeAllAttributes)
        {
            xmlWriter.WriteStartElement("Audience");
            xmlWriter.WriteAttributeString("AudienceDescription", audience.AudienceDescription);
            xmlWriter.WriteAttributeString("AudienceID", audience.AudienceID.ToString());
            xmlWriter.WriteAttributeString("AudienceName", audience.AudienceName);
            xmlWriter.WriteAttributeString("CreateTime", audience.CreateTime.ToString());
            xmlWriter.WriteAttributeString("GroupOperation", audience.GroupOperation.ToString());
            xmlWriter.WriteAttributeString("LastCompilation", audience.LastCompilation.ToString());
            xmlWriter.WriteAttributeString("LastError", audience.LastError);
            xmlWriter.WriteAttributeString("LastPropertyUpdate", audience.LastPropertyUpdate.ToString());
            xmlWriter.WriteAttributeString("LastRuleUpdate", audience.LastRuleUpdate.ToString());
            xmlWriter.WriteAttributeString("MemberShipCount", audience.MemberShipCount.ToString());
            xmlWriter.WriteAttributeString("OwnerAccountName", audience.OwnerAccountName);

            ArrayList audienceRules = audience.AudienceRules;
            xmlWriter.WriteStartElement("rules");
            if (audienceRules != null && audienceRules.Count > 0)
            {
                foreach (AudienceRuleComponent rule in audienceRules)
                {
                    xmlWriter.WriteStartElement("rule");
                    if (includeAllAttributes)
                    {
                        xmlWriter.WriteAttributeString("field", rule.LeftContent);
                        xmlWriter.WriteAttributeString("op", rule.Operator);
                        xmlWriter.WriteAttributeString("value", rule.RightContent);
                    }
                    else
                    {
                        switch (rule.Operator.ToLowerInvariant())
                        {
                            case "=":
                            case ">":
                            case ">=":
                            case "<":
                            case "<=":
                            case "contains":
                            case "<>":
                            case "not contains":
                                xmlWriter.WriteAttributeString("field", rule.LeftContent);
                                xmlWriter.WriteAttributeString("op", rule.Operator);
                                xmlWriter.WriteAttributeString("value", rule.RightContent);
                                break;
                            case "reports under":
                            case "member of":
                                xmlWriter.WriteAttributeString("op", rule.Operator);
                                xmlWriter.WriteAttributeString("value", rule.RightContent);
                                break;
                            case "and":
                            case "or":
                            case "(":
                            case ")":
                                xmlWriter.WriteAttributeString("op", rule.Operator);
                                break;
                        }
                    }
                    xmlWriter.WriteEndElement(); // rule
                }
            }
            xmlWriter.WriteEndElement(); // rules
            xmlWriter.WriteEndElement(); // Audience
        }