Newtonsoft.Json.JsonConvert.DeserializeObject(string, Newtonsoft.Json.JsonSerializerSettings)

Here are the examples of the csharp api Newtonsoft.Json.JsonConvert.DeserializeObject(string, Newtonsoft.Json.JsonSerializerSettings) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5104 Examples 7

19 View Source File : AuditoriumWebClient.cs
License : Apache License 2.0
Project Creator : 42skillz

public async Task<AuditoriumDto> GetAuditoriumSeatingFor(string showId)
        {
            var response = await _webClient.GetAsync($"{_uriAuditoriumSeatingRepository}api/v1/data_for_auditoriumSeating/{showId}");

            response.EnsureSuccessStatusCode();

            var jsonAuditoriumSeating = await response.Content.ReadreplacedtringAsync();

            var auditoriumSeatingDto = JsonConvert.DeserializeObject<AuditoriumDto>(jsonAuditoriumSeating, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});

            return auditoriumSeatingDto;
        }

19 View Source File : SeatReservationsWebClient.cs
License : Apache License 2.0
Project Creator : 42skillz

public async Task<ReservedSeatsDto> GetReservedSeats(string showId)
        {
            var jsonSeatReservations = await GetDataForReservations(showId);

            var reservationsSeatsDto = JsonConvert.DeserializeObject<ReservedSeatsDto>(jsonSeatReservations,
                    new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});

            return reservationsSeatsDto;
        }

19 View Source File : SpeechRecognitionService.cs
License : MIT License
Project Creator : ActiveNick

SpeechServiceResult ParseWebSocketSpeechResult(string result)
        {
            SpeechServiceResult wssr = new SpeechServiceResult();

            using (StringReader sr = new StringReader(result))
            {
                int linecount = 0;
                string line;
                bool isBodyStarted = false;
                string bodyJSON = "";

                // Parse each line in the WebSocket results to extra the headers and JSON body.
                // The header is in the first 3 lines of the response, the rest is the body.
                while ((line = sr.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (line.Length > 0)
                    {
                        switch (linecount)
                        {
                            case 0:  // X-RequestID
                                if (line.Substring(0, 11).ToLower() == "x-requestid")
                                {
                                    wssr.RequestId = line.Substring(12);
                                }
                                break;

                            case 1:  // Content-Type & charset on the same line, separated by a semi-colon
                                var sublines = line.Split(new[] { ';' });

                                if (sublines[0].Trim().Substring(0, 12).ToLower() == "content-type")
                                {
                                    wssr.ContentType = sublines[0].Trim().Substring(13);

                                    if (sublines.Length > 1)
                                    {
                                        if (sublines[1].Trim().Substring(0, 7).ToLower() == "charset")
                                        {
                                            wssr.CharSet = sublines[1].Trim().Substring(8);

                                        }
                                    }
                                }
                                break;

                            case 2:  // Path
                                if (line.Substring(0, 4).ToLower() == "path")
                                {
                                    string pathStr = line.Substring(5).Trim().ToLower();
                                    switch (pathStr)
                                    {
                                        case "turn.start":
                                            wssr.Path = SpeechServiceResult.SpeechMessagePaths.TurnStart;
                                            break;
                                        case "speech.startdetected":
                                            wssr.Path = SpeechServiceResult.SpeechMessagePaths.SpeechStartDetected;
                                            break;
                                        case "speech.hypothesis":
                                            wssr.Path = SpeechServiceResult.SpeechMessagePaths.SpeechHypothesis;
                                            //jobtelemetry.ReceivedMessages.Append<Receivedmessage>(
                                            //    new Receivedmessage(

                                            //    ));
                                            break;
                                        case "speech.enddetected":
                                            wssr.Path = SpeechServiceResult.SpeechMessagePaths.SpeechEndDetected;
                                            break;
                                        case "speech.phrase":
                                            wssr.Path = SpeechServiceResult.SpeechMessagePaths.SpeechPhrase;
                                            break;
                                        case "turn.end":
                                            wssr.Path = SpeechServiceResult.SpeechMessagePaths.SpeechEndDetected;
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                break;

                            default:
                                if (!isBodyStarted)
                                {
                                    // For all non-empty lines past the first three (header), once we encounter an opening brace '{'
                                    // we treat the rest of the response as the main results body which is formatted in JSON.
                                    if (line.Substring(0, 1) == "{")
                                    {
                                        isBodyStarted = true;
                                        bodyJSON += line + lineSeparator;
                                    }
                                }
                                else
                                {
                                    bodyJSON += line + lineSeparator;
                                }
                                break;
                        } 
                    }

                    linecount++;
                }

                // Once the full response has been parsed between header and body components,
                // we need to parse the JSON content of the body itself.
                if (bodyJSON.Length > 0)
                {
                    RecognitionContent srr = JsonConvert.DeserializeObject<RecognitionContent>(bodyJSON);
                    if (srr != null)
                    {
                        wssr.Result = srr;
                    }
                }
            }

            return wssr;
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : adamped

public void DifferentialSync()
		{
			var changed = _rows.Where(x => x.LastUpdated >= _lastSync || (x.Deleted != null && x.Deleted >= _lastSync)).ToList();

			var list = new List<string>();

			foreach (var item in changed)
			{
				var original = JsonConvert.DeserializeObject<TableSchema>(item.Original);

				// A better way to implement this is needed. It only detects the first column changed.
				// This would need to group them all together and send them.
				// But again, this is a sample, I can't do all the work for you :)
				// At the moment this will only work with Name or Description

				if (original.Name != item.Name)
					list.Add(JsonConvert.SerializeObject(new { Id = item.Id, LastUpdated=item.LastUpdated, Name = item.Name }));
				else if (original.Description != item.Description)
					list.Add(JsonConvert.SerializeObject(new { Id = item.Id, LastUpdated = item.LastUpdated, Description = item.Description }));

				item.Original = null; // Clear original as now sync'd
			}

			_server.DifferentialSync(list);

			foreach (var row in _server.PullSync(_lastSync))
				if (!_rows.Any(x => x.Id == row.Id)) // Does not exist, hence insert
					InsertRow(new ClientTableSchema(row));
				else if (row.Deleted.HasValue)
					DeleteRow(row.Id);
				else
					UpdateRow(new ClientTableSchema(row));

			_lastSync = DateTimeOffset.Now;
		}

19 View Source File : SubmitConverter.cs
License : MIT License
Project Creator : afaniuolo

private void CreateAddressBookSender(Guid destSubmitActionItemId)
		{
			var desreplacedem = _destMasterRepository.GetSitecoreItem(destSubmitActionItemId);
			if (desreplacedem != null &&
			    desreplacedem.Fields.FirstOrDefault(f => f.FieldId == Guid.Parse(SubmitActionConstants.SubmitActionFieldId))?.Value ==
			    SubmitActionConstants.SubmitActionField_SendEmailActionValue)
			{
				var sendEmail = JsonConvert.DeserializeObject<SendEmailAction>(desreplacedem.Fields
					.First(f => f.FieldId == new Guid(SubmitActionConstants.ParametersFieldId)).Value);

				var emailFromValue = sendEmail.from;

				if (!string.IsNullOrEmpty(emailFromValue) && emailFromValue.IndexOf('@') > 0)
				{
					var emailAddressMetadata = _metadataProvider.GereplacedemMetadataByTemplateName("Email Address");
					var senderItems = _destMasterRepository.GetSitecoreDescendantsItems(
						emailAddressMetadata.destTemplateId,
						new Guid(EmailAddressConstants.EmailAddressSendersFolderId));

					
					if (!senderItems.Any(item => item.Fields.FirstOrDefault(f => f.FieldId == Guid.Parse(EmailAddressConstants.EmailAddressValueFieldId)) != null 
					                             && string.Equals(item.Fields.First(f => f.FieldId == Guid.Parse(EmailAddressConstants.EmailAddressValueFieldId)).Value, emailFromValue, StringComparison.InvariantCultureIgnoreCase)))
					{
						var addressSenderItemName = emailFromValue.Substring(0, emailFromValue.IndexOf('@'));

						// Set Email Address item fields
						var addressSenderItemFieldValues = new Dictionary<Guid, string>();
						addressSenderItemFieldValues.Add(new Guid(EmailAddressConstants.EmailAddressValueFieldId),
							emailFromValue); // Value field

						CreateEmailAddressItem("Email Address", addressSenderItemName, addressSenderItemFieldValues);
					}
				}
			}
		}

19 View Source File : LayoutDescriptionEx.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            JObject jo = JObject.Load(reader);
            switch (jo["Type"].Value<int>())
            {
                case 1:
                    return JsonConvert.DeserializeObject<StarsLineDescription>(jo.ToString(), SpecifiedSubclreplacedConversion);
                case 2:
                    return JsonConvert.DeserializeObject<TextOnlyLineDescription>(jo.ToString(), SpecifiedSubclreplacedConversion);
                default:
                    throw new Exception();
            }
        }

19 View Source File : StringsResource.cs
License : MIT License
Project Creator : aimore

public static AppResource FromJson(string json) => JsonConvert.DeserializeObject<AppResource>(json, Converter.Settings);

19 View Source File : ApiService.cs
License : MIT License
Project Creator : aimore

public async static Task<object> GetWordTranslation(string word)
        {
            object responseModel = null;
            var url = $"/translation/text/translate?source=auto&target=de&input={word}";
            if (_httpClient?.BaseAddress == null)
            {
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
                _httpClient.BaseAddress = new Uri(baseUrl);
                _httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Key", apiKey);
            }
            var response = await _httpClient.GetAsync(url);
            using (HttpContent content = response.Content)
            {
                var output = await content.ReadreplacedtringAsync();
                bool hasResponseSucceeded = (response?.StatusCode == System.Net.HttpStatusCode.OK);
                responseModel = hasResponseSucceeded ? JsonConvert.DeserializeObject<TranslationModel>(output) as object : JsonConvert.DeserializeObject<ApiErrorResponseModel>(output) as object;
                if (responseModel is ApiErrorResponseModel)
                    await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("ERROR", ((ApiErrorResponseModel)responseModel)?.Error?.Message, "cancel");
            }

            return responseModel;
        }

19 View Source File : HeroesModel.cs
License : MIT License
Project Creator : aimore

public static Heroes[] FromJson(string json) => JsonConvert.DeserializeObject<Heroes[]>(json, Converter.Settings);

19 View Source File : TranslationModel.cs
License : MIT License
Project Creator : aimore

public static TranslationModel FromJson(string json) => JsonConvert.DeserializeObject<TranslationModel>(json, Converter.Settings);

19 View Source File : ApiService.cs
License : MIT License
Project Creator : aimore

public async static Task<Models.WordDefinitionModel> GetWordDefinitions(string word)
        {
            WordDefinitionModel responseModel = null;
            using (HttpClient client = new HttpClient())
            {
                var url = $"/?define={word}";
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
                client.BaseAddress = new Uri(googleDictionaryUrl);
                //client.DefaultRequestHeaders.Add("X-RapidAPI-Key", apiKey);
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    using (HttpContent content = response.Content)
                    {
                        var output = await content.ReadreplacedtringAsync();
                        if(response?.StatusCode == System.Net.HttpStatusCode.OK)
                            responseModel = JsonConvert.DeserializeObject<WordDefinitionModel>(output);
                        if (responseModel == null)
                            await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("ERROR", "No definitions for this word!", "cancel");
                    }
                }
                return responseModel;
            }
        }

19 View Source File : ObjectStore.cs
License : MIT License
Project Creator : AkiniKites

public static T LoadObject<T>(string path, string name)
        {
            using var s = IoC.Archiver.LoadFileStream(path, $"{Prefix}{name}");
            if (s == null)
                return default;

            using var reader = new StreamReader(s);
            var json = reader.ReadToEnd();

            try
            {
                return JsonConvert.DeserializeObject<T>(json, JsonHelper.Converters);
            }
            catch (Exception ex)
            {
                return default;
            }
        }

19 View Source File : GameCache.cs
License : MIT License
Project Creator : AkiniKites

public bool TryLoadCache(out T data)
        {
            data = default(T);

            if (IoC.CmdOptions.DisableGameCache)
                return false;

            var cacheLock = _cacheLocks.GetOrAdd(CachePath, x => new ReaderWriterLockSlim());
            string json;

            using (cacheLock.UsingReaderLock())
            {
                if (!File.Exists(CachePath))
                    return false;

                json = File.ReadAllText(CachePath);
            }

            var cache = JsonConvert.DeserializeObject<CacheData>(
                json, JsonHelper.Converters);

            if (cache == null || cache.Path != IoC.Settings.GamePath)
            {
                ClearCache();
                return false;
            }

            data = cache.Data;
            return true;
        }

19 View Source File : CharacterReferences.cs
License : MIT License
Project Creator : AkiniKites

private List<ByteSearchResult<CharacterModel>> LoadResults()
        {
            lock (_lock)
            {
                List<ByteSearchResult<CharacterModel>> results = null;
                FileBackup.RunWithBackup(ResultsFile, () =>
                {
                    if (!File.Exists(ResultsFile))
                        return false;
                    var json = File.ReadAllText(ResultsFile);
                    results = JsonConvert.DeserializeObject<List<ByteSearchResult<CharacterModel>>>(json,
                        JsonHelper.Converters);
                    return true;
                });

                return results;
            }
        }

19 View Source File : TransformationModel.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

public static TransformationModel LoadFromJson(string jsonConfig)
        {
            TransformationModel res = JsonConvert.DeserializeObject<TransformationModel>(jsonConfig);
            return res;
        }

19 View Source File : JSONSourceComponentModel.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

public static JSONSourceComponentModel LoadFromJson(string jsonConfig)
        {
            JSONSourceComponentModel res = JsonConvert.DeserializeObject<JSONSourceComponentModel>(jsonConfig);
            return res;
        }

19 View Source File : JSONSourceComponentModel.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

public static JSONDataSourceModel LoadFromJson(string jsonConfig)
        {
            JSONDataSourceModel res = JsonConvert.DeserializeObject<JSONDataSourceModel>(jsonConfig);
            return res;
        }

19 View Source File : JSONSourceComponentModel.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

public static JSONDataMappingModel LoadFromJson(string jsonConfig)
        {
            JSONDataMappingModel res = JsonConvert.DeserializeObject<JSONDataMappingModel>(jsonConfig);
            return res;
        }

19 View Source File : JSONSourceComponentModel.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola

public static JSONAdvancedSettingsModel LoadFromJson(string jsonConfig)
        {
            JSONAdvancedSettingsModel res = JsonConvert.DeserializeObject<JSONAdvancedSettingsModel>(jsonConfig);
            return res;
        }

19 View Source File : DataService.cs
License : MIT License
Project Creator : Aleksbgbg

public T Load<T>(string dataName, Func<string> emptyData)
        {
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(_appDataService.GetFile($"Data/{dataName}.json", emptyData)));
        }

19 View Source File : DataService.cs
License : MIT License
Project Creator : Aleksbgbg

public T LoadAndWipe<T>(string dataName, string emptyData = "")
        {
            string dataFile = _appDataService.GetFile($"Data/{dataName}.json", emptyData);

            string fileData = File.ReadAllText(dataFile);

            if (fileData != emptyData)
            {
                File.WriteAllText(dataFile, emptyData); // Prevent duplicate loading of file if not cleared correctly
            }

            return JsonConvert.DeserializeObject<T>(fileData);
        }

19 View Source File : YouTubeApiService.cs
License : MIT License
Project Creator : Aleksbgbg

private async Task<YouTubeVideo> GetVideo(string id)
        {
            VideosResource.ListRequest videoRequest = _youTubeApiService.Videos.List("snippet");
            videoRequest.Id = id;

            VideoListResponse videoResponse = await videoRequest.ExecuteAsync();

            Video video = videoResponse.Items.First();

            string statistics = await _httpClient.GetStringAsync($"https://www.googleapis.com/youtube/v3/videos?id={video.Id}&key=AIzaSyA6F0Qqlul32ly5jSbnK9FYPL2Ge8Q7nQM&part=statistics");

            return new YouTubeVideo(video, JsonConvert.DeserializeObject<VideoListResponse>(statistics)
                                                      .Items
                                                      .Single()
                                                      .Statistics
                                                      .ViewCount);
        }

19 View Source File : JsonConverter.cs
License : Apache License 2.0
Project Creator : AlexWan

public static List<PurpleWalletUpdate> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<PurpleWalletUpdate>>(json, ConverterWallet.Settings);
        }

19 View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public List<PairInfoResponse> GetSecurities()
        {
            lock (_lock)
            {
                try
                {

                    var request = GetAuthenticatedRequest(Method.GET);
                    var response = new RestClient("https://www.bitstamp.net/api/v2/trading-pairs-info/").Execute(request);

                    if (UpdatePairs != null)
                    {
                        UpdatePairs(JsonConvert.DeserializeObject<List<PairInfoResponse>>(response.Content));
                    }

                    return JsonConvert.DeserializeObject<List<PairInfoResponse>>(response.Content);
                }
                catch (Exception ex)
                {
                    if (LogMessageEvent != null)
                    {
                        LogMessageEvent(ex.ToString(), LogMessageType.Error);
                    }

                    return null;
                }
            }
        }

19 View Source File : JsonConverter.cs
License : Apache License 2.0
Project Creator : AlexWan

public static List<DataObject> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<DataObject>>(json,
                Converter.Settings);
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public decimal GetLeverage(string securityName)
        {
            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var headers = new Dictionary<string, string>();

            headers.Add("Timestamp", timeStamp);
            headers.Add("KEY", _publicKey);
            headers.Add("SIGN", _signer.GetSignStringRest("GET", _host + _path + _wallet + "/positions/" + securityName, "", "", timeStamp));

            var jsecPosition = _requestREST.SendGetQuery("GET", _host + _path + _wallet + "/positions/" + securityName, "", headers);

            var secPosition = JsonConvert.DeserializeObject<GfPosition>(jsecPosition);

            return Converter.StringToDecimal(secPosition.Leverage);
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void SendOrder(Order order)
        {
            decimal outputVolume = order.Volume;
            if (order.Side == Side.Sell)
                outputVolume = -1 * order.Volume;

            CreateOrderRequst jOrder = new CreateOrderRequst()
            {
                Contract = order.SecurityNameCode,
                Iceberg = 0,
                Price = order.Price.ToString(CultureInfo.InvariantCulture),
                Size = Convert.ToInt64(outputVolume),
                Tif = "gtc",
                Text = $"t-{order.NumberUser}"
            };

            string bodyContent = JsonConvert.SerializeObject(jOrder).Replace(" ", "").Replace(Environment.NewLine, "");


            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var headers = new Dictionary<string, string>();

            headers.Add("Timestamp", timeStamp);
            headers.Add("KEY", _publicKey);
            headers.Add("SIGN", _signer.GetSignStringRest("POST", _path + _wallet + "/orders", "", bodyContent, timeStamp));

            var result = _requestREST.SendPostQuery("POST", _host + _path + _wallet, "/orders", Encoding.UTF8.GetBytes(bodyContent), headers);



            CreateOrderResponse orderResponse = JsonConvert.DeserializeObject<CreateOrderResponse>(result);

            if (orderResponse.Status == "finished")
            {
                SendLogMessage($"Order num {order.NumberUser} on exchange.", LogMessageType.Trade);
            }
            else if (orderResponse.Status == "open")
            {
                SendLogMessage($"Order num {order.NumberUser} wait to execution on exchange.", LogMessageType.Trade);
            }
            else
            {
                //err_msg
                dynamic errorData = JToken.Parse(result);
                string errorMsg = errorData.err_msg;

                SendLogMessage($"Order exchange error num {order.NumberUser} : {errorMsg}", LogMessageType.Error);

                order.State = OrderStateType.Fail;

                OnOrderEvent(order);
            }
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void CancelOrder(Order order)
        {
            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var headers = new Dictionary<string, string>();

            headers.Add("Timestamp", timeStamp);
            headers.Add("KEY", _publicKey);
            headers.Add("SIGN", _signer.GetSignStringRest("DELETE", _path + _wallet + $"/orders/{order.NumberMarket}", "", "", timeStamp));

            var result = _requestREST.SendGetQuery("DELETE", _host + _path + _wallet, $"/orders/{order.NumberMarket}", headers);

            CancelOrderResponse cancelResponse = JsonConvert.DeserializeObject<CancelOrderResponse>(result);

            if (cancelResponse.FinishAs == "canceled")
            {
                SendLogMessage($"Order num {order.NumberUser} canceled.", LogMessageType.Trade);
                order.State = OrderStateType.Cancel;
                OnOrderEvent(order);
            }
            else
            {
                SendLogMessage($"Error on order cancel num {order.NumberUser}", LogMessageType.Error);
            }
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private List<Candle> GetCandles(int oldInterval, string security, DateTime startTime, DateTime endTime)
        {
            lock (_locker)
            {
                try
                {
                    var needIntervalForQuery = CandlesCreator.DetermineAppropriateIntervalForRequest(oldInterval, _supportedIntervals, out var needInterval);

                    var from = TimeManager.GetTimeStampSecondsToDateTime(startTime);
                    var to = TimeManager.GetTimeStampSecondsToDateTime(endTime);

                    string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
                    var headers = new Dictionary<string, string>();
                    headers.Add("Timestamp", timeStamp);

                    RestRequestBuilder requestBuilder = new RestRequestBuilder();
                    requestBuilder.AddParam("contract", security);
                    requestBuilder.AddParam("from", from.ToString());
                    requestBuilder.AddParam("to", to.ToString());
                    requestBuilder.AddParam("interval", needIntervalForQuery);

                    PublicUrlBuilder urlBuilder = new PublicUrlBuilder(_host, _path, _wallet);

                    var candlesJson = _requestREST.SendGetQuery("GET", "", urlBuilder.Build("/candlesticks", requestBuilder), headers);

                    var candlesOut = JsonConvert.DeserializeObject<GfCandle[]>(candlesJson);

                    var oldCandles = CreateCandlesFromJson(candlesOut);

                    if (oldInterval == needInterval)
                    {
                        return oldCandles;
                    }

                    var newCandles = CandlesCreator.CreateCandlesRequiredInterval(needInterval, oldInterval, oldCandles);

                    return newCandles;
                }
                catch
                {
                    SendLogMessage(OsLocalization.Market.Message95 + security, LogMessageType.Error);

                    return null;
                }
            }
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private List<Trade> GetTrades(string security, DateTime endTime)
        {
            lock (_locker)
            {
                try
                {
                    var to = TimeManager.GetTimeStampSecondsToDateTime(endTime);

                    string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
                    var headers = new Dictionary<string, string>();
                    headers.Add("Timestamp", timeStamp);

                    RestRequestBuilder requestBuilder = new RestRequestBuilder();
                    requestBuilder.AddParam("contract", security);
                    requestBuilder.AddParam("limit", "1000");
                    requestBuilder.AddParam("to", to.ToString());

                    PublicUrlBuilder urlBuilder = new PublicUrlBuilder(_host, _path, _wallet);

                    var tradesJson = _requestREST.SendGetQuery("GET", "", urlBuilder.Build("/trades", requestBuilder), headers);

                    var tradesOut = JsonConvert.DeserializeObject<GfTrade[]>(tradesJson);

                    var oldTrades = CreateTradesFromJson(tradesOut);

                    return oldTrades;
                }
                catch
                {
                    SendLogMessage(OsLocalization.Market.Message95 + security, LogMessageType.Error);

                    return null;
                }
            }
        }

19 View Source File : JsonConverter.cs
License : Apache License 2.0
Project Creator : AlexWan

public static List<ChangedElement> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<ChangedElement>>(json,
                ConverterTicks.Settings);
        }

19 View Source File : JsonConverter.cs
License : Apache License 2.0
Project Creator : AlexWan

public static List<List<double>> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<List<double>>>(json,
                CandlesConverter.Settings);
        }

19 View Source File : JsonConverter.cs
License : Apache License 2.0
Project Creator : AlexWan

public static List<double> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<double>>(json,
                ConverterLastCandle.Settings);
        }

19 View Source File : JsonConverter.cs
License : Apache License 2.0
Project Creator : AlexWan

public static List<PurpleWalet> FromJson(string json)
        {
            return JsonConvert.DeserializeObject<List<PurpleWalet>>(json, ConverterWallets.Settings);
        }

19 View Source File : KrakenClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void GetBalanceAndPortfolio()
        {
            if (_isConnected == false)
            {
                return;
            }
            try
            {
                var tradeBalance = _kraken.GetTradeBalance("currency", "ZUSD");

                var ret = JsonConvert.DeserializeObject<GetTradeBalanceResponse>(tradeBalance.ToString());

                Portfolio newPortfolio = new Portfolio();
                newPortfolio.Number = "KrakenTradePortfolio";

                if (ret == null ||
                    ret.Result == null)
                {
                    return;
                }

                newPortfolio.ValueCurrent = ret.Result.TradeBalance;
                newPortfolio.ValueBegin = ret.Result.TradeBalance;
                newPortfolio.ValueBlocked = ret.Result.MarginAmount;

                if (NewPortfolioEvent != null)
                {
                    NewPortfolioEvent(newPortfolio);
                }

                _myPortfolio = newPortfolio;
                UpdatePositionOnBoard();

            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : KrakenClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public void GetSecurities()
        {
            if (_isConnected == false)
            {
                return;
            }
            try
            {
                var message = _kraken.GetreplacedetPairs(null);
                var obj = JsonConvert.DeserializeObject<GetreplacedetPairsResponse>(message.ToString());

                if (obj.Error.Count != 0)
                {
                    SendLogMessage(obj.Error[0], LogMessageType.Error);
                    return;
                }

                var replacedets = obj.Result;

                List<Security> securities = new List<Security>();

                for (int i = 0; i < replacedets.Count; i++)
                {
                    if (replacedets.Keys.ElementAt(i).EndsWith(".d"))
                    {
                        continue;
                    }
                    // if (replacedets.Keys.ElementAt(i).StartsWith("X"))
                    // {
                    //     continue;
                    // }
                    /* if (replacedets.Keys.ElementAt(i).StartsWith("XZ"))
                     {
                         continue;
                     }*/

                    replacedetPair pair = replacedets[replacedets.Keys.ElementAt(i)];
                    Security sec = new Security();
                    sec.Name = replacedets.Keys.ElementAt(i);
                    sec.NameFull = pair.WsName;
                    sec.NameClreplaced = pair.AclreplacedQuote;
                    sec.Decimals = pair.PairDecimals;
                    sec.NameId = sec.Name;
                    sec.SecurityType = SecurityType.CurrencyPair;
                    sec.Lot = 1;

                    decimal step = 1;

                    for (int i2 = 0; i2 < pair.PairDecimals; i2++)
                    {
                        step *= 0.1m;
                    }

                    sec.PriceStep = step;
                    sec.PriceStepCost = step;

                    securities.Add(sec);
                }

                if (UpdatePairs != null)
                {
                    for (int i = 0; i < securities.Count; i++)
                    {
                        UpdatePairs(securities[i]);
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan

private BuySellResponse Execute(double amount, double price, string securityUrl)
        {
            lock (_lock)
            {
                try
                {
                    var request = GetAuthenticatedRequest(Method.POST);
                    request.AddParameter("amount", amount.ToString().Replace(",", "."));
                    request.AddParameter("price", price.ToString().Replace(",", "."));

                    var response = new RestClient(securityUrl).Execute(request);

                    if (response.Content.IndexOf("error", StringComparison.Ordinal) > 0)
                    {
                        SendLogMessage("Ошибка на выставлении ордера", LogMessageType.Error);
                        SendLogMessage(response.Content, LogMessageType.Error);
                        return null;
                    }


                    return JsonConvert.DeserializeObject<BuySellResponse>(response.Content);
                }
                catch (Exception ex)
                {
                    SendLogMessage(ex.ToString(), LogMessageType.Error);
                    return null;
                }
            }
        }

19 View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public BalanceResponse GetBalance()
        {
            lock (_lock)
            {
                try
                {
                    var request = GetAuthenticatedRequest(Method.POST);
                    var response = new RestClient("https://www.bitstamp.net/api/v2/balance/").Execute(request);

                    if (response.Content.Contains("error"))
                    {
                        SendLogMessage("BitStamp Response Error " + response.Content, LogMessageType.Error);

                        return null;
                    }

                    if (UpdatePortfolio != null)
                    {
                        UpdatePortfolio(JsonConvert.DeserializeObject<BalanceResponse>(response.Content));
                    }

                    return JsonConvert.DeserializeObject<BalanceResponse>(response.Content);
                }
                catch (Exception ex)
                {
                    LogMessageEvent(ex.ToString(), LogMessageType.Error);
                    return null;
                }
            }
        }

19 View Source File : BitStampClient.cs
License : Apache License 2.0
Project Creator : AlexWan

public OrderStatusResponse GetOrderStatus(string orderId)
        {
            lock (_lock)
            {
                try
                {
                    var request = GetAuthenticatedRequest(Method.POST);
                    request.AddParameter("id", orderId);

                    var response = new RestClient("https://www.bitstamp.net/api/order_status/").Execute(request);

                    return JsonConvert.DeserializeObject<OrderStatusResponse>(response.Content);
                }
                catch (Exception ex)
                {
                    SendLogMessage(ex.ToString(), LogMessageType.Error);
                    return null;
                }
            }
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public decimal GetMaxLeverage(string securityName)
        {
            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var headers = new Dictionary<string, string>();

            headers.Add("Timestamp", timeStamp);
            headers.Add("KEY", _publicKey);
            headers.Add("SIGN", _signer.GetSignStringRest("GET", _host + _path + _wallet + "/positions/" + securityName, "", "", timeStamp));

            var jsecPosition = _requestREST.SendGetQuery("GET", _host + _path + _wallet + "/positions/" + securityName, "", headers);

            var secPosition = JsonConvert.DeserializeObject<GfPosition>(jsecPosition);

            return Converter.StringToDecimal(secPosition.LeverageMax);
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void GetSecurities()
        {
            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var headers = new Dictionary<string, string>();
            headers.Add("Timestamp", timeStamp);
            var securitiesJson = _requestREST.SendGetQuery("GET", _host + _path + _wallet, "/contracts", headers);

            var _securities = new List<Security>();

            var jSecurities = JsonConvert.DeserializeObject<GfSecurity[]>(securitiesJson);

            foreach (var jSec in jSecurities)
            {
                try
                {
                    Security security = new Security();

                    var name = jSec.Name.ToUpper();

                    security.Name = name;
                    security.NameFull = security.Name;
                    security.NameId = security.Name;
                    security.NameClreplaced = SecurityType.Futures.ToString();
                    security.SecurityType = SecurityType.Futures;
                    security.Decimals = jSec.MarkPriceRound.Split('.')[1].Count();
                    security.Lot = 1;
                    security.PriceStep = Converter.StringToDecimal(jSec.MarkPriceRound);
                    security.PriceStepCost = Converter.StringToDecimal(jSec.MarkPriceRound);
                    security.State = SecurityStateType.Activ;
                    security.Go = jSec.OrderSizeMin;

                    _securities.Add(security);
                }
                catch (Exception error)
                {
                    throw new Exception("Security creation error \n" + error.ToString());
                }
            }

            OnSecurityEvent(_securities);
        }

19 View Source File : GateIoFuturesServer.cs
License : Apache License 2.0
Project Creator : AlexWan

public override void GetPortfolios()
        {
            string timeStamp = TimeManager.GetUnixTimeStampSeconds().ToString();
            var headers = new Dictionary<string, string>();

            headers.Add("Timestamp", timeStamp);
            headers.Add("KEY", _publicKey);
            headers.Add("SIGN", _signer.GetSignStringRest("GET", _path + _wallet + "/accounts", "", "", timeStamp));

            var result = _requestREST.SendGetQuery("GET", _host + _path + _wallet, "/accounts", headers);

            if (result.Contains("failed"))
            {
                SendLogMessage("GateIFutures: Cant get porfolios", LogMessageType.Error);
                return;
            }

            GfAccount accountInfo = JsonConvert.DeserializeObject<GfAccount>(result);

            Portfolio portfolio = Portfolios[0];

            portfolio.ClearPositionOnBoard();

            PositionOnBoard pos = new PositionOnBoard();
            pos.SecurityNameCode = accountInfo.Currency;
            pos.ValueBegin = Converter.StringToDecimal(accountInfo.Total);
            pos.ValueCurrent = Converter.StringToDecimal(accountInfo.Available);
            pos.ValueBlocked = Converter.StringToDecimal(accountInfo.PositionMargin) + Converter.StringToDecimal(accountInfo.OrderMargin);

            portfolio.SetNewPosition(pos);

            OnPortfolioEvent(Portfolios);
        }

19 View Source File : KrakenMessageSerializer.cs
License : Apache License 2.0
Project Creator : AlexWan

public TKrakenMessage Deserialize<TKrakenMessage>(string json) 
            where TKrakenMessage : clreplaced, IKrakenMessage
        {
            if (string.IsNullOrEmpty(json))
            {
                throw new ArgumentNullException(nameof(json));
            }

            return JsonConvert.DeserializeObject<TKrakenMessage>(json, serializerSettings);
        }

19 View Source File : SkeldMap.cs
License : MIT License
Project Creator : altskop

private void loadPolygons()
        {
            using (StreamReader r = new StreamReader(Constants.FILE_LOCATION + "/Skeld/polygons.json"))
            {
                string json = r.ReadToEnd();
                polygons = JsonConvert.DeserializeObject<List<Polygon>>(json);
            }
        }

19 View Source File : SkeldMap.cs
License : MIT License
Project Creator : altskop

private void loadWaypoints()
        {
            using (StreamReader r = new StreamReader(Constants.FILE_LOCATION + "/Skeld/waypoints.json"))
            {
                string json = r.ReadToEnd();
                waypoints = JsonConvert.DeserializeObject<List<Vertex>>(json);
            }
        }

19 View Source File : SkeldMap.cs
License : MIT License
Project Creator : altskop

private void loadPlaces()
        {
            using (StreamReader r = new StreamReader(Constants.FILE_LOCATION + "/Skeld/places.json"))
            {
                string json = r.ReadToEnd();
                places = JsonConvert.DeserializeObject<List<Vertex>>(json);
            }
        }

19 View Source File : SkeldMap.cs
License : MIT License
Project Creator : altskop

private void loadRegions()
        {
            using (StreamReader r = new StreamReader(Constants.FILE_LOCATION + "/Skeld/regions.json"))
            {
                string json = r.ReadToEnd();
                regions = JsonConvert.DeserializeObject<List<Region>>(json);
            }
        }

19 View Source File : KeyBinding.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static void LoadConfig()
        {
            var settingArrayList = Settings.Default.KeyBinding37;

            if (Settings.Default.IsEightKeyLayout) settingArrayList = Settings.Default.KeyBinding13;
            var settingKeyArrayList = Settings.Default.CtrlKeyBinding;
            if (settingArrayList != null)
                for (var i = 0; i < settingArrayList.Count; i++)
                    _keymap[i + 48] = (int) settingArrayList[i];

            if (settingKeyArrayList != null)
            {
                _ctrKeyMap["OctaveLower"] = (Keys)settingKeyArrayList[0];
                _ctrKeyMap["OctaveHigher"] = (Keys)settingKeyArrayList[1];
            }


            
            var tmpArraylist = JsonConvert.DeserializeObject<ArrayList>(Settings.Default.HotKeyBinding);
            hotkeyArrayList = new ArrayList();
            foreach (JObject j in tmpArraylist)
                hotkeyArrayList.Add(new GlobalHotKey(j["Name"].ToString(), (Modifiers) j["Modifiers"].Value<int>(),
                    (Keys) j["Key"].Value<int>(), j["Enabled"].Value<bool>()));
            
        }

19 View Source File : MainForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private void label1_Click(object sender, EventArgs e)
        {
            var s = new SongSelect();
            string id="";
            s.Getid += (SongSelect.IdSelector)(x =>
            {
                id = x;
            });
            s.ShowDialog();
            if (id!=null)
            {
                var jsonscore=NetMidiDownload.DownloadMidi(id);
                try
                {
                    KeyplayClreplaced keyplay = JsonConvert.DeserializeObject<KeyplayClreplaced>(jsonscore);




                    pathTextBox.Text = keyplay.Filename;
                    Log.overlayLog($"网络文件:{Path.GetFileName(midFileDiag.FileName)}");
                    radioButton2.Checked = true;

                    var bpm = keyplay.BPM;
                    var tmp = new List<string>();

                    if (keyplay.Tracks?.Length != 0)
                        for (var i = 0; i < keyplay.Tracks.Length; i++)
                            tmp.Add($"track_{i}:{keyplay.Tracks[i].name}");


                    trackComboBox.DataSource = tmp;
                    trackComboBox.SelectedIndex = Math.Min(tmp.Count - 1, trackLock);
                    //TODO: if source midi not imported successfully will cause error
                    //TODO: Enhancement issue#14 lock track selection
                    if (bpm >= nudBpm.Maximum)
                        nudBpm.Value = nudBpm.Maximum;
                    else if (bpm <= nudBpm.Minimum)
                        nudBpm.Value = nudBpm.Minimum;
                    else
                        nudBpm.Value = bpm;
                    mtk.netmidi = keyplay;
                    netMidiFlag = true;

                }
                catch (Exception ee)
                {

                   throw ee ;
                }
            }
            
        }

19 View Source File : CommonUtilities.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static async void GetLatestVersion()
        {
            var wc = new WebClient();
            try
            {
                var nowVersion = replacedembly.GetExecutingreplacedembly().GetName().Version.ToString();
               
                System.Threading.Thread.Sleep(50);
                var newVersionJson = await UpdateHelper.UpdateHelper.CheckUpdate();
                System.Threading.Thread.Sleep(50);
                
                try
                {
                    var versionObj = JsonConvert.DeserializeObject<versionObject>(newVersionJson);
                    ParameterController.countDownPacket = versionObj.countDownPacket;
                    ParameterController.ensemblePacket = versionObj.ensemblePacket;
                    ParameterController.ensembleStartPacket = versionObj.ensembleStartPacket;
                    ParameterController.ensembleStopPacket = versionObj.ensembleStopPacket;
                    ParameterController.partyStopPacket = versionObj.partyStopPacket;
                    
                    if (versionObj.isRefuseToUse||versionObj.APIVersion==2)
                    {
                        Environment.Exit(-1);
                    }
                    if (nowVersion != versionObj.Version)
                    {
                        if (MessageBox.Show(new Form() { TopMost = true }, $"检测到新版本{versionObj.Version}已经发布,点击确定下载最新版哦!\r\n " +
                                           $"当然就算你点了取消,这个提示每次打开还会出现的哦!" +
                                           $"下载错误可以去NGA发布帖哦!bbs.nga.cn/read.php?tid=18790669 \r\n" +
                                           $"新版本更新内容:{versionObj.Description}", "哇——更新啦!",
                               MessageBoxButtons.OKCancel,
                               MessageBoxIcon.Information) == DialogResult.OK)
                        {
                            Process.Start("http://blog.ffxiv.cat/index.php/download/");

                        }
                        if (versionObj.isForceUpdate)
                        {
                            Environment.Exit(-2);
                        }
                    }
                       



                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                    Console.WriteLine(e);
                    
                }
                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                
            }
        }

See More Examples