Ejemplo n.º 1
0
        /// <summary>
        /// Reads and writes data to and from the network.
        /// </summary>
        /// <param name="transactionData">JSON representation of the transaction.</param>
        /// <returns></returns>
        public async Task <string> processTransaction(Newtonsoft.Json.Linq.JToken transactionData)
        {
            // Save the request for receipt printing
            // NOTE: possible data loss in multi-thread....
            requestJSON = transactionData.ToString();
            // Start the connection to the device server
            startListener();
            // Get a network stream to read and write to the device server
            NetworkStream stream = client.GetStream();

            Byte[] data = System.Text.Encoding.ASCII.GetBytes(transactionData.ToString());
            // Write the json data to the stream
            log.Write("Writing request: " + requestJSON);
            stream.Write(data, 0, data.Length);
            Byte[] res = new byte[16384];
            // Block waiting for response on stream
            Int32 bytes = stream.Read(res, 0, res.Length);

            responseJSON = System.Text.Encoding.ASCII.GetString(res, 0, bytes);
            // Clean up and return
            stream.Close();
            //client.Close();
            log.Write("Response received: " + responseJSON);
            return(responseJSON);
        }
Ejemplo n.º 2
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Newtonsoft.Json.Linq.JToken t = Newtonsoft.Json.Linq.JToken.FromObject(value);
            writer.Formatting = Formatting.Indented;

            writer.WriteStartObject();

            JObject        o             = (JObject)t;
            IList <string> propertyNames = o.Properties().Select(p => p.Name).ToList();

            // List<JToken> jts = ((Newtonsoft.Json.Linq.JObject)t).Children;  writer.WriteValue("\n");
            foreach (string p in propertyNames)
            {
                writer.Formatting = Formatting.None;
                writer.WritePropertyName(p);
                var s = value.GetType().GetProperty(p).GetValue(value, null);;
                writer.WriteValue(s);
            }

            // if (t.Type != JTokenType.Object)
            // {
            //   t.WriteTo(writer);
            // }
            //else
            //{
            //    JObject o = (JObject)t;
            //    IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList();

            //    o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));

            //    o.WriteTo(writer);
            //}
            writer.WriteEndObject();
            writer.CloseOutput = false;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// リクエストから条件入力インスタンスを取得
        /// </summary>
        /// <param name="src">リクエスト</param>
        /// <returns>条件入力インスタンス</returns>
        private UserSearchCondition getUserSearchCondition(Newtonsoft.Json.Linq.JObject src)
        {
            var searchCondition = new UserSearchCondition();

            Newtonsoft.Json.Linq.JToken jsonToken = null;

            var paramName = string.Empty;

            // パラメータの設定
            paramName = "searchUserId";
            if (src.TryGetValue(paramName, out jsonToken))
            {
                searchCondition.SearchUserId = src[paramName].ToString();
            }
            paramName = "pageIndex";
            if (src.TryGetValue(paramName, out jsonToken))
            {
                searchCondition.PageIndex = (int)src[paramName];
            }
            paramName = "sortKey";
            if (src.TryGetValue(paramName, out jsonToken))
            {
                searchCondition.SortKey = src[paramName].ToString();
            }
            paramName = "sortType";
            if (src.TryGetValue(paramName, out jsonToken))
            {
                searchCondition.SortType = src[paramName].ToString();
            }

            return(searchCondition);
        }
Ejemplo n.º 4
0
 public HttpApiServer(HttpConfig serverConfig)
 {
     mActionFactory = new ActionHandlerFactory();
     if (serverConfig != null)
     {
         ServerConfig = serverConfig;
     }
     else
     {
         string configFile = "HttpConfig.json";
         if (System.IO.File.Exists(configFile))
         {
             using (System.IO.StreamReader reader = new StreamReader(configFile, Encoding.UTF8))
             {
                 string json = reader.ReadToEnd();
                 Newtonsoft.Json.Linq.JToken toke = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                 ServerConfig = toke["HttpConfig"].ToObject <HttpConfig>();
             }
         }
         else
         {
             ServerConfig = new HttpConfig();
         }
     }
     mResourceCenter = new StaticResurce.ResourceCenter(this);
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes the device using stored config file.
        /// </summary>
        /// <param name="DeviceConfigFilePath">File path of the device configuration file</param>
        /// <returns>True if no errors configuring device, False otherwise.</returns>
        public bool initializeDevice(string DeviceConfigFilePath)
        {
            try
            {
                // Read in config file
                string settingsString = System.IO.File.ReadAllText(DeviceConfigFilePath);
                // Trim off carrige returns and line feeds
                int len = settingsString.Length;
                while (settingsString[len - 1] != '}')
                {
                    settingsString = settingsString.Substring(0, len - 1);
                    len            = settingsString.Length;
                }

                // Parse out as JSON
                Newtonsoft.Json.Linq.JObject settings        = Newtonsoft.Json.Linq.JObject.Parse(settingsString);
                Newtonsoft.Json.Linq.JToken  destinationIP   = settings.GetValue("DestinationIP");
                Newtonsoft.Json.Linq.JToken  destinationPort = settings.GetValue("DestinationPort");

                // Set the device parameters
                // TO-DO: setComSettings
                IPAddress = destinationIP.ToString();
                Port      = Int32.Parse(destinationPort.ToString());

                initialized = true;
            }
            catch (Exception e)
            {
                initialized = false;
                log.Write("Error: Device Initialization " + e.StackTrace);
            }
            log.Write("Device Initialized: " + initialized);
            return(initialized);
        }
Ejemplo n.º 6
0
        /**
         * <summary>
         * Convert appropriate <c cref='NJL'>JSON Linq</c> objects to <c cref='Configuration'>Configuration</c> objects.
         * </summary>
         * <param name="jToken">JSON Linq object to convert.</param>
         * <returns>The corresponding <c cref='Configuration'>Configuration</c> or null for empty configuration.</returns>
         * <exception cref="UnhandledJsonTokenException">An item with unhandled runtime type derived from <see cref='NJL.JContainer'/> was encountered inside <paramref name="jToken"/>.</exception>		 */
        public static Configuration?FromJsonLinq(NJL.JToken jToken)
        {
            var pruned = JsonPruner.Transform(jToken);

            return(JsonPruner.Filter(pruned)
                        ? pruned.ToObject <Configuration>(Converter.JsonSerializer)
                        : default);
Ejemplo n.º 7
0
        public void AddInput(Newtonsoft.Json.Linq.JToken Data, OleExec sfcdb)
        {
            string            InsertSql = "";
            T_R_Station_Input input;
            string            ID        = Data["ID"].ToString();
            string            StationID = Data["STATION_ID"].ToString();
            string            InputID   = Data["INPUT_ID"].ToString();
            double            SeqNo     = Convert.ToDouble(Data["SEQ_NO"]);
            string            Rlinput   = Data["REMEMBER_LAST_INPUT"].ToString();
            double            ScanFlag  = Convert.ToDouble(Data["SCAN_FLAG"]);
            string            DName     = Data["DISPLAY_NAME"].ToString();

            try
            {
                input = new T_R_Station_Input(sfcdb, DBTYPE);
                DeleteStationInput(ID, sfcdb);
                Row_R_Station_Input row = (Row_R_Station_Input)input.NewRow();
                row.ID                  = ID;
                row.STATION_ID          = StationID;
                row.INPUT_ID            = InputID;
                row.SEQ_NO              = SeqNo;
                row.SCAN_FLAG           = ScanFlag;
                row.DISPLAY_NAME        = DName;
                row.REMEMBER_LAST_INPUT = Rlinput;
                row.EDIT_EMP            = LoginUser.EMP_NO;
                row.EDIT_TIME           = GetDBDateTime();
                InsertSql               = row.GetInsertString(DBTYPE);
                sfcdb.ExecSQL(InsertSql);
            }
            catch (Exception e)
            {
                //  this.DBPools["SFCDB"].Return(sfcdb);
                throw e;
            }
        }
Ejemplo n.º 8
0
        public void AddStationOutput(Newtonsoft.Json.Linq.JToken Data, OleExec sfcdb)
        {
            string             InsertSql = "";
            T_R_Station_Output StationOutput;
            string             ID          = Data["ID"]?.ToString();
            string             StationID   = Data["R_STATION_ID"]?.ToString();
            string             OutputName  = Data["NAME"]?.ToString();
            double             SeqNo       = Convert.ToDouble(Data["SEQ_NO"]);
            string             SessionType = Data["SESSION_TYPE"]?.ToString();
            string             SessionKey  = Data["SESSION_KEY"]?.ToString();
            string             DisplayType = Data["DISPLAY_TYPE"]?.ToString();

            try
            {
                StationOutput = new T_R_Station_Output(sfcdb, DBTYPE);
                DeleteStationOutput(ID, sfcdb);
                Row_R_Station_Output row = (Row_R_Station_Output)StationOutput.NewRow();
                row.ID           = ID;
                row.R_STATION_ID = StationID;
                row.NAME         = OutputName;
                row.SEQ_NO       = SeqNo;
                row.DISPLAY_TYPE = DisplayType;
                row.SESSION_TYPE = SessionType;
                row.SESSION_KEY  = SessionKey;
                row.EDIT_EMP     = LoginUser.EMP_NO;
                row.EDIT_TIME    = GetDBDateTime();
                InsertSql        = row.GetInsertString(DBTYPE);
                sfcdb.ExecSQL(InsertSql);
            }
            catch (Exception e)
            {
                //   this.DBPools["SFCDB"].Return(sfcdb);
                throw e;
            }
        }
Ejemplo n.º 9
0
        public async Task ApplyConfiguration(Newtonsoft.Json.Linq.JToken configJson)
        {
            var config = new ConfigurationDataUrl(DefaultUrl);

            config.LoadValuesFromJson(configJson);

            var formattedUrl = config.GetFormattedHostUrl();
            var releases     = await PerformQuery(new TorznabQuery(), formattedUrl);

            if (releases.Length == 0)
            {
                throw new Exception("Could not find releases from this URL");
            }

            BaseUrl = formattedUrl;

            var configSaveData = new JObject();

            configSaveData["base_url"] = BaseUrl;

            if (OnSaveConfigurationRequested != null)
            {
                OnSaveConfigurationRequested(this, configSaveData);
            }

            IsConfigured = true;
        }
Ejemplo n.º 10
0
        public HttpConfig LoadConfig()
        {
            string file = Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + mConfigFile;

            if (System.IO.File.Exists(file))
            {
                using (System.IO.StreamReader reader = new StreamReader(mConfigFile, Encoding.UTF8))
                {
                    string json = reader.ReadToEnd();
                    if (string.IsNullOrEmpty(json))
                    {
                        return(new HttpConfig());
                    }
                    Newtonsoft.Json.Linq.JToken toke = (Newtonsoft.Json.Linq.JToken)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    if (toke["HttpConfig"] != null && toke["HttpConfig"].Type == JTokenType.Object)
                    {
                        return(toke["HttpConfig"].ToObject <HttpConfig>());
                    }
                    return(new HttpConfig());
                }
            }
            else
            {
                return(new HttpConfig());
            }
        }
Ejemplo n.º 11
0
        public Json_IRec(Newtonsoft.Json.Linq.JToken jt)
        {
            thisJToken = jt;
            if (jt is JArray)
            {
                thisString = "[Array]";
                foreach (var j in thisJToken.Children())
                {
                    thisSubs.Add(new Json_IRec(j));
                }
            }
            else if (jt is JObject)
            {
                thisString = "[Object]";
                foreach (var j in thisJToken.Children())
                {
                    thisSubs.Add(new Json_IRec(j));
                }
            }
            else if (jt is JProperty)
            {
                var jp  = jt as JProperty;
                var val = jp.Value;
                if (jp.Value is JObject)
                {
                    val = "[Object]";
                }
                if (jp.Value is JArray)
                {
                    val = "[Array]";
                }
                thisString = jp.Name + ": " + val;

                if (jp.Value is JObject | jp.Value is JArray)
                {
                    foreach (var j in jp.Value.Children())
                    {
                        thisSubs.Add(new Json_IRec(j));
                    }
                }
            }

            else
            {
                thisString = jt.Path;
                if (jt is Newtonsoft.Json.Linq.JValue)
                {
                    thisString = (jt as Newtonsoft.Json.Linq.JValue).Value.ToString();
                }
                thisJToken = jt;
                if (jt.HasValues)
                {
                    foreach (var j in thisJToken.Children())
                    {
                        thisSubs.Add(new Json_IRec(j));
                    }
                }
            }
        }
Ejemplo n.º 12
0
 public WebsocketContext(HttpApiServer server, HttpRequest request, Newtonsoft.Json.Linq.JToken parameterData)
 {
     Server         = server;
     Request        = request;
     mParameterData = parameterData;
     AsyncResult    = false;
     Tag            = mParameterData;
 }
Ejemplo n.º 13
0
 public static bool IsNullOrEmpty(Newtonsoft.Json.Linq.JToken token)
 {
     return((token == null) ||
            (token.Type == Newtonsoft.Json.Linq.JTokenType.Array && !token.HasValues) ||
            (token.Type == Newtonsoft.Json.Linq.JTokenType.Object && !token.HasValues) ||
            (token.Type == Newtonsoft.Json.Linq.JTokenType.String && token.ToString() == String.Empty) ||
            (token.Type == Newtonsoft.Json.Linq.JTokenType.Null));
 }
Ejemplo n.º 14
0
 public static dynamic GetValueString(this Newtonsoft.Json.Linq.JToken jObj, params string[] keys)
 {
     try
     {
         return(Ass.P.PStr(Ass.Data.Utils.GetJsonValue(jObj, keys)));
     }
     catch { return(""); }
 }
Ejemplo n.º 15
0
        private static async Task <string> uploadFileAsync(string apikey, string fileOnDisk, string client, int priority,
                                                           MiningIntensity intensity, string origFilename, TimeSpan maxWaitingTime, TimeSpan?restartTaskAfterTime = null,
                                                           Api.CallbackData callBackData = null
                                                           )
        {
            string callBackDataString = "";

            if (callBackData != null)
            {
                callBackDataString = Newtonsoft.Json.JsonConvert.SerializeObject(callBackData);
            }

            var fullUrl = "";

            byte[] resbyte;
            string res = "";

            try
            {
                using (WebOcr wc = new WebOcr())
                {
                    string param = "fn=" + System.Net.WebUtility.UrlEncode((origFilename ?? ""))
                                   + "&client=" + System.Net.WebUtility.UrlEncode(client ?? "")
                                   + "&apikey=" + apikey
                                   + "&priority=" + priority
                                   + "&intensity=" + (int)intensity
                                   + "&expirationIn=" + (int)(maxWaitingTime.TotalSeconds * 1.05) //add 5%
                                   + "&restartIn=" + (int)(restartTaskAfterTime?.TotalSeconds ?? 0)
                                   + "&callbackData=" + System.Net.WebUtility.UrlEncode(callBackDataString);

                    fullUrl = ApiUrl + "addTask.ashx?" + param;
                    resbyte = await wc.UploadFileTaskAsync(fullUrl, "POST", fileOnDisk);

                    res = System.Text.Encoding.UTF8.GetString(resbyte);
                    Newtonsoft.Json.Linq.JToken json = Newtonsoft.Json.Linq.JToken.Parse(res);

                    if (json["taskid"] != null)
                    {
                        return(json["taskid"].ToString());
                    }
                    else
                    {
                        logger.Error($"ExtApi.TextFromFileAsync API Exception\nFile:{origFilename}\n content: " + res);
                        throw new ApiException(res);
                    }
                }
            }
            catch (System.Net.WebException e)
            {
                logger.Debug($"called ext API TextFromFile {fullUrl}.\nResponse: {res}\n" + ApiUrl, e);
                throw new ApiException("called ext API ", e);
            }
            catch (Exception e)
            {
                logger.Debug($"called ext API TextFromFile {fullUrl}.\nResponse: {res}\n" + ApiUrl, e);
                throw;
            }
        }
Ejemplo n.º 16
0
 public bool IPLimitProcess(DataReceivedEventArgs args)
 {
     if (string.IsNullOrEmpty(args.Html) || args.Html.Contains("503 Service Unavailable"))
     {
         return(true);
     }
     Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(args.Html)["success"];
     return((token == null) || (token.ToString() != "True"));
 }
Ejemplo n.º 17
0
        public override void Update(DataSourceContext context, IDataItem item, Newtonsoft.Json.Linq.JToken data)
        {
            var           schema = GetAlpaca(context, true, false, false)["schema"] as JObject;
            TabController tc     = new TabController();
            var           tab    = (TabInfo)item.Item;

            if (HasProperty(schema, "", "TabName"))
            {
                tab.TabName = data["TabName"]?.ToString() ?? "";
            }
            if (HasProperty(schema, "", "Title"))
            {
                tab.Title = data["Title"]?.ToString() ?? "";
            }
            if (HasProperty(schema, "", "Description"))
            {
                tab.Description = data["Description"]?.ToString() ?? "";
            }
            if (HasProperty(schema, "", "Settings"))
            {
                var settings       = data["Settings"] as JObject;
                var settingsSchema = schema["properties"]["Settings"]["properties"] as JObject;
                foreach (var prop in settingsSchema.Properties())
                {
                    if (settings[prop.Name] != null)
                    {
                        tc.UpdateTabSetting(tab.TabID, prop.Name, settings[prop.Name].ToString());
                    }
                    else
                    {
                        tc.DeleteTabSetting(tab.TabID, prop.Name);
                    }
                }
            }
            if (HasProperty(schema, "", "Head"))
            {
                string head           = "";
                var    settings       = data["Head"] as JObject;
                var    settingsSchema = schema["properties"]["Head"]["properties"] as JObject;
                foreach (var prop in settingsSchema.Properties())
                {
                    if (settings[prop.Name] != null)
                    {
                        tc.UpdateTabSetting(tab.TabID, prop.Name, settings[prop.Name].ToString());
                    }
                    else
                    {
                        tc.DeleteTabSetting(tab.TabID, prop.Name);
                    }
                    head += $"<meta property=\"{prop.Name}\" content=\"{prop.Value.ToString()}\" />";
                }
                tab.PageHeadText = head;
            }
            tc.UpdateTab(tab);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Certaines réponses (body) peuvent contenir une erreur et pourtant renvoyer un code http 200
        /// </summary>
        /// <param name="retourWS"></param>
        /// <returns></returns>
        public static RESTErrorDTO CheckBodyIfHaveError(Newtonsoft.Json.Linq.JToken retourWS)
        {
            JToken jtError, jtErrorCode, jtErrorMessage, jtHttpBody;

            jtError        = retourWS.SelectToken("error");
            jtErrorCode    = retourWS.SelectToken("ErrorCode");
            jtErrorMessage = retourWS.SelectToken("ErrorMessage");
            jtHttpBody     = retourWS.SelectToken("HttpBody");

            if (jtErrorCode != null || jtErrorMessage != null || jtHttpBody != null)
            {
                int    code    = 0;
                string message = string.Empty;

                if (jtError != null)
                {
                    // message = ToolsJsonNet.GetValue<string>(jtError);
                    throw new Exception("check jtError");
                }
                if (jtErrorCode != null)
                {
                    // code = ToolsJsonNet.GetValue<int>(jtErrorCode);
                    throw new Exception("check jtErrorCode");
                }
                if (jtErrorMessage != null)
                {
                    // message = ToolsJsonNet.GetValue<string>(jtErrorMessage).Trim();
                    throw new Exception("check jtErrorMessage");
                }
                if (jtHttpBody != null)
                {
                    throw new Exception("check jtHttpBody");

                    /*
                     * if (!String.IsNullOrEmpty(message) && ToolsJsonNet.GetValue<string>(jtHttpBody).Trim().Length > 0)
                     * {
                     *  message += Environment.NewLine;
                     * }
                     *
                     * message += ToolsJsonNet.GetValue<string>(jtHttpBody).Replace("{", string.Empty)
                     *                                      .Replace("}", string.Empty)
                     *                                      .Replace("\\\"", string.Empty)
                     *                                      .Replace("\"", string.Empty)
                     *                                      .Replace("  ", " ").Replace("  ", " ")
                     *                                      .Trim();
                     */
                }

                return(new RESTErrorDTO(RESTErrorType.InBody, code, message));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 19
0
        public IActionResult Find([FromBody] Dictionary <string, object> param)
        {
            // ログインチェック
            if (!isLogin(param))
            {
                return(Unauthorized());
            }

            var userId = string.Empty;

            if (param.ContainsKey("requestData"))
            {
                var requestData = param["requestData"] as Newtonsoft.Json.Linq.JObject;
                Newtonsoft.Json.Linq.JToken jsonToken = null;

                var paramName = string.Empty;

                // パラメータの設定
                paramName = "id";
                if (requestData.TryGetValue(paramName, out jsonToken))
                {
                    userId = requestData[paramName].ToString();
                }
            }

            // 入力チェック
            if (string.IsNullOrEmpty(userId))
            {
                logger.LogError("Pram[{0}]が未設定", nameof(userId));
                return(BadRequest());
            }

            UserModel serviceResult = null;

            try
            {
                serviceResult = service.Find(userId);
            }
            catch (Exception ex)
            {
                logger.LogCritical("[{0}", ex.Message);
                return(BadRequest());
            }

            var status  = ResponseDTO.Results.OK;
            var message = string.Empty;

            if (serviceResult == null)
            {
                status  = ResponseDTO.Results.NG;
                message = ErrorNotFound;
            }

            return(Json(new ResponseDTO(status, message, serviceResult)));
        }
Ejemplo n.º 20
0
 public bool IPLimitProcess(DataReceivedEventArgs args)
 {
     if (string.IsNullOrEmpty(args.Html) || args.Html.Contains("503 Service Unavailable"))
     {
         return(true);
     }
     Newtonsoft.Json.Linq.JObject obj2   = Newtonsoft.Json.Linq.JObject.Parse(args.Html);
     Newtonsoft.Json.Linq.JToken  token  = obj2["jsonObj"];
     Newtonsoft.Json.Linq.JToken  token2 = obj2["result"];
     return((token2 == null) || (token2.ToString() != "1"));
 }
Ejemplo n.º 21
0
        public bool TryGetValue(Newtonsoft.Json.Linq.JToken token, out Dictionary <string, object> item)
        {
            item = null;
            if (!token.HasValues)
            {
                return(false);
            }

            item = token.ToObject <Dictionary <string, object> >();
            return(true);
        }
Ejemplo n.º 22
0
 public override void HandleSuccess(Newtonsoft.Json.Linq.JToken response)
 {
     if (response.Type == JTokenType.Integer && response.ToObject <int>() == 0)
     {
         CallSuccessHandler((T) new MResponseRemoveNode());
     }
     else
     {
         HandleError(MegaApiError.EUNEXPECTED);
     }
 }
Ejemplo n.º 23
0
 public void ReadSettings(Newtonsoft.Json.Linq.JToken jObject)
 {
     try {
         this.LoggingEnabled = bool.TryParse(jObject["LoggingEnabled"]?.ToString() ?? "false", out var _enable) && _enable;
         //this.AutoSize = jObject["AutoSize"]?.ToObject<bool>() ?? this.AutoSize;
         //this.AutoSizeMode = jObject["AutoSize"]?.ToObject<AutoSizeMode>() ?? this.AutoSizeMode;
         //this.AutoScaleDimensions = jObject["AutoSize"]?.ToObject<SizeF>() ?? this.AutoScaleDimensions;
         //this.AutoScaleMode = jObject["AutoSize"]?.ToObject<AutoScaleMode>() ?? this.AutoScaleMode;
     }
     catch (Exception e) {
         Log.Debug(e.ToString());
     }
 }
Ejemplo n.º 24
0
        //处理"msg_attach"值,发送消息的时候需要把json object 转换成string
        internal static void ConvertAttachObjectToString(Newtonsoft.Json.Linq.JToken token)
        {
            var attachmentToken = token.SelectToken(NIMIMMessage.AttachmentPath);

            if (attachmentToken == null)
            {
                return;
            }
            if (attachmentToken.Type == Newtonsoft.Json.Linq.JTokenType.Object)
            {
                var attachValue = attachmentToken.ToString(Formatting.None);
                attachmentToken.Replace(attachValue);
            }
        }
Ejemplo n.º 25
0
        public EqualizerChannelViewModel(Newtonsoft.Json.Linq.JToken jToken)
        {
            ChannelName = jToken[nameof(ChannelName)].Value <string>();

            foreach (var band in jToken["Items"].Children().ToList())
            {
                AddBand(band);
            }

            foreach (object band in Items)
            {
                ((EqualizerBandViewModel)band).PropertyChanged += EqualizerBandViewModel_PropertyChanged;
            }
        }
Ejemplo n.º 26
0
        public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
        {
            string url = string.Format(urlPattern, fromCurrency, toCurrency);

            using (var wc = new WebClient())
            {
                var json = wc.DownloadString(url);

                Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(json);
                decimal exchangeRate = (decimal)token.SelectToken("rate");

                return(Math.Round(amount * exchangeRate, 2).ToString());
            }
        }
Ejemplo n.º 27
0
        public static T GetValue <T>(Newtonsoft.Json.Linq.JToken jtoken)
#endif
        {
            switch (jtoken.Type)
            {
            case Newtonsoft.Json.Linq.JTokenType.Null:
                return(default(T));


            case Newtonsoft.Json.Linq.JTokenType.Integer:
                if (typeof(T) == typeof(int))
                {
                    return((T)(object)(int)jtoken);
                }
                break;

            case Newtonsoft.Json.Linq.JTokenType.String:
                if (typeof(T) == typeof(string))
                {
                    return((T)(object)(string)jtoken);
                }
                else if (typeof(T) == typeof(int))
                {
                    return((T)(object)(int)jtoken);
                }
                break;


            case Newtonsoft.Json.Linq.JTokenType.Array:
            case Newtonsoft.Json.Linq.JTokenType.Boolean:
            case Newtonsoft.Json.Linq.JTokenType.Bytes:
            case Newtonsoft.Json.Linq.JTokenType.Comment:
            case Newtonsoft.Json.Linq.JTokenType.Constructor:
            case Newtonsoft.Json.Linq.JTokenType.Date:
            case Newtonsoft.Json.Linq.JTokenType.Float:
            case Newtonsoft.Json.Linq.JTokenType.Guid:
            case Newtonsoft.Json.Linq.JTokenType.None:
            case Newtonsoft.Json.Linq.JTokenType.Object:
            case Newtonsoft.Json.Linq.JTokenType.Property:
            case Newtonsoft.Json.Linq.JTokenType.Raw:
            case Newtonsoft.Json.Linq.JTokenType.TimeSpan:
            case Newtonsoft.Json.Linq.JTokenType.Undefined:
            case Newtonsoft.Json.Linq.JTokenType.Uri:
            default:
                break;
            }

            throw new NotSupportedException("ToolsJsonNet.GetValue<T>() : jtoken.Type = " + jtoken.Type.ToString() + " -- typeof(T).Name = " + typeof(T).Name);
        }
Ejemplo n.º 28
0
        public static DataTable JsonToDataTable(string json, string tableName)
        {
            bool      columnsCreated = false;
            DataTable dt             = new DataTable(tableName);

            Newtonsoft.Json.Linq.JObject root  = Newtonsoft.Json.Linq.JObject.Parse(json);
            Newtonsoft.Json.Linq.JArray  items = (Newtonsoft.Json.Linq.JArray)root[tableName];

            Newtonsoft.Json.Linq.JObject item   = default(Newtonsoft.Json.Linq.JObject);
            Newtonsoft.Json.Linq.JToken  jtoken = default(Newtonsoft.Json.Linq.JToken);

            for (int i = 0; i <= items.Count - 1; i++)
            {
                // Create the columns once
                if (columnsCreated == false)
                {
                    item   = (Newtonsoft.Json.Linq.JObject)items[i];
                    jtoken = item.First;

                    while (jtoken != null)
                    {
                        dt.Columns.Add(new DataColumn(((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()));
                        jtoken = jtoken.Next;
                    }

                    columnsCreated = true;
                }

                // Add each of the columns into a new row then put that new row into the DataTable
                item   = (Newtonsoft.Json.Linq.JObject)items[i];
                jtoken = item.First;

                // Create the new row, put the values into the columns then add the row to the DataTable
                DataRow dr = dt.NewRow();

                while (jtoken != null)
                {
                    dr[((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()] = ((Newtonsoft.Json.Linq.JProperty)jtoken).Value.ToString();
                    jtoken = jtoken.Next;
                }

                dt.Rows.Add(dr);
            }

            return(dt);
        }
Ejemplo n.º 29
0
    public string UpdateCustomerAddress(string param)
    {
        Newtonsoft.Json.Linq.JObject jObject           = Newtonsoft.Json.Linq.JObject.Parse(param);
        Newtonsoft.Json.Linq.JToken  aspNetUserAddress = jObject.SelectTokens("AspNetUserAddress").FirstOrDefault();

        string email       = aspNetUserAddress["Email"] + "";
        string phoneNumber = aspNetUserAddress["PhoneNumber"] + "";
        string firstname   = aspNetUserAddress["Firstname"] + "";
        string lastname    = aspNetUserAddress["Lastname"] + "";
        string company     = aspNetUserAddress["Company"] + "";
        string street      = aspNetUserAddress["Street"] + "";
        string city        = aspNetUserAddress["City"] + "";
        string zip         = aspNetUserAddress["Zip"] + "";
        string state       = aspNetUserAddress["State"] + "";
        string country     = aspNetUserAddress["Country"] + "";

        return(null);
    }
Ejemplo n.º 30
0
 static int TryGetValue(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)ToLua.CheckObject <Newtonsoft.Json.Linq.JObject>(L, 1);
         string arg0 = ToLua.CheckString(L, 2);
         Newtonsoft.Json.Linq.JToken arg1 = null;
         bool o = obj.TryGetValue(arg0, out arg1);
         LuaDLL.lua_pushboolean(L, o);
         ToLua.PushObject(L, arg1);
         return(2);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }