Example #1
0
    public void Manual()
    {
      JArray array = new JArray();
      JValue text = new JValue("Manual text");
      JValue date = new JValue(new DateTime(2000, 5, 23));

      array.Add(text);
      array.Add(date);

      string json = array.ToString();
      // [
      //   "Manual text",
      //   "\/Date(958996800000+1200)\/"
      // ]
    }
Example #2
0
        public static void vaildData()
        {
            JArray ja = (JArray)JsonConvert.DeserializeObject(File.ReadAllText(@"input/mergeresult_final.json"));
            JArray jaTemp = new JArray();
            DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Users\GIS-615\SkyDrive\论文&项目\研究生毕业论文\数据\GetPoiTimeLineWithAzure\原始数据");
            foreach (JObject jo in ja)
            {
                int count = 0;
                foreach (FileInfo file in dirInfo.GetFiles())
                {
                    string filename = file.Name.Substring(0, file.Name.Length - 5);
                    if (jo["poiid"].ToString().Equals(filename))
                    {
                        count++;
                        break;
                    }
                }
                if (count == 0)
                {
                    jaTemp.Add(jo);
                }
            }

            File.WriteAllText(@"output//nullData.json", jaTemp.ToString());
        }
        public void Example()
        {
            #region Usage
            JArray array = new JArray();
            array.Add("Manual text");
            array.Add(new DateTime(2000, 5, 23));

            JObject o = new JObject();
            o["MyArray"] = array;

            string json = o.ToString();
            // {
            //   "MyArray": [
            //     "Manual text",
            //     "2000-05-23T00:00:00"
            //   ]
            // }
            #endregion
        }
Example #4
0
 public static JArray MergeJArray(JArray arr1, JArray arr2)
 {
     if (arr2.Count > 0)
     {
         foreach (JObject jo in arr2)
         {
             arr1.Add(jo);
         }
     }
     return arr1;
 }
Example #5
0
    public void GenericCollectionCopyTo()
    {
      JArray j = new JArray();
      j.Add(new JValue(1));
      j.Add(new JValue(2));
      j.Add(new JValue(3));
      Assert.AreEqual(3, j.Count);

      JToken[] a = new JToken[5];

      ((ICollection<JToken>) j).CopyTo(a, 1);

      Assert.AreEqual(null, a[0]);

      Assert.AreEqual(1, (int) a[1]);

      Assert.AreEqual(2, (int) a[2]);

      Assert.AreEqual(3, (int) a[3]);

      Assert.AreEqual(null, a[4]);

    }
Example #6
0
        public void SaveHooks(Dictionary <string, List <Hook> > hooks)
        {
            JArray arr = ob["completions"] as JArray;

            foreach (string nameSpace in hooks.Keys)
            {
                foreach (Hook hook in hooks[nameSpace])
                {
                    if (hook.Name != "")
                    {
                        arr?.Add(hook.Name);
                    }
                }
            }
        }
Example #7
0
        public void SaveClassFuncs(Dictionary <string, List <Function> > classFuncs)
        {
            JArray arr = ob["completions"] as JArray;

            foreach (string nameSpace in classFuncs.Keys)
            {
                foreach (Function func in classFuncs[nameSpace])
                {
                    arr?.Add(new JObject
                    {
                        { "trigger", $"{func.Name}" },
                        { "contents", BuildGlobalSnippet(func) }
                    });
                }
            }
        }
        public static JContainer ToJContainer(this ICollection target)
        {
            if (target != null)
            {
                var jobjarray = new JArray();

                foreach (var item in target)
                {
                    jobjarray.Add(item.ToJContainer());
                }

                return jobjarray;
            }

            return null;
        }
Example #9
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetUser(string query_loginName, string query_username)
        {
            JArray ja = new JArray();

            try
            {
                using (venuesEntities db = new venuesEntities())
                {

                    string strSql = "SELECT su.User_Id,su.User_LoginName,su.User_Name,su.User_Password,sd.DA_Name,sd.DA_Code,su.User_TypeId FROM tbl_sys_user AS su LEFT JOIN tbl_sys_dictionary AS sd ON su.User_TypeId=sd.DA_Id where 1=1 ";
                    if (query_loginName != "")
                    {
                        strSql += " and su.User_LoginName='" + query_loginName + "'";
                    }
                    else if (query_username != "")
                    {
                        strSql += " and su.User_Name='" + query_username + "'";
                    }

                    ObjectQuery<DbDataRecord> results = db.CreateQuery<DbDataRecord>(strSql);

                    foreach (var item in results)
                    {
                        ja.Add(
                            new JObject(
                                new JProperty("User_Id", item["User_Id"].ToString()),
                                new JProperty("User_LoginName", item["User_LoginName"].ToString()),
                                new JProperty("User_Name", item["User_Name"].ToString()),
                                new JProperty("User_Password", item["User_Password"].ToString()),
                                new JProperty("DA_Name", item["DA_Name"].ToString()),
                                new JProperty("User_TypeId", item["User_TypeId"].ToString()),
                                new JProperty("DA_Code", item["DA_Code"].ToString())
                                )
                            );
                    };
                }
            }
            catch (Exception e)
            {
                addLog(KeyManager.LogTypeId_Error, KeyManager.CUR_USERID, KeyManager.MENUS.Menu_SystemUsersManager, "查询用户列表,User_LoginName=" + query_loginName + ",User_Name=" + query_username + ",错误信息:" + e.Message);
            }
            addLog(KeyManager.LogTypeId_Option, KeyManager.CUR_USERID, KeyManager.MENUS.Menu_SystemUsersManager, "查询用户列表,User_LoginName=" + query_loginName + ",User_Name=" + query_username);
            return ja.ToString();
        }
Example #10
0
 private static void DiffCategories()
 {
     //type1
     int[] typeArray = new int[]{
         33,
         116,179,180,182,183,
         184,185,186,187,188,
         195,196,197,198,
         199,200,201,202,203,
         204,205,206,207,208,
         234,239,240,243,244,
         245,246,607
     };
     //去掉252,254,20,156,219,45,52,671,678,189, 220,221,222,223,224,
     //225,226,227,228,229,230,231,232,233,235,236,237,238,250,604,677,627,628
     List<int> typeList = new List<int>(typeArray);
     JArray ja = (JArray)JsonConvert.DeserializeObject(File.ReadAllText(@"../../output/type1/typetrue.json"));
     //foreach (int num in typeList)
     //{
     int num = 252;
         string path = @"../../output/45/";
         //if (!Directory.Exists(path))
         //{
         //    Directory.CreateDirectory(path);
         //}
         JArray jaType = new JArray();
         foreach (JObject jo in ja)
         {
             if (Int32.Parse(jo["category"].ToString()) == num)
             {
                 jaType.Add(jo);
                 Console.WriteLine("jaType :" + DateTime.Now.ToLocalTime().ToString() + ";" + jo["title"].ToString() + ";" + jo["poiid"].ToString());
                 streamWriter.WriteLine("jaType :" + DateTime.Now.ToLocalTime().ToString() + ";" + jo["title"].ToString() + ";" + jo["poiid"].ToString());
             }
             Console.WriteLine("jaType:" + DateTime.Now.ToLocalTime().ToString() + ";" + jaType.Count.ToString());
             streamWriter.WriteLine("jaType:" + DateTime.Now.ToLocalTime().ToString() + ";" + jaType.Count.ToString());
             File.WriteAllText(path + "/" + num + ".json", jaType.ToString());
         }
     //}
 }
Example #11
0
 public override string ToString()
 {
     JObject json = new JObject();
     json["type"] = Signable.GetType().Name;
     using (MemoryStream ms = new MemoryStream())
     using (BinaryWriter writer = new BinaryWriter(ms, Encoding.UTF8))
     {
         Signable.SerializeUnsigned(writer);
         writer.Flush();
         json["hex"] = ms.ToArray().ToHexString();
     }
     JArray scripts = new JArray();
     for (int i = 0; i < signatures.Length; i++)
     {
         if (signatures[i] == null)
         {
             scripts.Add(null);
         }
         else
         {
             scripts.Add(new JObject());
             scripts[i]["redeem_script"] = redeemScripts[i].ToHexString();
             JArray sigs = new JArray();
             foreach (var pair in signatures[i])
             {
                 JObject signature = new JObject();
                 signature["pubkey"] = pair.Key.EncodePoint(true).ToHexString();
                 signature["signature"] = pair.Value.ToHexString();
                 sigs.Add(signature);
             }
             scripts[i]["signatures"] = sigs;
             scripts[i]["completed"] = completed[i];
         }
     }
     json["scripts"] = scripts;
     return json.ToString();
 }
Example #12
0
        string GetAnnounceJson(string uri, bool shuttingDown)
        {
            var env_ext = new JArray ();
            foreach (var e in envelopes)
                env_ext.Add (e);
            if (extensions != null)
                env_ext.Add (extensions);

            var data = new JArray {
                PacketVersion,
                Identity,
                Sector,
                shuttingDown ? 0.0 : Weight, // weight
                shuttingDown ? 0.1 : SendInterval,
                uri,
                env_ext,
                (uri != null && !shuttingDown) ? EncodeActionList () : new JArray(),
                (DateTime.UtcNow - new DateTime (1970, 1, 1)).TotalMilliseconds
            };

            return JSON.Stringify (data);
        }
Example #13
0
        public static Result FromJsonFirefox(JObject obj)
        {
            //Log ("protocol", $"from result: {obj}");
            JObject o;

            if (obj["ownProperties"] != null && obj["prototype"]?["class"]?.Value <string>() == "Array")
            {
                var ret        = new JArray();
                var arrayItems = obj["ownProperties"];
                foreach (JProperty arrayItem in arrayItems)
                {
                    if (arrayItem.Name != "length")
                    {
                        ret.Add(arrayItem.Value["value"]);
                    }
                }
                o = JObject.FromObject(new
                {
                    result = new
                    {
                        value = ret
                    }
                });
            }
            else if (obj["result"] is JObject && obj["result"]?["type"]?.Value <string>() == "object")
            {
                if (obj["result"]["class"].Value <string>() == "Array")
                {
                    o = JObject.FromObject(new
                    {
                        result = new
                        {
                            value = obj["result"]["preview"]["items"]
                        }
                    });
                }
                else if (obj["result"]?["preview"] != null)
                {
                    o = JObject.FromObject(new
                    {
                        result = new
                        {
                            value = obj["result"]?["preview"]?["ownProperties"]?["value"]
                        }
                    });
                }
                else
                {
                    o = JObject.FromObject(new
                    {
                        result = new
                        {
                            value = obj["result"]
                        }
                    });
                }
            }
            else if (obj["result"] != null)
            {
                o = JObject.FromObject(new
                {
                    result = new
                    {
                        value       = obj["result"],
                        type        = obj["resultType"],
                        description = obj["resultDescription"]
                    }
                });
            }
            else
            {
                o = JObject.FromObject(new
                {
                    result = new
                    {
                        value = obj
                    }
                });
            }
            bool resultHasError = obj["hasException"] != null && obj["hasException"].Value <bool>();

            if (resultHasError)
            {
                return(new Result(obj["exception"] as JObject, resultHasError, obj));
            }
            return(new Result(o, false, obj));
        }
        protected override void ProcessRequest()
        {
            if (!Modified())
            {
                Response.StatusCode = 304;
                return;
            }

            //
            // Generate the SMD object graph.
            //

            IRpcServiceDescriptor service = TargetService.GetDescriptor();

            JObject smd = new JObject();
            
            smd.Put("SMDVersion", ".1");
            smd.Put("objectName", JsonRpcServices.GetServiceName(TargetService));
            smd.Put("serviceType", "JSON-RPC");
            smd.Put("serviceURL", Request.FilePath); // TODO: Check whether this should be an absolute path from the protocol root.

            IRpcMethodDescriptor[] methods = service.GetMethods();

            if (methods.Length > 0) // TODO: Check if methods entry can be skipped if there are none.
            {
                JArray smdMethods = new JArray();

                foreach (IRpcMethodDescriptor method in methods)
                {
                    JObject smdMethod = new JObject();
                    smdMethod.Put("name", method.Name);
                
                    IRpcParameterDescriptor[] parameters = method.GetParameters();

                    if (parameters.Length > 0) // TODO: Check if parameters entry can be skipped if there are none.
                    {
                        JArray smdParameters = new JArray();

                        foreach (IRpcParameterDescriptor parameter in parameters)
                        {
                            JObject smdParameter = new JObject();
                            smdParameter.Put("name", parameter.Name);
                            smdParameters.Add(smdParameter);
                        }

                        smdMethod.Put("parameters", smdParameters);
                    }

                    smdMethods.Add(smdMethod);
                }

                smd.Put("methods", smdMethods);
            }

            //
            // Generate the response.
            //

            if (HasLastModifiedTime)
            {
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetLastModified(LastModifiedTime);
            }

            Response.ContentType = "text/plain";

            Response.AppendHeader("Content-Disposition", 
                "attachment; filename=" + service.Name + ".smd");

            JsonTextWriter writer = new JsonTextWriter(Response.Output);
            writer.WriteValue(smd);
        }
Example #15
0
        public MainWindow()
        {
            InitializeComponent();
            string patches;

            if (File.Exists("patches.json"))
            {
                // Read File
                patches = File.ReadAllText("patches.json");
            }
            else
            {
                try {
                    using (WebClient wc = new WebClient()) {
                        // Download the patches.json from GitHub
                        string  onlinePatchesString = wc.DownloadString(PatchesUrl);
                        JObject webPatches          = JsonConvert.DeserializeObject <JObject>(onlinePatchesString);

                        JArray defaultPatches = new JArray();
                        var    gamesObj       = (JObject)webPatches;
                        foreach (var gameObj in gamesObj)
                        {
                            JObject defaultPatch = new JObject(
                                new JProperty("Name", gameObj.Key),
                                new JProperty("Exec_name", gamesObj[gameObj.Key]["Exec_name"]),
                                new JProperty("Offset", gamesObj[gameObj.Key]["Offset"]),
                                new JProperty("Patches", gamesObj[gameObj.Key]["Exec_namePatches"]));
                            defaultPatches.Add(defaultPatch);
                        }
                        var file = File.CreateText("patches.json");
                        patches = defaultPatches.ToString();
                        Console.WriteLine(patches);

                        var json = JsonConvert.SerializeObject(defaultPatches, Formatting.Indented);
                        file.Write(json);
                        file.Close();
                    }
                } catch (WebException e) {
                    Console.WriteLine("Error download online patches... Using default");
                    Console.WriteLine(e);
                    // Create File
                    Console.WriteLine("No patches.json found, creating new Patches.json");
                    JArray defaultPatches = new JArray();

                    JObject defaultPatch = new JObject(
                        new JProperty("Name", "Moekuri: Adorable + Tactical SRPG"),
                        new JProperty("Exec_name", "moekurii.exe"),
                        new JProperty("Offset", "0x2B9"),
                        new JProperty("Patches", "0x3A"));
                    defaultPatches.Add(defaultPatch);
                    patches = defaultPatches.ToString();

                    var file = File.CreateText("patches.json");

                    var json = JsonConvert.SerializeObject(defaultPatches, Formatting.Indented);
                    file.Write(json);
                    file.Close();
                }
            }

            dynamic games = JsonConvert.DeserializeObject(patches);

            foreach (var game in games)
            {
                GameListElement.Children.Add(new System.Windows.Controls.RadioButton {
                    Content    = game.Name,
                    GroupName  = "GameButtons",
                    FontFamily = new FontFamily("Arial"),
                    FontSize   = 14.0,
                    Margin     = new Thickness(15, 5, 15, 0),
                    Foreground = Brushes.White
                });
                Console.WriteLine("{0} {1} {2} {3}", game.Name, game.Exec_name, game.Offset, game.Patches);
                JObject gameObject = new JObject();
                gameObject["Name"]                = (string)game.Name;
                gameObject["Exec_name"]           = (string)game.Exec_name;
                gameObject["Offset"]              = (string)game.Offset;
                gameObject["Patches"]             = (string)game.Patches;
                gamesObject[game.Name.ToString()] = gameObject;
            }
        }
Example #16
0
    public void Remove()
    {
      JValue v = new JValue(1);
      JArray j = new JArray();
      j.Add(v);

      Assert.AreEqual(1, j.Count);

      Assert.AreEqual(false, j.Remove(new JValue(1)));
      Assert.AreEqual(false, j.Remove(null));
      Assert.AreEqual(true, j.Remove(v));
      Assert.AreEqual(false, j.Remove(v));

      Assert.AreEqual(0, j.Count);
    }
Example #17
0
    public void Item()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(2);
      JValue v3 = new JValue(3);
      JValue v4 = new JValue(4);

      JArray j = new JArray();

      j.Add(v1);
      j.Add(v2);
      j.Add(v3);

      j[1] = v4;

      Assert.AreEqual(null, v2.Parent);
      Assert.AreEqual(-1, j.IndexOf(v2));
      Assert.AreEqual(j, v4.Parent);
      Assert.AreEqual(1, j.IndexOf(v4));
    }
Example #18
0
        private static JToken GetJsonSchehma(ISerializationBase serialization, bool getDocumentation = false)
        {
            var xmlValue = serialization as Hyak.ServiceModel.XmlElement;

            if (xmlValue != null)
            {
                return("(xml)");
            }

            var jsonValue = serialization as Hyak.ServiceModel.JsonValue;

            if (jsonValue != null)
            {
                var knownObjectType = jsonValue.Type as Hyak.ServiceModel.KnownObjectType;
                if (knownObjectType != null)
                {
                    var schema = new JObject();
                    foreach (var member in jsonValue.Members)
                    {
                        if ((member is JsonValue && ((JsonValue)member).PassThrough) ||
                            (member is JsonArray && ((JsonArray)member).PassThrough) ||
                            (member is JsonDictionary && ((JsonDictionary)member).PassThrough))
                        {
                            return(GetJsonSchehma(member, getDocumentation));
                        }

                        schema[member.Name] = GetJsonSchehma(member, getDocumentation);
                    }
                    return(schema);
                }

                var knownType = jsonValue.Type as Hyak.ServiceModel.KnownType;
                if (knownType != null && !getDocumentation)
                {
                    return(GetJsonSchema(knownType));
                }
                else if (knownType != null && getDocumentation)
                {
                    return(jsonValue.PropertyBinding != null && jsonValue.PropertyBinding.Documentation != null
                        ? jsonValue.PropertyBinding.Documentation.Text
                        : string.Empty);
                }

                throw new InvalidOperationException("Should not reach here. jsonValue.Type  = " + jsonValue.Type);
            }

            var jsonArray = serialization as Hyak.ServiceModel.JsonArray;

            if (jsonArray != null)
            {
                var schema = new JArray();
                if (jsonArray.ElementFormat != null)
                {
                    schema.Add(GetJsonSchehma(jsonArray.ElementFormat, getDocumentation));
                }
                else
                {
                    var knownType = jsonArray.Type.GenericParameters[0] as Hyak.ServiceModel.KnownType;
                    if (knownType != null && !getDocumentation)
                    {
                        schema.Add(GetJsonSchema(knownType));
                    }
                    else if (knownType != null && getDocumentation)
                    {
                        schema.Add(jsonArray.PropertyBinding.Documentation != null
                        ? jsonArray.PropertyBinding.Documentation.Text
                        : string.Empty);
                    }
                    else
                    {
                        throw new InvalidOperationException("Should not reach here. array's elementType  = " + jsonArray.Type.GenericParameters[0]);
                    }
                }

                return(schema);
            }

            var jsonDict = serialization as Hyak.ServiceModel.JsonDictionary;

            if (jsonDict != null)
            {
                return(new JObject());
            }

            throw new InvalidOperationException("Should not reach here for " + serialization.GetType());
        }
Example #19
0
        // Edit
        public void Edit(int id, string group, string name, string formalName, string desc)
        {
            JArray arrEquip = new JArray();

            Equipment equipment = db.Equipments.Find(id);
            bool      change    = false;

            if (equipment.Group != (string.IsNullOrEmpty(group) ? null : group.Trim()))
            {
                JObject obj = new JObject();
                obj.Add("Type", "Group");
                obj.Add("oValue", equipment.Group);
                obj.Add("nValue", group);
                arrEquip.Add(obj);

                equipment.Group = group;
                change          = true;
            }

            if (equipment.Name != (string.IsNullOrEmpty(name) ? null : name.Trim()))
            {
                JObject obj = new JObject();
                obj.Add("Type", "Name");
                obj.Add("oValue", equipment.Name);
                obj.Add("nValue", name);
                arrEquip.Add(obj);

                equipment.Name = name;
                change         = true;
            }

            if (equipment.FormalName != (string.IsNullOrEmpty(formalName) ? null : formalName.Trim()))
            {
                JObject obj = new JObject();
                obj.Add("Type", "FormalName");
                obj.Add("oValue", equipment.FormalName);
                obj.Add("nValue", formalName);
                arrEquip.Add(obj);

                equipment.FormalName = formalName;
                change = true;
            }

            if (equipment.Desc != (string.IsNullOrEmpty(desc) ? null : desc.Trim()))
            {
                JObject obj = new JObject();
                obj.Add("Type", "Desc");
                obj.Add("oValue", equipment.Desc);
                obj.Add("nValue", desc);
                arrEquip.Add(obj);

                equipment.Desc = desc;
                change         = true;
            }

            if (change)
            {
                Log log = new Log
                {
                    ActionType = "P.Equipment",
                    RefId      = equipment.Id,
                    Date       = DateTime.Now,
                    User       = User.Identity.Name,
                    ChangeData = arrEquip.ToString()
                };

                db.Add(log);
                db.Entry(equipment).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
Example #20
0
        public JObject UpdateDocument(JObject document, IUpdateEntry entry)
        {
            var anyPropertyUpdated = false;

            foreach (var property in entry.EntityType.GetProperties())
            {
                if (entry.EntityState == EntityState.Added ||
                    entry.IsModified(property))
                {
                    var storeName = property.Cosmos().PropertyName;
                    if (storeName != "")
                    {
                        var value = entry.GetCurrentValue(property);
                        document[storeName] = value != null?JToken.FromObject(value) : null;

                        anyPropertyUpdated = true;
                    }
                }
            }

            foreach (var ownedNavigation in entry.EntityType.GetNavigations())
            {
                var fk = ownedNavigation.ForeignKey;
                if (!fk.IsOwnership ||
                    ownedNavigation.IsDependentToPrincipal() ||
                    fk.DeclaringEntityType.IsDocumentRoot())
                {
                    continue;
                }

                var nestedDocumentSource = _database.GetDocumentSource(fk.DeclaringEntityType);
                var nestedValue          = entry.GetCurrentValue(ownedNavigation);
                if (nestedValue == null)
                {
                    if (document[ownedNavigation.Name] != null)
                    {
                        document[ownedNavigation.Name] = null;
                        anyPropertyUpdated             = true;
                    }
                }
                else if (fk.IsUnique)
                {
                    var nestedEntry = ((InternalEntityEntry)entry).StateManager.TryGetEntry(nestedValue, fk.DeclaringEntityType);
                    if (nestedEntry == null)
                    {
                        return(document);
                    }

                    if (document[ownedNavigation.Name] is JObject nestedDocument)
                    {
                        nestedDocument = nestedDocumentSource.UpdateDocument(nestedDocument, nestedEntry);
                    }
                    else
                    {
                        nestedDocument = nestedDocumentSource.CreateDocument(nestedEntry);
                    }

                    if (nestedDocument != null)
                    {
                        document[ownedNavigation.Name] = nestedDocument;
                        anyPropertyUpdated             = true;
                    }
                }
                else
                {
                    var array = new JArray();
                    foreach (var dependent in (IEnumerable)nestedValue)
                    {
                        var dependentEntry = ((InternalEntityEntry)entry).StateManager.TryGetEntry(dependent, fk.DeclaringEntityType);
                        if (dependentEntry == null)
                        {
                            continue;
                        }

                        array.Add(_database.GetDocumentSource(dependentEntry.EntityType).CreateDocument(dependentEntry));
                    }

                    document[ownedNavigation.Name] = array;
                    anyPropertyUpdated             = true;
                }
            }

            return(anyPropertyUpdated ? document : null);
        }
Example #21
0
        // encode bytes into legible json tag object.
        private void EncodeTag(byte[] tag, JArray jArray)
        {
            if (tag.Length == 0)
            {
                return;
            }

            // if start byte is not opening of tag, treat it as entry.
            if (tag[0] != 0x2)
            {
                EncodeEntry(tag, jArray);
            }
            else
            {
                /*
                 * // [0] -> 0x2 (opening of tag)
                 * // [1] -> byte (type of tag)
                 * // [2] -> byte (type of length)
                 * // [..] -> length data (depending on type of length)
                 * // [..length..] -> data
                 * // [last] -> 0x3 (closing of tag)
                 *
                 * byte lengthType = tag[2];
                 * int totalLength;
                 * byte[] tagData;
                 *
                 * if (lengthType < 0xf0)
                 * {
                 *  // length type itself is a length, including the length type byte itself.
                 *  // total length -> [0] + [1] + (length type = [2...data...]) + [last]
                 *  totalLength = lengthType + 3;
                 *  tagData = new byte[lengthType - 1];
                 *  Array.Copy(tag, 3, tagData, 0, lengthType - 1);
                 * }
                 * else if (lengthType == 0xf0)
                 * {
                 *  // trailing byte is the length.
                 *  // total length -> [0] + [1] + [2] + [length byte] + (length byte = [...data...]) + [last]
                 *  totalLength = tag[3] + 5;
                 *  tagData = new byte[tag[3]];
                 *  Array.Copy(tag, 4, tagData, 0, tag[3]);
                 * }
                 * else if (lengthType == 0xf1)
                 * {
                 *  // trailing byte * 256 is the length.
                 *  // total length -> [0] + [1] + [2] + [length byte] + (length byte * 256 = [...data...]) + [last]
                 *  totalLength = (tag[3] * 256) + 5;
                 *  tagData = new byte[tag[3] * 256];
                 *  Array.Copy(tag, 4, tagData, 0, tag[3] * 256);
                 * }
                 * else if (lengthType == 0xf2)
                 * {
                 *  // (trailing byte << 8) + (next byte) is the length. (int16)
                 *  // total length -> [0] + [1] + [2] + [l1] + [l2] + ([...data...]) + [last]
                 *  int dataLength = (tag[3] << 8) + tag[4];
                 *  totalLength = dataLength + 6;
                 *  tagData = new byte[dataLength];
                 *  Array.Copy(tag, 5, tagData, 0, dataLength);
                 * }
                 * else if (lengthType == 0xf3)
                 * {
                 *  // (trailing byte << 16) + (next byte << 8) + (next byte) is the length. (int24)
                 *  // total length -> [0] + [1] + [2] + [l1] + [l2] + [l3] + ([...data...]) + [last]
                 *  int dataLength = (tag[3] << 16) + (tag[4] << 8) + tag[5];
                 *  totalLength = dataLength + 7;
                 *  tagData = new byte[dataLength];
                 *  Array.Copy(tag, 6, tagData, 0, dataLength);
                 * }
                 * else if (lengthType == 0xf4)
                 * {
                 *  // (trailing byte << 24) + (next byte << 16) + (next byte << 8) + (next byte) is the length. (int32)
                 *  // total length -> [0] + [1] + [2] + [l1] + [l2] + [l3] + [l4] + ([...data...]) + [last]
                 *  int dataLength = (tag[3] << 24) + (tag[4] << 16) + (tag[5] << 8) + tag[6];
                 *  totalLength = dataLength + 8;
                 *  tagData = new byte[dataLength];
                 *  Array.Copy(tag, 7, tagData, 0, dataLength);
                 * }
                 * else throw new Exception();
                 *
                 * // check tag closing byte.
                 * if (tag[totalLength - 1] != 0x3) throw new Exception();
                 *
                 * jArray.Add(CreateTagJObject(tag[1], tagData));
                 *
                 * byte[] field = new byte[tag.Length - totalLength];
                 * Array.Copy(tag, totalLength, field, 0, field.Length);
                 * EncodeField(field, jArray);*/

                byte tagType = tag[1];

                // length byte + tag
                byte[] tagData = new byte[tag.Length - 2];
                Array.Copy(tag, 2, tagData, 0, tagData.Length);

                byte[] tail = SplitByLength(ref tagData);

                // check tag closing byte.
                if (tail[0] != 0x3)
                {
                    throw new Exception();
                }

                jArray.Add(new JObject(
                               new JProperty("EntryType", "Tag"),
                               new JProperty("EntryValue", CreateTagJObject(tagType, tagData))));

                // remaining entry after tag closing byte
                byte[] entry = new byte[tail.Length - 1];
                Array.Copy(tail, 1, entry, 0, entry.Length);
                EncodeEntry(entry, jArray);
            }
        }
Example #22
0
        async Task OnStreamingMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken)
        {
            dynamic channelData = new JObject();

            channelData.originalActivity = new JObject();
            IMessageActivity act = turnContext.Activity;

            channelData.originalActivity.id = act.Id;
            var resp = MessageFactory.Text("OK");

            resp.ChannelData = channelData;

            if (turnContext.Activity.Attachments != null)
            {
                var attachments = new JArray();
                foreach (var a in turnContext.Activity.Attachments)
                {
                    var stream = a.Content as Stream;
                    //using (var reader = new BinaryReader(stream))
                    {
                        // TODO - find the right way to read the whole stream
                        var     t    = SlurpStream(stream); //  reader.ReadBytes((int)stream.Length);
                        dynamic atch = new JObject();
                        atch.contentType  = a.ContentType;
                        atch.contentUrl   = Convert.ToBase64String(t);
                        atch.thumbnailUrl = a.ThumbnailUrl;
                        attachments.Add(atch);
                    }
                }
                channelData.originalActivity.attachments = attachments;
            }

            if (act.Text.StartsWith("attach"))
            {
                var urls        = act.Text.Split(" ");
                var attachments = new List <Attachment>();
                foreach (var url in urls.Skip(1))
                {
                    byte[] rawBytes;
                    using (WebClient webClient = new WebClient())
                    {
                        rawBytes = webClient.DownloadData(url);
                    }

                    var dataUri = "data:text/plain;base64," + Convert.ToBase64String(rawBytes);

                    var attachment = new Attachment
                    {
                        Name        = "hello.png",
                        ContentType = "image/png",
                        ContentUrl  = dataUri
                    };
                    attachments.Add(attachment);
                }
                resp.Attachments = attachments;
            }


            channelData.originalActivity.text = act.Text;
            await turnContext.SendActivityAsync(resp, cancellationToken);
        }
Example #23
0
        public JObject InfoCompeVagues(DBPatinVitesse db)
        {
            var queryCompe =
                from compe in db.Competition
                where compe.NoCompetition == noCompeti
                select compe;

            ;

            JObject programme = new JObject();

            programme.Add("Nom", queryCompe.First().Commentaire);
            JArray ja = new JArray();

            programme.Add("Groupes", ja);

            var pc = from progcourse in db.ProgCourses
                     where progcourse.NoCompetition == noCompeti
                     select progcourse.Groupe;

            var     grppreced     = string.Empty;
            var     vgpreced      = string.Empty;
            JArray  vaguesGroupes = new JArray();
            JArray  patineurVague = new JArray();
            JObject vagueJson     = null;

            // Sélection de tous les temps des patineurs de la compétition
            var laTotal = from patvag in db.PatVagues
                          join patcmp in db.PatineurCompe on patvag.NoPatCompe equals patcmp.NoPatCompe
                          join patineur in db.Patineur on patcmp.NoPatineur equals patineur.NoPatineur
                          join club in db.Club on patineur.NoClub equals club.NoClub
                          join vag in db.Vagues on patvag.CleTVagues equals vag.CleTVagues
                          join progcrs in db.ProgCourses on vag.CleDistancesCompe equals progcrs.CleDistancesCompe
                          join diststd in db.DistanceStandards on progcrs.NoDistance equals diststd.NoDistance
                          join cmnt in db.Commentaire on patvag.Juge equals cmnt.Code
                          where patvag.NoPatCompe == patcmp.NoPatCompe &&
                          patcmp.NoPatineur == patineur.NoPatineur &&
                          patineur.NoClub == club.NoClub &&
                          patvag.CleTVagues == vag.CleTVagues &&
                          vag.CleDistancesCompe == progcrs.CleDistancesCompe &&
                          progcrs.NoDistance == diststd.NoDistance &&
                          patcmp.NoCompetition == noCompeti &&
                          progcrs.NoCompetition == noCompeti
                          select new ResultatObj()
            {
                NoPatineur      = patineur.NoPatineur,
                Nom             = patineur.Nom + "," + patineur.Prenom,
                Club            = club.NomClub,
                NoCasque        = patvag.NoCasque,
                Temps           = patvag.Temps,
                Point           = patvag.Point,
                Rang            = patvag.Rang,
                Code            = cmnt.CodeAction.Replace("NIL", string.Empty),
                NoVague         = vag.NoVague,
                Epreuve         = vag.Qual_ou_Fin,
                Groupe          = patcmp.Groupe,
                LongueurEpreuve = diststd.LongueurEpreuve,
                NoBloc          = progcrs.NoBloc,
                Sexe            = patineur.Sexe
            };

            var nbp = laTotal.Count();

            //var laTotale1 = laTotal.OrderBy(z => z, comparer ).ThenBy(z => z.NoBloc).ThenBy(z => z.Rang).ThenBy(z => z.Point).ThenBy(z => z.NoCasque);
            //var laTotale1 = laTotal.OrderBy(z => z, comparer);
            //var laTotale1 = laTotal.OrderBy(z => z.Groupe).ThenBy(z => z.Sexe).ThenBy(z => z.ChiffreVague).ThenBy(z => z.LettreVague).ThenBy(z => z.NoBloc).ThenBy(z => z.Rang).ThenBy(z => z.Point).ThenBy(z => z.NoCasque);
            //var laTotale1 = laTotal.OrderBy(z => z.Groupe + z.Sexe + z.NoVague.PadLeft(6,'0') + z.NoBloc.ToString().PadLeft(3,'0') + z.Rang.ToString().PadLeft(4,'0')).ThenBy(z => z.Point).ThenBy(z => z.NoCasque);
            bool         m         = this.mixte;
            TrieResultat comparer  = new TrieResultat(m);
            var          laTotale1 = laTotal.ToList().OrderBy(z => z, comparer).ToList();

            nbp = laTotale1.Count();
            var laTotale2 = laTotale1.ToList();

            nbp = laTotale2.Count();
            //foreach (var ab in laTotale2)
            //{
            //    Console.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}", ab.Groupe, ab.NoVague, ab.Nom, ab.Rang, ab.Temps, ab.Point, ab.Club, ab.LongueurEpreuve, ab.Nom, ab.Epreuve, ab.Code));
            //}

            var noGroupe = 0;
            Dictionary <int, ResultatObj> dictRes = new Dictionary <int, ResultatObj>();

            foreach (var ab in laTotale2)
            {
                string nomgrp = ab.Groupe + " " + ab.Sexe.ToUpper();
                if (m)
                {
                    nomgrp = ab.Groupe;
                }
                if (grppreced != nomgrp)
                {
                    // Si le groupe change, la vague change
                    if (vagueJson != null)
                    {
                        vaguesGroupes.Add(vagueJson);
                    }
                    vagueChange(out vgpreced, out patineurVague, out vagueJson, ab);
                    if (!string.IsNullOrEmpty(grppreced))
                    {
                        noGroupe += 1;
                        //string groupeData = vaguesGroupes.ToString();
                        CreerFichierResultatGroupe(noGroupe, vaguesGroupes, grppreced, (JArray)programme["Groupes"], dictRes);
                        dictRes = new Dictionary <int, ResultatObj>();
                    }
                    vaguesGroupes = new JArray();
                    grppreced     = nomgrp;
                    //vgpreced = ab.NoVague;
                }
                else if (vgpreced != ab.NoVague)
                {
                    if (vagueJson != null)
                    {
                        vaguesGroupes.Add(vagueJson);
                    }
                    vagueChange(out vgpreced, out patineurVague, out vagueJson, ab);
                }
                if (dictRes.ContainsKey(ab.NoPatineur))
                {
                    dictRes[ab.NoPatineur].Point += ab.Point;
                }
                else
                {
                    dictRes.Add(ab.NoPatineur, new ResultatObj()
                    {
                        NoPatineur = ab.NoPatineur,
                        Nom        = ab.Nom,
                        Club       = ab.Club,
                        Point      = ab.Point,
                        Code       = ""
                    });
                }

                JObject patineurJson = new JObject();
                patineurJson.Add("Casque", ab.NoCasque.ToString());
                patineurJson.Add("Patineurs", ab.Nom);
                patineurJson.Add("Club", ab.Club);
                patineurJson.Add("Rang", ab.Rang);
                patineurJson.Add("Temps", ab.Temps);
                patineurJson.Add("Commentaire", ab.Code);
                patineurJson.Add("Point", ab.Point);
                patineurJson.Add("Date", "");
                patineurVague.Add(patineurJson);
                //Console.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}", ab.Groupe, ab.NoVague, ab.Nom, ab.Rang, ab.Temps, ab.Point, ab.Club, ab.LongueurEpreuve, ab.Nom, ab.Etape));
            }

            // On termine avec le dernier groupe
            noGroupe += 1;
            if (vagueJson != null)
            {
                vaguesGroupes.Add(vagueJson);
            }
            if (!string.IsNullOrEmpty(grppreced))
            {
                //string groupeData = vaguesGroupes.ToString();
                CreerFichierResultatGroupe(noGroupe, vaguesGroupes, grppreced, (JArray)programme["Groupes"], dictRes);
            }

            // Créer le fichier de programme
            string programmeStr = programme.ToString();

            programmeStr = programmeStr.Replace(Environment.NewLine, string.Empty);
            //string extFich = "js";
            //if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Fmt"]) && ConfigurationManager.AppSettings["Fmt"] == "JSON")
            //{
            //    extFich = "json";
            //}
            string nomficheprg = string.Format("programme.{0}", extFich);

            string newtext = programmeStr;

            if (extFich == "js")
            {
                newtext = string.Format("var a = '{0}';", programmeStr);
            }

            string pathResultat = Path.Combine(this.pathTravail, "ResultatsTravail");

            if (!Directory.Exists(pathResultat))
            {
                Directory.CreateDirectory(pathResultat);
            }
            pathResultat = Path.Combine(pathResultat, "programme.json");
            string ResultatsPrecedents = Path.Combine(this.pathTravail, "ResultatsPrecedents");

            if (!Directory.Exists(ResultatsPrecedents))
            {
                Directory.CreateDirectory(ResultatsPrecedents);
            }
            ResultatsPrecedents = Path.Combine(ResultatsPrecedents, "programme.json");
            string ResultatsFTP = Path.Combine(this.pathTravail, "ResultatsFTP");

            if (!Directory.Exists(ResultatsFTP))
            {
                Directory.CreateDirectory(ResultatsFTP);
            }
            ResultatsFTP = Path.Combine(ResultatsFTP, "programme.json");


            using (StreamWriter sr = new StreamWriter(pathResultat))
            {
                sr.Write(newtext);
            }

            if (!System.IO.File.Exists(ResultatsPrecedents))
            {
                // première copie du résultat
                System.IO.File.Copy(pathResultat, ResultatsPrecedents);
                System.IO.File.Copy(pathResultat, ResultatsFTP);
            }
            else
            {
                string contenuGit = System.IO.File.ReadAllText(ResultatsPrecedents);
                if (contenuGit != newtext)
                {
                    System.IO.File.Delete(ResultatsPrecedents);
                    System.IO.File.Copy(pathResultat, ResultatsPrecedents);
                    System.IO.File.Copy(pathResultat, ResultatsFTP);
                }
            }
            //List<string> ls = new List<string>();
            return(programme);
        }
Example #24
0
        private void CreerFichierResultatGroupe(int noGroupe, JArray groupeData, string nomGroupe, JArray groupes, Dictionary <int, ResultatObj> dictRes)
        {
            //string extFich = "js";
            //if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Fmt"]) && ConfigurationManager.AppSettings["Fmt"] == "JSON")
            //{
            //    extFich = "json";
            //}

            JObject jogrp = new JObject();

            jogrp.Add("Groupe", nomGroupe);
            //string gitLink = ConfigurationManager.AppSettings["gitLink"];

            jogrp.Add("src", string.Format("data/GR{0}.{1}", noGroupe, extFich));

            groupes.Add(jogrp);
            // Ajouter la compilation des temps
            List <ResultatObj> ls = dictRes.Values.OrderByDescending(z => z.Point).ToList();
            var i = 0;

            ls.ForEach(z => z.Rang = ++i);

            JArray patineurCompile = new JArray();

            foreach (ResultatObj ab in ls)
            {
                JObject patineurJson = new JObject();
                patineurJson.Add("Casque", ab.NoCasque.ToString());
                patineurJson.Add("Patineurs", ab.Nom);
                patineurJson.Add("Club", ab.Club);
                patineurJson.Add("Rang", ab.Rang);
                patineurJson.Add("Temps", ab.Temps);
                patineurJson.Add("Commentaire", ab.Code);
                patineurJson.Add("Point", ab.Point);
                patineurJson.Add("Date", "");
                patineurCompile.Add(patineurJson);
            }

            JObject vagueJson = new JObject();

            vagueJson.Add("vague", "Sommaire");
            vagueJson.Add("distance", nomGroupe);
            vagueJson.Add("etape", "competition");
            vagueJson.Add("Patineurs", patineurCompile);
            groupeData.Add(vagueJson);

            string groupeDatastr = groupeData.ToString();

            groupeDatastr = groupeDatastr.Replace(Environment.NewLine, string.Empty);
            string nomfichx            = string.Format("GR{0}.{1}", noGroupe, extFich);
            string pathResultat        = Path.Combine(this.pathTravail, "ResultatsTravail", nomfichx);
            string ResultatsPrecedents = Path.Combine(this.pathTravail, "ResultatsPrecedents", nomfichx);
            string ResultatsFTP        = Path.Combine(this.pathTravail, "ResultatsFTP", nomfichx);

            string newtxt = string.Empty;

            if (extFich == "json")
            {
                newtxt = groupeDatastr;
            }
            else
            {
                newtxt = string.Format("var a = '{0}';", groupeDatastr);
            }

            using (StreamWriter sr = new StreamWriter(pathResultat))
            {
                sr.Write(newtxt);
            }

            if (!System.IO.File.Exists(ResultatsPrecedents))
            {
                System.IO.File.Copy(pathResultat, ResultatsPrecedents);
                System.IO.File.Copy(pathResultat, ResultatsFTP);
            }
            else
            {
                string contenuGit = System.IO.File.ReadAllText(ResultatsPrecedents);
                if (contenuGit != newtxt)
                {
                    System.IO.File.Delete(ResultatsPrecedents);
                    System.IO.File.Copy(pathResultat, ResultatsPrecedents);
                    System.IO.File.Copy(pathResultat, ResultatsFTP, true);
                }
            }
        }
Example #25
0
		public JObject B2n(Body body)
		{
			JObject bodyValue = new JObject();
			
			string bodyName = GetBodyName(body);
			if (null != bodyName)
				bodyValue["name"] = bodyName;
			
			switch (body.BodyType)
			{
			case BodyType.Static:
				bodyValue["type"] = 0;
				break;
			case BodyType.Kinematic:
				bodyValue["type"] = 1;
				break;
			case BodyType.Dynamic:
				bodyValue["type"] = 2;
				break;
			}
			
			VecToJson("position", body.Position, bodyValue);
			FloatToJson("angle", body.Rotation, bodyValue);
			
			VecToJson("linearVelocity", body.LinearVelocity, bodyValue);
			FloatToJson("angularVelocity", body.AngularVelocity, bodyValue);
			
			if (body.LinearDamping != 0)
				FloatToJson("linearDamping", body.LinearDamping, bodyValue);
			if (body.AngularDamping != 0)
				FloatToJson("angularDamping", body.AngularDamping, bodyValue);
			if (body.GravityScale != 1)
				FloatToJson("gravityScale", body.GravityScale, bodyValue);
			
			if (body.IsBullet)
				bodyValue["bullet"] = true;
			if (!body.SleepingAllowed)
				bodyValue["allowSleep"] = false;
			if (body.Awake)
				bodyValue["awake"] = true;
			if (!body.Enabled)
				bodyValue["active"] = false;
			if (body.FixedRotation)
				bodyValue["fixedRotation"] = true;
			
			
			
			/*MassData massData = new MassData();
            massData.Mass = body.Mass;
            massData.Centroid = body.LocalCenter; //im not sure
            massData.Inertia = body.Inertia;*/
			//body.getMassData(massData);
			if (body.Mass != 0)
				FloatToJson("massData-mass", body.Mass, bodyValue);
			if (body.LocalCenter.X != 0 || body.LocalCenter.Y != 0)
				VecToJson("massData-center", body.LocalCenter, bodyValue);
			if (body.Inertia != 0)
			{
				FloatToJson("massData-I", body.Inertia, bodyValue);
			}
			
			
			JArray arr = new JArray();
			foreach (var fixture in body.FixtureList)
			{
				arr.Add( B2n(fixture) );
			}
			bodyValue["fixture"] = arr;
			
			JArray customPropertyValue = WriteCustomPropertiesToJson(body);
			if (customPropertyValue.Count > 0)
				bodyValue["customProperties"] = customPropertyValue;
			
			return bodyValue;
		}
Example #26
0
        public static void ParatikaParameter(Dictionary <string, string> requestParameters, List <ShoppingCartItem> cart, IWorkContext _workContext, IHttpContextAccessor _httpContextAccessor, IWebHelper _webHelper, ParatikaOrderPaymentSettings _paratikaOrderPaymentSettings, IOrderTotalCalculationService _orderTotalCalculationService)
        {
            var storeLocation  = _webHelper.GetStoreLocation();
            var getPaymentGuid = _httpContextAccessor.HttpContext.Session.Get <string>("MERCHANTPAYMENTID_" + _workContext.CurrentCustomer.Id);

            requestParameters.Add("MERCHANT", _paratikaOrderPaymentSettings.Code);
            requestParameters.Add("MERCHANTUSER", _paratikaOrderPaymentSettings.Username);
            requestParameters.Add("MERCHANTPASSWORD", _paratikaOrderPaymentSettings.Password);

            requestParameters.Add("MERCHANTPAYMENTID", getPaymentGuid);
            var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(cart, out var orderDiscountAmount, out var orderAppliedDiscounts, out var appliedGiftCards, out var redeemedRewardPoints, out var redeemedRewardPointsAmount);

            requestParameters.Add("AMOUNT", orderTotal.ToString());
            requestParameters.Add("CURRENCY", "TRY");
            requestParameters.Add("SESSIONTYPE", "PAYMENTSESSION");
            requestParameters.Add("RETURNURL", $"{storeLocation}Paratika/PaymentInfoCallBack");

            JArray oItems = new JArray();

            foreach (var card in cart)
            {
                JObject item = new JObject();
                item.Add("code", card.Product.Sku);
                item.Add("name", card.Product.Name);
                item.Add("quantity", card.Quantity);
                item.Add("description", card.Product.Name);
                item.Add("amount", card.Product.Price);
                oItems.Add(item);
            }

            decimal productSum = 0;

            foreach (var item in oItems)
            {
                productSum += Convert.ToDecimal(item["amount"]) * Convert.ToInt32(item["quantity"]);
            }
            if (orderTotal != productSum)
            {
                if (orderTotal > productSum)
                {
                    var     diffrerent = orderTotal - productSum;
                    JObject item       = new JObject();
                    item.Add("code", "different");
                    item.Add("name", "different");
                    item.Add("quantity", "1");
                    item.Add("description", "different");
                    item.Add("amount", diffrerent.ToString());
                    oItems.Add(item);
                }
                else
                {
                    var     diffrerent = productSum - orderTotal;
                    JObject item       = new JObject();
                    item.Add("code", "discount");
                    item.Add("name", "discount");
                    item.Add("quantity", "1");
                    item.Add("description", "discount");
                    item.Add("amount", diffrerent.ToString());
                    oItems.Add(item);
                }
            }
            requestParameters.Add("ORDERITEMS", encodeParameter(oItems.ToString()));

            JObject extra = new JObject();

            extra.Add("IntegrationModel", "API");
            //extra.Add("AlwaysSaveCard", "true");
            requestParameters.Add("EXTRA", encodeParameter(extra.ToString()));

            requestParameters.Add("CUSTOMER", _workContext.CurrentCustomer.CustomerGuid.ToString());
            requestParameters.Add("CUSTOMERNAME", _workContext.CurrentCustomer.ShippingAddress.FirstName + " " + _workContext.CurrentCustomer.ShippingAddress.LastName);
            requestParameters.Add("CUSTOMEREMAIL", _workContext.CurrentCustomer.Email);
            requestParameters.Add("CUSTOMERIP", _workContext.CurrentCustomer.LastIpAddress);
            requestParameters.Add("CUSTOMERPHONE", _workContext.CurrentCustomer.ShippingAddress.PhoneNumber);
            //requestParameters.Add("CUSTOMERBIRTHDAY", _workContext.CurrentCustomer.ShippingAddress.);
            requestParameters.Add("CUSTOMERUSERAGENT", _httpContextAccessor.HttpContext.Request.Headers["User-Agent"].ToString());

            requestParameters.Add("BILLTOADDRESSLINE", _workContext.CurrentCustomer.BillingAddress.Address1);
            requestParameters.Add("BILLTOCITY", _workContext.CurrentCustomer.BillingAddress.City);
            requestParameters.Add("BILLTOCOUNTRY", _workContext.CurrentCustomer.BillingAddress.Country.Name);
            requestParameters.Add("BILLTOPOSTALCODE", _workContext.CurrentCustomer.BillingAddress.ZipPostalCode);
            requestParameters.Add("BILLTOPHONE", _workContext.CurrentCustomer.BillingAddress.PhoneNumber);
            requestParameters.Add("SHIPTOADDRESSLINE", _workContext.CurrentCustomer.ShippingAddress.Address1);
            requestParameters.Add("SHIPTOCITY", _workContext.CurrentCustomer.ShippingAddress.City);
            requestParameters.Add("SHIPTOCOUNTRY", _workContext.CurrentCustomer.ShippingAddress.Country.Name);
            requestParameters.Add("SHIPTOPOSTALCODE", _workContext.CurrentCustomer.ShippingAddress.ZipPostalCode);
            requestParameters.Add("SHIPTOPHONE", _workContext.CurrentCustomer.ShippingAddress.PhoneNumber);
        }
Example #27
0
    public void GenericCollectionCopyToInsufficientArrayCapacity()
    {
      JArray j = new JArray();
      j.Add(new JValue(1));
      j.Add(new JValue(2));
      j.Add(new JValue(3));

      ((ICollection<JToken>)j).CopyTo(new JToken[3], 1);
    }
Example #28
0
        public void DoDownload()
        {
            jsonFile = Path.Combine(DownDir, "meta.json");
            if (!File.Exists(jsonFile))
            {
                return;
            }

            string  jsonContent = File.ReadAllText(jsonFile);
            JObject initJson    = JObject.Parse(jsonContent);
            JArray  parts       = JArray.Parse(initJson["m3u8Info"]["segments"].ToString()); //大分组
            string  segCount    = initJson["m3u8Info"]["count"].ToString();
            string  oriCount    = initJson["m3u8Info"]["originalCount"].ToString();          //原始分片数量
            string  isVOD       = initJson["m3u8Info"]["vod"].ToString();

            try
            {
                if (initJson["m3u8Info"]["audio"].ToString() != "")
                {
                    externalAudio = true;
                }
                externalAudioUrl = initJson["m3u8Info"]["audio"].ToString();
                LOGGER.WriteLine(strings.hasExternalAudioTrack);
                LOGGER.PrintLine(strings.hasExternalAudioTrack, LOGGER.Warning);
            }
            catch (Exception) {}
            try
            {
                if (initJson["m3u8Info"]["sub"].ToString() != "")
                {
                    externalSub = true;
                }
                externalSubUrl = initJson["m3u8Info"]["sub"].ToString();
                LOGGER.WriteLine(strings.hasExternalSubtitleTrack);
                LOGGER.PrintLine(strings.hasExternalSubtitleTrack, LOGGER.Warning);
            }
            catch (Exception) { }
            total        = Convert.ToInt32(segCount);
            PartsCount   = parts.Count;
            segsPadZero  = string.Empty.PadRight(oriCount.Length, '0');
            partsPadZero = string.Empty.PadRight(Convert.ToString(parts.Count).Length, '0');

            //是直播视频
            if (isVOD == "False")
            {
                return;
            }

            Global.ShouldStop = false; //是否该停止下载

            if (!Directory.Exists(DownDir))
            {
                Directory.CreateDirectory(DownDir); //新建文件夹
            }
            Watcher watcher = new Watcher(DownDir);

            watcher.Total      = total;
            watcher.PartsCount = PartsCount;
            watcher.WatcherStrat();

            //开始计算速度
            timer.Enabled = true;
            cts           = new CancellationTokenSource();

            //开始调用下载
            LOGGER.WriteLine(strings.startDownloading);
            LOGGER.PrintLine(strings.startDownloading, LOGGER.Warning);

            //下载MAP文件(若有)
            try
            {
                Downloader sd = new Downloader();
                sd.TimeOut = TimeOut;
                sd.FileUrl = initJson["m3u8Info"]["extMAP"].Value <string>();
                sd.Headers = Headers;
                sd.Method  = "NONE";
                if (sd.FileUrl.Contains("|"))  //有range
                {
                    string[] tmp = sd.FileUrl.Split('|');
                    sd.FileUrl    = tmp[0];
                    sd.StartByte  = Convert.ToUInt32(tmp[1].Split('@')[1]);
                    sd.ExpectByte = Convert.ToUInt32(tmp[1].Split('@')[0]);
                }
                sd.SavePath = DownDir + "\\!MAP.tsdownloading";
                if (File.Exists(sd.SavePath))
                {
                    File.Delete(sd.SavePath);
                }
                if (File.Exists(DownDir + "\\Part_0\\!MAP.ts"))
                {
                    File.Delete(DownDir + "\\Part_0\\!MAP.ts");
                }
                LOGGER.PrintLine(strings.downloadingMapFile);
                sd.Down();  //开始下载
            }
            catch (Exception e)
            {
                //LOG.WriteLineError(e.ToString());
            }

            //首先下载第一个分片
            JToken firstSeg = JArray.Parse(parts[0].ToString())[0];

            if (!File.Exists(DownDir + "\\Part_" + 0.ToString(partsPadZero) + "\\" + firstSeg["index"].Value <int>().ToString(segsPadZero) + ".ts"))
            {
                try
                {
                    Downloader sd = new Downloader();
                    sd.TimeOut = TimeOut;
                    sd.SegDur  = firstSeg["duration"].Value <double>();
                    if (sd.SegDur < 0)
                    {
                        sd.SegDur = 0;                //防止负数
                    }
                    sd.FileUrl = firstSeg["segUri"].Value <string>();
                    //VTT字幕
                    if (isVTT == false && (sd.FileUrl.Trim('\"').EndsWith(".vtt") || sd.FileUrl.Trim('\"').EndsWith(".webvtt")))
                    {
                        isVTT = true;
                    }
                    sd.Method = firstSeg["method"].Value <string>();
                    if (sd.Method != "NONE")
                    {
                        sd.Key = firstSeg["key"].Value <string>();
                        sd.Iv  = firstSeg["iv"].Value <string>();
                    }
                    if (firstSeg["expectByte"] != null)
                    {
                        sd.ExpectByte = firstSeg["expectByte"].Value <long>();
                    }
                    if (firstSeg["startByte"] != null)
                    {
                        sd.StartByte = firstSeg["startByte"].Value <long>();
                    }
                    sd.Headers  = Headers;
                    sd.SavePath = DownDir + "\\Part_" + 0.ToString(partsPadZero) + "\\" + firstSeg["index"].Value <int>().ToString(segsPadZero) + ".tsdownloading";
                    if (File.Exists(sd.SavePath))
                    {
                        File.Delete(sd.SavePath);
                    }
                    LOGGER.PrintLine(strings.downloadingFirstSegement);
                    if (!Global.ShouldStop)
                    {
                        sd.Down();  //开始下载
                    }
                }
                catch (Exception e)
                {
                    //LOG.WriteLineError(e.ToString());
                }
            }

            if (Global.HadReadInfo == false)
            {
                string href = DownDir + "\\Part_" + 0.ToString(partsPadZero) + "\\" + firstSeg["index"].Value <int>().ToString(segsPadZero) + ".ts";
                if (File.Exists(DownDir + "\\!MAP.ts"))
                {
                    href = DownDir + "\\!MAP.ts";
                }
                Global.GzipHandler(href);
                bool flag = false;
                foreach (string ss in (string[])Global.GetVideoInfo(href).ToArray(typeof(string)))
                {
                    LOGGER.WriteLine(ss.Trim());
                    LOGGER.PrintLine(ss.Trim(), 0);
                    if (ss.Trim().Contains("Error in reading file"))
                    {
                        flag = true;
                    }
                }
                LOGGER.PrintLine(strings.waitForCompletion, LOGGER.Warning);
                if (!flag)
                {
                    Global.HadReadInfo = true;
                }
            }

            //多线程设置
            ParallelOptions parallelOptions = new ParallelOptions
            {
                MaxDegreeOfParallelism = Threads,
                CancellationToken      = cts.Token
            };

            //构造包含所有分片的新的segments
            JArray segments = new JArray();

            for (int i = 0; i < parts.Count; i++)
            {
                var tmp = JArray.Parse(parts[i].ToString());
                for (int j = 0; j < tmp.Count; j++)
                {
                    JObject t = (JObject)tmp[j];
                    t.Add("part", i);
                    segments.Add(t);
                }
            }

            //剔除第一个分片(已下载过)
            segments.RemoveAt(0);

            try
            {
                ParallelLoopResult result = Parallel.ForEach(segments,
                                                             parallelOptions,
                                                             () => new Downloader(),
                                                             (info, loopstate, index, sd) =>
                {
                    if (Global.ShouldStop)
                    {
                        loopstate.Stop();
                    }
                    else
                    {
                        sd.TimeOut = TimeOut;
                        sd.SegDur  = info["duration"].Value <double>();
                        if (sd.SegDur < 0)
                        {
                            sd.SegDur = 0;                    //防止负数
                        }
                        sd.FileUrl = info["segUri"].Value <string>();
                        //VTT字幕
                        if (isVTT == false && (sd.FileUrl.Trim('\"').EndsWith(".vtt") || sd.FileUrl.Trim('\"').EndsWith(".webvtt")))
                        {
                            isVTT = true;
                        }
                        sd.Method = info["method"].Value <string>();
                        if (sd.Method != "NONE")
                        {
                            sd.Key = info["key"].Value <string>();
                            sd.Iv  = info["iv"].Value <string>();
                        }
                        if (firstSeg["expectByte"] != null)
                        {
                            sd.ExpectByte = info["expectByte"].Value <long>();
                        }
                        if (firstSeg["startByte"] != null)
                        {
                            sd.StartByte = info["startByte"].Value <long>();
                        }
                        sd.Headers  = Headers;
                        sd.SavePath = DownDir + "\\Part_" + info["part"].Value <int>().ToString(partsPadZero) + "\\" + info["index"].Value <int>().ToString(segsPadZero) + ".tsdownloading";
                        if (File.Exists(sd.SavePath))
                        {
                            File.Delete(sd.SavePath);
                        }
                        if (!Global.ShouldStop)
                        {
                            sd.Down();      //开始下载
                        }
                    }
                    return(sd);
                },
                                                             (sd) => { });

                if (result.IsCompleted)
                {
                    //LOGGER.WriteLine("Part " + (info["part"].Value<int>() + 1).ToString(partsPadZero) + " of " + parts.Count + " Completed");
                }
            }
            catch (Exception)
            {
                ;//捕获取消循环产生的异常
            }
            finally
            {
                cts.Dispose();
            }

            watcher.WatcherStop();

            //停止速度监测
            timer.Enabled = false;

            //检测是否下完
            IsComplete(Convert.ToInt32(segCount));
        }
Example #29
0
    public void RemoveAt()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(1);
      JValue v3 = new JValue(1);

      JArray j = new JArray();

      j.Add(v1);
      j.Add(v2);
      j.Add(v3);

      Assert.AreEqual(true, j.Contains(v1));
      j.RemoveAt(0);
      Assert.AreEqual(false, j.Contains(v1));

      Assert.AreEqual(true, j.Contains(v3));
      j.RemoveAt(1);
      Assert.AreEqual(false, j.Contains(v3));

      Assert.AreEqual(1, j.Count);
    }
Example #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string rid    = Context.Request.Params["rid"];
                string method = Context.Request.Params["method"];
                //rid = 782512 + "";
                Range  = new JObject();
                points = new JArray();
                if (string.IsNullOrEmpty(rid))
                {
                    Range  = new JObject();
                    points = new JArray();
                    return;
                }
                else
                {
                    #region 查询数据
                    //查询线路信息
                    string hql;
                    if (string.IsNullOrEmpty(method))  //method=NULL 查微信
                    {
                        hql = "SELECT NEW uf_CarGPS_WFRange(a.id,a.wfRequestId,a.sqr,a.ccqsrq,a.ccqssj,a.ccjzrq,a.ccjzsj,a.ccdd,a.Range,a.RangeCount,a.sqgs,a.sqbm,a.LastUpdateTime,a.WxOpenid)FROM uf_CarGPS_WFRange a WHERE wfRequestId=?";
                    }
                    else//method!=NULL GPS
                    {
                        hql = "SELECT NEW uf_CarGPS_WFRange(a.id,a.wfRequestId,a.sqr,a.ccqsrq,a.ccqssj,a.ccjzrq,a.ccjzsj,a.ccdd,a.Range,a.RangeCount,a.sqgs,a.sqbm,a.LastUpdateTime,a.WxOpenid)FROM uf_CarGPS_WFRange a WHERE wfRequestId=? and WxOpenid is null";
                    }
                    SimpleQuery <uf_CarGPS_WFRange> GQuery = new SimpleQuery <uf_CarGPS_WFRange>(hql, Int32.Parse(rid));
                    uf_CarGPS_WFRange[]             GBeans = GQuery.Execute();
                    if (GBeans.Length < 1)
                    {
                        Range  = new JObject();
                        points = new JArray();
                        return;
                    }
                    uf_CarGPS_WFRange GBean = GBeans[0];
                    //查询人员信息
                    hql = "SELECT NEW HrmResource(a.id,a.loginid,a.lastname)FROM HrmResource a WHERE a.id=?";
                    SimpleQuery <HrmResource> SQuery = new SimpleQuery <HrmResource>(hql, GBean.sqr);
                    HrmResource[]             UBeans = SQuery.Execute();
                    if (UBeans.Length == 0)
                    {
                        Range  = new JObject();
                        points = new JArray();
                        return;
                    }
                    //查询出线路信息
                    hql = "SELECT NEW uf_CarGPS_WFRoute(a.id,a.PointsCount,a.CreateTime,a.RouteRange,a.WFRangeID,a.Points,a.LastUpdateTime)FROM uf_CarGPS_WFRoute a WHERE a.WFRangeID = ?";
                    SimpleQuery <uf_CarGPS_WFRoute> RQuery = new SimpleQuery <uf_CarGPS_WFRoute>(hql, GBean.id);
                    uf_CarGPS_WFRoute[]             RBeans = RQuery.Execute();

                    #endregion
                    #region 封装数据
                    Range.Add("id", GBean.id);
                    Range.Add("rid", GBean.wfRequestId);
                    Range.Add("uName", UBeans[0].lastname);
                    Range.Add("sqr", GBean.sqr);
                    Range.Add("ccqsrq", GBean.ccqsrq);
                    Range.Add("ccqssj", GBean.ccqssj);
                    Range.Add("ccdd", GBean.ccdd);
                    Range.Add("Range", GBean.Range);
                    Range.Add("RangeCount", GBean.RangeCount);
                    Range.Add("sqgs", GBean.sqgs);
                    Range.Add("sqbm", GBean.sqbm);
                    Range.Add("LastUpdateTime", GBean.LastUpdateTime);
                    Range.Add("WxOpenid", GBean.WxOpenid);
                    if (RBeans.Length > 0)
                    {
                        foreach (uf_CarGPS_WFRoute bean in RBeans)
                        {
                            JObject jo = new JObject();
                            jo.Add("id", bean.id);
                            jo.Add("PointsCount", bean.PointsCount);
                            jo.Add("CreateTime", bean.CreateTime);
                            jo.Add("RouteRange", bean.RouteRange);
                            jo.Add("WFRangeID", bean.WFRangeID);
                            jo.Add("Points", bean.Points);
                            if (bean.LastUpdateTime != null && bean.LastUpdateTime.Length > 12)
                            {
                                DateTime dt = DateTime.ParseExact(bean.LastUpdateTime, "yyyy/MM/dd", System.Globalization.CultureInfo.CurrentCulture);
                                jo.Add("LastUpdateTime", dt.ToString("yyyy/MM/dd HH:mm:ss"));
                            }
                            else if (bean.LastUpdateTime != null)
                            {
                                jo.Add("LastUpdateTime", bean.LastUpdateTime);
                            }
                            else
                            {
                                jo.Add("LastUpdateTime", "");
                            }

                            points.Add(jo);
                        }
                    }
                    #endregion
                    #region 返回数据

                    //已经放在参数内 不需要返回

                    #endregion
                }
            }
            catch (Exception _e)
            {
                Log.Error("MapSearch2:", _e);
                throw;
            }
            //根据流程id查询 uf_CarGPS_WFRange 和 uf_CarGPS_WFRange的明细 uf_CarGPS_WFRoute、
        }
        public override async Task <IActionResult> Handle(HandlerContext context, CancellationToken cancellationToken)
        {
            try
            {
                _umaTicketGrantTypeValidator.Validate(context);
                var oauthClient = await AuthenticateClient(context, cancellationToken);

                context.SetClient(oauthClient);
                var ticket           = context.Request.Data.GetTicket();
                var claimTokenFormat = context.Request.Data.GetClaimTokenFormat();
                if (string.IsNullOrWhiteSpace(claimTokenFormat))
                {
                    claimTokenFormat = _umaHostOptions.DefaultClaimTokenFormat;
                }

                var scopes           = context.Request.Data.GetScopesFromAuthorizationRequest();
                var permissionTicket = await _umaPermissionTicketHelper.GetTicket(ticket);

                if (permissionTicket == null)
                {
                    throw new OAuthException(ErrorCodes.INVALID_GRANT, UMAErrorMessages.INVALID_TICKET);
                }

                ClaimTokenFormatFetcherResult claimTokenFormatFetcherResult = null;
                if (!string.IsNullOrWhiteSpace(claimTokenFormat))
                {
                    var claimTokenFormatFetcher = _claimTokenFormatFetchers.FirstOrDefault(c => c.Name == claimTokenFormat);
                    if (claimTokenFormatFetcher == null)
                    {
                        throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(UMAErrorMessages.BAD_TOKEN_FORMAT, claimTokenFormat));
                    }

                    claimTokenFormatFetcherResult = await claimTokenFormatFetcher.Fetch(context);
                }

                if (claimTokenFormatFetcherResult == null)
                {
                    return(BuildError(HttpStatusCode.Unauthorized, UMAErrorCodes.REQUEST_DENIED, UMAErrorMessages.REQUEST_DENIED));
                }

                var invalidScopes = permissionTicket.Records.Any(rec => !scopes.All(sc => rec.Scopes.Contains(sc)));
                if (invalidScopes)
                {
                    throw new OAuthException(ErrorCodes.INVALID_SCOPE, UMAErrorMessages.INVALID_SCOPE);
                }

                var umaResources = await _umaResourceQueryRepository.FindByIdentifiers(permissionTicket.Records.Select(r => r.ResourceId));

                var requiredClaims = new List <UMAResourcePermissionClaim>();
                foreach (var umaResource in umaResources)
                {
                    foreach (var permission in umaResource.Permissions)
                    {
                        if (permission.Scopes.Any(sc => scopes.Contains(sc)))
                        {
                            var unknownClaims = permission.Claims.Where(cl => !claimTokenFormatFetcherResult.Payload.Any(c => c.Key == cl.Name));
                            requiredClaims.AddRange(unknownClaims);
                        }
                    }
                }

                if (requiredClaims.Any())
                {
                    var needInfoResult = new JObject
                    {
                        { "need_info", new JObject
                          {
                              { UMATokenRequestParameters.Ticket, permissionTicket.Id },
                              { "required_claims", new JArray(requiredClaims.Select(rc => new JObject
                                    {
                                        { UMAResourcePermissionNames.ClaimTokenFormat, _umaHostOptions.DefaultClaimTokenFormat },
                                        { UMAResourcePermissionNames.ClaimType, rc.ClaimType },
                                        { UMAResourcePermissionNames.ClaimFriendlyName, rc.FriendlyName },
                                        { UMAResourcePermissionNames.ClaimName, rc.Name }
                                    })) },
                              { "redirect_uri", _umaHostOptions.OpenIdRedirectUrl }
                          } }
                    };
                    return(new ContentResult
                    {
                        Content = needInfoResult.ToString(),
                        ContentType = "application/json",
                        StatusCode = (int)HttpStatusCode.Unauthorized
                    });
                }

                var isNotAuthorized = umaResources.Any(ua => ua.Permissions.Where(p => p.Scopes.Any(sc => scopes.Contains(sc)))
                                                       .All(pr => pr.Claims.All(cl => claimTokenFormatFetcherResult.Payload.Any(c => c.Key == cl.Name && !c.Value.ToString().Equals(cl.Value, StringComparison.InvariantCultureIgnoreCase)))));
                if (isNotAuthorized)
                {
                    var pendingRequests = await _umaPendingRequestQueryRepository.FindByTicketIdentifier(permissionTicket.Id);

                    if (pendingRequests.Any())
                    {
                        return(BuildError(HttpStatusCode.Unauthorized, UMAErrorCodes.REQUEST_DENIED, UMAErrorMessages.REQUEST_DENIED));
                    }

                    foreach (var umaResource in umaResources)
                    {
                        var permissionTicketRecord = permissionTicket.Records.First(r => r.ResourceId == umaResource.Id);
                        var umaPendingRequest      = new UMAPendingRequest(permissionTicket.Id, umaResource.Subject, DateTime.UtcNow)
                        {
                            Requester = claimTokenFormatFetcherResult.Subject,
                            Scopes    = umaResource.Scopes,
                            Resource  = umaResource
                        };
                        _umaPendingRequestCommandRepository.Add(umaPendingRequest);
                    }

                    await _umaPendingRequestCommandRepository.SaveChanges(cancellationToken);

                    return(new ContentResult
                    {
                        ContentType = "application/json",
                        StatusCode = (int)HttpStatusCode.Unauthorized,
                        Content = new JObject
                        {
                            { "request_submitted", new JObject
                              {
                                  { UMATokenRequestParameters.Ticket, permissionTicket.Id },
                                  { "interval", _umaHostOptions.RequestSubmittedInterval }
                              } }
                        }.ToString()
                    });
                }

                var jArr = new JArray();
                foreach (var permission in permissionTicket.Records)
                {
                    jArr.Add(new JObject()
                    {
                        { UMAPermissionNames.ResourceId, permission.ResourceId },
                        { UMAPermissionNames.ResourceScopes, new JArray(permission.Scopes) }
                    });
                }

                var result = BuildResult(context, scopes);
                foreach (var tokenBuilder in _tokenBuilders)
                {
                    await tokenBuilder.Build(scopes, new JObject
                    {
                        { "permissions", jArr }
                    }, context, cancellationToken);
                }

                _tokenProfiles.First(t => t.Profile == context.Client.PreferredTokenProfile).Enrich(context);
                foreach (var kvp in context.Response.Parameters)
                {
                    result.Add(kvp.Key, kvp.Value);
                }

                return(new OkObjectResult(result));
            }
            catch (OAuthException ex)
            {
                return(BuildError(HttpStatusCode.BadRequest, ex.Code, ex.Message));
            }
        }
Example #32
0
        internal static JToken MapProperties(JToken source, bool inInstance)
        {
            var result = source;

            if (source is JObject obj)
            {
                var nobj = new JObject();

                // Fix datetime by reverting to simple timex
                if (!inInstance && obj.TryGetValue("type", out var type) && type.Type == JTokenType.String && _dateSubtypes.Contains(type.Value <string>()))
                {
                    var timexs = obj["values"];
                    var arr    = new JArray();
                    if (timexs != null)
                    {
                        var unique = new HashSet <string>();
                        foreach (var elt in timexs)
                        {
                            unique.Add(elt["timex"]?.Value <string>());
                        }

                        foreach (var timex in unique)
                        {
                            arr.Add(timex);
                        }

                        nobj["timex"] = arr;
                    }

                    nobj["type"] = type;
                }
                else
                {
                    // Map or remove properties
                    foreach (var property in obj.Properties())
                    {
                        var name     = NormalizeEntity(property.Name);
                        var isObj    = property.Value.Type == JTokenType.Object;
                        var isArray  = property.Value.Type == JTokenType.Array;
                        var isString = property.Value.Type == JTokenType.String;
                        var isInt    = property.Value.Type == JTokenType.Integer;
                        var val      = MapProperties(property.Value, inInstance || property.Name == MetadataKey);
                        if (name == "datetime" && isArray)
                        {
                            nobj.Add("datetimeV1", val);
                        }
                        else if (name == "datetimeV2" && isArray)
                        {
                            nobj.Add("datetime", val);
                        }
                        else if (inInstance)
                        {
                            // Correct $instance issues
                            if (name == "length" && isInt)
                            {
                                nobj.Add("endIndex", property.Value.Value <int>() + property.Parent["startIndex"].Value <int>());
                            }
                            else if (!((isInt && name == "modelTypeId") ||
                                       (isString && name == "role")))
                            {
                                nobj.Add(name, val);
                            }
                        }
                        else
                        {
                            // Correct non-$instance values
                            if (name == "unit" && isString)
                            {
                                nobj.Add("units", val);
                            }
                            else
                            {
                                nobj.Add(name, val);
                            }
                        }
                    }
                }

                result = nobj;
            }
            else if (source is JArray arr)
            {
                var narr = new JArray();
                foreach (var elt in arr)
                {
                    // Check if element is geographyV2
                    var isGeographyV2 = string.Empty;
                    foreach (var props in elt.Children())
                    {
                        var tokenProp = props as JProperty;
                        if (tokenProp == null)
                        {
                            break;
                        }

                        if (tokenProp.Name.Contains("type") && _geographySubtypes.Contains(tokenProp.Value.ToString()))
                        {
                            isGeographyV2 = tokenProp.Value.ToString();
                            break;
                        }
                    }

                    if (!inInstance && !string.IsNullOrEmpty(isGeographyV2))
                    {
                        var geoEntity = new JObject();
                        foreach (var props in elt.Children())
                        {
                            var tokenProp = props as JProperty;
                            if (tokenProp.Name.Contains("value"))
                            {
                                geoEntity.Add("location", tokenProp.Value);
                            }
                        }

                        geoEntity.Add("type", isGeographyV2);
                        narr.Add(geoEntity);
                    }
                    else
                    {
                        narr.Add(MapProperties(elt, inInstance));
                    }
                }

                result = narr;
            }

            return(result);
        }
        protected virtual JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getaccountstate":
            {
                UInt160      script_hash = Wallet.ToScriptHash(_params[0].AsString());
                AccountState account     = Blockchain.Default.GetAccountState(script_hash) ?? new AccountState(script_hash);
                return(account.ToJson());
            }

            case "getassetstate":
            {
                UInt256    asset_id = UInt256.Parse(_params[0].AsString());
                AssetState asset    = Blockchain.Default.GetAssetState(asset_id);
                return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset"));
            }

            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Default.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Default.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = block.ToJson();
                    json["confirmations"] = Blockchain.Default.Height - block.Index + 1;
                    UInt256 hash = Blockchain.Default.GetNextBlockHash(block.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }
                else
                {
                    return(block.ToArray().ToHexString());
                }
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetBlockHash(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getblocksysfee":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetSysFeeAmount(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getconnectioncount":
                return(LocalNode.RemoteNodeCount);

            case "getcontractstate":
            {
                UInt160       script_hash = UInt160.Parse(_params[0].AsString());
                ContractState contract    = Blockchain.Default.GetContract(script_hash);
                return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
            }

            case "getrawmempool":
                return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                int         height  = -1;
                Transaction tx      = LocalNode.GetTransaction(hash);
                if (tx == null)
                {
                    tx = Blockchain.Default.GetTransaction(hash, out height);
                }
                if (tx == null)
                {
                    throw new RpcException(-100, "Unknown transaction");
                }
                if (verbose)
                {
                    JObject json = tx.ToJson();
                    if (height >= 0)
                    {
                        Header header = Blockchain.Default.GetHeader((uint)height);
                        json["blockhash"]     = header.Hash.ToString();
                        json["confirmations"] = Blockchain.Default.Height - header.Index + 1;
                        json["blocktime"]     = header.Timestamp;
                    }
                    return(json);
                }
                else
                {
                    return(tx.ToArray().ToHexString());
                }
            }

            case "getstorage":
            {
                UInt160     script_hash = UInt160.Parse(_params[0].AsString());
                byte[]      key         = _params[1].AsString().HexToBytes();
                StorageItem item        = Blockchain.Default.GetStorageItem(new StorageKey
                    {
                        ScriptHash = script_hash,
                        Key        = key
                    }) ?? new StorageItem();
                return(item.Value?.ToHexString());
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index));
            }

            case "invoke":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                ContractParameter[] parameters  = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray();
                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, parameters).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                byte[]              script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, operation, args).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(GetInvokeResult(script));
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(LocalNode.Relay(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(LocalNode.Relay(block));
            }

            case "validateaddress":
            {
                JObject json = new JObject();
                UInt160 scriptHash;
                try
                {
                    scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                }
                catch
                {
                    scriptHash = null;
                }
                json["address"] = _params[0];
                json["isvalid"] = scriptHash != null;
                return(json);
            }

            case "getpeers":
            {
                JObject json = new JObject();

                {
                    JArray unconnectedPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetUnconnectedPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        unconnectedPeers.Add(peerJson);
                    }
                    json["unconnected"] = unconnectedPeers;
                }

                {
                    JArray badPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetBadPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        badPeers.Add(peerJson);
                    }
                    json["bad"] = badPeers;
                }

                {
                    JArray connectedPeers = new JArray();
                    foreach (RemoteNode node in LocalNode.GetRemoteNodes())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = node.RemoteEndpoint.Address.ToString();
                        peerJson["port"]    = node.ListenerEndpoint.Port;
                        connectedPeers.Add(peerJson);
                    }
                    json["connected"] = connectedPeers;
                }

                return(json);
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Example #34
0
        /// <summary>
        /// Sign a transaction
        /// </summary>
        /// <param name="request">The transaction to be signed</param>
        /// <returns>The signed transaction</returns>
        public async Task <SignRawTransactionResponse> SignRawTransactionWithKeyAsync(SignRawTransactionWithKeyRequest request)
        {
            Dictionary <string, object> values = new Dictionary <string, object>();

            values.Add("hexstring", request.Transaction.ToHex());
            JArray keys = new JArray();

            foreach (var k in request.PrivateKeys ?? new Key[0])
            {
                keys.Add(k.GetBitcoinSecret(Network).ToString());
            }
            values.Add("privkeys", keys);

            if (request.PreviousTransactions != null)
            {
                JArray prevs = new JArray();
                foreach (var prev in request.PreviousTransactions)
                {
                    JObject prevObj = new JObject();
                    prevObj.Add(new JProperty("txid", prev.OutPoint.Hash.ToString()));
                    prevObj.Add(new JProperty("vout", prev.OutPoint.N));
                    prevObj.Add(new JProperty("scriptPubKey", prev.ScriptPubKey.ToHex()));
                    if (prev.RedeemScript != null)
                    {
                        prevObj.Add(new JProperty("redeemScript", prev.RedeemScript.ToHex()));
                    }
                    prevObj.Add(new JProperty("amount", prev.Amount.ToDecimal(MoneyUnit.BTC).ToString()));
                    prevs.Add(prevObj);
                }
                values.Add("prevtxs", prevs);

                if (request.SigHash.HasValue)
                {
                    values.Add("sighashtype", SigHashToString(request.SigHash.Value));
                }
            }

            var result = await SendCommandWithNamedArgsAsync("signrawtransactionwithkey", values).ConfigureAwait(false);

            var response = new SignRawTransactionResponse();

            response.SignedTransaction = ParseTxHex(result.Result["hex"].Value <string>());
            response.Complete          = result.Result["complete"].Value <bool>();
            var errors    = result.Result["errors"] as JArray;
            var errorList = new List <SignRawTransactionResponse.ScriptError>();

            if (errors != null)
            {
                foreach (var error in errors)
                {
                    var scriptError = new SignRawTransactionResponse.ScriptError();
                    scriptError.OutPoint  = OutPoint.Parse($"{error["txid"].Value<string>()}-{(int)error["vout"].Value<long>()}");
                    scriptError.ScriptSig = Script.FromBytesUnsafe(Encoders.Hex.DecodeData(error["scriptSig"].Value <string>()));
                    scriptError.Sequence  = new Sequence((uint)error["sequence"].Value <long>());
                    scriptError.Error     = error["error"].Value <string>();
                    errorList.Add(scriptError);
                }
            }
            response.Errors = errorList.ToArray();
            return(response);
        }
Example #35
0
        JArray EncodeActionList()
        {
            var byNs = new Dictionary<string, JArray> ();

            foreach (var ac in actions) {
                JArray sublist;
                if (!byNs.TryGetValue (ac.Name.Namespace, out sublist)) {
                    byNs [ac.Name.Namespace] = sublist = new JArray ();
                    sublist.Add (ac.Name.Namespace);
                }

                sublist.Add (ac.Name.Version == 1 ? new JArray { ac.Name.Name, ac.FlagString } :
                    new JArray { ac.Name.Name, ac.FlagString, ac.Name.Version });
            }

            return new JArray (byNs.Values);
        }
Example #36
0
        public async void CheckTest()
        {
            var anotherAnswer = "Answer";

            var getAll = await _client.GetAsync("/api/TestingTest/GetAllTest");

            var tests = JArray.Parse(await getAll.Content.ReadAsStringAsync());

            foreach (var test in tests)
            {
                var getTest = await _client.PostAsJsonAsync("/api/TestingTest/GetTest", (string)test["id"]);

                var questions = JArray.Parse(await getTest.Content.ReadAsStringAsync());

                bool st = false;

                foreach (var question in questions)
                {
                    /**
                     * {
                     *  "id": "quest2",
                     *  "themaId": "thema-1",
                     *  "thema": null,
                     *  "name": "Question 2",
                     *  "description": "Текст ВОПРОСА 1",
                     *  "answers": [
                     *    "Ответ 1",
                     *    "Ответ 2",
                     *    "Ответ 3",
                     *    "Ответ 4",
                     *    "Ответ 5"
                     *  ],
                     *  "rightAnswers": null,
                     *  "appraisal": 5.0,
                     *  "countAnswers": 5,
                     *  "time": 0,
                     *  "allAnswers": false,
                     *  "typeAnswer": 2
                     * }
                     */
                    var jA = new JArray();
                    if (st)
                    {
                        jA.Add(anotherAnswer);
                    }
                    else
                    {
                        jA.Add("Ответ 1");
                    }
                    st = !st;
                    question["rightAnswers"] = jA;
                    question["time"]         = 1500;
                }

                var headerTest  = getTest.Headers.FirstOrDefault(a => a.Key.Equals("test")).Value.First();
                var headerStart = getTest.Headers.FirstOrDefault(a => a.Key.Equals("dateStart")).Value.First();

                // Remove
                _client.DefaultRequestHeaders.Remove("test");
                _client.DefaultRequestHeaders.Remove("dateStart");

                _client.DefaultRequestHeaders.Add("test", headerTest);
                _client.DefaultRequestHeaders.Add("dateStart", headerStart);

                var getResultTest = await _client.PostAsJsonAsync("/api/TestingTest/Result", questions);

                var result = JObject.Parse(await getResultTest.Content.ReadAsStringAsync());

                Assert.NotNull(result.Value <string>("testId"));
                Assert.NotEmpty(result.Value <string>("testId"));
            }
        }
Example #37
0
 /// <inheritdoc />
 protected override JsonArray OnAppendBool(bool value)
 {
     _jArray?.Add(new JValue(value));
     return(this);
 }
Example #38
0
        protected JObject CreateDescriptor(string template, string group = "weapon", bool addInventoryIcon = false)
        {
            JObject descriptor = JObject.Parse(template);

            if (descriptor["name"] == null)
            {
                descriptor["name"] = "perfectlygenericitem";
            }

            if (descriptor["count"] == null)
            {
                descriptor["count"] = 1;
            }

            if (descriptor["parameters"] == null)
            {
                descriptor["parameters"] = new JObject();
            }

            JObject parameters = (JObject)descriptor["parameters"];

            if (parameters == null)
            {
                parameters = new JObject();
            }
            if (parameters["animationCustom"] == null)
            {
                parameters["animationCustom"] = new JObject();
            }
            if (parameters["animationCustom"]["animatedParts"] == null)
            {
                parameters["animationCustom"]["animatedParts"] = new JObject();
            }
            if (parameters["animationCustom"]["animatedParts"]["parts"] == null)
            {
                parameters["animationCustom"]["animatedParts"]["parts"] = new JObject();
            }

            JToken parts = parameters["animationCustom"]["animatedParts"]["parts"];

            string prefix = "D_";
            int    i      = 1;

            JArray groups = new JArray();

            if (!string.IsNullOrEmpty(group))
            {
                groups.Add(group);
            }

            foreach (Drawable item in output.Drawables)
            {
                if (item == null)
                {
                    continue;
                }
                JObject part = JObject.Parse("{'properties':{'centered':false,'offset':[0,0]}}");
                part["properties"]["image"]                = item.ResultImage;
                part["properties"]["offset"][0]            = item.BlockX + Math.Round(output.OffsetX / 8d, 3);
                part["properties"]["offset"][1]            = item.BlockY + Math.Round(output.OffsetY / 8d, 3);
                part["properties"]["transformationGroups"] = groups;

                parts[prefix + i++] = part;
            }

            if (addInventoryIcon)
            {
                parameters["inventoryIcon"] = DrawableUtilities.GenerateInventoryIcon(output);
            }

            return(descriptor);
        }
Example #39
0
        void BuildLeve(Game.Leve sLeve)
        {
            if (sLeve.Key <= 20 || sLeve.Name == "")
            {
                return;
            }

            dynamic leve = new JObject();

            leve.id = sLeve.Key;
            _builder.Localize.HtmlStrings((JObject)leve, sLeve, "Name", "Description");
            leve.patch       = PatchDatabase.Get("leve", sLeve.Key);
            leve.client      = sLeve.LeveClient.Name.ToString().Replace("Client: ", "");
            leve.lvl         = sLeve.ClassJobLevel;
            leve.jobCategory = sLeve.ClassJobCategory.Key;

            var sNpc     = _builder.Realm.GameData.ENpcs[sLeve.LevemeteLevel.Object.Key];
            var levemete = _builder.Db.NpcsById[sNpc.Key];

            leve.levemete = sNpc.Key;
            _builder.Db.AddReference(leve, "npc", sNpc.Key, false);

            if (sLeve.StartLevel != null && sLeve.StartLevel.Key != 0)
            {
                leve.coords = _builder.GetCoords(sLeve.StartLevel);

                var locationInfo = _builder.LocationInfoByMapId[sLeve.StartLevel.Map.Key];
                leve.zoneid = locationInfo.PlaceName.Key;
            }

            leve.areaid = sLeve.PlaceNameStart.Key;
            _builder.Db.AddLocationReference(sLeve.PlaceNameStart.Key);

            if (sLeve.ExpReward > 0)
            {
                leve.xp = sLeve.ExpReward;
            }

            if (sLeve.GilReward > 0)
            {
                leve.gil = sLeve.GilReward;
            }

            switch (sLeve.LeveAssignmentType.Key)
            {
            case 16:     // Maelstrom
            case 17:     // Adders
            case 18:     // Flames
                leve.gc = sLeve.LeveAssignmentType.Key - 15;
                break;
            }

            if (sLeve.LeveRewardItem.ItemGroups.Any(ig => ig.Value.Key > 0))
            {
                // Embed the rewards, as they will be kept in separate files.
                leve.rewards = sLeve.LeveRewardItem.Key;

                foreach (var group in sLeve.LeveRewardItem.ItemGroups.SelectMany(g => g.Value.Items))
                {
                    var item = _builder.Db.ItemsById[group.Item.Key];
                    if (item.category == 59) // Crystal
                    {
                        continue;            // Skip these, there are too many.
                    }
                    if (item.leves == null)
                    {
                        item.leves = new JArray();
                    }

                    JArray leves = item.leves;
                    if (!leves.Any(l => (int)l == sLeve.Key))
                    {
                        leves.Add(sLeve.Key);
                        _builder.Db.AddReference(item, "leve", sLeve.Key, false);
                        _builder.Db.AddReference(leve, "item", group.Item.Key, false);
                    }
                }
            }

            leve.plate    = Utils.GetIconId(sLeve.PlateIcon);
            leve.frame    = Utils.GetIconId(sLeve.FrameIcon);
            leve.areaicon = IconDatabase.EnsureEntry("leve\\area", sLeve.IssuerIcon);

            // Find turn-ins for crafting and fisher leves.
            if (_craftLevesByLeve.TryGetValue(sLeve, out var sCraftLeve))
            {
                if (sCraftLeve.Repeats > 0)
                {
                    leve.repeats = sCraftLeve.Repeats;
                }

                JArray requires = new JArray();
                leve.requires = requires;
                foreach (var sCraftLeveItem in sCraftLeve.Items)
                {
                    dynamic entry = requires.FirstOrDefault(t => (int)t["item"] == sCraftLeveItem.Item.Key);
                    if (entry != null)
                    {
                        if (entry.amount == null)
                        {
                            entry.amount = 1;
                        }
                        entry.amount += sCraftLeveItem.Count;
                        continue;
                    }

                    dynamic requireItem = new JObject();
                    requireItem.item = sCraftLeveItem.Item.Key;
                    if (sCraftLeveItem.Count > 1)
                    {
                        requireItem.amount = sCraftLeveItem.Count;
                    }
                    leve.requires.Add(requireItem);

                    var item = _builder.Db.ItemsById[sCraftLeveItem.Item.Key];
                    if (item.requiredByLeves == null)
                    {
                        item.requiredByLeves = new JArray();
                    }
                    item.requiredByLeves.Add(sLeve.Key);

                    _builder.Db.AddReference(item, "leve", sLeve.Key, false);
                    _builder.Db.AddReference(leve, "item", sCraftLeveItem.Item.Key, false);
                }
            }

            // TODO: CompanyLeve sheet for seal rewards and stuff?

            _builder.Db.Leves.Add(leve);
        }
Example #40
0
        public HttpResponseMessage GET()
        {
            List <string> PID      = new List <string>();
            List <string> numLikes = new List <string>();
            List <string> comments = new List <string>();
            SQLBlock      block    = new SQLBlock();

            using (SqlConnection connection = new SqlConnection(block.connectionString))
                using (SqlCommand command = new SqlCommand($"select TOP (10) PID from [dbo].[Photos]", connection))
                {
                    try
                    {
                        connection.Open();
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    PID.Add(reader[0].ToString());
                                }
                            }
                        }
                    }
                    catch (SqlException e3)
                    {
                        connection.Close();
                        return(new HttpResponseMessage(HttpStatusCode.Conflict)); // bad formed request
                    }
                }
            foreach (var value in PID)
            {
                //Get The number of likes for each PID
                using (SqlConnection connection = new SqlConnection(block.connectionString))
                    using (SqlCommand command = new SqlCommand($"SELECT Count(*) FROM LIKES L WHERE L.PID = '{value}'", connection))
                    {
                        try
                        {
                            connection.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        numLikes.Add(reader[0].ToString());
                                    }
                                }
                            }
                        }
                        catch (SqlException e3)
                        {
                            connection.Close();
                            return(new HttpResponseMessage(HttpStatusCode.Conflict)); // bad formed request
                        }
                    }
                //Get the comments for each PID
                using (SqlConnection connection = new SqlConnection(block.connectionString))
                    using (SqlCommand command = new SqlCommand($"SELECT comment FROM Comments C WHERE C.PID = '{value}'", connection))
                    {
                        try
                        {
                            connection.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                string myComments = "";
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        myComments += reader[0].ToString() + ";";
                                    }
                                }
                                comments.Add(myComments);
                            }
                        }
                        catch (SqlException e3)
                        {
                            connection.Close();
                            return(new HttpResponseMessage(HttpStatusCode.Conflict)); // bad formed request
                        }
                    }
            }
            JArray responseObjects = new JArray();

            for (int i = 0; i < PID.Count; i++)
            {
                JObject J = new JObject(
                    new JProperty("PID", PID[i]),
                    new JProperty("numLikes", numLikes[i]),
                    new JProperty("comments", comments[i]));
                responseObjects.Add(J);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK, responseObjects);

            return(response);
        }
Example #41
0
		public JObject B2n(World world)
		{
			JObject worldValue = new JObject();
			
			m_bodyToIndexMap.Clear();
			m_jointToIndexMap.Clear();
			
			VecToJson("gravity", world.Gravity, worldValue);
			worldValue["allowSleep"] = Settings.AllowSleep;
			worldValue["autoClearForces"] = world.AutoClearForces;
			worldValue["warmStarting"] = Settings.EnableWarmstarting;
			worldValue["continuousPhysics"] = Settings.ContinuousPhysics;
			
			JArray customPropertyValue = WriteCustomPropertiesToJson(null);
			if (customPropertyValue.Count > 0)
				worldValue["customProperties"] = customPropertyValue;
			
			int i = 0;
			JArray arr = new JArray(); ;
			foreach (var item in world.BodyList)
			{
				m_bodyToIndexMap.Add(item, i);
				arr.Add(B2n(item));
				i++;
			}
			worldValue["body"] = arr;
			
			arr = new JArray();
			// need two passes for joints because gear joints reference other joints
			foreach (var joint in world.JointList)
			{
				if (joint.JointType == JointType.Gear)
					continue;
				m_jointToIndexMap[joint] = i;
				arr.Add( B2n(joint) );
				i++;
			}
			
			foreach (var joint in world.JointList)
			{
				if (joint.JointType != JointType.Gear)
					continue;
				m_jointToIndexMap[joint] = i;
				arr.Add(B2n(joint));
				i++;
			}
			worldValue["joint"] = arr;
			
			
			arr = new JArray();
			// Currently the only efficient way to add images to a Jb2dJson
			// is by using the R.U.B.E editor. This code has not been tested,
			// but should work ok.
			foreach (var image in m_imageToNameMap.Keys)
			{
				arr.Add(B2n(image));
			}
			worldValue["image"] = arr;
			
			
			m_bodyToIndexMap.Clear();
			m_jointToIndexMap.Clear();
			return worldValue;
		}
Example #42
0
        public static async Task <bool> RunAsync(FileSystemStorageType storageType, string output, ILogger log)
        {
            var outputPath = Directory.GetCurrentDirectory();

            if (!string.IsNullOrEmpty(output))
            {
                outputPath = output;
            }

            outputPath = Path.GetFullPath(outputPath);

            if (Directory.Exists(outputPath))
            {
                outputPath = Path.Combine(outputPath, "sleet.json");
            }

            if (File.Exists(outputPath))
            {
                log.LogError($"File already exists {outputPath}");
                return(false);
            }

            if (!Directory.Exists(Path.GetDirectoryName(outputPath)))
            {
                log.LogError($"Directory does not exist {Path.GetDirectoryName(outputPath)}");
                return(false);
            }

            // Create the config template
            var json = new JObject
            {
                { "username", "" },
                { "useremail", "" }
            };

            var sourcesArray = new JArray();

            json.Add("sources", sourcesArray);

            JObject storageTemplateJson = null;

            switch (storageType)
            {
            case FileSystemStorageType.Local:
                storageTemplateJson = new JObject
                {
                    { "name", "myLocalFeed" },
                    { "type", "local" },
                    { "path", Path.Combine(Directory.GetCurrentDirectory(), "myFeed") }
                };
                break;

            case FileSystemStorageType.Azure:
                storageTemplateJson = new JObject
                {
                    { "name", "myAzureFeed" },
                    { "type", "azure" },
                    { "path", "https://yourStorageAccount.blob.core.windows.net/myFeed/" },
                    { "container", "myFeed" },
                    { "connectionString", AzureFileSystem.AzureEmptyConnectionString }
                };
                break;

            case FileSystemStorageType.AmazonS3:
                storageTemplateJson = new JObject
                {
                    { "name", "myAmazonS3Feed" },
                    { "type", "s3" },
                    { "path", "https://s3.amazonaws.com/bucketname/" },
                    { "bucketName", "bucketname" },
                    { "region", "us-east-1" },
                    { "accessKeyId", "" },
                    { "secretAccessKey", "" }
                };
                break;
            }

            if (storageTemplateJson != null)
            {
                sourcesArray.Add(storageTemplateJson);
            }

            await log.LogAsync(LogLevel.Minimal, $"Writing config template to {outputPath}");

            File.WriteAllText(outputPath, json.ToString());

            await log.LogAsync(LogLevel.Minimal, "Modify this template by changing the name and path for your own feed.");

            return(true);
        }
Example #43
0
		protected JArray WriteCustomPropertiesToJson(Object item)
		{
			JArray customPropertiesValue = new JArray();
			
			if (null == item)
				return customPropertiesValue;
			
			Nb2dJsonCustomProperties props = GetCustomPropertiesForItem(item, false);
			
			if (props == null)
				return customPropertiesValue;
			
			
			foreach (var customProp in props.m_customPropertyMap_int)
			{
				KeyValuePair<string, int> pair = (KeyValuePair<string, int>)customProp;
				JObject proValue = new JObject();
				proValue["name"] = pair.Key;
				proValue["int"] = pair.Value;
				customPropertiesValue.Add(proValue);
			}
			
			
			
			foreach (var customProp in props.m_customPropertyMap_float)
			{
				KeyValuePair<string, Double> pair = (KeyValuePair<string, Double>)customProp;
				JObject proValue = new JObject();
				proValue["name"] = pair.Key;
				proValue["float"] = pair.Value;
				customPropertiesValue.Add(proValue);
			}
			
			
			
			
			foreach (var customProp in props.m_customPropertyMap_string)
			{
				KeyValuePair<string, string> pair = (KeyValuePair<string, string>)customProp;
				JObject proValue = new JObject();
				proValue["name"] = pair.Key;
				proValue["string"] = pair.Value;
				customPropertiesValue.Add(proValue);
			}
			
			
			
			foreach (var customProp in props.m_customPropertyMap_vec2)
			{
				KeyValuePair<string, Vector2> pair = (KeyValuePair<string, Vector2>)customProp;
				JObject proValue = new JObject();
				proValue["name"] = pair.Key;
				VecToJson("vec2", pair.Value, proValue);
				customPropertiesValue.Add(proValue);
			}
			
			
			
			foreach (var customProp in props.m_customPropertyMap_bool)
			{
				KeyValuePair<string, bool> pair = (KeyValuePair<string, bool>)customProp;
				JObject proValue = new JObject();
				proValue["name"] = pair.Key;
				proValue["bool"] = pair.Value;
				customPropertiesValue.Add(proValue);
			}
			
			return customPropertiesValue;
		}
        public void LinqToJsonCreateNormal()
        {
            #region LinqToJsonCreateNormal
            JArray array = new JArray();
            JValue text = new JValue("Manual text");
            JValue date = new JValue(new DateTime(2000, 5, 23));

            array.Add(text);
            array.Add(date);

            string json = array.ToString();
            // [
            //   "Manual text",
            //   "2000-05-23T00:00:00"
            // ]
            #endregion
        }
Example #45
0
    public void GenericCollectionCopyToInsufficientArrayCapacity()
    {
      JArray j = new JArray();
      j.Add(new JValue(1));
      j.Add(new JValue(2));
      j.Add(new JValue(3));

      ExceptionAssert.Throws<ArgumentException>(
        @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.",
        () =>
        {
          ((ICollection<JToken>)j).CopyTo(new JToken[3], 1);
        });
    }
Example #46
0
 public void AddPropertyToArray()
 {
   JArray a = new JArray();
   a.Add(new JProperty("PropertyName"));
 }
Example #47
0
    public void IndexOf()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(1);
      JValue v3 = new JValue(1);

      JArray j = new JArray();

      j.Add(v1);
      Assert.AreEqual(0, j.IndexOf(v1));

      j.Add(v2);
      Assert.AreEqual(0, j.IndexOf(v1));
      Assert.AreEqual(1, j.IndexOf(v2));

      j.AddFirst(v3);
      Assert.AreEqual(1, j.IndexOf(v1));
      Assert.AreEqual(2, j.IndexOf(v2));
      Assert.AreEqual(0, j.IndexOf(v3));

      v3.Remove();
      Assert.AreEqual(0, j.IndexOf(v1));
      Assert.AreEqual(1, j.IndexOf(v2));
      Assert.AreEqual(-1, j.IndexOf(v3));
    }
Example #48
0
 /// <summary>
 /// 数据整合
 /// </summary>
 private static void MergeData()
 {
     DirectoryInfo rootDir = new DirectoryInfo(@"../../" + "input");
     JArray jaAll = new JArray();
     List<string> poiIdList = new List<string>();
     try
     {
         //遍历文件
         foreach (FileInfo file in rootDir.GetFiles("*.*"))
         {
             string readText = File.ReadAllText(file.Directory + "\\" + file.Name);
             JArray ja = (JArray)JsonConvert.DeserializeObject(readText);
             foreach (JObject joTemp in ja)
             {
                 //Scenic scenic = JsonConvert.DeserializeObject<Scenic>(jo.ToString());
                 if (jaAll.Count == 0)
                 {
                     jaAll.Add(joTemp);
                     poiIdList.Add(joTemp["poiid"].ToString());
                 }
                 else
                 {
                     if (!poiIdList.Contains(joTemp["poiid"].ToString()))
                     {
                         jaAll.Add(joTemp);
                         poiIdList.Add(joTemp["poiid"].ToString());
                     }
                 }
             }
             streamWriter.WriteLine("File: " + DateTime.Now.ToLocalTime().ToString() + " ; " + file.ToString() + " ; " + ja.Count);
             Console.WriteLine("File: " + DateTime.Now.ToLocalTime().ToString() + " ; " + file.ToString() + " ; " + ja.Count);
         }
         File.WriteAllText(@"../../" + "/output/result.json", jaAll.ToString());
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error :" + DateTime.Now.ToLocalTime().ToString() + " ; " + ex.Message.ToString());
         streamWriter.WriteLine("Error :" + DateTime.Now.ToLocalTime().ToString() + " ; " + ex.Message.ToString());
     }
 }
Example #49
0
    public void Insert()
    {
      JValue v1 = new JValue(1);
      JValue v2 = new JValue(2);
      JValue v3 = new JValue(3);
      JValue v4 = new JValue(4);

      JArray j = new JArray();

      j.Add(v1);
      j.Add(v2);
      j.Add(v3);
      j.Insert(1, v4);

      Assert.AreEqual(0, j.IndexOf(v1));
      Assert.AreEqual(1, j.IndexOf(v4));
      Assert.AreEqual(2, j.IndexOf(v2));
      Assert.AreEqual(3, j.IndexOf(v3));
    }
Example #50
0
        public void DecodeData(string UID_16, string StructName, string GatewayID, string UID, string strProtocol, AsyncSocketConnection agent, TPKGHead msg)
        {
            //取协议解析数据
            #region
            var query2 = db.GetCollection <SendStructure2>().Where(o => o.UID_16 == UID_16 && o.StructName == StructName && o.DataAreaDec == "1").DoQuery().ToList();//查询出数据部分协议
            // to do 需要根据gatewayid去数据库里查找其对应的应用云平台接口地址
            WaitCallback ac = async(xx) =>
            {
                //BluetoothDeviceData obj = null;
                JObject json  = new JObject();
                dynamic json2 = new System.Dynamic.ExpandoObject();//动态构建Json数据包,该方法暂定为不可用。
                try
                {
                    json.Add(new JProperty("Success", true));
                    json.Add(new JProperty("Code", 1));
                    json.Add(new JProperty("Type", "01"));
                    json.Add(new JProperty("GatewayID", GatewayID));
                    json.Add(new JProperty("UID", UID));

                    //第二种方法,动态构建Json数据包,暂时未将其发到应用云平台,只用于存储到数据库中
                    json2.Success   = true;
                    json2.Code      = 1;
                    json2.Type      = "01";
                    json2.GatewayID = GatewayID;
                    json2.UID       = UID;
                    //var s = Newtonsoft.Json.JsonConvert.SerializeObject(json2);


                    JArray array = new JArray();
                    foreach (var q in query2)
                    {
                        //取出所有的数据域部分,进行数据处理,等到testresult,testresultdesc
                        string strDataDesc = q.DataDesc;
                        string strFormula  = q.Formula;

                        int iPos1 = Convert.ToInt32(q.LocationBegin + "");
                        int iPos2 = Convert.ToInt32(q.LocationEnd + "");
                        //log.Info($"获取位置:iPos1={ iPos1},iPos2={ iPos2}");

                        double data;
                        string strVHex;
                        if (q.LocationEnd == -1)
                        {
                            strVHex = strProtocol.Substring((iPos1 - 1) * 2, 2);//得到16进制值,数据段的值
                        }
                        else
                        {
                            strVHex = strProtocol.Substring((iPos1 - 1) * 2, 2 * (iPos2 - iPos1) + 2); //得到16进制值,数据段的值
                        }
                        if (!string.IsNullOrEmpty(q.Formula))                                          //存在需要进一步计算转换的公式
                        {
                            int    iTestResult1 = SensorNetwork.Common.RadixConverter.HexStrToInt32(strVHex);
                            string strTemp1     = q.Formula.Replace("D", iTestResult1.ToString());
                            Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();//公式计算
                            var Result1 = Microsoft.JScript.Eval.JScriptEvaluate(strTemp1, ve);
                            data = Convert.ToDouble(Result1);
                            //log.Info($"取数:data={ data}");
                        }
                        else
                        {
                            data = SensorNetwork.Common.RadixConverter.HexStrToInt32(strVHex) / 1.0;
                            //log.Info($"取数:data={ data}");
                        }
                        //log.Info($"数组中加入数据:TestResult={ data},TestResultDesc={q.DataDesc}");
                        JObject jo = new JObject();
                        jo.Add(new JProperty("TestResult", data));
                        jo.Add(new JProperty("TestResultDesc", q.DataDesc)); //
                        array.Add(jo);
                    }
                    //array.Add( DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    json.Add("Result", array);
                    json.Add(new JProperty("TestTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                    json2.Result   = array;
                    json2.TestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string s = Newtonsoft.Json.JsonConvert.SerializeObject(json2);

                    //发送数据
                    DataSending send = new DataSending();
                    await send.SendingData(agent, msg, GatewayID, json);
                }
                catch (Exception ex)
                {
                    log.Info($"处理蓝牙设备数据包发生异常:{ ex.Message}");
                    //设备UID错误
                    JObject jsonError = new JObject(
                        new JProperty("Success", false),
                        new JProperty("Result", "错误"),
                        new JProperty("TestTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                        );
                    //此处要加发送
                    //发送数据
                    DataSending send = new DataSending();
                    await send.SendingData(agent, msg, GatewayID, jsonError);
                }
                //log.Info($"蓝牙设备数据包:{ obj.ToJson()}");


                //                        log.Info($"发送到应用云平台的蓝牙设备JSON数据:{ json}");
                //log.Info($"json.tostring:{ json.ToString()}");
                //以下部分要重新写代码入数据库
                string js = json.ToString();                                    // json.ToString().Substring(0, 1002),//保存长度有问题,需要更改.Substring(0, 1002)
                string s2 = Newtonsoft.Json.JsonConvert.SerializeObject(json2); //使用第二种Json构造方式,存入数据库
                log.Info($"js:{ js.Length}");
                var d = new BluetoothSensorLog()
                {
                    GatewayID = agent.TerminalId,
                    UID       = UID,
                    Json      = s2,
                    Created   = DateTime.Now,
                };
                await db.AddAsync(d);

                // }
            };//end    WaitCallback ac = async (xx) =>
            System.Threading.ThreadPool.QueueUserWorkItem(ac, null);

            #endregion
        }
Example #51
0
    public void AddArrayToSelf()
    {
      JArray a = new JArray(1, 2);
      a.Add(a);

      Assert.AreEqual(3, a.Count);
      Assert.AreEqual(1, (int) a[0]);
      Assert.AreEqual(2, (int) a[1]);
      Assert.AreNotSame(a, a[2]);
    }
Example #52
0
 public override string ToString()
 {
     JObject json = new JObject();
     json["type"] = Signable.GetType().Name;
     using (MemoryStream ms = new MemoryStream())
     using (BinaryWriter writer = new BinaryWriter(ms, Encoding.UTF8))
     {
         Signable.SerializeUnsigned(writer);
         writer.Flush();
         json["hex"] = ms.ToArray().ToHexString();
     }
     JArray multisignatures = new JArray();
     for (int i = 0; i < signatures.Length; i++)
     {
         if (signatures[i] == null)
         {
             multisignatures.Add(null);
         }
         else
         {
             multisignatures.Add(new JObject());
             multisignatures[i]["redeem_script"] = signatures[i].redeemScript.ToHexString();
             JArray sigs = new JArray();
             for (int j = 0; j < signatures[i].signatures.Length; j++)
             {
                 if (signatures[i].signatures[j] == null)
                 {
                     sigs.Add(null);
                 }
                 else
                 {
                     sigs.Add(signatures[i].signatures[j].ToHexString());
                 }
             }
             multisignatures[i]["signatures"] = sigs;
         }
     }
     json["multi_signatures"] = multisignatures;
     return json.ToString();
 }
        public JArray GetPatientList(string firstName, string lastName, string dateOfBirth, string NPINumber)
        {
            try
            {
                List <PatientEntity> patientEntity       = new List <PatientEntity>();
                List <tblPatients>   tblPatientEntity    = new List <tblPatients>();
                Team.Rehab.DataModel.RehabEntities rehab = new RehabEntities();
                string ReferralSource = string.Empty;
                if (!string.IsNullOrEmpty(NPINumber))
                {
                    tblReferrer referrer = _unitOfWork.ReferrerRepo.Get(o => o.NPINumber == NPINumber).FirstOrDefault();
                    if (referrer != null)
                    {
                        ReferralSource = Convert.ToString(referrer.Rrowid);
                    }
                }
                var query = rehab.tblPatients.AsQueryable();
                if (!string.IsNullOrEmpty(NPINumber))
                {
                    query = query.Where(iv => iv.ReferralSource.Contains(ReferralSource));
                }
                if (!string.IsNullOrEmpty(firstName))
                {
                    query = query.Where(iv => iv.FirstName.Contains(firstName));
                }

                if (!string.IsNullOrEmpty(lastName))
                {
                    query = query.Where(iv => iv.LastName.Contains(lastName));
                }
                if (!string.IsNullOrEmpty(dateOfBirth))
                {
                    query = query.Where(iv => iv.BirthDate.Equals(dateOfBirth));
                }

                patientEntity = (from iv in query
                                 select new PatientEntity {
                    Prowid = iv.Prowid,
                    FirstName = iv.FirstName,
                    LastName = iv.LastName,
                    MiddleInitial = iv.MiddleInitial,
                    Gender = iv.Gender,
                    BirthDate = iv.BirthDate,
                    Address1 = iv.Address1,
                    Address2 = iv.Address2,
                    City = iv.City,
                    State = iv.State,
                    ZipCode = iv.ZipCode,
                    HomePh = iv.HomePh,
                    WorkPh = iv.WorkPh,
                    CellPh = iv.CellPh,
                }).ToList();


                //===============mapper end==========================================
                JArray jResponse = new JArray();
                if (patientEntity.Count() > 0)
                {
                    CCDAGeneration.PatientDemographics _patientDemographics = new CCDAGeneration.PatientDemographics();


                    jResponse = _patientDemographics.ConvertPatientInfo(patientEntity);
                    return(jResponse);
                }
                else
                {
                    JArray  jsonArray = new JArray();
                    JObject rss       =
                        new JObject(
                            new JProperty("No record found"
                                          ));
                    jsonArray.Add(rss);
                    return(jsonArray);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #54
0
        public override List <SearchResultItem> Search(string query, string category = null)
        {
            List <SearchResultItem> searchResultItems = new List <SearchResultItem>();
            List <Category>         categories        = new List <Category>();
            JObject json = GetWebData <JObject>(string.Format("https://www.svtplay.se/api/search?q={0}", HttpUtility.UrlEncode(query)));

            if (json["categories"] != null && json["categories"].Type == JTokenType.Array)
            {
                Category genres = new Category()
                {
                    Name                    = "Genrer",
                    HasSubCategories        = true,
                    SubCategoriesDiscovered = true,
                    SubCategories           = new List <Category>()
                };
                foreach (JToken item in json["categories"].Value <JArray>())
                {
                    genres.SubCategories.Add(new RssLink()
                    {
                        Name             = item["name"].Value <string>(),
                        Url              = item["contentUrl"].Value <string>().Replace("genre/", "").Replace("/", ""),
                        Thumb            = item["thumbnailImage"] != null && item["thumbnailImage"].Type != JTokenType.Null ? item["thumbnailImage"].Value <string>() : "",
                        HasSubCategories = true,
                        SubCategories    = new List <Category>()
                    });
                }
                genres.SubCategories.ForEach(c => c.Other = (Func <List <Category> >)(() => GetTagCategories(c)));
                if (genres.SubCategories.Count > 0)
                {
                    categories.Add(genres);
                }
            }
            if (json["videosAndTitles"] != null && json["videosAndTitles"].Type == JTokenType.Array)
            {
                Category titles = new Category()
                {
                    Name                    = "Program",
                    HasSubCategories        = true,
                    SubCategoriesDiscovered = true,
                    SubCategories           = new List <Category>()
                };
                foreach (JToken item in json["videosAndTitles"].Value <JArray>().Where(i => i["titleType"] == null))
                {
                    titles.SubCategories.Add(new RssLink()
                    {
                        Name             = item["programTitle"].Value <string>(),
                        Url              = item["contentUrl"].Value <string>().Replace("/", ""),
                        Thumb            = item["poster"] != null && item["poster"].Type != JTokenType.Null ? item["poster"].Value <string>().Replace("{format}", "medium") : "",
                        Description      = item["description"].Value <string>(),
                        HasSubCategories = true,
                        SubCategories    = new List <Category>()
                    });
                }
                titles.SubCategories.ForEach(t => t.Other = (Func <List <Category> >)(() => GetProgramCategoriesAndVideos(t)));
                if (titles.SubCategories.Count > 0)
                {
                    categories.Add(titles);
                }
                SvtCategory videos = new SvtCategory()
                {
                    Name             = "Videos",
                    HasSubCategories = false
                };
                JArray filtered = new JArray();
                foreach (JToken to in json["videosAndTitles"].Value <JArray>().Where(t => t["titleType"] != null))
                {
                    filtered.Add(to);
                }
                videos.Videos = GetVideos(filtered);
                if (videos.Videos.Count > 0)
                {
                    categories.Add(videos);
                }
            }
            if (json["openArchive"] != null && json["openArchive"].Type == JTokenType.Array)
            {
                SvtCategory openArchive = new SvtCategory()
                {
                    Name             = "Öppet arkiv",
                    HasSubCategories = false
                };
                openArchive.Videos = GetVideos(json["openArchive"].Value <JArray>());
                if (openArchive.Videos.Count > 0)
                {
                    categories.Add(openArchive);
                }
            }
            categories.ForEach(c => searchResultItems.Add(c));
            return(searchResultItems);
        }
Example #55
0
        //获取统计结果
        public String getOptionData(Question q)
        {
            String      optionData = null;
            VoteDao     votedao    = new VoteDao();
            List <Vote> votelist   = votedao.getByQuestion(q);

            if (q.optionNum == 1)
            {
                if (votelist.Count != 0)
                {
                    int sum = 0;
                    foreach (Vote v in votelist)
                    {
                        sum += int.Parse(v.voteRecord);
                    }
                    optionData = (sum / votelist.Count).ToString();//取投票结果的平均值
                }
                else
                {
                    optionData = 0.ToString();//没有投票记录时结果为0
                }
            }
            else
            {
                //多选 [{'value':50,'name':'直接访问'},{'value':50,'name':'邮件营销'},{'value':50,'name':'联盟广告'},{'value':50,'name':'视频广告'},{'value':50,'name':'搜索引擎'}]
                JArray   jarry  = new JArray();
                String[] names  = q.queOption.Split('#');
                int[]    values = null;
                foreach (Vote v in votelist)
                {
                    String[] records = v.voteRecord.Split('#');
                    int[]    sum     = new int[records.Length - 1];
                    //统计每个选项的总分
                    for (int i = 0; i < records.Length - 1; i++)
                    {
                        sum[i] += int.Parse(records[i]);
                    }
                    //计算平均分
                    for (int i = 0; i < sum.Length; i++)
                    {
                        sum[i] /= votelist.Count;
                    }
                    values = sum;
                }
                if (values == null)
                {
                    values = new int[q.optionNum];
                }
                //组装
                for (int i = 0; i < names.Length - 1; i++)
                {
                    JObject json = new JObject();
                    json["name"]  = names[i];
                    json["value"] = values[i];
                    jarry.Add(json);
                }
                optionData = jarry.ToString();
            }
            QuestionDao questiondao = new Dao.QuestionDao();

            q.optionData = optionData;
            questiondao.update(q);

            return(q.optionData);
        }
Example #56
0
        public override MixProduct ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            if (Id == 0)
            {
                Id = Repository.Max(c => c.Id, _context, _transaction).Data + 1;
                CreatedDateTime = DateTime.UtcNow;
            }
            if (Properties != null && Properties.Count > 0)
            {
                JArray arrProperties = new JArray();
                foreach (var p in Properties.Where(p => !string.IsNullOrEmpty(p.Value) && !string.IsNullOrEmpty(p.Name)).OrderBy(p => p.Priority))
                {
                    arrProperties.Add(JObject.FromObject(p));
                }
                ExtraProperties = arrProperties.ToString(Formatting.None);
            }

            Template = View != null?string.Format(@"{0}/{1}{2}", View.FolderType, View.FileName, View.Extension) : Template;

            if (ThumbnailFileStream != null)
            {
                string folder = CommonHelper.GetFullPath(new string[]
                {
                    MixConstants.Folder.UploadFolder, "Products", DateTime.UtcNow.ToString("dd-MM-yyyy")
                });
                string filename      = CommonHelper.GetRandomName(ThumbnailFileStream.Name);
                bool   saveThumbnail = CommonHelper.SaveFileBase64(folder, filename, ThumbnailFileStream.Base64);
                if (saveThumbnail)
                {
                    CommonHelper.RemoveFile(Thumbnail);
                    Thumbnail = CommonHelper.GetFullPath(new string[] { folder, filename });
                }
            }
            if (ImageFileStream != null)
            {
                string folder = CommonHelper.GetFullPath(new string[]
                {
                    MixConstants.Folder.UploadFolder, "Products", DateTime.UtcNow.ToString("dd-MM-yyyy")
                });
                string filename  = CommonHelper.GetRandomName(ImageFileStream.Name);
                bool   saveImage = CommonHelper.SaveFileBase64(folder, filename, ImageFileStream.Base64);
                if (saveImage)
                {
                    CommonHelper.RemoveFile(Image);
                    Image = CommonHelper.GetFullPath(new string[] { folder, filename });
                }
            }
            if (Image[0] == '/')
            {
                Image = Image.Substring(1);
            }
            if (Thumbnail[0] == '/')
            {
                Thumbnail = Thumbnail.Substring(1);
            }
            Tags        = ListTag.ToString(Newtonsoft.Json.Formatting.None);
            NormalPrice = MixCmsHelper.ReversePrice(StrNormalPrice);
            DealPrice   = MixCmsHelper.ReversePrice(StrDealPrice);
            ImportPrice = MixCmsHelper.ReversePrice(StrImportPrice);

            GenerateSEO();

            return(base.ParseModel(_context, _transaction));
        }
Example #57
0
            static JObject XmlToJObject(XElement node)
            {
                JObject jObj = new JObject();
                foreach (var attr in node.Attributes())
                {
                    jObj.Add(attr.Name.LocalName, attr.Value);
                }

                foreach (var childs in node.Elements().GroupBy(x => x.Name.LocalName))
                {
                    string name = childs.ElementAt(0).Name.LocalName;
                    if (childs.Count() > 1)
                    {
                        JArray jArray = new JArray();
                        foreach (var child in childs)
                        {
                            jArray.Add(XmlToJObject(child));
                        }
                        jObj.Add(name, jArray);
                    }
                    else
                    {
                        jObj.Add(name, XmlToJObject(childs.ElementAt(0)));
                    }
                }

                node.Elements().Remove();
                if (!String.IsNullOrEmpty(node.Value))
                {
                    string name = "Value";
                    while (jObj[name] != null) name = "_" + name;
                    jObj.Add(name, node.Value);
                }

                return jObj;
            }
Example #58
0
 public override string ToString()
 {
     JObject json = new JObject();
     json["type"] = Signable.GetType().Name;
     json["hex"] = Signable.ToUnsignedArray().ToHexString();
     JArray multisignatures = new JArray();
     for (int i = 0; i < signatures.Length; i++)
     {
         if (signatures[i] == null)
         {
             multisignatures.Add(null);
         }
         else
         {
             multisignatures.Add(new JObject());
             multisignatures[i]["redeem_script"] = signatures[i].redeemScript.ToHexString();
             JArray sigs = new JArray();
             for (int j = 0; j < signatures[i].signatures.Length; j++)
             {
                 if (signatures[i].signatures[j] == null)
                 {
                     sigs.Add(null);
                 }
                 else
                 {
                     sigs.Add(signatures[i].signatures[j].ToHexString());
                 }
             }
             multisignatures[i]["signatures"] = sigs;
         }
     }
     json["multi_signatures"] = multisignatures;
     return json.ToString();
 }
Example #59
0
        public async Task <ActionResult <string> > GetCharacter(string nom_per)
        {
            /*
             * Selección y validación del personaje del cual se expondrá información
             */
            string NomPer;

            if (nom_per != "ironman" && nom_per != "capamerica")
            {
                return(NotFound());
            }
            else if (nom_per == "ironman")
            {
                NomPer = "Iron Man";
            }
            else
            {
                NomPer = "Captain America";
            }

            /*
             * Consultas para filtrar la información que será expuesta
             */
            //obteniendo la fecha de la última sincronización
            var LastSync = await _context.Comics
                           .Select(p => p.Last_sync)
                           .Distinct()
                           .ToListAsync();

            //obteniendo los id de los comics en que está involucrado el personaje
            var IdComics = await _context.Personajes
                           .Where(b =>
                                  b.Nom_per.Contains(NomPer))
                           .Select(p => p.Id_com)
                           .Distinct()
                           .ToListAsync();

            //obteniendo lista de los otros heroes que interactúan con el personaje
            List <string> Personajes = new List <string>();

            foreach (var i in IdComics)
            {
                var ListaPer = await _context.Personajes
                               .Where(b =>
                                      b.Id_com == i)
                               .Select(p => p.Nom_per)
                               .Distinct()
                               .ToListAsync();

                foreach (var j in ListaPer)
                {
                    Personajes.Add(j);
                }
            }
            List <string> Characters = Personajes.Distinct().ToList(); // lista de hereoes que interactuaron con el personaje sin ordenar

            //obteniendo detalle de los comics en que aparecen los otros heroes (sin descartar al personaje)
            JArray  JCharacters = new JArray();
            JObject JChar       = new JObject();

            foreach (var i in Characters)
            {
                var ListaIdCom = await _context.Personajes
                                 .Where(b =>
                                        b.Nom_per.Contains(i))
                                 .Select(p => p.Id_com)
                                 .Distinct()
                                 .ToListAsync();

                List <string> Comics = new List <string>();
                foreach (var j in ListaIdCom)
                {
                    var ListaTitCom = await _context.Comics
                                      .Where(b =>
                                             b.Id == j)
                                      .Select(p => p.Tit_com)
                                      .ToListAsync();

                    Comics.AddRange(ListaTitCom);
                }
                JChar =
                    new JObject(
                        new JProperty("character", i),
                        new JProperty("comics", Comics));
                JCharacters.Add(JChar);
            }

            /*
             * Colección JSON final resultante
             */
            JObject rss =
                new JObject(
                    new JProperty("last_sync", LastSync[0]),
                    new JProperty("characters", JCharacters));

            return(rss.ToString());
        }
Example #60
-1
    public void AddToSelf()
    {
      JArray a = new JArray();
      a.Add(a);

      Assert.IsFalse(ReferenceEquals(a[0], a));
    }