Example #1
0
        internal static string BareValue(JsonValue json)
        {
            string value = json?.ToString();

            if (String.IsNullOrEmpty(value))
            {
                return(String.Empty);
            }
            if (value.Length > 2 && value[0] == '"' && value[value.Length - 1] == '"')
            {
                value = value.Substring(1, value.Length - 2);
            }
            return(value);
        }
Example #2
0
        /// <summary>
        /// Compares two JsonValue objects.
        /// </summary>
        /// <param name="expected">The expected JsonValue.</param>
        /// <param name="actual">The actual JsonValue.</param>
        public void Compare(JsonValue expected, JsonValue actual)
        {
            assert.AreEqual(expected.JsonType, actual.JsonType, "The types of nodes '{0}' and '{1}' are not equal.", expected.ToString(), actual.ToString());

            switch (expected.JsonType)
            {
                case JsonValueType.JsonProperty:
                    CompareProperty((JsonProperty)expected, (JsonProperty)actual);
                    break;
                case JsonValueType.JsonObject:
                    CompareObject((JsonObject)expected, (JsonObject)actual);
                    break;
                case JsonValueType.JsonArray:
                    CompareArray((JsonArray)expected, (JsonArray)actual);
                    break;
                case JsonValueType.JsonPrimitiveValue:
                    ComparePrimitiveValue((JsonPrimitiveValue)expected, (JsonPrimitiveValue)actual);
                    break;
                default:
                    assert.Fail("Unexpected JsonType value '{0}'.", expected.JsonType);
                    break;
            }
        }
        public static bool Compare(JsonValue initValue, JsonValue newValue)
        {
            if (initValue == null && newValue == null)
            {
                return(true);
            }

            if (initValue == null || newValue == null)
            {
                return(false);
            }

            if (initValue is JsonPrimitive)
            {
                string initStr;
                if (initValue.JsonType == JsonType.String)
                {
                    initStr = initValue.ToString();
                }
                else
                {
                    initStr = string.Format("\"{0}\"", ((JsonPrimitive)initValue).Value.ToString());
                }

                string newStr;
                if (newValue is JsonPrimitive)
                {
                    newStr  = newValue.ToString();
                    initStr = HttpUtility.UrlDecode(HttpUtility.UrlEncode(initStr));
                    return(initStr.Equals(newStr));
                }
                else if (newValue is JsonObject && newValue.Count == 1)
                {
                    initStr = string.Format("{0}", initValue.ToString());
                    return(((JsonObject)newValue).Keys.Contains(initStr));
                }

                return(false);
            }

            if (initValue.Count != newValue.Count)
            {
                return(false);
            }

            if (initValue is JsonObject && newValue is JsonObject)
            {
                foreach (KeyValuePair <string, JsonValue> item in initValue)
                {
                    if (!Compare(item.Value, newValue[item.Key]))
                    {
                        return(false);
                    }
                }

                return(true);
            }

            if (initValue is JsonArray && newValue is JsonArray)
            {
                for (int i = 0; i < initValue.Count; i++)
                {
                    if (!Compare(initValue[i], newValue[i]))
                    {
                        return(false);
                    }
                }

                return(true);
            }

            return(false);
        }
Example #4
0
        public void persist_decimal_point_for_float_json_values()
        {
            var value = new JsonValue(10.000);

            value.ToString().ShouldEqual("10.0");
        }
Example #5
0
        private async Task <AddProductResponce> GetProduct(int RecieptID)
        {
            GlobalRecieptID = RecieptID;
            JsonValue GetProductResponce = await HttpRequestHelper <String> .GetRequest(ServiceTypes.GetProducts, SessionHelper.AccessToken + "/" + RecieptID.ToString());

            AddProductResponce getProductResponse = JsonConvert.DeserializeObject <AddProductResponce>(GetProductResponce.ToString());

            if (getProductResponse.IsSuccess)
            {
                List <ProductDTO> lstGetProduct = getProductResponse.Lstproducts.Select(dc => new ProductDTO()
                {
                    AddedOn     = dc.AddedOn,
                    IsAvailable = dc.IsAvailable,
                    Name        = dc.Name,
                    Price       = dc.Price,
                    ProductID   = dc.ProductID,
                    Quantity    = dc.Quantity,
                    RecieptID   = dc.RecieptID,
                    UpdatedOn   = dc.UpdatedOn,
                }).ToList();

                ProductData = new ObservableCollection <ProductDTO>();

                foreach (ProductDTO getProduct in lstGetProduct)
                {
                    ProductData.Add(getProduct);
                }
            }
            else
            {
            }
            return(getProductResponse);
        }
        private async void AddProductClicked(object obj)
        {
            AddProductRequest addProductRequest = new AddProductRequest();

            addProductRequest.AuthToken = SessionHelper.AccessToken;
            ProductDTO productDTO = new ProductDTO();

            productDTO.AddedOn           = DateTime.Now.ToString();
            productDTO.IsAvailable       = true;
            productDTO.Name              = Name;
            productDTO.Price             = Price;
            productDTO.ProductID         = ProductID;
            productDTO.RecieptID         = GlobalRecieptID;
            productDTO.Quantity          = Quantity;
            productDTO.UpdatedOn         = DateTime.Now.ToString();
            addProductRequest.productDTO = productDTO;
            JsonValue AddProductResponse = await HttpRequestHelper <AddProductRequest> .POSTreq(ServiceTypes.AddProduct, addProductRequest);

            AddProductResponce addProductResponce = JsonConvert.DeserializeObject <AddProductResponce>(AddProductResponse.ToString());

            if (addProductResponce.IsSuccess)
            {
                var mdp     = (Application.Current.MainPage as MasterDetailPage);
                var navPage = mdp.Detail as NavigationPage;
                await navPage.PushAsync(new ProductList(Convert.ToInt32(GlobalRecieptID)), true);
            }
        }
Example #7
0
        private async void UpdateRecieptStatusClicked(object obj)
        {
            RecieptDTO recieptDTO = new RecieptDTO();

            recieptDTO.Status    = "4";
            recieptDTO.Price     = "";
            recieptDTO.StoreID   = StoreID;
            recieptDTO.RecieptID = RecieptID;
            UpdateRecieptStatusRequest updateRecieptStatusRequest = new UpdateRecieptStatusRequest();

            updateRecieptStatusRequest.AuthToken        = SessionHelper.AccessToken;
            updateRecieptStatusRequest.updatRrecieptDTO = recieptDTO;
            JsonValue updateRecieptRequest = await HttpRequestHelper <UpdateRecieptStatusRequest> .POSTreq(ServiceTypes.UpdateRecieptStatus, updateRecieptStatusRequest);

            UpdateRecieptStatusResponse updateRecieptStatusResponse = JsonConvert.DeserializeObject <UpdateRecieptStatusResponse>(updateRecieptRequest.ToString());

            if (updateRecieptStatusResponse.IsSuccess)
            {
                await App.Current.MainPage.DisplayAlert("Success", updateRecieptStatusResponse.Message, "Ok");
            }
            else
            {
                await App.Current.MainPage.DisplayAlert("Error", updateRecieptStatusResponse.Message, "Ok");
            }
        }
Example #8
0
        /// <summary>
        /// Creates Item on target list and attachs picture take with TakeAPicture method
        /// </summary>
        /// <param name="title">Item title</param>
        /// <param name="siteURL">SharePoint site url</param>
        /// <param name="accessToken">Token from succesful authentication</param>
        /// <param name="filePath">Picture path</param>
        /// <returns></returns>
        public async Task <string> CreateItemWithPicture(string title, string siteURL, string accessToken, string filePath)
        {
            string requestUrl = siteURL + "_api/Web/Lists/GetByTitle('SPXPictures')/Items";

            var formDigest = await GetFormDigest(siteURL, accessToken);

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

            HttpRequestMessage request =
                new HttpRequestMessage(HttpMethod.Post, requestUrl);

            request.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", accessToken);

            // Note that the form digest is not needed for bearer authentication.  This can
            //safely be removed, but left here for posterity.
            request.Headers.Add("X-RequestDigest", formDigest);

            var requestContent = new StringContent(
                "{ '__metadata': { 'type': 'SP.Data.SPXPicturesListItem' }, 'Title': '" + title + "'}");

            requestContent.Headers.ContentType =
                System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json;odata=verbose");

            request.Content = requestContent;

            HttpResponseMessage response = await client.SendAsync(request);

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

                JsonObject d           = (JsonObject)JsonValue.Parse(responseString);
                JsonObject results     = (JsonObject)d["d"];
                JsonValue  newItemId   = (JsonValue)results["ID"];
                var        endpointUrl = string.Format("{0}({1})/AttachmentFiles/add(FileName='{2}')", requestUrl, newItemId.ToString(), App._file.Name);

                using (var stream = System.IO.File.OpenRead(filePath))
                {
                    HttpContent file = new StreamContent(stream);
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    var resp = await client.PostAsync(endpointUrl, file);

                    Toast.MakeText(this, "Picture Uploaded!", ToastLength.Long).Show();
                }
                return(responseString);
            }

            return(null);
        }
		public object Deserialize(JsonValue value, JsonMapper mapper)
		{
			return JsonConvert.DeserializeObject<Article>(value.ToString());
		}
Example #10
0
        /// <summary>
        /// Parse streamed JSON line
        /// </summary>
        /// <param name="graph">JSON object graph</param>
        /// <param name="handler">result handler</param>
        public static void ParseStreamLine(JsonValue graph, IStreamHandler handler)
        {


            try
            {
                // element.foo() -> element.IsDefined("foo")

                //
                // fast path: first, identify standard status payload
                ////////////////////////////////////////////////////////////////////////////////////
                if (TwitterStreamParser.ParseStreamLineAsStatus(graph, handler))
                {
                    return;
                }

                //
                // parse stream-specific elements
                //

                // friends lists
                var friends = graph["friends"].AsArrayOrNull();
                if (friends != null)
                {
                    // friends enumeration
                    var friendsIds = friends.Select(v => v.AsLong()).ToArray();
                    handler.OnMessage(new StreamEnumeration(friendsIds));
                    return;
                }
                friends = graph["friends_str"].AsArrayOrNull();
                if (friends != null)
                {
                    // friends enumeration(stringified)
                    var friendsIds = friends.Select(v => v.AsString().ParseLong()).ToArray();
                    handler.OnMessage(new StreamEnumeration(friendsIds));
                    return;
                }

                var @event = graph["event"].AsString();
                if (@event != null)
                {
                    ParseStreamEvent(@event.ToLower(), graph, handler);
                    return;
                }

                // too many follows warning
                var warning = graph["warning"].AsObjectOrNull();
                if (warning != null)
                {
                    var code = warning["code"].AsString();
                    if (code == "FOLLOWS_OVER_LIMIT")
                    {
                        handler.OnMessage(new StreamTooManyFollowsWarning(
                            code,
                            warning["message"].AsString(),
                            warning["user_id"].AsLong(),
                            TwitterStreamParser.GetTimestamp(warning)));
                        return;
                    }
                }

                // fallback to default stream handler
                TwitterStreamParser.ParseNotStatusStreamLine(graph, handler);
            }
            catch (Exception ex)
            {
                handler.OnException(new StreamParseException(
                    "Stream graph parse failed.", graph.ToString(), ex));
            }
        }
Example #11
0
 /// <summary>
 /// Parse streamed twitter event
 /// </summary>
 /// <param name="ev">event name</param>
 /// <param name="graph">JSON object graph</param>
 /// <param name="handler">result handler</param>
 private static void ParseStreamEvent(string ev, JsonValue graph, IStreamHandler handler)
 {
     try
     {
         var source = new TwitterUser(graph[EventSourceKey]);
         var target = new TwitterUser(graph[EventTargetKey]);
         var timestamp = graph[EventCreatedAtKey].AsString().ParseTwitterDateTime();
         switch (ev)
         {
             case "favorite":
             case "unfavorite":
             case "quoted_tweet":
             case "favorited_retweet":
             case "retweeted_retweet":
                 handler.OnMessage(new StreamStatusEvent(source, target,
                     new TwitterStatus(graph[EventTargetObjectKey]), ev, timestamp));
                 break;
             case "block":
             case "unblock":
             case "follow":
             case "unfollow":
             case "mute":
             case "unmute":
             case "user_update":
             case "user_delete":
             case "user_suspend":
                 handler.OnMessage(new StreamUserEvent(source, target,
                     ev, timestamp));
                 break;
             case "list_created":
             case "list_destroyed":
             case "list_updated":
             case "list_member_added":
             case "list_member_removed":
             case "list_user_subscribed":
             case "list_user_unsubscribed":
                 handler.OnMessage(new StreamListEvent(source, target,
                     new TwitterList(graph[EventTargetObjectKey]), ev, timestamp));
                 break;
             case "access_revoked":
             case "access_unrevoked":
                 handler.OnMessage(new StreamAccessInformationEvent(source, target,
                     new AccessInformation(graph[EventTargetObjectKey]), ev, timestamp));
                 break;
         }
     }
     catch (Exception ex)
     {
         handler.OnException(new StreamParseException(
             "Event parse failed:" + ev, graph.ToString(), ex));
     }
 }
Example #12
0
        /// <summary>
        /// Parse streamed JSON line (which is not a status)
        /// </summary>
        /// <param name="graph">JSON object graph</param>
        /// <param name="handler">result handler</param>
        internal static void ParseNotStatusStreamLine(JsonValue graph, IStreamHandler handler)
        {
            try
            {
                // element.foo() -> element.IsDefined("foo")

                // direct message
                JsonValue directMessage;
                if (graph.TryGetValue("direct_message", out directMessage))
                {
                    handler.OnStatus(new TwitterStatus(graph["direct_message"]));
                    return;
                }

                // delete
                JsonValue delete;
                if (graph.TryGetValue("delete", out delete))
                {
                    var timestamp = GetTimestamp(delete);
                    JsonValue status;
                    if (delete.TryGetValue("status", out status))
                    {
                        handler.OnMessage(new StreamDelete(
                            Int64.Parse(status["id_str"].AsString()),
                            Int64.Parse(status["user_id_str"].AsString()),
                            timestamp));
                        return;
                    }
                    if (delete.TryGetValue("direct_message", out directMessage))
                    {
                        handler.OnMessage(new StreamDelete(
                            Int64.Parse(directMessage["id_str"].AsString()),
                            Int64.Parse(directMessage["user_id"].AsString()),
                            timestamp));
                        return;
                    }
                }

                // scrub_geo
                JsonValue scrubGeo;
                if (graph.TryGetValue("scrub_geo", out scrubGeo))
                {
                    handler.OnMessage(new StreamScrubGeo(
                        Int64.Parse(scrubGeo["user_id_str"].AsString()),
                        Int64.Parse(scrubGeo["up_to_status_id_str"].AsString()),
                        GetTimestamp(scrubGeo)));
                    return;
                }

                // limit
                JsonValue limit;
                if (graph.TryGetValue("limit", out limit))
                {
                    handler.OnMessage(new StreamLimit(
                        limit["track"].AsLong(),
                        GetTimestamp(limit)));
                    return;
                }

                // withheld
                JsonValue statusWithheld;
                if (graph.TryGetValue("status_withheld", out statusWithheld))
                {
                    handler.OnMessage(new StreamWithheld(
                        statusWithheld["user_id"].AsLong(),
                        statusWithheld["id"].AsLong(),
                        ((JsonArray)statusWithheld["withheld_in_countries"]).Select(s => s.AsString()).ToArray(),
                        GetTimestamp(statusWithheld)));
                    return;
                }
                JsonValue userWithheld;
                if (graph.TryGetValue("user_withheld", out userWithheld))
                {
                    handler.OnMessage(new StreamWithheld(
                        userWithheld["id"].AsLong(),
                        ((JsonArray)statusWithheld["withheld_in_countries"]).Select(s => s.AsString()).ToArray(),
                        GetTimestamp(statusWithheld)));
                    return;
                }

                // disconnect
                JsonValue disconnect;
                if (graph.TryGetValue("disconnect", out disconnect))
                {
                    handler.OnMessage(new StreamDisconnect(
                        (DisconnectCode)disconnect["code"].AsLong(),
                        disconnect["stream_name"].AsString(),
                        disconnect["reason"].AsString(),
                        GetTimestamp(disconnect)));
                    return;
                }

                // stall warning
                JsonValue warning;
                if (graph.TryGetValue("warning", out warning))
                {
                    var timestamp = GetTimestamp(warning);
                    var code = warning["code"].AsString();
                    if (code == "FALLING_BEHIND")
                    {
                        handler.OnMessage(new StreamStallWarning(
                            code,
                            warning["message"].AsString(),
                            (int)warning["percent_full"].AsLong(),
                            timestamp));
                        return;
                    }
                }

                // user update
                JsonValue @event;
                if (graph.TryGetValue("event", out @event))
                {
                    var ev = @event.AsString().ToLower();
                    if (ev == "user_update")
                    {
                        // parse user_update only in generic streams.
                        handler.OnMessage(new StreamUserEvent(
                            new TwitterUser(graph["source"]),
                            new TwitterUser(graph["target"]),
                            ev, graph["created_at"].AsString().ParseTwitterDateTime()));
                        return;
                    }
                    // unknown event...
                    handler.OnMessage(new StreamUnknownMessage("event: " + ev, graph.ToString()));
                }

                // unknown event-type...
                handler.OnMessage(new StreamUnknownMessage(null, graph.ToString()));

            }
            catch (Exception ex)
            {
                handler.OnException(new StreamParseException(
                    "Stream graph parse failed.", graph.ToString(), ex));
            }
        }
Example #13
0
 /// <summary>
 ///     Constructor for a key-value argument (not a file upload).</summary>
 /// <param name="name">
 ///     Name of the argument.</param>
 /// <param name="value">
 ///     Value of the argument. This value is encoded as JSON syntax.</param>
 /// <seealso cref="HArg(string,string)"/>
 /// <seealso cref="HArg(string,string,string,byte[])"/>
 public HArg(string name, JsonValue value)
 {
     Name = name;
     Value = value.ToString();
 }
Example #14
0
 public void NewMessage(JsonValue aMessage)
 {
     Console.WriteLine("Send {0}", aMessage.ToString());
     iBrowserTabProxy.Send(aMessage);
 }
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            string tourneyID = Intent.GetStringExtra("tourneyID") ?? "None";

            auth      = FirebaseAuth.GetInstance(MainActivity.app);
            mDatabase = FirebaseDatabase.Instance.Reference;

            base.OnCreate(savedInstanceState);

            // Loading tournaments
            var firebase = new FirebaseClient("https://fir-test-1bdb3.firebaseio.com/");
            var items    = await firebase
                           .Child("tournaments")
                           .OnceAsync <TournamentViewModel>();

            foreach (var item in items)
            {
                if (item.Object.TournamentID.Equals(tourneyID))
                {
                    query = item.Object;
                    break;
                }
            }



            SetContentView(Resource.Layout.ViewEventPage);

            // Adding Components
            TextView title      = FindViewById <TextView>(Resource.Id.tournamentTitle);
            TextView startDate  = FindViewById <TextView>(Resource.Id.startDateTitle);
            TextView finishDate = FindViewById <TextView>(Resource.Id.finishDateTitle);
            TextView awardMoney = FindViewById <TextView>(Resource.Id.awardMoneyTitle);
            TextView format     = FindViewById <TextView>(Resource.Id.formatTitle);

            Button location       = FindViewById <Button>(Resource.Id.location);
            Button adminProfile   = FindViewById <Button>(Resource.Id.adminProfileView);
            Button register       = FindViewById <Button>(Resource.Id.register);
            Button edit           = FindViewById <Button>(Resource.Id.edit);
            Button bracketURL     = FindViewById <Button>(Resource.Id.bracketLink);
            Button updateResult   = FindViewById <Button>(Resource.Id.updateResult);
            Button searchOpponent = FindViewById <Button>(Resource.Id.searchOpponentButton);
            Button endTournament  = FindViewById <Button>(Resource.Id.finishTournament);

            AutoCompleteTextView matchNumber        = FindViewById <AutoCompleteTextView>(Resource.Id.MatchNumberText);
            AutoCompleteTextView matchWinner        = FindViewById <AutoCompleteTextView>(Resource.Id.matchWinnerText);
            AutoCompleteTextView searchOpponentText = FindViewById <AutoCompleteTextView>(Resource.Id.searchOpponent);

            ImageView showCase    = FindViewById <ImageView>(Resource.Id.tourneyImageShowCaseEventPage);
            string    showCaseURL = "https://firebasestorage.googleapis.com/v0/b/fir-test-1bdb3.appspot.com/o/ShowCase.png?alt=media&token=f0c6e2e7-e9fc-46e8-a2ad-528ebf778aad";

            Glide.With(this).Load(showCaseURL).Apply(RequestOptions.CircleCropTransform()).Into(showCase);


            if (MainActivity.decision.Equals("Login as Admin"))
            {
                register.Enabled = false;
            }

            if (query.Finished.Equals("true"))
            {
                matchNumber.Enabled  = false;
                matchWinner.Enabled  = false;
                updateResult.Enabled = false;
            }

            if (!query.AdminID.Equals(auth.CurrentUser.Email))
            {
                edit.Enabled          = false;
                matchNumber.Enabled   = false;
                matchWinner.Enabled   = false;
                updateResult.Enabled  = false;
                endTournament.Enabled = false;
            }

            if (query.online.Equals("true"))
            {
                location.Enabled = false;
            }

            if (query.Live.Equals("false"))
            {
                bracketURL.Enabled   = false;
                matchNumber.Enabled  = false;
                matchWinner.Enabled  = false;
                updateResult.Enabled = false;
            }
            else
            {
                register.Enabled = false;
            }

            if (query.Paid.Equals("false"))
            {
                register.Text = "Register for Free";
            }
            else
            {
                register.Text = "Register for " + query.EntryFee + "¢";
            }



            title.Text      = query.Title ?? "";
            startDate.Text  = query.StartDate ?? "";
            finishDate.Text = query.FinishDate ?? "";
            awardMoney.Text = query.AwardMoney + "" ?? "";
            format.Text     = query.Format ?? "";

            endTournament.Click += async(sender, e) =>
            {
                if (query.Finished.Equals("true"))
                {
                    Toast.MakeText(ApplicationContext, "Tournament is already Over!", ToastLength.Short).Show();
                }
                else
                {
                    if (query.Live.Equals("true"))
                    {
                        await mDatabase.Child("tournaments").Child(tourneyID).Child("Finished").SetValueAsync("true");

                        Toast.MakeText(ApplicationContext, "Tournament Ended", ToastLength.Short).Show();
                    }
                    else
                    {
                        Toast.MakeText(ApplicationContext, "You cannot end a tournament before it goes live!", ToastLength.Short).Show();
                    }
                }
            };

            searchOpponent.Click += async(sender, e) =>
            {
                // Loading users' data for searching
                var users = await firebase.Child("users").OnceAsync <UserViewModel>();

                bool   found  = false;
                string userID = "";

                foreach (var user in users)
                {
                    if (user.Object.Email.Equals(searchOpponentText.Text.Trim().ToLower()))
                    {
                        found  = true;
                        userID = user.Object.Email;
                        break;
                    }
                }

                if (found)
                {
                    Intent viewProfileActivity = new Intent(Application.Context, typeof(ViewProfileActivity));
                    viewProfileActivity.PutExtra("toEmail", userID); // Recipient email
                    HomeActivity.fromHome = false;
                    StartActivity(viewProfileActivity);
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Invalid user", ToastLength.Short).Show();
                }
            };

            updateResult.Click += async(sender, e) =>
            {
                int  spo;
                bool validInputs = false;

                // Getting user input values

                int  matchNo;
                bool result = int.TryParse(matchNumber.Text, out matchNo);

                int  playerNo;
                bool result2 = int.TryParse(matchWinner.Text, out playerNo);

                if (result && result2)
                {
                    string url = "https://api.challonge.com/v1/tournaments/" + query.BracketID + "/matches.json?api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy";
                    // Create an HTTP web request using the URL:
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                    request.ContentType = "application/json";
                    request.Method      = "GET";
                    request.Timeout     = 20200000;

                    // Send the request to the server and wait for the response:
                    using (WebResponse response = await request.GetResponseAsync())
                    {
                        // Get a stream representation of the HTTP web response:
                        using (Stream stream = response.GetResponseStream())
                        {
                            // Use this stream to build a JSON document object:
                            JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                            foreach (JsonValue abc in jsonDoc)
                            {
                                JsonValue match = abc["match"];

                                spo = match["suggested_play_order"];

                                if (spo == matchNo)
                                {
                                    id          = match["id"];
                                    validInputs = true;

                                    if (playerNo == 1)
                                    {
                                        matchWinnerID = match["player1_id"];
                                        matchScore    = "1-0";
                                    }
                                    else if (playerNo == 2)
                                    {
                                        matchWinnerID = match["player2_id"];
                                        matchScore    = "0-1";
                                    }
                                    else
                                    {
                                        validInputs = false;
                                    }

                                    break;
                                }
                            }
                        }
                    }

                    // Now updating the result of that particular match
                    if (validInputs)
                    {
                        url = "https://api.challonge.com/v1/tournaments/" + query.BracketID + "/matches/" + id + ".json?api_key=nzFuvS0FNlSVr7KWKdTpoCqP4EXhPAlyMccTfIyy&match[winner_id]=" + matchWinnerID + "&match[scores_csv]=" + matchScore;
                        // Create an HTTP web request using the URL:
                        request               = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
                        request.ContentType   = "application/json";
                        request.Method        = "PUT";
                        request.ContentLength = 0;
                        request.Timeout       = 20200000;

                        // Send the request to the server and wait for the response:
                        using (WebResponse response = await request.GetResponseAsync())
                        {
                            // Get a stream representation of the HTTP web response:
                            using (Stream stream = response.GetResponseStream())
                            {
                                // Use this stream to build a JSON document object:
                                JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                                Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                            }
                        }
                    }
                    else
                    {
                        Toast.MakeText(ApplicationContext, "Either Match number or Player number is not valid. Try again.", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "Match Number and Player number must be whole numbers", ToastLength.Long).Show();
                }
            };

            bracketURL.Click += (sender, e) =>
            {
                Intent viewBracket = new Intent(Application.Context, typeof(ViewTournamentBracketActivity));
                viewBracket.PutExtra("url", query.BracketURL);
                StartActivity(viewBracket);
            };

            edit.Click += (sender, e) =>
            {
                Intent editTournament = new Intent(Application.Context, typeof(AddTournamentActivity));
                editTournament.PutExtra("tourneyID", tourneyID);
                StartActivity(editTournament);
            };

            location.Click += (sender, e) =>
            {
                Intent viewTournamentLocation = new Intent(Application.Context, typeof(ViewTournamentLocationActivity));
                viewTournamentLocation.PutExtra("coords", query.Location);
                StartActivity(viewTournamentLocation);
            };

            adminProfile.Click += (sender, e) =>
            {
                Intent viewProfileActivity = new Intent(Application.Context, typeof(ViewProfileActivity));
                viewProfileActivity.PutExtra("toEmail", query.AdminID); // Recipient email
                HomeActivity.fromHome = false;
                StartActivity(viewProfileActivity);
            };

            register.Click += async(sender, e) =>
            {
                string temp     = query.Participants;
                string entryFee = query.EntryFee;

                // Temp change here from null to ""
                if (temp == null)
                {
                    if (query.Paid.Equals("false"))
                    {
                        temp = "";

                        temp += auth.CurrentUser.Email;

                        await mDatabase.Child("tournaments").Child(tourneyID).Child("Participants").SetValueAsync(temp);

                        Toast.MakeText(ApplicationContext, "Registered", ToastLength.Long).Show();
                    }
                    else
                    {
                        // Render the view from the type generated from RazorView.cshtml
                        var model = new PaymentSendModel()
                        {
                            TournamentID = tourneyID, EntryFee = entryFee, NewParticipant = "true", Participants = "none", PlayerEmail = auth.CurrentUser.Email
                        };
                        //string query = "?tourneyID=" + tourneyID + "&entryFee=" + entryFee + "&NewParticipant=true&PlayerEmail=" + auth.CurrentUser.Email;
                        var template = new PaymentSendRazorView()
                        {
                            Model = model
                        };
                        var page = template.GenerateString();

                        // Load the rendered HTML into the view with a base URL
                        // that points to the root of the bundled Assets folder
                        // It is done in another activity
                        Intent makePaymentActivity = new Intent(Application.Context, typeof(MakePaymentActivity));
                        makePaymentActivity.PutExtra("page", page);
                        StartActivity(makePaymentActivity);
                    }
                }
                else
                {
                    bool registered = false;

                    string[] temps = temp.Split(',');

                    if (temps.Count() == int.Parse(query.ParticipantsLimit))
                    {
                        Toast.MakeText(ApplicationContext, "Registration is full!", ToastLength.Long).Show();
                    }
                    else
                    {
                        foreach (string item in temps)
                        {
                            if (item.Equals(auth.CurrentUser.Email))
                            {
                                registered = true;
                                Toast.MakeText(ApplicationContext, "Already Registered", ToastLength.Long).Show();
                                break;
                            }
                        }

                        if (!registered)
                        {
                            if (query.Paid.Equals("false"))
                            {
                                temp += "," + auth.CurrentUser.Email;

                                await mDatabase.Child("tournaments").Child(tourneyID).Child("Participants").SetValueAsync(temp);

                                Toast.MakeText(ApplicationContext, "Registered", ToastLength.Long).Show();
                            }
                            else
                            {
                                // Render the view from the type generated from RazorView.cshtml
                                var model = new PaymentSendModel()
                                {
                                    TournamentID = tourneyID, EntryFee = entryFee, NewParticipant = "false", Participants = temp, PlayerEmail = auth.CurrentUser.Email
                                };
                                //string query = "?tourneyID=" + tourneyID + "&entryFee=" + entryFee + "&NewParticipant=true&PlayerEmail=" + auth.CurrentUser.Email;
                                var template = new PaymentSendRazorView()
                                {
                                    Model = model
                                };
                                var page = template.GenerateString();

                                // Load the rendered HTML into the view with a base URL
                                // that points to the root of the bundled Assets folder
                                // It is done in another activity
                                Intent makePaymentActivity = new Intent(Application.Context, typeof(MakePaymentActivity));
                                makePaymentActivity.PutExtra("page", page);
                                StartActivity(makePaymentActivity);
                            }
                        }
                    }
                }


                /*
                 * if (query.Participants == null)
                 *  query.Participants = "";
                 *
                 * query.Participants += test + ",";
                 * db.Update(query);
                 * query = (from s in db.Table<TournamentViewModel>()
                 *       where s.TournamentID == tourneyID
                 *       select s).FirstOrDefault();
                 *
                 * Intent viewTournamentsActivity = new Intent(Application.Context, typeof(ViewTournamentsActivity));
                 * viewTournamentsActivity.PutExtra("email", test);
                 * viewTournamentsActivity.PutExtra("userType", userType);
                 * StartActivity(viewTournamentsActivity);
                 * Toast.MakeText(ApplicationContext, "Registered", ToastLength.Long).Show();
                 */
            };
        }
Example #16
0
        static int Main(string[] args)
        {
            string    file = null;
            Stringify todo = Stringify.Hjson;
            bool      err = false, roundtrip = false, rootBraces = true;

            foreach (string arg in args)
            {
                if (arg == "-j")
                {
                    todo = Stringify.Formatted;
                }
                else if (arg == "-c")
                {
                    todo = Stringify.Plain;
                }
                else if (arg == "-h")
                {
                    todo = Stringify.Hjson;
                }
                else if (arg == "-r")
                {
                    roundtrip = true; todo = Stringify.Hjson;
                }
                else if (arg == "-n")
                {
                    rootBraces = false;
                }
                else if (!arg.StartsWith("-"))
                {
                    if (file == null)
                    {
                        file = arg;
                    }
                    else
                    {
                        err = true;
                    }
                }
                else
                {
                    err = true;
                }
            }

            if (err || file == null)
            {
                Console.WriteLine("hjsonc [OPTION] FILE");
                Console.WriteLine("Options:");
                Console.WriteLine("  -h  Hjson output (default)");
                Console.WriteLine("  -r  Hjson output, round trip with comments");
                Console.WriteLine("  -j  JSON output (formatted)");
                Console.WriteLine("  -c  JSON output (compact)");
                Console.WriteLine("  -n  omit braces for the root object (Hjson).");
                return(1);
            }

            JsonValue data = HjsonValue.Load(file, new HjsonOptions {
                KeepWsc = roundtrip
            });

            if (todo == Stringify.Hjson)
            {
                Console.WriteLine(data.ToString(new HjsonOptions {
                    KeepWsc = roundtrip, EmitRootBraces = rootBraces
                }));
            }
            else
            {
                Console.WriteLine(data.ToString(todo));
            }
            return(0);
        }
Example #17
0
 public static JsonValue valueOrDefault(JsonValue jsonObject, string key, string defaultValue)
 {
     // Returns jsonObject[key] if it exists. If the key doesn't exist returns defaultValue and
     // logs the anomaly into the Chronojump log.
     if (jsonObject.ContainsKey(key))
     {
         return(jsonObject [key]);
     }
     else
     {
         LogB.Information("JsonUtils::valueOrDefault: returning default (" + defaultValue + ") from JSON: " + jsonObject.ToString());
         return(defaultValue);
     }
 }
Example #18
0
        //Creates the main attributes of the page when it is loaded
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View v = inflater.Inflate(Resource.Layout.myProperties, container, false);

            mainLayout = v.FindViewById <LinearLayout>(Resource.Id.mainLayout);
            Button displayProperties = v.FindViewById <Button>(Resource.Id.showProperty);

            id = int.Parse(ap.getAccessKey());

            displayProperties.Click += async delegate
            {
                string    url  = "http://housechecker.co.uk/api/export_property.php";
                JsonValue json = await FetchUserAsync(url);

                string jsonString = json.ToString();
                //Getting the properties from the database and putting it into the list
                propertyList = JsonConvert.DeserializeObject <List <Address> >(jsonString);
                //Getting each property for the current landlord
                foreach (var accomodation in propertyList.Where(a => a.user_id.Equals(id)))
                {
                    //Creating the layout for the properties
                    LinearLayout newLayout = new LinearLayout(this.Context);
                    newLayout.Orientation = Orientation.Vertical;
                    TextView displayAddress = new TextView(this.Context);
                    displayAddress.Text = "Address: " + accomodation.address1 + ", " + accomodation.address2 + "\nCity: " +
                                          accomodation.city + "\nPostcode " + accomodation.postcode;
                    displayAddress.Typeface = Typeface.DefaultBold;
                    displayAddress.TextSize = 16;
                    displayAddress.Gravity  = GravityFlags.Center;

                    //Button to allow for more informaiton

                    ImageView imageView = new ImageView(this.Context);

                    try
                    {
                        string imageURL = accomodation.image.Remove(0, 2);
                        imageURL = "http://housechecker.co.uk" + imageURL;
                        WebRequest request = WebRequest.Create(imageURL);
                        // Creates the image URL based from what is stored in the database
                        WebResponse resp       = request.GetResponse();
                        Stream      respStream = resp.GetResponseStream();
                        Bitmap      bmp        = BitmapFactory.DecodeStream(respStream);
                        Bitmap      image      = Bitmap.CreateScaledBitmap(bmp, 500, 500, false);
                        // Resizes the image to fit
                        respStream.Dispose();
                        imageView.SetImageBitmap(image);
                        imageView.RefreshDrawableState();
                        // Creates it and sets it to the view
                    }
                    catch (Exception e)
                    {
                        imageView.SetImageDrawable(Resources.GetDrawable(Resource.Drawable.propertyStock));
                    }

                    imageView.Click += (senderNew, eNew) =>
                    {
                        FragmentTransaction fragmentTx     = FragmentManager.BeginTransaction();
                        PropertyDetail      propertyDetail = new PropertyDetail();
                        Bundle bundle = new Bundle();
                        bundle.PutString("accomID", accomodation.id.ToString());
                        propertyDetail.Arguments = bundle;
                        fragmentTx.Replace(Resource.Id.content_frame, propertyDetail);
                        fragmentTx.Commit();
                        // Creates a click event function for the image so it will go to the selected property
                    };

                    newLayout.AddView(imageView);
                    newLayout.AddView(displayAddress);
                    mainLayout.AddView(newLayout);
                }
            };
            displayProperties.CallOnClick();
            return(v);
        }
Example #19
0
        public void WriteValue(JsonValue value)
        {
            if (value.IsNull())
            {
                return;
            }
            if (value.GetValueType() == typeof(List <object>))
            {
                document_.Append('[');
                int size = value.GetLength();
                for (int ArrayIndex = 0; ArrayIndex < size; ++ArrayIndex)
                {
                    if (ArrayIndex > 0)
                    {
                        document_.Append(',');
                    }

                    WriteValue((value.Get(ArrayIndex)));
                }
                document_.Append(']');
            }
            else if (value.GetValueType() == typeof(Dictionary <String, object>))
            {
                string[] keys = value.GetKeys();

                document_.Append('{');

                for (int DicIndex = 0; DicIndex != keys.Length; ++DicIndex)
                {
                    if (DicIndex != 0)
                    {
                        document_.Append(',');
                    }

                    document_.Append(QuoteString(keys[DicIndex]));
                    document_.Append(':');

                    WriteValue((value.Get(keys[DicIndex])));
                }
                document_.Append('}');
            }
            else if (value.GetValueType() == typeof(string))
            {
                document_.Append(QuoteString(value.GetString()));
            }
            else if (value.GetValueType() == typeof(bool))
            {
                if (value.GetBoolean())
                {
                    document_.Append("true");
                }
                else
                {
                    document_.Append("false");
                }
            }
            else
            {
                document_.Append(value.ToString());
            }
        }
		public object Deserialize(JsonValue value, JsonMapper mapper)
		{
			return JsonConvert.DeserializeObject<ContributionCollection>(value.ToString());
		}
Example #21
0
        private async Task <GetQuotedVendorResponce> QuotedProductsForStore(int receiptID, int storeID)
        {
            GetQuotedProductsForStoreRequest getQuotedProductsForStoreRequest = new GetQuotedProductsForStoreRequest();

            getQuotedProductsForStoreRequest.AuthToken = SessionHelper.AccessToken;
            getQuotedProductsForStoreRequest.RecieptId = receiptID;
            getQuotedProductsForStoreRequest.StoreId   = storeID;
            JsonValue GetQuoteRecieptResponse = await HttpRequestHelper <GetQuotedProductsForStoreRequest> .POSTreq(ServiceTypes.GetQuotedProductsForStore, getQuotedProductsForStoreRequest);

            GetQuotedVendorResponce getQuotedResponce = JsonConvert.DeserializeObject <GetQuotedVendorResponce>(GetQuoteRecieptResponse.ToString());

            if (getQuotedResponce.IsSuccess)
            {
                List <QuotedProductsForStoreModal> lstGetReciepts = getQuotedResponce.LstProducts.Select(dc => new QuotedProductsForStoreModal()
                {
                    CreatedOn = dc.AddedOn,
                    Name      = dc.Name,
                    Price     = dc.Price,
                    RecieptID = (int)dc.RecieptID,
                    Quantity  = dc.Quantity,
                    SubTotal  = dc.SubTotal,
                    StoreName = dc.Name
                }).ToList();

                QuotedProductsForStoreData = new ObservableCollection <QuotedProductsForStoreModal>();

                foreach (QuotedProductsForStoreModal getQuoteReciept in lstGetReciepts)
                {
                    getQuoteReciept.Total = Convert.ToDouble(getQuoteReciept.Quantity) * Convert.ToDouble(getQuoteReciept.Price);
                    QuotedProductsForStoreData.Add(getQuoteReciept);
                }
            }
            else
            {
            }
            return(getQuotedResponce);
        }
Example #22
0
        /// <summary>
        /// Attempts to connect to a users dropbox. First, the dropbox_file_converter_config.json file will be checked for an access key which will be used to attempt to gain access to a users Dropbox. If this fails for whatever reason, then the user will go through Dropbox's OAuth2 procedure for obtaining an access key.
        /// </summary>
        public void ConnectToDropbox(ref JsonValue config)
        {
            bool connected = false;

            while (!connected)
            {
                //Attempt to load a previously saved access key from the config file
                string accessKey = (string)config["access_key"];

                //Attempt to start a Dropbox database connection with the access key
                try
                {
                    //If the loaded access key is not an empty string, try to establish a dropbox connection with it
                    if (accessKey != string.Empty)
                    {
                        //Establish the dropbox connection
                        Console.WriteLine("Attempting dropbox connection...");
                        dbx = new DropboxClient(accessKey);

                        //Check if the previously established connection is valid by making a small request of the users account name
                        var getAccount = Task.Run((Func <Task <Dropbox.Api.Users.FullAccount> >)dbx.Users.GetCurrentAccountAsync);
                        getAccount.Wait();
                        Console.WriteLine("Dropbox connection established. Connected as {0}!\n", getAccount.Result.Name.DisplayName);
                        connected = true;
                    }
                    else
                    {
                        Console.WriteLine("No access key found for user. Attempting to obtain one...\n");
                    }
                }
                catch
                {
                    Console.WriteLine("Access key from config JSON not valid. Will have to obtain another...\n");
                }

                try
                {
                    //Use Dropbox's OAuth2 feature to authenticate new users, if the user does not have a valid access key
                    if (!connected)
                    {
                        //Use the dropbox app key to redirect the user to a webpage, giving them the choice to allow this app to access their Dropbox
                        Console.WriteLine("Opening authorisation webpage...");
                        Uri webpage = DropboxOAuth2Helper.GetAuthorizeUri(dropboxAppKey);
                        System.Diagnostics.Process.Start(webpage.ToString());

                        //If the user chooses to allow the app to access their Dropbox, then they will be given a key to paste back into this app
                        Console.WriteLine("Please paste in the key provided to you below:");
                        string key = Console.ReadLine();
                        Console.WriteLine("\nThank you, attempting dropbox connection now...");

                        //Use this key in conjunction with the dropbox app secret to obtain an access key that can be used to access the users Dropbox
                        var getAccessKeyTask = Task.Run(() => DropboxOAuth2Helper.ProcessCodeFlowAsync(key, dropboxAppKey, dropboxAppSecret));
                        getAccessKeyTask.Wait();

                        //Save the new access key to the config JSON, format it to make it more human readable, and save it back to the app's root
                        config["access_key"] = getAccessKeyTask.Result.AccessToken.ToString();
                        File.WriteAllText("dropbox_file_converter_config.json", config.ToString().Replace("{", "{" + Environment.NewLine).Replace(",", "," + Environment.NewLine));
                    }
                }
                catch
                {
                    Console.WriteLine("Something went wrong trying to obtain an access token. Program will now close...");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
            }
        }
Example #23
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            //Set buttons and main layout
            View v = inflater.Inflate(Resource.Layout.myReviews, container, false);

            mainLayout = v.FindViewById <LinearLayout>(Resource.Id.mainLayout);
            Button showReviews = v.FindViewById <Button>(Resource.Id.showReviews);

            //Get ID from previous page
            id = int.Parse(ap.getAccessKey());

            showReviews.Click += async delegate
            {
                //Grab url json data for the review tables
                string url = "http://housechecker.co.uk/api/export_review.php";
                //Get the json data
                JsonValue json = await FetchUserAsync(url);

                //convert to string
                string jsonString = json.ToString();
                //Set the review list
                reviewList = JsonConvert.DeserializeObject <List <Review> >(jsonString);

                //For every review with user id that equals the current user id
                foreach (var reviews in reviewList.Where(a => a.user_id.Equals(id)))
                {
                    //Get url of the property table which shows every property
                    url  = "http://housechecker.co.uk/api/export_property.php";
                    json = await FetchUserAsync(url);

                    Address accom = JsonConvert.DeserializeObject <List <Address> >(json.ToString())
                                    .Where(a => a.id == reviews.property_id).FirstOrDefault();

                    //start dynamically creating layout of the reviews
                    LinearLayout reviewDisplay = new LinearLayout(this.Context);
                    reviewDisplay.Orientation = Orientation.Vertical;

                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
                    lp.SetMargins(100, 20, 0, 0);

                    //Set accomodation title and display the review
                    TextView accomTitle    = new TextView(this.Context);
                    TextView displayReview = new TextView(this.Context);

                    reviewDisplay.LayoutParameters = lp;

                    accomTitle.TextSize    = 20;
                    displayReview.TextSize = 16;

                    //Display the reviews which belong to the user
                    displayReview.Text = "Review title: " + reviews.title + "\nReview Comment: "
                                         + reviews.comment + "\nReview Rating: " + reviews.rating;
                    accomTitle.Text = accom.address1;

                    reviewDisplay.AddView(accomTitle);
                    reviewDisplay.AddView(displayReview);


                    mainLayout.AddView(reviewDisplay);
                }
            };
            showReviews.CallOnClick();
            return(v);
        }
Example #24
0
 public static string AsString(this JsonValue jsonValue)
 {
     return(jsonValue is JsonPrimitive jsonPrimitiveValue && jsonPrimitiveValue.JsonType == JsonType.String
         ? (string)jsonValue
         : jsonValue.ToString());
 }
 internal static string AsString(this JsonValue obj)
 {
     return(obj.ToString().Replace(DOUBLE_QUOTE, DOUBLE_QUOTE_SUB).Replace("\"", "").Replace(DOUBLE_QUOTE_SUB, "\"").Replace(DOUBLE_SLASH, @"\"));
 }
Example #26
0
        //Get coordinaes of all users
        public IEnumerable <Coordinate> getUserLocations()
        {
            JsonValue json2  = GetCoords("http://gsios.azurewebsites.net/location/userLocations");
            var       coords = JsonConvert.DeserializeObject <IEnumerable <Coordinate> >(json2.ToString());

            return(coords);
        }
        private static void ImportTags(JsonObject jTagsRoot,
                                       Dictionary <string, List <string> > dTags)
        {
            try
            {
                JsonValue jTags = jTagsRoot.Items["children"];
                if (jTags == null)
                {
                    Debug.Assert(false); return;
                }
                JsonArray arTags = (jTags.Value as JsonArray);
                if (arTags == null)
                {
                    Debug.Assert(false); return;
                }

                foreach (JsonValue jvTag in arTags.Values)
                {
                    JsonObject jTag = (jvTag.Value as JsonObject);
                    if (jTag == null)
                    {
                        Debug.Assert(false); continue;
                    }

                    JsonValue jvName = jTag.Items["title"];
                    if (jvName == null)
                    {
                        Debug.Assert(false); continue;
                    }
                    string strName = jvName.ToString();
                    if (string.IsNullOrEmpty(strName))
                    {
                        Debug.Assert(false); continue;
                    }

                    List <string> lUris;
                    dTags.TryGetValue(strName, out lUris);
                    if (lUris == null)
                    {
                        lUris          = new List <string>();
                        dTags[strName] = lUris;
                    }

                    JsonValue jvUrls = jTag.Items["children"];
                    if (jvUrls == null)
                    {
                        Debug.Assert(false); continue;
                    }
                    JsonArray arUrls = (jvUrls.Value as JsonArray);
                    if (arUrls == null)
                    {
                        Debug.Assert(false); continue;
                    }

                    foreach (JsonValue jvPlace in arUrls.Values)
                    {
                        JsonObject jUrl = (jvPlace.Value as JsonObject);
                        if (jUrl == null)
                        {
                            Debug.Assert(false); continue;
                        }

                        JsonValue jvUri = jUrl.Items["uri"];
                        if (jvUri == null)
                        {
                            Debug.Assert(false); continue;
                        }

                        string strUri = jvUri.ToString();
                        if (!string.IsNullOrEmpty(strUri))
                        {
                            lUris.Add(strUri);
                        }
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Example #28
0
        /// <summary>
        /// Check for external updates.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void outputTimer_Tick(object sender, EventArgs e)
        {
            //Show console messages.
            while (Util.Terminal.output.Count != 0)
            {
                txtConsole.AppendText(Util.Terminal.output.Dequeue());
            }

            if (SyncServer != null)
            {
                //check for new clients.
                {
                    GameSocket gs = SyncServer.getSocket();
                    if (gs != null)
                    {
                        Util.Terminal.WriteLine("New Sync Client Connected [" + ((glSocket)gs).IPAddress + "]");
                        clientList.Add(gs);
                    }
                }

                //check for DC'd clients.
                Queue <GameSocket> toDestroy = new Queue <GameSocket>();
                foreach (GameSocket gs in clientList)
                {
                    if (!gs.isConnected)
                    {
                        toDestroy.Enqueue(gs);
                    }
                }

                //remove DC'd clients.
                while (toDestroy.Count != 0)
                {
                    clientList.Remove(toDestroy.Dequeue());
                }

                //Do we have any games to collect?
                lock (AchronWeb.features.consts.gameSendList)
                {
                    foreach (GameSocket gs in clientList)
                    {
                        if (gs.isConnected)
                        {
                            PacketData data = gs.GetData();
                            if (data != null)
                            {
                                data.beginRead();
                                AchronWeb.features.achronGame remoteGame = jsonToGame(JsonValue.Parse(data.readString()));

                                if (remoteGame.host == "127.0.0.1" || remoteGame.host == "::1")
                                {
                                    remoteGame.host = ((glSocket)gs).IPAddress;
                                }

                                //send the game to other clients too.
                                foreach (GameSocket gsN in clientList)
                                {
                                    if (gsN == gs)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        PacketData outData = new PacketData(0x01, 0x02);
                                        outData.writeString(gameToJson(remoteGame).ToString());
                                        gsN.SendData(outData);
                                    }
                                }

                                lock (AchronWeb.features.consts.gameList)
                                {
                                    AchronWeb.features.consts.gameCount++;
                                    remoteGame.lastUpdate = AchronWeb.features.consts.GetTime();
                                    remoteGame.gameID     = AchronWeb.features.consts.gameCount;
                                    AchronWeb.features.consts.gameList.Add(remoteGame.gameID, remoteGame);
                                }

                                Util.Terminal.WriteLine("New Remote Game: " + remoteGame.gameName + " / " + remoteGame.level + " / " + remoteGame.host);
                            }
                        }
                    }
                }

                //Do we got any games to send?
                lock (AchronWeb.features.consts.gameSendList)
                {
                    if (AchronWeb.features.consts.gameSendList.Count != 0)
                    {
                        JsonValue toSend = gameToJson(AchronWeb.features.consts.gameSendList.Dequeue());
                        foreach (GameSocket gs in clientList)
                        {
                            if (gs.isConnected)
                            {
                                PacketData pd = new PacketData(0x01, 0x02);
                                pd.writeString(toSend.ToString());
                                gs.SendData(pd);
                            }
                        }
                    }
                }

                txtServerStatus.Text = "Clients: " + clientList.Count;
            }

            if (SyncClient != null)
            {
                if (!SyncClient.isConnected)
                {
                    txtClientStatus.Text  = "Connection Lost";
                    SyncClient            = null;
                    btnHost.Enabled       = true;
                    btnJoinServer.Enabled = true;
                }
                else
                {
                    PacketData data = SyncClient.GetData();
                    if (data != null) //we have a packet.
                    {
                        data.beginRead();
                        AchronWeb.features.achronGame remoteGame = jsonToGame(JsonValue.Parse(data.readString()));

                        if (remoteGame.host == "127.0.0.1" || remoteGame.host == "::1")
                        {
                            remoteGame.host = SyncClient.IPAddress;
                        }

                        lock (AchronWeb.features.consts.gameList)
                        {
                            AchronWeb.features.consts.gameCount++;
                            remoteGame.lastUpdate = AchronWeb.features.consts.GetTime();
                            remoteGame.gameID     = AchronWeb.features.consts.gameCount;
                            AchronWeb.features.consts.gameList.Add(remoteGame.gameID, remoteGame);
                        }

                        Util.Terminal.WriteLine("New Remote Game: " + remoteGame.gameName + " / " + remoteGame.level + " / " + remoteGame.host);
                    }

                    //Do we gots a game to send?
                    if (AchronWeb.features.consts.gameSendList.Count != 0)
                    {
                        JsonValue toSend = gameToJson(AchronWeb.features.consts.gameSendList.Dequeue());

                        if (SyncClient.isConnected)
                        {
                            PacketData pd = new PacketData(0x01, 0x02);
                            pd.writeString(toSend.ToString());
                            SyncClient.SendData(pd);
                        }
                    }

                    txtClientStatus.Text = "Connected";
                }
            }
        }
Example #29
0
        public void persist_exp_for_float_json_values()
        {
            var value = new JsonValue(1e100);

            value.ToString().ShouldEqual("1E+100");
        }
        private async Task <GetQuotedRecieptsForCustomerResponce> QuotedRecieptForCustomer()
        {
            string    AccessToken = SessionHelper.AccessToken;
            JsonValue GetQuotedRecieptCustResponse = await HttpRequestHelper <String> .GetRequest(ServiceTypes.GetQuotedRecieptsForCustomer, AccessToken);

            GetQuotedRecieptsForCustomerResponce getQuotedRecieptsForCustomerResponce = JsonConvert.DeserializeObject <GetQuotedRecieptsForCustomerResponce>(GetQuotedRecieptCustResponse.ToString());

            if (getQuotedRecieptsForCustomerResponce.IsSuccess)
            {
                List <GetQuotedRecieptsForCustomerModel> lstGetReciepts = getQuotedRecieptsForCustomerResponce.LstReciepts.Select(dc => new GetQuotedRecieptsForCustomerModel()
                {
                    Name      = dc.Name,
                    Price     = dc.Price,
                    RecieptID = dc.RecieptID,
                    Status    = dc.Status,
                    StoreID   = dc.StoreID,
                    StoreName = dc.StoreName,
                    Username  = dc.Username
                }).ToList();

                GetQuotedRecieptsForCustomerData = new ObservableCollection <GetQuotedRecieptsForCustomerModel>();

                foreach (GetQuotedRecieptsForCustomerModel getReciept in lstGetReciepts)
                {
                    GetQuotedRecieptsForCustomerData.Add(getReciept);
                }
            }
            else
            {
            }
            return(getQuotedRecieptsForCustomerResponce);
        }
Example #31
0
 /// <constructor />
 public JsonContent(JsonValue json) : base(json.ToString(), Encoding.UTF8, MediaType.Json)
 {
 }
        private async Task <Country> GetCountryInfo(string latitude, string longitude)
        {
            string country = await GetCountryCode(latitude, longitude);

            string         url     = "http://api.geonames.org/countryInfoJSON?formatted=true&lang=es&country=" + country + "&username=rdomingo86&style=full";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "GET";

            using (WebResponse response = await request.GetResponseAsync())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    JsonValue json = await Task.Run(() => JsonObject.Load(stream));

                    CountryInfoResult result = JsonConvert.DeserializeObject <CountryInfoResult>(json.ToString());
                    return(result.country[0]);
                }
            }
        }
		public object Deserialize(JsonValue value, JsonMapper mapper)
		{
			var deserializedObject = JsonConvert.DeserializeObject<CardsResponse>(value.ToString());
			deserializedObject.RawJson = value.ToString();
			return deserializedObject;
		}
        private async void UpdateQuoteClicked()
        {
            UpdateProductAvailabilityRequest updateProductAvailabilityRequest = new UpdateProductAvailabilityRequest();

            updateProductAvailabilityRequest.ProductInfo = new List <ProductDTO>();
            updateProductAvailabilityRequest.AuthToken   = SessionHelper.AccessToken;
            foreach (QueuedOrderProductsModal item in ListGetProduct)
            {
                ProductDTO productDTO = new ProductDTO();
                productDTO.AddedOn     = DateTime.Now.ToString();
                productDTO.IsAvailable = true;
                productDTO.Name        = item.Name;
                productDTO.Price       = item.Price;
                productDTO.ProductID   = item.ProductID;
                productDTO.RecieptID   = item.RecieptID;
                productDTO.Quantity    = item.Quantity;
                productDTO.UpdatedOn   = DateTime.Now.ToString();
                updateProductAvailabilityRequest.ProductInfo.Add(productDTO);
            }
            JsonValue AddProductResponse = await HttpRequestHelper <UpdateProductAvailabilityRequest> .POSTreq(ServiceTypes.UpdateProductAvailability, updateProductAvailabilityRequest);

            UpdateProductAvailabilityResponse updateProductAvailabilityResponse = JsonConvert.DeserializeObject <UpdateProductAvailabilityResponse>(AddProductResponse.ToString());

            if (updateProductAvailabilityResponse.IsSuccess)
            {
                await App.Current.MainPage.DisplayAlert("Error", updateProductAvailabilityResponse.Message, "Ok");
            }
        }
 public override string ToString()
 {
     return(Value.ToString());
 }
        private async Task <AddProductResponce> GetProduct(int receiptID)
        {
            JsonValue GetProductResponce = await HttpRequestHelper <String> .GetRequest(ServiceTypes.GetProducts, SessionHelper.AccessToken + "/" + receiptID);

            AddProductResponce getProductResponse = JsonConvert.DeserializeObject <AddProductResponce>(GetProductResponce.ToString());

            if (getProductResponse.IsSuccess)
            {
                ListGetProduct = getProductResponse.Lstproducts.Select(dc => new QueuedOrderProductsModal()
                {
                    AddedOn     = dc.AddedOn,
                    IsAvailable = dc.IsAvailable,
                    Name        = dc.Name,
                    Price       = dc.Price,
                    ProductID   = dc.ProductID,
                    Quantity    = dc.Quantity,
                    RecieptID   = dc.RecieptID,
                    UpdatedOn   = dc.UpdatedOn,
                    Total       = 0
                }).ToList();

                foreach (QueuedOrderProductsModal getProduct in lstGetProduct)
                {
                    ProductData.Add(getProduct);
                }
            }
            else
            {
            }
            return(getProductResponse);
        }
Example #37
0
        private async void ListItemClicked(int position)
        {
            Android.Support.V4.App.Fragment fragment = null;
            switch (position)
            {
            case 0:
                int       id   = int.Parse(ap.getAccessKey());
                string    url  = "http://housechecker.co.uk/api/export.php";
                JsonValue json = await FetchUserAsync(url);

                string         jsonString      = json.ToString();
                List <Student> listOfLandlords = JsonConvert.DeserializeObject <List <Student> >(jsonString);
                var            user            = listOfLandlords.Where(a => a.Id == id).FirstOrDefault();

                if (user.Type == "Landlord")
                {
                    IMenuItem item1 = navigationView.Menu.FindItem(Resource.Id.nav_extra1);
                    item1.SetTitle("Add Property");
                    IMenuItem item2 = navigationView.Menu.FindItem(Resource.Id.nav_extra2);
                    item2.SetTitle("My Properties");
                    // If the user type is Landlord, it sets the two extra features to these options
                }
                else
                {
                    IMenuItem item1 = navigationView.Menu.FindItem(Resource.Id.nav_extra1);
                    item1.SetTitle("Favourite Properties");
                    IMenuItem item2 = navigationView.Menu.FindItem(Resource.Id.nav_extra2);
                    item2.SetTitle("My Reviews");
                    // If you're a student the options are different
                }
                // Gets the list of users and finds the one that matches your ID

                usernameDisplay = FindViewById <TextView>(Resource.Id.navBarHeader);
                // Gets the display name for the nav bar


                if (user.Type == "Landlord")
                {
                    fragment             = LandlordDashboard.NewInstance();
                    usernameDisplay.Text = user.CompanyName;
                    // Sets the name to company name if you are a landlord
                }
                else
                {
                    fragment             = StudentDashboard.NewInstance();
                    usernameDisplay.Text = user.Name;
                    // And to username if you are a student
                }
                break;

            case 1:
                fragment = PropertyDetail.NewInstance();
                Bundle idBundle = new Bundle();
                idBundle.PutString("accomID", "77");
                fragment.Arguments = idBundle;
                // This code calls the new fragment and places it on the screen aka loading a new page
                break;

            case 2:
                fragment = SearchPage.NewInstance();
                break;

            case 3:
                fragment = Profile.NewInstance();
                break;

            case 4:
                if (userType == "Landlord")
                {
                    fragment = AddProperty.NewInstance();
                }
                else
                {
                    fragment = DisplayFavourites.NewInstance();
                }
                break;

            case 5:
                if (userType == "Landlord")
                {
                    fragment = MyProperties.NewInstance();
                }
                else
                {
                    fragment = MyReviews.NewInstance();
                }
                break;

            case 6:
                id   = int.Parse(ap.getAccessKey());
                url  = "http://housechecker.co.uk/api/export.php";
                json = await FetchUserAsync(url);

                jsonString      = json.ToString();
                listOfLandlords = JsonConvert.DeserializeObject <List <Student> >(jsonString);
                user            = listOfLandlords.Where(a => a.Id == id).FirstOrDefault();

                if (user.Type == "Landlord")
                {
                    IMenuItem item1 = navigationView.Menu.FindItem(Resource.Id.nav_extra1);
                    item1.SetTitle("Add Property");
                    IMenuItem item2 = navigationView.Menu.FindItem(Resource.Id.nav_extra2);
                    item2.SetTitle("My Properties");
                    // If the user type is Landlord, it sets the two extra features to these options
                }
                else
                {
                    IMenuItem item1 = navigationView.Menu.FindItem(Resource.Id.nav_extra1);
                    item1.SetTitle("Favourite Properties");
                    IMenuItem item2 = navigationView.Menu.FindItem(Resource.Id.nav_extra2);
                    item2.SetTitle("My Reviews");
                    // If you're a student the options are different
                }
                // Gets the list of users and finds the one that matches your ID

                url  = "http://housechecker.co.uk/api/display.php";
                json = await FetchUserAsync(url);

                jsonString = json.ToString();
                var addressList = JsonConvert.DeserializeObject <List <Address> >(jsonString);

                accomID  = addressList.Where(a => a.address1 == markerTitle).FirstOrDefault().id;
                fragment = PropertyDetail.NewInstance();
                Bundle bundle = new Bundle();
                bundle.PutString("accomID", accomID.ToString());
                fragment.Arguments = bundle;
                // Gets the accomodation that has been clicked on from the map page and then loads it
                break;
            }

            SupportFragmentManager.BeginTransaction()
            .Replace(Resource.Id.content_frame, fragment)
            .Commit();
            // Commits the transaction
        }
        public void Update(IEnumerable <ClothesItem> source)
        {
            var needUpdate = false;

            foreach (var clothesItem in _clothesList)
            {
                foreach (var item in source)
                {
                    if (clothesItem.TypeId == item.TypeId && clothesItem.Size != item.Size)
                    {
                        clothesItem.Size = item.Size;
                        _allSizeData[AppSettings.SelectedBrandId.ToString()][item.TypeId] = item.Size;
                        needUpdate = true;
                    }
                }
            }

            if (needUpdate)
            {
                Task.Run(() => _filesystem.SaveFile($"{AccountService.AccountDataFolder}/{AppSettings.SelectedAccount}_data.json", _allSizeData.ToString()));
            }
        }
Example #39
0
        public async Task Plan(String startText, String destinationText)
        {
            goStation.Visibility     = ViewStates.Invisible;
            goDestination.Visibility = ViewStates.Invisible;
            AddButton.Visibility     = ViewStates.Invisible;
            goNavigate.Visibility    = ViewStates.Invisible;
            plan    = true;
            nearest = false;

            startText       = startText.Trim();
            destinationText = destinationText.Trim();
            string url1  = "http://chargetogoapi.azurewebsites.net/api/chargepoint/destination/" + startText;
            string json1 = await FetchGoogleDataAsync(url1);

            string url2  = "http://chargetogoapi.azurewebsites.net/api/chargepoint/destination/" + destinationText;
            string json2 = await FetchGoogleDataAsync(url2);

            XmlDocument xml1 = new XmlDocument();

            xml1.LoadXml(json1);
            XmlNodeList xnList1 = xml1.SelectNodes("/location");

            XmlDocument xml2 = new XmlDocument();

            xml2.LoadXml(json2);
            XmlNodeList xnList2 = xml2.SelectNodes("/location");

            destinationLat = "0"; destinationLng = "0";
            startLat       = "0"; startLng = "0";
            string url3 = "0";

            foreach (XmlNode xn in xnList1)
            {
                startLat = xn["lat"].InnerText;
                startLng = xn["lng"].InnerText;
                //Console.WriteLine("Name: {0} {1}", destinationLat, destinationLng);
            }
            foreach (XmlNode xn in xnList2)
            {
                destinationLat = xn["lat"].InnerText;
                destinationLng = xn["lng"].InnerText;
                //Console.WriteLine("Name: {0} {1}", destinationLat, destinationLng);
            }


            url3 = "http://chargetogoapi.azurewebsites.net/api/chargepoint/route/" + startLat + "/" + startLng + "/" + destinationLat + "/" + destinationLng + "/" + range;

            //for polyline
            x = Convert.ToDouble(destinationLat);
            y = Convert.ToDouble(destinationLng);

            JsonValue json3 = await FetchDataAsync(url3);

            viaPointsToDestination = DeserializeToList <ChargePointDto>(json3.ToString());

            GMap.Clear();
            goPlan.Visibility = ViewStates.Visible;
            //location
            LatLng latlng            = new LatLng(Convert.ToDouble(startLat), Convert.ToDouble(startLng));
            var    options           = new MarkerOptions().SetPosition(latlng).SetTitle(startText).SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueAzure));
            Marker DestinationMarker = GMap.AddMarker(options);

            //destination
            LatLng        destination = new LatLng(Convert.ToDouble(destinationLat), Convert.ToDouble(destinationLng));
            MarkerOptions options1    = new MarkerOptions().SetPosition(destination).SetTitle(destinationText).SetSnippet("Destination").SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueAzure));

            GMap.AddMarker(options1);

            //stations
            foreach (var point in viaPointsToDestination)
            {
                AddNewPoint(point.Name, point.Latitude, point.Longitude, point.Info.Replace(", ", "\n"));
            }

            CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(MidPoint(Convert.ToDouble(startLat), Convert.ToDouble(startLng), Convert.ToDouble(destinationLat), Convert.ToDouble(destinationLng)), 8);

            GMap.MoveCamera(camera);

            //Toast.MakeText(Application.Context, editText.Text, ToastLength.Long).Show();
        }
Example #40
0
 public static JsonValue valueOrDefault(JsonValue jsonObject, string key, string defaultValue)
 {
     // Returns jsonObject[key] if it exists. If the key doesn't exist returns defaultValue and
     // logs the anomaly into the Chronojump log.
     if (jsonObject.ContainsKey (key)) {
         return jsonObject [key];
     } else {
         LogB.Information ("JsonUtils::valueOrDefault: returning default (" + defaultValue + ") from JSON: " + jsonObject.ToString ());
         return defaultValue;
     }
 }