/// <summary>
        /// Gets the user information synchronous.
        /// this is triggered when a user makes a request who does not have an account already.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="config">The configuration.</param>
        /// <returns>The user object with information retrieved from the identity server</returns>
        public static User GetUserInformation(this HttpContext actionContext, Config config)
        {
            string bearerToken = actionContext.Request.Headers.GetCommaSeparatedValues("Authorization").FirstOrDefault();

            if (string.IsNullOrEmpty(bearerToken))
            {
                return(null);
            }
            // Not sure maybe has to be retrieved from the originating identity server aka from the token iss.
            RestClient  client  = new RestClient(config.IdentityServer.IdentityUrl + "/connect/userinfo");
            RestRequest request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", bearerToken);
            IRestResponse response     = client.Execute(request);
            JObject       jsonResponse = JsonConvert.DeserializeObject <JObject>(response.Content);

            if (jsonResponse?.ContainsKey("name") != true ||
                jsonResponse?.ContainsKey("email") != true ||
                jsonResponse?.ContainsKey("sub") != true)
            {
                return(null);
            }
            User newUser = new User()
            {
                Name       = (string)jsonResponse["name"],
                Email      = (string)jsonResponse["email"],
                IdentityId = (string)jsonResponse["sub"]
            };

            return(newUser);
        }
Example #2
0
        /// <summary>
        ///     Gets the user information synchronous.
        ///     this is triggered when a user makes a request who does not have an account already.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        /// <param name="config">The configuration.</param>
        /// <returns>The user object with information retrieved from the identity server</returns>
        public static UserCreateInternalResource GetUserInformation(this HttpContext actionContext, Config config)
        {
            string bearerToken = actionContext.Request.Headers.GetCommaSeparatedValues("Authorization")
                                 .FirstOrDefault();
            string providerId = "";

            if (bearerToken != null)
            {
                string token = bearerToken.Replace("Bearer ", "");
                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                if (handler.ReadToken(token) is JwtSecurityToken tokens)
                {
                    providerId = tokens.Claims.FirstOrDefault(claim => claim.Type == "idp")
                                 ?.Value;
                }
            }

            if (string.IsNullOrEmpty(bearerToken))
            {
                return(null);
            }

            // Not sure maybe has to be retrieved from the originating identity server aka from the token iss.
            RestClient  client  = new RestClient(config.IdentityServer.IdentityUrl + "/connect/userinfo");
            RestRequest request = new RestRequest(Method.POST);

            request.AddHeader("Authorization", bearerToken);
            IRestResponse response     = client.Execute(request);
            JObject       jsonResponse = JsonConvert.DeserializeObject <JObject>(response.Content);

            if (jsonResponse?.ContainsKey("name") != true ||
                jsonResponse?.ContainsKey("email") != true ||
                jsonResponse?.ContainsKey("sub") != true)
            {
                return(null);
            }

            UserCreateInternalResource newUser = new UserCreateInternalResource
            {
                Name                  = (string)jsonResponse["name"],
                Email                 = (string)jsonResponse["email"],
                IdentityId            = (string)jsonResponse["sub"],
                IdentityInstitutionId = providerId
            };

            return(newUser);
        }
        public bool checkout([Microsoft.AspNetCore.Mvc.FromBody] JObject data)
        {
            string products          = data["products"].ToString();
            string user_id           = data["user_id"].ToString();
            bool   use_discount      = data["use_discount"].ToObject <bool>();
            string sign              = data["sign"].ToString();
            string voucher_id_string = "";

            if (data.ContainsKey("voucher_id"))
            {
                voucher_id_string = data["voucher_id"].ToString();
                Logger.LogInfo(voucher_id_string, "Root");
                bool valid = Voucher.isVoucherAvailable(voucher_id_string);
                if (!valid)
                {
                    HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    message.Content = new StringContent("Invalid Coupon");
                    throw new HttpResponseException(message);
                }
            }

            List <Product> products_list = new List <Product>();
            string         id_string     = "";
            float          final_price   = 0.0f;
            JArray         prods         = JArray.Parse(products);

            for (int i = 0; i < prods.Count; ++i)
            {
                string product_id = prods.ElementAt(i).ToString();
                id_string += product_id;
                Product product = Product.GetProduct(product_id);
                if (product == null)
                {
                    HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NotFound);
                    message.Content = new StringContent("Invalid Product ID");
                    throw new HttpResponseException(message);
                }
                float price = product.GetPriceEuros() + product.GetPriceCents() / 100.0f;
                final_price += price;
                products_list.Add(product);
            }

            string user_key = Client.GetUserPublicKey(user_id);

            if (user_key == null)
            {
                HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.NotFound);
                message.Content = new StringContent("Invalid User ID");
                throw new HttpResponseException(message);
            }

            /*
             * RSAEncrypter encrypter = RSAEncrypter.GetRSAEncrypter();
             * if (!encrypter.Verify(id_string, sign, user_key))
             * {
             *  HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Unauthorized);
             *  message.Content = new StringContent("Invalid Content Signature");
             *  throw new HttpResponseException(message);
             * }*/

            // figure out if voucher should be generated
            bool generateVoucher    = false;
            int  vouchersToGenerate = 0;

            KeyValuePair <int, int> spent = Client.GetTotalAmmountSpent(user_id);
            float current_ammount_spent   = (float)spent.Key + spent.Value / 100.0f;
            float hundredsSpent           = MathF.Truncate(current_ammount_spent / 100.0f);
            float totalAmmountSpent       = current_ammount_spent + final_price;
            float newHundredsSpent        = MathF.Truncate(totalAmmountSpent / 100.0f);

            if (newHundredsSpent > hundredsSpent)
            {
                generateVoucher    = true;
                vouchersToGenerate = (int)(newHundredsSpent - hundredsSpent);
            }


            float account_delta = 0;

            KeyValuePair <int, int> accumulated = Client.GetAccumulatedDiscount(user_id);
            float totalAccumulated = accumulated.Key + accumulated.Value / 100.0f;

            if (use_discount)
            {
                if (totalAccumulated >= final_price)
                {
                    account_delta = totalAccumulated - final_price;
                }
                else
                {
                    account_delta = -totalAccumulated;
                }
            }

            if (voucher_id_string != "")
            {
                Voucher.Use(voucher_id_string);
                account_delta += 0.15f * final_price;
            }

            // generate transaction
            if (voucher_id_string != "")
            {
                Transaction.RegisterTransaction(user_id, voucher_id_string, use_discount, products_list);
            }
            else
            {
                Transaction.RegisterTransaction(user_id, "NULL", use_discount, products_list);
            }

            // update current spent
            int spent_euros = (int)MathF.Truncate(totalAmmountSpent);
            int spent_cents = (int)(totalAmmountSpent - spent_euros);

            Client.UpdateTotalSpent(user_id, spent_euros, spent_cents);

            // update ammount in account
            totalAccumulated += account_delta;
            int accumulated_euros = (int)MathF.Truncate(totalAccumulated);
            int accumulated_cents = (int)(totalAccumulated - accumulated_euros);

            Client.UpdateTotalAccumulated(user_id, accumulated_euros, accumulated_cents);

            if (generateVoucher)
            {
                // add voucher to user account
                for (int i = 0; i < vouchersToGenerate; ++i)
                {
                    Voucher.CreateVoucher(user_id);
                }
            }

            return(true);
        }
Example #4
0
        protected override TypeReference InferType(IReferenceMap referenceMap, object value)
        {
            value = value ?? throw new ArgumentNullException(nameof(value));

            if (value is JToken token)
            {
                switch (token.Type)
                {
                case JTokenType.Object:
                    JObject jObject = (JObject)token;
                    if (jObject.ContainsKey("$jsii.date"))
                    {
                        return(new TypeReference(primitive: PrimitiveType.Date));
                    }
                    if (jObject.ContainsKey("$jsii.enum"))
                    {
                        return(new TypeReference(jObject.ToObject <EnumValue>().FullyQualifiedName));
                    }
                    if (jObject.ContainsKey("$jsii.byref"))
                    {
                        return(new TypeReference(jObject.ToObject <ByRefValue>().FullyQualifiedName));
                    }

                    // At this point, we can't distinguish between a PrimitiveType.Json and a CollectionKind.Map,
                    // so we default to CollectionKind.Map.
                    return(new TypeReference(
                               collection: new CollectionTypeReference(
                                   kind: CollectionKind.Map,
                                   elementType: new TypeReference(primitive: PrimitiveType.Any)
                                   )
                               ));

                case JTokenType.Array:
                    return(new TypeReference
                           (
                               collection: new CollectionTypeReference
                               (
                                   CollectionKind.Array,
                                   new TypeReference(primitive: PrimitiveType.Any)
                               )
                           ));

                case JTokenType.Boolean:
                    return(new TypeReference(primitive: PrimitiveType.Boolean));

                case JTokenType.String:
                    return(new TypeReference(primitive: PrimitiveType.String));

                case JTokenType.Float:
                case JTokenType.Integer:
                    return(new TypeReference(primitive: PrimitiveType.Number));

                default:
                    throw new ArgumentException($"Value has unexpected token type {token.Type}", nameof(value));
                }
            }

            System.Type type = value.GetType();

            if (type.IsAssignableFrom(typeof(string)))
            {
                return(new TypeReference(primitive: PrimitiveType.String));
            }

            if (type.IsAssignableFrom(typeof(bool)))
            {
                return(new TypeReference(primitive: PrimitiveType.Boolean));
            }

            if (IsNumeric(type))
            {
                return(new TypeReference(primitive: PrimitiveType.Number));
            }

            throw new ArgumentException($"Value has unexpected type {type.Name}", nameof(value));
        }
Example #5
0
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static JToken Flatten(JToken input, JToken context, JsonLdOptions opts)
        {
            // 2-6) NOTE: these are all the same steps as in expand
            JArray expanded = Expand(input, opts);

            // 7)
            if (context is JObject && ((IDictionary <string, JToken>)context).ContainsKey(
                    "@context"))
            {
                context = context["@context"];
            }
            // 8) NOTE: blank node generation variables are members of JsonLdApi
            // 9) NOTE: the next block is the Flattening Algorithm described in
            // http://json-ld.org/spec/latest/json-ld-api/#flattening-algorithm
            // 1)
            JObject nodeMap = new JObject();

            nodeMap["@default"] = new JObject();
            // 2)
            new JsonLdApi(opts).GenerateNodeMap(expanded, nodeMap);
            // 3)
            JObject defaultGraph = (JObject)JsonLD.Collections.Remove
                                       (nodeMap, "@default");

            // 4)
            foreach (string graphName in ((IDictionary <string, JToken>)nodeMap).Keys)
            {
                JObject graph = (JObject)nodeMap[graphName];
                // 4.1+4.2)
                JObject entry;
                if (!defaultGraph.ContainsKey(graphName))
                {
                    entry                   = new JObject();
                    entry["@id"]            = graphName;
                    defaultGraph[graphName] = entry;
                }
                else
                {
                    entry = (JObject)defaultGraph[graphName];
                }
                // 4.3)
                // TODO: SPEC doesn't specify that this should only be added if it
                // doesn't exists
                if (!entry.ContainsKey("@graph"))
                {
                    entry["@graph"] = new JArray();
                }
                JArray keys = new JArray(((IDictionary <string, JToken>)graph).Keys);
                keys.SortInPlace();
                foreach (string id in keys)
                {
                    JObject node = (JObject)graph[id];
                    if (!(node.ContainsKey("@id") && node.Count == 1))
                    {
                        ((JArray)entry["@graph"]).Add(node);
                    }
                }
            }
            // 5)
            JArray flattened = new JArray();
            // 6)
            JArray keys_1 = new JArray(((IDictionary <string, JToken>)defaultGraph).Keys);

            keys_1.SortInPlace();
            foreach (string id_1 in keys_1)
            {
                JObject node = (JObject)defaultGraph[id_1
                               ];
                if (!(node.ContainsKey("@id") && node.Count == 1))
                {
                    flattened.Add(node);
                }
            }
            // 8)
            if (!context.IsNull() && !flattened.IsEmpty())
            {
                Context activeCtx = new Context(opts);
                activeCtx = activeCtx.Parse(context);
                // TODO: only instantiate one jsonldapi
                JToken compacted = new JsonLdApi(opts).Compact(activeCtx, null, flattened, opts.GetCompactArrays
                                                                   ());
                if (!(compacted is JArray))
                {
                    JArray tmp = new JArray();
                    tmp.Add(compacted);
                    compacted = tmp;
                }
                string  alias = activeCtx.CompactIri("@graph");
                JObject rval  = activeCtx.Serialize();
                rval[alias] = compacted;
                return(rval);
            }
            return(flattened);
        }
Example #6
0
        void OnBookmarkCallback(NativeActivityContext context, Bookmark bookmark, object obj)
        {
            // context.RemoveBookmark(bookmark.Name);
            bool waitforcompleted = WaitForCompleted.Get(context);

            if (!waitforcompleted)
            {
                return;
            }
            var     _msg    = JObject.Parse(obj.ToString());
            JObject payload = _msg; // Backward compatible with older version of openflow

            if (_msg.ContainsKey("payload"))
            {
                payload = _msg.Value <JObject>("payload");
            }
            var state = _msg["state"].ToString();

            if (!string.IsNullOrEmpty(state))
            {
                if (state == "idle")
                {
                    Log.Output("Workflow out node set to idle, so also going idle again.");
                    context.CreateBookmark(bookmark.Name, new BookmarkCallback(OnBookmarkCallback));
                    return;
                }
                else if (state == "failed")
                {
                    var message = "Invoke OpenFlow Workflow failed";
                    if (_msg.ContainsKey("error"))
                    {
                        message = _msg["error"].ToString();
                    }
                    if (_msg.ContainsKey("_error"))
                    {
                        message = _msg["_error"].ToString();
                    }
                    if (payload.ContainsKey("error"))
                    {
                        message = payload["error"].ToString();
                    }
                    if (payload.ContainsKey("_error"))
                    {
                        message = payload["_error"].ToString();
                    }
                    if (string.IsNullOrEmpty(message))
                    {
                        message = "Invoke OpenFlow Workflow failed";
                    }
                    throw new Exception(message);
                }
            }

            List <string> keys = payload.Properties().Select(p => p.Name).ToList();

            foreach (var key in keys)
            {
                var myVar = context.DataContext.GetProperties().Find(key, true);
                if (myVar != null)
                {
                    if (myVar.PropertyType.Name == "JArray")
                    {
                        var json = payload[key].ToString();
                        var jobj = JArray.Parse(json);
                        myVar.SetValue(context.DataContext, jobj);
                    }
                    else if (myVar.PropertyType.Name == "JObject")
                    {
                        var json = payload[key].ToString();
                        var jobj = JObject.Parse(json);
                        myVar.SetValue(context.DataContext, jobj);
                    }
                    else
                    {
                        myVar.SetValue(context.DataContext, payload[key].ToString());
                    }
                    //var myValue = myVar.GetValue(context.DataContext);
                }
                else
                {
                    Log.Debug("Recived property " + key + " but no variable exists to save the value in " + payload[key]);
                }
                //action.setvariable(key, payload[key]);
            }
        }
        private void UpdateLootLog_Click(object sender, RoutedEventArgs e)
        {
            TextReader     lootLogReader  = null;
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title = "Old Loot Log";
            if (openFileDialog.ShowDialog() == true)
            {
                lootLogReader = new StreamReader(openFileDialog.FileName);
            }

            List <string[]> newResults = new List <string[]>();

            var lootlogParser = new CsvParser(lootLogReader, CultureInfo.InvariantCulture);

            string[] record = null;
            while ((record = lootlogParser.Read()) != null)
            {
                if (record.Length == 9)
                {
                    MessageBox.Show("Missing ItemRefID -- Loot Log too old");
                    return;
                }

                int itemId = int.Parse(record[0]);

                JObject newItem  = ItemDB.Instance.FindItem(itemId);
                string  itemName = newItem["UniqueName"].ToString();
                if (newItem.ContainsKey("LocalizedNames") && newItem["LocalizedNames"] != null)
                {
                    JObject localizedNames = (JObject)newItem["LocalizedNames"];
                    if (localizedNames.ContainsKey("EN-US"))
                    {
                        itemName += " - " + localizedNames["EN-US"].ToString();
                    }
                }

                string shortName = newItem["UniqueName"].ToString();
                string quality   = "0";
                if (shortName.Contains("@"))
                {
                    quality = shortName.Split('@')[1];
                }

                // 5,6,7
                record[5] = shortName;
                record[6] = itemName;
                record[7] = quality;

                newResults.Add(record);
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Title = "Save Location";
            if (saveFileDialog.ShowDialog() == true)
            {
                using (FileStream fs = saveFileDialog.OpenFile() as FileStream)
                    using (TextWriter sr = new StreamWriter(fs))
                        using (CsvWriter lootWriter = new CsvWriter(sr, CultureInfo.InvariantCulture))
                        {
                            foreach (string[] item in newResults)
                            {
                                foreach (string itemValue in item)
                                {
                                    lootWriter.WriteField(itemValue);
                                }
                                lootWriter.NextRecord();
                            }
                            //lootWriter.WriteRecords(newResults.AsEnumerable<string[]>());
                        }
            }

            MessageBox.Show("New log written to --> " + saveFileDialog.FileName);
        }
Example #8
0
        public IActionResult Put(int id, [FromBody] JObject value)
        {
            var    successes = 0;
            var    failures  = 0;
            var    banned    = false;
            string site      = null;
            int    score     = 0;

            var  authHeader = HttpContext.Request.Headers.TryGetValue("APIKey", out var values);
            Guid key        = new Guid(values[0]);

            if (!UsageStatisticsService.UsageStatistics.ContainsKey(key))
            {
                UsageStatisticsService.UsageStatistics.Add(key, new UsageStatisticsService.Usage());
            }

            if (value.ContainsKey("successes"))
            {
                int.TryParse(value["successes"].ToString(), out successes);
            }
            if (value.ContainsKey("failures"))
            {
                int.TryParse(value["failures"].ToString(), out failures);
            }
            if (successes > failures)
            {
                score = 1;
            }
            else if (failures > successes)
            {
                score = -1;
            }
            if (value.ContainsKey("banned"))
            {
                banned = value["banned"].ToString().Equals("true", StringComparison.OrdinalIgnoreCase);
            }
            if (value.ContainsKey("site"))
            {
                site = value["site"].ToString();
            }

            var requestSuccesses = successes;
            var requestFailures  = failures;
            var requestBanned    = banned;

            if (site != null)
            {
                using (var conn = new SqlConnection(Configuration.DatabaseConnectionString))
                {
                    bool update = false;
                    conn.Open();
                    var sql     = $"SELECT banned, successes, failures, score FROM proxysitescore WHERE proxyid = {id} and site = '{site}'";
                    var command = new SqlCommand(sql, conn);
                    using (var reader = command.ExecuteReader())
                    {
                        update = reader.Read();
                        if (update)
                        {
                            banned    |= bool.Parse(reader.GetValue(0).ToString());
                            successes += Int32.Parse(reader.GetValue(1).ToString());
                            failures  += Int32.Parse(reader.GetValue(2).ToString());
                            score     += Int32.Parse(reader.GetValue(3).ToString());
                        }
                    }
                    if (update)
                    {
                        sql     = $"UPDATE ProxySiteScore SET banned = {(banned ? 1 : 0)}, successes = {successes}, failures = {failures}, score = {score}   WHERE ProxyID = {id} AND Site = '{site}'";
                        command = new SqlCommand(sql, conn);
                        var insertReader = command.ExecuteScalar();
                    }
                    else
                    {
                        sql     = $"INSERT INTO ProxySiteScore (proxyid, site, banned, successes, failures, score) VALUES ({id}, '{site}', {(banned ? 1 : 0)}, {successes}, {failures}, {score})";
                        command = new SqlCommand(sql, conn);
                        var pssResult = command.ExecuteScalar();
                    }
                }
            }

            using (var conn = new SqlConnection(Configuration.DatabaseConnectionString))
            {
                conn.Open();
                // Update the proxy itself.
                var sql     = "SELECT totalsuccesses, totalfailures, score FROM Proxy where ProxyID = " + id;
                var command = new SqlCommand(sql, conn);
                using (var reader = command.ExecuteReader())
                {
                    reader.Read();
                    successes += Int32.Parse(reader.GetValue(0).ToString());
                    failures  += Int32.Parse(reader.GetValue(1).ToString());
                    if (site != null && score < 0)
                    {
                        score = 0;
                    }                                             // Failures are being attributed to the site here, not the proxy.
                    else if (banned)
                    {
                        score = -1;
                    }                                // If reporting against a proxy as a whole, "ban" isn't really a thing but we can ding the score.
                    score += Int32.Parse(reader.GetValue(2).ToString());
                    if (score > 4)
                    {
                        score = 4;
                    }                             // Max proxy score is 4.
                }
                sql     = $"UPDATE Proxy SET totalsuccesses = {successes}, totalfailures = {failures}, score = {score} WHERE proxyid = {id}";
                command = new SqlCommand(sql, conn);
                var pResult = command.ExecuteScalar();
            }

            // Report usage statistics
            UsageStatisticsService.UsageStatistics[key].SuccessesReported += requestSuccesses;
            if (site != null)
            {
                UsageStatisticsService.UsageStatistics[key].SiteFailuresReported += requestFailures;
                UsageStatisticsService.UsageStatistics[key].BansReported         += requestBanned ? 1 : 0;
            }
            else
            {
                UsageStatisticsService.UsageStatistics[key].ProxyFailuresReported += requestFailures;
            }
            return(NoContent());
        }
Example #9
0
        protected override void ReadEntry(JObject entry)
        {
            entry.AssertNotMissing("id", "name", "group", "tags", "gender", "vehicleType", "runSpeedFactor", "state", "invWidth", "invHeight", "range", "attackSpeed", "knockCount", "splashRadius", "splashAngle", "splashDamage", "stand", "ai", "color1", "color2", "color3", "cp", "life");

            var raceData = new RaceData();

            raceData.Id               = entry.ReadInt("id");
            raceData.Name             = entry.ReadString("name");
            raceData.Group            = entry.ReadString("group");
            raceData.Tags             = entry.ReadString("tags");
            raceData.Gender           = (Gender)entry.ReadByte("gender");
            raceData.VehicleType      = entry.ReadInt("vehicleType");
            raceData.RunSpeedFactor   = entry.ReadFloat("runSpeedFactor");
            raceData.DefaultState     = entry.ReadUInt("state");
            raceData.InventoryWidth   = entry.ReadInt("invWidth");
            raceData.InventoryHeight  = entry.ReadInt("invHeight");
            raceData.AttackSkill      = 23002;        // Combat Mastery, they all use this anyway.
            raceData.AttackMinBase    = entry.ReadInt("attackMinBase");
            raceData.AttackMaxBase    = entry.ReadInt("attackMaxBase");
            raceData.AttackMinBaseMod = entry.ReadInt("attackMinBaseMod");
            raceData.AttackMaxBaseMod = entry.ReadInt("attackMaxBaseMod");
            raceData.InjuryMinBase    = entry.ReadInt("injuryMinBase");
            raceData.InjuryMaxBase    = entry.ReadInt("injuryMaxBase");
            raceData.InjuryMinBaseMod = entry.ReadInt("injuryMinBaseMod");
            raceData.InjuryMaxBaseMod = entry.ReadInt("injuryMaxBaseMod");
            raceData.AttackRange      = entry.ReadInt("range");
            raceData.AttackSpeed      = entry.ReadInt("attackSpeed");
            raceData.KnockCount       = entry.ReadInt("knockCount");
            raceData.CriticalBase     = entry.ReadInt("criticalBase");
            raceData.CriticalBaseMod  = entry.ReadInt("criticalBaseMod");
            raceData.BalanceBase      = entry.ReadInt("balanceBase");
            raceData.BalanceBaseMod   = entry.ReadInt("balanceBaseMod");
            raceData.SplashRadius     = entry.ReadInt("splashRadius");
            raceData.SplashAngle      = entry.ReadInt("splashAngle");
            raceData.SplashDamage     = entry.ReadFloat("splashDamage");
            raceData.Stand            = (RaceStands)entry.ReadInt("stand");
            raceData.AI               = entry.ReadString("ai");

            // Looks
            raceData.Color1 = entry.ReadUInt("color1");
            raceData.Color2 = entry.ReadUInt("color2");
            raceData.Color3 = entry.ReadUInt("color3");

            if (!entry.ContainsAnyKeys("size", "sizeMin", "sizeMax"))
            {
                raceData.SizeMin = raceData.SizeMax = 1;
            }
            else if (entry.ContainsKey("size"))
            {
                raceData.SizeMin = raceData.SizeMax = entry.ReadFloat("size");
            }
            else
            {
                raceData.SizeMin = entry.ReadFloat("sizeMin", 1);
                raceData.SizeMax = entry.ReadFloat("sizeMax", 1);
            }

            if (raceData.SizeMin > raceData.SizeMax)
            {
                raceData.SizeMax = raceData.SizeMin;
            }

            // Face
            Action <string, JObject, List <int> > readArrOrIntCol = (col, obj, list) =>
            {
                if (obj[col] != null)
                {
                    if (obj[col].Type == JTokenType.Integer)
                    {
                        list.Add(obj.ReadInt(col));
                    }
                    else if (obj[col].Type == JTokenType.Array)
                    {
                        list.AddRange(obj[col].Select(id => (int)id));
                    }
                }
            };

            readArrOrIntCol("eyeColor", entry, raceData.Face.EyeColors);
            readArrOrIntCol("eyeType", entry, raceData.Face.EyeTypes);
            readArrOrIntCol("mouthType", entry, raceData.Face.MouthTypes);
            readArrOrIntCol("skinColor", entry, raceData.Face.SkinColors);

            // Stat Info
            raceData.Level = entry.ReadInt("level");
            raceData.Str   = entry.ReadFloat("str");
            raceData.Int   = entry.ReadFloat("int");
            raceData.Dex   = entry.ReadFloat("dex");
            raceData.Will  = entry.ReadFloat("will");
            raceData.Luck  = entry.ReadFloat("luck");

            raceData.CombatPower      = entry.ReadFloat("cp");
            raceData.Life             = entry.ReadFloat("life");
            raceData.Mana             = entry.ReadFloat("mana");
            raceData.Stamina          = entry.ReadFloat("stamina");
            raceData.Defense          = entry.ReadInt("defense");
            raceData.Protection       = (int)entry.ReadFloat("protection");
            raceData.ElementPhysical  = entry.ReadInt("elementPhysical");
            raceData.ElementLightning = entry.ReadInt("elementLightning");
            raceData.ElementFire      = entry.ReadInt("elementFire");
            raceData.ElementIce       = entry.ReadInt("elementIce");
            raceData.Exp     = entry.ReadInt("exp");
            raceData.GoldMin = entry.ReadInt("goldMin");
            raceData.GoldMax = entry.ReadInt("goldMax");

            // Drops
            if (entry.ContainsKeys("drops"))
            {
                foreach (JObject drop in entry["drops"].Where(a => a.Type == JTokenType.Object))
                {
                    drop.AssertNotMissing("itemId", "chance");

                    var dropData = new DropData();
                    dropData.ItemId = drop.ReadInt("itemId");
                    dropData.Chance = drop.ReadFloat("chance");
                    var amount = drop.ReadInt("amount");
                    dropData.AmountMin = drop.ReadInt("minAmount");
                    dropData.AmountMax = drop.ReadInt("maxAmount");
                    dropData.Prefix    = drop.ReadInt("prefix");
                    dropData.Suffix    = drop.ReadInt("suffix");

                    if (amount != 0)
                    {
                        dropData.AmountMin = dropData.AmountMax = amount;
                    }
                    if (dropData.AmountMin > dropData.AmountMax)
                    {
                        dropData.AmountMax = dropData.AmountMin;
                    }

                    if (dropData.Chance > 100)
                    {
                        dropData.Chance = 100;
                    }
                    else if (dropData.Chance < 0)
                    {
                        dropData.Chance = 0;
                    }

                    if (drop.ContainsKey("color1"))
                    {
                        dropData.Color1 = drop.ReadUInt("color1");
                    }
                    if (drop.ContainsKey("color2"))
                    {
                        dropData.Color2 = drop.ReadUInt("color2");
                    }
                    if (drop.ContainsKey("color3"))
                    {
                        dropData.Color3 = drop.ReadUInt("color3");
                    }

                    dropData.Durability = drop.ReadInt("durability", -1);

                    raceData.Drops.Add(dropData);
                }
            }

            // Skills
            if (entry.ContainsKeys("skills"))
            {
                foreach (JObject skill in entry["skills"].Where(a => a.Type == JTokenType.Object))
                {
                    skill.AssertNotMissing("skillId", "rank");

                    var skillData = new RaceSkillData();
                    skillData.SkillId = skill.ReadUShort("skillId");

                    var rank = skill.ReadString("rank");
                    if (rank == "N")
                    {
                        skillData.Rank = 0;
                    }
                    else
                    {
                        skillData.Rank = (byte)(16 - int.Parse(rank, NumberStyles.HexNumber));
                    }

                    raceData.Skills.Add(skillData);
                }
            }

            // Items
            if (entry.ContainsKeys("equip"))
            {
                foreach (JObject item in entry["equip"].Where(a => a.Type == JTokenType.Object))
                {
                    item.AssertNotMissing("itemId", "pocket");

                    var itemData = new RaceItemData();

                    // Item ids
                    if (item["itemId"].Type == JTokenType.Integer)
                    {
                        itemData.ItemIds.Add(item.ReadInt("itemId"));
                    }
                    else if (item["itemId"].Type == JTokenType.Array)
                    {
                        foreach (var id in item["itemId"])
                        {
                            itemData.ItemIds.Add((int)id);
                        }
                    }

                    // Check that we got ids
                    if (itemData.ItemIds.Count == 0)
                    {
                        throw new MandatoryValueException(null, "itemId", item);
                    }

                    // Color 1
                    if (item["color1"] != null)
                    {
                        if (item["color1"].Type == JTokenType.Integer)
                        {
                            itemData.Color1s.Add(item.ReadUInt("color1"));
                        }
                        else if (item["color1"].Type == JTokenType.Array)
                        {
                            foreach (var id in item["color1"])
                            {
                                itemData.Color1s.Add((uint)id);
                            }
                        }
                    }

                    // Color 2
                    if (item["color2"] != null)
                    {
                        if (item["color2"].Type == JTokenType.Integer)
                        {
                            itemData.Color2s.Add(item.ReadUInt("color2"));
                        }
                        else if (item["color2"].Type == JTokenType.Array)
                        {
                            foreach (var id in item["color2"])
                            {
                                itemData.Color2s.Add((uint)id);
                            }
                        }
                    }

                    // Color 3
                    if (item["color3"] != null)
                    {
                        if (item["color3"].Type == JTokenType.Integer)
                        {
                            itemData.Color3s.Add(item.ReadUInt("color3"));
                        }
                        else if (item["color3"].Type == JTokenType.Array)
                        {
                            foreach (var id in item["color3"])
                            {
                                itemData.Color3s.Add((uint)id);
                            }
                        }
                    }

                    // Pocket
                    itemData.Pocket = item.ReadInt("pocket");

                    raceData.Equip.Add(itemData);
                }
            }

            // Speed
            SpeedData actionInfo;

            if ((actionInfo = AuraData.SpeedDb.Find(raceData.Group + "/walk")) != null)
            {
                raceData.WalkingSpeed = actionInfo.Speed;
            }
            else if ((actionInfo = AuraData.SpeedDb.Find(raceData.Group + "/*")) != null)
            {
                raceData.WalkingSpeed = actionInfo.Speed;
            }
            else if ((actionInfo = AuraData.SpeedDb.Find(Regex.Replace(raceData.Group, "/.*$", "") + "/*/walk")) != null)
            {
                raceData.WalkingSpeed = actionInfo.Speed;
            }
            else if ((actionInfo = AuraData.SpeedDb.Find(Regex.Replace(raceData.Group, "/.*$", "") + "/*/*")) != null)
            {
                raceData.WalkingSpeed = actionInfo.Speed;
            }
            else
            {
                raceData.WalkingSpeed = 207.6892f;
            }

            if ((actionInfo = AuraData.SpeedDb.Find(raceData.Group + "/run")) != null)
            {
                raceData.RunningSpeed = actionInfo.Speed;
            }
            else if ((actionInfo = AuraData.SpeedDb.Find(raceData.Group + "/*")) != null)
            {
                raceData.RunningSpeed = actionInfo.Speed;
            }
            else if ((actionInfo = AuraData.SpeedDb.Find(Regex.Replace(raceData.Group, "/.*$", "") + "/*/run")) != null)
            {
                raceData.RunningSpeed = actionInfo.Speed;
            }
            else if ((actionInfo = AuraData.SpeedDb.Find(Regex.Replace(raceData.Group, "/.*$", "") + "/*/*")) != null)
            {
                raceData.RunningSpeed = actionInfo.Speed;
            }
            else
            {
                raceData.RunningSpeed = 373.850647f;
            }

            this.Entries[raceData.Id] = raceData;
        }
Example #10
0
 /// <summary>
 /// 获取Map对象值
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="info"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static T Get <T>(this JObject info, string key)
 {
     if (!info.ContainsKey(key))
     {
         return(default);
Example #11
0
    private async Task <(string lastSetTag, bool multipleTags, bool hasGroup)> ImportTupper(
        JObject tupper, string lastSetTag)
    {
        if (!tupper.ContainsKey("name") || tupper["name"].Type == JTokenType.Null)
        {
            throw new ImportException("Field 'name' cannot be null.");
        }

        var hasGroup     = tupper.ContainsKey("group_id") && tupper["group_id"].Type != JTokenType.Null;
        var multipleTags = false;

        var name = tupper.Value <string>("name");

        var isNewMember = false;

        if (!_existingMemberNames.TryGetValue(name, out var memberId))
        {
            var newMember = await _repo.CreateMember(_system.Id, name, _conn);

            memberId    = newMember.Id;
            isNewMember = true;
            _result.Added++;
        }
        else
        {
            _result.Modified++;
        }

        var patch = new MemberPatch();

        patch.Name = name;
        if (tupper.ContainsKey("avatar_url") && tupper["avatar_url"].Type != JTokenType.Null)
        {
            patch.AvatarUrl = tupper.Value <string>("avatar_url").NullIfEmpty();
        }
        if (tupper.ContainsKey("brackets"))
        {
            var brackets = tupper.Value <JArray>("brackets");
            if (brackets.Count % 2 != 0)
            {
                throw new ImportException($"Field 'brackets' in tupper {name} is invalid.");
            }
            var tags = new List <ProxyTag>();
            for (var i = 0; i < brackets.Count / 2; i++)
            {
                tags.Add(new ProxyTag((string)brackets[i * 2], (string)brackets[i * 2 + 1]));
            }
            patch.ProxyTags = tags.ToArray();
        }

        if (tupper.ContainsKey("posts") && isNewMember)
        {
            patch.MessageCount = tupper.Value <int>("posts");
        }
        if (tupper.ContainsKey("show_brackets"))
        {
            patch.KeepProxy = tupper.Value <bool>("show_brackets");
        }
        if (tupper.ContainsKey("birthday") && tupper["birthday"].Type != JTokenType.Null)
        {
            var parsed = DateTimeFormats.TimestampExportFormat.Parse(tupper.Value <string>("birthday"));
            if (!parsed.Success)
            {
                throw new ImportException($"Field 'birthday' in tupper {name} is invalid.");
            }
            patch.Birthday = LocalDate.FromDateTime(parsed.Value.ToDateTimeUtc());
        }

        if (tupper.ContainsKey("description"))
        {
            patch.Description = tupper.Value <string>("description");
        }
        if (tupper.ContainsKey("nick"))
        {
            patch.DisplayName = tupper.Value <string>("nick");
        }
        if (tupper.ContainsKey("tag") && tupper["tag"].Type != JTokenType.Null)
        {
            var tag = tupper.Value <string>("tag");
            if (tag != lastSetTag)
            {
                lastSetTag   = tag;
                multipleTags = true;
            }

            patch.DisplayName = $"{name} {tag}";
        }

        patch.AssertIsValid();
        if (patch.Errors.Count > 0)
        {
            var err = patch.Errors[0];
            if (err is FieldTooLongError)
            {
                throw new ImportException($"Field {err.Key} in tupper {name} is too long "
                                          + $"({(err as FieldTooLongError).ActualLength} > {(err as FieldTooLongError).MaxLength}).");
            }
            if (err.Text != null)
            {
                throw new ImportException($"tupper {name}: {err.Text}");
            }
            throw new ImportException($"Field {err.Key} in tupper {name} is invalid.");
        }

        _logger.Debug(
            "Importing member with identifier {FileId} to system {System} (is creating new member? {IsCreatingNewMember})",
            name, _system.Id, isNewMember);

        await _repo.UpdateMember(memberId, patch, _conn);

        return(lastSetTag, multipleTags, hasGroup);
    }
Example #12
0
        private void readData(JObject rootObject, string keyString, ref List <ControlData> controlDataList)
        {
            if (rootObject.ContainsKey(keyString) == false)
            {
                return;
            }

            var controlList = rootObject.Value <JArray>(keyString);

            for (int i = 0; i < controlList.Count; i++)
            {
                var controlObject = (JObject)controlList[i];

                if (controlObject.ContainsKey("index") == false ||
                    controlObject.ContainsKey("name") == false)
                {
                    continue;
                }

                int    sensorIndex = controlObject.Value <int>("index");
                string sensorName  = controlObject.Value <string>("name");

                var controlData = new ControlData(sensorIndex, sensorName);

                // FanData
                var fanList = controlObject.Value <JArray>("fan");
                for (int j = 0; j < fanList.Count; j++)
                {
                    var fanObject = (JObject)fanList[j];

                    if (fanObject.ContainsKey("index") == false ||
                        fanObject.ContainsKey("name") == false)
                    {
                        continue;
                    }

                    int    fanIndex   = fanObject.Value <int>("index");
                    string fanName    = fanObject.Value <string>("name");
                    bool   isStep     = (fanObject.ContainsKey("step") == true) ? fanObject.Value <bool>("step") : true;
                    int    hysteresis = (fanObject.ContainsKey("hysteresis") == true) ? fanObject.Value <int>("hysteresis") : 0;
                    int    unit       = (fanObject.ContainsKey("unit") == true) ? fanObject.Value <int>("unit") : 1;

                    var fanData = new FanData(fanIndex, fanName, (FanValueUnit)unit, isStep, hysteresis);

                    // Percent value
                    var valueList = fanObject.Value <JArray>("value");

                    // fan value list
                    if (valueList.Count == fanData.getMaxFanValue())
                    {
                        for (int k = 0; k < valueList.Count; k++)
                        {
                            int value = valueList[k].Value <int>();
                            fanData.ValueList[k] = value;
                        }

                        // add fan data
                        controlData.FanDataList.Add(fanData);
                    }
                }

                // add control data
                controlDataList.Add(controlData);
            }
        }
        private ZCRMAttachment GetZCRMAttachment(JObject attachmentDetails)
        {
            ZCRMAttachment attachment = ZCRMAttachment.GetInstance(parentRecord, Convert.ToInt64(attachmentDetails["id"]));
            string         fileName   = (string)attachmentDetails["File_Name"];

            if (fileName != null)
            {
                attachment.FileName = fileName;
                attachment.FileType = fileName.Substring(fileName.LastIndexOf('.') + 1);
            }
            if (attachmentDetails.ContainsKey("Size"))
            {
                attachment.Size = Convert.ToInt64(attachmentDetails["Size"]);
            }
            if (attachmentDetails.ContainsKey("Created_By") && attachmentDetails["Created_By"].Type != JTokenType.Null)
            {
                JObject  createdByObject = (JObject)attachmentDetails["Created_By"];
                ZCRMUser createdBy       = ZCRMUser.GetInstance(Convert.ToInt64(createdByObject["id"]), (string)createdByObject["name"]);
                attachment.CreatedBy   = createdBy;
                attachment.CreatedTime = CommonUtil.RemoveEscaping((string)JsonConvert.SerializeObject(attachmentDetails["Created_Time"]));

                if (attachmentDetails["Owner"] != null && attachmentDetails["Owner"].Type != JTokenType.Null)
                {
                    JObject  ownerObject = (JObject)attachmentDetails["Owner"];
                    ZCRMUser owner       = ZCRMUser.GetInstance(Convert.ToInt64(ownerObject["id"]), (string)ownerObject["name"]);
                    attachment.Owner = owner;
                }
                else
                {
                    attachment.Owner = createdBy;
                }
            }
            if (attachmentDetails.ContainsKey("Modified_By") && attachmentDetails["Modified_By"].Type != JTokenType.Null)
            {
                JObject  modifiedByObject = (JObject)attachmentDetails["Modified_By"];
                ZCRMUser modifiedBy       = ZCRMUser.GetInstance(Convert.ToInt64(modifiedByObject["id"]), (string)modifiedByObject["name"]);
                attachment.ModifiedBy   = modifiedBy;
                attachment.ModifiedTime = CommonUtil.RemoveEscaping((string)JsonConvert.SerializeObject(attachmentDetails["Modified_Time"]));
            }

            if (attachmentDetails.ContainsKey("$editable"))
            {
                if (attachmentDetails["$editable"] != null)
                {
                    attachment.Editable = Convert.ToBoolean(attachmentDetails["$editable"]);
                }
            }
            if (attachmentDetails.ContainsKey("$file_id"))
            {
                if (attachmentDetails["$file_id"] != null)
                {
                    attachment.FieldId = Convert.ToString(attachmentDetails["$file_id"]);
                }
            }
            if (attachmentDetails.ContainsKey("$type"))
            {
                if (attachmentDetails["$type"] != null)
                {
                    attachment.Type = Convert.ToString(attachmentDetails["$type"]);
                }
            }
            if (attachmentDetails.ContainsKey("$se_module"))
            {
                if (attachmentDetails["$se_module"] != null)
                {
                    attachment.Se_module = Convert.ToString(attachmentDetails["$se_module"]);
                }
            }
            if (attachmentDetails.ContainsKey("$link_url"))
            {
                if (attachmentDetails["$link_url"] != null)
                {
                    attachment.Link_url = Convert.ToString(attachmentDetails["$link_url"]);
                }
            }

            return(attachment);
        }
        private async Task ConfigureVsCodeSettings()
        {
            var vsVm = viewModelResolver.Resolve <VSCodePageViewModel>();

            if (!toInstallProvider.Model.InstallVsCode && !vsVm.Model.AlreadyInstalled)
            {
                return;
            }

            var dataPath = await SetVsCodePortableMode();

            var settingsDir  = Path.Combine(dataPath, "user-data", "User");
            var settingsFile = Path.Combine(settingsDir, "settings.json");

            var homePath = configurationProvider.InstallDirectory;

            var codeFolder = Path.Combine(homePath, configurationProvider.UpgradeConfig.PathFolder);

            try
            {
                Directory.CreateDirectory(codeFolder);
            }
            catch (IOException)
            {
            }

            try
            {
                Directory.CreateDirectory(settingsDir);
            }
            catch (IOException)
            {
            }

            dynamic settingsJson = new JObject();

            if (File.Exists(settingsFile))
            {
                settingsJson = (JObject)JsonConvert.DeserializeObject(await File.ReadAllTextAsync(settingsFile)) !;
            }

            SetIfNotSet("java.home", Path.Combine(homePath, "jdk"), settingsJson);
            SetIfNotSet("extensions.autoUpdate", false, settingsJson);
            SetIfNotSet("extensions.autoCheckUpdates", false, settingsJson);
            SetIfNotSet("extensions.ignoreRecommendations", true, settingsJson);
            SetIfNotSet("extensions.showRecommendationsOnlyOnDemand", false, settingsJson);
            SetIfNotSet("update.channel", "none", settingsJson);
            SetIfNotSet("update.showReleaseNotes", false, settingsJson);

            if (!settingsJson.ContainsKey("terminal.integrated.env.windows"))
            {
                dynamic terminalProps = new JObject();

                terminalProps["JAVA_HOME"] = Path.Combine(homePath, "jdk");
                terminalProps["PATH"]      = Path.Combine(homePath, "jdk", "bin") + ";${env:PATH}";

                settingsJson["terminal.integrated.env.windows"] = terminalProps;
            }
            else
            {
                dynamic terminalEnv = settingsJson["terminal.integrated.env.windows"];
                terminalEnv["JAVA_HOME"] = Path.Combine(homePath, "jdk");
                string path = terminalEnv["PATH"];
                if (path == null)
                {
                    terminalEnv["PATH"] = Path.Combine(homePath, "jdk", "bin") + ";${env:PATH}";
                }
                else
                {
                    var binPath = Path.Combine(homePath, "jdk", "bin");
                    if (!path.Contains(binPath))
                    {
                        path = binPath + ";" + path;
                        terminalEnv["PATH"] = path;
                    }
                }
            }

            // TODO Handle Unix and Mac Paths

            var serialized = JsonConvert.SerializeObject(settingsJson, Formatting.Indented);
            await File.WriteAllTextAsync(settingsFile, serialized);
        }
Example #15
0
File: GS.cs Project: engina/SharkIT
 public void DownloadSong(string host, string key, JObject song)
 {
     if (song.ContainsKey("Percentage"))
     {
         return;
     }
     Download d = new Download(new Uri("http://" + host + "/stream.php"), key, m_cc, song);
     d.Progress += new EventHandler(d_Progress);
     return;
     CookieAwareWebClient wc = new CookieAwareWebClient(m_cc);
     //!FIXME Segmented downloads
     NameValueCollection nvc = new NameValueCollection();
     nvc.Add("streamKey", key);
     wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
     wc.UploadValuesCompleted += new UploadValuesCompletedEventHandler(wc_DownloadStream);
     wc.UploadValuesAsync(new Uri("http://" + host + "/stream.php"), "POST", nvc, song);
 }
Example #16
0
File: GS.cs Project: engina/SharkIT
        private JObject _Request(string uri, string method, JObject parameters, UploadStringCompletedEventHandler handler, object handlerToken, JObject headerOverride)
        {
            JObject request = new JObject();
            request.Add("parameters", parameters);
            JObject header = new JObject();
            header.Add("session", m_sid);
            header.Add("client", "jsqueue");
            header.Add("clientRevision", "20120123.02");
            header.Add("privacy", 0);
            // Somehow this uuid is important, and I don't really know what it is, the UUID of the JSQueue flash object ?
            header.Add("uuid", "E1AA0D1D-86EF-4CE2-AEC9-F70358E2535E");
            header.Add("country", m_countryObj);
            request.Add("header", header);
            request.Add("method", method);

            if (headerOverride != null)
            {
                IDictionaryEnumerator e = headerOverride.GetEnumerator();
                while (e.MoveNext())
                {
                    if (header.ContainsKey(e.Key))
                        header[e.Key] = e.Value;
                    else
                        header.Add(e.Key, e.Value);
                }
            }

            string t = GenerateToken(method, (string)header["client"]);
            header.Add("token", t);

            string requestStr = JSON.JsonEncode(request).Replace("\n", "").Replace(" ", "").Replace("\r", "");
            CookieAwareWebClient wc = new CookieAwareWebClient(m_cc);
            wc.UploadStringCompleted += handler;
            wc.UploadStringAsync(new Uri(uri + method), "POST", requestStr, handlerToken);
            RequestSent(this, requestStr);
            return request;
        }
Example #17
0
        private async Task <byte[]> GeneratePdfDataFromHtml(Guid id, string html, JObject options)
        {
            _logger.LogDebug($"Generating pdf from {id}");

            Browser browser = default;
            Page    page    = default;

            try
            {
                browser = await Puppeteer.LaunchAsync(new LaunchOptions
                {
                    ExecutablePath    = _chromiumPath,
                    Headless          = true,
                    IgnoreHTTPSErrors = true,
                    Args = new[] { "--no-sandbox", "--disable-dev-shm-usage", "--incognito", "--disable-gpu", "--disable-software-rasterizer" },
                    EnqueueTransportMessages = false
                });

                page = await browser.NewPageAsync();

                await page.SetContentAsync(html,
                                           new NavigationOptions
                {
                    Timeout   = 15 * 1000,
                    WaitUntil = new[] { WaitUntilNavigation.Load, WaitUntilNavigation.DOMContentLoaded }
                });

                var defaultPdfOptions = new PdfOptions
                {
                    Format = options.ContainsKey("Width") && options.ContainsKey("Height") ?
                             new PaperFormat(
                        options["Width"].Value <decimal>(),
                        options["Height"].Value <decimal>()
                        ) :
                             PaperFormat.A4
                };

                return(await page.PdfDataAsync(new PdfOptions
                {
                    Format = defaultPdfOptions.Format,
                    DisplayHeaderFooter = options.ContainsKey("footerTemplate") || options.ContainsKey("headerTemplate"),
                    FooterTemplate = options.ContainsKey("footerTemplate") ? options["footerTemplate"].Value <string>() : defaultPdfOptions.FooterTemplate,
                    HeaderTemplate = options.ContainsKey("headerTemplate") ? options["headerTemplate"].Value <string>() : defaultPdfOptions.HeaderTemplate,
                    PrintBackground = options.ContainsKey("printBackground") ? options["printBackground"].Value <bool>() : defaultPdfOptions.PrintBackground,
                    PreferCSSPageSize = options.ContainsKey("preferCSSPageSize") ? options["preferCSSPageSize"].Value <bool>() : defaultPdfOptions.PreferCSSPageSize,
                    PageRanges = options.ContainsKey("pageRanges") ? options["pageRanges"].Value <string>() : defaultPdfOptions.PageRanges,
                    MarginOptions = new MarginOptions
                    {
                        Top = options.ContainsKey("marginTop") ? options["marginTop"].Value <string>() : defaultPdfOptions.MarginOptions.Top,
                        Bottom = options.ContainsKey("marginBottom") ? options["marginBottom"].Value <string>() : defaultPdfOptions.MarginOptions.Bottom,
                        Left = options.ContainsKey("marginLeft") ? options["marginLeft"].Value <string>() : defaultPdfOptions.MarginOptions.Left,
                        Right = options.ContainsKey("marginRight") ? options["marginRight"].Value <string>() : defaultPdfOptions.MarginOptions.Right,
                    }
                }));
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Failed to generate pdf from {id}");
                throw;
            }
            finally
            {
                await page?.CloseAsync();

                page?.Dispose();
                await browser?.CloseAsync();

                browser?.Dispose();
            }
        }
Example #18
0
        private double?[] GetSingleRates(JObject joProfile, int percentage)
        {
            var nsRates = new double?[48];

            if (!joProfile.ContainsKey("basal"))
            {
                return(nsRates);
            }

            foreach (JObject joRate in joProfile["basal"])
            {
                int?basalIndex = null;

                var nsRate = joRate.SafeDouble("value");
                if (!nsRate.HasValue)
                {
                    continue;
                }

                var rate = (nsRate.Value * percentage / 100.0).Round(0.05m);

                var tas = joRate.SafeInt("timeAsSeconds");
                if (tas.HasValue)
                {
                    basalIndex = (int)tas.Value / 1800;
                }

                var nsTimeString = joRate.SafeString("time");
                if (!string.IsNullOrEmpty(nsTimeString))
                {
                    var nsTimeComponents = nsTimeString.Split(':');
                    if (nsTimeComponents.Length == 2)
                    {
                        int nsHour;
                        int nsMinute;
                        if (int.TryParse(nsTimeComponents[0], out nsHour) &&
                            int.TryParse(nsTimeComponents[1], out nsMinute))
                        {
                            int index_candidate = nsHour * 2;
                            if (nsMinute == 0)
                            {
                                basalIndex = index_candidate;
                            }
                            else if (nsMinute == 30)
                            {
                                basalIndex = index_candidate + 1;
                            }
                        }
                    }
                }

                if (!basalIndex.HasValue)
                {
                    continue;
                }

                if (basalIndex >= 0 && basalIndex < 48 && rate > 0 && rate < 30)
                {
                    nsRates[basalIndex.Value] = rate;
                }
            }

            return(nsRates);
        }
Example #19
0
        public Status ParseStatus(JObject obj, long issuer, User creater)
        {
            var status = new Status
            {
                Issuer = new List <long> {
                    issuer
                },
                CreatedAt         = ParseTwitterDateTime(obj["created_at"].ToString()),
                ID                = obj["id"].ToObject <long>(),
                Text              = SafeGetString(obj, "full_text"),
                Source            = obj["source"].ToString(),
                Truncated         = obj["truncated"].ToObject <bool>(),
                ReplyToStatusId   = SafeGetLong(obj, "in_reply_to_status_id"),
                ReplyToUserId     = SafeGetLong(obj, "in_reply_to_user_id"),
                ReplyToScreenName = SafeGetString(obj, "in_reply_to_screen_name"),
                Creater           = creater,
                //TODO: coordinates
                //TODO: place
                QuotedStatusId  = SafeGetLong(obj, "quoted_status_id"),
                IsQuote         = obj["is_quote_status"].ToObject <bool>(),
                QuotedStatus    = SafeGetStatus(obj, "quoted_status", issuer),
                RetweetedStatus = SafeGetStatus(obj, "retweeted_status", issuer),
                RetweetCount    = obj["retweet_count"].ToObject <int>(),
                FavoriteCount   = obj["favorite_count"].ToObject <int>()
            };
            var entities = obj["entities"].ToObject <JObject>();

            if (status.Text == null)
            {
                status.Text = obj["text"].ToString();
            }


            ParseBasicEntitesGroup(status, entities);
            if (entities.ContainsKey("polls"))
            {
                status.Polls = ParseArray(entities["polls"].ToObject <JArray>(), ParsePolls);
            }
            else if (obj.ContainsKey("card"))
            {
                var card     = obj["card"];
                var cardName = card["name"].ToString();
                if (cardName.EndsWith("choice_text_only"))
                {
                    var polls = new Polls();

                    var values = card["binding_values"];

                    polls.DurationMinutes = values["duration_minutes"]["string_value"].ToObject <int>();
                    polls.EndDateTime     = ParsePollsCardDateTime(values["end_datetime_utc"]["string_value"].ToString());
                    polls.URL             = values["api"]["string_value"].ToString();

                    var count = 2;
                    if (cardName == "poll3choice_text_only")
                    {
                        count = 3;
                    }
                    else if (cardName == "poll4choice_text_only")
                    {
                        count = 4;
                    }
                    polls.Options = new Polls.Option[count];
                    for (int i = 0; i < count; i++)
                    {
                        polls.Options[i]  = ParseCardPollsOption(values.ToObject <JObject>(), i + 1);
                        polls.TotalCount += polls.Options[i].Count;
                    }

                    status.Polls = new Polls[] { polls };
                }
            }
            if (obj.ContainsKey("extended_entities"))
            {
                status.ExtendMedias = ParseArray(obj["extended_entities"]["media"].ToObject <JArray>(), ParseExtendMedia);
            }
            status.IsFavortedByUser  = SafeGetBool(obj, "favorited");
            status.IsRetweetedByUser = SafeGetBool(obj, "retweeted");
            status.PossiblySensitive = SafeGetBool(obj, "possibly_sensitive");

            return(StatusFilter.ApplyFilter(status));
        }
Example #20
0
        protected override async Task ProcessRecordAsync()
        {
            try
            {
                var WorkflowRuntime = new RuntimeDefinedParameter();
                _staticStorage.TryGetValue("Workflow", out WorkflowRuntime);
                string WorkflowName = "";
                if (WorkflowRuntime.Value != null && !string.IsNullOrEmpty(WorkflowRuntime.Value.ToString()))
                {
                    WorkflowName = WorkflowRuntime.Value.ToString();
                }
                var workflow = _workflows.Where(x => x.name == WorkflowName).FirstOrDefault();
                if (workflow == null)
                {
                    WriteError(new ErrorRecord(new Exception("Missing workflow name or workflow not found"), "", ErrorCategory.NotSpecified, null));
                    return;
                }
                if (Object != null)
                {
                    json = Object.toJson();
                }
                if (string.IsNullOrEmpty(json))
                {
                    json = "{}";
                }
                await RegisterQueue();

                JObject tmpObject = JObject.Parse(json);
                correlationId = Guid.NewGuid().ToString().Replace("{", "").Replace("}", "").Replace("-", "");

                global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage;

                WriteProgress(new ProgressRecord(0, "Invoking", "Invoking " + workflow.name));
                var result = await global.webSocketClient.QueueMessage(workflow.queue, tmpObject, psqueue, correlationId);

                workItemsWaiting.WaitOne();
                WriteProgress(new ProgressRecord(0, "Invoking", "completed")
                {
                    RecordType = ProgressRecordType.Completed
                });

                JObject payload = msg;
                if (msg.ContainsKey("payload"))
                {
                    payload = msg.Value <JObject>("payload");
                }
                if (state == "failed")
                {
                    var message = "Invoke OpenFlow Workflow failed";
                    if (msg.ContainsKey("error"))
                    {
                        message = msg["error"].ToString();
                    }
                    if (msg.ContainsKey("_error"))
                    {
                        message = msg["_error"].ToString();
                    }
                    if (payload.ContainsKey("error"))
                    {
                        message = payload["error"].ToString();
                    }
                    if (payload.ContainsKey("_error"))
                    {
                        message = payload["_error"].ToString();
                    }
                    if (string.IsNullOrEmpty(message))
                    {
                        message = "Invoke OpenFlow Workflow failed";
                    }
                    WriteError(new ErrorRecord(new Exception(message), "", ErrorCategory.NotSpecified, null));
                    return;
                }
                if (payload != null)
                {
                    var _result = payload.toPSObject();
                    WriteObject(_result);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "", ErrorCategory.NotSpecified, null));
                WriteProgress(new ProgressRecord(0, "Invoking", "completed")
                {
                    RecordType = ProgressRecordType.Completed
                });
            }
        }
        public async Task <IActionResult> LoginUser(dynamic req)
        {
            JObject body = DeserializeRequest(req);

            string res;

            try {
                res = await AuthConnection.Instance.LoginUser(body.GetValue("email").ToString().ToLowerInvariant(),
                                                              body.GetValue("password").ToString());
            } catch (Exception e) {
                return(BadRequest($"Something went wrong: {e}"));
            }

            // If the user exists in Azure B2C but doesn't exist in the database, create the user's profile
            // First, get the user's claims from the generated JWT
            JObject tokenObject = DeserializeRequest(res);

            if (tokenObject.ContainsKey("error"))
            {
                return(Unauthorized(tokenObject.GetValue("error_description").ToString()));
            }

            JwtSecurityToken jwt = AuthConnection.DecodeToken(tokenObject.GetValue("access_token").ToString());

            Dictionary <string, string> claimsDictionary = new Dictionary <string, string>();

            foreach (Claim claim in jwt.Claims)
            {
                claimsDictionary[claim.Type] = claim.Value;
            }

            try {
                // See if the user exists in the database
                string queryString = ReadVertexQuery(claimsDictionary["emails"]);
                var    result      = await DatabaseConnection.Instance.ExecuteQuery(queryString);

                // If the user exists, return Ok()
                if (result.Count > 0)
                {
                    return(Ok(res));
                }

                // Else, create the user
                JObject user = new JObject(
                    new JProperty("firstName", claimsDictionary["given_name"]),
                    new JProperty("lastName", claimsDictionary["family_name"]),
                    new JProperty("email", claimsDictionary["emails"].ToLowerInvariant()));

                IActionResult createUserResult = await CreateUser(user.ToString()).ConfigureAwait(false);

                OkObjectResult okResult = createUserResult as OkObjectResult;

                if (okResult.StatusCode != 200)
                {
                    return(BadRequest("Error creating new user vertex when signing in user for the first time"));
                }

                return(Ok(res));
            } catch (Exception e) {
                return(BadRequest($"Unknown error signing user for the first time: {e}"));
            }
        }
Example #22
0
        /// <summary>
        /// This method will convert string representaion of current Json object, and update the world model
        /// This method will not check for walls since walls will only be sent once and will be processed in TryInitializedDrawingPanel method
        /// </summary>
        /// <param name="s">string representation of Json object </param>
        private void ConvertAndUpdateWorld(string s)
        {
            JObject obj = JObject.Parse(s);

            if (obj.ContainsKey("tank"))
            {
                Tank tank = JsonConvert.DeserializeObject <Tank>(s);
                lock (TheWorld.Tanks)
                {
                    if (tank.Disconnected) // Remove the tank from the world and Start Explosion animation
                    {
                        if (TheWorld.Tanks.ContainsKey(tank.ID))
                        {
                            TheWorld.Tanks.Remove(tank.ID);
                        }
                        Explode(tank);
                    }
                    else if (tank.Died) // Start an explosion animation
                    {
                        Explode(tank);
                    }
                    else // add to the world
                    {
                        if (TheWorld.Tanks.ContainsKey(tank.ID))
                        {
                            TheWorld.Tanks[tank.ID] = tank;
                        }
                        else
                        {
                            TheWorld.Tanks.Add(tank.ID, tank);
                        }
                    }
                }
            }
            else if (obj.ContainsKey("power"))
            {
                Powerup powerup = JsonConvert.DeserializeObject <Powerup>(s);
                lock (TheWorld.Powerups)
                {
                    if (powerup.Died) //Remove power up from the world
                    {
                        if (TheWorld.Powerups.ContainsKey(powerup.ID))
                        {
                            TheWorld.Powerups.Remove(powerup.ID);
                        }
                    }
                    else // Add to the World model as usual
                    {
                        if (TheWorld.Powerups.ContainsKey(powerup.ID))
                        {
                            TheWorld.Powerups[powerup.ID] = powerup;
                        }
                        else
                        {
                            TheWorld.Powerups.Add(powerup.ID, powerup);
                        }
                    }
                }
            }
            else if (obj.ContainsKey("proj"))
            {
                Projectile projectile = JsonConvert.DeserializeObject <Projectile>(s);
                lock (TheWorld.Projectiles)
                {
                    if (projectile.Died) // Remove projectile in the world
                    {
                        if (TheWorld.Projectiles.ContainsKey(projectile.ID))
                        {
                            TheWorld.Projectiles.Remove(projectile.ID);
                        }
                    }
                    else // Add to the World model as usual
                    {
                        if (TheWorld.Projectiles.ContainsKey(projectile.ID))
                        {
                            TheWorld.Projectiles[projectile.ID] = projectile;
                        }
                        else
                        {
                            TheWorld.Projectiles.Add(projectile.ID, projectile);
                        }
                    }
                }
            }
            else if (obj.ContainsKey("beam"))
            {
                Beam beam = JsonConvert.DeserializeObject <Beam>(s);
                //Inform the drawing panel to draw beam
                StartBeamAnimation(beam);
            }
        }
Example #23
0
        /// <summary>
        /// Constructs a lobby
        /// </summary>
        /// <param name="clientWebSocket">Client web socket</param>
        /// <param name="isConnectionSecure">Is connection secure</param>
        /// <param name="lobbyID">Lobby ID</param>
        /// <param name="minimalDrawingTime">Minimal drawing time in seconds</param>
        /// <param name="maximalDrawingTime">Maximal drawing time in seconds</param>
        /// <param name="minimalRoundCount">Minimal round count</param>
        /// <param name="maximalRoundCount">Maximal round count</param>
        /// <param name="minimalMaximalPlayerCount">Minimal of maximal player count</param>
        /// <param name="maximalMaximalPlayerCount">Maximal of maximal player count</param>
        /// <param name="minimalClientsPerIPLimit">Minimal clients per IP limit</param>
        /// <param name="maximalClientsPerIPLimit">Maximal clients per IP limit</param>
        /// <param name="maximalPlayerCount">Maximal player count</param>
        /// <param name="currentMaximalRoundCount">Current maximal round count</param>
        /// <param name="isLobbyPublic">Is lobby public</param>
        /// <param name="isVotekickingEnabled">Is votekicking enabled</param>
        /// <param name="customWordsChance">Custom words chance</param>
        /// <param name="allowedClientsPerIPCount">Allowed clients per IP count</param>
        /// <param name="drawingBoardBaseWidth">Drawing board base width</param>
        /// <param name="drawingBoardBaseHeight">Drawing board base height</param>
        /// <param name="minimalBrushSize">Minimal brush size</param>
        /// <param name="maximalBrushSize">Maximal brush size</param>
        /// <param name="suggestedBrushSizes">Suggested brush sizes</param>
        /// <param name="canvasColor">Canvas color</param>
        public Lobby
        (
            ClientWebSocket clientWebSocket,
            bool isConnectionSecure,
            string lobbyID,
            uint minimalDrawingTime,
            uint maximalDrawingTime,
            uint minimalRoundCount,
            uint maximalRoundCount,
            uint minimalMaximalPlayerCount,
            uint maximalMaximalPlayerCount,
            uint minimalClientsPerIPLimit,
            uint maximalClientsPerIPLimit,
            uint maximalPlayerCount,
            uint currentMaximalRoundCount,
            bool isLobbyPublic,
            bool isVotekickingEnabled,
            uint customWordsChance,
            uint allowedClientsPerIPCount,
            uint drawingBoardBaseWidth,
            uint drawingBoardBaseHeight,
            uint minimalBrushSize,
            uint maximalBrushSize,
            IEnumerable<uint> suggestedBrushSizes,
            IColor canvasColor
        )
        {
            Limits = new LobbyLimits
            (
                minimalDrawingTime,
                maximalDrawingTime,
                minimalRoundCount,
                maximalRoundCount,
                minimalMaximalPlayerCount,
                maximalMaximalPlayerCount,
                minimalClientsPerIPLimit,
                maximalClientsPerIPLimit,
                minimalBrushSize,
                maximalBrushSize
            );
            if (maximalPlayerCount < minimalMaximalPlayerCount)
            {
                throw new ArgumentException("Maximal player count can't be smaller than minimal of maximal player count.", nameof(maximalPlayerCount));
            }
            if (maximalPlayerCount > maximalMaximalPlayerCount)
            {
                throw new ArgumentException("Maximal player count can't be bigger than maximal of maximal player count.", nameof(maximalPlayerCount));
            }
            if (currentMaximalRoundCount < minimalRoundCount)
            {
                throw new ArgumentException("Current maximal round count can't be smaller than minimal round count.", nameof(currentMaximalRoundCount));
            }
            if (currentMaximalRoundCount > maximalRoundCount)
            {
                throw new ArgumentException("Current maximal round count can't be bigger than maximal round count.", nameof(currentMaximalRoundCount));
            }
            if (customWordsChance > 100U)
            {
                throw new ArgumentException("Custom words chance can't be bigger than 100.", nameof(customWordsChance));
            }
            if (allowedClientsPerIPCount < minimalClientsPerIPLimit)
            {
                throw new ArgumentException("Clients per IP limit can't be smaller than minimal clients per IP limit.", nameof(allowedClientsPerIPCount));
            }
            if (allowedClientsPerIPCount > maximalClientsPerIPLimit)
            {
                throw new ArgumentException("Clients per IP limit can't be bigger than maximal clients per IP limit.", nameof(allowedClientsPerIPCount));
            }
            if (drawingBoardBaseWidth < 1U)
            {
                throw new ArgumentException("Drawing board base width can't be smaller than one.", nameof(drawingBoardBaseWidth));
            }
            if (drawingBoardBaseHeight < 1U)
            {
                throw new ArgumentException("Drawing board base height can't be smaller than one.", nameof(drawingBoardBaseHeight));
            }
            this.clientWebSocket = clientWebSocket ?? throw new ArgumentNullException(nameof(clientWebSocket));
            IsConnectionSecure = isConnectionSecure;
            LobbyID = lobbyID ?? throw new ArgumentNullException(nameof(lobbyID));
            MaximalPlayerCount = maximalPlayerCount;
            CurrentMaximalRoundCount = currentMaximalRoundCount;
            IsLobbyPublic = isLobbyPublic;
            IsVotekickingEnabled = isVotekickingEnabled;
            CustomWordsChance = customWordsChance;
            AllowedClientsPerIPCount = allowedClientsPerIPCount;
            DrawingBoardBaseWidth = drawingBoardBaseWidth;
            DrawingBoardBaseHeight = drawingBoardBaseHeight;
            SuggestedBrushSizes = suggestedBrushSizes ?? throw new ArgumentNullException(nameof(suggestedBrushSizes));
            CanvasColor = canvasColor;
            AddMessageParser<ReadyReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    ReadyData ready = gameMessage.Data;
                    uint current_round = ready.CurrentRound;
                    uint current_maximal_round_count = ready.CurrentMaximalRoundCount;
                    long current_drawing_time = ready.CurrentDrawingTime;
                    if (current_maximal_round_count > Limits.MaximalRoundCount)
                    {
                        throw new InvalidDataException($"Current maximal round count can't be bigger than maximal round count, which is { Limits.MaximalRoundCount }.");
                    }
                    if (current_round > current_maximal_round_count)
                    {
                        throw new InvalidDataException($"Current round can't be bigger than current maximal round count, which is { current_maximal_round_count }.");
                    }
                    if (current_drawing_time > (Limits.MaximalDrawingTime * 1000L))
                    {
                        throw new InvalidDataException($"Current drawing time can't be bigger than the specified maximal maximal player count, which is { Limits.MaximalMaximalPlayerCount }.");
                    }
                    IsPlayerAllowedToDraw = ready.IsPlayerAllowedToDraw;
                    IsVotekickingEnabled = ready.IsVotekickingEnabled;
                    GameState = ready.GameState;
                    CurrentRound = current_round;
                    CurrentMaximalRoundCount = current_maximal_round_count;
                    CurrentDrawingTime = ready.CurrentDrawingTime;
                    if (ready.WordHints == null)
                    {
                        wordHints = Array.Empty<IWordHint>();
                    }
                    else
                    {
                        if (wordHints.Length != ready.WordHints.Count)
                        {
                            wordHints = new IWordHint[ready.WordHints.Count];
                        }
#if SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                        for (int index = 0; index < wordHints.Length; index++)
#else
                        Parallel.For(0, wordHints.Length, (index) =>
#endif
                        {
                            WordHintData word_hint_data = ready.WordHints[index];
                            wordHints[index] = new WordHint(word_hint_data.Character, word_hint_data.Underline);
                        }
#if !SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                        );
#endif
                    }
                    UpdateAllPlayers(ready.Players);
                    MyPlayer = players.ContainsKey(ready.PlayerID) ? players[ready.PlayerID] : null;
                    Owner = players.ContainsKey(ready.OwnerID) ? players[ready.OwnerID] : null;
                    currentDrawing.Clear();
                    JObject json_object = JObject.Parse(json);
                    if (json_object.ContainsKey("data"))
                    {
                        if (json_object["data"] is JObject json_data_object)
                        {
                            if (json_data_object.ContainsKey("currentDrawing"))
                            {
                                if (json_data_object["currentDrawing"] is JArray json_draw_commands)
                                {
                                    ParseCurrentDrawingFromJSON(json_draw_commands);
                                }
                            }
                        }
                    }
                    OnReadyGameMessageReceived?.Invoke();
                },
                MessageParseFailedEvent
            );
            AddMessageParser<NextTurnReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    NextTurnData next_turn = gameMessage.Data;
                    IsPlayerAllowedToDraw = false;
                    GameState = EGameState.Ongoing;
                    CurrentRound = next_turn.Round;
                    CurrentDrawingTime = next_turn.RoundEndTime;
                    UpdateAllPlayers(next_turn.Players);
                    PreviousWord = next_turn.PreviousWord ?? PreviousWord;
                    currentDrawing.Clear();
                    OnNextTurnGameMessageReceived?.Invoke();
                }, MessageParseFailedEvent
            );
            AddMessageParser<GameOverReceiveGameMessage>
            (
                (gameMessage, json) =>
                {
                    GameOverData game_over = gameMessage.Data;
                    IsPlayerAllowedToDraw = false;
                    GameState = EGameState.Ongoing;
                    CurrentRound = game_over.CurrentRound;
                    CurrentDrawingTime = game_over.CurrentDrawingTime;
                    UpdateAllPlayers(game_over.Players);
                    PreviousWord = game_over.PreviousWord ?? PreviousWord;
                    currentDrawing.Clear();
                    OnGameOverMessageReceived?.Invoke();
                }, MessageParseFailedEvent
            );
            AddMessageParser<NameChangeReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    NameChangeData name_change = gameMessage.Data;
                    if (players.ContainsKey(name_change.PlayerID) && players[name_change.PlayerID] is IInternalPlayer internal_player)
                    {
                        internal_player.UpdateNameInternally(name_change.PlayerName);
                        OnNameChangeGameMessageReceived?.Invoke(internal_player);
                    }
                },
                MessageParseFailedEvent
            );
            AddMessageParser<UpdatePlayersReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    UpdateAllPlayers(gameMessage.Data);
                    OnUpdatePlayersGameMessageReceived?.Invoke(players);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<UpdateWordhintReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    GameState = EGameState.Ongoing;
                    WordHintData[] word_hints = gameMessage.Data;
                    if (wordHints.Length != word_hints.Length)
                    {
                        wordHints = new IWordHint[word_hints.Length];
                    }
#if SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                    for (int index = 0; index < wordHints.Length; index++)
#else
                    Parallel.For(0, wordHints.Length, (index) =>
#endif
                    {
                        WordHintData word_hint_data = word_hints[index];
                        wordHints[index] = new WordHint(word_hint_data.Character, word_hint_data.Underline);
                    }
#if !SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                    );
#endif
                    OnUpdateWordhintGameMessageReceived?.Invoke(wordHints);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<MessageReceiveGameMessageData>((gameMessage, json) => OnMessageGameMessageReceived?.Invoke(players.ContainsKey(gameMessage.Data.AuthorID) ? players[gameMessage.Data.AuthorID] : null, gameMessage.Data.Content), MessageParseFailedEvent);
            AddMessageParser<NonGuessingPlayerMessageReceiveGameMessageData>((gameMessage, json) => OnNonGuessingPlayerMessageGameMessageReceived?.Invoke(players.ContainsKey(gameMessage.Data.AuthorID) ? players[gameMessage.Data.AuthorID] : null, gameMessage.Data.Content), MessageParseFailedEvent);
            AddMessageParser<SystemMessageReceiveGameMessageData>((gameMessage, json) => OnSystemMessageGameMessageReceived?.Invoke(gameMessage.Data), MessageParseFailedEvent);
            AddMessageParser<LineReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    LineData line = gameMessage.Data;
                    IColor color = (Color)line.Color;
                    GameState = EGameState.Ongoing;
                    currentDrawing.Add(new DrawCommand(EDrawCommandType.Line, line.FromX, line.FromY, line.ToX, line.ToY, color, line.LineWidth));
                    OnLineGameMessageReceived?.Invoke(line.FromX, line.FromY, line.ToX, line.ToY, color, line.LineWidth);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<FillReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    FillData fill = gameMessage.Data;
                    IColor color = (Color)fill.Color;
                    currentDrawing.Add(new DrawCommand(EDrawCommandType.Fill, fill.X, fill.Y, fill.X, fill.Y, color, 0.0f));
                    OnFillGameMessageReceived(fill.X, fill.Y, color);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<ClearDrawingBoardReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    currentDrawing.Clear();
                    OnClearDrawingBoardGameMessageReceived?.Invoke();
                },
                MessageParseFailedEvent
            );
            AddMessageParser<YourTurnReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    IsPlayerAllowedToDraw = true;
                    currentDrawing.Clear();
                    OnYourTurnGameMessageReceived?.Invoke((string[])gameMessage.Data.Clone());
                },
                MessageParseFailedEvent
            );
            AddMessageParser<CloseGuessReceiveGameMessageData>((gameMessage, json) => OnCloseGuessGameMessageReceived?.Invoke(gameMessage.Data), MessageParseFailedEvent);
            AddMessageParser<CorrectGuessReceiveGameMessageData>((gameMessage, json) => OnCorrectGuessGameMessageReceived?.Invoke(players.ContainsKey(gameMessage.Data) ? players[gameMessage.Data] : null), MessageParseFailedEvent);
            AddMessageParser<KickVoteReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    KickVoteData kick_vote = gameMessage.Data;
                    if (players.ContainsKey(kick_vote.PlayerID) && players[kick_vote.PlayerID] is IInternalPlayer internal_player)
                    {
                        internal_player.UpdateNameInternally(kick_vote.PlayerName);
                        OnKickVoteGameMessageReceived?.Invoke(internal_player, kick_vote.VoteCount, kick_vote.RequiredVoteCount);
                    }
                },
                MessageParseFailedEvent
            );
            AddMessageParser<DrawerKickedReceiveGameMessageData>((gameMessage, json) => OnDrawerKickedGameMessageReceived?.Invoke(), MessageParseFailedEvent);
            AddMessageParser<OwnerChangeReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    OwnerChangeData owner_change = gameMessage.Data;
                    if (players.ContainsKey(owner_change.PlayerID) && players[owner_change.PlayerID] is IInternalPlayer internal_player)
                    {
                        internal_player.UpdateNameInternally(owner_change.PlayerName);
                        OnOwnerChangeGameMessageReceived?.Invoke(internal_player);
                    }
                },
                MessageParseFailedEvent
            );
            AddMessageParser<DrawingReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    currentDrawing.Clear();
                    JObject json_object = JObject.Parse(json);
                    if (json_object.ContainsKey("data"))
                    {
                        if (json_object["data"] is JArray json_draw_commands)
                        {
                            ParseCurrentDrawingFromJSON(json_draw_commands);
                        }
                    }
                    OnDrawingGameMessageReceived?.Invoke(currentDrawing);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<LobbySettingsChangedReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    LobbySettingsChangeData lobby_settings_change = gameMessage.Data;
                    uint maximal_player_count = lobby_settings_change.MaximalPlayerCount;
                    uint custom_words_chance = lobby_settings_change.CustomWordsChance;
                    if (maximal_player_count < Limits.MinimalMaximalPlayerCount)
                    {
                        throw new InvalidDataException($"Maximal player count can't be smaller than the specified minimal maximal player count, which is { Limits.MinimalMaximalPlayerCount }.");
                    }
                    if (maximal_player_count > Limits.MaximalMaximalPlayerCount)
                    {
                        throw new InvalidDataException($"Maximal player count can't be bigger than the specified maximal maximal player count, which is { Limits.MaximalMaximalPlayerCount }.");
                    }
                    if (custom_words_chance > 100U)
                    {
                        throw new InvalidDataException("Custom words chance can't be bigger than one hundred.");
                    }
                    MaximalPlayerCount = maximal_player_count;
                    IsLobbyPublic = lobby_settings_change.IsLobbyPublic;
                    IsVotekickingEnabled = lobby_settings_change.IsVotekickingEnabled;
                    CustomWordsChance = custom_words_chance;
                },
                MessageParseFailedEvent
            );
            webSocketSendThread = new Thread(async () =>
            {
                while ((this.clientWebSocket != null) && (this.clientWebSocket.State == WebSocketState.Open))
                {
                    while (sendGameMessageQueue.TryDequeue(out string send_game_message))
                    {
                        await clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(send_game_message)), WebSocketMessageType.Text, true, default);
                    }
                }
            });
            webSocketReceiveThread = new Thread(async () =>
            {
                using (MemoryStream memory_stream = new MemoryStream())
                {
                    using (StreamReader reader = new StreamReader(memory_stream))
                    {
                        while ((this.clientWebSocket != null) && (this.clientWebSocket.State == WebSocketState.Open))
                        {
                            try
                            {
                                WebSocketReceiveResult result = await this.clientWebSocket.ReceiveAsync(receiveBuffer, default);
                                if (result != null)
                                {
                                    memory_stream.Write(receiveBuffer.Array, 0, result.Count);
                                    if (result.EndOfMessage)
                                    {
                                        memory_stream.Seek(0L, SeekOrigin.Begin);
                                        receivedGameMessages.Enqueue(reader.ReadToEnd());
                                        memory_stream.Seek(0L, SeekOrigin.Begin);
                                        memory_stream.SetLength(0L);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Console.Error.WriteLine(e);
                                this.clientWebSocket.Dispose();
                                this.clientWebSocket = null;
                            }
                        }
                    }
                }
            });
            webSocketSendThread.Start();
            webSocketReceiveThread.Start();
        }
        private async Task ExtractSoftwareStatement(JObject jObj)
        {
            var softwareStatement = jObj.GetSoftwareStatementFromRegisterRequest();

            if (string.IsNullOrWhiteSpace(softwareStatement))
            {
                return;
            }

            if (!_jwtParser.IsJwsToken(softwareStatement))
            {
                throw new OAuthException(ErrorCodes.INVALID_SOFTWARE_STATEMENT, ErrorMessages.BAD_JWS_SOFTWARE_STATEMENT);
            }

            SimpleIdServer.Jwt.Jws.JwsPayload jwsPayload;
            SimpleIdServer.Jwt.Jws.JwsHeader  header;
            try
            {
                jwsPayload = _jwtParser.ExtractJwsPayload(softwareStatement);
                header     = _jwtParser.ExtractJwsHeader(softwareStatement);
                if (jwsPayload == null)
                {
                    throw new OAuthException(ErrorCodes.INVALID_SOFTWARE_STATEMENT, ErrorMessages.BAD_JWS_SOFTWARE_STATEMENT);
                }
            }
            catch
            {
                throw new OAuthException(ErrorCodes.INVALID_SOFTWARE_STATEMENT, ErrorMessages.BAD_JWS_SOFTWARE_STATEMENT);
            }

            var issuer       = jwsPayload.GetIssuer();
            var trustedParty = OauthHostOptions.SoftwareStatementTrustedParties.FirstOrDefault(s => s.Iss == issuer);

            if (trustedParty == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_SOFTWARE_STATEMENT, ErrorMessages.BAD_ISSUER_SOFTWARE_STATEMENT);
            }

            using (var httpClient = _httpClientFactory.GetHttpClient())
            {
                var json = await httpClient.GetStringAsync(trustedParty.JwksUrl);

                var keysJson    = JObject.Parse(json)["keys"].ToString();
                var jsonWebKeys = JsonConvert.DeserializeObject <JArray>(keysJson).Select(k => SimpleIdServer.Jwt.JsonWebKey.Deserialize(k.ToString()));
                var jsonWebKey  = jsonWebKeys.FirstOrDefault(j => j.Kid == header.Kid);
                jwsPayload = _jwtParser.Unsign(softwareStatement, jsonWebKey);
                if (jwsPayload == null)
                {
                    throw new OAuthException(ErrorCodes.INVALID_SOFTWARE_STATEMENT, ErrorMessages.BAD_SOFTWARE_STATEMENT_SIGNATURE);
                }

                foreach (var kvp in jwsPayload)
                {
                    if (jObj.ContainsKey(kvp.Key))
                    {
                        jObj.Remove(kvp.Key);
                    }

                    jObj.Add(kvp.Key, JToken.FromObject(kvp.Value));
                }
            }
        }
 public DontImportUserFromWisa(JObject obj)
 {
     SetDefaults();
     this.userName        = obj.ContainsKey("UserName") ? obj["UserName"].ToString() : "";
     this.ShortInfo.Value = "Account: " + userName;
 }
        protected virtual void Parameter(TemplateContext context, string parameterName, JObject parameter)
        {
            if (context.Parameters.ContainsKey(parameterName) || parameter == null || !parameter.ContainsKey("defaultValue"))
            {
                return;
            }

            var type         = parameter["type"].ToObject <ParameterType>();
            var defaultValue = parameter["defaultValue"];

            if (type == ParameterType.Bool)
            {
                context.Parameters.Add(parameterName, new LazyParameter <bool>(defaultValue));
            }
            else if (type == ParameterType.Int)
            {
                context.Parameters.Add(parameterName, new LazyParameter <int>(defaultValue));
            }
            else if (type == ParameterType.String)
            {
                context.Parameters.Add(parameterName, new LazyParameter <string>(defaultValue));
            }
            else if (type == ParameterType.Array)
            {
                context.Parameters.Add(parameterName, new LazyParameter <JArray>(defaultValue));
            }
            else if (type == ParameterType.Object)
            {
                context.Parameters.Add(parameterName, new LazyParameter <JObject>(defaultValue));
            }
            else
            {
                context.Parameters.Add(parameterName, ExpandPropertyToken(context, defaultValue));
            }
        }
Example #27
0
        public void Workflow()
        {
            // Delete any existing widgets in the test subreddit so our tests won't fail.  --Kris
            WidgetResults widgetResults = reddit.Models.Widgets.Get(false, testData["Subreddit"]);

            if (widgetResults != null && widgetResults.Items.Count > 0)
            {
                foreach (KeyValuePair <string, dynamic> pair in widgetResults.Items)
                {
                    JObject data = pair.Value;
                    if (data.ContainsKey("id"))
                    {
                        try
                        {
                            reddit.Models.Widgets.Delete(data["id"].ToString(), testData["Subreddit"]);
                        }
                        // At least one id came back with a WIDGET_NOEXIST error even though it was in the retrieved results.  --Kris
                        catch (RedditBadRequestException) { }
                        catch (AggregateException ex) when(ex.InnerException is RedditBadRequestException)
                        {
                        }
                    }
                }
            }

            // Create TextArea Widget.  --Kris
            WidgetTextArea widgetTextArea = reddit.Models.Widgets.Add(new WidgetTextArea("Test Widget", "This is a test."), testData["Subreddit"]);

            // Create Calendar Widget.  --Kris
            WidgetCalendar widgetCalendar = reddit.Models.Widgets.Add(new WidgetCalendar(
                                                                          new WidgetCalendarConfiguration(0, true, true, true, true, true), "*****@*****.**",
                                                                          false, "Test Calendar Widget", new WidgetStyles()), testData["Subreddit"]);

            // Create CommunityList Widget.  --Kris
            WidgetCommunityListDetailed widgetCommunityList = reddit.Models.Widgets.Add(
                new WidgetCommunityList(new List <string> {
                testData["Subreddit"], "RedditDotNETBot"
            },
                                        "Test CommunityList Widget", new WidgetStyles()), testData["Subreddit"]);

            Assert.IsNotNull(widgetTextArea);
            Assert.IsNotNull(widgetCalendar);
            Assert.IsNotNull(widgetCommunityList);

            // Retrieve the widgets we just created.  --Kris
            widgetResults = reddit.Models.Widgets.Get(false, testData["Subreddit"]);

            Validate(widgetResults);

            // Figure out which result goes with which type (only one of each which makes things easier).  --Kris
            string widgetTextAreaId      = null;
            string widgetCalendarId      = null;
            string widgetCommunityListId = null;

            foreach (KeyValuePair <string, dynamic> pair in widgetResults.Items)
            {
                JObject data = pair.Value;
                if (data.ContainsKey("kind") && data.ContainsKey("id"))
                {
                    switch (data["kind"].ToString())
                    {
                    case "textarea":
                        widgetTextAreaId = data["id"].ToString();
                        break;

                    case "calendar":
                        widgetCalendarId = data["id"].ToString();
                        break;

                    case "community-list":
                        widgetCommunityListId = data["id"].ToString();
                        break;
                    }
                }
            }

            Assert.IsNotNull(widgetTextAreaId);
            Assert.IsNotNull(widgetCalendarId);
            Assert.IsNotNull(widgetCommunityListId);

            // Modify the TextArea Widget.  --Kris
            WidgetTextArea widgetTextAreaUpdated = reddit.Models.Widgets.Update(widgetTextAreaId, new WidgetTextArea("Test Widget B", "This is a test."),
                                                                                testData["Subreddit"]);

            Assert.IsNotNull(widgetTextAreaUpdated);

            // Modify the Calendar Widget.  --Kris
            WidgetCalendar widgetCalendarUpdated = reddit.Models.Widgets.Update(widgetCalendarId, new WidgetCalendar(
                                                                                    new WidgetCalendarConfiguration(0, true, true, true, true, true), "*****@*****.**",
                                                                                    false, "Test Calendar Widget B", new WidgetStyles()), testData["Subreddit"]);

            Assert.IsNotNull(widgetCalendarUpdated);

            // Modify the CommunityList Widget.  --Kris
            WidgetCommunityList widgetCommunityListUpdated = reddit.Models.Widgets.Update(widgetCommunityListId,
                                                                                          new WidgetCommunityList(new List <string> {
                testData["Subreddit"], "RedditDotNETBot"
            },
                                                                                                                  "Test CommunityList Widget", new WidgetStyles()), testData["Subreddit"]);

            Assert.IsNotNull(widgetCommunityListUpdated);

            // Reverse the order of widgets in the test subreddit.  --Kris
            List <string> order = widgetResults.Layout.Sidebar.Order;

            order.Reverse();

            reddit.Models.Widgets.UpdateOrder("sidebar", order, testData["Subreddit"]);

            // Delete the widgets.  --Kris
            DeleteWidget(widgetTextAreaId);
            DeleteWidget(widgetCalendarId);
            DeleteWidget(widgetCommunityListId);
        }
Example #28
0
        /// <summary>
        /// Applies the JSON formatted result of an on-before-contextmenu script and fails silently (Error only visible in debug log).
        /// </summary>
        /// <param name="model"></param>
        /// <param name="result"></param>
        /// <param name="parameterName"></param>
        private void applyResultToModel(ref IMenuModel model, JObject result, string parameterName)
        {
            if (result.ContainsKey("clear") && result["clear"].ToObject <bool>())
            {
                model.Clear();
            }

            if (!result.ContainsKey("entries") || result["entries"] == null)
            {
                return;
            }

            JArray entries = result["entries"] as JArray;

            if (entries == null)
            {
                Tools.Logger.Log("Error while getting entries of result from parameter " + parameterName, Tools.Logger.LogLevel.error);
                return;
            }

            foreach (var entry in entries)
            {
                int    id   = 0;
                string text = "missing text";
                if (entry["id"] != null)
                {
                    try {
                        id = entry["id"].ToObject <int>();
                    } catch (Exception) {
                        Tools.Logger.Log("Invalid 'id' for entry of result from parameter " + parameterName, Tools.Logger.LogLevel.error);
                    }
                    if (id > 1998)
                    {
                        Tools.Logger.Log("id for entry of result is too high, only 1998 ids allowd from parameter " + parameterName, Tools.Logger.LogLevel.error);
                        id = 0;
                    }
                }
                id = ((int)CefMenuCommand.UserFirst) + id;
                if (entry["text"] != null)
                {
                    try {
                        text = entry["text"].ToObject <string>();
                    } catch (Exception) {
                        Tools.Logger.Log("Invalid 'text' for entry of result from parameter " + parameterName, Tools.Logger.LogLevel.error);
                    }
                }

                string type = "label";
                if (entry["type"] != null)
                {
                    try {
                        type = entry["type"].ToObject <string>();
                    } catch (Exception) {
                        Tools.Logger.Log("Invalid 'type' for entry of result from parameter " + parameterName, Tools.Logger.LogLevel.error);
                    }
                }

                switch (type)
                {
                case "separator":
                    model.AddSeparator();
                    break;

                case "checkbox":
                    model.AddCheckItem((CefMenuCommand)id, text);
                    bool isChecked = false;
                    if (entry["checked"] != null)
                    {
                        try {
                            isChecked = entry["checked"].ToObject <bool>();
                        } catch (Exception) {
                            Tools.Logger.Log("Invalid value for 'checked' for entry of result from parameter " + parameterName, Tools.Logger.LogLevel.error);
                        }
                        model.SetCheckedAt(model.Count - 1, isChecked);
                    }
                    break;

                default:
                    model.AddItem((CefMenuCommand)id, text);
                    break;
                }
            }
        }
Example #29
0
        public List <string> GetListDataFromFile(string pathFile, string fileName, string importer)
        {
            FileStream fs = new FileStream(pathFile, FileMode.Open);

            // Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(fs);

            // Get first/desired sheet from the workbook
            ISheet sheet = workbook.GetSheetAt(0);

            // Prepare variable
            List <string>           result           = new List <string>();
            DataFormatter           formatter        = new DataFormatter();
            JObject                 jsonObject       = new JObject();
            JObject                 jsonObjectTemp   = null;
            JObject                 finalObj         = null;
            List <CellRangeAddress> listMergedRegion = new List <CellRangeAddress>();
            int    maxMergedRegionRowLength          = GetMaxMergedRegionRowLength(sheet, listMergedRegion);
            ICell  parentCell            = null;
            string parentStringCellValue = string.Empty;
            string currStringCellValue   = string.Empty;
            int    currRowIndex          = 0;
            int    currColIndex          = 0;
            bool   isReadHeader          = true;
            string jsonBluePrint         = string.Empty; // Use to set value by key when read data after read header

            SortMergedRegions(listMergedRegion, true);
            SortMergedRegions(listMergedRegion, false);

            AddMergeRegionToJSON(sheet, maxMergedRegionRowLength, listMergedRegion, jsonObject, 0, string.Empty);

            // Start reading
            int lastRowNum = sheet.LastRowNum;

            for (int i = 0; i <= lastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null)
                {
                    continue;
                }

                // For each row, iterate through all the columns
                List <ICell> cells = row.Cells;

                if (!string.Empty.Equals(jsonBluePrint))
                {
                    jsonObjectTemp = JObject.Parse(jsonBluePrint);
                }

                foreach (ICell cell in cells)
                {
                    if (isReadHeader)
                    {
                        if (cell.CellType != CellType.Blank)
                        {
                            // Reading header -> ICell always string
                            currStringCellValue = cell.StringCellValue;
                            if ("(1)".Equals(currStringCellValue))
                            {
                                isReadHeader = false;

                                finalObj = new JObject {
                                    { Keywords.NAME_SURVEY, fileName },
                                    { Keywords.IMPORTER, importer },
                                    { Keywords.CREATED_AT, DateTime.Now.ToString(Configs.DATETIME_FORMAT, CultureInfo.InvariantCulture) },
                                    { Keywords.DATA, jsonObject }
                                };

                                jsonBluePrint = JsonConvert.SerializeObject(finalObj);
                                break;
                            }

                            currRowIndex = cell.RowIndex;
                            currColIndex = cell.ColumnIndex;
                            if (currRowIndex < _numberAddedRow)
                            {
                                // These cell in row was added
                                continue;
                            }
                            if (currRowIndex != 0)
                            {
                                parentCell = GetParentCell(sheet, currRowIndex, currColIndex);
                            }

                            if (!jsonObject.ContainsKey(currStringCellValue))
                            {
                                if (parentCell != null && parentCell.CellType != CellType.Blank)
                                {
                                    parentStringCellValue = parentCell.StringCellValue;
                                }
                                AddKeyToJsonObject(jsonObject, parentStringCellValue, currStringCellValue, false);
                            }
                        }
                    }
                    else
                    {
                        SetValueToJSONBluePrint(jsonObjectTemp, formatter.FormatCellValue(cell), 0);
                    }
                }

                if (jsonObjectTemp != null)
                {
                    result.Add(JsonConvert.SerializeObject(jsonObjectTemp));
                }
            }
            fs.Close();

            return(result);
        }
Example #30
0
        private PatchResult <JObject> TryPrivatePatch(JObject JSON,
                                                      JObject Patch)
        {
            foreach (var property in Patch)
            {
                if (property.Key == "country_code")
                {
                    return(PatchResult <JObject> .Failed(JSON,
                                                         "Patching the 'country code' of a charging session is not allowed!"));
                }

                else if (property.Key == "party_id")
                {
                    return(PatchResult <JObject> .Failed(JSON,
                                                         "Patching the 'party identification' of a charging session is not allowed!"));
                }

                else if (property.Key == "id")
                {
                    return(PatchResult <JObject> .Failed(JSON,
                                                         "Patching the 'identification' of a charging session is not allowed!"));
                }

                else if (property.Value is null)
                {
                    JSON.Remove(property.Key);
                }

                else if (property.Value is JObject subObject)
                {
                    if (JSON.ContainsKey(property.Key))
                    {
                        if (JSON[property.Key] is JObject oldSubObject)
                        {
                            //ToDo: Perhaps use a more generic JSON patch here!
                            // PatchObject.Apply(ToJSON(), EVSEPatch),
                            var patchResult = TryPrivatePatch(oldSubObject, subObject);

                            if (patchResult.IsSuccess)
                            {
                                JSON[property.Key] = patchResult.PatchedData;
                            }
                        }

                        else
                        {
                            JSON[property.Key] = subObject;
                        }
                    }

                    else
                    {
                        JSON.Add(property.Key, subObject);
                    }
                }

                //else if (property.Value is JArray subArray)
                //{
                //}

                else
                {
                    JSON[property.Key] = property.Value;
                }
            }

            return(PatchResult <JObject> .Success(JSON));
        }
Example #31
0
        public BonusProductEvent(JObject bonusItem)
        {
            if (bonusItem.ContainsKey("id"))
            {
                var shield = bonusItem["shield"] as JObject;
                var card   = bonusItem["card"] as JObject;

                var control = bonusItem["control"] as JObject;

                this.Year  = DateTime.Now.Year;
                this.Week  = ISOWeek.GetWeekOfYear(DateTime.Now);
                this.Title = TryAndGetField <string>(bonusItem, "title");
                if (card == null)
                {
                    this.Id   = TryAndGetField <long>(bonusItem, "id");
                    this.Link = TryAndGetField <string>(bonusItem, "link");
                }
                else
                {
                    var productOfCard = card["products"] as JArray;
                    this.Id   = TryAndGetField <long>(card, "id");
                    this.Link = TryAndGetField <string>(productOfCard[0] as JObject, "link");
                }
                this.Brand = TryAndGetField <string>(bonusItem, "brand");
                if (bonusItem.ContainsKey("discount"))
                {
                    var discount = bonusItem["discount"] as JObject;
                    var price    = bonusItem["price"] as JObject;


                    if (discount.ContainsKey("fromPrice"))
                    {
                        this.FromPriceInCents = discount["fromPrice"].Value <int>();
                    }
                    else if (price != null && price.ContainsKey("was"))
                    {
                        this.FromPriceInCents = ParseDecimalPrice(price["was"].Value <string>());
                    }

                    if (discount.ContainsKey("forPrice"))
                    {
                        this.ForPriceInCents = discount["forPrice"].Value <int>();
                    }
                    else if (price != null && price.ContainsKey("now"))
                    {
                        this.ForPriceInCents = ParseDecimalPrice(price["now"].Value <string>());
                    }

                    this.StartDate = TryAndGetField <DateTime>(discount, "startDate");
                    this.EndDate   = TryAndGetField <DateTime>(discount, "endDate");

                    if (discount.ContainsKey("text"))
                    {
                        this.DiscountText = discount["text"].Value <string>();
                    }
                    else if (shield != null && shield.ContainsKey("text"))
                    {
                        this.DiscountText = shield["text"].Value <string>();
                    }

                    this.Store = TryAndGetField <string>(control, "theme");
                    if (this.Store == null)
                    {
                        this.Store = TryAndGetField <string>(control, "bonusType");
                    }
                    if (this.Store == null || this.Store.Equals("bonus"))
                    {
                        this.Store = "ah";
                    }
                }

                this.UnitSize = TryAndGetField <string>(bonusItem, "unitSize");
                this.Category = TryAndGetField <string>(bonusItem, "category");

                this.NumberOfProducts = TryAndGetField <int>(bonusItem, "numberOfProducts");
                var fromPrice        = this.FromPriceInCents;
                var forPrice         = this.ForPriceInCents;
                var amountOfProducts = 1;
                BonusTextAnalyser.AnalyseBonusText(this.DiscountText, ref fromPrice, ref forPrice, ref amountOfProducts);
                this.FromPriceInCents         = fromPrice;
                this.ForPriceInCents          = forPrice;
                this.ActiveAtNumberOfProducts = amountOfProducts;
            }
            else
            {
                this.Id = long.MinValue;
            }
        }
Example #32
0
 private void AssertContainsKey(JObject j, string key)
 {
     Assert.IsTrue(j.ContainsKey(key), $"JObject should contain key: {key}");
 }
Example #33
0
        void m_gs_DownloadProgress(object sender, JObject song, long percentage)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new DownloadProgress(m_gs_DownloadProgress), new object[] { sender, song, percentage });
                return;
            }

            log("Downloading " + (string)song["Name"] + " " + percentage + "%");

            if (percentage > 90 && !song.ContainsKey("AlreadyTriggered"))
            {
                song["AlreadyTriggered"] = true;
                Dequeue(1);
            }
            m_updateQueue.Enqueue(song);
        }
Example #34
0
        /**
         * This is the lowest level request method. Use higher level if possible.
         */
        public JObject Request(string uri, string method, ClientType client, JObject parameters, JObject headerOverrides, RequestHandler handler, object state)
        {
            JObject request = new JObject();
            request.Add("parameters", parameters);
            JObject header = new JObject();
            if (m_token != null)
            {
                string t = GenerateToken(method);
                header.Add("token", t);
            }
            header.Add("session", m_sid);

            if (client == ClientType.HTML)
                header.Add("client", "htmlshark");
            else if (client == ClientType.JSQueue)
                header.Add("client", "jsqueue");
            else
                throw new Exception("ClientType not supported.");

            header.Add("clientRevision", "20101012.37");
            header.Add("privacy", 0);
            // Somehow this uuid is important, and I don't really know what it is, the UUID of the JSQueue flash object ?
            header.Add("uuid", "6BFBFCDE-B44F-4EC5-AF69-76CCC4A2DAD0");
            header.Add("country", m_countryObj);
            request.Add("header", header);
            request.Add("method", method);

            if (headerOverrides != null)
            {
                IDictionaryEnumerator e = headerOverrides.GetEnumerator();
                while (e.MoveNext())
                {
                    if (header.ContainsKey(e.Key))
                        header[e.Key] = e.Value;
                    else
                        header.Add(e.Key, e.Value);
                }
            }
            string requestStr = request.ToString().Replace("\n", "").Replace(" ", "").Replace("\r", "");
            CookieAwareWebClient wc = new CookieAwareWebClient(m_cc);
            wc.UploadStringCompleted += new UploadStringCompletedEventHandler(GSRequestHandler);
            wc.UploadStringAsync(new Uri(uri + "?" + method), "POST", requestStr, new object[]{ handler, state });
            if(RequestSent != null)
                RequestSent(this, requestStr);
            return request;
        }