示例#1
0
 private static JToken CreateJValueParentsIfNeeded(this FieldView self, JToken currentLevel)
 {
     if (self.IsInChildObject())   // Navigate down to the correct child JObject
     {
         string[] parents = self.fullPath.Split(".");
         for (int i = 0; i < parents.Length - 1; i++)
         {
             string fieldName = parents.ElementAt(i);
             var    child     = GetChildJToken(currentLevel, fieldName);
             if (child == null)
             {
                 if (int.TryParse(parents.ElementAt(i + 1), out int _))
                 {
                     currentLevel[fieldName] = new JArray();
                 }
                 else
                 {
                     currentLevel[fieldName] = new JObject();
                 }
             }
             currentLevel = child;
             AssertV2.IsNotNull(currentLevel, $"rootModel (p='{fieldName}', child={child}");
         }
     }
     return(currentLevel);
 }
示例#2
0
        public virtual async Task <long> GetCurrentPing(string ipOrUrl = "8.8.8.8", int timeoutInMs = 500)
        {
            PingReply pingReply = await new Ping().SendPingAsync(ipOrUrl, timeoutInMs);

            AssertV2.IsNotNull(pingReply, "result");
            return(pingReply.RoundtripTime); // return ping in MS
        }
示例#3
0
 public ProgressionSystem(LocalAnalytics analytics, FeatureFlagManager <T> featureFlagManager)
 {
     // Make sure the FeatureFlag system was set up too:
     AssertV2.IsNotNull(FeatureFlagManager <T> .instance, "FeatureFlagManager.instance");
     this.analytics          = analytics;
     this.featureFlagManager = featureFlagManager;
 }
示例#4
0
        public async Task <GameObject> NewViewFromSchema(JsonSchema schema, JsonSchemaToView generator)
        {
            AssertV2.IsNotNull(schema, "schema");
            AssertV2.IsNotNull(generator, "generator");
            if (schema.properties == null)
            {
                AssertV2.IsFalse(generator.schemaGenerator.schemas.IsNullOrEmpty(), "generator.schema dict is emtpy!");
                if (generator.schemaGenerator.schemas.TryGetValue(schema.modelType, out JsonSchema vm))
                {
                    schema = vm;
                }
                else
                {
                    Log.e($"No Schema found for schema.modelType={schema.modelType}");
                }
            }
            AssertV2.IsNotNull(schema.properties, "schema.properties");
            GameObject rootContainerView = await generator.NewRootContainerView(rootPrefabName);

            rootContainerView.GetComponentInChildren <FieldView>().field = schema;
            var innerContainer = await generator.SelectInnerViewContainerFromObjectFieldView(rootContainerView);

            await generator.ObjectJsonSchemaToView(schema, innerContainer);

            return(rootContainerView);
        }
示例#5
0
        /// <summary> Connects a model with a view </summary>
        /// <returns> A task that can be awaited on, that returns the fully setup presenter </returns>
        public static async Task <Presenter <T> > LoadModelIntoView <T>(this Presenter <T> self, T model)
        {
            AssertV2.IsNotNull(self.targetView, "presenter.targetView");
            await self.OnLoad(model);

            return(self);
        }
示例#6
0
        public NewsManager newsManager; // protected because its accessed by the list entries

        public async Task LoadNews()
        {
            AssertV2.IsNotNull(newsManager, "newsManager");
            var allNews = showOnlyUnread ? await newsManager.GetAllUnreadNews() : await newsManager.GetAllNews();

            this.CellData = allNews.ToList(); // This will trigger showing the list entries
        }
示例#7
0
        public virtual async Task <long> GetCurrentPing(string ipOrUrl = "8.8.8.8", int timeoutInMs = DEFAULT_PING_TIMEOUT)
        {
            PingReply pingReply = await new Ping().SendPingAsync(ipOrUrl, timeoutInMs);

            AssertV2.IsNotNull(pingReply, "pingReply");
            if (pingReply.Status != IPStatus.Success)
            {
                throw new TimeoutException("Ping failed: " + pingReply.Status);
            }
            return(pingReply.RoundtripTime); // return ping in MS
        }
示例#8
0
        private void LoadImageFromUrl(Image targetImage, string urlToLoad)
        {
            AssertV2.IsNotNull(targetImage, "targetImage");
            var isUrlEmpty = urlToLoad.IsNullOrEmpty();

            targetImage.gameObject.GetParent().SetActiveV2(!isUrlEmpty);
            if (!isUrlEmpty)
            {
                targetImage.LoadFromUrl(urlToLoad).OnError(LogImageLoadError);
            }
        }
 private static bool JsonCouldBeFullyParsed(IJsonReader jsonReader, IJsonWriter jsonWriter, object result, string json)
 {
     try {
         AssertV2.IsFalse(string.IsNullOrEmpty(json), "Json isNullOrEmpty");
         var input  = jsonReader.Read <System.Collections.Generic.Dictionary <string, object> >(json);
         var parsed = jsonReader.Read <System.Collections.Generic.Dictionary <string, object> >(jsonWriter.Write(result));
         AssertV2.IsNotNull(parsed, "parsed");
         return(JsonCouldBeFullyParsed(jsonReader, result.GetType().Name, input, parsed, 0));
     } catch (Exception e) { Log.e(new Exception("exception during parsing json=" + json, e)); }
     return(false);
 }
示例#10
0
        public Task <long> GetCurrentPing(string domainToPing = "8.8.8.8", int timeoutInMs = 500)
        {
            Task <PingReply> pingTask = new Ping().SendPingAsync(domainToPing, timeoutInMs);

            AssertV2.IsNotNull(pingTask, "ping");
            return(pingTask.ContinueWith(finishedPingTask => {
                var pingReply = finishedPingTask.Result;
                AssertV2.IsNotNull(pingReply, "result");
                return pingReply.RoundtripTime;
            })); // return ping in MS
        }
示例#11
0
 private IProgress ProgressInjectionRequest(object caller, bool createIfNull)
 {
     AssertV2.IsNotNull(caller, "caller");
     if (caller is string id)
     {
         return(GetOrAddProgress(id, 0, createIfNull));
     }
     if (caller is KeyValuePair <string, double> p)
     {
         return(GetOrAddProgress(p.Key, p.Value, createIfNull));
     }
     throw new ArgumentException($"Cant handle caller='{caller}'");
 }
示例#12
0
 private void OnEnable()
 {
     if (scaler == null)
     {
         scaler = GetComponent <CanvasScalerV2>();
     }
     if (es == null)
     {
         es = EventSystem.current;
     }
     AssertV2.IsNotNull(scaler, "No CanvasScalerV2 assigned");
     AssertV2.IsNotNull(es, "No event system found in scene");
 }
 private static bool JsonCouldBeFullyParsed(IJsonReader reader, string path, IDictionary input, IDictionary parsed, int depth)
 {
     if (depth > MAX_DEPTH)
     {
         Log.e("Deth > " + MAX_DEPTH + ", will abort recursive search on this level, path=" + path); return(false);
     }
     foreach (var f in input)
     {
         var field = (DictionaryEntry)f;
         var key   = field.Key;
         var value = field.Value;
         //Assert.IsTrue(field != null);
         value = JsonReader.convertToGenericDictionaryOrArray(value);
         if (value != null && !parsed.Contains(key))
         {
             var infoStringAboutField = "field " + path + "." + key + " = " + value;
             if (value != null)
             {
                 infoStringAboutField += ", value type=(" + value.GetType() + ")";
             }
             var args = new StackFrame(5 + depth, true).AddTo(null);
             Log.e(" > Missing " + infoStringAboutField, args);
             return(false);
         }
         else if (value is IDictionary)
         {
             var a = value as IDictionary;
             var valueInParsedDict = JsonReader.convertToGenericDictionaryOrArray(parsed[key]);
             var b    = valueInParsedDict as IDictionary;
             var args = new StackFrame(5 + depth, true).AddTo(null);
             AssertV2.IsNotNull(b, "Field was found but it was not a JsonObject, it was a " + valueInParsedDict.GetType(), args);
             return(JsonCouldBeFullyParsed(reader, path + "." + key, a, b, depth + 1));
         }
         else if (value is IDictionary[])
         {
             var a = value as IDictionary[];
             var valueInParsedArray = JsonReader.convertToGenericDictionaryOrArray(parsed[key]);
             var b    = valueInParsedArray as IDictionary[];
             var args = new StackFrame(5 + depth, true).AddTo(null);
             AssertV2.IsNotNull(b, "Field was found but it was not a JsonArray, it was a " + valueInParsedArray.GetType(), args);
             AssertV2.AreEqual(a.Length, b.Length, "", args);
             var r = true;
             for (int i = 0; i < a.Length; i++)
             {
                 r = JsonCouldBeFullyParsed(reader, path + "." + key + "[" + i + "]", a[i], b[i], depth + 1) & r;
             }
             return(r);
         }
     }
     return(true);
 }
示例#14
0
 internal virtual int SortMenuEntries(Entry x, Entry y)
 {
     AssertV2.IsNotNull(x, "ActionMenu.Entry x");
     AssertV2.IsNotNull(y, "ActionMenu.Entry y");
     if (x.isFavorite == y.isFavorite)
     {
         return(0);
     }
     if (x.isFavorite && !y.isFavorite)
     {
         return(-1);
     }
     return(1);
 }
示例#15
0
 private async Task <T> ReturnInitializedFlag(T flag)
 {
     if (flag != null)
     {
         AssertV2.IsNotNull(flag.localState, "flag.localState");
         if (flag.localState.randomPercentage == 0)
         {
             // if the server decided its a staged rollout no rnd % generated yet so do it:
             flag.localState.randomPercentage = new Random().Next(1, 100);
             await featureFlagStore.Set(flag.id, flag); // save in local store
         }
     }
     return(flag);
 }
示例#16
0
        public async Task <T> GetResult <T>()
        {
            waitForRequestToBeConfigured.TrySetResult(true);
            HttpResponseMessage resp = await request;

            if (typeof(T).IsCastableTo <Exception>() && resp.StatusCode.IsErrorStatus())
            {
                return((T)(object)new NoSuccessError(resp.StatusCode, await GetResult <string>()));
            }
            if (HttpStatusCode.OK != resp.StatusCode)
            {
                Log.w("response.StatusCode=" + resp.StatusCode);
            }
            if (TypeCheck.AreEqual <T, HttpResponseMessage>())
            {
                return((T)(object)resp);
            }
            if (TypeCheck.AreEqual <T, HttpStatusCode>())
            {
                return((T)(object)resp.StatusCode);
            }
            if (TypeCheck.AreEqual <T, Headers>())
            {
                return((T)(object) await GetResultHeaders());
            }
            HttpContent content = resp.Content;

            if (TypeCheck.AreEqual <T, HttpContent>())
            {
                return((T)(object)content);
            }
            if (TypeCheck.AreEqual <T, Stream>())
            {
                return((T)(object)await content.ReadAsStreamAsync());
            }
            if (TypeCheck.AreEqual <T, byte[]>())
            {
                return((T)(object)await content.ReadAsByteArrayAsync());
            }
            var respText = await content.ReadAsStringAsync();

            if (typeof(T) == typeof(string))
            {
                return((T)(object)respText);
            }
            AssertV2.IsNotNull(respText, "respText");
            AssertV2.IsNotNull(respText.IsNullOrEmpty(), "respText.IsNullOrEmpty");
            try { return(jsonReader.Read <T>(respText)); } catch (JsonReaderException e) { throw new JsonReaderException("Cant parse to JSON: " + respText, e); }
        }
示例#17
0
        public bool TryGetColor(string colorName, out Color c)
        {
            c = Color.clear;
            if (colors.IsNullOrEmpty())
            {
                return(false);
            }
            AssertV2.IsNotNull(colorName, "colorName");
            AssertV2.IsFalse(colors.IsNullOrEmpty(), "colors.IsNullOrEmpty");
            var namedColor = colors.FirstOrDefault(x => x.colorName == colorName);

            if (namedColor != null)
            {
                c = namedColor.colorValue; return(true);
            }
            return(false);
        }
示例#18
0
        public static async Task LoadModelList(this ListFieldView self, JObject root, JsonSchemaToView viewGenerator)
        {
            JArray modelArray = self.GetFieldJModel(root) as JArray;

            AssertV2.IsNotNull(modelArray, "modelArray");
            var map = new Dictionary <FieldView, JToken>();

            for (int i = 0; i < modelArray.Count; i++)
            {
                var    fieldName = "" + i;
                JToken entry     = modelArray[i];
                var    fv        = await CreateChildEntryView(self, root, viewGenerator, entry, fieldName);

                map.Add(fv, entry);
            }
            SetupButtons(self, root, viewGenerator, modelArray, map);
        }
示例#19
0
        public async Task <T> GetResult <T>()
        {
            HttpResponseMessage resp = await request;

            if (typeof(T).IsCastableTo <Exception>() && resp.StatusCode.IsErrorStatus())
            {
                return((T)(object)new NoSuccessError(resp.StatusCode, await GetResult <string>()));
            }
            AssertV2.IsTrue(HttpStatusCode.OK == resp.StatusCode, "response.StatusCode=" + resp.StatusCode);
            if (TypeCheck.AreEqual <T, HttpResponseMessage>())
            {
                return((T)(object)resp);
            }
            if (TypeCheck.AreEqual <T, HttpStatusCode>())
            {
                return((T)(object)resp.StatusCode);
            }
            if (TypeCheck.AreEqual <T, Headers>())
            {
                return((T)(object) await GetResultHeaders());
            }
            HttpContent content = resp.Content;

            if (TypeCheck.AreEqual <T, HttpContent>())
            {
                return((T)(object)content);
            }
            if (TypeCheck.AreEqual <T, Stream>())
            {
                return((T)(object)await content.ReadAsStreamAsync());
            }
            if (TypeCheck.AreEqual <T, byte[]>())
            {
                return((T)(object)await content.ReadAsByteArrayAsync());
            }
            var respText = await content.ReadAsStringAsync();

            if (typeof(T) == typeof(string))
            {
                return((T)(object)respText);
            }
            AssertV2.IsNotNull(respText, "respText");
            AssertV2.IsNotNull(respText.IsNullOrEmpty(), "respText.IsNullOrEmpty");
            return(jsonReader.Read <T>(respText));
        }
示例#20
0
        protected override void OnActiveToggleInGroupChanged2(IEnumerable <Toggle> activeToggles)
        {
            AssertV2.IsNotNull(targetTabsPanel, "TargetTabsPanel");
            var activeToggle = activeToggles.Single();
            var link         = activeToggle.GetComponent <Link>();

            AssertV2.IsNotNull(link, "Link component for toggle " + activeToggle, activeToggle);
            string prefabNameOfNewView = onTabRequested(link.id);

            if (!prefabNameOfNewView.IsNullOrEmpty())
            {
                ExchangeTabInPanel(targetTabsPanel, prefabNameOfNewView);
            }
            else
            {
                onCustomTabClickAction(link.id, targetTabsPanel);
            }
        }
示例#21
0
        private async Task ShowModelInstanceInView()
        {
            // Get the previously created view (see above)
            var uiView = gameObject.GetChild(0);

            AssertV2.IsNotNull(uiView, "uiView");
            // Create some example model instance:
            var modelInstance = Ui18_1_JsonSchemaUiGenerator.NewExampleUserInstance();

            JsonSchemaPresenter p = new JsonSchemaPresenter(JsonSchemaToView.NewViewGenerator());

            p.targetView = uiView;
            var changedInstance = await p.LoadViaJsonIntoView(modelInstance);

            uiView.Destroy(); // Close the view by destroying it after the user done with it

            var changedFields = MergeJson.GetDiff(modelInstance, changedInstance);

            Log.d("Fields changed: " + changedFields?.ToPrettyString());
        }
示例#22
0
        public override IEnumerator RunTest()
        {
            var testTracker = new TestAppFlowTracker();

            testTracker.WithAllTrackingActive();
            AppFlow.AddAppFlowTracker(testTracker);

            setupImmutableDatastore();
            // In setupImmutableDatastore() Log.MethodEntered is used, so there must be a recorded method:
            AssertV2.AreEqual(1, testTracker.recordedEvents.Count(x => x.category == EventConsts.catMethod));
            // In setupImmutableDatastore() the datastore will be set as a singleton:
            AssertV2.AreEqual(1, testTracker.recordedEvents.Count(x => x.action.Contains("DataStore")));

            var store = MyDataModel.GetStore();

            AssertV2.IsNotNull(store, "store");
            store.Dispatch(new ActionSetBool1()
            {
                newB = true
            });
            store.Dispatch(new ActionSetString1 {
                newS = "abc"
            });
            AssertV2.AreEqual(true, store.GetState().subSection1.bool1);
            AssertV2.AreEqual("abc", store.GetState().subSection1.string1);
            // After the 2 mutations, there should be 2 mutation AppFlow events recorded:
            AssertV2.AreEqual(2, testTracker.recordedEvents.Count(x => x.category == EventConsts.catMutation));

            var presenter = new MyDataModelPresenter();

            presenter.targetView = gameObject;
            yield return(presenter.LoadModelIntoView(store).AsCoroutine());

            // After the presenter loaded the UI there should be a load start and load end event recorded:
            AssertV2.AreEqual(2, testTracker.recordedEvents.Count(x => x.category == EventConsts.catPresenter));
            // The MyDataModelPresenter uses a GetLinkMap() when connecting to the view:
            AssertV2.AreEqual(1, testTracker.recordedEvents.Count(x => x.category == EventConsts.catLinked));

            yield return(new WaitForSeconds(1));
        }
        public static bool LogAnyDiffToNewFieldViews(this Dictionary <string, FieldView> self, Dictionary <string, FieldView> newFieldViews)
        {
            // First compare all field views that are found both in the list of old and new views and print out the changes:
            self.CheckIntersectingFieldViewsForChanges(newFieldViews, (oldFieldView, newFieldView, _) => {
                AssertV2.IsNotNull(oldFieldView.field, "oldFieldView.field");
                AssertV2.IsNotNull(newFieldView.field, "newFieldView.field");
                var diff = MergeJson.GetDiff(oldFieldView.field, newFieldView.field);
                if (!diff.IsNullOrEmpty())
                {
                    Log.e($"Detected changed field view '{oldFieldView.fullPath}' that needs UI update! " +
                          $"Detected changes: {diff.ToPrettyString()}", oldFieldView.gameObject);
                }
            });

            // Second the list of views that have to be removed from the old UI is listed (and auto deleted if desired):
            foreach (var removed in self.GetOutdatedFieldViewsToDelete(newFieldViews))
            {
                Log.e($"The field '{removed.Key}' was removed from the model and HAS TO BE DELETED from the UI", removed.Value.gameObject);
            }

            // Finally check if there are any missing views in the old UI that have to be manually added (picked from the new UI):
            return(self.FindNewFieldViewsAddedIn(newFieldViews));
        }
示例#24
0
 /// <summary> Since the rootFieldView.properties are not correctly serialized by unity, this Dictionary has to be reconstructed from the
 /// FieldViews in the children GameObjects.So first fill the properties of the rootFieldView again with the fields of the
 /// direct children GameObjects.And do this recursively for all found ObjectFieldViews </summary>
 private static void RestorePropertiesFromChildrenGOs(ObjectFieldView targetFieldView)
 {
     AssertV2.IsNotNull(targetFieldView, "targetFieldView");
     if (targetFieldView.field.properties.IsNullOrEmpty())
     {
         var children = targetFieldView.mainLink.gameObject.GetChildren().Map(c => c.GetComponent <FieldView>()).Filter(x => x != null);
         if (children.IsNullOrEmpty())
         {
             Log.w(targetFieldView.fieldName + " had no children fieldViews");
         }
         else
         {
             foreach (var vm in children.OfType <ObjectFieldView>())
             {
                 RestorePropertiesFromChildrenGOs(vm);
             }
             var fieldDict = children.ToDictionary(x => x.fieldName, x => x.field);
             if (!fieldDict.IsNullOrEmpty())
             {
                 targetFieldView.field.properties = fieldDict;
             }
         }
     }
 }
示例#25
0
 private void Start()
 {
     AssertV2.IsNotNull(field, "field", gameObject);
     AssertV2.IsNotNull(menuOnClickVisibilityToggle, "menuOnClickVisibilityToggle", gameObject);
     CreateMenuEntryUis();
 }
示例#26
0
        public virtual JsonSchema NewField(string name, Type parentType, object pInstance = null, JToken jpInstance = null)
        {
            MemberInfo model      = parentType?.GetMember(name).First();
            Type       modelType  = GetModelType(model);
            JTokenType jTokenType = ToJTokenType(modelType, jpInstance);

            AssertV2.IsNotNull(jTokenType, "jTokenType");
            JsonSchema newField = new JsonSchema()
            {
                type = jTokenType.ToJsonSchemaType(), title = JsonSchema.ToTitle(name)
            };

            ExtractFieldDocu(newField, model, modelType, jTokenType, pInstance, jpInstance);
            if (model != null)
            {
                if (!model.CanWriteTo())
                {
                    newField.readOnly = true;
                }
                if (model.TryGetCustomAttribute(out RegexAttribute attr))
                {
                    newField.pattern = attr.regex;
                }
                if (model.TryGetCustomAttribute(out ContentAttribute c))
                {
                    newField.format = "" + c.type;
                }
                if (model.TryGetCustomAttribute(out MinMaxRangeAttribute ra))
                {
                    newField.minimum = ra.minimum;
                    newField.maximum = ra.maximum;
                }
                if (model.TryGetCustomAttribute(out InputLengthAttribute ila))
                {
                    if (ila.minLength > 0)
                    {
                        newField.minLength = ila.minLength;
                    }
                    if (ila.maxLength > 0)
                    {
                        newField.maxLength = ila.maxLength;
                    }
                }
                if (model.TryGetCustomAttribute(out EnumAttribute e))
                {
                    newField.contentEnum     = e.names;
                    newField.additionalItems = e.allowOtherInput;
                }
                if (model.TryGetCustomAttribute(out RequiredAttribute r))
                {
                    newField.mandatory = true;
                }
                if (model.TryGetCustomAttribute(out JsonPropertyAttribute p))
                {
                    if (p.Required == Required.Always || p.Required == Required.DisallowNull)
                    {
                        newField.mandatory = true;
                    }
                }

                if (modelType.IsEnum)
                {
                    newField.contentEnum = Enum.GetNames(modelType);
                }
            }
            if (jTokenType == JTokenType.Object)
            {
                if (modelType == null)
                {
                    newField.properties = new Dictionary <string, JsonSchema>();
                    AddFieldsViaJson(newField, null, jpInstance as JObject);
                }
                else
                {
                    var modelInstance = pInstance != null?model.GetValue(pInstance) : null;

                    SetupInnerJsonSchema(newField, modelType, modelInstance);
                }
            }
            if (jTokenType == JTokenType.Array)
            {
                var listElemType   = GetListElementType(modelType);
                var arrayElemJType = ToJTokenType(listElemType);
                if (arrayElemJType == JTokenType.Null)
                {
                    if (jpInstance is JArray a && a.Count > 0)
                    {
                        arrayElemJType = a.First.Type;
                    }
                }
                if (arrayElemJType != JTokenType.Null)
                {
                    if (!IsSimpleType(arrayElemJType))
                    {
                        var childrenInstances = GetChildrenArray(pInstance, jpInstance, model);
                        if (childrenInstances == null || AllChildrenHaveSameType(childrenInstances))
                        {
                            var firstChildInstance = childrenInstances?.FirstOrDefault();
                            var childVm            = new JsonSchema()
                            {
                                type = arrayElemJType.ToJsonSchemaType()
                            };
                            SetupInnerJsonSchema(childVm, listElemType, firstChildInstance);
                            newField.items = new List <JsonSchema>()
                            {
                                childVm
                            };
                        }
                        else
                        {
                            newField.items = new List <JsonSchema>();
                            foreach (var child in childrenInstances)
                            {
                                var childVm = new JsonSchema()
                                {
                                    type = arrayElemJType.ToJsonSchemaType()
                                };
                                SetupInnerJsonSchema(childVm, child.GetType(), child);
                                newField.items.Add(childVm);
                            }
                            AssertV2.AreEqual(childrenInstances.Length, newField.items.Count);
                        }
                    }
                    else
                    {
                        newField.items = new List <JsonSchema>()
                        {
                            new JsonSchema()
                            {
                                type = arrayElemJType.ToJsonSchemaType()
                            }
                        };
                    }
                }
            }
            return(newField);
        }