Example #1
0
        public GoogleCalendar()
        {
            var keyFolder   = HttpContext.Current.Server.MapPath("~/Resources");
            var keyFilePath = Path.Combine(keyFolder, "vanicrm-d871072c086a.json");

            var json = File.ReadAllText(keyFilePath);

            Newtonsoft.Json.Linq.JObject cr = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(json);
            string s = (string)cr.GetValue("private_key");
            string serviceAccountEmail = (string)cr.GetValue("client_email");

            string[] scopes = new string[] {
                CalendarService.Scope.Calendar, // Manage your calendars
            };

            //GoogleCredential credential = new GoogleCredential() {  }.

            var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = scopes,

                //User = "******",
            }.FromPrivateKey(s));

            calendarService = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
            });
        }
Example #2
0
        private void connectToIPAddress(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ipTextBox.Text))
            {
                socket = IO.Socket("http://" + _serverIP + ":" + SERVER_PORT);
                socket.On(Socket.EVENT_CONNECT, () =>
                {
                    IsConnected = true;
                });

                socket.On("chat message", (data) =>
                {
                    Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)data;
                    Newtonsoft.Json.Linq.JToken un   = obj.GetValue("username");
                    Newtonsoft.Json.Linq.JToken ts   = obj.GetValue("timestamp");
                    Newtonsoft.Json.Linq.JToken ms   = obj.GetValue("message");
                    Console.WriteLine(un);
                    Console.WriteLine(ts.ToString());
                    Console.WriteLine(ms);

                    //MessageList += Environment.NewLine + un.ToString() + ":" + Environment.NewLine;
                    MessageList += Environment.NewLine + un.ToString() + ts.ToString() + ":\n" + ms.ToString() + Environment.NewLine;
                    //MessageList += Environment.NewLine + ts.ToString() + Environment.NewLine;
                });

                socket.On(Socket.EVENT_CONNECT_ERROR, () =>
                {
                    //System.Windows.MessageBox.Show("Erreur de connexion.", "Erreur");
                    Console.WriteLine("Connection failed");
                });
            }
        }
Example #3
0
        /// <summary>
        /// 用Cookie进行登录
        /// </summary>
        /// <returns></returns>
        public static bool Login()
        {
            HttpCookie cook = HttpContext.Current.Request.Cookies.Get("userInfo");

            if (cook == null || string.IsNullOrEmpty(cook.Value))
            {
                return(false);
            }

            try{
                string jsonStr = Common.Helper.Common.DeDesCode(cook.Value);
                Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonStr) as Newtonsoft.Json.Linq.JObject;

                string userName = Convert.ToString(obj.GetValue("UserName"));
                string passWord = Convert.ToString(obj.GetValue("PassWord"));
                List <DBHelper.Model.JCUser> list = DBHelper.BLL.BJCUser.Select("UserName=@UserName and PassWord=@PassWord",
                                                                                new DBHelper.Model.ParameterList("@UserName", userName, "@PassWord", passWord));

                if (list.Count > 0)
                {
                    DBHelper.Model.JCUser user = list[0];

                    return(Login(user));
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
        public MessageBoxControl()
        {
            DataContext = this;
            InitializeComponent();
            _username = user.Username;
            socket    = AppSocket.Instance;
            GetChatRooms();
            currentChannel = "Général";
            socket.Emit("joinChannel", user.Username, "Général");

            socket.On("newChannel", (data) =>
            {
                GetChatRooms();
            });

            socket.On("chat message", (data) =>
            {
                Console.WriteLine("message!");
                Newtonsoft.Json.Linq.JObject obj        = (Newtonsoft.Json.Linq.JObject)data;
                Newtonsoft.Json.Linq.JToken un          = obj.GetValue("username");
                Newtonsoft.Json.Linq.JToken ts          = obj.GetValue("timestamp");
                Newtonsoft.Json.Linq.JToken ms          = obj.GetValue("message");
                Newtonsoft.Json.Linq.JToken channelName = obj.GetValue("channel");
                string newMessage = Environment.NewLine + un.ToString() + ts.ToString() + ":\n" + ms.ToString() + Environment.NewLine;
                updateDictionnary(newMessage.ToString(), channelName.ToString());
                Dispatcher.Invoke(() =>
                {
                    if (currentChannel == channelName.ToString())
                    {
                        messageList.Text += newMessage.ToString();
                    }
                });
            });
        }
        public decimal GetIdFromConceptJsonObject(string ConceptString)
        {
            Newtonsoft.Json.Linq.JObject cnpJObject = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(ConceptString);

            if (cnpJObject.HasValues && (decimal)cnpJObject.GetValue("ID") > 0)
            {
                return((decimal)cnpJObject.GetValue("ID"));
            }

            return(0);
        }
Example #6
0
        protected async Task Test1()
        {
            string   credPath = @"d:\\project-id-9301225348112901974-d05770b23edc.json";
            DateTime t1       = new DateTime(); t1 = DateTime.Now;
            string   json     = File.ReadAllText(credPath);

            Newtonsoft.Json.Linq.JObject cr = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(json);
            string private_key = (string)cr.GetValue("private_key");
            string email       = (string)cr.GetValue("Client_email");

            ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("104602038154026657417")
            {
                Scopes = new[] { SheetsService.Scope.Spreadsheets }
            }.FromPrivateKey(private_key));


            // Create the service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "CC_Sheets_Service",
            });
            var fred = service.Spreadsheets.Get("10usxblP6yGQTB2VkYeA5xuLUMepf1TuIcyhig4H1ygk");

            fred.IncludeGridData = true;


            String spreadsheetId = "10usxblP6yGQTB2VkYeA5xuLUMepf1TuIcyhig4H1ygk";
            String range         = "Sheet1!A1:AB210";

            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, range);



            ValueRange response            = request.Execute();
            IList <IList <Object> > values = response.Values;
            TimeSpan ts1 = new TimeSpan(); ts1 = DateTime.Now - t1;

            fred = fred;

            for (var i = 1; i < 210; i++)
            {
                string s  = (string)values[i][0];
                string s1 = "";
                if (s == "6752")
                {
                    s1 = (string)values[i][1];
                    s1 = s1;
                }
            }
        }
Example #7
0
        public async Task <IHttpActionResult> Post([FromBody] Newtonsoft.Json.Linq.JObject data)
        {
            string email = data.GetValue("email").ToString();
            string senha = data.GetValue("senha").ToString();

            Cliente cliente = db.Clientes.First(x => x.Email == email && x.Senha == senha);             // código de consulta por login e senha

            if (cliente == null)
            {
                return(NotFound());
            }

            return(Ok(new ClienteView(cliente)));
        }
Example #8
0
        /// <summary>
        /// 获取jsapiticket
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string GetWXJsapi_Ticket(string accessToken)
        {
            string result = "";
            string ticket = "";

            try
            {
                string key = WxConfig.AppId + "ticket";
                if (CacheHelper.Get(key) == null)
                {
                    System.Net.HttpWebRequest xhr    = (HttpWebRequest)HttpWebRequest.Create(string.Format(WxUrl.Jsapi_TicketUrl, accessToken).ToString());
                    System.IO.Stream          stream = xhr.GetResponse().GetResponseStream();
                    System.IO.StreamReader    reader = new System.IO.StreamReader(stream);
                    result = reader.ReadToEnd();
                    reader.Close();
                    stream.Close();
                    Newtonsoft.Json.Linq.JObject remark = Newtonsoft.Json.Linq.JObject.Parse(result);

                    ticket = remark.GetValue("ticket").ToString();
                    CacheHelper.Add(key, ticket, TimeSpan.FromSeconds(7000));
                    return(ticket);
                }
                else
                {
                    return(CacheHelper.Get(key).ToString());
                }
            }
            catch (Exception ex)
            {
                //ErrorLogHelper.Error(ex);
                //BizLogHelper.InfoMessage("获取微信accesstoken", "appid:" + appid + ";secret:" + secret + ";返回值:" + result, null);
                return("err");
            }
        }
Example #9
0
        /// <summary>
        /// 获取微信AccessToken
        /// </summary>
        /// <param name="appid">APPIDy</param>
        /// <param name="secret">凭证</param>
        /// <returns></returns>
        public static string GetWXAccessToken(string appid, string secret)
        {
            string result       = "";
            string access_token = "";

            try
            {
                if (CacheHelper.Get(appid) == null)
                {
                    System.Net.HttpWebRequest xhr    = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret).ToString());
                    System.IO.Stream          stream = xhr.GetResponse().GetResponseStream();
                    System.IO.StreamReader    reader = new System.IO.StreamReader(stream);
                    result = reader.ReadToEnd();
                    reader.Close();
                    stream.Close();
                    Newtonsoft.Json.Linq.JObject remark = Newtonsoft.Json.Linq.JObject.Parse(result);

                    access_token = remark.GetValue("access_token").ToString();
                    CacheHelper.Add(appid, access_token, TimeSpan.FromSeconds(7000));
                    return(access_token);
                }
                else
                {
                    return(CacheHelper.Get(appid).ToString());
                }
            }
            catch (Exception ex)
            {
                //ErrorLogHelper.Error(ex);
                //BizLogHelper.InfoMessage("获取微信accesstoken", "appid:" + appid + ";secret:" + secret + ";返回值:" + result, null);
                return("err");
            }
        }
Example #10
0
        protected override void ReadFromJson(Newtonsoft.Json.Linq.JObject obj)
        {
            base.ReadFromJson(obj);
            if (obj["speed"] != null)
            {
                _baseSpeed = (float)obj["speed"];
            }
            if (obj["stamina"] != null)
            {
                _baseMaxStamina = _stamina = (float)obj["stamina"];
            }
            if (obj["expReward"] != null)
            {
                _expReward = (int)obj["expReward"];
            }

            if (obj["targetedTags"] != null)
            {
                var tags = (Newtonsoft.Json.Linq.JArray)obj.GetValue("targetedTags");
                for (int i = 0; i < tags.Count; ++i)
                {
                    TargetedTags.Add((string)tags[i]);
                }
            }
        }
Example #11
0
        private void ContentPage_Appearing(object sender, EventArgs e)
        {
            cmdCollectData.IsVisible = false;
            cmdSettings.IsVisible    = false;
            cmdRegister.IsVisible    = false;
            cmdSync.IsVisible        = false;

            string UseMe = AccountInformation.GetAccountInformationString();
            //WebInteraction.SendHttpJSON(WebInteraction.m_LicenseLocation, "80", UseMe);
            string OnlineResponse = WebInteraction.SendHttpPost(WebInteraction.m_LicenseURL, UseMe);

            if (OnlineResponse != "")
            {
                //process json
                Newtonsoft.Json.Linq.JObject jo = new Newtonsoft.Json.Linq.JObject();
                jo = Newtonsoft.Json.Linq.JObject.Parse(OnlineResponse);
                string vv = jo.GetValue("Value").ToString();
                if (vv.IndexOf("1") == 0)
                {
                    cmdCollectData.IsVisible = true;
                    cmdSettings.IsVisible    = true;
                    cmdSync.IsVisible        = true;
                }
                else
                {
                    cmdRegister.IsVisible = true;
                }
            }
            m_Options.LoadOptionsFromDB();
            //if license ok, make buttons visible
        }
Example #12
0
        /// <summary>
        /// 通过剑客编号批量查询物流
        /// </summary>
        /// <param name="JKOrderId"></param>
        /// <param name="jkLogisticsList"></param>
        /// <returns></returns>
        public bool multi_QueryLogistics(string[] JKOrderId, out string jkLogisticsList)
        {
            Dictionary <string, string> kvs = new Dictionary <string, string>();

            kvs.Add("method", "jianke.logistics.get");
            kvs.Add("cid", _tscid);
            kvs.Add("signMethod", "md5");
            kvs.Add("randomStr", Ass.Data.Utils.GetRandomString(8));
            var str = Newtonsoft.Json.JsonConvert.SerializeObject(JKOrderId).Replace("\"", "");

            kvs.Add("orderNo", str);
            var    json     = JKSign(kvs, "orderNo");
            var    netJK    = new NETDrugStore();
            string codeJson = netJK.HttpsPostDrugOrderInfo(json, _url);

            Newtonsoft.Json.Linq.JObject jobj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(codeJson);
            var rtnCode = jobj.GetValueString("returnCode", "code");

            if (rtnCode == "SUCCESS")
            {
                jkLogisticsList = jobj.GetValue("mapList")[0].GetValueString("orderNo");
                return(true);
            }
            else
            {
                throw new Exception("三方返回错误信息:[" + rtnCode + "]" + jobj.GetValueString("returnMsg", "message"));
            }
        }
Example #13
0
        public static string getComment(HttpListenerRequest request)
        {
            String url          = result.id + "/comments";
            bool   isFinished   = false;
            String outputString = "";

            while (isFinished == false)
            {
                RestRequest rComments = new RestRequest(url);
                rComments.AddParameter("access_token", jsonParse.GetValue("token").ToString());

                Facebook.Comment facebookComment = JsonConvert.DeserializeObject <Facebook.Comment>(rClient.Execute(rComments).Content);
                foreach (Facebook.commentClass comment in facebookComment.data)
                {
                    outputString += String.Format("<b>{0}</b> : {1}<br>\n", comment.from.name, comment.message);
                }

                if (facebookComment.paging.next != null)
                {
                    url = facebookComment.paging.next.Replace("https://graph.facebook.com/v2.8/", "");
                }
                else
                {
                    isFinished = true;
                }
            }
            return(outputString);
        }
Example #14
0
        public static double GetMainCurrencyPrice(string mainMarket, PTMagicConfiguration systemConfiguration, LogHelper log)
        {
            double result = 0;

            if (mainMarket != "USD")
            {
                try
                {
                    string baseUrl = "https://api.binance.us/api/v1/ticker/24hr?symbol=" + mainMarket + "USDT";

                    log.DoLogInfo("BinanceUS - Getting main market price...");
                    Newtonsoft.Json.Linq.JObject jsonObject = GetSimpleJsonObjectFromURL(baseUrl, log, null);
                    if (jsonObject != null)
                    {
                        log.DoLogInfo("BinanceUS - Market data received for " + mainMarket + "USDT");

                        result = (double)jsonObject.GetValue("lastPrice");
                        log.DoLogInfo("BinanceUS - Current price for " + mainMarket + "USDT: " + result.ToString("#,#0.00") + " USD");
                    }
                }
                catch (Exception ex)
                {
                    log.DoLogCritical(ex.Message, ex);
                }
                return(result);
            }
            else
            {
                return(1.0);
            }
        }
Example #15
0
        public async Task AGitHubConnector_WillReturnAGitHubUser_WhenSearchingSuccessfully()
        {
            Newtonsoft.Json.Linq.JObject expectedUser = Generators.JsonGitHubUser.Sample(50, 1).First();
            HttpResponseMessage          expectedResponseFromGitHub = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(expectedUser.ToString())
            };

            HttpResponseMessage expectedRepositoriesResponse = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent("[]")
            };

            Mock <IAppHttpClient> appHttpClient = new Mock <IAppHttpClient>();

            appHttpClient.SetupSequence(c => c.Get(It.IsAny <string>()))
            .ReturnsAsync(expectedResponseFromGitHub)
            .ReturnsAsync(expectedRepositoriesResponse);

            GitHubConnector connector = new GitHubConnector(appHttpClient.Object);
            GitHubUser      result    = await connector.FindUser("test");

            Assert.AreEqual(result.FullName, expectedUser.GetValue("name").ToString());
        }
Example #16
0
        private System.Type GetObjectSubtype(Newtonsoft.Json.Linq.JObject jObject, System.Type objectType, string discriminator)
        {
            var objectTypeInfo   = System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType);
            var customAttributes = System.Reflection.CustomAttributeExtensions.GetCustomAttributes(objectTypeInfo);

            var     knownTypeAttributes = System.Linq.Enumerable.Where(customAttributes, a => a.GetType().Name == "KnownTypeAttribute");
            dynamic knownTypeAttribute  = System.Linq.Enumerable.SingleOrDefault(knownTypeAttributes, a => IsKnwonTypeTargetType(a, discriminator));

            if (knownTypeAttribute != null)
            {
                return(knownTypeAttribute.Type);
            }

            var typeName = objectType.Namespace + "." + discriminator;
            var subtype  = System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType).Assembly.GetType(typeName);

            if (subtype != null)
            {
                return(subtype);
            }

            var typeInfo = jObject.GetValue("$type");

            if (typeInfo != null)
            {
                return(System.Type.GetType(Newtonsoft.Json.Linq.Extensions.Value <string>(typeInfo)));
            }

            throw new System.InvalidOperationException("Could not find subtype of '" + objectType.Name + "' with discriminator '" + discriminator + "'.");
        }
        /// <inheritdoc/>
        public override object?ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            Newtonsoft.Json.Linq.JObject jObject = serializer.Deserialize <Newtonsoft.Json.Linq.JObject>(reader);
            if (jObject == null)
            {
                return(null);
            }

            var  discriminator = Newtonsoft.Json.Linq.Extensions.Value <string>(jObject.GetValue(this.discriminator, StringComparison.OrdinalIgnoreCase));
            Type subtype       = GetObjectSubtype(objectType, discriminator);

            var objectContract = serializer.ContractResolver.ResolveContract(subtype) as Newtonsoft.Json.Serialization.JsonObjectContract;

            if (objectContract == null || System.Linq.Enumerable.All(objectContract.Properties, p => p.PropertyName != this.discriminator))
            {
                jObject.Remove(this.discriminator);
            }

            try
            {
                isReading = true;
                return(serializer.Deserialize(jObject.CreateReader(), subtype));
            }
            finally
            {
                isReading = false;
            }
        }
Example #18
0
        public static string GetLatestGitHubRelease(LogHelper log, string defaultVersion)
        {
            string result = defaultVersion;

            try
            {
                string baseUrl = "https://api.github.com/repos/legedric/ptmagic/releases/latest";

                Newtonsoft.Json.Linq.JObject jsonObject = GetSimpleJsonObjectFromURL(baseUrl, log, true);
                if (jsonObject != null)
                {
                    result = jsonObject.GetValue("tag_name").ToString();
                }
            }
            catch (WebException ex)
            {
                log.DoLogDebug("GitHub version check error: " + ex.Message);
            }
            catch (Exception ex)
            {
                log.DoLogDebug("GitHub version check error: " + ex.Message);
            }

            return(result);
        }
Example #19
0
        public void TestAddUserSuccessfully()
        {
            Newtonsoft.Json.Linq.JObject response = DatabaseCommunicator.AddUser("*****@*****.**", "1");

            Assert.AreEqual(response.GetValue("message").ToString(), "Success");

            DeleteUser("*****@*****.**");
        }
Example #20
0
        public ZaloProfile GetProfile(string code)
        {
            Newtonsoft.Json.Linq.JObject token = appClient.getAccessToken(code);
            var sc = token.GetValue("access_token");

            Newtonsoft.Json.Linq.JObject profile = appClient.getProfile(sc.ToString(), "id,name");
            return(profile.ToObject <ZaloProfile>());
        }
Example #21
0
        static void Main(string[] args)
        {
            Console.WriteLine("LiveBot for C#\nYour Facebook Livestream Utilites");
            if (!File.Exists("config.json"))
            {
                Console.WriteLine("[ERROR] config.json File Not Found!");
                Console.ReadKey();
                Environment.Exit(1);
            }
            else
            {
                Console.WriteLine("[INFO] config.json Found!");
            }
            StreamReader sr = new StreamReader("config.json");

            jsonParse = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(sr.ReadToEnd());
            Console.WriteLine("Requesting New Stream Post...");
            RestRequest rNewStream = new RestRequest("me/live_videos", Method.POST);

            rNewStream.AddParameter("access_token", jsonParse.GetValue("token").ToString());
            rNewStream.AddParameter("title", jsonParse.GetValue("title").ToString());
            rNewStream.AddParameter("description", jsonParse.GetValue("description").ToString());
            rNewStream.AddParameter("save_vod", jsonParse.GetValue("save_vod").ToString());
            rNewStream.AddParameter("status", jsonParse.GetValue("status").ToString());
            result = JsonConvert.DeserializeObject <Facebook.LiveStreamResult>(rClient.Execute(rNewStream).Content);
            Console.WriteLine("[INFO] Stream Request Success!\nStream URL : rtmp://rtmp-api.facebook.com:80/rtmp/");
            Console.WriteLine("Stream Key : " + result.stream_url.Replace("rtmp://rtmp-api.facebook.com:80/rtmp/", ""));
            Console.ReadKey();
            WebServer ws = new WebServer(getComment, "http://127.0.0.1:8080/getComment/");

            ws.Run();
            Console.WriteLine("Type :quit to Exit!");
            bool isExit = false;

            while (isExit == false)
            {
                string arg = Console.ReadLine();
                if (arg == "quit")
                {
                    ws.Stop();
                    Environment.Exit(0);
                }
            }
        }
 public JsonResult CheckLogin([FromBody] Newtonsoft.Json.Linq.JObject data)
 {
     if (String.IsNullOrEmpty(data.GetValue("login").ToString()))
     {
         return(Json(new { success = false }));
     }
     using (var context = new PrincipalContext(ContextType.Domain, "demo")) //TODO domain name
     {
         var user = UserPrincipal.FindByIdentity(context, data.GetValue("login").ToString());
         if (user != null)
         {
             return(Json(new { success = true, name = user.DisplayName }));
         }
         else
         {
             return(Json(new { success = false }));
         }
     }
 }
Example #23
0
 protected override void OnReading(Newtonsoft.Json.Linq.JObject json)
 {
     forward = json.GetSafeStringValue("forward");
     range   = json.GetSafeStringValue("range");
     if (json.GetValue("removeable") != null)
     {
         removeable = bool.Parse(json.GetValue("removeable").ToString());
     }
     else
     {
         removeable = false;
     }
     deadable  = json.GetSafeStringValue("deadable");
     animation = json.GetSafeDoubleValue("animation");
     //prop = json.GetSafeStringValue("prop");
     //this.equipProp = new EquipmentProp();
     //this.equipProp.ReadFromJson(prop);
     base.OnReading(json);
 }
Example #24
0
        public void TestSaveUrlUnsuccessfully()
        {
            string user = "******";
            string url  = "gpnotebook.com";

            DatabaseCommunicator.email = user;
            Newtonsoft.Json.Linq.JObject response = DatabaseCommunicator.SaveURL(url);

            Assert.AreEqual(response.GetValue("message").ToString(), "User not found");
        }
Example #25
0
        public void TestSaveQueryUnsuccessfully()
        {
            string user_not_in_db = "*****@*****.**";
            string query          = "liver failure";

            DatabaseCommunicator.email = user_not_in_db;
            Newtonsoft.Json.Linq.JObject response = DatabaseCommunicator.SaveQuery(query);

            Assert.AreEqual(response.GetValue("message").ToString(), "User not found");
        }
        public async Task <IActionResult> SaveResult([FromBody] Newtonsoft.Json.Linq.JObject data)
        {
            if (data == null)
            {
                return(Json(new { ok = false, newUrl = "/Error" })); // редиректнули на страниц "Опрос пройден";
            }
            var    user     = Helper.UserHelper.GetUser(HttpContext, userRepository);
            string surveyId = data.GetValue("surveyId").ToString();

            if (data.GetValue("anew").ToString() == true.ToString()) // проверяем, это первое прохождение опроса или нет
            {
                userAnswer.DeleteRange(userAnswer.GetItems().Where(ob => ob.UserId == user.Id).ToList()).Wait();
            }
            List <SurveyService.Models.UserAnswer> answersList = new List <SurveyService.Models.UserAnswer>();

            foreach (var item in data.GetValue("data"))
            {
                var answer = answersList.Where(ob => ob.QuestionId == item.First["questionId"].ToString()).FirstOrDefault();
                if (answer == null)
                {
                    answer = new SurveyService.Models.UserAnswer()
                    {
                        QuestionId = item.First["questionId"].ToString(), UserId = user.Id, OptionsForAnswers = new List <SurveyService.Models.OptionsForAnswer>()
                    };
                    answersList.Add(answer);
                }
                if (item.First["type"].ToString() == "custom") // кастомный ответ (пользователь вводит текст в поле ответа)
                {
                    answer.OwnAnswerText = item.First["text"].ToString();
                }
                else // стандартный ответ (выбран из списка ответов)
                {
                    answer.OptionsForAnswers.Add(new SurveyService.Models.OptionsForAnswer()
                    {
                        OptionId = item.First["optionId"].ToString()
                    });
                }
            }
            await userAnswer.CreateRange(answersList);

            return(Json(new { ok = true, newUrl = Url.Action("SurveyCompleted", new { @surveyId = surveyId }) })); // редиректнули на страниц "Опрос пройден"
        }
Example #27
0
        protected override void OnReading(Newtonsoft.Json.Linq.JObject json)
        {
            cost         = json.GetSafeDoubleValue("cost");
            success      = json.GetSafeDoubleValue("success");
            description2 = json.GetSafeStringValue("description2");
            range        = json.GetSafeStringValue("range");
            forward      = json.GetSafeStringValue("forward");
            if (json.GetValue("trigger") != null)
            {
                trigger = bool.Parse(json.GetValue("trigger").ToString());
            }
            else
            {
                trigger = false;
            }

            animation = json.GetSafeDoubleValue("animation");
            deadable  = json.GetSafeStringValue("deadable");
            base.OnReading(json);
        }
Example #28
0
        public void TestAddUserUnsuccessfully()
        {
            string user = "******";

            DatabaseCommunicator.AddUser(user, "11");
            Newtonsoft.Json.Linq.JObject response = DatabaseCommunicator.AddUser(user, "9");

            Assert.AreEqual(response.GetValue("message").ToString(), "User already created.");

            DeleteUser(user);
        }
Example #29
0
        private static void ReadJsonDataFile(string filePath, Dictionary <string, List <Rule> > rules)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                using (StreamReader sr = new StreamReader(fs))
                    using (JsonTextReader reader = new JsonTextReader(sr))
                    {
                        while (reader.Read())
                        {
                            if (reader.TokenType == JsonToken.StartObject)
                            {
                                // Load each object from the stream and do something with it
                                Newtonsoft.Json.Linq.JObject obj = Newtonsoft.Json.Linq.JObject.Load(reader);
                                Variable v = new Variable(Convert.ToString(obj.GetValue("signal")),
                                                          Convert.ToString(obj.GetValue("value")),
                                                          Convert.ToString(obj.GetValue("value_type")));
                                if (!rules.ContainsKey(v.Signal))
                                {
                                    continue;
                                }
                                List <Rule> signalRules = rules[v.Signal];

                                foreach (Rule r in signalRules)
                                {
                                    if (v.ValueType == "Integer")
                                    {
                                        ProcessIntegerValueType(r, v);
                                    }
                                    else if (v.ValueType == "String")
                                    {
                                        ProcessStringValueType(r, v);
                                    }
                                    else if (v.ValueType == "Datetime")
                                    {
                                        ProcessDateTimeValueType(r, v);
                                    }
                                }
                            }
                        }
                    }
        }
Example #30
0
        /// <summary>
        /// Reads in the Configuration file settings and sets them to display.
        /// </summary>
        private void readSettings()
        {
            try
            {
                // Read in config file
                string settingsString = System.IO.File.ReadAllText(configFilePath);

                // Parse out as JSON components
                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");
                Newtonsoft.Json.Linq.JToken  SerialPort      = settings.GetValue("SerialPort");
                Newtonsoft.Json.Linq.JToken  BaudRate        = settings.GetValue("BaudRate");
                Newtonsoft.Json.Linq.JToken  CommType        = settings.GetValue("CommType");
                Newtonsoft.Json.Linq.JToken  TimeOut         = settings.GetValue("TimeOut");

                // Update the display fields
                destinationIP.Text   = DestinationIP.ToString();
                destinationPort.Text = DestinationPort.ToString();
                serialPort.Text      = SerialPort.ToString();
                baudRate.Text        = BaudRate.ToString();
                commType.Text        = CommType.ToString();
                timeOut.Text         = TimeOut.ToString();
            }
            catch (Exception e)
            {
                // Error reading file
                Console.WriteLine("Error reading file {0}", configFilePath);
            }
        }
Example #31
0
        public async void makeRequest()
        {
            var param = File.ReadAllLines("auth.dat");
            Newtonsoft.Json.Linq.JObject RESPONSE = Newtonsoft.Json.Linq.JObject.Parse(param[0]);
            using (var newClient = new HttpClient())
            {
                var values = new Dictionary<string, string>
                {
                    {"grant_type", "refresh_token"},
                    {"refresh_token", (string)RESPONSE["refresh_token"]},
                    {"client_id", "envatomate-3ur0bxxw"},
                    {"client_secret", "hhlB6MdIT5xCEy3wlwwbOaEK2XryGYqe"}
                };
                var content = new FormUrlEncodedContent(values);
                var response = await newClient.PostAsync("https://api.envato.com/token", content);
                var responseString = await response.Content.ReadAsStringAsync();
                Newtonsoft.Json.Linq.JObject NEWRESPONSE = Newtonsoft.Json.Linq.JObject.Parse(responseString);
                refreshedResponse = NEWRESPONSE;
                accessToken = (string)refreshedResponse["access_token"];
            }

            var client = new RestClient("https://api.envato.com/v1/market/private/user/account.json");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Bearer " + refreshedResponse.GetValue("access_token"));
            IRestResponse newResponse = client.Execute(request);


            // Check Response //
            Newtonsoft.Json.Linq.JObject THIS_ENVATO_RESPONSE = Newtonsoft.Json.Linq.JObject.Parse(newResponse.Content);
            //DEBUG - MessageBox.Show(ENVATO_RESPONSE.ToString());//
            // End of checking //

            // Populate the form //
            welcomeLabel.Text = ("Welcome, " + (string)THIS_ENVATO_RESPONSE["account"]["firstname"] + ".");
            profileImg.ImageLocation = (string)THIS_ENVATO_RESPONSE["account"]["image"];
            UI_BALANCE.Text = "£" + (string)THIS_ENVATO_RESPONSE["account"]["balance"];
            // End of populating //
        }