コード例 #1
0
        public HttpListenerContext Context;                                                          //We store the original data for circumstances where the data is not stored seperatly in this object

        public StandardisedRequestObject(HttpListenerContext Context, ResponseObject ResponseObject) // When creating the object we will require the ListenerContext and the ResponseObject that are being used
        {
            Headers       = Context.Request.Headers;                                                 //Set the objects data
            URL           = Context.Request.RawUrl.ToLower();
            Method        = Context.Request.HttpMethod.ToLower();
            URLSegments   = URL.Split("/".ToCharArray());
            URLParamaters = GetParamaters(Context.Request.RawUrl);
            if (Method == "post")//If the method is post, read the posted data into json format and store it
            {
                string StreamString = new System.IO.StreamReader(Context.Request.InputStream).ReadToEnd();
                if (StreamString != "")
                {
                    RequestData = Newtonsoft.Json.Linq.JToken.Parse(StreamString);
                }
            }
            this.Context        = Context;//Set the objects object references
            this.ResponseObject = ResponseObject;
        }
コード例 #2
0
        GetValue(string key)
        {
            if (this.m_data != null)
            {
                Newtonsoft.Json.Linq.JToken k = this.m_data[key];

                if (k != null)
                {
                    //string[] hello = k.Values<string>();
                    string token = k.ToObject <string>();
                    return(new Microsoft.AspNetCore.Mvc.ModelBinding.ValueProviderResult(
                               new Microsoft.Extensions.Primitives.StringValues(token)
                               ));
                }
            } // End if (this.m_data != null)

            return(Microsoft.AspNetCore.Mvc.ModelBinding.ValueProviderResult.None);
        } // End Function GetValue
 /// <summary>
 /// Constructs a new <see cref="WorkbookFunctionsCumIPmtRequestBuilder"/>.
 /// </summary>
 /// <param name="requestUrl">The URL for the request.</param>
 /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
 /// <param name="rate">A rate parameter for the OData method call.</param>
 /// <param name="nper">A nper parameter for the OData method call.</param>
 /// <param name="pv">A pv parameter for the OData method call.</param>
 /// <param name="startPeriod">A startPeriod parameter for the OData method call.</param>
 /// <param name="endPeriod">A endPeriod parameter for the OData method call.</param>
 /// <param name="type">A type parameter for the OData method call.</param>
 public WorkbookFunctionsCumIPmtRequestBuilder(
     string requestUrl,
     IBaseClient client,
     Newtonsoft.Json.Linq.JToken rate,
     Newtonsoft.Json.Linq.JToken nper,
     Newtonsoft.Json.Linq.JToken pv,
     Newtonsoft.Json.Linq.JToken startPeriod,
     Newtonsoft.Json.Linq.JToken endPeriod,
     Newtonsoft.Json.Linq.JToken type)
     : base(requestUrl, client)
 {
     this.SetParameter("rate", rate, true);
     this.SetParameter("nper", nper, true);
     this.SetParameter("pv", pv, true);
     this.SetParameter("startPeriod", startPeriod, true);
     this.SetParameter("endPeriod", endPeriod, true);
     this.SetParameter("type", type, true);
 }
コード例 #4
0
        public static object ParseFromJsonArray(Type tp, string szJson)
        {
            if (string.IsNullOrEmpty(szJson))
            {
                return(null);
            }

            Newtonsoft.Json.Linq.JArray jarray = Newtonsoft.Json.Linq.JArray.Parse(szJson);
            if (jarray.Count > 0)
            {
                Newtonsoft.Json.Linq.JToken jt = jarray[0];
                return(jt.ToObject(tp));
            }
            else
            {
                return(null);
            }
        }
コード例 #5
0
 /// <summary>
 /// Constructs a new <see cref="WorkbookFunctionsYieldMatRequestBuilder"/>.
 /// </summary>
 /// <param name="requestUrl">The URL for the request.</param>
 /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
 /// <param name="settlement">A settlement parameter for the OData method call.</param>
 /// <param name="maturity">A maturity parameter for the OData method call.</param>
 /// <param name="issue">A issue parameter for the OData method call.</param>
 /// <param name="rate">A rate parameter for the OData method call.</param>
 /// <param name="pr">A pr parameter for the OData method call.</param>
 /// <param name="basis">A basis parameter for the OData method call.</param>
 public WorkbookFunctionsYieldMatRequestBuilder(
     string requestUrl,
     IBaseClient client,
     Newtonsoft.Json.Linq.JToken settlement,
     Newtonsoft.Json.Linq.JToken maturity,
     Newtonsoft.Json.Linq.JToken issue,
     Newtonsoft.Json.Linq.JToken rate,
     Newtonsoft.Json.Linq.JToken pr,
     Newtonsoft.Json.Linq.JToken basis)
     : base(requestUrl, client)
 {
     this.SetParameter("settlement", settlement, true);
     this.SetParameter("maturity", maturity, true);
     this.SetParameter("issue", issue, true);
     this.SetParameter("rate", rate, true);
     this.SetParameter("pr", pr, true);
     this.SetParameter("basis", basis, true);
 }
コード例 #6
0
 /// <summary>
 /// Constructs a new <see cref="WorkbookFunctionsIpmtRequestBuilder"/>.
 /// </summary>
 /// <param name="requestUrl">The URL for the request.</param>
 /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
 /// <param name="rate">A rate parameter for the OData method call.</param>
 /// <param name="per">A per parameter for the OData method call.</param>
 /// <param name="nper">A nper parameter for the OData method call.</param>
 /// <param name="pv">A pv parameter for the OData method call.</param>
 /// <param name="fv">A fv parameter for the OData method call.</param>
 /// <param name="type">A type parameter for the OData method call.</param>
 public WorkbookFunctionsIpmtRequestBuilder(
     string requestUrl,
     IBaseClient client,
     Newtonsoft.Json.Linq.JToken rate,
     Newtonsoft.Json.Linq.JToken per,
     Newtonsoft.Json.Linq.JToken nper,
     Newtonsoft.Json.Linq.JToken pv,
     Newtonsoft.Json.Linq.JToken fv,
     Newtonsoft.Json.Linq.JToken type)
     : base(requestUrl, client)
 {
     this.SetParameter("rate", rate, true);
     this.SetParameter("per", per, true);
     this.SetParameter("nper", nper, true);
     this.SetParameter("pv", pv, true);
     this.SetParameter("fv", fv, true);
     this.SetParameter("type", type, true);
 }
コード例 #7
0
        /** Handle results returned from the document
         */
        public override void _HandleResult(Newtonsoft.Json.Linq.JToken value)
        {
            if (OfficeExtension.Utility._IsNullOrUndefined(value))
            {
                return;
            }
            Newtonsoft.Json.Linq.JObject obj = value as Newtonsoft.Json.Linq.JObject;
            if (obj == null)
            {
                return;
            }

            OfficeExtension.Utility._FixObjectPathIfNecessary(this, obj);
            if (!OfficeExtension.Utility._IsUndefined(obj["Font"]))
            {
                this.Font._HandleResult(obj["Font"]);
            }
        }
        protected override void Analyze(Region region, string regionPointer)
        {
            var jsonPointer = new JsonPointer(regionPointer);

            Newtonsoft.Json.Linq.JToken regionToken = jsonPointer.Evaluate(Context.InputLogToken);

            if (regionToken.HasProperty(SarifPropertyName.EndLine) &&
                region.EndLine < region.StartLine)
            {
                string endLinePointer = regionPointer.AtProperty(SarifPropertyName.EndLine);

                LogResult(
                    endLinePointer,
                    nameof(RuleResources.SARIF1012_Default),
                    region.EndLine.ToInvariantString(),
                    region.StartLine.ToInvariantString());
            }
        }
コード例 #9
0
 /// <summary>
 /// Constructs a new <see cref="WorkbookFunctionsDurationRequestBuilder"/>.
 /// </summary>
 /// <param name="requestUrl">The URL for the request.</param>
 /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
 /// <param name="settlement">A settlement parameter for the OData method call.</param>
 /// <param name="maturity">A maturity parameter for the OData method call.</param>
 /// <param name="coupon">A coupon parameter for the OData method call.</param>
 /// <param name="yld">A yld parameter for the OData method call.</param>
 /// <param name="frequency">A frequency parameter for the OData method call.</param>
 /// <param name="basis">A basis parameter for the OData method call.</param>
 public WorkbookFunctionsDurationRequestBuilder(
     string requestUrl,
     IBaseClient client,
     Newtonsoft.Json.Linq.JToken settlement,
     Newtonsoft.Json.Linq.JToken maturity,
     Newtonsoft.Json.Linq.JToken coupon,
     Newtonsoft.Json.Linq.JToken yld,
     Newtonsoft.Json.Linq.JToken frequency,
     Newtonsoft.Json.Linq.JToken basis)
     : base(requestUrl, client)
 {
     this.SetParameter("settlement", settlement, true);
     this.SetParameter("maturity", maturity, true);
     this.SetParameter("coupon", coupon, true);
     this.SetParameter("yld", yld, true);
     this.SetParameter("frequency", frequency, true);
     this.SetParameter("basis", basis, true);
 }
コード例 #10
0
        private void InitGacha(BraveExvius b)
        {
            Gachas = b.GetUserInfo[GameObject.GachaScheduleMst];

            foreach (var gacha in b.GachaId)
            {
                JPGacha.Items.Add(gacha);
            }

            JPGacha.SelectedIndex = 0;

            foreach (var ticket in Ticket.Tickets)
            {
                JPGachaTicket.Items.Add(ticket.Name);
            }

            JPGachaTicket.SelectedIndex = 0;
        }
コード例 #11
0
 /// <summary>
 /// Constructs a new <see cref="WorkbookFunctionsBeta_DistRequestBuilder"/>.
 /// </summary>
 /// <param name="requestUrl">The URL for the request.</param>
 /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
 /// <param name="x">A x parameter for the OData method call.</param>
 /// <param name="alpha">A alpha parameter for the OData method call.</param>
 /// <param name="beta">A beta parameter for the OData method call.</param>
 /// <param name="cumulative">A cumulative parameter for the OData method call.</param>
 /// <param name="A">A A parameter for the OData method call.</param>
 /// <param name="B">A B parameter for the OData method call.</param>
 public WorkbookFunctionsBeta_DistRequestBuilder(
     string requestUrl,
     IBaseClient client,
     Newtonsoft.Json.Linq.JToken x,
     Newtonsoft.Json.Linq.JToken alpha,
     Newtonsoft.Json.Linq.JToken beta,
     Newtonsoft.Json.Linq.JToken cumulative,
     Newtonsoft.Json.Linq.JToken A,
     Newtonsoft.Json.Linq.JToken B)
     : base(requestUrl, client)
 {
     this.SetParameter("x", x, true);
     this.SetParameter("alpha", alpha, true);
     this.SetParameter("beta", beta, true);
     this.SetParameter("cumulative", cumulative, true);
     this.SetParameter("a", A, true);
     this.SetParameter("b", B, true);
 }
コード例 #12
0
        public async Task urban([Remainder] string urbanstr)
        {
            using (System.Net.WebClient WebClient = new System.Net.WebClient())
            {
                string Resp = await WebClient.DownloadStringTaskAsync("http://api.urbandictionary.com/v0/define?term=" + urbanstr);

                Newtonsoft.Json.Linq.JToken JsonContent = Newtonsoft.Json.Linq.JToken.Parse(Resp);
                JsonContent = JsonContent.SelectToken("list.[0].definition");
                if (JsonContent != null)
                {
                    await Context.Channel.SendMessageAsync(JsonContent.ToString());
                }
                else
                {
                    await Context.Channel.SendMessageAsync("No definition found for: " + urbanstr);
                }
            }
        }
コード例 #13
0
 public static void Play(OnMessageReceivedArgs e, string[] SegmentedMessage)
 {
     if (e.ChatMessage.IsBroadcaster || e.ChatMessage.IsModerator)
     {
         Newtonsoft.Json.Linq.JToken Result = Shared.APIIntergrations.Nightbot.Requests.PlaySong();
         if (Result["status"].ToString() == "200")
         {
             MessageHandler.SendMessage(e, Shared.ConfigHandler.Config["CommandResponses"]["Moderator"]["Play"].ToString(), null);
         }
         else
         {
             MessageHandler.SendMessage(e, Shared.ConfigHandler.Config["CommandResponses"]["Moderator"]["NightBotError"].ToString(), null);
             Console.WriteLine(Result["message"].ToString());
         }
         return;
     }
     NotMod(e);
 }
 /// <summary>
 /// Constructs a new <see cref="WorkbookFunctionsRateRequestBuilder"/>.
 /// </summary>
 /// <param name="requestUrl">The URL for the request.</param>
 /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
 /// <param name="nper">A nper parameter for the OData method call.</param>
 /// <param name="pmt">A pmt parameter for the OData method call.</param>
 /// <param name="pv">A pv parameter for the OData method call.</param>
 /// <param name="fv">A fv parameter for the OData method call.</param>
 /// <param name="type">A type parameter for the OData method call.</param>
 /// <param name="guess">A guess parameter for the OData method call.</param>
 public WorkbookFunctionsRateRequestBuilder(
     string requestUrl,
     IBaseClient client,
     Newtonsoft.Json.Linq.JToken nper,
     Newtonsoft.Json.Linq.JToken pmt,
     Newtonsoft.Json.Linq.JToken pv,
     Newtonsoft.Json.Linq.JToken fv,
     Newtonsoft.Json.Linq.JToken type,
     Newtonsoft.Json.Linq.JToken guess)
     : base(requestUrl, client)
 {
     this.SetParameter("nper", nper, true);
     this.SetParameter("pmt", pmt, true);
     this.SetParameter("pv", pv, true);
     this.SetParameter("fv", fv, true);
     this.SetParameter("type", type, true);
     this.SetParameter("guess", guess, true);
 }
コード例 #15
0
        private string DisplayAllRankedResults(Newtonsoft.Json.Linq.JObject responseObjects)
        {
            string[] rankingGroups = new string[] { "mainline" };
            string   displaystr    = "";

            // Loop through the ranking groups in priority order
            foreach (string rankingName in rankingGroups)
            {
                Newtonsoft.Json.Linq.JToken rankingResponseItems = responseObjects.SelectToken($"rankingResponse.{rankingName}.items");
                if (rankingResponseItems != null)
                {
                    foreach (Newtonsoft.Json.Linq.JObject rankingResponseItem in rankingResponseItems)
                    {
                        Newtonsoft.Json.Linq.JToken resultIndex;
                        rankingResponseItem.TryGetValue("resultIndex", out resultIndex);
                        var answerType = rankingResponseItem.Value <string>("answerType");
                        switch (answerType)
                        {
                        case "WebPages":
                            displaystr = displaystr + DisplaySpecificResults(resultIndex, responseObjects.SelectToken("webPages.value"), "WebPage", "name", "url", "snippet");

                            break;
                            //case "News":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("news.value"), "News", "name", "url", "description");
                            //    break;
                            //case "Images":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("images.value"), "Image", "thumbnailUrl");
                            //    break;
                            //case "Videos":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("videos.value"), "Video", "embedHtml");
                            //    break;
                            //case "RelatedSearches":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("relatedSearches.value"), "RelatedSearch", "displayText", "webSearchUrl");
                            //    break;
                        }
                        if (displaystr != "")
                        {
                            return(displaystr);
                        }
                    }
                }
            }
            return(displaystr);
        }
コード例 #16
0
        /// <summary>
        /// 根据输入值,获取设备点对应的真正值,此方法正好和Transform相反
        /// </summary>
        /// <param name="point"></param>
        /// <param name="objValue"></param>
        /// <returns></returns>
        public static object GetRealValue(Newtonsoft.Json.Linq.JToken point, object objValue)
        {
            double value;

            try
            {
                value = Convert.ToDouble(objValue);
            }
            catch
            {
                return(objValue);
            }

            var detail    = point["detail"];
            var isDigital = point.Value <bool>("isDigital");

            if (isDigital)
            {
                return(value > 0 ? 1 : 0);
            }
            var isTransform = detail.Value <bool>("IsTransform");
            var isLinear    = detail.Value <bool>("IsLinear");
            var isSquare    = detail.Value <bool>("IsSquare");

            if (isTransform)
            {
                //传感器上限
                double sensorMax = detail.Value <double>("SensorMax");
                double sensorMin = detail.Value <double>("SensorMin");
                double max       = point.Value <double>("max");
                double min       = point.Value <double>("min");
                var    k         = (max - min) / (sensorMax - sensorMin);
                var    b         = (min * (sensorMax - sensorMin) - sensorMin * (max - min)) / (sensorMax - sensorMin);
                // value = k * value + b;//y=k*x+b

                value = (value - b) / k;
            }

            if (isLinear)
            {
                //无法逆推
            }
            return(value);
        }
コード例 #17
0
ファイル: AudioPlayer.cs プロジェクト: 5l1v3r1/SpagBot
        private async Task <VideoInfo> GetVideoViaTCPAsync(string domain)
        {
            using (System.Net.Sockets.TcpClient TCP = new System.Net.Sockets.TcpClient())
            {
                await TCP.ConnectAsync(System.Net.IPAddress.Parse("127.0.0.1"), 1212);

                var    stream = TCP.GetStream();
                byte[] data   = System.Text.Encoding.UTF8.GetBytes(domain);
                stream.Write(data, 0, data.Length);
                string response = "";
                do
                {
                    System.Threading.Thread.Sleep(200);
                } while (stream.CanRead == false);
                using (System.IO.StreamReader SR = new System.IO.StreamReader(stream))
                {
                    response = SR.ReadToEnd();
                }
                VideoInfo VideoInfo = null;
                Newtonsoft.Json.Linq.JToken Vals = Newtonsoft.Json.Linq.JToken.Parse(response);
                if (Vals["errorset"] != null)
                {
                    SendMessage_Raised("Failed to get track: " + Vals.SelectToken("errorset").ToString(), MessageClient);
                }
                else
                {
                    string          url   = Vals.SelectToken("url").ToString();
                    string          title = Vals.SelectToken("title").ToString();
                    VideoInfo.Types type  = VideoInfo.Types.Video;
                    switch (Vals.SelectToken("type").ToString())
                    {
                    case "video":
                        type = VideoInfo.Types.Video;
                        break;

                    case "livestream":
                        type = VideoInfo.Types.Livestream;
                        break;
                    }
                    VideoInfo = VideoInfo.CreateCustomVideo(url, title, type);
                }
                return(VideoInfo);
            }
        }
コード例 #18
0
ファイル: Accounts.cs プロジェクト: Jaminima/OwlCoinV2
        public static EventResponse PayUser(string MyID, IDType MyIDType, string TheirID, IDType TheirIDType, int Amount)
        {
            Amount = Math.Abs(Amount);
            EventResponse Response = new EventResponse();

            UserData.CreateUser(TheirID, TheirIDType);

            if (UserData.UserExists(MyID, MyIDType) && UserData.UserExists(TheirID, TheirIDType))
            {
                Newtonsoft.Json.Linq.JToken MyUser    = UserData.GetUser(MyID, MyIDType),
                                            TheirUser = UserData.GetUser(TheirID, TheirIDType);
                if (MyUser["Status"].ToString() != "200" || TheirUser["Status"].ToString() != "200")
                {
                    Response.Message = Shared.ConfigHandler.Config["CommandResponses"]["Errors"]["WhoKnows"].ToString(); return(Response);
                }
                MyUser = MyUser["Data"]; TheirUser = TheirUser["Data"];
                if (MyUser["UserId"].ToString() == TheirUser["UserId"].ToString())
                {
                    Response.Message = Shared.ConfigHandler.Config["CommandResponses"]["Errors"]["Self"].ToString(); return(Response);
                }
                int MyBal    = int.Parse(MyUser["Account"]["Balance"].ToString()),
                    TheirBal = int.Parse(TheirUser["Account"]["Balance"].ToString());
                if (MyBal >= Amount)
                {
                    Dictionary <string, string> Headers = new Dictionary <string, string> {
                    };
                    Headers.Add("Value", Amount.ToString());
                    WebRequests.POST("/account/take/" + MyUser["UserId"], Headers);
                    WebRequests.POST("/account/give/" + TheirUser["UserId"], Headers);
                    Response.Message = " Payment of " + Amount + " Owlcoin Complete, New Balance: " + MyBal + " Owlcoin!";
                    Response.Success = true;
                }
                else
                {
                    Response.Message = Shared.ConfigHandler.Config["CommandResponses"]["Errors"]["NotEnough"].ToString();
                }
            }
            else
            {
                Response.Message = Shared.ConfigHandler.Config["CommandResponses"]["Errors"]["NoUser"].ToString();
            }

            return(Response);
        }
コード例 #19
0
 public static string GetAuthToken()
 {
     if (((TimeSpan)(DateTime.Now - LastRefreshed)).TotalSeconds > 600)
     {
         string URLStart = Init.MasterConfig["API"]["WebAddress"] + ":" + Init.MasterConfig["API"]["Port"] + "/";
         if (Init.MasterConfig["API"]["AddressPath"].ToString() != "")
         {
             URLStart += Init.MasterConfig["API"]["AddressPath"] + "/";
         }
         WebRequest Req = WebRequest.Create(URLStart + "bot");
         Req.Headers.Add("RefreshToken", Init.MasterConfig["API"]["RefreshToken"].ToString());
         Req.Headers.Add("BotID", Init.MasterConfig["API"]["ID"].ToString());
         Req.Method = "POST";
         Stream PostStream = Req.GetRequestStream();
         PostStream.Write(new byte[] { }, 0, new byte[] { }.Length);
         PostStream.Flush();
         PostStream.Close();
         try
         {
             WebResponse Res                   = Req.GetResponse();
             string      StreamString          = new StreamReader(Res.GetResponseStream()).ReadToEnd();
             Newtonsoft.Json.Linq.JToken JData = Newtonsoft.Json.Linq.JToken.Parse(StreamString);
             ResponseObject RObj               = ResponseObject.FromJson(JData);
             if (RObj.Data.Count() != 0)
             {
                 Objects.Bot B = Objects.Bot.FromJson(RObj.Data);
                 Init.MasterConfig["API"]["RefreshToken"] = B.RefreshToken;
                 LastRefreshed = B.TokenRefreshDateTime;
                 LastAuthToken = B.AccessToken;
                 FileHandler.SaveJSON("./Data/Master.config.json", Init.MasterConfig);
             }
             else
             {
                 return(null);
             }
         }
         catch (WebException E)
         {
             Console.WriteLine(E);
             return(null);
         }
     }
     return(LastAuthToken);
 }
コード例 #20
0
        /** Handle results returned from the document
         */
        public override void _HandleResult(Newtonsoft.Json.Linq.JToken value)
        {
            if (OfficeExtension.Utility._IsNullOrUndefined(value))
            {
                return;
            }
            Newtonsoft.Json.Linq.JObject obj = value as Newtonsoft.Json.Linq.JObject;
            if (obj == null)
            {
                return;
            }

            OfficeExtension.Utility._FixObjectPathIfNecessary(this, obj);
            if (!OfficeExtension.Utility._IsUndefined(obj["Criteria"]))
            {
                this.LoadedPropertyNames.Add("Criteria");
                this.m_criteria = obj["Criteria"].ToObject <Microsoft.ExcelServices.FilterCriteria>();
            }
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: DevSide69/GooglePlaceAPI
 public static List <string> GetPlaceId(string json)
 {
     try
     {
         List <string> lId = new List <string>();
         Dictionary <string, object> test = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);
         Newtonsoft.Json.Linq.JArray tes  = (Newtonsoft.Json.Linq.JArray)test["results"];
         for (int i = 0; i < tes.Count; i++)
         {
             Newtonsoft.Json.Linq.JToken tok = (Newtonsoft.Json.Linq.JToken)tes[i]["place_id"];
             lId.Add(tok.ToString());
         }
         return(lId);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
コード例 #22
0
        /// <summary>
        /// Create a new row in the database
        /// </summary>
        /// <typeparam name="T">The object type</typeparam>
        /// <param name="name">The name of the object</param>
        /// <param name="data">The object to create</param>
        /// <param name="id">Out the created row id</param>
        /// <param name="deep">Create also direct descendents of the object through child relations</param>
        /// <param name="returnObject">If set to true it returns the object. Use it if you have triggered actions that modify the created object.</param>
        /// <param name="parameters">Parameters for triggered actions</param>
        /// <returns>A typed object</returns>
        public T Post <T>(string name, T data, out string id, bool?deep = null, bool?returnObject = null, string parameters = null) where T : new()
        {
            var request = new RestRequest("/1/objects/{name}", Method.POST);

            request.AddUrlSegment("name", name);
            request.RequestFormat = DataFormat.Json;
            request.AddBody(data);
            if (deep.HasValue)
            {
                request.AddParameter("deep", deep.Value, ParameterType.QueryString);
            }
            if (returnObject.HasValue)
            {
                request.AddParameter("returnObject", returnObject.Value, ParameterType.QueryString);
            }
            if (parameters != null)
            {
                request.AddParameter("parameters", parameters, ParameterType.QueryString);
            }

            var response = client.Execute <T>(request);

            id = null;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var result = JsonConvert.DeserializeObject <Dictionary <string, object> >(response.Content);
                if (result.ContainsKey("__metadata"))
                {
                    Newtonsoft.Json.Linq.JToken metadata = (Newtonsoft.Json.Linq.JToken)result["__metadata"];
                    id = metadata["id"].ToString();
                }
                if (returnObject.HasValue && returnObject.Value)
                {
                    return(response.Data);
                }
                return(default(T));
            }
            else
            {
                throw new BeckandException(response);
            }
        }
コード例 #23
0
        public void GetFunctionsList(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JToken Data, MESStationReturn StationReturn)
        {
            //  Assembly.LoadFile(System.IO.Directory.GetCurrentDirectory() + "\\" + DLL);
            string        DllName      = Data["DllName"].ToString().Trim();
            string        ClassName    = Data["ClassName"].ToString();
            List <string> FunctionList = new List <string>();
            Assembly      assemby      = Assembly.LoadFile(System.IO.Directory.GetCurrentDirectory() + "\\" + DllName);
            //  Assembly assemby = Assembly.Load(DllName);
            Type   t   = assemby.GetType(ClassName);
            object obj = assemby.CreateInstance(ClassName);

            // MesAPIBase API = (MesAPIBase)obj;
            //   Dictionary<string, MESStation.BaseClass.APIInfo> APIS;
            //   MESReturnView.Public.GetApiFunctionsListReturn ret = new MESReturnView.Public.GetApiFunctionsListReturn();
            //APIS = API.Apis;
            foreach (var item in obj.GetType().GetMethods())
            {
                if (item.Name == "ToString")
                {
                    continue;
                }

                if (item.Name == "Equals")
                {
                    continue;
                }

                if (item.Name == "GetHashCode")
                {
                    continue;
                }

                if (item.Name == "GetType")
                {
                    continue;
                }

                FunctionList.Add(item.Name);
            }
            StationReturn.Data        = FunctionList;
            StationReturn.MessageCode = "MES00000001";
            StationReturn.Status      = "Pass";
        }
コード例 #24
0
        public static void CheckForNewDonation()
        {
            WebRequest Req = WebRequest.Create("https://streamlabs.com/api/v1.0/donations?access_token=" + Alert.GetAuthCode() + "&limit=100");

            Req.Method = "GET";
            WebResponse Res; Newtonsoft.Json.Linq.JObject CurrentData, OldData = ConfigHandler.LoadConfig("./Data/Donations.dump");

            try
            {
                Res = Req.GetResponse();
                string SData = new StreamReader(Res.GetResponseStream()).ReadToEnd();
                if (SData == null)
                {
                    return;
                }
                CurrentData = Newtonsoft.Json.Linq.JObject.Parse(SData);
            }
            catch (WebException E)
            {
                Console.WriteLine(E.Message);
                return;
            }
            ConfigHandler.SaveConfig("./Data/Donations.dump", CurrentData);
            for (int i = 0; i < OldData["data"].Count(); i++)
            {
                if (CurrentData["data"][i]["donation_id"].ToString() != OldData["data"][0]["donation_id"].ToString())
                {
                    Newtonsoft.Json.Linq.JToken CurrentDonation = CurrentData["data"][i];
                    double Amount = Math.Round(Double.Parse(CurrentDonation["amount"].ToString()), 2);
                    int    Owc    = (int)Math.Floor(Amount * int.Parse(Shared.ConfigHandler.Config["Rewards"]["Twitch"]["Donation"].ToString()));
                    TwitchLib.Api.Models.v5.Users.Users Users = TwitchBot.UserHandler.UserFromUsername(CurrentDonation["name"].ToString());
                    if (Users.Matches.Length != 0)
                    {
                        Data.Accounts.GiveUser(Users.Matches[0].Id, IDType.Twitch, Owc);
                        TwitchBot.MessageHandler.SendMessage(Shared.ConfigHandler.Config["ChannelName"].ToString(), Shared.ConfigHandler.Config["EventMessages"]["Donation"].ToString(), CurrentDonation["name"].ToString(), null, -1, Owc, Amount.ToString() + " " + CurrentDonation["currency"].ToString());
                    }
                }
                else
                {
                    break;
                }
            }
        }
コード例 #25
0
        // Update setting that controller requested.  This will also get passed to the sensor driver to handle.
        private bool HandleChangeSetting(object body)
        {
            var array = (Newtonsoft.Json.Linq.JArray)body;

            Newtonsoft.Json.Linq.JToken jSettingName  = array[0];
            Newtonsoft.Json.Linq.JToken jSettingValue = array[1];

            string settingName  = jSettingName.ToString();
            object settingValue = jSettingValue.ToObject <object>();

            if (settingName == "data_file_directory")
            {
                this.overrideDataFileDirectory = (string)settingValue;
            }

            this.DriverHandleNewSetting(settingName, settingValue);

            return(true);
        }
コード例 #26
0
        /** Handle results returned from the document
         */
        public override void _HandleResult(Newtonsoft.Json.Linq.JToken value)
        {
            if (OfficeExtension.Utility._IsNullOrUndefined(value))
            {
                return;
            }
            Newtonsoft.Json.Linq.JObject obj = value as Newtonsoft.Json.Linq.JObject;
            if (obj == null)
            {
                return;
            }

            OfficeExtension.Utility._FixObjectPathIfNecessary(this, obj);
            if (!OfficeExtension.Utility._IsUndefined(obj["CalculationMode"]))
            {
                this.LoadedPropertyNames.Add("CalculationMode");
                this.m_calculationMode = obj["CalculationMode"].ToObject <string>();
            }
        }
コード例 #27
0
ファイル: Utils.cs プロジェクト: learningKool/Ptakopysk
        public static List <object> GenerateAdditionalArguments(Type type, Newtonsoft.Json.Linq.JToken data)
        {
            if (type == null || data == null)
            {
                return(null);
            }

            MethodInfo method;

            try { method = type.GetMethod("GenerateAdditionalArguments", new Type[] { typeof(Newtonsoft.Json.Linq.JToken) }); }
            catch { return(null); }
            if (method == null || !method.IsStatic)
            {
                return(null);
            }

            try { return((List <object>)method.Invoke(null, new object[] { data })); }
            catch { return(null); }
        }
コード例 #28
0
        Json2List(System.IO.Stream inputStream, System.Text.Encoding enc)
        {
            if (inputStream == null)
            {
                throw new System.ArgumentNullException(nameof(inputStream));
            } // End if (inputStream == null)

            Newtonsoft.Json.Linq.JToken jsonData = null;

            using (System.IO.TextReader tr = new System.IO.StreamReader(inputStream, enc))
            {
                using (Newtonsoft.Json.JsonTextReader jsonReader = new Newtonsoft.Json.JsonTextReader(tr))
                {
                    jsonData = Newtonsoft.Json.Linq.JToken.ReadFrom(jsonReader);
                } // End Using jsonReader
            }     // End Using tr

            return(Json2List(jsonData));
        } // End Function Json2List
コード例 #29
0
        public bool HttpPostWrapper(string p_Controller,
                                    string p_OP, string p_jsnInData,
                                    out Newtonsoft.Json.Linq.JToken p_jsnOutData, out string p_jsnError)
        {
            int HttpStatusCodeOK = (int)HttpStatusCode.OK;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(c_Baseuri);

                var keyValues = new List <KeyValuePair <string, string> >();
                keyValues.Add(new KeyValuePair <string, string>("op", p_OP));
                keyValues.Add(new KeyValuePair <string, string>("jsnInData", p_jsnInData));
                var dataForHTTP = new FormUrlEncodedContent(keyValues);

                p_jsnOutData = "";
                p_jsnError   = "";

                var response = client.PostAsync(p_Controller, dataForHTTP).Result;
                if (response.IsSuccessStatusCode)
                {
                    string ServerResponseData = response.Content.ReadAsStringAsync().Result;
                    Newtonsoft.Json.Linq.JContainer OServerData =
                        Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(ServerResponseData);
                    string StatusCode = (string)OServerData["StatusCode"];
                    if (StatusCode != HttpStatusCodeOK.ToString())
                    {
                        p_jsnError = (string)OServerData["ErrorDescription"];
                        return(false);
                    }

                    Newtonsoft.Json.Linq.JToken jsnDataOut = OServerData.Last;
                    p_jsnOutData = jsnDataOut.First;;
                    return(true);
                }
                else
                {
                    p_jsnError = "{'Source:':'HttpPostWrapper','Message':' Http post failed with StatusCode:' " +
                                 response.StatusCode + " and ReasonPhrase:" + response.ReasonPhrase + "}";
                    return(false);
                }
            }
        }
コード例 #30
0
ファイル: NamedItem.cs プロジェクト: valentyng/OfficeApi
        /** Handle results returned from the document
         */
        public override void _HandleResult(Newtonsoft.Json.Linq.JToken value)
        {
            if (OfficeExtension.Utility._IsNullOrUndefined(value))
            {
                return;
            }
            Newtonsoft.Json.Linq.JObject obj = value as Newtonsoft.Json.Linq.JObject;
            if (obj == null)
            {
                return;
            }

            OfficeExtension.Utility._FixObjectPathIfNecessary(this, obj);
            if (!OfficeExtension.Utility._IsUndefined(obj["Name"]))
            {
                this.LoadedPropertyNames.Add("Name");
                this.m_name = obj["Name"].ToObject <string>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Type"]))
            {
                this.LoadedPropertyNames.Add("Type");
                this.m_type = obj["Type"].ToObject <string>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Value"]))
            {
                this.LoadedPropertyNames.Add("Value");
                this.m_value = obj["Value"].ToObject <object>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Visible"]))
            {
                this.LoadedPropertyNames.Add("Visible");
                this.m_visible = obj["Visible"].ToObject <bool>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["_Id"]))
            {
                this.LoadedPropertyNames.Add("_Id");
                this.m__Id = obj["_Id"].ToObject <string>();
            }
        }
コード例 #31
0
ファイル: MyJsonResult.cs プロジェクト: jbunzel/MvcRQ_git
 public JsonContent(MyJsonResult value)
 {
     _value = Newtonsoft.Json.Linq.JObject.Parse(new JavaScriptSerializer().Serialize(value));
     Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
 }