Example #1
20
 public RedditUser(Reddit reddit, JToken json, IWebAgent webAgent)
     : base(json)
 {
     Reddit = reddit;
     WebAgent = webAgent;
     JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings);
 }
Example #2
1
        private InfoShowItem JTokenToModel(JToken item)
        {
            Model.InfoShowItem oInfoShowItem = new Model.InfoShowItem();

            int id = int.Parse(item["id"].ToString());
            int count = int.Parse(item["count"].ToString());
            int rcount = int.Parse(item["rcount"].ToString());
            int fcount = int.Parse(item["fcount"].ToString());
            string img = item["img"].ToString() ?? "";
            string description = item["description"].ToString() ?? "";
            string keywords = item["keywords"].ToString() ?? "";
            int infoclass = int.Parse(item["infoclass"].ToString());
            long time = long.Parse(item["time"].ToString());
            string title = item["title"].ToString() ?? "";

            oInfoShowItem.id = id;
            oInfoShowItem.count = count;
            oInfoShowItem.rcount = rcount;
            oInfoShowItem.fcount = fcount;
            oInfoShowItem.img = img;//图片
            oInfoShowItem.description = description;
            oInfoShowItem.keywords = keywords;
            oInfoShowItem.infoclass = infoclass;
            oInfoShowItem.time = time;
            oInfoShowItem.title = title;

            return oInfoShowItem;
        }
        internal static string JsonToString(JToken token, string defaultValue = null)
        {
            if (token == null)
                return defaultValue;

            return token.ToString();
        }
Example #4
0
        public Function(JToken JSON, bool magicMethod = false)
            : this(magicMethod)
        {
            this.StartLine = Int32.MinValue;
            this.EndLine = Int32.MinValue;
            this.Formats = new List<string>();

            this.Name = (string)JSON.SelectToken(Keys.PHPDefinitionJSONKeys.GeneralKeys.Name);
            this.ParameterCount = (int)JSON.SelectToken(Keys.PHPDefinitionJSONKeys.GeneralKeys.ParameterCount);
            this.ReturnType = (string)JSON.SelectToken(Keys.PHPDefinitionJSONKeys.GeneralKeys.ReturnType);

            var formats = (JArray)JSON.SelectToken(Keys.PHPDefinitionJSONKeys.GeneralKeys.Formats);
            if (formats != null)
            {
                foreach (string format in formats)
                {
                    this.Formats.Add(format);
                }
            }

            var aliasArray = (JArray)JSON.SelectToken(Keys.PHPDefinitionJSONKeys.GeneralKeys.Aliases);
            if(aliasArray != null)
            {
                foreach (string alias in aliasArray)
                {
                    Aliases.Add(alias);
                }
            }
        }
Example #5
0
 public static JArray Diff(JArray source, JArray target, out bool changed, bool nullOnRemoved = false)
 {
     changed = source.Count != target.Count;
     var diffs = new JToken[target.Count];
     var commonLen = Math.Min(diffs.Length, source.Count);
     for (int i = 0; i < commonLen; i++)
     {
         if (target[i].Type == JTokenType.Object && source[i].Type == JTokenType.Object)
         {
             var subchanged = false;
             diffs[i] = Diff((JObject)source[i], (JObject)target[i], out subchanged, nullOnRemoved);
             if (subchanged) changed = true;
         }
         else if (target[i].Type == JTokenType.Array && source[i].Type == JTokenType.Array)
         {
             var subchanged = false;
             diffs[i] = Diff((JArray)source[i], (JArray)target[i], out subchanged, nullOnRemoved);
             if (subchanged) changed = true;
         }
         else
         {
             diffs[i] = target[i];
             if (!JToken.DeepEquals(source[i], target[i]))
                 changed = true;
         }
     }
     for (int i = commonLen; i < diffs.Length; i++)
     {
         diffs[i] = target[i];
         changed = true;
     }
     return new JArray(diffs);
 }
Example #6
0
 public Tax(JToken jTax)
     : this()
 {
     Kind = (string)jTax["kind"];
     ID = (string)jTax["iD"];
     Name = (string)jTax["name"];
 }
Example #7
0
        private static void CompareTokens(JToken expected, JToken actual)
        {
            if (expected == null && actual == null)
                return;

            if (expected == null || actual == null)
                FailValue(expected ?? "null", actual ?? "null");

            var expectedType = GetJsonType(expected);
            var actualType = GetJsonType(actual);

            if (expectedType != actualType)
                FailValue(expected, actual);

            switch (expectedType)
            {
                case JsonType.Null:
                    return;

                case JsonType.Primitive:
                    ComparePrimitives((JValue)expected, (JValue)actual);
                    break;

                case JsonType.Array:
                    CompareArrays((JArray)expected, (JArray)actual);
                    break;

                case JsonType.Map:
                    CompareMaps((JObject)expected, (JObject)actual);
                    break;
            }
        }
Example #8
0
    /// <summary>
    /// Initializes a new instance of the <see cref="JTokenReader"/> class.
    /// </summary>
    /// <param name="token">The token to read from.</param>
    public JTokenReader(JToken token)
    {
      ValidationUtils.ArgumentNotNull(token, "token");

      _root = token;
      _current = token;
    }
Example #9
0
 public Comment Init(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
 {
     var data = CommonInit(reddit, json, webAgent, sender);
     ParseComments(reddit, json, webAgent, sender);
     JsonConvert.PopulateObject(data.ToString(), this, reddit.JsonSerializerSettings);
     return this;
 }
Example #10
0
        public async Task ApplyConfiguration(JToken configJson)
        {
            var incomingConfig = new ConfigurationDataBasicLogin();
            incomingConfig.LoadValuesFromJson(configJson);
            var pairs = new Dictionary<string, string> {
                { "username", incomingConfig.Username.Value },
                { "password", incomingConfig.Password.Value }
            };
            var request = new Utils.Clients.WebRequest()
            {
                Url = LoginUrl,
                Type = RequestType.POST,
                Referer = SiteLink,
                PostData = pairs
            };
            var response = await webclient.GetString(request);
            CQ splashDom = response.Content;
            var link = splashDom[".trow2 a"].First();
            var resultPage = await RequestStringWithCookies(link.Attr("href"), response.Cookies);
            CQ resultDom = resultPage.Content;

            await ConfigureIfOK(response.Cookies, resultPage.Content.Contains("/logout.php"), () =>
            {
                var tries = resultDom["#main tr:eq(1) td font"].First().Text();
                var errorMessage = "Incorrect username or password! " + tries + " tries remaining.";
                throw new ExceptionWithConfigData(errorMessage, (ConfigurationData)incomingConfig);
            });
        }
Example #11
0
 public async Task<Comment> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent, Thing sender)
 {
     var data = CommonInit(reddit, json, webAgent, sender);
     await ParseCommentsAsync(reddit, json, webAgent, sender);
     await Task.Factory.StartNew(() => JsonConvert.PopulateObject(data.ToString(), this, reddit.JsonSerializerSettings));
     return this;
 }
 public override bool IsMatch(JToken t)
 {
     switch (Operator)
     {
         case QueryOperator.And:
             foreach (QueryExpression e in Expressions)
             {
                 if (!e.IsMatch(t))
                 {
                     return false;
                 }
             }
             return true;
         case QueryOperator.Or:
             foreach (QueryExpression e in Expressions)
             {
                 if (e.IsMatch(t))
                 {
                     return true;
                 }
             }
             return false;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
Example #13
0
		public static DiscordChannel ParseChannelAndChoose(JToken jmessage)
		{
			if (jmessage["type"].ToString().Equals("text", StringComparison.CurrentCultureIgnoreCase))
			{
				return new DiscordTextChannel
				{
					ID   = jmessage["id"].ToString(),
					Name = jmessage["name"].ToString(),
					Position = jmessage["position"].ToObject<int>(),
					GuildID  = jmessage["guild_id"].ToString(),
					Topic = jmessage["topic"].HasValues ? jmessage["topic"].ToString() : null,
					LastMessageID = jmessage["last_message_id"].ToString()
				};
			}
			else
			{
				return new DiscordVoiceChannel
				{
					ID   = jmessage["id"].ToString(),
					Name = jmessage["name"].ToString(),
					Position = jmessage["position"].ToObject<int>(),
					GuildID = jmessage["guild_id"].ToString(),
					Bitrate = jmessage["bitrate"].ToObject<int>()
				};
			}
		}
        protected void ProcessMessage(JToken message) {
            var channel = (string)message["channel"];
            var chansplit = channel.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (chansplit.Length < 2) return;

            if (chansplit[0] == "meta") {
                switch (chansplit[1]) {
                    case "handshake":
                        HandshakeCallback((JObject)message);
                        break;
                    case "connect":
                        ConnectCallback((JObject)message);
                        break;
                    case "subscribe":
                        SubscribeCallback((JObject)message);
                        break;
                    case "unsubscribe":
                        UnsubscribeCallback((JObject)message);
                        break;
                }
                return;
            }

            if (message["successful"] != null) {
                PublishCallback((JObject)message);
            }

            if (PrimaryReciever != null) {
                PrimaryReciever.OnMessage((JObject)message);
            }
            OnReceive((JObject)message);
        }
Example #15
0
        private static Protocol Parse(JToken j)
        {
            string protocol = JsonHelper.GetRequiredString(j, "protocol");
            string snamespace = JsonHelper.GetRequiredString(j, "namespace");
            string doc = JsonHelper.GetOptionalString(j, "doc");

            Names names = new Names();

            JToken jtypes = j["types"];
            List<Schema> types = new List<Schema>();
            if (jtypes is JArray)
            {
                foreach (JToken jtype in jtypes)
                {
                    Schema schema = Schema.ParseJson(jtype, names);
                    types.Add(schema);
                }
            }


            JToken jmessages = j["messages"];
            List<Message> messages = new List<Message>();


            foreach (JProperty jmessage in jmessages)
            {
                Message message = Message.Parse(jmessage, names);
                messages.Add(message);
            }

            


            return new Protocol(protocol, snamespace, doc, types, messages);
        }
Example #16
0
        public async Task ApplyConfiguration(JToken configJson)
        {
            var config = new ConfigurationDataBasicLogin();
            config.LoadValuesFromJson(configJson);
           
            var pairs = new Dictionary<string, string> {
				{ "username", config.Username.Value },
				{ "password", config.Password.Value }
			};

            var content = new FormUrlEncodedContent(pairs);

            var response = await client.PostAsync(LoginUrl, content);
            var responseContent = await response.Content.ReadAsStringAsync();

            if (!responseContent.Contains("logout.php"))
            {
                CQ dom = responseContent;
                var errorMessage = dom["td.text"].Text().Trim();
                throw new ExceptionWithConfigData(errorMessage, (ConfigurationData)config);
            }
            else
            {
                var configSaveData = new JObject();
                cookies.DumpToJson(SiteLink, configSaveData);
                SaveConfig(configSaveData);
                IsConfigured = true;
            }
        }
Example #17
0
        private static void UpdateFile(string downloadurl, string folder, JToken file, JToken oldFile, string job)
        {
            if (file["@sha"] == null) return;

            string shahash = (string)file["@sha"];
            string filename = (string)file["@name"];

            //If oldFile is null, that means this is a new file.
            if (oldFile != null)
            {
                string oldsha = (string)oldFile["@sha"];

                if (shahash == oldsha)
                {
                    return;
                }
            }

            shahash = shahash.Insert(2, "/").Insert(6, "/");

            int uncompressedsize = (int)file["@uncompressedSize"];
            int compressedsize = (int)file["@compressedSize"];

            if (uncompressedsize > compressedsize)
            {
                Downloader.DownloadAndDecompress(filename, downloadurl + "/" + shahash, folder + filename, job);
            }
            else
            {
                Downloader.Download(filename, downloadurl + "/" + shahash, folder + filename, job);
            }

            Console.WriteLine("Downloading: " + filename);
        }
Example #18
0
        public static Material FromJToken(JToken tok)
        {
            SerializedMaterial mat = JsonConvert.DeserializeObject<SerializedMaterial>(tok.ToString());

            if (string.IsNullOrWhiteSpace(mat.name))
                throw new Exception("Material: 'name' not defined.");
            if (string.IsNullOrWhiteSpace(mat.color))
                throw new Exception("Material: 'color' not defined.");
            Color c = mat.color.ColorFromHexString("Material: Unable to parse 'color'.");

            if (mat.texture == null)
                return new Material { Name = mat.name, Color = c,
                                      Ambient = mat.ambient, Lambert = mat.lambert,
                                      Specular = mat.specular, Textured = false };
            Texture t = null;
            try
            {
                t = Texture.FromPath(mat.texture);
            }
            catch { throw new Exception(string.Format("Material: Unable to load 'texture' at path '{0}'", mat.texture)); }

            return new Material
            {
                Name = mat.name,
                Color = c,
                Ambient = mat.ambient,
                Lambert = mat.lambert,
                Specular = mat.specular,
                Textured = true,
                Texture = t
            };
        }
Example #19
0
 private static bool TryGetInt(JToken json, out int value)
 {
     var x = json as JValue;
     var isInt = x != null && x.Type == JTokenType.Integer;
     value = isInt ? x.ToObject<int>() : 0;
     return isInt;
 }
 public override void Publish(string channel, JToken data)
 {
     if (!IsConnected) {
         throw new InvalidOperationException("WebSocket not connected or bayeux session not initialized");
     }
     Send(new { channel, data });
 }
Example #21
0
        public void WriteStartRootObject(string name, bool contained)
        {
            _createdRootObject = new JObject(new JProperty(JsonDomFhirReader.RESOURCETYPE_MEMBER_NAME, name));

            if (!contained)
                _root = _createdRootObject;                    
        }
        private static int GetReturnCodeForSuccess(JToken response)
        {
            if (response["200"] != null)
            {
                return 200;
            }

            if (response["202"] != null)
            {
                return 202;
            }

            if (response["201"] != null)
            {
                return 201;
            }

            if (response["206"] != null)
            {
                return 206;
            }

            if (response["204"] != null)
            {
                return 204;
            }

            throw new InvalidOperationException("Succes code not found");
        }
Example #23
0
        /// <summary>
        /// Configure our FADN Provider
        /// </summary>
        /// <param name="configJson">Our params in Json</param>
        /// <returns>Configuration state</returns>
        public async Task<IndexerConfigurationStatus> ApplyConfiguration(JToken configJson)
        {
            // Retrieve config values set by Jackett's user
            ConfigData.LoadValuesFromJson(configJson);

            // Check & Validate Config
            ValidateConfig();

            // Setting our data for a better emulated browser (maximum security)
            // TODO: Encoded Content not supported by Jackett at this time
            // emulatedBrowserHeaders.Add("Accept-Encoding", "gzip, deflate");

            // If we want to simulate a browser
            if (ConfigData.Browser.Value)
            {

                // Clean headers
                _emulatedBrowserHeaders.Clear();

                // Inject headers
                _emulatedBrowserHeaders.Add("Accept", ConfigData.HeaderAccept.Value);
                _emulatedBrowserHeaders.Add("Accept-Language", ConfigData.HeaderAcceptLang.Value);
                _emulatedBrowserHeaders.Add("DNT", Convert.ToInt32(ConfigData.HeaderDnt.Value).ToString());
                _emulatedBrowserHeaders.Add("Upgrade-Insecure-Requests", Convert.ToInt32(ConfigData.HeaderUpgradeInsecure.Value).ToString());
                _emulatedBrowserHeaders.Add("User-Agent", ConfigData.HeaderUserAgent.Value);
                _emulatedBrowserHeaders.Add("Referer", LoginUrl);
            }

            await DoLogin();

            return IndexerConfigurationStatus.RequiresTesting;
        }
Example #24
0
        public async Task<IndexerConfigurationStatus> ApplyConfiguration(JToken configJson)
        {
            var loginPage = await RequestStringWithCookies(LoginUrl);
            CQ loginDom = loginPage.Content;
            var loginPostUrl = loginDom["#login"].Attr("action");

            configData.LoadValuesFromJson(configJson);
            var pairs = new Dictionary<string, string> {
                { "username", configData.Username.Value },
                { "password", configData.Password.Value }
            };
            // Get inital cookies
            CookieHeader = string.Empty;
            var response = await RequestLoginAndFollowRedirect(SiteLink + loginPostUrl, pairs, CookieHeader, true, null, LoginUrl);

            await ConfigureIfOK(response.Cookies, response.Content != null && response.Content.Contains("Velkommen tilbage"), () =>
            {
                CQ dom = response.Content;
                var messageEl = dom["inputs"];
                var errorMessage = messageEl.Text().Trim();
                throw new ExceptionWithConfigData(errorMessage, configData);
            });

            var profilePage = await RequestStringWithCookies(ProfileUrl, response.Cookies);
            CQ profileDom = profilePage.Content;
            var passKey = profileDom["input[name=resetkey]"].Parent().Text();
            passKey = passKey.Substring(0, passKey.IndexOf(' '));
            configData.RSSKey.Value = passKey;
            SaveConfig();
            return IndexerConfigurationStatus.RequiresTesting;
        }
 protected void AddJOValue(String key, JToken value)
 {
     if (this.data[key] == null)
         this.data.Add(key, value);
     else
         this.data[key].Replace(value);
 }
        /// <summary>
        /// Converts the specified <code>token</code> into an instance of <code>IGridEditorConfig</code>.
        /// </summary>
        /// <param name="editor"></param>
        /// <param name="token">The instance of <code>JToken</code> representing the editor config.</param>
        /// <param name="config">The converted config.</param>
        public bool ConvertEditorConfig(GridEditor editor, JToken token, out IGridEditorConfig config) {
            
            config = null;

            switch (editor.Alias) {

                case "media_wide":
                case "media_wide_cropped":
                    config = GridEditorMediaConfig.Parse(editor, token as JObject);
                    break;

                case "banner_headline":
                case "banner_tagline":
                case "headline_centered":
                case "abstract":
                case "paragraph":
                case "quote_D":
                case "code":
                    config = GridEditorTextConfig.Parse(editor, token as JObject);
                    break;
                    
            }

            return config != null;
        
        }
        public static PhoneCall FillObject(JToken data)
        {
            DateTime IndianTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));

            PhoneCall Phonecall        = new PhoneCall();
            Phonecall.Action           = "1";
            Phonecall.AgentNumber      = data["agent_number"].ToString();
            Phonecall.BusinessCallType = data["business_call_type"].ToString();
            Phonecall.CallDuration     = (data["duration"] != null) ? data["duration"].ToString() : "0";
            Phonecall.CallId           = data["uuid"].ToString();
            Phonecall.CallType         = data["call_direction"].ToString();
            Phonecall.CallerId         = "";
            Phonecall.CustomerNumber   = data["customer_number"].ToString();
            Phonecall.Destination      = "";
            Phonecall.DispNumber       = data["knowlarity_number"].ToString();
            //Phonecall.EndTime          = "2015-09-01 11:35:52.090392+05:30";
            Phonecall.EndTime          = IndianTime.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss.ffffff+5:30");
            Phonecall.Extension        = "5";
            Phonecall.HangupCause      = "900";
            Phonecall.ResourceUrl      = (data["call_recording"] != null) ? data["call_recording"].ToString() : String.Empty;
            Phonecall.StartTime        = "2015-08-11 11:35:47+05:30";
            Phonecall.Timezone         = "Asia/Kolkata";
            Phonecall.Type             = "";

            return Phonecall;
            
        }
Example #28
0
 private static object ToObject(JToken token)
 {
     if (token.Type == JTokenType.Object)
     {
         Dictionary<string, object> dict = new Dictionary<string, object>();
         foreach (JProperty prop in token)
         {
             dict.Add(prop.Name, ToObject(prop.Value));
         }
         return dict;
     }
     else if (token.Type == JTokenType.Array)
     {
         List<object> list = new List<object>();
         foreach (JToken value in token)
         {
             list.Add(ToObject(value));
         }
         return list;
     }
     else if (token.Type == JTokenType.Date)
     {
         // Hacky hack back
         // Can't figure out how to tell JSON.net not to deserialize datetimes
         return ((JValue)token).ToObject<DateTime>().ToString("yyyy-MM-dd'T'HH:mm:ssZ");
     }
     else
     {
         return ((JValue)token).Value;
     }
 }
        /// <summary>
        /// Converts the specified <code>token</code> into an instance of <code>IGridControlValue</code>.
        /// </summary>
        /// <param name="control">The parent control.</param>
        /// <param name="token">The instance of <code>JToken</code> representing the control value.</param>
        /// <param name="value">The converted value.</param>
        public bool ConvertControlValue(GridControl control, JToken token, out IGridControlValue value) {
            
            value = null;
            
            switch (control.Editor.Alias) {

                case "media_wide":
                case "media_wide_cropped":
                    value = GridControlMediaValue.Parse(control, token as JObject);
                    break;

                case "banner_headline":
                case "banner_tagline":
                case "headline_centered":
                case "abstract":
                case "paragraph":
                case "quote_D":
                case "code":
                    value = GridControlTextValue.Parse(control, token);
                    break;
            
            }
            
            return value != null;
        
        }
 internal static MovieLinks Parse(JToken json) {
     return new MovieLinks() {
         Alternate = (string)json["alternate"],
         Cast = (string)json["cast"],
         Reviews = (string)json["reviews"]
     };
 }
Example #31
0
        protected override IWebSocket OnGetTickersWebSocket(Action <IReadOnlyCollection <KeyValuePair <string, ExchangeTicker> > > callback)
        {
            void innerCallback(string json)
            {
                #region sample json

                /*
                 * {
                 *  Nonce : int,
                 *  Deltas :
                 *  [
                 *      {
                 *          MarketName     : string,
                 *          High           : decimal,
                 *          Low            : decimal,
                 *          Volume         : decimal,
                 *          Last           : decimal,
                 *          BaseVolume     : decimal,
                 *          TimeStamp      : date,
                 *          Bid            : decimal,
                 *          Ask            : decimal,
                 *          OpenBuyOrders  : int,
                 *          OpenSellOrders : int,
                 *          PrevDay        : decimal,
                 *          Created        : date
                 *      }
                 *  ]
                 * }
                 */
                #endregion

                var    freshTickers = new Dictionary <string, ExchangeTicker>(StringComparer.OrdinalIgnoreCase);
                JToken token        = JToken.Parse(json);
                token = token["D"];
                foreach (JToken ticker in token)
                {
                    string   marketName = ticker["M"].ToStringInvariant();
                    decimal  last       = ticker["l"].ConvertInvariant <decimal>();
                    decimal  ask        = ticker["A"].ConvertInvariant <decimal>();
                    decimal  bid        = ticker["B"].ConvertInvariant <decimal>();
                    decimal  volume     = ticker["V"].ConvertInvariant <decimal>();
                    decimal  baseVolume = ticker["m"].ConvertInvariant <decimal>();
                    DateTime timestamp  = CryptoUtility.UnixTimeStampToDateTimeMilliseconds(ticker["T"].ConvertInvariant <long>());
                    var      t          = new ExchangeTicker
                    {
                        Ask    = ask,
                        Bid    = bid,
                        Last   = last,
                        Volume = new ExchangeVolume
                        {
                            ConvertedVolume = volume,
                            ConvertedSymbol = marketName,
                            BaseVolume      = baseVolume,
                            BaseSymbol      = marketName,
                            Timestamp       = timestamp
                        }
                    };
                    freshTickers[marketName] = t;
                }
                callback(freshTickers);
            }

            var client = SocketManager;
            return(client.SubscribeToSummaryDeltas(innerCallback));
        }
        /// <summary>
        ///     Before requesting a variable resolution, a client should
        ///     ask, whether the source can resolve a particular variable name.
        /// </summary>
        /// <param name="name">the name of the variable to resolve</param>
        /// <returns><c>true</c> if the variable can be resolved, <c>false</c> otherwise</returns>
        public bool CanResolveVariable(string name)
        {
            JToken selectToken = _variables.SelectToken(name);

            return(selectToken != null);
        }
Example #33
0
 private ExchangeTicker ParseTickerV2(string symbol, JToken ticker)
 {
     // {"buy":"0.00001273","change":"-0.00000009","changePercentage":"-0.70%","close":"0.00001273","createdDate":1527355333053,"currencyId":535,"dayHigh":"0.00001410","dayLow":"0.00001174","high":"0.00001410","inflows":"19.52673814","last":"0.00001273","low":"0.00001174","marketFrom":635,"name":{},"open":"0.00001282","outflows":"52.53715678","productId":535,"sell":"0.00001284","symbol":"you_btc","volume":"5643177.15601228"}
     return(this.ParseTicker(ticker, symbol, "sell", "buy", "last", "volume", null, "createdDate", TimestampType.UnixMilliseconds));
 }
Example #34
0
 private ExchangeTicker ParseTicker(string symbol, JToken data)
 {
     //{"date":"1518043621","ticker":{"high":"0.01878000","vol":"1911074.97335534","last":"0.01817627","low":"0.01813515","buy":"0.01817626","sell":"0.01823447"}}
     return(this.ParseTicker(data["ticker"], symbol, "sell", "buy", "last", "vol", null, "date", TimestampType.UnixSeconds));
 }
Example #35
0
 public override void Read(JObject jOperation)
 {
     Path  = jOperation.Value <string>("path");
     Value = jOperation.GetValue("value");
 }
Example #36
0
 public Verb(JToken verb) : this(verb, ApiVersion.GetLatest())
 {
 }
Example #37
0
        /// <summary>
        /// Evaluates the current <see cref="JsonPointer"/> against the specified target.
        /// </summary>
        /// <param name="target">The target <see cref="JToken"/>.</param>
        /// <param name="options">The evaluation options.</param>
        /// <returns>The result of the evaluation.</returns>
        public JToken Evaluate(JToken target, JsonPointerEvaluationOptions options = default)
        {
            if (_tokens is null) return target;

            for (var i = 0; i < _tokens.Length; i++)
            {
                JsonPointerToken token = _tokens[i];

                if (target is null || target.Type == JTokenType.Null)
                {
                    if (options.HasFlag(JsonPointerEvaluationOptions.NullCoalescing)) return target;
                    throw new InvalidOperationException($"Cannot evaluate the token '{token.Value}' on a null value.");
                }

                switch (target.Type)
                {
                    case JTokenType.String:
                    case JTokenType.Integer:
                    case JTokenType.Float:
                    case JTokenType.Boolean:
                        if (options.HasFlag(JsonPointerEvaluationOptions.PrimitiveMembersAndIndiciesAreNull)) target = null;
                        else throw new InvalidOperationException($"Cannot evaluate the token '{token.Value}' against the primitive value {target}.");

                        break;

                    case JTokenType.Object:
                        var o = (JObject)target;
                        if (!o.TryGetValue(token.Value, out target))
                        {
                            if (options.HasFlag(JsonPointerEvaluationOptions.MissingMembersAreNull)) target = null;
                            else throw new InvalidOperationException($"The current evaluated object does not contain the member '{token.Value}'.");
                            continue;
                        }

                        break;

                    case JTokenType.Array:
                        if (token.Value == "-")
                        {
                            if (options.HasFlag(JsonPointerEvaluationOptions.InvalidIndiciesAreNull)) target = null;
                            else throw new InvalidOperationException($"The new index token ('{token.Value}') is not supported.");
                            continue;
                        }

                        var a = (JArray)target;
                        var index = token.ArrayIndex;
                        if (!index.HasValue)
                        {
                            if (options.HasFlag(JsonPointerEvaluationOptions.ArrayMembersAreNull)) target = null;
                            else throw new InvalidOperationException($"An array cannot be indexed by the member '{token.Value}'.");
                            continue;
                        }

                        if (index.Value >= a.Count)
                        {
                            if (options.HasFlag(JsonPointerEvaluationOptions.InvalidIndiciesAreNull)) target = null;
                            else throw new InvalidOperationException($"The index {index.Value} falls outside the array length ({a.Count}).");
                            continue;
                        }

                        target = a[index.Value];
                        break;

                    default:
                        throw new InvalidOperationException($"Unsupported Json type {target.GetType()}.");
                }
            }

            return target;
        }
Example #38
0
		/// <summary>
		/// Initializes an instance of a browser element.
		/// </summary>
		/// <param name="element">The browser element this is for.</param>
		/// <param name="browser">The browser this element is associated with.</param>
		/// <param name="collection">The collection this element is associated with.</param>
		public OrderedList(JToken element, Browser browser, ElementCollection collection)
			: base(element, browser, collection)
		{
		}
Example #39
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            JToken t = JToken.FromObject(value);

            t.WriteTo(writer);
        }
Example #40
0
        public void Security_AuthorizeEndpointTests(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, AuthServerHappyPathConfiguration);

                IDisposable clientEndpoint = null;
                try
                {
                    clientEndpoint = WebApp.Start(Client_Redirect_Uri, app => app.Run(context => { return(context.Response.WriteAsync(context.Request.QueryString.Value)); }));

                    string tokenEndpointUri = applicationUrl + "TokenEndpoint";
                    var    basicClient      = new HttpClient();
                    var    headerValue      = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", "123", "invalid")));
                    basicClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);

                    HttpClient          httpClient          = new HttpClient();
                    string              requestUri          = null;
                    Uri                 landingUri          = null;
                    Uri                 applicationUri      = new Uri(applicationUrl);
                    HttpResponseMessage httpResponseMessage = null;

                    //Happy path - response_type:code
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Happy path - response_type:token
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    landingUri = new Uri(landingUri.AbsoluteUri.Replace('#', '?'));
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["access_token"]);
                    Assert.NotNull(landingUri.ParseQueryString()["expires_in"]);
                    Assert.Equal <string>("bearer", landingUri.ParseQueryString()["token_type"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Invalid redirect URI - pass error to application
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_passonerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>("error: invalid_request\r\n", httpResponseMessage.Content.ReadAsStringAsync().Result);
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");

                    //Invalid redirect URI - Display error by middleware
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_displayerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //What happens if we don't set Validated explicitly. Send an invalid clientId => We don't set Validated for this case.
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "token", "invalidClient", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //OnValidateAuthorizeRequest - Rejecting a request. Send an invalid state as we validate it there. Client should receive all the error code & description that we send
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "invalidstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    landingUri          = httpResponseMessage.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("state.invalid", landingUri.ParseQueryString()["error"]);
                    Assert.Equal <string>("state.invaliddescription", landingUri.ParseQueryString()["error_description"]);
                    Assert.Equal <string>("state.invaliduri", landingUri.ParseQueryString()["error_uri"]);
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error=state.invalid&error_description=state.invaliddescription&error_uri=state.invaliduri"), "Did not receive an error when provider did not set Validated");

                    //Missing response_type
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, null, "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("invalid_request", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Unsupported response_type
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "invalid_response_type", "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("unsupported_response_type", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Missing client_id
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "token", null, Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //Missing state - Should succeed
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", null);
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <bool>(false, landingUri.ParseQueryString().ContainsKey("state"));

                    //Token endpoint tests
                    //Invalid client (client_id, client_secret) - As form parameters
                    var formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "invalid") });
                    var responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    var jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_client", jToken.SelectToken("error").Value <string>());

                    //Invalid client (client_id, client_secret) - As Basic auth headers
                    responseMessage = basicClient.GetAsync(tokenEndpointUri).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_client", jToken.SelectToken("error").Value <string>());

                    //grant_type=authorization_code - invalid code being sent
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", "InvalidCode"), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_grant", jToken.SelectToken("error").Value <string>());

                    //grant_type=authorization_code - Full scenario
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", landingUri.ParseQueryString()["code"]), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=password -- Resource owner credentials -- Invalid credentials
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "invalid"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_grant", jToken.SelectToken("error").Value <string>());

                    //grant_type=password -- Resource owner credentials
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "password1"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=refresh_token -- Use the refresh token issued on the previous call
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "refresh_token"), new kvp("refresh_token", jToken.SelectToken("refresh_token").Value <string>()), new kvp("scope", "scope1 scope2") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=client_credentials - Bug# https://github.com/Katana/katana/issues/562
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "client_credentials"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                }
                finally
                {
                    //Finally close the client endpoint
                    if (clientEndpoint != null)
                    {
                        clientEndpoint.Dispose();
                    }
                }
            }
        }
Example #41
0
 public Attribute(JToken json, Template template, INode parent)
 {
     this.Json = json;
     this.Template = template;
     this.Parent = parent;
 }
 public JsonLegacySettings(JToken token)
 {
     this.token = token ?? throw new ArgumentNullException(nameof(token));
 }
Example #43
0
 public IEnumerable <Measurement> GetMeasurements(JToken token)
 {
     return(_templates.SelectMany(t => t.GetMeasurements(token)));
 }
Example #44
0
        public static FacebookEvent Event(long id, JToken json)
        {
            FacebookEvent fb;
            if ((fb = Data.FacebookEvents.FirstOrDefault(x => x.Id == id)) == null)
            {
                fb = new FacebookEvent
                {
                    Id = id,
                    Name = json.TryGetValue<string>("name")
                };
                if (fb.Name == default(string))
                    return null;
                Data.FacebookEvents.InsertOnSubmit(fb);
            }
            if (!json.Any())
                return fb;

            fb.Name = json.TryGetValue<string>("name");
            fb.Description = json.TryGetValue<string>("description");
            fb.TimeStart = json.TryGetValue<DateTime>("start_time");
            fb.TimeEnd = json.TryGetValue<DateTime>("end_time");
            if (fb.TimeEnd == default(DateTime))
                fb.TimeEnd = null;
            fb.TimeUpdated = json.TryGetValue<DateTime>("updated_time");
            if (fb.TimeUpdated == default(DateTime))
                fb.TimeUpdated = null;
            fb.Response = json.TryGetValue<string>("rsvp_status");

            try
            {
                Data.SubmitChanges();
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("There was an error saving the event: {0} {1}", id, fb.Name), ex);
                return null;
            }

            var fromId = json["owner"].TryGetValue<long?>("id");
            if (fromId != null)
            {
                var contact = Contact(fromId.Value, json["owner"]);
                if (contact != null)
                    fb.Contact = contact.Id;
                try
                {
                    Data.SubmitChanges();
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("There was an error saving the event: {0} {1}", id, fb.Name), ex);
                }
            }

            var locationId = json.TryGetValue<long?>("id");
            if (locationId != null)
            {
                var location = Place(locationId.Value, json["venue"]);
                if (location != null)
                    fb.Place = location.Id;
                try
                {
                    Data.SubmitChanges();
                }
                catch (Exception ex)
                {
                    Log.Error(string.Format("There was an error saving the event: {0} {1}", id, fb.Name), ex);
                }
            }

            var comments = json.TryGetValue<JObject>("comments");
            if (comments != null)
            {
                Message(id, json);
            }

            return fb;
        }
Example #45
0
        private void ProcessData(object RawData)
        {
            if (RawData != null)
            {
                string speed = null;

                JObject data = (JObject)RawData;

                JToken address = data["address"];
                speed = data["reportedHashRate"].ToString();
                var    unpaid  = data["unpaid"];
                JToken workers = data["workers"];

                foreach (EtherminePriceEntry entry in PriceEntries)
                {
                    if (entry.Wallet.ToLower().Contains(address.ToString().ToLower()))
                    {
                        entry.Balance = (decimal)unpaid;
                        if (entry.CoinName.ToLower() == "zcash")
                        {
                            entry.Balance /= 100000000;
                        }
                        if (entry.CoinName.ToLower() == "ethereum")
                        {
                            entry.Balance /= 1000000000000000000;
                        }
                        if (entry.CoinName.ToLower() == "ethereumclassic")
                        {
                            entry.Balance /= 1000000000000000000;
                        }

                        entry.BalanceBTC = entry.Balance * entry.ExRate;
                        //totalBalance += entry.BalanceBTC;

                        if (speed.EndsWith("H/s"))
                        {
                            entry.AcceptSpeed = speed.Replace("H/s", "").ExtractDecimal() / 1000;
                        }
                        if (speed.EndsWith("MH/s"))
                        {
                            entry.AcceptSpeed = speed.Replace("MH/s", "").ExtractDecimal() * 1000;
                        }
                        if (speed.EndsWith("kH/s"))
                        {
                            entry.AcceptSpeed = speed.Replace("kH/s", "").ExtractDecimal();
                        }

                        if (workers != null)
                        {
                            foreach (JProperty item in workers.Children())
                            {
                                var    AcSpWrk  = 0m;
                                string hashrate = item.Value["hashrate"].ToString();
                                if (item.Name.ToString().ToLower() == _worker.ToLower() && !string.IsNullOrWhiteSpace(hashrate))
                                {
                                    if (hashrate.EndsWith("H/s"))
                                    {
                                        AcSpWrk = hashrate.Replace("H/s", "").ExtractDecimal() / 1000;
                                    }
                                    if (hashrate.EndsWith("MH/s"))
                                    {
                                        AcSpWrk = hashrate.Replace("MH/s", "").ExtractDecimal() * 1000;
                                    }
                                    if (hashrate.EndsWith("kH/s"))
                                    {
                                        AcSpWrk = hashrate.Replace("kH/s", "").ExtractDecimal();
                                    }

                                    if (AcSpWrk.ExtractDecimal() > entry.AcceptSpeed)
                                    {
                                        AcSpWrk = 0;
                                    }

                                    entry.AcSpWrk = AcSpWrk.ExtractDecimal();

                                    AverageSpeed(entry);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #46
0
        /// <summary>
        /// Configure our WiHD Provider
        /// </summary>
        /// <param name="configJson">Our params in Json</param>
        /// <returns>Configuration state</returns>
        public async Task <IndexerConfigurationStatus> ApplyConfiguration(JToken configJson)
        {
            // Retrieve config values set by Jackett's user
            ConfigData.LoadValuesFromJson(configJson);

            // Check & Validate Config
            validateConfig();

            // Setting our data for a better emulated browser (maximum security)
            // TODO: Encoded Content not supported by Jackett at this time
            // emulatedBrowserHeaders.Add("Accept-Encoding", "gzip, deflate");

            // If we want to simulate a browser
            if (ConfigData.Browser.Value)
            {
                // Clean headers
                emulatedBrowserHeaders.Clear();

                // Inject headers
                emulatedBrowserHeaders.Add("Accept", ConfigData.HeaderAccept.Value);
                emulatedBrowserHeaders.Add("Accept-Language", ConfigData.HeaderAcceptLang.Value);
                emulatedBrowserHeaders.Add("DNT", Convert.ToInt32(ConfigData.HeaderDNT.Value).ToString());
                emulatedBrowserHeaders.Add("Upgrade-Insecure-Requests", Convert.ToInt32(ConfigData.HeaderUpgradeInsecure.Value).ToString());
                emulatedBrowserHeaders.Add("User-Agent", ConfigData.HeaderUserAgent.Value);
            }


            // Getting login form to retrieve CSRF token
            var myRequest = new Utils.Clients.WebRequest()
            {
                Url = LoginUrl
            };

            // Add our headers to request
            myRequest.Headers = emulatedBrowserHeaders;

            // Building login form data
            var pairs = new Dictionary <string, string> {
                { "username", ConfigData.Username.Value },
                { "password", ConfigData.Password.Value },
                { "keeplogged", "1" },
                { "login", "Connexion" }
            };

            // Do the login
            var request = new Utils.Clients.WebRequest()
            {
                PostData = pairs,
                Referer  = LoginUrl,
                Type     = RequestType.POST,
                Url      = LoginUrl,
                Headers  = emulatedBrowserHeaders
            };

            // Perform loggin
            latencyNow();
            output("\nPerform loggin.. with " + LoginUrl);
            var response = await webclient.GetString(request);

            // Test if we are logged in
            await ConfigureIfOK(response.Cookies, response.Cookies.Contains("session="), () =>
            {
                // Parse error page
                CQ dom         = response.Content;
                string message = dom[".warning"].Text().Split('.').Reverse().Skip(1).First();

                // Try left
                string left = dom[".info"].Text().Trim();

                // Oops, unable to login
                output("-> Login failed: \"" + message + "\" and " + left + " tries left before being banned for 6 hours !", "error");
                throw new ExceptionWithConfigData("Login failed: " + message, configData);
            });

            output("-> Login Success");

            return(IndexerConfigurationStatus.RequiresTesting);
        }
Example #47
0
        private static void SetTextVariables(JArray AssetProperties)
        {
            _displayName            = string.Empty;
            _description            = string.Empty;
            _shortDescription       = string.Empty;
            _cosmeticSource         = string.Empty;
            _cosmeticItemDefinition = string.Empty;
            _itemAction             = string.Empty;
            _maxStackSize           = string.Empty;
            _miniMapIconBrushPath   = string.Empty;
            _userFacingFlagsToken   = null;
            _userHeroFlagsToken     = null;
            _userWeaponFlagsToken   = null;

            JToken name_namespace     = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "DisplayName", "namespace");
            JToken name_key           = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "DisplayName", "key");
            JToken name_source_string = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "DisplayName", "source_string");

            JToken description_namespace     = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "Description", "namespace");
            JToken description_key           = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "Description", "key");
            JToken description_source_string = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "Description", "source_string");

            JToken short_description_namespace     = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "ShortDescription", "namespace");
            JToken short_description_key           = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "ShortDescription", "key");
            JToken short_description_source_string = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "ShortDescription", "source_string");

            JToken cosmetic_item  = AssetsUtility.GetPropertyTagImport <JToken>(AssetProperties, "cosmetic_item");
            JToken max_stack_size = AssetsUtility.GetPropertyTag <JToken>(AssetProperties, "MaxStackSize");
            JToken ammo_data      = AssetsUtility.GetPropertyTagText <JToken>(AssetProperties, "AmmoData", "asset_path_name");

            JArray gTagsArray       = AssetsUtility.GetPropertyTagStruct <JArray>(AssetProperties, "GameplayTags", "gameplay_tags");
            JArray hTagsArray       = AssetsUtility.GetPropertyTagStruct <JArray>(AssetProperties, "RequiredGPTags", "gameplay_tags");
            JArray wTagsArray       = AssetsUtility.GetPropertyTagStruct <JArray>(AssetProperties, "AnalyticTags", "gameplay_tags");
            JArray MiniMapIconArray = AssetsUtility.GetPropertyTagStruct <JArray>(AssetProperties, "MiniMapIconBrush", "properties");

            if (name_namespace != null && name_key != null && name_source_string != null)
            {
                _displayName = AssetTranslations.SearchTranslation(name_namespace.Value <string>(), name_key.Value <string>(), name_source_string.Value <string>());
            }

            if (description_namespace != null && description_key != null && description_source_string != null)
            {
                _description = AssetTranslations.SearchTranslation(description_namespace.Value <string>(), description_key.Value <string>(), description_source_string.Value <string>());
            }

            if (short_description_namespace != null && short_description_key != null && short_description_source_string != null)
            {
                _shortDescription = AssetTranslations.SearchTranslation(short_description_namespace.Value <string>(), short_description_key.Value <string>(), short_description_source_string.Value <string>());
            }
            else if (AssetsLoader.ExportType == "AthenaItemWrapDefinition")
            {
                _shortDescription = AssetTranslations.SearchTranslation("Fort.Cosmetics", "ItemWrapShortDescription", "Wrap");
            }

            if (cosmetic_item != null)
            {
                _cosmeticItemDefinition = cosmetic_item.Value <string>();
            }
            if (max_stack_size != null)
            {
                _maxStackSize = "Max Stack Size: " + max_stack_size.Value <string>();
            }
            if (ammo_data != null && ammo_data.Value <string>().Contains("Ammo"))
            {
                string path = FoldersUtility.FixFortnitePath(ammo_data.Value <string>());
                IconAmmoData.DrawIconAmmoData(path);

                JArray weapon_stat_handle = AssetsUtility.GetPropertyTagStruct <JArray>(AssetProperties, "WeaponStatHandle", "properties");
                if (weapon_stat_handle != null)
                {
                    JToken stats_file = AssetsUtility.GetPropertyTagImport <JToken>(weapon_stat_handle, "DataTable");
                    JToken row_name   = AssetsUtility.GetPropertyTag <JToken>(weapon_stat_handle, "RowName");
                    if (stats_file != null && row_name != null)
                    {
                        WeaponStats.DrawWeaponStats(stats_file.Value <string>(), row_name.Value <string>());
                    }
                }
            }

            if (gTagsArray != null)
            {
                JToken cSetToken = gTagsArray.Children <JToken>().FirstOrDefault(x => x.ToString().StartsWith("Cosmetics.Set."));
                if (cSetToken != null)
                {
                    string cosmeticSet = CosmeticSet.GetCosmeticSet(cSetToken.Value <string>());
                    if (!string.IsNullOrEmpty(cosmeticSet))
                    {
                        _description += cosmeticSet;
                    }
                }

                JToken cFilterToken = gTagsArray.Children <JToken>().FirstOrDefault(x => x.ToString().StartsWith("Cosmetics.Filter.Season."));
                if (cFilterToken != null)
                {
                    string cosmeticFilter = CosmeticSeason.GetCosmeticSeason(cFilterToken.Value <string>().Substring("Cosmetics.Filter.Season.".Length));
                    if (!string.IsNullOrEmpty(cosmeticFilter))
                    {
                        _description += cosmeticFilter;
                    }
                }

                JToken cSourceToken = gTagsArray.Children <JToken>().FirstOrDefault(x => x.ToString().StartsWith("Cosmetics.Source."));
                if (cSourceToken != null)
                {
                    _cosmeticSource = cSourceToken.Value <string>().Substring("Cosmetics.Source.".Length);
                }

                JToken cActionToken = gTagsArray.Children <JToken>().FirstOrDefault(x => x.ToString().StartsWith("Athena.ItemAction."));
                if (cActionToken != null)
                {
                    _itemAction = cActionToken.Value <string>().Substring("Athena.ItemAction.".Length);
                }

                _userFacingFlagsToken = gTagsArray.Children <JToken>().Where(x => x.ToString().StartsWith("Cosmetics.UserFacingFlags."));
            }

            if (hTagsArray != null)
            {
                _userHeroFlagsToken = hTagsArray.Children <JToken>().Where(x => x.ToString().StartsWith("Unlocks.Class."));
            }

            if (wTagsArray != null)
            {
                _userWeaponFlagsToken = wTagsArray.Children <JToken>().Where(x => x.ToString().StartsWith("Weapon.Ranged.", StringComparison.InvariantCultureIgnoreCase));
            }
            else if (MiniMapIconArray != null)
            {
                JToken resourceObjectToken = AssetsUtility.GetPropertyTagOuterImport <JToken>(MiniMapIconArray, "ResourceObject");
                if (resourceObjectToken != null)
                {
                    _miniMapIconBrushPath = FoldersUtility.FixFortnitePath(resourceObjectToken.Value <string>());
                }
            }
        }
Example #48
0
 public static string getStringValueOfObjectFromJToken(JToken jToken, string propertyName)
 {
     return(getStringValueOfObjectFromJToken(jToken, propertyName, false));
 }
Example #49
0
 void OnMessage(int deviceId, JToken message)
 {
     Debug.Log("received message from device " + deviceId + ". content: " + message);
 }
Example #50
0
		public UserEmailContextField(JToken node) : base(node)
		{
		}
Example #51
0
        private static ZumoTest CreatePushTest(string wnsMethod, string nhNotificationType, JToken payload, XElement expectedResult, bool templatePush = false)
        {
            string testName      = "Test for " + wnsMethod + ": ";
            string payloadString = payload.ToString(Formatting.None);

            testName += payloadString.Length < 15 ? payloadString : (payloadString.Substring(0, 15) + "...");
            return(new ZumoTest(testName, async delegate(ZumoTest test)
            {
                test.AddLog("Test for method {0}, with payload {1}", wnsMethod, payload);
                var client = ZumoTestGlobals.Instance.Client;
                var table = client.GetTable(ZumoTestGlobals.PushTestTableName);

                // Workaround for multiple registration bug
                ZumoPushTests.pushesReceived.Clear();

                PushWatcher watcher = new PushWatcher();
                var item = new JObject();
                item.Add("method", wnsMethod);
                item.Add("channelUri", pushChannelUri);
                item.Add("payload", payload);
                item.Add("xmlPayload", expectedResult.ToString());
                item.Add("templateNotification", ZumoPushTestGlobals.TemplateNotification);
                if (ZumoTestGlobals.Instance.IsNHPushEnabled)
                {
                    item.Add("usingNH", true);
                    item.Add("nhNotificationType", nhNotificationType);
                }
                var pushResult = await table.InsertAsync(item);
                test.AddLog("Push result: {0}", pushResult);
                var notificationResult = await watcher.WaitForPush(TimeSpan.FromSeconds(10));
                if (notificationResult == null)
                {
                    test.AddLog("Error, push not received on the timeout allowed");
                    return false;
                }
                else
                {
                    test.AddLog("Push notification received:");
                    XElement receivedPushInfo = null;
                    switch (notificationResult.NotificationType)
                    {
                    case PushNotificationType.Raw:
                        if (nhNotificationType == "template")
                        {
                            receivedPushInfo = XElement.Parse(notificationResult.RawNotification.Content);
                        }
                        else
                        {
                            receivedPushInfo = new XElement("raw", new XText(notificationResult.RawNotification.Content));
                        }
                        break;

                    case PushNotificationType.Toast:
                        receivedPushInfo = XElement.Parse(notificationResult.ToastNotification.Content.GetXml());
                        break;

                    case PushNotificationType.Badge:
                        receivedPushInfo = XElement.Parse(notificationResult.BadgeNotification.Content.GetXml());
                        break;

                    case PushNotificationType.Tile:
                        receivedPushInfo = XElement.Parse(notificationResult.TileNotification.Content.GetXml());
                        break;
                    }

                    test.AddLog("  {0}: {1}", notificationResult.NotificationType, receivedPushInfo);

                    bool passed;
                    if (expectedResult.ToString(SaveOptions.DisableFormatting) == receivedPushInfo.ToString(SaveOptions.DisableFormatting))
                    {
                        test.AddLog("Received notification is the expected one.");
                        passed = true;
                    }
                    else
                    {
                        test.AddLog("Received notification is not the expected one. Expected:");
                        test.AddLog(expectedResult.ToString());
                        test.AddLog("Actual:");
                        test.AddLog(receivedPushInfo.ToString());
                        passed = false;
                    }

                    await Task.Delay(5000); // leave some time between pushes
                    return passed;
                }
            }, templatePush ? ZumoTestGlobals.RuntimeFeatureNames.NH_PUSH_ENABLED : ZumoTestGlobals.RuntimeFeatureNames.STRING_ID_TABLES));
        }
        private static bool DeepEquals(JToken token1, JToken token2, bool ignoreArrayOrder, bool throwOnMismatch)
        {
            if (token1.Type != token2.Type)
            {
                if (throwOnMismatch)
                {
                    throw new DeepEqualityFailure(token1, token2);
                }
                return(false);
            }
            switch (token1.Type)
            {
            case JTokenType.Object:
                var o1 = token1 as JObject;
                var o2 = token2 as JObject;
                foreach (var p in o1.Properties())
                {
                    if (o2[p.Name] == null)
                    {
                        if (throwOnMismatch)
                        {
                            throw new DeepEqualityFailure(token1, token2);
                        }
                        return(false);
                    }
                    if (!DeepEquals(o1[p.Name], o2[p.Name], ignoreArrayOrder, throwOnMismatch))
                    {
                        if (throwOnMismatch)
                        {
                            throw new DeepEqualityFailure(o1[p.Name], o2[p.Name]);
                        }
                        return(false);
                    }
                }
                if (o2.Properties().Any(p2 => o1.Property(p2.Name) == null))
                {
                    if (throwOnMismatch)
                    {
                        throw new DeepEqualityFailure(token1, token2);
                    }
                    return(false);
                }
                return(true);

            case JTokenType.Array:
                var a1 = token1 as JArray;
                var a2 = token2 as JArray;
                if (a1.Count != a2.Count)
                {
                    if (throwOnMismatch)
                    {
                        throw new DeepEqualityFailure(token1, token2);
                    }
                    return(false);
                }

                if (!ignoreArrayOrder)
                {
                    for (int i = 0; i < a1.Count; i++)
                    {
                        if (!DeepEquals(a1[i], a2[i], ignoreArrayOrder, throwOnMismatch))
                        {
                            if (throwOnMismatch)
                            {
                                throw new DeepEqualityFailure(token1, token2);
                            }
                            return(false);
                        }
                    }
                    return(true);
                }
                var unmatchedItems = (token2 as JArray).ToList();
                foreach (var item1 in a1)
                {
                    if (unmatchedItems.Count == 0)
                    {
                        if (throwOnMismatch)
                        {
                            throw new DeepEqualityFailure(token1, token2);
                        }
                        return(false);
                    }
                    var match = unmatchedItems.FindIndex(x => DeepEquals(item1, x, ignoreArrayOrder, false));
                    if (match >= 0)
                    {
                        unmatchedItems.RemoveAt(match);
                    }
                    else
                    {
                        if (throwOnMismatch)
                        {
                            throw new DeepEqualityFailure(token1, token2);
                        }
                        return(false);
                    }
                }
                return(unmatchedItems.Count == 0);

            default:
                return(JToken.DeepEquals(token1, token2));
            }
        }
            public override object ConvertDbToEditor(Property property, PropertyType propertyType, IDataTypeService dataTypeService)
            {
                if (property.Value == null || string.IsNullOrWhiteSpace(property.Value.ToString()))
                {
                    return(string.Empty);
                }

                var value = JsonConvert.DeserializeObject <List <object> >(property.Value.ToString());

                if (value == null)
                {
                    return(string.Empty);
                }

                var contentType = NestedContentHelper.GetContentTypeFromPreValue(propertyType.DataTypeDefinitionId);

                if (contentType == null)
                {
                    return(string.Empty);
                }

                // Process value
                for (var i = 0; i < value.Count; i++)
                {
                    var o             = value[i];
                    var propValues    = ((JObject)o);
                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.PropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType == null)
                        {
                            if (propKey != "name")
                            {
                                // Property missing so just delete the value
                                propValues[propKey] = null;
                            }
                        }
                        else
                        {
                            // Create a fake property using the property abd stored value
                            var prop = new Property(propType, propValues[propKey] == null ? null : propValues[propKey].ToString());

                            // Lookup the property editor
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                            // Get the editor to do it's conversion
                            var newValue = propEditor.ValueEditor.ConvertDbToEditor(prop, propType,
                                                                                    ApplicationContext.Current.Services.DataTypeService);

                            // Store the value back
                            propValues[propKey] = (newValue == null) ? null : JToken.FromObject(newValue);
                        }
                    }
                }

                // Update the value on the property
                property.Value = JsonConvert.SerializeObject(value);

                // Pass the call down
                return(base.ConvertDbToEditor(property, propertyType, dataTypeService));
            }
 public DeepEqualityFailure(JToken expected, JToken actual) : base(
         $"DeepEquality failed at {expected.Path}.\nExpected: {expected}\nActual: {actual}")
 {
 }
        private bool MatchTokens(JToken leftResult, JToken rightResult)
        {
            var leftValue  = leftResult as JValue;
            var rightValue = rightResult as JValue;

            if (leftValue != null && rightValue != null)
            {
                switch (Operator)
                {
                case QueryOperator.Equals:
                    if (EqualsWithStringCoercion(leftValue, rightValue))
                    {
                        return(true);
                    }
                    break;

                case QueryOperator.NotEquals:
                    if (!EqualsWithStringCoercion(leftValue, rightValue))
                    {
                        return(true);
                    }
                    break;

                case QueryOperator.GreaterThan:
                    if (leftValue.CompareTo(rightValue) > 0)
                    {
                        return(true);
                    }
                    break;

                case QueryOperator.GreaterThanOrEquals:
                    if (leftValue.CompareTo(rightValue) >= 0)
                    {
                        return(true);
                    }
                    break;

                case QueryOperator.LessThan:
                    if (leftValue.CompareTo(rightValue) < 0)
                    {
                        return(true);
                    }
                    break;

                case QueryOperator.LessThanOrEquals:
                    if (leftValue.CompareTo(rightValue) <= 0)
                    {
                        return(true);
                    }
                    break;

                case QueryOperator.Exists:
                    return(true);
                }
            }
            else
            {
                switch (Operator)
                {
                case QueryOperator.Exists:
                // you can only specify primitive types in a comparison
                // notequals will always be true
                case QueryOperator.NotEquals:
                    return(true);
                }
            }

            return(false);
        }
            public override object ConvertEditorToDb(ContentPropertyData editorValue, object currentValue)
            {
                if (editorValue.Value == null || string.IsNullOrWhiteSpace(editorValue.Value.ToString()))
                {
                    return(null);
                }

                var value = JsonConvert.DeserializeObject <List <object> >(editorValue.Value.ToString());

                if (value == null)
                {
                    return(string.Empty);
                }

                var contentType = NestedContentHelper.GetContentTypeFromPreValue(editorValue.PreValues);

                if (contentType == null)
                {
                    return(string.Empty);
                }

                // Process value
                for (var i = 0; i < value.Count; i++)
                {
                    var o             = value[i];
                    var propValues    = ((JObject)o);
                    var propValueKeys = propValues.Properties().Select(x => x.Name).ToArray();

                    foreach (var propKey in propValueKeys)
                    {
                        var propType = contentType.PropertyTypes.FirstOrDefault(x => x.Alias == propKey);
                        if (propType == null)
                        {
                            if (propKey != "name")
                            {
                                // Property missing so just delete the value
                                propValues[propKey] = null;
                            }
                        }
                        else
                        {
                            // Fetch the property types prevalue
                            var propPreValues = Services.DataTypeService.GetPreValuesCollectionByDataTypeId(
                                propType.DataTypeDefinitionId);

                            // Lookup the property editor
                            var propEditor = PropertyEditorResolver.Current.GetByAlias(propType.PropertyEditorAlias);

                            // Create a fake content property data object
                            var contentPropData = new ContentPropertyData(
                                propValues[propKey] == null ? null : propValues[propKey].ToString(), propPreValues,
                                new Dictionary <string, object>());

                            // Get the property editor to do it's conversion
                            var newValue = propEditor.ValueEditor.ConvertEditorToDb(contentPropData, propValues[propKey]);

                            // Store the value back
                            propValues[propKey] = (newValue == null) ? null : JToken.FromObject(newValue);
                        }
                    }
                }

                return(JsonConvert.SerializeObject(value));
            }
Example #57
0
        /// <summary>
        /// Create or update a transformation for a stream analytics job.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The resource group name of the stream analytics job.
        /// </param>
        /// <param name='jobName'>
        /// Required. The name of the stream analytics job.
        /// </param>
        /// <param name='parameters'>
        /// Required. The parameters required to create or update a
        /// transformation for the stream analytics job.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response of the transformation create operation.
        /// </returns>
        public async Task <TransformationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string jobName, TransformationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (jobName == null)
            {
                throw new ArgumentNullException("jobName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.Transformation != null)
            {
                if (parameters.Transformation.Name == null)
                {
                    throw new ArgumentNullException("parameters.Transformation.Name");
                }
                if (parameters.Transformation.Properties == null)
                {
                    throw new ArgumentNullException("parameters.Transformation.Properties");
                }
                if (parameters.Transformation.Properties.Query == null)
                {
                    throw new ArgumentNullException("parameters.Transformation.Properties.Query");
                }
            }

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("jobName", jobName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
            }

            // Construct URL
            string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/resourcegroups/" + Uri.EscapeDataString(resourceGroupName) + "/providers/Microsoft.StreamAnalytics/streamingjobs/" + Uri.EscapeDataString(jobName) + "/transformations/" + (parameters.Transformation.Name == null ? "" : Uri.EscapeDataString(parameters.Transformation.Name)) + "?";

            url = url + "api-version=2014-12-01-preview";
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Put;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString());

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                JToken requestDoc     = null;

                JObject transformationCreateOrUpdateParametersValue = new JObject();
                requestDoc = transformationCreateOrUpdateParametersValue;

                if (parameters.Transformation != null)
                {
                    transformationCreateOrUpdateParametersValue["name"] = parameters.Transformation.Name;

                    JObject propertiesValue = new JObject();
                    transformationCreateOrUpdateParametersValue["properties"] = propertiesValue;

                    if (parameters.Transformation.Properties.Etag != null)
                    {
                        propertiesValue["etag"] = parameters.Transformation.Properties.Etag;
                    }

                    if (parameters.Transformation.Properties.StreamingUnits != null)
                    {
                        propertiesValue["streamingUnits"] = parameters.Transformation.Properties.StreamingUnits.Value;
                    }

                    propertiesValue["query"] = parameters.Transformation.Properties.Query;
                }

                requestContent      = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    TransformationCreateOrUpdateResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new TransformationCreateOrUpdateResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            Transformation transformationInstance = new Transformation();
                            result.Transformation = transformationInstance;

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                transformationInstance.Name = nameInstance;
                            }

                            JToken propertiesValue2 = responseDoc["properties"];
                            if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
                            {
                                TransformationProperties propertiesInstance = new TransformationProperties();
                                transformationInstance.Properties = propertiesInstance;

                                JToken etagValue = propertiesValue2["etag"];
                                if (etagValue != null && etagValue.Type != JTokenType.Null)
                                {
                                    string etagInstance = ((string)etagValue);
                                    propertiesInstance.Etag = etagInstance;
                                }

                                JToken streamingUnitsValue = propertiesValue2["streamingUnits"];
                                if (streamingUnitsValue != null && streamingUnitsValue.Type != JTokenType.Null)
                                {
                                    int streamingUnitsInstance = ((int)streamingUnitsValue);
                                    propertiesInstance.StreamingUnits = streamingUnitsInstance;
                                }

                                JToken queryValue = propertiesValue2["query"];
                                if (queryValue != null && queryValue.Type != JTokenType.Null)
                                {
                                    string queryInstance = ((string)queryValue);
                                    propertiesInstance.Query = queryInstance;
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("Date"))
                    {
                        result.Date = DateTime.Parse(httpResponse.Headers.GetValues("Date").FirstOrDefault(), CultureInfo.InvariantCulture);
                    }
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
 public abstract bool IsMatch(JToken root, JToken t);
Example #59
0
 /// <summary>
 /// Initializes an instance of a browser element.
 /// </summary>
 /// <param name="element"> The browser element this is for. </param>
 /// <param name="browser"> The browser this element is associated with. </param>
 /// <param name="collection"> The collection this element is associated with. </param>
 public OptionGroup(JToken element, Browser browser, ElementCollection collection)
     : base(element, browser, collection)
 {
 }
Example #60
0
        void ParseModelValue(JToken property, MixAttributeSetValues.NavigationViewModel item)
        {
            switch (item.DataType)
            {
            case MixEnums.MixDataType.DateTime:
                item.DateTimeValue = property.Value <DateTime?>();
                break;

            case MixEnums.MixDataType.Date:
                item.DateTimeValue = property.Value <DateTime?>();
                break;

            case MixEnums.MixDataType.Time:
                item.DateTimeValue = property.Value <DateTime?>();
                break;

            case MixEnums.MixDataType.Double:
                item.DoubleValue = property.Value <double?>();
                break;

            case MixEnums.MixDataType.Boolean:
                item.BooleanValue = property.Value <bool?>();
                break;

            case MixEnums.MixDataType.Number:
                item.IntegerValue = property.Value <int?>();
                break;

            case MixEnums.MixDataType.Reference:
                //string url = $"/api/v1/odata/en-us/related-attribute-set-data/mobile/parent/set/{Id}/{item.Field.ReferenceId}";

                //foreach (var nav in item.DataNavs)
                //{
                //    arr.Add(nav.Data.Data);
                //}
                //return (new JProperty(item.AttributeFieldName, url));
                break;

            case MixEnums.MixDataType.Custom:
            case MixEnums.MixDataType.Duration:
            case MixEnums.MixDataType.PhoneNumber:
            case MixEnums.MixDataType.Text:
            case MixEnums.MixDataType.Html:
            case MixEnums.MixDataType.MultilineText:
            case MixEnums.MixDataType.EmailAddress:
            case MixEnums.MixDataType.Password:
            case MixEnums.MixDataType.Url:
            case MixEnums.MixDataType.ImageUrl:
            case MixEnums.MixDataType.CreditCard:
            case MixEnums.MixDataType.PostalCode:
            case MixEnums.MixDataType.Upload:
            case MixEnums.MixDataType.Color:
            case MixEnums.MixDataType.Icon:
            case MixEnums.MixDataType.VideoYoutube:
            case MixEnums.MixDataType.TuiEditor:
            default:
                item.StringValue = property.Value <string>();
                break;
            }
            item.StringValue = property.Value <string>();
        }