示例#1
0
        public void CreateWithInvalidEngagementResturnsNull()
        {
            var          engagement   = new Engagement("testDecisionPoint");
            ImageMessage imageMessage = ImageMessage.Create(engagement);

            Assert.IsNull(imageMessage);
        }
        /// <summary>
        /// Requests a rewarded ad at a <code>decisionPoint</code>.
        /// </summary>
        /// <param name="decisionPoint">the decision point</param>
        /// <param name="parameters">an optional set of real-time parameters</param>
        /// <param name="callback">the callback to handle the result</param>
        public void RequestRewardedAd(string decisionPoint, Params parameters, Action <RewardedAd> callback)
        {
            if (smartads != null)
            {
                Engagement engagement = BuildEngagement(decisionPoint, parameters)
                                        .AddParam("ddnaAdSessionCount", smartads.GetSessionCount(decisionPoint))
                                        .AddParam("ddnaAdDailyCount", smartads.GetDailyCount(decisionPoint));

                if (smartads.GetLastShown(decisionPoint).HasValue)
                {
                    engagement.AddParam("ddnaAdLastShownTime", smartads.GetLastShown(decisionPoint).Value);
                }

                ddna.RequestEngagement(engagement,
                                       (response) =>
                {
                    Logger.LogDebug("Creating a rewarded ad at '" + decisionPoint + "'");
                    callback(RewardedAd.CreateUnchecked(response));
                }, (exception) =>
                {
                    Logger.LogWarning("Creating rewarded ad despite failed Engage request");
                    callback(RewardedAd.CreateUnchecked(engagement));
                });
            }
        }
示例#3
0
        /// <summary>
        /// Requests an Engagement with Engage.  The engagement is populated with the result of the request and
        /// returned in the onCompleted callback.  The engagement's json field can be queried for the returned json.
        /// A cache is maintained that will return the last valid response if available.
        /// </summary>
        /// <param name="engagement">The engagement the request is for.</param>
        /// <param name="onCompleted">Method called with the Engagement populated by Engage.</param>
        /// <exception cref="System.Exception">Thrown if the SDK has not been started, and if the Engage URL has not been set.</exception>
        public void RequestEngagement(Engagement engagement, Action <Engagement> onCompleted, Action <Exception> onError)
        {
            if (!this.started)
            {
                throw new Exception("You must first start the SDK via the StartSDK method.");
            }

            if (String.IsNullOrEmpty(this.EngageURL))
            {
                throw new Exception("Engage URL not configured.");
            }

            try {
                var dict = engagement.AsDictionary();

                var request = new EngageRequest(dict["decisionPoint"] as string);
                request.Flavour    = dict["flavour"] as string;
                request.Parameters = dict["parameters"] as Dictionary <string, object>;

                EngageResponse handler = (string response, int statusCode, string error) => {
                    engagement.Raw        = response;
                    engagement.StatusCode = statusCode;
                    engagement.Error      = error;

                    onCompleted(engagement);
                };

                StartCoroutine(Engage.Request(this, request, handler));
            } catch (Exception ex) {
                Logger.LogWarning("Engagement request failed: " + ex.Message);
            }
        }
        private ImageMessage(
            DDNA ddna,
            JSONObject configuration,
            string name,
            int depth,
            Engagement engagement)
        {
            this.ddna = ddna;

            gameObject = new GameObject(name, typeof(RectTransform));
            SpriteMap spriteMap = gameObject.AddComponent <SpriteMap>();

            spriteMap.Build(ddna, configuration);


            OrientationChange changer = gameObject.AddComponent <OrientationChange>();

            changer.Init(redraw);

            this.name          = name;
            this.configuration = configuration;
            this.spriteMap     = spriteMap;
            this.depth         = depth;
            this.engagement    = engagement;
            changeListener     = changer;
        }
示例#5
0
        public void CreateWithInvalidImageJSONReturnsNull()
        {
            var          engagement = new Engagement("testDecisionPoint");
            ImageMessage imageMessage;

            engagement.Raw = "{\"transactionID\":2184816393350012928,\"image\":{\"height\":256,\"format\":\"png\",\"spritemap\":{\"background\":{\"x\":2,\"y\":38,\"width\":319,\"height\":177},\"buttons\":[{\"x\":2,\"y\":2,\"width\":160,\"height\":34},{\"x\":323,\"y\":180,\"width\":157,\"height\":35}]},\"layout\":{\"landscape\":{\"background\":{\"contain\":{\"halign\":\"center\",\"valign\":\"center\",\"left\":\"10%\",\"right\":\"10%\",\"top\":\"10%\",\"bottom\":\"10%\"},\"action\":{\"type\":\"none\",\"value\":\"\"}},\"buttons\":[{\"x\":-1,\"y\":144,\"action\":{\"type\":\"dismiss\",\"value\":\"\"}},{\"x\":160,\"y\":143,\"action\":{\"type\":\"action\",\"value\":\"reward\"}}]}},\"shim\":{\"mask\":\"dimmed\",\"action\":{\"type\":\"none\"}},\"url\":\"http://download.deltadna.net/engagements/3eef962b51f84f9ca21643ca21fb3057.png\"},\"parameters\":{\"rewardName\":\"wrench\"}}";

            imageMessage = ImageMessage.Create(engagement);
            Assert.IsNull(imageMessage);

            engagement.Raw = "{\"transactionID\":2184816393350012928,\"image\":{\"width\":512,\"format\":\"png\",\"spritemap\":{\"background\":{\"x\":2,\"y\":38,\"width\":319,\"height\":177},\"buttons\":[{\"x\":2,\"y\":2,\"width\":160,\"height\":34},{\"x\":323,\"y\":180,\"width\":157,\"height\":35}]},\"layout\":{\"landscape\":{\"background\":{\"contain\":{\"halign\":\"center\",\"valign\":\"center\",\"left\":\"10%\",\"right\":\"10%\",\"top\":\"10%\",\"bottom\":\"10%\"},\"action\":{\"type\":\"none\",\"value\":\"\"}},\"buttons\":[{\"x\":-1,\"y\":144,\"action\":{\"type\":\"dismiss\",\"value\":\"\"}},{\"x\":160,\"y\":143,\"action\":{\"type\":\"action\",\"value\":\"reward\"}}]}},\"shim\":{\"mask\":\"dimmed\",\"action\":{\"type\":\"none\"}},\"url\":\"http://download.deltadna.net/engagements/3eef962b51f84f9ca21643ca21fb3057.png\"},\"parameters\":{\"rewardName\":\"wrench\"}}";

            imageMessage = ImageMessage.Create(engagement);
            Assert.IsNull(imageMessage);

            engagement.Raw = "{\"transactionID\":2184816393350012928,\"image\":{\"width\":512,\"height\":256,\"format\":\"png\",\"layout\":{\"landscape\":{\"background\":{\"contain\":{\"halign\":\"center\",\"valign\":\"center\",\"left\":\"10%\",\"right\":\"10%\",\"top\":\"10%\",\"bottom\":\"10%\"},\"action\":{\"type\":\"none\",\"value\":\"\"}},\"buttons\":[{\"x\":-1,\"y\":144,\"action\":{\"type\":\"dismiss\",\"value\":\"\"}},{\"x\":160,\"y\":143,\"action\":{\"type\":\"action\",\"value\":\"reward\"}}]}},\"shim\":{\"mask\":\"dimmed\",\"action\":{\"type\":\"none\"}},\"url\":\"http://download.deltadna.net/engagements/3eef962b51f84f9ca21643ca21fb3057.png\"},\"parameters\":{\"rewardName\":\"wrench\"}}";

            imageMessage = ImageMessage.Create(engagement);
            Assert.IsNull(imageMessage);

            engagement.Raw = "{\"transactionID\":2184816393350012928,\"image\":{\"width\":512,\"height\":256,\"format\":\"png\",\"spritemap\":{\"background\":{\"x\":2,\"y\":38,\"width\":319,\"height\":177},\"buttons\":[{\"x\":2,\"y\":2,\"width\":160,\"height\":34},{\"x\":323,\"y\":180,\"width\":157,\"height\":35}]},\"shim\":{\"mask\":\"dimmed\",\"action\":{\"type\":\"none\"}},\"url\":\"http://download.deltadna.net/engagements/3eef962b51f84f9ca21643ca21fb3057.png\"},\"parameters\":{\"rewardName\":\"wrench\"}}";

            imageMessage = ImageMessage.Create(engagement);
            Assert.IsNull(imageMessage);

            engagement.Raw = "{\"transactionID\":2184816393350012928,\"image\":{\"width\":512,\"height\":256,\"format\":\"png\",\"spritemap\":{\"background\":{\"x\":2,\"y\":38,\"width\":319,\"height\":177},\"buttons\":[{\"x\":2,\"y\":2,\"width\":160,\"height\":34},{\"x\":323,\"y\":180,\"width\":157,\"height\":35}]},\"layout\":{\"landscape\":{\"background\":{\"contain\":{\"halign\":\"center\",\"valign\":\"center\",\"left\":\"10%\",\"right\":\"10%\",\"top\":\"10%\",\"bottom\":\"10%\"},\"action\":{\"type\":\"none\",\"value\":\"\"}},\"buttons\":[{\"x\":-1,\"y\":144,\"action\":{\"type\":\"dismiss\",\"value\":\"\"}},{\"x\":160,\"y\":143,\"action\":{\"type\":\"action\",\"value\":\"reward\"}}]}},\"shim\":{\"mask\":\"dimmed\",\"action\":{\"type\":\"none\"}}},\"parameters\":{\"rewardName\":\"wrench\"}}";

            imageMessage = ImageMessage.Create(engagement);
            Assert.IsNull(imageMessage);
        }
示例#6
0
        override internal void RequestEngagement(Engagement engagement, Action <Engagement> onCompleted, Action <Exception> onError)
        {
            engagement.StatusCode = 200;
            engagement.Raw        = "{}";
            engagement.Error      = null;

            onCompleted(engagement);
        }
示例#7
0
        private RewardedAd(Engagement engagement) : base(engagement)
        {
            this.engagement = engagement;

            SmartAds.Instance.OnRewardedAdLoaded -= NotifyOnLoaded;
            SmartAds.Instance.OnRewardedAdLoaded += NotifyOnLoaded;
            SmartAds.Instance.OnRewardedAdOpenedWithDecisionPoint -= NotifyOnOpened;
            SmartAds.Instance.OnRewardedAdOpenedWithDecisionPoint += NotifyOnOpened;
        }
        public static InterstitialAd Create(Engagement engagement)
        {
            if (!SmartAds.Instance.IsInterstitialAdAllowed(engagement, false))
            {
                return(null);
            }

            return(CreateUnchecked(engagement));
        }
示例#9
0
        public static RewardedAd Create(Engagement engagement)
        {
            if (!SmartAds.Instance.IsRewardedAdAllowed(engagement, false))
            {
                return(null);
            }

            return(CreateUnchecked(engagement));
        }
示例#10
0
        public void CreateWithEngagementWithoutImageKeyReturnsNull()
        {
            var engagement = new Engagement("testDecisionPoint");

            engagement.Raw = "{\n\t\"transactionID\": 2184799313132298240,\n\t\"trace\": {\n\t\t\"initialState\": {\n\t\t\t\"serverNow\": 1460107947856000,\n\t\t\t\"userCreated\": 1459296000000000,\n\t\t\t\"roeLimited\": false\n\t\t},\n\t\t\"engagements\": [{\n\t\t\t\"engagementID\": 4451,\n\t\t\t\"behaviour\": 0,\n\t\t\t\"silent\": false,\n\t\t\t\"enabled\": true,\n\t\t\t\"parameterCriteria\": [],\n\t\t\t\"metricCriteria\": [],\n\t\t\t\"existingVariant\": 8800,\n\t\t\t\"existingState\": null,\n\t\t\t\"existingStateTimestamp\": null,\n\t\t\t\"existingConverted\": 0,\n\t\t\t\"parameters\": {\n\t\t\t\t\"adShowSession\": true\n\t\t\t}\n\t\t}]\n\t},\n\t\"parameters\": {\n\t\t\"adShowSession\": true,\n\t\t\"adProviders\": [{\n\t\t\t\"adProvider\": \"ADMOB\",\n\t\t\t\"eCPM\": 294,\n\t\t\t\"adUnitId\": \"ca-app-pub-4857093250239318/9840016386\"\n\t\t}],\n\t\t\"adRewardedProviders\": [{\n\t\t\t\"adProvider\": \"UNITY\",\n\t\t\t\"eCPM\": 1060,\n\t\t\t\"gameId\": \"106546\",\n\t\t\t\"testMode\": false\n\t\t}, {\n\t\t\t\"adProvider\": \"ADCOLONY\",\n\t\t\t\"eCPM\": 1323,\n\t\t\t\"appId\": \"appdd80fa453e784901bc\",\n\t\t\t\"clientOptions\": \"version:1.0,store:google\",\n\t\t\t\"zoneId\": \"vzc9a5567db2d447d29a\"\n\t\t}, {\n\t\t\t\"adProvider\": \"CHARTBOOST\",\n\t\t\t\"eCPM\": 38,\n\t\t\t\"appId\": \"56e3e633da15274fc8aa6cbf\",\n\t\t\t\"appSignature\": \"a7f6e1592a33abbcc0ac1e311d0ea1f614fefe7c\",\n\t\t\t\"location\": \"Default\"\n\t\t}, {\n\t\t\t\"adProvider\": \"VUNGLE\",\n\t\t\t\"eCPM\": 4,\n\t\t\t\"appId\": \"961178606\"\n\t\t}],\n\t\t\"adFloorPrice\": 1,\n\t\t\"adMinimumInterval\": 200,\n\t\t\"adMaxPerSession\": 20,\n\t\t\"adMaxPerNetwork\": 1,\n\t\t\"adDemoteOnRequestCode\": 1\n\t}\n}";

            ImageMessage imageMessage = ImageMessage.Create(engagement);

            Assert.IsNull(imageMessage);
        }
示例#11
0
        public void InvalidRawJSON()
        {
            var engagement = new Engagement("testDecisionPoint");

            engagement.Raw = "Not valid JSON";

            Assert.AreEqual("Not valid JSON", engagement.Raw);
            Assert.IsNotNull(engagement.JSON);
            CollectionAssert.IsEmpty(engagement.JSON);
        }
示例#12
0
        public void RequestImageMessage(string decisionPoint, Dictionary <string, object> engageParams, IPopup popup, Action <Dictionary <string, object> > callback)
        {
            var engagement = new Engagement(decisionPoint);

            foreach (var key in engageParams.Keys)
            {
                engagement.AddParam(key, engageParams[key]);
            }
            RequestImageMessage(engagement, popup, callback);
        }
示例#13
0
 internal static RewardedAd CreateUnchecked(Engagement engagement)
 {
     if (engagement != null && engagement.JSON == null)
     {
         return(new RewardedAd(null));
     }
     else
     {
         return(new RewardedAd(engagement));
     }
 }
 internal static InterstitialAd CreateUnchecked(Engagement engagement)
 {
     if (engagement != null && engagement.JSON == null)
     {
         return(new InterstitialAd(null));
     }
     else
     {
         return(new InterstitialAd(engagement));
     }
 }
示例#15
0
        private ImageMessage(JSONObject configuration, string name, int depth, Engagement engagement)
        {
            gameObject = new GameObject(name, typeof(RectTransform));
            SpriteMap spriteMap = gameObject.AddComponent <SpriteMap>();

            spriteMap.Build(configuration);

            this.configuration = configuration;
            this.spriteMap     = spriteMap;
            this.depth         = depth;
            this.engagement    = engagement;
        }
示例#16
0
        override internal void RequestSessionConfiguration()
        {
            Logger.LogDebug("Requesting session configuration");

            var firstSession = PlayerPrefs.HasKey(DDNA.PF_KEY_FIRST_SESSION)
                ? DateTime.ParseExact(
                PlayerPrefs.GetString(DDNA.PF_KEY_FIRST_SESSION),
                Settings.EVENT_TIMESTAMP_FORMAT,
                CultureInfo.InvariantCulture)
                : (DateTime?)null;
            var lastSession = PlayerPrefs.HasKey(DDNA.PF_KEY_LAST_SESSION)
                ? DateTime.ParseExact(
                PlayerPrefs.GetString(DDNA.PF_KEY_LAST_SESSION),
                Settings.EVENT_TIMESTAMP_FORMAT,
                CultureInfo.InvariantCulture)
                : (DateTime?)null;

            Engagement engagement = new Engagement("config")
            {
                Flavour = "internal"
            };

            engagement.AddParam("timeSinceFirstSession", firstSession != null
                         ? ((TimeSpan)(DateTime.UtcNow - firstSession)).TotalMilliseconds
                         : 0);
            engagement.AddParam("timeSinceLastSession", lastSession != null
                         ? ((TimeSpan)(DateTime.UtcNow - lastSession)).TotalMilliseconds
                         : 0);


            if (!String.IsNullOrEmpty(ClientInfo.LanguageCode))
            {
                engagement.AddParam("language", ClientInfo.LanguageCode);
            }

            if (!String.IsNullOrEmpty(ClientInfo.CountryCode))
            {
                engagement.AddParam("country", ClientInfo.CountryCode);
            }

            if (!String.IsNullOrEmpty(ClientInfo.OperatingSystemVersion))
            {
                engagement.AddParam("operatingSystemVersion", ClientInfo.OperatingSystemVersion);
            }

            if (!String.IsNullOrEmpty(ClientInfo.Manufacturer))
            {
                engagement.AddParam("deviceManufacturer", ClientInfo.Manufacturer);
            }

            RequestEngagement(engagement, HandleSessionConfigurationCallback);
        }
示例#17
0
        /// <summary>
        /// Requests game parameters at a <code>decisionPoint</code>.
        /// </summary>
        /// <param name="decisionPoint">the decision point</param>
        /// <param name="parameters">an optional set of real-time parameters</param>
        /// <param name="callback">the callback to handle the result</param>
        /// <exception cref="ArgumentException">if the <code>decisionPoint</code> is null or empty</exception>
        public void RequestGameParameters(string decisionPoint, Params parameters, Action <JSONObject> callback)
        {
            Engagement engagement = BuildEngagement(decisionPoint, parameters);

            ddna.RequestEngagement(engagement,
                                   (response) =>
            {
                callback(response.JSON != null && response.JSON.ContainsKey("parameters") ? response.JSON["parameters"] as JSONObject : new JSONObject());
            }, (exception) =>
            {
                callback(new JSONObject());
            });
        }
示例#18
0
        public void CreateAValidEngagement()
        {
            var engagement = new Engagement("testDecisionPoint");

            Assert.AreEqual("testDecisionPoint", engagement.DecisionPoint);
            Assert.AreEqual("engagement", engagement.Flavour);
            CollectionAssert.AreEquivalent(new Dictionary <string, object>()
            {
                { "decisionPoint", "testDecisionPoint" },
                { "flavour", "engagement" },
                { "parameters", new Dictionary <string, object>() }
            }, engagement.AsDictionary());
        }
示例#19
0
        /// <summary>
        /// Requests an image message at a <code>decisionPoint</code>.
        /// </summary>
        /// <param name="decisionPoint">the decision point</param>
        /// <param name="parameters">an optional set of real-time parameters</param>
        /// <param name="callback">the callback to handle the result</param>
        public void RequestImageMessage(string decisionPoint, Params parameters, Action <ImageMessage> callback)
        {
            Engagement engagement = BuildEngagement(decisionPoint, parameters);

            ddna.RequestEngagement(engagement,
                                   (response) =>
            {
                callback(ImageMessage.Create(response));
            }, (exception) =>
            {
                callback(null);
            });
        }
示例#20
0
        public void OnEngagementBtn_Clicked()
        {
            var engagement = new Engagement("gameLoaded")
                             .AddParam("userLevel", 4)
                             .AddParam("experience", 1000)
                             .AddParam("missionName", "Disco Volante");

            DDNA.Instance.RequestEngagement(engagement, (Dictionary <string, object> response) => {
                popUpContent.text = MiniJSON.Json.Serialize(response);
            });

            popUpTitle.text = "Engage returned";
            popUpObj.SetActive(true);
        }
示例#21
0
        override internal void RequestEngagement(Engagement engagement, Action <Dictionary <string, object> > callback)
        {
            if (!this.started)
            {
                throw new Exception("You must first start the SDK via the StartSDK method.");
            }
            else if (whitelistDps.Count != 0 &&
                     !whitelistDps.Contains(engagement.GetDecisionPointAndFlavour()))
            {
                Logger.LogDebug(string.Format(
                                    "Decision point {0} is not whitelisted",
                                    engagement.GetDecisionPointAndFlavour()));
                engagement.StatusCode = 200;
                engagement.Raw        = "{}";
                callback(engagement.JSON);
                return;
            }

            if (String.IsNullOrEmpty(this.EngageURL))
            {
                throw new Exception("Engage URL not configured.");
            }

            try {
                var dict = engagement.AsDictionary();

                var request = new EngageRequest(dict["decisionPoint"] as string);
                request.Flavour    = dict["flavour"] as string;
                request.Parameters = dict["parameters"] as Dictionary <string, object>;

                EngageResponse handler = (string response, int statusCode, string error) => {
                    JSONObject responseJSON = new JSONObject();
                    if (response != null)
                    {
                        try {
                            responseJSON = DeltaDNA.MiniJSON.Json.Deserialize(response) as JSONObject;
                        } catch (Exception exception) {
                            Logger.LogError("Engagement " + engagement.DecisionPoint + " responded with invalid JSON: " + exception.Message);
                        }
                    }
                    callback(responseJSON);
                };

                StartCoroutine(Engage.Request(ddna, engageCache, request, handler));
            } catch (Exception ex) {
                Logger.LogWarning("Engagement request failed: " + ex.Message);
            }
        }
        public static ImageMessage Create(DDNA ddna, Engagement engagement, JSONObject options)
        {
            if (engagement == null || engagement.JSON == null || !engagement.JSON.ContainsKey("image"))
            {
                return(null);
            }

            string name  = "DeltaDNA Image Message";
            int    depth = 0;

            if (options != null)
            {
                if (options.ContainsKey("name"))
                {
                    name = options["name"] as string;
                }

                if (options.ContainsKey("depth"))
                {
                    depth = (int)options["depth"];
                }
            }

            ImageMessage imageMessage = null;

            try{
                var configuration = engagement.JSON["image"] as JSONObject;
                if (ValidConfiguration(configuration))
                {
                    imageMessage = new ImageMessage(ddna, configuration, name, depth, engagement);
                    if (engagement.JSON.ContainsKey("parameters"))
                    {
                        imageMessage.Parameters = engagement.JSON["parameters"] as JSONObject;
                    }
                }
                else
                {
                    Logger.LogWarning("Invalid image message configuration.");
                }
            }
            catch (Exception exception) {
                Logger.LogWarning("Failed to create image message: " + exception.Message);
            }

            return(imageMessage);
        }
示例#23
0
        override internal void RequestEngagement(Engagement engagement, Action <Engagement> onCompleted, Action <Exception> onError)
        {
            if (!this.started)
            {
                throw new Exception("You must first start the SDK via the StartSDK method.");
            }
            else if (whitelistDps.Count != 0 &&
                     !whitelistDps.Contains(engagement.GetDecisionPointAndFlavour()))
            {
                Logger.LogDebug(string.Format(
                                    "Decision point {0} is not whitelisted",
                                    engagement.GetDecisionPointAndFlavour()));
                engagement.StatusCode = 200;
                engagement.Raw        = "{}";
                onCompleted(engagement);
                return;
            }

            if (String.IsNullOrEmpty(this.EngageURL))
            {
                throw new Exception("Engage URL not configured.");
            }

            try {
                var dict = engagement.AsDictionary();

                var request = new EngageRequest(dict["decisionPoint"] as string);
                request.Flavour    = dict["flavour"] as string;
                request.Parameters = dict["parameters"] as Dictionary <string, object>;

                EngageResponse handler = (string response, int statusCode, string error) => {
                    engagement.Raw        = response;
                    engagement.StatusCode = statusCode;
                    engagement.Error      = error;

                    onCompleted(engagement);
                };

                StartCoroutine(Engage.Request(ddna, engageCache, request, handler));
            } catch (Exception ex) {
                Logger.LogWarning("Engagement request failed: " + ex.Message);
            }
        }
示例#24
0
        public void OnImageMessageBtn_Clicked()
        {
            var engagement = new Engagement("testImageMessage")
                             .AddParam("userLevel", 4)
                             .AddParam("experience", 1000)
                             .AddParam("missionName", "Disco Volante");

            DDNA.Instance.RequestEngagement(engagement, (response) => {
                ImageMessage imageMessage = ImageMessage.Create(response);

                // Check we got an engagement with a valid image message.
                if (imageMessage != null)
                {
                    Debug.Log("Engage returned a valid image message.");

                    // This example will show the image as soon as the background
                    // and button images have been downloaded.
                    imageMessage.OnDidReceiveResources += () => {
                        Debug.Log("Image Message loaded resources.");
                        imageMessage.Show();
                    };

                    // Add a handler for the 'dismiss' action.
                    imageMessage.OnDismiss += (ImageMessage.EventArgs obj) => {
                        Debug.Log("Image Message dismissed by " + obj.ID);
                    };

                    // Add a handler for the 'action' action.
                    imageMessage.OnAction += (ImageMessage.EventArgs obj) => {
                        Debug.Log("Image Message actioned by " + obj.ID + " with command " + obj.ActionValue);
                    };

                    // Download the image message resources.
                    imageMessage.FetchResources();
                }
                else
                {
                    Debug.Log("Engage didn't return an image message.");
                }
            }, (exception) => {
                Debug.Log("Engage reported an error: " + exception.Message);
            });
        }
示例#25
0
        override internal void RequestSessionConfiguration()
        {
            Logger.LogDebug("Requesting session configuration");

            DateTime?firstSession = RetrieveSessionDate(DDNA.PF_KEY_FIRST_SESSION);
            DateTime?lastSession  = RetrieveSessionDate(DDNA.PF_KEY_LAST_SESSION);

            Engagement engagement = new Engagement("config")
            {
                Flavour = "internal"
            };

            engagement.AddParam("timeSinceFirstSession", firstSession != null
                         ? ((TimeSpan)(DateTime.UtcNow - firstSession)).TotalMilliseconds
                         : 0);
            engagement.AddParam("timeSinceLastSession", lastSession != null
                         ? ((TimeSpan)(DateTime.UtcNow - lastSession)).TotalMilliseconds
                         : 0);


            if (!String.IsNullOrEmpty(ClientInfo.LanguageCode))
            {
                engagement.AddParam("language", ClientInfo.LanguageCode);
            }

            if (!String.IsNullOrEmpty(ClientInfo.CountryCode))
            {
                engagement.AddParam("country", ClientInfo.CountryCode);
            }

            if (!String.IsNullOrEmpty(ClientInfo.OperatingSystemVersion))
            {
                engagement.AddParam("operatingSystemVersion", ClientInfo.OperatingSystemVersion);
            }

            if (!String.IsNullOrEmpty(ClientInfo.Manufacturer))
            {
                engagement.AddParam("deviceManufacturer", ClientInfo.Manufacturer);
            }

            RequestEngagement(engagement, HandleSessionConfigurationCallback);
        }
示例#26
0
        public void RequestImageMessage(Engagement engagement, IPopup popup, Action <Dictionary <string, object> > callback)
        {
            Action <Dictionary <string, object> > imageCallback = (response) =>
            {
                if (response != null)
                {
                    if (response.ContainsKey("image"))
                    {
                        var image = response["image"] as Dictionary <string, object>;
                        popup.Prepare(image);
                    }
                    if (callback != null)
                    {
                        callback(response);
                    }
                }
            };

            RequestEngagement(engagement, imageCallback);
        }
示例#27
0
        public void ValidRawJSON()
        {
            var engagement = new Engagement("testDecisionPoint");

            engagement.Raw = "{\"x\": 1,\"y\": \"Hello\",\"z\": [{\"1\": \"a\"}]}";

            Assert.IsNotNull(engagement.JSON);
            CollectionAssert.IsNotEmpty(engagement.JSON);
            CollectionAssert.AreEquivalent(new Dictionary <string, object>()
            {
                { "x", 1 },
                { "y", "Hello" },
                { "z", new List <object>()
                  {
                      new Dictionary <string, object>()
                      {
                          { "1", "a" }
                      }
                  } }
            }, engagement.JSON);
        }
示例#28
0
        public void CreateAValidEngagementWithExtraParameters()
        {
            var engagement = new Engagement("testDecisionPoint");

            engagement.AddParam("A", 1);
            engagement.AddParam("B", "two");
            engagement.AddParam("C", true);

            Assert.AreEqual("testDecisionPoint", engagement.DecisionPoint);
            Assert.AreEqual("engagement", engagement.Flavour);
            CollectionAssert.AreEquivalent(new Dictionary <string, object>()
            {
                { "decisionPoint", "testDecisionPoint" },
                { "flavour", "engagement" },
                { "parameters", new Dictionary <string, object>()
                  {
                      { "A", 1 },
                      { "B", "two" },
                      { "C", true }
                  } }
            }, engagement.AsDictionary());
        }
示例#29
0
        public void CreateWithValidEngagement()
        {
            var engagement = new Engagement("testDecisionPoint");

            engagement.Raw = "{\"transactionID\":2184816393350012928,\"image\":{\"width\":512,\"height\":256,\"format\":\"png\",\"spritemap\":{\"background\":{\"x\":2,\"y\":38,\"width\":319,\"height\":177},\"buttons\":[{\"x\":2,\"y\":2,\"width\":160,\"height\":34},{\"x\":323,\"y\":180,\"width\":157,\"height\":35}]},\"layout\":{\"landscape\":{\"background\":{\"contain\":{\"halign\":\"center\",\"valign\":\"center\",\"left\":\"10%\",\"right\":\"10%\",\"top\":\"10%\",\"bottom\":\"10%\"},\"action\":{\"type\":\"none\",\"value\":\"\"}},\"buttons\":[{\"x\":-1,\"y\":144,\"action\":{\"type\":\"dismiss\",\"value\":\"\"}},{\"x\":160,\"y\":143,\"action\":{\"type\":\"action\",\"value\":\"reward\"}}]}},\"shim\":{\"mask\":\"dimmed\",\"action\":{\"type\":\"none\"}},\"url\":\"http://download.deltadna.net/engagements/3eef962b51f84f9ca21643ca21fb3057.png\"},\"parameters\":{\"rewardName\":\"wrench\"}}";

            Assert.IsNotNull(engagement.JSON);
            Assert.Contains("image", engagement.JSON.Keys);
            Assert.Contains("parameters", engagement.JSON.Keys);

            ImageMessage imageMessage = ImageMessage.Create(engagement);

            Assert.IsNotNull(imageMessage);

            Assert.That(!imageMessage.IsReady());
            Assert.That(!imageMessage.IsShowing());

            Assert.IsNotNull(imageMessage.Parameters);
            Assert.AreEqual(imageMessage.Parameters, new System.Collections.Generic.Dictionary <string, object>()
            {
                { "rewardName", "wrench" }
            });
        }
示例#30
0
        /// <summary>
        /// Makes an Engage request.  The result of the engagement will be passed as a dictionary object to your callback method. The dictionary
        /// will be empty if engage couldn't be reached on a campaign is not running.
        /// A cache is maintained that will return the last valid response if available.
        /// </summary>
        /// <param name="engagement">The engagement the request is for.</param>
        /// <param name="callback">Method called with the response from Engage.</param>
        /// <exception cref="System.Exception">Thrown if the SDK has not been started, and if the Engage URL has not been set.</exception>
        public void RequestEngagement(Engagement engagement, Action <Dictionary <string, object> > callback)
        {
            if (!this.started)
            {
                throw new Exception("You must first start the SDK via the StartSDK method.");
            }

            if (String.IsNullOrEmpty(this.EngageURL))
            {
                throw new Exception("Engage URL not configured.");
            }

            try {
                var dict = engagement.AsDictionary();

                var request = new EngageRequest(dict["decisionPoint"] as string);
                request.Flavour    = dict["flavour"] as string;
                request.Parameters = dict["parameters"] as Dictionary <string, object>;

                EngageResponse handler = (string response, int statusCode, string error) => {
                    JSONObject responseJSON = new JSONObject();
                    if (response != null)
                    {
                        try {
                            responseJSON = DeltaDNA.MiniJSON.Json.Deserialize(response) as JSONObject;
                        } catch (Exception exception) {
                            Logger.LogError("Engagement " + engagement.DecisionPoint + " responded with invalid JSON: " + exception.Message);
                        }
                    }
                    callback(responseJSON);
                };

                StartCoroutine(Engage.Request(this, request, handler));
            } catch (Exception ex) {
                Logger.LogWarning("Engagement request failed: " + ex.Message);
            }
        }