public static JsonObject ToJson(Dominion.GameDescription gameDescription, int starRating)
        {
            JsonObject root = new Windows.Data.Json.JsonObject();

            root.Add(jsonNameDeck, ToJson(gameDescription));

            JsonArray expansionArray = new JsonArray();
            Dominion.Expansion[] presentExpansions;
            Dominion.Expansion[] missingExpansions;
            gameDescription.GetRequiredExpansions(out presentExpansions, out missingExpansions);

            foreach (var expansion in presentExpansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(true));
                expansionArray.Add(expansionObject);
            }

            foreach (var expansion in missingExpansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(false));
                expansionArray.Add(expansionObject);
            }

            root.Add(jsonNameRequiredExpansions, expansionArray);

            root.Add(jsonNameRating, JsonValue.CreateNumberValue(starRating));

            return root;
        }
Example #2
0
    private void CreateJsonTest()
    {
        JsonArray weekDiet = new JsonArray();
        for(int i=0;i<7;i++)
        {
            JsonObject diet = new JsonObject();
            diet["DayNumber"] = i;
            diet["Breakfast"] = "Banana"+ i;
            diet["Lunch"] = "Banana"+ i;
            diet["Dinner"] = "Banana"+ i;
            diet["WithSugar"] = (i % 2 == 0);
            diet["RandomNumber"] = Random.Range(0f,1.5f);

            weekDiet.Add(diet);
        }

        for (int i=0;i<7;i++)
        {
            if (i % 2 == 1)
            {
                weekDiet[i]["RandomNumber"] = 3;
                weekDiet[i]["RandomNumber"] = weekDiet[i]["RandomNumber"] * 2f;
            }
        }

        Debug.Log("Test InputOutputFileTest done: \n"+ weekDiet.ToJsonPrettyPrintString());
    }
Example #3
0
        public async Task<string> Search(string search)
        {
            using (AutoResetEvent handle = new AutoResetEvent(false))
            {
                JsonObject message = new JsonObject();
                message.Add("method", JsonValue.CreateStringValue("core.library.search"));

                JsonObject queryObject = new JsonObject();
                queryObject.Add("track_name", JsonValue.CreateStringValue(search));

                JsonArray urisArray = new JsonArray();
                urisArray.Add(JsonValue.CreateStringValue("spotify:"));

                JsonObject paramsObject = new JsonObject();
                paramsObject.Add("query", queryObject);
                paramsObject.Add("uris", urisArray);

                message.Add("params", paramsObject);

                string result = null;
                await Send(message, searchResult =>
                {
                    JsonArray tracks = searchResult.GetNamedArray("result")[0].GetObject().GetNamedArray("tracks");
                    result = tracks.First().GetObject().GetNamedString("uri");

                    handle.Set();
                });

                handle.WaitOne(TimeSpan.FromSeconds(30));
                return result;
            }
        }
Example #4
0
        public JsonValue GetAll()
        {
            JsonObject parameters = WebOperationContext.Current.IncomingRequest.GetQueryStringAsJsonObject();

            JsonValue term;
            string termValue = parameters.TryGetValue("term", out term) ? term.ReadAs<string>() : String.Empty;

            using (SqlConnection sc = new SqlConnection(connectionString))
            {
                sc.Open();
                using (SqlCommand getAll = new SqlCommand("SELECT Email FROM Contact WHERE (Email LIKE @term)", sc))
                {
                    getAll.Parameters.AddWithValue("@term", termValue + "%");
                    SqlDataReader reader = getAll.ExecuteReader();

                    JsonArray results = new JsonArray();
                    while (reader.Read())
                    {
                        results.Add(Convert.ToString(reader[0], CultureInfo.InvariantCulture));
                    }

                    return results;
                }
            }
        }
 public void GetCategoryInfo(HttpContext context)
 {
     Func<Maticsoft.Model.SNS.Categories, bool> predicate = null;
     string categoryId = context.Request.Params["CID"];
     int type = Globals.SafeInt(context.Request.Params["Type"], 0);
     JsonObject obj2 = new JsonObject();
     if (!string.IsNullOrWhiteSpace(categoryId))
     {
         if (predicate == null)
         {
             predicate = c => c.ParentID == Globals.SafeInt(categoryId, 0);
         }
         List<Maticsoft.Model.SNS.Categories> list2 = this.SNSCateBll.GetAllCateByCache(type).Where<Maticsoft.Model.SNS.Categories>(predicate).ToList<Maticsoft.Model.SNS.Categories>();
         if ((list2 != null) && (list2.Count > 0))
         {
             JsonArray data = new JsonArray();
             list2.ForEach(delegate (Maticsoft.Model.SNS.Categories info) {
                 data.Add(new JsonObject(new string[] { "CategoryId", "Name", "ParentID", "HasChildren" }, new object[] { info.CategoryId, info.Name, info.ParentID, info.HasChildren }));
             });
             obj2.Put("STATUS", "Success");
             obj2.Put("DATA", data);
         }
         else
         {
             obj2.Put("STATUS", "Fail");
         }
     }
     else
     {
         obj2.Put("STATUS", "Error");
     }
     context.Response.Write(obj2.ToString());
 }
        public string Stringify()
        {
            JsonArray jsonArray = new JsonArray();
            foreach (School school in Education)
            {
                jsonArray.Add(school.ToJsonObject());
            }

            JsonObject jsonObject = new JsonObject();
            jsonObject[idKey] = JsonValue.CreateStringValue(Id);

            // Treating a blank string as null
            if (String.IsNullOrEmpty(Phone))
            {
                jsonObject[phoneKey] = JsonValue.CreateNullValue();
            }
            else
            {
                jsonObject[phoneKey] = JsonValue.CreateStringValue(Phone);
            }

            jsonObject[nameKey] = JsonValue.CreateStringValue(Name);
            jsonObject[educationKey] = jsonArray;
            jsonObject[timezoneKey] = JsonValue.CreateNumberValue(Timezone);
            jsonObject[verifiedKey] = JsonValue.CreateBooleanValue(Verified);

            return jsonObject.Stringify();
        }
Example #7
0
 private static JsonArray serializeArray(IEnumerable arr)
 {
     Type elType;
     JsonArray array = new JsonArray();
     foreach (var el in arr)
     {
         elType = el.GetType();
         JsonValueType valueType = JsonValue.GetPrimitiveType(elType);
         if (valueType == JsonValueType.Object)
             array.Add(serializeObject(el));
         else if (valueType == JsonValueType.Array)
             array.Add(serializeArray((IEnumerable)el));
         else
             array.Add(new JsonPrimitive(el.ToString(), valueType));
     }
     return array;
 }
Example #8
0
 JsonArray GetJson(IEnumerable<Song> songs)
 {
     JsonArray array = new JsonArray();
     foreach (Song song in songs) {
         array.Add(new JsonNumber(song.Id));
     }
     return array;
 }
Example #9
0
 protected override IJsonToken LibraryResponse(Library library)
 {
     JsonArray artists = new JsonArray();
     foreach (Artist artist in library.GetArtists()) {
         artists.Add(artist.ToJson());
     }
     return artists;
 }
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
            var selected = new List<object>(TileList.SelectedItems);

            var picker = new FileSavePicker();
            picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
            var file = await picker.PickSaveFileAsync();
            if (file != null) {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, "");
                
                using (var stream = await file.OpenStreamForWriteAsync())
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {

                    while (zip.Entries.Count > 0) {
                        zip.Entries[0].Delete();
                    }

                    using (var metaStream = zip.CreateEntry("tiles.json").Open())
                    using (var writer = new StreamWriter(metaStream)) {
                        var array = new JsonArray();

                        selected.ForEachWithIndex<SecondaryTile>((item, index) => {
                            var objet = new JsonObject();
                            objet.Add("Name", item.DisplayName);
                            objet.Add("Arguments", item.Arguments);
                            objet.Add("TileId", item.TileId);
                            objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
                            objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
                            objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
                            
                            array.Add(objet);

                            if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
                                var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
                                
                                zip.CreateEntryFromFile(path, item.TileId + "/normal");
                            }
                        });
                        writer.WriteLine(array.Stringify());
                        
                    }

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if(status == FileUpdateStatus.Complete) {
                        var folder = await file.GetParentAsync();
                        await new MessageDialog("Speichern erfolgreich").ShowAsync();
                    } else {
                        await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
                    }

                    Debug.WriteLine(status);
                }
            }
        }
Example #11
0
 //把函数转换出来的Json串交给后台数据库服务
 public void Invoke(IAsyncObject obj, Func<JsonValue> method)
 {
     //传递到后台执行
     Uri uri = new Uri(Uri);
     WebClient client = new WebClient();
     client.UploadStringCompleted += (o, e) =>
     {
         obj.IsBusy = false;
         //通知数据提交过程完成
         if (e.Error != null)
         {
             obj.State = State.Error;
             obj.Error = e.Error.GetMessage();
         }
         else
         {
             //返回数据重新赋值给对象
             JsonObject resultJson =  (JsonObject)JsonValue.Parse(e.Result);
             if (resultJson.ContainsKey(obj.Name))
             {
                 (obj as IFromJson).FromJson((JsonObject)resultJson[obj.Name]);
             }
             //判定是否保存成功
             if (resultJson.ContainsKey("success")) 
             {
                 string success = resultJson["success"];
                 MessageBox.Show(success);
             }
             if (resultJson.ContainsKey("error"))
             {
                 obj.Error = resultJson["error"];
                 obj.State = State.Error;
                 obj.OnCompleted(e);
                 return;
             }
             else 
             {
                 obj.State = State.End;
             }
         }
         obj.OnCompleted(e);
     };
     JsonArray array = new JsonArray();
     JsonValue json = method();
     if (json is JsonObject)
     {
         //把执行批处理对象的名字添加进去
         json["name"] = obj.Name;
         array.Add(json);
     }
     else
     {
         array = (JsonArray) json;
     }
     obj.IsBusy = true;
     obj.State = State.Start;
     client.UploadStringAsync(uri, array.ToString());
 }
Example #12
0
        static void Main(string[] args)
        {
            var inputString = @"{
                ""firstName"":""Иван"",
                ""lastName"":""Иванов"",
                ""test"":""test1\ntest2\ntest3\\"",
                ""address"":{
                    ""streetAddress"":""Московское ш., 101, кв.101"",
                    ""city"":""Ленинград"",
                    ""postalCode"":101101
                },
                ""phoneNumbers"":[
                    ""812 123-1234"",
                    ""916 123-4567""
                ]
            }";
            var json = (JsonObject)JsonParser.Parse(inputString);
            Console.WriteLine("First name: {0}", json["firstName"]);
            Console.WriteLine("Last name: {0}", json["lastName"]);
            var address = (JsonObject)json["address"];
            foreach (var el in address.Keys) Console.WriteLine("{0} = {1}", el, address[el]);
            var phoneNumbers = (JsonArray)json["phoneNumbers"];
            foreach (var el in phoneNumbers) Console.WriteLine("Phone: {0}", el);
            var encodedJson = json.Encode();
            var decodedJson = JsonParser.Parse(encodedJson);
            Debug.Assert(encodedJson == decodedJson.Encode());
            Console.WriteLine("Encoded JSON: {0}", encodedJson);

            var testJson = new JsonObject();
            testJson["hello"] = new JsonValue("world");
            testJson["escaped_string"] = new JsonValue(@"Blabla""[123]\{abc}");
            var author = new JsonObject();
            author["name"] = new JsonValue("Cluster");
            author["age"] = new JsonValue(26);
            var contacts = new JsonArray();
            contacts.Add(new JsonValue("http://clusterrr.com"));
            contacts.Add(new JsonValue("*****@*****.**"));
            author["contacts"] = contacts;
            testJson["author"] = author;
            encodedJson = testJson.Encode();
            decodedJson = JsonParser.Parse(encodedJson);
            Debug.Assert(encodedJson == decodedJson.Encode());
            Console.WriteLine("Encoded JSON: {0}", encodedJson);
            Console.ReadLine();
        }
Example #13
0
 protected override IJsonToken LibraryResponse(Library library)
 {
     JsonArray array = new JsonArray();
     SearchIndex index = new SearchIndex(library.GetSongs());
     foreach (KeyValuePair<string, List<Song>> kvp in index) {
         array.Add(GetJson(kvp.Key, kvp.Value));
     }
     return array;
 }
Example #14
0
        public IJsonValue ConvertToJson(object instance)
        {
            Movie[] movies = (Movie[])instance;
            JsonArray result = new JsonArray();
            foreach (var movie in movies)
            {
                result.Add(MobileServiceTableSerializer.Serialize(movie));
            }

            return result;
        }
Example #15
0
 public static JsonValue GetAllUsers(Cache cache)
 {
     var ret = new JsonArray();
     foreach (var itm in cache)
     {
         if (itm is DictionaryEntry && ((DictionaryEntry)itm).Value is Tuple<string, string>)
         {
             ret.Add(GetUser(cache, ((DictionaryEntry)itm).Key.ToString()));
         }
     }
     return ret;
 }
Example #16
0
 public string GetJson()
 {
     JsonArray jsonarray = new JsonArray();
     foreach (var school in Education)
     {
         jsonarray.Add(school.ToJsonObject());
     }
     JsonObject jsonobject = new JsonObject();
     jsonobject["age"] = JsonValue.CreateStringValue(Age.ToString());
     jsonobject["name"] = JsonValue.CreateStringValue(Name);
     jsonobject["education"] = jsonarray;
     return jsonobject.Stringify();
 }
Example #17
0
        public static JsonArray ToJson(this ModelStateDictionary modalState)
        {
            var errors = new JsonArray();
            foreach (var prop in modalState.Values)
            {
                if (prop.Errors.Any())
                {
                    errors.Add(prop.Errors.First().ErrorMessage);
                }
            }

            return errors;
        }
Example #18
0
        public override JsonObject ApiGetConfiguration()
        {
            JsonObject configuration = base.ApiGetConfiguration();

            JsonArray casements = new JsonArray();
            foreach (var casement in _casements)
            {
                casements.Add(JsonValue.CreateStringValue(casement.Id));
            }

            configuration.SetNamedValue("casements", casements);

            return configuration;
        }
        public override JsonObject ApiGetConfiguration()
        {
            JsonObject configuration = base.ApiGetConfiguration();

            JsonArray buttonIds = new JsonArray();
            foreach (var button in _buttons)
            {
                buttonIds.Add(JsonValue.CreateStringValue(button.Key));
            }
            
            configuration.SetNamedValue("buttons", buttonIds);

            return configuration;
        }
        static JsonArray CreateJsonArray(Random rndGen, int depth)
        {
            int size = rndGen.Next(CreatorSettings.MaxArrayLength);
            if (CreatorSettings.NullValueProbability == 0 && size == 0)
            {
                size++;
            }

            JsonArray result = new JsonArray();
            for (int i = 0; i < size; i++)
            {
                result.Add(CreateJsonValue(rndGen, depth + 1));
            }

            return result;
        }
Example #21
0
        public string Stringify()
        {
            JsonArray jsonArray = new JsonArray();
            foreach (School school in Education)
            {
                jsonArray.Add(school.ToJsonObject());
            }

            JsonObject jsonObject = new JsonObject();
            jsonObject[idKey] = JsonValue.CreateStringValue(Id);
            jsonObject[nameKey] = JsonValue.CreateStringValue(Name);
            jsonObject[educationKey] = jsonArray;
            jsonObject[timezoneKey] = JsonValue.CreateNumberValue(Timezone);
            jsonObject[verifiedKey] = JsonValue.CreateBooleanValue(Verified);

            return jsonObject.Stringify();
        }
        public static JsonObject ToJsonForGetExpansions(AppDataContext appDataContext)
        {
            JsonObject root = new Windows.Data.Json.JsonObject();

            JsonArray expansionArray = new JsonArray();

            foreach (var expansion in appDataContext.Expansions)
            {
                JsonObject expansionObject = new JsonObject();
                expansionObject.Add("name", JsonValue.CreateStringValue(expansion.DominionExpansion.ToProgramaticName()));
                expansionObject.Add("present", JsonValue.CreateBooleanValue(expansion.IsEnabled.Value));
                expansionArray.Add(expansionObject);
            }
            root.Add(jsonNameRequiredExpansions, expansionArray);

            return root;
        }
        public string GetLogItemsFromPosition(FilteredRequest p_FilteredRequest)
        {
            var l_Date = DateTime.Parse(p_FilteredRequest.FileDate);

            var l_Task = PxLog.Models.PxLogModel.GetLogItemsFromPosition(l_Date, p_FilteredRequest.Position, p_FilteredRequest.LogTypes, p_FilteredRequest.ContextSearchTerm, p_FilteredRequest.DetailsSearchTerm);
            l_Task.Wait();
            var l_Result = l_Task.Result;

            var l_JsonItems = new JsonArray();

            foreach (var l_Item in l_Result)
            {
                l_JsonItems.Add(l_Item.ToJson());

            }

            return l_JsonItems.Serialize();
        }
Example #24
0
        public JsonObject MakePublicJson()
        {
            var json = new JsonObject();

            json.Add("isAlive", IsAlive);

            json.Add("handCardCount", Hand.Count);

            var jsonDiscardPile = new JsonArray();

            json.Add("discardPile", jsonDiscardPile);
            foreach (var card in DiscardPile)
            {
                jsonDiscardPile.Add(card.MakeJson());
            }

            return(json);
        }
Example #25
0
        internal static IJsonValue GenericDataObjectToJsonValue(GenericDataObject obj)
        {
            if (obj is null)
            {
                return(JsonValue.CreateNullValue());
            }

            switch (obj.Type)
            {
            case GenericDataObjectType.Bool:
                return(JsonValue.CreateBooleanValue(((GenericDataBool)obj).Value));

            case GenericDataObjectType.List:
            {
                var result = new JsonArray();
                foreach (var value in (GenericDataList)obj)
                {
                    result.Add(GenericDataObjectToJsonValue(value));
                }

                return(result);
            }

            case GenericDataObjectType.Map:
            {
                var result = new JsonObject();
                foreach ((var key, var value) in (GenericDataMap)obj)
                {
                    result.Add(key, GenericDataObjectToJsonValue(value));
                }

                return(result);
            }

            case GenericDataObjectType.Number:
                return(JsonValue.CreateNumberValue(((GenericDataNumber)obj).Value));

            case GenericDataObjectType.String:
                return(JsonValue.CreateStringValue(((GenericDataString)obj).Value));

            default:
                throw new InvalidOperationException();
            }
        }
Example #26
0
        private string WebCall_GetCategoryInfo(string categoryList)
        {
            string[] categories = categoryList.Split(',');


            JsonArray joArray = new JsonArray();

            for (int i = 0; i < categories.Length; i++)
            {
                GlobalCurrentCategoryId = categories[i];

                //使用 WebClient 類別向伺服器發出要求
                WebClient client = new WebClient();
                client.Encoding = Encoding.UTF8;
                string serviceUrl = GetServiceUrl(ServiceType.GetCategoryInfo) + GetParameterString();

                //反序列化用
                string result = "";

                try
                {
                    //接收結果
                    result = client.DownloadString(serviceUrl);
                    JsonObject JOResult       = (JsonObject)JsonConvert.Import(result);
                    string     data           = JsonConvert.ExportToString(JOResult["data"]);
                    JsonObject JOCategoryInfo = (JsonObject)JsonConvert.Import(data);
                    joArray.Add(JOCategoryInfo);
                }
                catch (WebException webEx)
                {
                    ErrMessage = webEx.ToString();
                }
                catch (NotSupportedException nsEx)
                {
                    ErrMessage = nsEx.ToString();
                }
                catch (Exception ex)
                {
                    ErrMessage = ex.ToString();
                }
            }

            return(JsonConvert.ExportToString(joArray));
        }
Example #27
0
        private JsonArray ReadArray(JsonArray jsonArray)
        {
            this.scanner.Assert('[');

            this.scanner.SkipWhitespace();

            if (this.scanner.Peek() == ']')
            {
                this.scanner.Read();
            }
            else
            {
                while (true)
                {
                    this.scanner.SkipWhitespace();

                    var value = ReadJsonValue();

                    jsonArray.Add(value);

                    this.scanner.SkipWhitespace();

                    var next = this.scanner.Read();

                    if (next == ']')
                    {
                        break;
                    }
                    else if (next == ',')
                    {
                        continue;
                    }
                    else
                    {
                        throw new JsonParseException(
                                  ErrorType.InvalidOrUnexpectedCharacter,
                                  this.scanner.Position
                                  );
                    }
                }
            }

            return(jsonArray);
        }
Example #28
0
        //把函数转换出来的Json串交给后台数据库服务
        public void Invoke(IAsyncObject obj, Func <JsonValue> method)
        {
            //传递到后台执行
            Uri       uri    = new Uri(Uri);
            WebClient client = new WebClient();

            client.UploadStringCompleted += (o, e) =>
            {
                obj.IsBusy = false;
                //通知数据提交过程完成
                if (e.Error != null)
                {
                    obj.State = State.Error;
                    obj.Error = e.Error.GetMessage();
                }
                else
                {
                    //返回数据重新赋值给对象
                    JsonObject resultJson = (JsonObject)JsonValue.Parse(e.Result);
                    if (resultJson.ContainsKey(obj.Name))
                    {
                        (obj as IFromJson).FromJson((JsonObject)resultJson[obj.Name]);
                    }
                    obj.State = State.End;
                }
                obj.OnCompleted(e);
            };
            JsonArray array = new JsonArray();
            JsonValue json  = method();

            if (json is JsonObject)
            {
                //把执行批处理对象的名字添加进去
                json["name"] = obj.Name;
                array.Add(json);
            }
            else
            {
                array = (JsonArray)json;
            }
            obj.IsBusy = true;
            obj.State  = State.Start;
            client.UploadStringAsync(uri, array.ToString());
        }
Example #29
0
        JsonObject GetData(int start, int limit)
        {
            JsonObject
                tmpJsonObject = new JsonObject();

            JsonArray
                tmpJsonArray = new JsonArray();

            using (SqlConnection conn = new SqlConnection(GetConnectionString()))
            {
                conn.Open();

                SqlCommand
                    cmd = conn.CreateCommand();

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "GetStaffPage";
                SqlCommandBuilder.DeriveParameters(cmd);
                cmd.Parameters["@start"].Value = start;
                cmd.Parameters["@limit"].Value = limit;

                using (SqlDataReader r = cmd.ExecuteReader())
                {
                    if (r.HasRows)
                    {
                        int
                            idx = r.GetOrdinal("BirthDate");

                        while (r.Read())
                        {
                            tmpJsonArray.Add(new JsonObject(new Dictionary <string, object> {
                                { "Id", r["Id"] }, { "Name", r["Name"] }, { "Salary", r["Salary"] }, { "Dep", r["Dep"] }, { "BirthDate", r["BirthDate"] }
                            }));
                        }
                    }
                }
            }

            tmpJsonObject.Accumulate("success", true);
            tmpJsonObject.Accumulate("count", GetCount());
            tmpJsonObject.Accumulate("rows", tmpJsonArray);

            return(tmpJsonObject);
        }
Example #30
0
        public void RemoveField(JsonObject model, JsonObject field)
        {
            collection.ModSchema(true);
            JsonArray ja  = model.GetNamedArray("flds");
            JsonArray ja2 = new JsonArray();
            int       idx = -1;

            for (int i = 0; i < ja.Count; ++i)
            {
                if (field.Equals(ja.GetObjectAt((uint)i)))
                {
                    idx = i;
                    continue;
                }
                ja2.Add(ja[i]);
            }

            if (idx < 0)
            {
                throw new ModelException("RemoveFiled: Can't find field to remove");
            }

            model["flds"] = ja2;
            int sortf = (int)model.GetNamedNumber("sortf");

            if (sortf >= model.GetNamedArray("flds").Count)
            {
                model["sortf"] = JsonValue.CreateNumberValue(sortf - 1);
            }
            UpdateFieldOrds(model);
            TransformFields(model, (List <string> f) =>
            {
                List <string> l = new List <string>(f);
                l.RemoveAt(idx);
                return(l);
            });

            if (idx == SortIdx(model))
            {
                // need to rebuild
                collection.UpdateFieldCache(NoteIds(model).ToArray());
            }
            RenameField(model, field, null);
        }
Example #31
0
        /// <summary>
        /// Generates a json representation of the manifest;
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="version">The version.</param>
        /// <param name="dependencies">The dependencies.</param>
        /// <returns>Returns a task representing the asynchronous operation. The result contains the generated json manifest.</returns>
        public static async Task <string> GenerateJson(string name, string version, ParsedDependencies dependencies)
        {
            JsonClass rootJson = new JsonClass();

            rootJson.Add("nameVersion", Constants.NAME_ASSEMBLY_VERSION);
            rootJson.Add("name", name);

            if (version.Count(c => c == '.') > 2)
            {
                version = string.Join(".", version.Split('.').Take(3));
            }

            rootJson.Add("version", version);

            List <Task <JsonNode> > infrastructureTasks = new List <Task <JsonNode> >();

            foreach (var dependency in dependencies.InfrastructureDependencies)
            {
                infrastructureTasks.Add(dependency.ToJson());
            }
            List <Task <JsonNode> > serviceTasks = new List <Task <JsonNode> >();

            foreach (var dependency in dependencies.ServiceDependencies)
            {
                serviceTasks.Add(dependency.ToJson());
            }
            await Task.WhenAll(Task.WhenAll(serviceTasks), Task.WhenAll(infrastructureTasks)).ConfigureAwait(false);

            JsonArray infrastructureDependencies = new JsonArray();
            JsonArray serviceDependencies        = new JsonArray();

            foreach (var task in serviceTasks)
            {
                serviceDependencies.Add(task.Result);
            }
            foreach (var task in infrastructureTasks)
            {
                infrastructureDependencies.Add(task.Result);
            }
            rootJson.Add("infrastructure_dependencies", infrastructureDependencies);
            rootJson.Add("service_dependencies", serviceDependencies);

            return(rootJson.ToString());
        }
Example #32
0
            public override JsonValue ToJson()
            {
                dynamic json = base.ToJson();

                json.source = Source;
                if (OriginDataset != null)
                {
                    json.origin_dataset = OriginDataset;
                }
                if (!string.IsNullOrEmpty(Seed))
                {
                    json.seed = Seed;
                }
                if (Size != 0)
                {
                    json.size = Size;
                }
                if (SampleRate != 0.0)
                {
                    json.sample_rate = SampleRate;
                }
                json.out_of_bag = OutOfBag;
                if (ExcludedFields.Count > 0)
                {
                    var excluded_fields = new JsonArray();
                    foreach (var excludedField in ExcludedFields)
                    {
                        excluded_fields.Add((JsonValue)excludedField);
                    }
                    json.excluded_fields = excluded_fields;
                }

                if (FieldInfos.Count > 0)
                {
                    var field = new JsonObject();
                    foreach (var kv in FieldInfos)
                    {
                        field[kv.Key] = kv.Value.ToJson();
                    }
                    json.field = field;
                }

                return(json);
            }
Example #33
0
    protected override JsonObject Serialize()
    {
        JsonObject json = new JsonObject();

        json["now"]         = Helper.ToUnixTimeMs(DateTime.UtcNow);
        json["waveHP"]      = _currentWaveHP.Serialize();
        json["decadeHP"]    = _currentDecadeStartHP.Serialize();
        json["hpPerZombie"] = _hpPerZombie.Serialize();
        json["zombieCount"] = _currentZombieCount;
        json["decadeCount"] = _currentDecadeZombieCount;
        json["waveNumber"]  = WaveNumber;
        json["mainType"]    = _currentMainZombieType.ToString();

        JsonArray mainTypes = new JsonArray();

        for (int i = 0; i < _otherMainTypes.Count; i++)
        {
            mainTypes.Add(_otherMainTypes[i].ToString());
        }

        json["otherMainTypes"] = mainTypes;

        JsonArray addTypes = new JsonArray();

        for (int i = 0; i < _otherAddTypes.Count; i++)
        {
            addTypes.Add(_otherAddTypes[i].ToString());
        }

        json["otherAddTypes"] = addTypes;

        json["aliveCount"]    = _zombies.Count;
        json["lastBossAlive"] = _lastBossAlive;

        JsonArray zombies = new JsonArray();

        for (int i = 0; i < _zombies.Count; i++)
        {
            zombies.Add(_zombies[i].Serialize());
        }

        json["zombies"] = zombies;
        return(json);
    }
Example #34
0
        JsonArray GetChildren(DataTable dt, ulong?ParentId, uint Level)
        {
            JsonArray
                JsonArray = null;

            DataRow[]
            DataRows = dt.Select((ParentId.HasValue ? "(PARENTID=" + ParentId.Value + ")" : "(PARENTID is null)") + " and (L=" + Level + ")");

            if (DataRows.Length == 0)
            {
                return(JsonArray);
            }

            JsonArray = new JsonArray();

            foreach (DataRow row in DataRows)
            {
                ulong
                             Id = Convert.ToUInt64(row["ID"]);

                JsonObject
                    JsonObject = new JsonObject(new Dictionary <string, object> {
                    { "id", Id }, { "nodeId", Id }, { "pnodeID", ParentId.HasValue ? (object)ParentId.Value : null }, { "text", row["VAL"] }
                });

                if (Id == 8)
                {
                    JsonObject.Accumulate("checked", true);
                }

                JsonArray
                    Children;

                JsonObject.Accumulate("leaf", (Children = GetChildren(dt, Id, Level + 1)) == null);
                if (Children != null)
                {
                    JsonObject.Accumulate("children", Children);
                }

                JsonArray.Add(JsonObject);
            }

            return(JsonArray);
        }
        internal byte[] ToJsonArray(int offset, int length)
        {
            JsonObject jo = new JsonObject();

            jo.Add("method", "gdata");

            JsonArray jag = new JsonArray();
            JsonArray jao = new JsonArray();

            for (int i = offset; (i < offset + length) && (i < this.Count); i++)
            {
                jag.Add(new JsonArray {
                    this[i].gid, this[i].token
                });
            }
            jo.Add("gidlist", jag);

            return(Encoding.ASCII.GetBytes(jo.ToString()));
        }
Example #36
0
    public JsonArray GetDirectoryList(string type)
    {
        JsonArray  ja = new JsonArray();
        JsonObject jo;
        String     tmpStr;

        string sql = " select FullName from Directory "
                     + " where Type = '" + type + "'"
                     + " order by FullName";

        this.dbAccess.open();
        try
        {
            System.Data.DataTable dt = dbAccess.select(sql);

            foreach (System.Data.DataRow dr in dt.Rows)
            {
                jo = new JsonObject();
                foreach (System.Data.DataColumn col in dt.Columns)
                {
                    if (col.DataType == System.Type.GetType("System.DateTime"))
                    {
                        tmpStr = Convert.ToDateTime(dr[col.ColumnName]).ToString(GlobalSetting.DateTimeFormat);
                    }
                    else
                    {
                        tmpStr = dr[col.ColumnName].ToString();
                    }
                    jo.Accumulate(col.ColumnName.ToLower(), tmpStr);
                }
                ja.Add(jo);
            }
        }
        catch
        {
            throw;
        }
        finally
        {
            this.dbAccess.close();
        }
        return(ja);
    }
Example #37
0
            public override JsonValue ToJson()
            {
                dynamic json = base.ToJson();

                if (!string.IsNullOrWhiteSpace(DataSet))
                {
                    json.dataset = DataSet;
                }
                if (ExcludedFields.Count > 0)
                {
                    var excluded_fields = new JsonArray();
                    foreach (var excludedField in ExcludedFields)
                    {
                        excluded_fields.Add((JsonValue)excludedField);
                    }
                    json.excluded_fields = excluded_fields;
                }
                return(json);
            }
Example #38
0
 /// <summary>
 /// 树型JSON结构处理
 /// </summary>
 /// <param name="ds"></param>
 /// <param name="json"></param>
 /// <param name="ID"></param>
 private void AddNode(DataTable ds, JsonArray json, string ID)
 {
     DataRow[] rows = ds.Select("pid=" + ID);
     foreach (DataRow dr in rows)
     {
         string     _id = dr["id"].ToString();
         JsonObject j   = new JsonObject();
         j.Add("id", _id);
         j.Add("name", dr["name"].ToString());
         JsonArray arr = new JsonArray();
         AddNode(ds, arr, _id);
         if (arr.Count > 0)
         {
             j.Add("open", "true");
             j.Add("children", arr);
         }
         json.Add(j);
     }
 }
Example #39
0
        public string Stringify()
        {
            JsonArray jsonArray = new JsonArray();

            foreach (CardContent card in contents)
            {
                jsonArray.Add(card.ToJsonObject());
            }

            JsonObject jsonObject = new JsonObject();

            jsonObject[cardIdKey] = JsonValue.CreateStringValue(cardId.ToString());

            // Treating a blank string as null
            jsonObject[headerTitleKey] = JsonValue.CreateStringValue(headerTitle);
            jsonObject[contentsKey]    = jsonArray;
            return(jsonArray.Stringify());
            //return jsonObject.Stringify();
        }
Example #40
0
        /// <summary>
        /// 根据表名称或表名与值获取键值对json数据
        /// </summary>
        private void GetKeyValueJsonDataByDataTable()
        {
            JsonObject jsonData   = JsonResult(false, enumReturnTitle.GetData, "数据获取失败。");
            string     DataTable  = UrlHelper.ReqStr("DataTable");
            string     KeyField   = UrlHelper.ReqStr("KeyField");
            string     ValueField = UrlHelper.ReqStr("ValueField");
            bool       IsSingle   = UrlHelper.ReqBoolByGetOrPost("IsSingle");
            string     Val        = UrlHelper.ReqStr("Val");
            string     condition  = "";

            if (IsSingle)
            {
                condition = string.Format(" {0}='{1}' ", ValueField, Val);
            }
            try
            {
                IDataReader idr    = DBControl.Base.DBAccess.GetDataIDR(string.Format("{0},{1}", KeyField, ValueField), DataTable, condition, "");
                JsonArray   jArray = new JsonArray();
                if (null != idr)
                {
                    jsonData = JsonResult(true, enumReturnTitle.GetData, "数据获取成功。");
                    int index = 0;
                    while (idr.Read())
                    {
                        JsonObject tempObj = new JsonObject();
                        tempObj.Add("DataValue", idr[ValueField].ToString());
                        tempObj.Add("DataKey", idr[KeyField].ToString());
                        jArray.Add(tempObj);
                        index++;
                    }
                    idr.Close();
                    idr.Dispose();
                }
                jsonData.Add("rows", jArray);
                JsonWriter jWriter = new JsonWriter();
                jsonData.Write(jWriter);
                CurrentContext.Response.Write(jWriter.ToString());
            }
            catch (Exception ex)
            {
                ReturnMsg(false, enumReturnTitle.GetData, string.Format("获取数据失败:{0}", ex.Message));
            }
        }
Example #41
0
        public JsonObject queryReservation(string cmmcode, string hotelid, string rsvno)
        {
            var request = new JsonObject();

            request["method"]  = "xmsopen.reservation.xopqueryreservation";
            request["ver"]     = "1.0.0";
            request["cmmcode"] = cmmcode;
            var jary = new JsonArray();

            request["params"] = jary;
            var param = new JsonObject();

            param["hotelid"] = hotelid;
            param["rsvno"]   = rsvno;
            jary.Add(param);
            var rsp = execute(request);

            return(rsp);
        }
Example #42
0
        /// <summary>
        /// 获取房型
        /// </summary>
        /// <param name="cmmcode"></param>
        /// <param name="hotelid"></param>
        /// <returns></returns>
        public getRoomTypeJsonRsult getRoomType(string cmmcode, string hotelid)
        {
            var request = new JsonObject();

            request["method"] = "xmsopen.reservation.xopgetroomtype";
            request["ver"]    = "1.0.0";
            //request["hotelid"] = "H000069";
            request["cmmcode"] = cmmcode;
            var jary = new JsonArray();

            request["params"] = jary;
            var param = new JsonObject();

            param["hotelid"] = hotelid;
            jary.Add(param);
            var rsp = execute <getRoomTypeJsonRsult>(request);

            return(rsp);
        }
Example #43
0
        private static JsonValue _Encode <T>(SerializationContext context)
        {
            var queue = (Queue <T>)context.Source;
            var array = new JsonArray();

            for (int i = 0; i < queue.Count; i++)
            {
                var element    = queue.ElementAt(i);
                var newContext = new SerializationContext(context)
                {
                    CurrentLocation = context.CurrentLocation.CloneAndAppend(i.ToString()),
                    InferredType    = element?.GetType() ?? typeof(T),
                    RequestedType   = typeof(T),
                    Source          = element
                };
                array.Add(context.RootSerializer.Serialize(newContext));
            }
            return(array);
        }
        public string Stringify()
        {
            JsonObject jsonObject = new JsonObject();

            jsonObject.Add("Aplicacion", JsonValue.CreateStringValue(Aplicacion));
            jsonObject.Add("Categoria", JsonValue.CreateNumberValue(Categoria));

            JsonArray EtiquetasArray = new JsonArray();

            foreach (var fila in Etiquetas)
            {
                EtiquetasArray.Add(fila.Objectify());
            }

            jsonObject.Add("Etiquetas", EtiquetasArray);
            jsonObject.Add("Agregar", JsonValue.CreateBooleanValue(Agregar));

            return(jsonObject.Stringify());
        }
Example #45
0
        private JsonObject buildPOSTRequest(String path, String path1)
        {
            var inventories = new JsonArray();

            //var messages = new JsonArray();

            if (path != "")
            {
                inventories.Add(buildInventory(path));
                //    messages.Add(buildMessages(path));
            }

            var json = new JsonObject();

            json.Add("inventories", inventories);
            //json.Add("messages", messages);

            return(json);
        }
        public static JsonArray orbitingBodies(CelestialBody body)
        {
            JsonArray json = new JsonArray();

            if (body.orbitingBodies != null && body.orbitingBodies.Count > 0)
            {
                int childrenCount = body.orbitingBodies.Count;
                // log(body.name + " has " + childrenCount + " children");
                for (int i = 0; i < childrenCount; i++)
                {
                    // log("child " + i);
                    if (body.orbitingBodies[i] != null)
                    {
                        json.Add(body.orbitingBodies[i].name);
                    }
                }
            }
            return(json);
        }
Example #47
0
    public string DumpJson()
    {
        JsonObject obj = new JsonObject();

        obj["type"]   = gameObject.name;
        obj["global"] = true;
        JsonArray components = new JsonArray();

        obj["components"] = components;

        JsonObject terrain = new JsonObject("type", "Ex.Terrain");

        components.Add(terrain);
        JsonObject data = new JsonObject();

        terrain["data"] = data;

        data["tileSize"]            = Helpers.Pack(tileSize);
        data["viewDist"]            = viewDist;
        data["meshSamples"]         = meshSamples;
        data["splatSamples"]        = splatSamples;
        data["slopeAngle"]          = slopeAngle;
        data["seed"]                = seed;
        data["chunk"]               = objects[0].name;
        data["shader"]              = shader.name;
        data["heightmapKernelName"] = heightmapKernelName;
        data["splatmapKernelName"]  = splatmapKernelName;
        data["terrainBaseLayer"]    = terrainLayers[0].name;
        data["terrainCliffLayer"]   = terrainLayers[1].name;
        for (int i = 2; i < terrainLayers.Length; i++)
        {
            data["terrainLayer" + (i - 1)] = terrainLayers[i].name;
        }
        data["objectNoise"]        = Helpers.Pack(objectNoise);
        data["heightmapNoise"]     = Helpers.Pack(heightmapNoise);
        data["splatmapNoise"]      = Helpers.Pack(splatmapNoise);
        data["objectUberNoise"]    = Helpers.Pack(objectUberNoise);
        data["heightmapUberNoise"] = Helpers.Pack(heightmapUberNoise);
        data["splatmapUberNoise"]  = Helpers.Pack(splatmapUberNoise);
        data["extra"] = Helpers.Pack(craterData);

        return(obj.PrettyPrint());
    }
        async private void onCreateClick(object sender, RoutedEventArgs e)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(Config.URI);

                JsonArray playerNames = new JsonArray();
                foreach (string s in teammateListBox.Items)
                {
                    playerNames.Add(JsonValue.CreateStringValue(s));
                }

                JsonObject jsonObject = new JsonObject();
                jsonObject["name"]      = JsonValue.CreateStringValue(teamNameBox.Text);
                jsonObject["sport"]     = JsonValue.CreateStringValue((string)sportTypeBox.SelectedValue);
                jsonObject["usernames"] = playerNames;

                byte[]           byteArray = Encoding.UTF8.GetBytes(jsonObject.ToString());
                ByteArrayContent content   = new ByteArrayContent(byteArray);

                try
                {
                    HttpResponseMessage response = await client.PutAsync("api/team/team/", content);

                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();

                        D.p(result);
                        Frame rootFrame = Window.Current.Content as Frame;
                        rootFrame.Navigate(typeof(HomePage));
                    }
                    else
                    {
                        statusLabel.Text = await response.Content.ReadAsStringAsync();
                    }
                }
                catch (Exception ex)
                {
                    statusLabel.Text = "No Internet Connection";
                }
            }
        }
Example #49
0
        public override IJsonValue ToJson()
        {
            JsonObject RetVal = new JsonObject();

            RetVal.Add(nameof(Name), Name);
            JsonArray BookItems = new JsonArray();

            lock ( _LockItems ) {
                foreach (TBook BookItem in Items)
                {
                    JsonObject JsonBook = new JsonObject();
                    JsonBook.Add(nameof(TBook.Name), BookItem.Name);
                    JsonBook.Add(nameof(TBook.Number), BookItem.Number);
                    BookItems.Add(JsonBook);
                }
            }
            RetVal.Add(nameof(Items), BookItems);
            return(RetVal);
        }
Example #50
0
        /// <summary>
        /// Parses the token of type array
        /// </summary>
        /// <returns>Parsed array</returns>
        private JsonArray ParseArray()
        {
            // Array can start only with '['
            ExceptionUtilities.Assert(this.tokenizer.TokenType == JsonTokenType.LeftSquareBracket, "Invalid Token");

            // Should not end before we get ']'
            ExceptionUtilities.Assert(this.tokenizer.HasMoreTokens(), "Invalid End Of Stream");
            this.tokenizer.GetNextToken();

            // Array is an ordered collection of values
            ExceptionUtilities.Assert(this.IsValueType(this.tokenizer.TokenType) || this.tokenizer.TokenType == JsonTokenType.RightSquareBracket, "InvalidToken");
            var result = new JsonArray();

            while (this.tokenizer.HasMoreTokens())
            {
                if (this.IsValueType(this.tokenizer.TokenType))
                {
                    JsonValue v = this.ParseValue();
                    result.Add(v);

                    // Values are separated by , (comma).
                    ExceptionUtilities.Assert(this.tokenizer.TokenType == JsonTokenType.Comma || this.tokenizer.TokenType == JsonTokenType.RightSquareBracket, "Invalid Token");
                }
                else if (this.tokenizer.TokenType == JsonTokenType.RightSquareBracket)
                {
                    if (this.tokenizer.HasMoreTokens())
                    {
                        this.tokenizer.GetNextToken();
                    }

                    return(result);
                }
                else if (this.tokenizer.TokenType == JsonTokenType.Comma)
                {
                    this.tokenizer.GetNextToken();

                    // Last element of the array cannot be followed by a comma.
                    ExceptionUtilities.Assert(this.IsValueType(this.tokenizer.TokenType) || this.tokenizer.TokenType == JsonTokenType.RightSquareBracket, "InvalidToken");
                }
            }

            return(result);
        }
Example #51
0
        private JsonArray GetPackageCates(int parentID, bool deep = true)
        {
            helper.SetParameter("@ParentID", parentID);
            string     sql = "select CategoryID,CategoryName,ParentID,Sort from PackageCates where ParentID=@ParentID order by Sort desc,CategoryID";
            JsonArray  cateList;
            JsonObject cateObj;

            using (SqlDataReader dr = helper.ExecuteReader(sql, CommandType.Text))
            {
                if (dr.HasRows)
                {
                    cateList = new JsonArray();
                    while (dr.Read())
                    {
                        cateObj = new JsonObject();
                        cateObj.Add("categoryID", (int)dr[0]);
                        cateObj.Add("categoryName", (string)dr[1]);
                        cateObj.Add("parentID", dr[2] == DBNull.Value ? 0 : (int)dr[2]);
                        cateObj.Add("sort", dr[3] == DBNull.Value ? 0 : (int)dr[3]);
                        cateList.Add(cateObj);
                    }
                }
                else
                {
                    cateList = null;
                }
            }
            if (cateList != null && deep)
            {
                JsonArray newsCateChildren;
                for (int i = 0; i < cateList.Count; i++)
                {
                    cateObj          = cateList[i];
                    parentID         = (int)cateObj["categoryID"];
                    newsCateChildren = GetPackageCates(parentID);
                    if (newsCateChildren != null)
                    {
                        cateObj.Add("children", newsCateChildren);
                    }
                }
            }
            return(cateList);
        }
Example #52
0
        public static string GetJSArray(List <Dictionary <string, string> > list)
        {
            if (list == null)
            {
                return("[]");
            }
            JsonArray jsArray = new JsonArray();

            foreach (var user in list)
            {
                JsonValue entry = new JsonObject();
                foreach (KeyValuePair <string, string> kvp in user)
                {
                    entry[kvp.Key] = kvp.Value;
                }
                jsArray.Add(entry);
            }
            return(jsArray.ToString());
        }
Example #53
0
        public void SetArray(String fieldName, long[] value)
        {
            if (String.IsNullOrEmpty(fieldName))
                throw new System.ArgumentException("field name is null or empty");

            data.Remove(fieldName);

            if (value != null)
            {
                JsonArray arr = new JsonArray();

                for (int i = 0, max = value.Length; i < max; i++)
                {
                    arr.Add(value[i]);
                }

                data.Add(fieldName, arr);
            }
        }
        private static JsonToken ReadArray(TextReader reader)
        {
            JsonArray array = new JsonArray();
            reader.Read();	// read '['
            readEmptyCharacters(reader);
            while ((char)reader.Peek() != ']')
            {
                JsonToken val = ReadValue(reader);
                array.Add(val);

                readEmptyCharacters(reader);
                char c = (char)reader.Peek();
                if (c == ',')
                    reader.Read();
                else if (c != ']')
                    throw new IOException("Invalid JSON format: Invalid array separator. Expected ',' or ']' - Found'" + c + "'");
            }
            reader.Read(); //Read ']'
            return array;
        }
Example #55
0
        private void ParseArray(Action<JsonArray> callback)
        {
            JsonArray array = new JsonArray();

            Action<JsonValue> onValue = value =>
            {
                array.Add(value);
            };

            while (reader.Next())
            {
                switch (reader.Token.Type)
                {
                    case JsonTokenType.EndArray:
                        callback.Invoke(array);
                        return;

                    default:
                        ParseValue(onValue);
                        break;
                }
            }
        }
        static JsonObject JsonObj(AddRegistrationRequest registration)
        {
            var jsonObj = new JsonObject();

            if (registration.QuietTime != null)
            {
                var quiettime = new JsonObject();
                quiettime["start"] = registration.QuietTime.Start;
                quiettime["end"] = registration.QuietTime.End;
                jsonObj["quiettime"] = quiettime;
            }

            if (registration.Alias != null)
            {
                jsonObj["alias"] = registration.Alias;
            }
            if (registration.Badge != null)
            {
                jsonObj["badge"] = registration.Badge.Value;
            }
            if (registration.TimeZone != null)
            {
                jsonObj["tz"] = registration.TimeZone;
            }
               // jsonObj.tags = Dynamic.ListValue(registration.Tags);
            if (registration.Tags != null)
            {
                var tagArray = new JsonArray();
                foreach (var tag in registration.Tags)
                {
                    tagArray.Add(tag);
                }
                jsonObj["tags"] = tagArray;
            }

            return jsonObj;
        }
Example #57
0
 private string GetCategoriesList()
 {
     JsonObject obj2 = new JsonObject();
     int parentCategoryId = Globals.SafeInt(base.Request.Form["ParentCategoryId"], -1);
     if (parentCategoryId < 0)
     {
         obj2.Put("ERROR", "NOPARENTCATEGORYID");
         return obj2.ToString();
     }
     List<Maticsoft.Model.Shop.Products.CategoryInfo> categorysByParentId = this.manage.GetCategorysByParentId(parentCategoryId, -1);
     if ((categorysByParentId == null) || (categorysByParentId.Count < 1))
     {
         obj2.Put("STATUS", "NODATA");
         return obj2.ToString();
     }
     categorysByParentId.Sort((Comparison<Maticsoft.Model.Shop.Products.CategoryInfo>) ((x, y) => x.DisplaySequence.CompareTo(y.DisplaySequence)));
     obj2.Put("STATUS", "OK");
     JsonArray data = new JsonArray();
     categorysByParentId.ForEach(delegate (Maticsoft.Model.Shop.Products.CategoryInfo info) {
         data.Add(new JsonObject(new string[] { "CategoryId", "HasChildren", "CategoryName" }, new object[] { info.CategoryId.ToString(CultureInfo.InvariantCulture), info.HasChildren, info.Name }));
     });
     obj2.Put("DATA", data);
     return obj2.ToString();
 }
Example #58
0
 public void Set(IInternalControl aThisControl, Slice aSlice, List<IControl> aChildren)
 {
     var slice = aSlice.MakeAbsolute(iChildren.Count);
     if (slice.Count > 0)
     {
         iChildren.RemoveRange(slice.Start, slice.Count);
     }
     var childIds = new JsonArray();
     if (aChildren != null && aChildren.Count > 0)
     {
         iChildren.InsertRange(slice.Start, aChildren);
         foreach (var child in aChildren)
         {
             childIds.Add(child.Id);
         }
     }
     aThisControl.BrowserTab.Send(
         new JsonObject {
             { "type", "xf-bind-slice" },
             { "start", slice.Start },
             { "end", slice.End },
             { "control", aThisControl.Id },
             { "children", childIds } });
 }
Example #59
0
 public string GetUserName(string prefixText, int limit)
 {
     if (string.IsNullOrWhiteSpace(prefixText))
     {
         return string.Empty;
     }
     string strUName = this.HtmlEncode(prefixText);
     DataSet userName = new UsersExp().GetUserName(strUName, limit);
     JsonArray array = new JsonArray();
     if (userName.Tables[0].Rows.Count > 0)
     {
         for (int i = 0; i < userName.Tables[0].Rows.Count; i++)
         {
             string tmpStr = userName.Tables[0].Rows[i]["UserName"].ToString();
             if (this.CheckHtmlCode(ref tmpStr, prefixText))
             {
                 JsonObject obj2 = new JsonObject();
                 obj2.Accumulate("name", tmpStr);
                 array.Add(obj2);
             }
         }
     }
     return array.ToString();
 }
Example #60
-1
        public void Store()
        {
            var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var sessionJson = new JsonObject();

            if (Folder != null)
            {
                sessionJson.Add("Folder", JsonValue.CreateStringValue(Folder.Path));
            }

            if (Photo != null)
            {
                var photoJson = new JsonObject();
                photoJson.Add("Path", JsonValue.CreateStringValue(Photo.File.Path));
                var filterIdsJson = new JsonArray();
                
                foreach (var filter in Photo.Filters)
                {
                    filterIdsJson.Add(JsonValue.CreateStringValue(filter.Id));
                }

                photoJson.Add("FilterIds", filterIdsJson);

                sessionJson.Add("Photo", photoJson);
            }

            settings.Values["Session"] = sessionJson.Stringify();
        }