Example #1
5
 private static JObject InternalCall(string method, JArray _params)
 {
     switch (method)
     {
         case "getbestblockhash":
             return Blockchain.Default.CurrentBlockHash.ToString();
         case "getblock":
             {
                 UInt256 hash = UInt256.Parse(_params[0].AsString());
                 Block block = Blockchain.Default.GetBlock(hash);
                 if (block == null)
                     throw new RpcException(-100, "Unknown block");
                 return block.ToJson();
             }
         case "getblockcount":
             return Blockchain.Default.Height + 1;
         case "getblockhash":
             {
                 uint height = (uint)_params[0].AsNumber();
                 return Blockchain.Default.GetBlockHash(height).ToString();
             }
         case "getrawtransaction":
             {
                 UInt256 hash = UInt256.Parse(_params[0].AsString());
                 Transaction tx = Blockchain.Default.GetTransaction(hash);
                 if (tx == null)
                     throw new RpcException(-101, "Unknown transaction");
                 return tx.ToJson();
             }
         default:
             throw new RpcException(-32601, "Method not found");
     }
 }
Example #2
1
    public void ForEach()
    {
      JArray items = new JArray(new JObject(new JProperty("name", "value!")));

      foreach (JObject friend in items)
      {
        Console.WriteLine(friend);
      }
    }
Example #3
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());
        }
Example #4
0
 public static List<List<Coordinate[]>> ToListOfListOfCoordinates(JArray array)
 {
     List<List<Coordinate[]>> c = new List<List<Coordinate[]>>();
         for (int i = 0; i < array.Count; i++)
             c.Add(ToListOfCoordinates((JArray)array[i]));
         return c;
 }
Example #5
0
    public void Clear()
    {
      JArray a = new JArray {1};
      Assert.AreEqual(1, a.Count);

      a.Clear();
      Assert.AreEqual(0, a.Count);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      ConverterPrecedenceClass c = (ConverterPrecedenceClass)value;

      JToken j = new JArray(ConverterType, c.TestValue);

      j.WriteTo(writer);
    }
Example #7
0
 public static Coordinate[] ToCoordinates(JArray array)
 {
     Coordinate[] c = new Coordinate[array.Count];
         for (int i = 0; i < array.Count; i++)
         {
             c[i] = ToCoordinate((JArray) array[i]);
         }
         return c;
 }
        public void JArrayDictionary()
        {
            Dictionary<JToken, int> dic = new Dictionary<JToken, int>(JToken.EqualityComparer);
            JArray v11 = new JArray();
            JArray v12 = new JArray();

            dic[v11] = 1;
            dic[v12] += 1;
            Assert.AreEqual(2, dic[v11]);
        }
Example #9
0
    public void Contains()
    {
      JValue v = new JValue(1);

      JArray a = new JArray {v};

      Assert.AreEqual(false, a.Contains(new JValue(2)));
      Assert.AreEqual(false, a.Contains(new JValue(1)));
      Assert.AreEqual(false, a.Contains(null));
      Assert.AreEqual(true, a.Contains(v));
    }
Example #10
0
 public static JArray MergeJArray(JArray arr1, JArray arr2)
 {
     if (arr2.Count > 0)
     {
         foreach (JObject jo in arr2)
         {
             arr1.Add(jo);
         }
     }
     return arr1;
 }
Example #11
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 #12
0
		public override void Respond(IHttpContext context)
		{
			var dir = ResourceStore.Configuration.PluginsDirectory;
			if (Directory.Exists(dir))
			{
				var paths = from path in Directory.GetFiles(dir, "*.xap", SearchOption.AllDirectories)
				            select path.Replace(dir, string.Empty).Replace(".xap", string.Empty);

				var xaps = new JArray(paths);
				context.WriteJson(xaps);
			}
			else
			{
				context.WriteJson(new JArray());
			}
		}
        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;
        }
        public void Example()
        {
            #region Usage
            IList<BlogPost> blogPosts = new List<BlogPost>
            {
                new BlogPost
                {
                    Title = "Json.NET is awesome!",
                    AuthorName = "James Newton-King",
                    AuthorTwitter = "JamesNK",
                    PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
                    Body = @"<h3>Title!</h3>
                       <p>Content!</p>"
                }
            };

            JArray blogPostsArray = new JArray(
                blogPosts.Select(p => new JObject
                {
                    { "Title", p.Title },
                    {
                        "Author", new JObject
                        {
                            { "Name", p.AuthorName },
                            { "Twitter", p.AuthorTwitter }
                        }
                    },
                    { "Date", p.PostedDate },
                    { "BodyHtml", HttpUtility.HtmlEncode(p.Body) },
                })
                );

            Console.WriteLine(blogPostsArray.ToString());
            // [
            //   {
            //     "Title": "Json.NET is awesome!",
            //     "Author": {
            //       "Name": "James Newton-King",
            //       "Twitter": "JamesNK"
            //     },
            //     "Date": "2013-01-23T19:30:00",
            //     "BodyHtml": "&lt;h3&gt;Title!&lt;/h3&gt;\r\n&lt;p&gt;Content!&lt;/p&gt;"
            //   }
            // ]
            #endregion
        }
Example #15
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();
        }
        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
        }
            /// <summary>
            ///     Convert JSON Data
            /// </summary>
            /// <param name="jsondata">JSON Object</param>
            /// <returns>MDR Text Data</returns>
            /// <remarks></remarks>
            public static List<DeviceEventMdrTextData> CnvJsonDataToList(JArray jsondata)
            {
                var result = new List<DeviceEventMdrTextData>();

                foreach (var obj in jsondata)
                {
                    var tmp = new DeviceEventMdrTextData();

                    tmp.PatientSequenceNumber = Utilities.GetJTokenString(obj, "patient_sequence_number");
                    tmp.TextTypeCode = Utilities.GetJTokenString(obj, "text_type_code");
                    tmp.Text = Utilities.GetJTokenString(obj, "text");
                    tmp.MdrTextKey = Utilities.GetJTokenString(obj, "mdr_text_key");
                    tmp.DateReceived = Utilities.GetJTokenString(obj, "date_received");

                    result.Add(tmp);
                }

                return result;
            }
Example #18
0
        /// <summary>
        /// Static function to return instance of the union schema
        /// </summary>
        /// <param name="jarr">JSON object for the union schema</param>
        /// <param name="names">list of named schemas already read</param>
        /// <param name="encspace">enclosing namespace of the schema</param>
        /// <returns>new UnionSchema object</returns>
        internal static UnionSchema NewInstance(JArray jarr, PropertyMap props, SchemaNames names, string encspace)
        {
            List<Schema> schemas = new List<Schema>();
            IDictionary<string, string> uniqueSchemas = new Dictionary<string, string>();

            foreach (JToken jvalue in jarr)
            {
                Schema unionType = Schema.ParseJson(jvalue, names, encspace);
                if (null == unionType)
                    throw new SchemaParseException("Invalid JSON in union" + jvalue.ToString());

                string name = unionType.Name;
                if (uniqueSchemas.ContainsKey(name))
                    throw new SchemaParseException("Duplicate type in union: " + name);

                uniqueSchemas.Add(name, name);
                schemas.Add(unionType);
            }

            return new UnionSchema(schemas, props);
        }
Example #19
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());
         }
     //}
 }
            /// <summary>
            ///     Convert JSON Data
            /// </summary>
            /// <param name="jsondata">JSON Object</param>
            /// <returns>List(Of DeviceEventPatientData)</returns>
            /// <remarks></remarks>
            public static List<DeviceEventPatientData> CnvJsonDataToList(JArray jsondata)
            {
                var result = new List<DeviceEventPatientData>();

                foreach (var obj in jsondata)
                {
                    var tmp = new DeviceEventPatientData();

                    tmp.PatientSequenceNumber = (obj["patient_sequence_number"]).ToString();
                    tmp.DateReceived = (obj["date_received"]).ToString();
                    tmp.SequenceNumberTreatment = (obj["sequence_number_treatment"]).ToString();
                    foreach (var itm in obj["sequence_number_outcome"])
                    {
                        tmp.SequenceNumberOutcome.Add((itm).ToString());
                    }

                    //.MdrText = DeviceEventMdrTextData.CnvJsonDataToList(obj("mdr_text"))

                    result.Add(tmp);
                }

                return result;
            }
Example #21
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 #22
0
        public void ParseToJToken()
        {
            var obj = new JObject();
            obj["Id"] = Guid.Empty;
            obj["Username"] = "******";

            var profile = new JObject();
            profile["Birthday"] = new DateTime(2015, 1, 1);
            profile["Age"] = 12;

            var favors = new JArray();
            favors.Push(12);
            favors.Push("Sweet Milk");
            obj["Profile"] = profile;
            profile["Favors"] = favors;

            obj["Actived"] = true;

            var jsonString = obj.ToJson();

            var convert = new Json.Parser();
            var json = convert.Parse(jsonString) as JObject;
            System.Text.RegularExpressions.Regex JsonDateRegex = new System.Text.RegularExpressions.Regex("^(\\d{4})\\-(10|11|12|0?\\d)\\-([012]\\d|30|31)T([01]\\d|2[0-3]):([0-5]?\\d):([0-5]?\\d)$", System.Text.RegularExpressions.RegexOptions.Compiled);
            var datestr = "2015-01-01T10:3:3";
            var match = JsonDateRegex.Match(datestr);
            Assert.Equal(Guid.Empty.ToString(), json["Id"].ToString());
            Assert.Equal("yiy", (string)json["Username"]);
            Assert.Equal(true, (bool)json["Actived"]);
            profile = json["Profile"] as JObject;
            Assert.Equal(new DateTime(2015, 1, 1), (DateTime)profile["Birthday"]);
            Assert.Equal(12, (int)profile["Age"]);
            favors = profile["Favors"] as JArray;
            Assert.Equal(12, (int)favors[0]);
            Assert.Equal("Sweet Milk", (string)favors[1]);

        }
Example #23
0
        public static Dictionary<string, ExcelGroupRow> GetGroupRows(JArray array, string treecodeFiled)
        {
            var dict = new Dictionary<string, ExcelGroupRow>();
            if (string.IsNullOrEmpty(treecodeFiled)) return dict;
            for (int i = 0; i < array.Count; i++)
            {
                var item = array[i];
                var treecode = (string)item[treecodeFiled];
                treecode = treecode.Trim();
                ExcelGroupRow row = new ExcelGroupRow();
                row.StartIndex = i;
                row.EndIndex = i;
                row.TreeCode = treecode;
                var parentCode = treecode.Substring(0, Math.Max(0, treecode.LastIndexOf('.')));
                while (!string.IsNullOrEmpty(parentCode))
                {
                    ExcelGroupRow parent;
                    if (dict.TryGetValue(parentCode, out parent))
                    {
                        row.Parent = parent;
                        row.Level = parent.Level + 1;
                        item[treecodeFiled] = new string(' ', 2 * row.Level) + treecode;
                        while (parent != null)
                        {
                            parent.EndIndex = i;
                            parent = parent.Parent;
                        }
                        break;
                    }
                    parentCode = parentCode.Substring(0, Math.Max(0, parentCode.LastIndexOf('.') - 1));
                }
                dict.Add(treecode, row);
            }

            return dict;
        }
Example #24
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            var metaDataJson  = string.IsNullOrEmpty(this.Metadata) ? resource.Properties["metadata"]?.ToString() : GetObjectFromParameter(this.Metadata).ToString();
            var parameterJson = string.IsNullOrEmpty(this.Parameter) ? resource.Properties["parameters"]?.ToString() : GetObjectFromParameter(this.Parameter).ToString();

            var policySetDefinitionObject = new PolicySetDefinition
            {
                Name       = this.Name ?? resource.Name,
                Properties = new PolicySetDefinitionProperties
                {
                    Description       = this.Description ?? resource.Properties["description"]?.ToString(),
                    DisplayName       = this.DisplayName ?? resource.Properties["displayName"]?.ToString(),
                    PolicyDefinitions = string.IsNullOrEmpty(this.PolicyDefinition) ? JArray.Parse(resource.Properties["policyDefinitions"].ToString()) : GetPolicyDefinitionsObject(),
                    Metadata          = string.IsNullOrEmpty(metaDataJson) ?  null : JObject.Parse(metaDataJson),
                    Parameters        = string.IsNullOrEmpty(parameterJson) ? null : JObject.Parse(parameterJson)
                }
            };

            return(policySetDefinitionObject.ToJToken());
        }
 // auto resolve only works for string
 public void TestArray(
     [EventGridTrigger] JObject value)
 {
     JArray data = (JArray)value["data"];
     functionOut = (string)value["data"][0];
 }
Example #26
0
 private static U[] ConvertToArray <U>(JArray jarr)
 {
     return(ConvertToEnumerable <U>(jarr).ToArray());
 }
Example #27
0
        public async Task TestAnonCredsDemo()
        {
            //4. Issuer create ClaimDef
            var schemaJson = "{\n" +
                             "                    \"seqNo\":1,\n" +
                             "                    \"data\": {\n" +
                             "                        \"name\":\"gvt\",\n" +
                             "                        \"version\":\"1.0\",\n" +
                             "                        \"attr_names\":[\"age\",\"sex\",\"height\",\"name\"]\n" +
                             "                    }\n" +
                             "                }";
            var issuerDid = "NcYxiDXkpYi6ov5FcYDi1e";

            var claimDef = await AnonCreds.IssuerCreateAndStoreClaimDefAsync(_issuerWallet, issuerDid, schemaJson, null, false);

            Assert.IsNotNull(claimDef);

            //5. Prover create Master Secret
            var masterSecret = "masterSecretName";
            await AnonCreds.ProverCreateMasterSecretAsync(_proverWallet, masterSecret);

            //6. Prover store Claim Offer
            var claimOffer = string.Format("{{\"issuer_did\":\"{0}\", \"schema_seq_no\":{1}}}", issuerDid, 1);
            await AnonCreds.ProverStoreClaimOfferAsync(_proverWallet, claimOffer);

            //7. Prover get Claim Offers
            var claimOfferFilter = string.Format("{{\"issuer_did\":\"{0}\"}}", issuerDid);
            var claimOffersJson  = await AnonCreds.ProverGetClaimOffersAsync(_proverWallet, claimOfferFilter);

            var claimOffersObject = JArray.Parse(claimOffersJson);

            Assert.AreEqual(claimOffersObject.Count, 1);

            var claimOfferObject = (JObject)claimOffersObject[0];
            var claimOfferJson   = claimOfferObject.ToString();

            //8. Prover create ClaimReq
            var proverDid = "BzfFCYk";
            var claimReq  = await AnonCreds.ProverCreateAndStoreClaimReqAsync(_proverWallet, proverDid, claimOfferJson, claimDef, masterSecret);

            Assert.IsNotNull(claimReq);

            //9. Issuer create Claim
            var claimAttributesJson = "{\n" +
                                      "               \"sex\":[\"male\",\"5944657099558967239210949258394887428692050081607692519917050011144233115103\"],\n" +
                                      "               \"name\":[\"Alex\",\"1139481716457488690172217916278103335\"],\n" +
                                      "               \"height\":[\"175\",\"175\"],\n" +
                                      "               \"age\":[\"28\",\"28\"]\n" +
                                      "        }";

            var createClaimResult = await AnonCreds.IssuerCreateClaimAsync(_issuerWallet, claimReq, claimAttributesJson, -1);

            Assert.IsNotNull(createClaimResult);
            var claimJson = createClaimResult.ClaimJson;

            //10. Prover store Claim
            await AnonCreds.ProverStoreClaimAsync(_proverWallet, claimJson);

            //11. Prover gets Claims for Proof Request
            var proofRequestJson = "{\n" +
                                   "                          \"nonce\":\"123432421212\",\n" +
                                   "                          \"name\":\"proof_req_1\",\n" +
                                   "                          \"version\":\"0.1\",\n" +
                                   "                          \"requested_attrs\":{\"attr1_uuid\":{\"schema_seq_no\":1,\"name\":\"name\"},\n" +
                                   "                                                \"attr2_uuid\":{\"schema_seq_no\":1,\"name\":\"sex\"}},\n" +
                                   "                          \"requested_predicates\":{\"predicate1_uuid\":{\"attr_name\":\"age\",\"p_type\":\"GE\",\"value\":18}}\n" +
                                   "                  }";

            var claimsForProofJson = await AnonCreds.ProverGetClaimsForProofReqAsync(_proverWallet, proofRequestJson);

            Assert.IsNotNull(claimsForProofJson);

            var claimsForProof      = JObject.Parse(claimsForProofJson);
            var claimsForAttribute1 = (JArray)claimsForProof["attrs"]["attr1_uuid"];
            var claimsForAttribute2 = (JArray)claimsForProof["attrs"]["attr1_uuid"];
            var claimsForPredicate  = (JArray)claimsForProof["predicates"]["predicate1_uuid"];

            Assert.AreEqual(claimsForAttribute1.Count, 1);
            Assert.AreEqual(claimsForAttribute2.Count, 1);
            Assert.AreEqual(claimsForPredicate.Count, 1);

            var claimUuid = claimsForAttribute1[0].Value <string>("claim_uuid");

            //12. Prover create Proof
            var selfAttestedValue   = "yes";
            var requestedClaimsJson = string.Format("{{\n" +
                                                    "                                          \"self_attested_attributes\":{{\"self1\":\"{0}\"}},\n" +
                                                    "                                          \"requested_attrs\":{{\"attr1_uuid\":[\"{1}\", true],\n" +
                                                    "                                                               \"attr2_uuid\":[\"{2}\", false]}},\n" +
                                                    "                                          \"requested_predicates\":{{\"predicate1_uuid\":\"{3}\"}}\n" +
                                                    "                                        }}", selfAttestedValue, claimUuid, claimUuid, claimUuid);

            var schemasJson   = string.Format("{{\"{0}\":{1}}}", claimUuid, schemaJson);
            var claimDefsJson = string.Format("{{\"{0}\":{1}}}", claimUuid, claimDef);
            var revocRegsJson = "{}";


            var proofJson = await AnonCreds.ProverCreateProofAsync(_proverWallet, proofRequestJson, requestedClaimsJson, schemasJson,
                                                                   masterSecret, claimDefsJson, revocRegsJson);

            Assert.IsNotNull(proofJson);

            var proof = JObject.Parse(proofJson);

            //13. Verifier verify Proof
            Assert.AreEqual("Alex",
                            proof["requested_proof"]["revealed_attrs"]["attr1_uuid"][1]);

            Assert.IsNotNull(proof["requested_proof"]["unrevealed_attrs"].Value <string>("attr2_uuid"));

            Assert.AreEqual(selfAttestedValue, proof["requested_proof"]["self_attested_attrs"].Value <string>("self1"));

            Boolean valid = await AnonCreds.VerifierVerifyProofAsync(proofRequestJson, proofJson, schemasJson, claimDefsJson, revocRegsJson);

            Assert.IsTrue(valid);
        }
Example #28
0
        /* TODO: Audio
         * /// <summary>
         * /// </summary>
         * public static void LoadAvailableAudioDevices() {
         *  foreach (DirectSoundDeviceInfo device in App.AvailableAudioDevices) {
         *      SettingsViewModel.Instance.AvailableAudioDevicesList.Add(device.Description);
         *  }
         * }
         */
        /* TODO: Network
         * public static void LoadAvailableNetworkDevices() {
         *  foreach (NetworkInterface networkInterface in App.AvailableNetworkInterfaces) {
         *      SettingsViewModel.Instance.AvailableNetworkInterfacesList.Add(networkInterface.Name);
         *  }
         * }
         */

        public static void LoadAvailablePlugins()
        {
            UpdateViewModel.Instance.UpdatingAvailablePlugins = true;
            UpdateViewModel.Instance.AvailablePlugins.Clear();

            Func <bool> update = delegate {
                List <PluginSourceItem> pluginSourceList = new List <PluginSourceItem>();
                try {
                    //var httpWebRequest = (HttpWebRequest) WebRequest.Create("https://github.com/Icehunter/ffxivapp/raw/master/PACKAGES.json");
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/teast/ffxivapp/PACKAGES.json");
                    httpWebRequest.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4";
                    httpWebRequest.Headers.Add("Accept-Language", "en;q=0.8");
                    httpWebRequest.ContentType = "application/text; charset=utf-8";
                    httpWebRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                    using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) {
                        using (Stream response = httpResponse.GetResponseStream()) {
                            var responseText = string.Empty;
                            if (response != null)
                            {
                                using (var streamReader = new StreamReader(response)) {
                                    responseText = streamReader.ReadToEnd();
                                }
                            }

                            if (httpResponse.StatusCode == HttpStatusCode.OK || !string.IsNullOrWhiteSpace(responseText))
                            {
                                JArray jsonResult = JArray.Parse(responseText);
                                foreach (JToken jToken in jsonResult)
                                {
                                    bool enabled;
                                    bool.TryParse(jToken["Enabled"].ToString(), out enabled);
                                    var sourceURI = jToken["SourceURI"].ToString();

                                    if (enabled)
                                    {
                                        pluginSourceList.Add(
                                            new PluginSourceItem {
                                            Enabled   = true,
                                            Key       = Guid.NewGuid(),
                                            SourceURI = sourceURI
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    Logging.Log(Logger, new LogItem(ex, true));
                }

                foreach (PluginSourceItem pluginSourceItem in UpdateViewModel.Instance.AvailableSources)
                {
                    if (pluginSourceList.Any(p => string.Equals(p.SourceURI, pluginSourceItem.SourceURI, Constants.InvariantComparer)))
                    {
                        continue;
                    }

                    pluginSourceList.Add(pluginSourceItem);
                }

                foreach (PluginSourceItem item in pluginSourceList)
                {
                    if (item.Enabled)
                    {
                        try {
                            var httpWebRequest = (HttpWebRequest)WebRequest.Create(item.SourceURI);
                            httpWebRequest.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4";
                            httpWebRequest.Headers.Add("Accept-Language", "en;q=0.8");
                            httpWebRequest.ContentType = "application/text; charset=utf-8";
                            httpWebRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                            using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) {
                                using (Stream response = httpResponse.GetResponseStream()) {
                                    var responseText = string.Empty;
                                    if (response != null)
                                    {
                                        using (var streamReader = new StreamReader(response)) {
                                            responseText = streamReader.ReadToEnd();
                                        }
                                    }

                                    if (httpResponse.StatusCode == HttpStatusCode.OK || !string.IsNullOrWhiteSpace(responseText))
                                    {
                                        JObject  jsonResult     = JObject.Parse(responseText);
                                        JToken   pluginInfo     = jsonResult["PluginInfo"];
                                        JToken[] pluginFiles    = pluginInfo["Files"].ToArray();
                                        var      pluginDownload = new PluginDownloadItem {
                                            Files = new List <PluginFile>(
                                                pluginFiles.Select(
                                                    pluginFile => new PluginFile {
                                                Location = pluginFile["Location"].ToString(),
                                                Name     = pluginFile["Name"].ToString(),
                                                Checksum = pluginFile["Checksum"] == null
                                                                       ? string.Empty
                                                                       : pluginFile["Checksum"].ToString()
                                            })),
                                            Name         = pluginInfo["Name"].ToString(),
                                            FriendlyName = pluginInfo["FriendlyName"] == null
                                                               ? pluginInfo["Name"].ToString()
                                                               : pluginInfo["FriendlyName"].ToString(),
                                            Description = pluginInfo["Description"] == null
                                                              ? string.Empty
                                                              : pluginInfo["Description"].ToString(),
                                            SourceURI     = pluginInfo["SourceURI"].ToString(),
                                            LatestVersion = pluginInfo["Version"].ToString()
                                        };
                                        PluginInstance found = App.Plugins.Loaded.Find(pluginDownload.Name);
                                        if (found != null)
                                        {
                                            var latest  = pluginDownload.LatestVersion;
                                            var current = found.Instance.Version;
                                            pluginDownload.CurrentVersion = current;
                                            pluginDownload.Status         = PluginStatus.Installed;
                                            var latestBuild  = new BuildNumber();
                                            var currentBuild = new BuildNumber();
                                            if (BuildUtilities.NeedsUpdate(latest, current, ref latestBuild, ref currentBuild))
                                            {
                                                pluginDownload.Status = PluginStatus.UpdateAvailable;
                                                AppViewModel.Instance.HasNewPluginUpdate = true;

                                                DispatcherHelper.Invoke(() => UpdateViewModel.Instance.AvailablePluginUpdates++);
                                            }
                                            else
                                            {
                                                if (!found.Loaded)
                                                {
                                                    pluginDownload.Status = PluginStatus.OutOfDate;
                                                }
                                            }
                                        }

                                        DispatcherHelper.Invoke(() => UpdateViewModel.Instance.AvailablePlugins.Add(pluginDownload));
                                    }
                                }
                            }
                        }
                        catch (Exception ex) {
                            Logging.Log(Logger, new LogItem(ex, true));
                        }
                    }
                }

                UpdateViewModel.Instance.UpdatingAvailablePlugins = false;
                return(true);
            };

            Task.Run(() => update());
        }
Example #29
0
 private List <ExpandoObject> ParseCollection(JArray collection)
 {
     return(JsonConvert.DeserializeObject <List <ExpandoObject> >(collection.ToString(),
                                                                  JsonHelper.GetJsonSerializerSettings()));
 }
Example #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="vertexObject"></param>
        /// <param name="edgeDocId"></param>
        /// <param name="isReverse"></param>
        /// <param name="newEdgeObject"></param>
        public static void UpdateEdgeProperty(
            GraphViewCommand command,
            JObject vertexObject,
            string edgeDocId,     // Can be null
            bool isReverse,
            JObject newEdgeObject // With all metadata (including id, partition, srcV/sinkV, edgeId)
            )
        {
            bool   tooLarge;
            string srcOrSinkVInEdgeObject = isReverse ? KW_EDGE_SRCV : KW_EDGE_SINKV;

            if (edgeDocId == null)
            {
                JArray edgeContainer = (JArray)vertexObject[isReverse ? KW_VERTEX_REV_EDGE : KW_VERTEX_EDGE];

                // Don't use JToken.Replace() here.
                // Make sure the currently modified edge is the last child of edgeContainer, which
                // garantees the newly created edge-document won't be too large.
                //
                // NOTE: The following line applies for both incomming and outgoing edge.
                edgeContainer.Children <JObject>().First(
                    e => (string)e[KW_EDGE_ID] == (string)newEdgeObject[KW_EDGE_ID] &&
                    (string)e[srcOrSinkVInEdgeObject] == (string)newEdgeObject[srcOrSinkVInEdgeObject]
                    ).Remove();
                edgeContainer.Add(newEdgeObject);

                UploadOne(command, (string)vertexObject[KW_DOC_ID], vertexObject, false, out tooLarge);
                if (tooLarge)
                {
                    // Handle this situation: The updated edge is too large to be filled into the vertex-document
                    string existEdgeDocId, newEdgeDocId;
                    bool?  spillReverse = null;
                    EdgeDocumentHelper.SpillVertexEdgesToDocument(command, vertexObject, ref spillReverse, out existEdgeDocId, out newEdgeDocId);
                }
            }
            else
            {
                // Large vertex

                JObject edgeDocObject = command.Connection.RetrieveDocumentById(edgeDocId, command.Connection.GetDocumentPartition(vertexObject), command);
                edgeDocObject[KW_EDGEDOC_EDGE].Children <JObject>().First(
                    e => (string)e[KW_EDGE_ID] == (string)newEdgeObject[KW_EDGE_ID] &&
                    (string)e[srcOrSinkVInEdgeObject] == (string)newEdgeObject[srcOrSinkVInEdgeObject]
                    ).Remove();
                ((JArray)edgeDocObject[KW_EDGEDOC_EDGE]).Add(newEdgeObject);
                UploadOne(command, edgeDocId, edgeDocObject, false, out tooLarge);
                if (tooLarge)
                {
                    if (command.Connection.EdgeSpillThreshold == 1)
                    {
                        throw new GraphViewException("The edge is too large to be stored in one document!");
                    }

                    // Handle this situation: The modified edge is too large to be filled into the original edge-document
                    // Remove the edgeObject added just now, and upload the original edge-document
                    ((JArray)edgeDocObject[KW_EDGEDOC_EDGE]).Last.Remove();
                    UploadOne(command, edgeDocId, edgeDocObject, false, out tooLarge);
                    Debug.Assert(!tooLarge);

                    // Insert the edgeObject to one of the vertex's edge-documents
                    InsertEdgeObjectInternal(command, vertexObject, null, newEdgeObject, isReverse, out edgeDocId);
                }
            }
        }
Example #31
0
        public static void RemoveEdge(
            Dictionary <string, Tuple <JObject, string> > documentMap,
            GraphViewCommand command,
            string edgeDocId,
            VertexField vertexField,
            bool isReverse,
            string srcVertexId, string edgeId)
        {
            JObject vertexObject  = vertexField.VertexJObject;
            JArray  edgeContainer = (JArray)vertexObject[isReverse ? KW_VERTEX_REV_EDGE : KW_VERTEX_EDGE];

            // Check is this vertex an external vertex?
            if (!vertexField.ViaGraphAPI)
            {
#if DEBUG
                JObject edgeDocument = command.Connection.RetrieveDocumentById(edgeDocId, command.Connection.GetDocumentPartition(vertexObject), command);
                Debug.Assert(command.Connection.GetDocumentPartition(edgeDocument) == command.Connection.GetDocumentPartition(vertexObject));
#endif
                documentMap[edgeDocId] = new Tuple <JObject, string>(null, command.Connection.GetDocumentPartition(vertexObject));
                return;
            }


            if (IsSpilledVertex(vertexObject, isReverse))
            {
                // Now it is a large-degree vertex, and contains at least 1 edge-document
                Debug.Assert(!string.IsNullOrEmpty(edgeDocId), "!string.IsNullOrEmpty(edgeDocId)");

                JArray edgeDocumentsArray = edgeContainer;
                Debug.Assert(edgeDocumentsArray != null, "edgeDocuments != null");
                Debug.Assert(edgeDocumentsArray.Count == 1, "edgeDocuments.Count == 1");

                JObject edgeDocument = command.Connection.RetrieveDocumentById(edgeDocId, command.Connection.GetDocumentPartition(vertexObject), command);

                Debug.Assert(((string)edgeDocument[KW_DOC_ID]).Equals(edgeDocId), $"((string)edgeDocument['{KW_DOC_ID}']).Equals(edgeDocId)");
                Debug.Assert((bool)edgeDocument[KW_EDGEDOC_ISREVERSE] == isReverse, $"(bool)edgeDocument['{KW_EDGEDOC_ISREVERSE}'] == isReverse");
                Debug.Assert((string)edgeDocument[KW_EDGEDOC_VERTEXID] == (string)vertexObject[KW_DOC_ID], $"(string)edgeDocument['{KW_EDGEDOC_VERTEXID}'] == (string)vertexObject['id']");

                // The edge to be removed must exist! (garanteed by caller)
                JArray edgesArray = (JArray)edgeDocument[KW_EDGEDOC_EDGE];
                Debug.Assert(edgesArray != null, "edgesArray != null");
                Debug.Assert(edgesArray.Count > 0, "edgesArray.Count > 0");
                if (isReverse)
                {
                    edgesArray.First(e => (string)e[KW_EDGE_SRCV] == srcVertexId && (string)e[KW_EDGE_ID] == edgeId).Remove();
                }
                else
                {
                    edgesArray.First(e => (string)e[KW_EDGE_ID] == edgeId).Remove();
                }

                //
                // If the edge-document contains no edge after the removal, delete this edge-document.
                // Don't forget to update the vertex-document at the same time.
                //
                if (edgesArray.Count == 0)
                {
                    //
                    // Currently,
                    // If the modified edge document contains no edges, just do nothing, leave it here.
                    // This means the lastest edge document is empty
                    //
                    // If the empty document is not the latest document, delete the edge-document,
                    // and add the vertex-document to the upload list
                    if (command.Connection.EdgeSpillThreshold == 1 ||
                        (string)edgeDocumentsArray[0][KW_DOC_ID] != edgeDocId)
                    {
                        documentMap[edgeDocId] = new Tuple <JObject, string>(null, command.Connection.GetDocumentPartition(edgeDocument));
                    }
                    else
                    {
                        documentMap[edgeDocId] = new Tuple <JObject, string>(edgeDocument, command.Connection.GetDocumentPartition(edgeDocument));
                    }
                }
                else
                {
                    documentMap[edgeDocId] = new Tuple <JObject, string>(edgeDocument, command.Connection.GetDocumentPartition(edgeDocument));
                }
            }
            else
            {
                // This vertex is not spilled
                Debug.Assert(edgeDocId == null, "edgeDocId == null");

                if (isReverse)
                {
                    ((JArray)edgeContainer).First(e => (string)e[KW_EDGE_SRCV] == srcVertexId && (string)e[KW_EDGE_ID] == edgeId).Remove();
                }
                else
                {
                    ((JArray)edgeContainer).First(e => (string)e[KW_EDGE_ID] == edgeId).Remove();
                }
                documentMap[(string)vertexObject[KW_DOC_ID]] = new Tuple <JObject, string>(vertexObject, command.Connection.GetDocumentPartition(vertexObject));
            }
        }
Example #32
0
        /// <summary>
        /// This function spills a small-degree vertex, stores its edges into seperate documents
        /// Either its incoming or outgoing edges are moved to a new document, decided by which is larger in size
        /// NOTE: This function will upload the vertex document
        /// </summary>
        /// <param name="command"></param>
        /// <param name="vertexObject"></param>
        /// <param name="spillReverse">
        /// Whether to spill the outgoing edges or incoming edges.
        /// If it's null, let this function decide.
        /// (This happens when no spilling threshold is set but the document size limit is reached)
        /// </param>
        /// <param name="existEdgeDocId">This is the first edge-document (to store the existing edges)</param>
        /// <param name="newEdgeDocId">This is the second edge-document (to store the currently creating edge)</param>
        private static void SpillVertexEdgesToDocument(GraphViewCommand command, JObject vertexObject, ref bool?spillReverse, out string existEdgeDocId, out string newEdgeDocId)
        {
            if (spillReverse == null)
            {
                // Let this function decide whether incoming/outgoing edges to spill
                Debug.Assert(!IsSpilledVertex(vertexObject, true) || !IsSpilledVertex(vertexObject, false));
            }
            else
            {
                Debug.Assert(!IsSpilledVertex(vertexObject, spillReverse.Value));
            }

            // NOTE: The VertexCache is not updated here
            bool outEdgeSeperated = IsSpilledVertex(vertexObject, false);
            bool inEdgeSeperated  = IsSpilledVertex(vertexObject, true);

            if (inEdgeSeperated && outEdgeSeperated)
            {
                throw new Exception("BUG: Should not get here! Either incoming or outgoing edegs should not have been seperated");
            }

            JArray targetEdgeArray;

            if (inEdgeSeperated)
            {
                targetEdgeArray = (JArray)vertexObject[KW_VERTEX_EDGE];
                spillReverse    = false;
            }
            else if (outEdgeSeperated)
            {
                targetEdgeArray = (JArray)vertexObject[KW_VERTEX_REV_EDGE];
                spillReverse    = true;
            }
            else
            {
                JArray outEdgeArray = (JArray)vertexObject[KW_VERTEX_EDGE];
                JArray inEdgeArray  = (JArray)vertexObject[KW_VERTEX_REV_EDGE];
                spillReverse    = (outEdgeArray.ToString().Length < inEdgeArray.ToString().Length);
                targetEdgeArray = spillReverse.Value ? inEdgeArray : outEdgeArray;
            }

            // Create a new edge-document to store the currently creating edge
            JObject newEdgeDocObject = new JObject {
                [KW_DOC_ID]               = GraphViewConnection.GenerateDocumentId(),
                [KW_EDGEDOC_ISREVERSE]    = spillReverse.Value,
                [KW_EDGEDOC_VERTEXID]     = (string)vertexObject[KW_DOC_ID],
                [KW_EDGEDOC_VERTEX_LABEL] = (string)vertexObject[KW_VERTEX_LABEL],
                [KW_EDGEDOC_EDGE]         = new JArray(targetEdgeArray.Last),
                [KW_EDGEDOC_IDENTIFIER]   = (JValue)true,
            };

            if (command.Connection.PartitionPathTopLevel != null)
            {
                newEdgeDocObject[command.Connection.PartitionPathTopLevel] = vertexObject[command.Connection.PartitionPathTopLevel];
            }

            newEdgeDocId = command.Connection.CreateDocumentAsync(newEdgeDocObject, command).Result;
            targetEdgeArray.Last.Remove();  // Remove the currently create edge appended just now

            // Create another new edge-document to store the existing edges.
            JObject existEdgeDocObject = new JObject {
                [KW_DOC_ID]               = GraphViewConnection.GenerateDocumentId(),
                [KW_EDGEDOC_ISREVERSE]    = spillReverse.Value,
                [KW_EDGEDOC_VERTEXID]     = (string)vertexObject[KW_DOC_ID],
                [KW_EDGEDOC_VERTEX_LABEL] = (string)vertexObject[KW_VERTEX_LABEL],
                [KW_EDGEDOC_EDGE]         = targetEdgeArray,
                [KW_EDGEDOC_IDENTIFIER]   = (JValue)true,
            };

            if (command.Connection.PartitionPathTopLevel != null)
            {
                existEdgeDocObject[command.Connection.PartitionPathTopLevel] = vertexObject[command.Connection.PartitionPathTopLevel];
            }
            existEdgeDocId = command.Connection.CreateDocumentAsync(existEdgeDocObject, command).Result;

            // Update vertexObject to store the newly create edge-document & upload the vertexObject
            vertexObject[spillReverse.Value ? KW_VERTEX_REV_EDGE : KW_VERTEX_EDGE] = new JArray {
                // Store the last spilled edge document only.
                new JObject {
                    [KW_DOC_ID] = newEdgeDocId,
                },
            };

            // Update the vertex document to indicate whether it's spilled
            if (spillReverse.Value)
            {
                Debug.Assert((bool)vertexObject[KW_VERTEX_REVEDGE_SPILLED] == false);
                vertexObject[KW_VERTEX_REVEDGE_SPILLED] = true;
            }
            else
            {
                Debug.Assert((bool)vertexObject[KW_VERTEX_EDGE_SPILLED] == false);
                vertexObject[KW_VERTEX_EDGE_SPILLED] = true;
            }

            bool dummyTooLarge;

            UploadOne(command, (string)vertexObject[KW_DOC_ID], vertexObject, false, out dummyTooLarge);
            Debug.Assert(!dummyTooLarge);
        }
Example #33
0
        /// <summary>
        /// Insert edgeObject to one a vertex.
        /// NOTE: vertex-document and edge-document(s) are uploaded.
        /// NOTE: If changing _edge/_reverse_edge field from JArray to JObject, the "EdgeDocId" of existing
        ///       edges in VertexCache are updated (from null to the newly created edge-document's id)
        /// NOTE: Adding the newly created edge into VertexCache is not operated by this function. Actually,
        ///       if called by <see cref="UpdateEdgeProperty"/>, VertexCache should be updated by setting an
        ///       edge's property, but not adding a new edge.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="vertexObject"></param>
        /// <param name="vertexField">Can be null if we already know edgeContainer is JObject</param>
        /// <param name="edgeObject"></param>
        /// <param name="isReverse"></param>
        /// <param name="newEdgeDocId"></param>
        internal static void InsertEdgeObjectInternal(
            GraphViewCommand command,
            JObject vertexObject,
            VertexField vertexField,
            JObject edgeObject,
            bool isReverse,
            out string newEdgeDocId)
        {
            bool   tooLarge;
            JArray edgeContainer = (JArray)vertexObject[isReverse ? KW_VERTEX_REV_EDGE : KW_VERTEX_EDGE]; // JArray or JObject
            bool   isSpilled     = IsSpilledVertex(vertexObject, isReverse);

            //
            // This graph is compatible only, thus add an edge-document directly
            //
            if (command.Connection.GraphType != GraphType.GraphAPIOnly || command.Connection.EdgeSpillThreshold == 1)
            {
                Debug.Assert(command.Connection.EdgeSpillThreshold == 1);

                // Create a new edge-document to store the edge.
                JObject edgeDocObject = new JObject {
                    [KW_DOC_ID]               = GraphViewConnection.GenerateDocumentId(),
                    [KW_EDGEDOC_ISREVERSE]    = isReverse,
                    [KW_EDGEDOC_VERTEXID]     = (string)vertexObject[KW_DOC_ID],
                    [KW_EDGEDOC_VERTEX_LABEL] = (string)vertexObject[KW_VERTEX_LABEL],
                    [KW_EDGEDOC_EDGE]         = new JArray(edgeObject),
                    [KW_EDGEDOC_IDENTIFIER]   = (JValue)true,
                };
                if (command.Connection.PartitionPathTopLevel != null)
                {
                    // This may be KW_DOC_PARTITION, maybe not
                    edgeDocObject[command.Connection.PartitionPathTopLevel] = vertexObject[command.Connection.PartitionPathTopLevel];
                }

                // Upload the edge-document
                bool dummyTooLarge;
                UploadOne(command, (string)edgeDocObject[KW_DOC_ID], edgeDocObject, true, out dummyTooLarge);
                Debug.Assert(!dummyTooLarge);


                newEdgeDocId = (string)edgeDocObject[KW_DOC_ID];
                return;
            }


            if (isSpilled)
            {
                // Now it is a large-degree vertex, and contains at least 1 edge-document
                JArray edgeDocumentsArray = edgeContainer;
                Debug.Assert(edgeDocumentsArray != null, "edgeDocumentsArray != null");
                Debug.Assert(edgeDocumentsArray.Count == 1, "edgeDocumentsArray.Count == 1");

                string  lastEdgeDocId = (string)edgeDocumentsArray.Last[KW_DOC_ID];
                JObject edgeDocument  = command.Connection.RetrieveDocumentById(lastEdgeDocId, vertexField.Partition, command);
                Debug.Assert(((string)edgeDocument[KW_DOC_ID]).Equals(lastEdgeDocId), $"((string)edgeDocument[{KW_DOC_ID}]).Equals(lastEdgeDocId)");
                Debug.Assert((bool)edgeDocument[KW_EDGEDOC_ISREVERSE] == isReverse, $"(bool)edgeDocument['{KW_EDGEDOC_ISREVERSE}'] == isReverse");
                Debug.Assert((string)edgeDocument[KW_EDGEDOC_VERTEXID] == (string)vertexObject[KW_DOC_ID], $"(string)edgeDocument['{KW_EDGEDOC_VERTEXID}'] == (string)vertexObject['{KW_DOC_ID}']");

                JArray edgesArray = (JArray)edgeDocument[KW_EDGEDOC_EDGE];
                Debug.Assert(edgesArray != null, "edgesArray != null");
                Debug.Assert(edgesArray.Count > 0, "edgesArray.Count > 0");

                if (command.Connection.EdgeSpillThreshold == 0)
                {
                    // Don't spill an edge-document until it is too large
                    edgesArray.Add(edgeObject);
                    tooLarge = false;
                }
                else
                {
                    // Explicitly specified a threshold
                    Debug.Assert(command.Connection.EdgeSpillThreshold > 0, "connection.EdgeSpillThreshold > 0");
                    if (edgesArray.Count >= command.Connection.EdgeSpillThreshold)
                    {
                        // The threshold is reached!
                        tooLarge = true;
                    }
                    else
                    {
                        // The threshold is not reached
                        edgesArray.Add(edgeObject);
                        tooLarge = false;
                    }
                }

                // If the edge-document is not too large (reach the threshold), try to
                //   upload the edge into the document
                if (!tooLarge)
                {
                    UploadOne(command, lastEdgeDocId, edgeDocument, false, out tooLarge);
                }
                if (tooLarge)
                {
                    // The edge is too large to be filled into the last edge-document
                    // or the threashold is reached:
                    // Create a new edge-document to store the edge.
                    JObject edgeDocObject = new JObject {
                        [KW_DOC_ID]               = GraphViewConnection.GenerateDocumentId(),
                        [KW_EDGEDOC_ISREVERSE]    = isReverse,
                        [KW_EDGEDOC_VERTEXID]     = (string)vertexObject[KW_DOC_ID],
                        [KW_EDGEDOC_VERTEX_LABEL] = (string)vertexObject[KW_VERTEX_LABEL],
                        [KW_EDGEDOC_EDGE]         = new JArray(edgeObject),
                        [KW_EDGEDOC_IDENTIFIER]   = (JValue)true,
                    };
                    if (command.Connection.PartitionPathTopLevel != null)
                    {
                        // This may be KW_DOC_PARTITION, maybe not
                        edgeDocObject[command.Connection.PartitionPathTopLevel] = vertexObject[command.Connection.PartitionPathTopLevel];
                    }
                    lastEdgeDocId = command.Connection.CreateDocumentAsync(edgeDocObject, command).Result;

                    // Replace the newly created edge-document to vertexObject
                    Debug.Assert(edgeDocumentsArray.Count == 1);
                    edgeDocumentsArray[0][KW_DOC_ID] = lastEdgeDocId;
                }
                newEdgeDocId = lastEdgeDocId;

                // Upload the vertex documention (at least, its _nextXxx is changed)
                bool dummyTooLarge;
                UploadOne(command, (string)vertexObject[KW_DOC_ID], vertexObject, false, out dummyTooLarge);
                Debug.Assert(!dummyTooLarge);
            }
            else
            {
                // This vertex is not spilled
                bool?spillReverse;
                ((JArray)edgeContainer).Add(edgeObject);
                if (command.Connection.EdgeSpillThreshold == 0)
                {
                    // Don't spill an edge-document until it is too large
                    tooLarge     = false;
                    spillReverse = null;
                }
                else
                {
                    // Explicitly specified a threshold
                    Debug.Assert(command.Connection.EdgeSpillThreshold > 0, "connection.EdgeSpillThreshold > 0");
                    tooLarge     = (((JArray)edgeContainer).Count > command.Connection.EdgeSpillThreshold);
                    spillReverse = isReverse;
                }

                if (!tooLarge)
                {
                    UploadOne(command, (string)vertexObject[KW_DOC_ID], vertexObject, false, out tooLarge);
                }
                if (tooLarge)
                {
                    string existEdgeDocId;
                    // The vertex object is uploaded in SpillVertexEdgesToDocument
                    EdgeDocumentHelper.SpillVertexEdgesToDocument(command, vertexObject, ref spillReverse, out existEdgeDocId, out newEdgeDocId);

                    // the edges are spilled into two ducuments.
                    // one stores old edges(docId = existEdgeDocId), the other one stores the new edge.
                    // Because the new edge is not in the vertexCache, hence we can set all edges' docId as existEdgeDocId
                    Debug.Assert(spillReverse != null);
                    Debug.Assert(vertexField != null);
                    if (spillReverse.Value)
                    {
                        vertexField.RevAdjacencyList.ResetFetchedEdgesDocId(existEdgeDocId);
                    }
                    else
                    {
                        vertexField.AdjacencyList.ResetFetchedEdgesDocId(existEdgeDocId);
                    }
                }
                else
                {
                    newEdgeDocId = null;
                }
            }
        }
Example #34
0
        public static JToken ConvertFromDB(object data, NpgsqlDbColumn column)
        {
            if (data == null)
            {
                return(null);
            }

            if (data == DBNull.Value)
            {
                return(null);
            }

            var postgresType = column.DataTypeName;

            if (column.DataType == typeof(Array))
            {
                postgresType = $"{postgresType}[]";
            }

            var type       = PgSqlTypeManager.GetDotNetType(postgresType);
            var npgsqlType = PgSqlTypeManager.GetNpgsqlDbType(postgresType);


            JToken newObject = null;

            switch (npgsqlType)
            {
            case NpgsqlDbType.Json:
            case NpgsqlDbType.Jsonb:
            {
                if (type.IsListType())
                {
                    var list       = new JArray();
                    var enumerable = data as IEnumerable;
                    foreach (var o in enumerable)
                    {
                        var jt = JToken.Parse(o.ToString());
                        //var jo = jt.ToBasicDotNetObject();
                        list.Add(jt);
                    }
                    newObject = list;
                }
                else
                {
                    newObject = JToken.Parse(data.ToString());
                }
                break;
            }

            case NpgsqlDbType.Json | NpgsqlDbType.Array:
            case NpgsqlDbType.Jsonb | NpgsqlDbType.Array:
            {
                var list       = new JArray();
                var enumerable = data as IEnumerable;
                foreach (var o in enumerable)
                {
                    var jt = JToken.Parse(o.ToString());

                    list.Add(jt);
                }
                newObject = list;
                break;
            }

            default:
                newObject = JToken.FromObject(data);
                break;
            }

            return(newObject);
        }
Example #35
0
        /* TODO: Network
         * public static bool NetworkWorking {
         *  get {
         *      return NetworkHandler.Instance.IsRunning;
         *  }
         * }
         */

        /// <summary>
        /// </summary>
        public static void CheckUpdates()
        {
            try {
                Process[] updaters = Process.GetProcessesByName("FFXIVAPP.Updater");
                foreach (Process updater in updaters)
                {
                    updater.Kill();
                }

                if (File.Exists("FFXIVAPP.Updater.exe"))
                {
                    File.Delete("FFXIVAPP.Updater.Backup.exe");
                }
                else
                {
                    if (File.Exists("FFXIVAPP.Updater.Backup.exe"))
                    {
                        File.Move("FFXIVAPP.Updater.Backup.exe", "FFXIVAPP.Updater.exe");
                    }
                }
            }
            catch (Exception ex) {
                Logging.Log(Logger, new LogItem(ex, true));
            }

            Func <bool> update = delegate {
                var current = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                AppViewModel.Instance.CurrentVersion = current;
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/Icehunter/ffxivapp/releases");
                httpWebRequest.UserAgent = "Icehunter-FFXIVAPP";
                httpWebRequest.Headers.Add("Accept-Language", "en;q=0.8");
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse()) {
                    using (Stream response = httpResponse.GetResponseStream()) {
                        var responseText = string.Empty;
                        if (response != null)
                        {
                            using (var streamReader = new StreamReader(response)) {
                                responseText = streamReader.ReadToEnd();
                            }
                        }

                        var latestBuild  = new BuildNumber();
                        var currentBuild = new BuildNumber();
                        if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrWhiteSpace(responseText))
                        {
                            AppViewModel.Instance.HasNewVersion = false;
                            AppViewModel.Instance.LatestVersion = "Unknown";
                        }
                        else
                        {
                            JArray releases = JArray.Parse(responseText);
                            JToken release  = releases.FirstOrDefault(r => r?["target_commitish"].ToString() == "master");
                            var    latest   = release?["name"].ToString() ?? "Unknown";
                            latest = latest.Split(' ')[0];
                            AppViewModel.Instance.LatestVersion = latest;
                            switch (latest)
                            {
                            case "Unknown":
                                AppViewModel.Instance.HasNewVersion = false;
                                break;

                            default:
                                AppViewModel.Instance.DownloadUri   = string.Format("https://github.com/Icehunter/ffxivapp/releases/download/{0}/{0}.zip", latest);
                                AppViewModel.Instance.HasNewVersion = BuildUtilities.NeedsUpdate(latest, current, ref latestBuild, ref currentBuild);
                                break;
                            }

                            if (AppViewModel.Instance.HasNewVersion)
                            {
                                var title   = $"{AppViewModel.Instance.Locale["app_DownloadNoticeHeader"]} {AppViewModel.Instance.Locale["app_DownloadNoticeMessage"]}";
                                var message = new StringBuilder();
                                try {
                                    DateTime latestBuildDateTime  = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * latestBuild.Build + TimeSpan.TicksPerSecond * 2 * latestBuild.Revision));
                                    DateTime currentBuildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * currentBuild.Build + TimeSpan.TicksPerSecond * 2 * currentBuild.Revision));
                                    TimeSpan timeSpan             = latestBuildDateTime - currentBuildDateTime;
                                    if (timeSpan.TotalSeconds > 0)
                                    {
                                        message.AppendLine(string.Format("Missing {0} days, {1} hours and {2} seconds of updates.", timeSpan.Days, timeSpan.Hours, timeSpan.Seconds));
                                    }
                                }
                                catch (Exception ex) {
                                    Logging.Log(Logger, new LogItem(ex, true));
                                }
                                finally {
                                    message.AppendLine(AppViewModel.Instance.Locale["app_AlwaysReadUpdatesMessage"]);
                                }

                                MessageBoxHelper.ShowMessageAsync(title, message.ToString(), () => App.CloseApplication(true), delegate { });
                            }

                            // var uri = "https://ffxiv-app.com/Analytics/Google/?eCategory=Application Launch&eAction=Version Check&eLabel=FFXIVAPP";
                            // TODO: DispatcherHelper.Invoke(() => MainView.View.GoogleAnalytics.Navigate(uri));
                        }
                    }
                }

                return(true);
            };

            Task.Run(() => update());
        }
Example #36
0
        //private async Task<Dictionary<string, Tuple<int, double, string>>> getExplanationFromBackend()
        private async Task <List <Tuple <int, double, BitmapImage> > > getExplanationFromBackend()
        {
            try
            {
                var base64 = System.Convert.ToBase64String(this.img);

                var content = new MultipartFormDataContent
                {
                    { new StringContent(modelPath), "model_path" },
                    { new StringContent(base64), "image" }
                };

                topLablesV   = Int32.Parse(topLabels.Text);
                numSamplesV  = Int32.Parse(numSamples.Text);
                numFeaturesV = Int32.Parse(numFeatures.Text);

                hideRestV     = hideRest.IsChecked.Value.ToString();
                hideColorV    = hideColor.IsChecked.Value.ToString();
                positiveOnlyV = positiveOnly.IsChecked.Value.ToString();

                string url = "http://localhost:5000/lime?toplabels=" + topLablesV + "&hidecolor=" + hideColorV + "&numsamples=" + numSamplesV + "&positiveonly=" + positiveOnlyV + "&numfeatures=" + numFeaturesV + "&hiderest=" + hideRestV;

                var response = await client.PostAsync(url, content);

                var responseString = await response.Content.ReadAsStringAsync();

                var explanationDic = (JObject)JsonConvert.DeserializeObject(responseString);

                if (explanationDic["success"].Value <string>() == "failed")
                {
                    return(null);
                }

                JArray explanations = JArray.Parse(explanationDic["explanations"].Value <object>().ToString());

                List <Tuple <int, double, BitmapImage> > explanationData = new List <Tuple <int, double, BitmapImage> >();

                foreach (var item in explanations)
                {
                    var    temp              = item.ToArray();
                    int    cl                = (int)temp[0];
                    double cl_score          = (double)temp[1];
                    string explanation_img64 = (string)temp[2];
                    byte[] explanation       = System.Convert.FromBase64String(explanation_img64);

                    BitmapImage explanation_bitmap = new BitmapImage();
                    explanation_bitmap.BeginInit();
                    explanation_bitmap.StreamSource = new System.IO.MemoryStream(explanation);
                    explanation_bitmap.EndInit();
                    explanation_bitmap.Freeze();

                    Tuple <int, double, BitmapImage> tuple = new Tuple <int, double, BitmapImage>(cl, cl_score, explanation_bitmap);
                    explanationData.Add(tuple);
                }

                return(explanationData);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #37
0
        private async void initExam()
        {
            string exam = "";
            List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();

            //await Utils.ShowSystemTrayAsync(Color.FromArgb(255, 2, 140, 253), Colors.White, text: "正在紧张安排考试...", isIndeterminate: true);
            if (IsExamOrRe == 2)
            {
                paramList.Add(new KeyValuePair <string, string>("stuNum", appSetting.Values["stuNum"].ToString()));
                paramList.Add(new KeyValuePair <string, string>("idNum", appSetting.Values["idNum"].ToString()));
                exam = await NetWork.getHttpWebRequest("api/examSchedule", paramList);
            }
            else if (IsExamOrRe == 3)
            {
#if DEBUG
                paramList.Add(new KeyValuePair <string, string>("stu", "2014214136"));
#else
                paramList.Add(new KeyValuePair <string, string>("stu", appSetting.Values["stuNum"].ToString()));
#endif
                exam = await NetWork.getHttpWebRequest("examapi/index.php", paramList);
            }
            Debug.WriteLine("exam->" + exam);
            if (exam != "")
            {
                try
                {
                    JObject obj = JObject.Parse(exam);
                    if (Int32.Parse(obj["status"].ToString()) == 200)
                    {
                        List <ExamList> examList      = new List <ExamList>();
                        JArray          ExamListArray = Utils.ReadJso(exam);
                        for (int i = 0; i < ExamListArray.Count; i++)
                        {
                            ExamList examitem = new ExamList();
                            examitem.GetAttribute((JObject)ExamListArray[i]);
                            if (IsExamOrRe == 2)
                            {
                                examitem.DateTime = "第" + examitem.Week + "周周" + examitem.Weekday + "\r\n" + examitem.Begin_time + "-" + examitem.End_time;
                            }
                            else if (IsExamOrRe == 3)
                            {
                                examitem.DateTime = "日期:" + examitem.Date + "\r\n" + "时间:" + examitem.Time;
                            }
                            examList.Add(examitem);
                        }
                        ExamListView.ItemsSource = examList;
                    }
                    else if (Int32.Parse(obj["status"].ToString()) == 300)
                    {
                        ListFailedStackPanelTextBlock.Text = "暂无数据,过几天再来看看";

                        ListFailedStackPanel.Visibility          = Visibility.Visible;
                        ListFailedStackPanelImage.Visibility     = Visibility.Collapsed;
                        ListFailedStackPanelTextBlock.Visibility = Visibility.Visible;
                    }
                    else if (Int32.Parse(obj["status"].ToString()) == 0)
                    {
                        ListFailedStackPanelTextBlock.Text = "没补考的孩子别瞎点";

                        ListFailedStackPanel.Visibility          = Visibility.Visible;
                        ListFailedStackPanelImage.Visibility     = Visibility.Collapsed;
                        ListFailedStackPanelTextBlock.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        ListFailedStackPanelTextBlock.Text = "加载失败,点击重试";

                        ListFailedStackPanel.Visibility          = Visibility.Visible;
                        ListFailedStackPanelImage.Visibility     = Visibility.Visible;
                        ListFailedStackPanelTextBlock.Visibility = Visibility.Visible;
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("考试信息->解析异常");
                    ListFailedStackPanelTextBlock.Text = "加载失败,点击重试";

                    ListFailedStackPanel.Visibility          = Visibility.Visible;
                    ListFailedStackPanelImage.Visibility     = Visibility.Visible;
                    ListFailedStackPanelTextBlock.Visibility = Visibility.Visible;
                }
            }
            else
            {
                ListFailedStackPanelTextBlock.Text = "加载失败,点击重试";

                ListFailedStackPanel.Visibility          = Visibility.Visible;
                ListFailedStackPanelImage.Visibility     = Visibility.Visible;
                ListFailedStackPanelTextBlock.Visibility = Visibility.Visible;
            }
            //StatusBar statusBar = StatusBar.GetForCurrentView();
            //await statusBar.ProgressIndicator.HideAsync();
        }
Example #38
0
        private static void CargarJSON()
        {
            //string schemaJson = @"{
            //      'description': 'A person',
            //      'type': 'object',
            //      'properties':
            //      {
            //        'name': {'type':'string'},
            //        'hobbies': {
            //          'type': 'array',
            //          'items': {'type':'string'}
            //        }
            //      }
            //    }";

            //JSchema schema = JSchema.Parse(schemaJson);

            //JObject person = JObject.Parse(@"{
            //      'name': 'James',
            //      'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
            //    }");

            //bool valid = person.IsValid(schema);


            JArray myArray    = new JArray();
            string folderPath = @"C:\Users\sygno.jmartinez\Downloads\ConsoleApp1 (1)\ConsoleApp1\ConsoleApp1\jsonSP";
            string schemaJson = @"C:\Users\sygno.jmartinez\Downloads\ConsoleApp1 (1)\ConsoleApp1\ConsoleApp1\oracle_schema.json";
            bool   valid      = false;

            //string schemaJson = @"{
            //      'description': 'A person',
            //      'type': 'object',
            //      'properties':
            //      {
            //        'name': {'type':'string'},
            //        'hobbies': {
            //          'type': 'array',
            //          'items': {'type':'string'}
            //        }
            //      }
            //    }";

            JSchema schema = JSchema.Parse(File.ReadAllText(schemaJson));

            foreach (string file in Directory.EnumerateFiles(folderPath, "*.json"))
            {
                //using (StreamReader jsonStream = File.OpenText(file))
                //using (JsonTextReader reader = new JsonTextReader(jsonStream))
                //{
                //    JSchemaUrlResolver resolver = new JSchemaUrlResolver();

                //    JSchema schema = JSchema.Load(reader, new JSchemaReaderSettings
                //    {
                //        Resolver = resolver,
                //        // where the schema is being loaded from
                //        // referenced 'address.json' schema will be loaded from disk at 'c:\address.json'
                //        BaseUri = new Uri(@"c:\person.json")
                //    });

                //    // validate JSON
                //}


                //string contents = File.ReadAllText(file);

                //JsonTextReader reader = new JsonTextReader(new StringReader(contents));

                //JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
                //validatingReader.Schema = JsonSchema.Parse(schemaJson);

                //IList<string> messages = new List<string>();
                //validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);

                //JsonSerializer serializer = new JsonSerializer();
                //Procedimientos p = serializer.Deserialize<Procedimientos>(validatingReader);

                //using (StreamReader jsonStream = File.OpenText(file))
                //using (JsonTextReader reader = new JsonTextReader(jsonStream))
                //{
                //JSchema schema = JSchema.Parse(schemaJson);



                //JObject sp = JObject.Parse(@"{
                //      'name': null,
                //      'hobbies': ['Invalid content', 0.123456789]
                //    }");

                string @namespace = "ConsoleApp1";
                string @class;

                JObject sp = JObject.Parse(File.ReadAllText(file));

                IList <string> messages;
                valid = sp.IsValid(schema, out messages);

                // todos (validacion atomica)
                if (valid)
                {
                    @class = sp["Nombre"].ToString();
                    var    myClassType = Type.GetType(String.Format("{0}.{1}", @namespace, @class));
                    object instance    = myClassType == null ? null : Activator.CreateInstance(myClassType); //Check if exists, instantiate if so.

                    if (instance != null)
                    {
                        myArray.Add(sp);
                    }
                }
                else
                {
                    // mandar a logger errores del json
                }
                //}
                //}

                var lista = myArray.ToObject <List <Procedimientos> >();

                //return lista;
            }
        }
        private JArray GetJArray(string sourceAddress)
        {
            WebClient webClient = new WebClient();

            return(JArray.Parse(webClient.DownloadString(sourceAddress)));
        }
Example #40
0
        public IEnumerable <Frapid.WebsiteBuilder.Entities.Content> GetWhere(long pageNumber, [FromBody] JArray filters)
        {
            try
            {
                List <Frapid.DataAccess.Models.Filter> f = filters.ToObject <List <Frapid.DataAccess.Models.Filter> >(JsonHelper.GetJsonSerializer());
                return(this.ContentRepository.GetWhere(pageNumber, f));
            }
            catch (UnauthorizedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (DataAccessException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    Content    = new StringContent(ex.Message),
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
#if !DEBUG
            catch
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
#endif
        }
Example #41
0
        /// <summary>
        /// Handles file upload request, currently not consolidated with Attach File function
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        protected dynamic HandleFileUploadRequest(dynamic args)
        {
            var tableName = (string)args.table_name;
            var id        = (string)args.item_id;
            var path      = this.GetAttachmentFolder(tableName, id);

            dynamic contentItem = this.SiteDatabase.GetByIdAsJObject(tableName, int.Parse(id));

            var newFiles = new List <dynamic>();

            string attachmentType = this.Request.Form["attachmentType"] == null ? string.Empty : this.Request.Form["attachmentType"].ToString();
            var    CreateDate     = DateTime.Now;

            if ((bool)this.Request.Form.attachmentIsUnique == true)
            {
                if (this.Request.Files.Count() > 1)
                {
                    throw new InvalidOperationException("Cannot upload multiple file if attachmentIsUnique is true");
                }
            }

            foreach (var item in this.Request.Files)
            {
                var fileName = Path.GetFileName(item.Name);
                var filePath = Path.Combine(path, fileName);
                if (File.Exists(filePath))
                {
                    fileName = Path.GetFileNameWithoutExtension(item.Name) +
                               Guid.NewGuid() +
                               Path.GetExtension(item.Name);

                    filePath = Path.Combine(path, fileName);
                }

                using (var fs = File.Create(filePath))
                {
                    item.Value.CopyTo(fs);
                    newFiles.Add(new
                    {
                        CreateDate     = CreateDate,
                        AttachmentType = attachmentType,
                        DisplayOrder   = 0,
                        Caption        = string.Empty,
                        Url            =
                            Path.Combine(
                                "/Site",
                                "attachments",
                                tableName,
                                id,
                                fileName).Replace('\\', '/')
                    });
                }
            }

            if (contentItem.Attachments == null)
            {
                contentItem.Attachments = JArray.FromObject(newFiles);
            }
            else
            {
                if ((bool)this.Request.Form.attachmentIsUnique == true)
                {
                    bool wasSet = false;
                    foreach (JObject item in contentItem.Attachments as JArray)
                    {
                        if (item["AttachmentType"].ToString() == attachmentType.ToString())
                        {
                            // same type with current type
                            item["CreateDate"] = newFiles[0].CreateDate;

                            // delete the one being replaced
                            var directory = this.GetAttachmentFolder(tableName, id);
                            var toDelete  = Path.Combine(directory, Path.GetFileName(item["Url"].ToString()));

                            // delete when url is not null
                            if (!string.IsNullOrEmpty(item["Url"].ToString()))
                            {
                                File.Delete(toDelete);
                            }
                            BaseDataModule.AttachmentDeleted(this.Context, tableName, contentItem, item["Url"].ToString());

                            // set to new one
                            item["Url"] = newFiles[0].Url;
                            wasSet      = true;
                            break;
                        }
                    }

                    if (wasSet == false)
                    {
                        contentItem.Attachments.Add(JObject.FromObject(newFiles.First()));
                    }
                }
                else
                {
                    foreach (var item in newFiles)
                    {
                        contentItem.Attachments.Add(JObject.FromObject(item));
                    }
                }
            }


            this.SiteDatabase.UpsertRecord(tableName, contentItem);

            BaseDataModule.NewAttachments(this.Context, tableName, contentItem, newFiles);

            return(contentItem);
        }
        public async Task <Opportunity> UpdateWorkflowAsync(Opportunity opportunity, string requestId = "")
        {
            _logger.LogError($"RequestId: {requestId} - UpdateTeamAndChannels Started");

            try
            {
                bool    check           = true;
                dynamic jsonDyn         = null;
                var     opportunityName = WebUtility.UrlEncode(opportunity.DisplayName);
                var     options         = new List <QueryParam>();
                options.Add(new QueryParam("filter", $"startswith(displayName,'{opportunityName}')"));
                while (check)
                {
                    var groupIdJson = await _graphUserAppService.GetGroupAsync(options, "", requestId);

                    jsonDyn = groupIdJson;
                    JArray jsonArray = JArray.Parse(jsonDyn["value"].ToString());
                    if (jsonArray.Count() > 0)
                    {
                        if (!String.IsNullOrEmpty(jsonDyn.value[0].id.ToString()))
                        {
                            check = false;
                        }
                    }
                }

                var groupID = String.Empty;
                groupID = jsonDyn.value[0].id.ToString();


                var generalChannel = await _graphTeamsAppService.ListChannelAsync(groupID);

                dynamic generalChannelObj = generalChannel;
                string  generalChannelId  = generalChannelObj.value[0].id.ToString();

                if (!String.IsNullOrEmpty(generalChannelId))
                {
                    opportunity.Metadata.OpportunityChannelId = generalChannelId;
                }
                else
                {
                    throw new ResponseException($"RequestId: {requestId} - CreateWorkflowAsync Service Exception: Opportunity Channel is not created");
                }



                var channelInfo = new List <Tuple <string, string> >();
                foreach (var process in opportunity.Content.Template.ProcessList)
                {
                    if (process.Channel.ToLower() != "none" && process.ProcessType.ToLower() != "none")
                    {
                        try
                        {
                            var response = await _graphTeamsAppService.CreateChannelAsync(groupID, process.Channel, process.Channel + " Channel");

                            channelInfo.Add(new Tuple <string, string>(process.Channel, response["id"].ToString()));
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"RequestId: {requestId} - Adding new channel Exception: {ex}");
                        }
                    }
                }

                foreach (var channel in channelInfo)
                {
                    try
                    {
                        await _graphTeamsAppService.AddTab(channel.Item1, groupID, channel.Item2, opportunity.DisplayName, _baseUrl);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"RequestId: {requestId} - Adding General Tab Service Exception: {ex}");
                    }
                }

                return(opportunity);
            }
            catch (Exception ex)
            {
                _logger.LogError($"RequestId: {requestId} - CreateTeamAndChannels Service Exception: {ex}");
                throw new ResponseException($"RequestId: {requestId} - CreateTeamAndChannels Service Exception: {ex}");
            }
        }
Example #43
0
        public async Task TestAnonCredsWorksForSingleIssuerSingleProverMultipleClaims()
        {
            var issuerDid = "NcYxiDXkpYi6ov5FcYDi1e";

            //1. Issuer create ClaimDef
            var gvtSchemaJson = "{\n" +
                                "                    \"seqNo\":1,\n" +
                                "                    \"data\": {\n" +
                                "                        \"name\":\"gvt\",\n" +
                                "                        \"version\":\"1.0\",\n" +
                                "                        \"attr_names\":[\"age\",\"sex\",\"height\",\"name\"]\n" +
                                "                    }\n" +
                                "                }";

            var gvtClaimDef = await AnonCreds.IssuerCreateAndStoreClaimDefAsync(_issuerWallet, issuerDid, gvtSchemaJson, null, false);

            //2. Issuer create ClaimDef
            var xyzSchemaJson = "{\n" +
                                "                    \"seqNo\":2,\n" +
                                "                    \"data\": {\n" +
                                "                        \"name\":\"xyz\",\n" +
                                "                        \"version\":\"1.0\",\n" +
                                "                        \"attr_names\":[\"status\",\"period\"]\n" +
                                "                    }\n" +
                                "                }";

            var xyzClaimDef = await AnonCreds.IssuerCreateAndStoreClaimDefAsync(_issuerWallet, issuerDid, xyzSchemaJson, null, false);

            //3. Prover create Master Secret
            var masterSecret = "masterSecretName";
            await AnonCreds.ProverCreateMasterSecretAsync(_proverWallet, masterSecret);

            //4. Prover store Claim Offer received from Issuer
            var claimOffer = string.Format("{{\"issuer_did\":\"{0}\", \"schema_seq_no\":{1}}}", issuerDid, 1);
            await AnonCreds.ProverStoreClaimOfferAsync(_proverWallet, claimOffer);

            //5. Prover store Claim Offer received from Issuer
            var claimOffer2 = string.Format("{{\"issuer_did\":\"{0}\", \"schema_seq_no\":{1}}}", issuerDid, 2);
            await AnonCreds.ProverStoreClaimOfferAsync(_proverWallet, claimOffer2);

            //6. Prover get Claim Offers
            var claimOffersJson = await AnonCreds.ProverGetClaimOffersAsync(_proverWallet, "{}");

            var claimOffersObject = JArray.Parse(claimOffersJson);

            Assert.AreEqual(2, claimOffersObject.Count);

            var claimOfferObj1 = claimOffersObject[0];
            var claimOfferObj2 = claimOffersObject[1];

            var gvtClaimOffer = claimOfferObj1.Value <int>("schema_seq_no") == 1 ? claimOfferObj1.ToString() : claimOfferObj2.ToString();
            var xyzClaimOffer = claimOfferObj1.Value <int>("schema_seq_no") == 2 ? claimOfferObj1.ToString() : claimOfferObj2.ToString();


            //7. Prover create ClaimReq for GVT Claim Offer
            var proverDid   = "BzfFCYk";
            var gvtClaimReq = await AnonCreds.ProverCreateAndStoreClaimReqAsync(_proverWallet, proverDid, gvtClaimOffer, gvtClaimDef, masterSecret);

            //8. Issuer create Claim
            var gvtClaimAttributesJson = "{\n" +
                                         "               \"sex\":[\"male\",\"5944657099558967239210949258394887428692050081607692519917050011144233115103\"],\n" +
                                         "               \"name\":[\"Alex\",\"1139481716457488690172217916278103335\"],\n" +
                                         "               \"height\":[\"175\",\"175\"],\n" +
                                         "               \"age\":[\"28\",\"28\"]\n" +
                                         "        }";

            var gvtCreateClaimResult = await AnonCreds.IssuerCreateClaimAsync(_issuerWallet, gvtClaimReq, gvtClaimAttributesJson, -1);

            var gvtClaimJson = gvtCreateClaimResult.ClaimJson;

            //9. Prover store Claim
            await AnonCreds.ProverStoreClaimAsync(_proverWallet, gvtClaimJson);

            //10. Prover create ClaimReq for GVT Claim Offer
            var xyzClaimReq = await AnonCreds.ProverCreateAndStoreClaimReqAsync(_proverWallet, proverDid, xyzClaimOffer, xyzClaimDef, masterSecret);

            //11. Issuer create Claim
            var xyzClaimAttributesJson = "{\n" +
                                         "               \"status\":[\"partial\",\"51792877103171595686471452153480627530895\"],\n" +
                                         "               \"period\":[\"8\",\"8\"]\n" +
                                         "        }";

            var xyzCreateClaimResult = await AnonCreds.IssuerCreateClaimAsync(_issuerWallet, xyzClaimReq, xyzClaimAttributesJson, -1);

            var xyzClaimJson = xyzCreateClaimResult.ClaimJson;

            //12. Prover store Claim
            await AnonCreds.ProverStoreClaimAsync(_proverWallet, xyzClaimJson);

            //13. Prover gets Claims for Proof Request
            var proofRequestJson = "{\n" +
                                   "                          \"nonce\":\"123432421212\",\n" +
                                   "                          \"name\":\"proof_req_1\",\n" +
                                   "                          \"version\":\"0.1\",\n" +
                                   "                          \"requested_attrs\":{\"attr1_uuid\":{\"schema_seq_no\":1,\"name\":\"name\"}},\n" +
                                   "                          \"requested_predicates\":{\"predicate1_uuid\":{\"attr_name\":\"age\",\"p_type\":\"GE\",\"value\":18}," +
                                   "                                                    \"predicate2_uuid\":{\"attr_name\":\"period\",\"p_type\":\"GE\",\"value\":5}}\n" +
                                   "                  }";


            var claimsForProofJson = await AnonCreds.ProverGetClaimsForProofReqAsync(_proverWallet, proofRequestJson);

            Assert.IsNotNull(claimsForProofJson);

            var claimsForProof      = JObject.Parse(claimsForProofJson);
            var claimsForAttribute1 = (JArray)claimsForProof["attrs"]["attr1_uuid"];
            var claimsForPredicate1 = (JArray)claimsForProof["predicates"]["predicate1_uuid"];
            var claimsForPredicate2 = (JArray)claimsForProof["predicates"]["predicate2_uuid"];

            Assert.AreEqual(claimsForAttribute1.Count, 1);
            Assert.AreEqual(claimsForPredicate1.Count, 1);
            Assert.AreEqual(claimsForPredicate2.Count, 1);

            var claimUuidForAttr1      = claimsForAttribute1[0].Value <string>("claim_uuid");
            var claimUuidForPredicate1 = claimsForPredicate1[0].Value <string>("claim_uuid");
            var claimUuidForPredicate2 = claimsForPredicate2[0].Value <string>("claim_uuid");

            //14. Prover create Proof
            var requestedClaimsJson = string.Format("{{\n" +
                                                    "                                          \"self_attested_attributes\":{{}},\n" +
                                                    "                                          \"requested_attrs\":{{\"attr1_uuid\":[\"{0}\", true]}},\n" +
                                                    "                                          \"requested_predicates\":{{\"predicate1_uuid\":\"{1}\"," +
                                                    "                                                                    \"predicate2_uuid\":\"{2}\"}}\n" +
                                                    "                                        }}", claimUuidForAttr1, claimUuidForPredicate1, claimUuidForPredicate2);

            var schemasJson   = string.Format("{{\"{0}\":{1}, \"{2}\":{3}}}", claimUuidForAttr1, gvtSchemaJson, claimUuidForPredicate2, xyzSchemaJson);
            var claimDefsJson = string.Format("{{\"{0}\":{1}, \"{2}\":{3}}}", claimUuidForAttr1, gvtClaimDef, claimUuidForPredicate2, xyzClaimDef);

            var revocRegsJson = "{}";

            var proofJson = await AnonCreds.ProverCreateProofAsync(_proverWallet, proofRequestJson, requestedClaimsJson, schemasJson,
                                                                   masterSecret, claimDefsJson, revocRegsJson);

            Assert.IsNotNull(proofJson);

            var proof = JObject.Parse(proofJson);

            //15. Verifier verify Proof
            Assert.AreEqual("Alex",
                            proof["requested_proof"]["revealed_attrs"]["attr1_uuid"][1]);

            var valid = await AnonCreds.VerifierVerifyProofAsync(proofRequestJson, proofJson, schemasJson, claimDefsJson, revocRegsJson);

            Assert.IsTrue(valid);
        }
Example #44
0
        public IEnumerable <dynamic> GetWhere(string schemaName, string tableName, long pageNumber, [FromBody] JArray filters)
        {
            try
            {
                var f          = Filter.FromJArray(filters);
                var repository = new FormRepository(schemaName, tableName, this.MetaUser.Tenant, this.MetaUser.LoginId, this.MetaUser.UserId);
                return(repository.GetWhere(pageNumber, f));
            }
            catch (UnauthorizedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch (DataAccessException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    Content    = new StringContent(ex.Message),
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
#if !DEBUG
            catch
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
#endif
        }
        public NodeResponse Response(string partialpath, HttpListenerRequest request)
        {
            System.Diagnostics.Debug.WriteLine("Serve Scan Display " + partialpath);
            //foreach (var k in request.QueryString.AllKeys)   System.Diagnostics.Debug.WriteLine("Key {0} = {1}", k, request.QueryString[k]);

            int entry = (request.QueryString["entry"] ?? "-1").InvariantParseInt(-1);
            bool checkEDSM = (request.QueryString["EDSM"] ?? "false").InvariantParseBool(false);

            Bitmap img = null;
            JObject response = new JObject();
            response["responsetype"] = "scandisplayobjects";
            JArray objectlist = new JArray();

            var hl = discoveryform.history;
            if (hl.Count > 0)
            {
                if (entry < 0 || entry >= hl.Count)
                    entry = hl.Count - 1;

                // seen instances of exceptions accessing icons in different threads.  so push up to discovery form. need to investigate.
                discoveryform.Invoke((MethodInvoker)delegate
                {
                    StarScan.SystemNode sn = hl.StarScan.FindSystemSynchronous(hl.EntryOrder()[entry].System, checkEDSM);

                    if (sn != null)
                    {
                        int starsize = (request.QueryString["starsize"] ?? "48").InvariantParseInt(48);
                        int width = (request.QueryString["width"] ?? "800").InvariantParseInt(800);
                        SystemDisplay sd = new SystemDisplay();
                        sd.ShowMoons = (request.QueryString["showmoons"] ?? "true").InvariantParseBool(true);
                        sd.ShowOverlays = (request.QueryString["showbodyicons"] ?? "true").InvariantParseBool(true);
                        sd.ShowMaterials = (request.QueryString["showmaterials"] ?? "true").InvariantParseBool(true);
                        sd.ShowAllG = (request.QueryString["showgravity"] ?? "true").InvariantParseBool(true);
                        sd.ShowHabZone = (request.QueryString["showhabzone"] ?? "true").InvariantParseBool(true);
                        sd.ShowStarClasses = (request.QueryString["showstarclass"] ?? "true").InvariantParseBool(true);
                        sd.ShowPlanetClasses = (request.QueryString["showplanetclass"] ?? "true").InvariantParseBool(true);
                        sd.ShowDist = (request.QueryString["showdistance"] ?? "true").InvariantParseBool(true);
                        sd.ShowEDSMBodies = checkEDSM;
                        sd.SetSize(starsize);
                        sd.Font = new Font("MS Sans Serif", 8.25f);
                        sd.LargerFont = new Font("MS Sans Serif", 10f);
                        sd.FontUnderlined = new Font("MS Sans Serif", 8.25f, FontStyle.Underline);
                        ExtendedControls.ExtPictureBox imagebox = new ExtendedControls.ExtPictureBox();
                        sd.DrawSystem(imagebox, width, sn, null, null);
                        //imagebox.AddTextAutoSize(new Point(10, 10), new Size(1000, 48), "Generated on " + DateTime.UtcNow.ToString(), new Font("MS Sans Serif", 8.25f), Color.Red, Color.Black, 0);
                        imagebox.Render();

                        foreach (var e in imagebox.Elements)
                        {
                            if (e.ToolTipText.HasChars())
                            {
                                //     System.Diagnostics.Debug.WriteLine("{0} = {1}", e.Location, e.ToolTipText);
                                objectlist.Add(new JObject() { ["left"] = e.Position.X, ["top"] = e.Position.Y, ["right"] = e.Location.Right, ["bottom"] = e.Location.Bottom, ["text"] = e.ToolTipText });
                            }
                        }

                        img = imagebox.Image.Clone() as Bitmap;
                        imagebox.Dispose();
                    }
                });

            }
            else
            {
                discoveryform.Invoke((MethodInvoker)delegate
                {
                    img = BaseUtils.Icons.IconSet.GetIcon("Bodies.Unknown") as Bitmap;
                });
            }

            response["objectlist"] = objectlist;
            server.SendWebSockets(response, false); // refresh history

            Bitmap bmpclone = img.Clone() as Bitmap;
            var cnv = bmpclone.ConvertTo(System.Drawing.Imaging.ImageFormat.Png);   // this converts to png and returns the raw PNG bytes..
            WebHeaderCollection wc = new WebHeaderCollection();                     // indicate don't cache this, this is a temp image
            wc[HttpRequestHeader.CacheControl] = "no-store";
            return new NodeResponse(cnv, "image/png", wc);
        }
Example #46
0
 public void JArrayStringIndex()
 {
   ExceptionAssert.Throws<ArgumentException>(@"Accessed JArray values with invalid key value: ""purple"". Array position index expected.",
   () =>
   {
     JArray a = new JArray();
     Assert.AreEqual(null, a["purple"]);
   });
 }
Example #47
0
        public static async Task <string> GetSteamGameInfo(string gameName)
        {
            gameName = gameName.ToLower();

            if (steamGameList.Count == 0)
            {
                using (HttpClientWrapper client = new HttpClientWrapper())
                {
                    HttpResponseMessage response = await client.GetAsync("http://api.steampowered.com/ISteamApps/GetAppList/v0002/");

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string result = await response.Content.ReadAsStringAsync();

                        JObject jobj  = JObject.Parse(result);
                        JToken  list  = jobj["applist"]["apps"];
                        JArray  games = (JArray)list;
                        foreach (JToken game in games)
                        {
                            SteamGameChatCommand.steamGameList[game["name"].ToString().ToLower()] = (int)game["appid"];
                        }
                    }
                }
            }

            int gameID = -1;

            if (SteamGameChatCommand.steamGameList.ContainsKey(gameName))
            {
                gameID = SteamGameChatCommand.steamGameList[gameName];
            }
            else
            {
                string foundGame = SteamGameChatCommand.steamGameList.Keys.FirstOrDefault(g => g.Contains(gameName));
                if (foundGame != null)
                {
                    gameID = SteamGameChatCommand.steamGameList[foundGame];
                }
            }

            if (gameID > 0)
            {
                using (HttpClientWrapper client = new HttpClientWrapper())
                {
                    HttpResponseMessage response = await client.GetAsync("http://store.steampowered.com/api/appdetails?appids=" + gameID);

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string result = await response.Content.ReadAsStringAsync();

                        JObject jobj = JObject.Parse(result);
                        jobj = (JObject)jobj[gameID.ToString()]["data"];

                        double price = (int)jobj["price_overview"]["final"];
                        price = price / 100.0;

                        string url = string.Format("http://store.steampowered.com/app/{0}", gameID);

                        return(string.Format("Game: {0} - ${1} - {2}", jobj["name"], price, url));
                    }
                }
            }
            return(null);
        }
Example #48
0
        protected async Task <IActionResult> InternalSearch(SearchSCIMResourceParameter searchRequest)
        {
            _logger.LogInformation(Global.StartGetResources);
            try
            {
                if (searchRequest.Count > _options.MaxResults)
                {
                    searchRequest.Count = _options.MaxResults;
                }

                var schema = await _scimSchemaQueryRepository.FindRootSCIMSchemaByResourceType(_resourceType);

                var schemaIds = new List <string> {
                    schema.Id
                };
                schemaIds.AddRange(schema.SchemaExtensions.Select(s => s.Schema));
                var schemas = (await _scimSchemaQueryRepository.FindSCIMSchemaByIdentifiers(schemaIds)).ToList();
                var result  = await _scimRepresentationQueryRepository.FindSCIMRepresentations(new SearchSCIMRepresentationsParameter(_resourceType, searchRequest.StartIndex - 1, searchRequest.Count, searchRequest.SortBy, searchRequest.SortOrder, SCIMFilterParser.Parse(searchRequest.Filter, schemas)));

                var jObj = new JObject
                {
                    { SCIMConstants.StandardSCIMRepresentationAttributes.Schemas, new JArray(new [] { SCIMConstants.StandardSchemas.ListResponseSchemas.Id }) },
                    { SCIMConstants.StandardSCIMRepresentationAttributes.TotalResults, result.TotalResults },
                    { SCIMConstants.StandardSCIMRepresentationAttributes.ItemsPerPage, searchRequest.Count },
                    { SCIMConstants.StandardSCIMRepresentationAttributes.StartIndex, searchRequest.StartIndex }
                };
                var resources       = new JArray();
                var baseUrl         = Request.GetAbsoluteUriWithVirtualPath();
                var representations = result.Content.ToList();
                await _attributeReferenceEnricher.Enrich(_resourceType, representations, baseUrl);

                foreach (var record in representations)
                {
                    JObject newJObj  = null;
                    var     location = $"{baseUrl}/{_resourceType}/{record.Id}";
                    if (searchRequest.Attributes.Any())
                    {
                        newJObj = record.ToResponseWithIncludedAttributes(searchRequest.Attributes.Select(a => SCIMFilterParser.Parse(a, schemas)).ToList());
                    }
                    else if (searchRequest.ExcludedAttributes.Any())
                    {
                        newJObj = record.ToResponseWithExcludedAttributes(searchRequest.ExcludedAttributes.Select(a => SCIMFilterParser.Parse(a, schemas)).ToList(), location);
                    }
                    else
                    {
                        newJObj = record.ToResponse(location, true);
                    }

                    resources.Add(newJObj);
                }

                jObj.Add(SCIMConstants.StandardSCIMRepresentationAttributes.Resources, resources);
                return(new ContentResult
                {
                    StatusCode = (int)HttpStatusCode.OK,
                    Content = jObj.ToString(),
                    ContentType = SCIMConstants.STANDARD_SCIM_CONTENT_TYPE
                });
            }
            catch (SCIMFilterException ex)
            {
                _logger.LogError(ex, ex.Message);
                return(this.BuildError(HttpStatusCode.BadRequest, ex.Message, SCIMConstants.ErrorSCIMTypes.InvalidFilter));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(this.BuildError(HttpStatusCode.InternalServerError, ex.ToString(), SCIMConstants.ErrorSCIMTypes.InternalServerError));
            }
        }
Example #49
0
    public void CreateJTokenTree()
    {
      JObject o =
        new JObject(
          new JProperty("Test1", "Test1Value"),
          new JProperty("Test2", "Test2Value"),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      Assert.AreEqual(4, o.Properties().Count());

      Assert.AreEqual(@"{
  ""Test1"": ""Test1Value"",
  ""Test2"": ""Test2Value"",
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", o.ToString());

      JArray a =
        new JArray(
          o,
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
          55,
          new JArray(
            "1",
            2,
            3.0,
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
          ),
          new JConstructor(
            "ConstructorName",
            "param1",
            2,
            3.0
          )
        );

      Assert.AreEqual(5, a.Count());
      Assert.AreEqual(@"[
  {
    ""Test1"": ""Test1Value"",
    ""Test2"": ""Test2Value"",
    ""Test3"": ""Test3Value"",
    ""Test4"": null
  },
  ""2000-10-10T00:00:00Z"",
  55,
  [
    ""1"",
    2,
    3.0,
    ""0004-05-06T07:08:09Z""
  ],
  new ConstructorName(
    ""param1"",
    2,
    3.0
  )
]", a.ToString());
    }
Example #50
0
 public static IEnumerable <Point> ParseArray(string json)
 {
     return(FromJson(JArray.Parse(json)));
 }
Example #51
0
        public static bool CheckForUpdates(out string addr, out string latestVersion, out string description)
        {
            IUpdaterImpl impl = DependencyService.Get <IUpdaterImpl>();

            string t = impl.GetFileType();
            int    v = impl.GetCurrentVersion();

            JArray resp = ExecuteRequest("https://api.github.com/repos/borishonman/condor-app/releases");

            if (resp == null)
            {
                addr          = null;
                latestVersion = "";
                description   = "";
                return(false);
            }

            //find the latest release with the binary type we want
            JObject latestRelease = null;
            JObject latestAsset   = null;

            foreach (JToken tok in resp)
            {
                //get the asset based on the type of binary we want
                JObject asset = null;
                foreach (JToken tokA in (JArray)((JObject)tok).GetValue("assets"))
                {
                    JObject curAsset = tokA as JObject;
                    string  file     = (string)curAsset.GetValue("name");
                    if (file.EndsWith(t))
                    {
                        asset = curAsset;
                        break;
                    }
                }
                //if no asset was found, we know this release won't work
                if (asset == null)
                {
                    continue;
                }
                //check the release against the current app version
                string release = (string)((JObject)tok).GetValue("tag_name");
                release = release.Substring(1).Replace(".", "");
                if (int.Parse(release) > v)
                {
                    latestRelease = (JObject)tok;
                    latestAsset   = asset;
                }
            }

            IConfig cfg = ConfigFactory.GetInstance();

            if (latestRelease != null && cfg.Address != null)
            {
                string releaseVer = (string)latestRelease.GetValue("tag_name");
                addr          = latestRelease != null ? cfg.Address + "/app/" : null;
                latestVersion = releaseVer;
                description   = (string)latestRelease.GetValue("body");
                return(true);
            }

            addr          = "";
            latestVersion = "";
            description   = "";
            return(false);
        }
Example #52
0
    public SaveWorkState(ContextProvider contextProvider, JArray entitiesArray)
    {
        ContextProvider = contextProvider;
          var jObjects = entitiesArray.Select(jt => (dynamic)jt).ToList();
          var groups = jObjects.GroupBy(jo => (String)jo.entityAspect.entityTypeName).ToList();

          EntityInfoGroups = groups.Select(g => {
        var entityType = ContextProvider.LookupEntityType(g.Key);
        var entityInfos = g.Select(jo => ContextProvider.CreateEntityInfoFromJson(jo, entityType)).Cast<EntityInfo>().ToList();
        return new EntityGroup() { EntityType = entityType, EntityInfos = entityInfos };
          }).ToList();
    }
        static void Main(string[] args)
        {
            // Create standard .NET web client instance
            WebClient webClient = new WebClient();

            // Set API Key
            webClient.Headers.Add("x-api-key", API_KEY);

            try
            {
                // URL for `PDF To JPEG` API call
                string url = "https://api.pdf.co/v1/pdf/convert/to/jpg";

                // Prepare requests params as JSON
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters.Add("password", Password);
                parameters.Add("pages", Pages);
                parameters.Add("url", SourceFileUrl);
                parameters.Add("async", Async);

                // Convert dictionary of params to JSON
                string jsonPayload = JsonConvert.SerializeObject(parameters);

                // Execute POST request with JSON payload
                string response = webClient.UploadString(url, jsonPayload);

                // Parse JSON response
                JObject json = JObject.Parse(response);

                if (json["error"].ToObject <bool>() == false)
                {
                    // Asynchronous job ID
                    string jobId = json["jobId"].ToString();
                    // URL of generated JSON file available after the job completion; it will contain URLs of result JPEG files.
                    string resultJsonFileUrl = json["url"].ToString();

                    // Check the job status in a loop.
                    // If you don't want to pause the main thread you can rework the code
                    // to use a separate thread for the status checking and completion.
                    do
                    {
                        string status = CheckJobStatus(jobId);                         // Possible statuses: "working", "failed", "aborted", "success".

                        // Display timestamp and status (for demo purposes)
                        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status);

                        if (status == "success")
                        {
                            // Download JSON file as string
                            string jsonFileString = webClient.DownloadString(resultJsonFileUrl);

                            JArray resultFilesUrls = JArray.Parse(jsonFileString);

                            // Download generated JPEG files
                            int page = 1;
                            foreach (JToken token in resultFilesUrls)
                            {
                                string resultFileUrl = token.ToString();
                                string localFileName = String.Format(@".\page{0}.jpg", page);

                                webClient.DownloadFile(resultFileUrl, localFileName);

                                Console.WriteLine("Downloaded \"{0}\".", localFileName);
                                page++;
                            }
                            break;
                        }
                        else if (status == "working")
                        {
                            // Pause for a few seconds
                            Thread.Sleep(3000);
                        }
                        else
                        {
                            Console.WriteLine(status);
                            break;
                        }
                    }while (true);
                }
                else
                {
                    Console.WriteLine(json["message"].ToString());
                }
            }
            catch (WebException e)
            {
                Console.WriteLine(e.ToString());
            }

            webClient.Dispose();


            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
Example #54
0
    public void EvaluateOutOfBoundsIndxerWithError()
    {
      JArray a = new JArray(1, 2, 3, 4, 5);

      a.SelectToken("[1000].Ha", true);
    }
Example #55
0
    public void EvaluateArray()
    {
      JArray a = new JArray(1, 2, 3, 4);

      JToken t = a.SelectToken("[1]");
      Assert.IsNotNull(t);
      Assert.AreEqual(JTokenType.Integer, t.Type);
      Assert.AreEqual(2, (int)t);
    }
Example #56
0
    public void EvaluateOutOfBoundsIndxer()
    {
      JArray a = new JArray(1, 2, 3, 4, 5);

      JToken t = a.SelectToken("[1000].Ha");
      Assert.IsNull(t);
    }
        public /* TODO: internal? */ void InvokeFunction(string module, string method, JArray arguments, string tracingName)
        {
            QueueConfiguration.JavaScriptQueue.Dispatch(() =>
            {
                QueueConfiguration.JavaScriptQueue.AssertOnThread();

                if (IsDisposed)
                {
                    return;
                }

                using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, tracingName).Start())
                {
                    if (_bridge == null)
                    {
                        throw new InvalidOperationException("Bridge has not been initialized.");
                    }

                    _bridge.CallFunction(module, method, arguments);
                }
            });
        }
Example #58
0
        private static void SetProjectionMatrix(TFrameworkElement view, Dimensions dimensions, JArray transforms)
        {
            var transformMatrix = TransformHelper.ProcessTransform(transforms);

            var translateMatrix     = Matrix3D.Identity;
            var translateBackMatrix = Matrix3D.Identity;

            if (!double.IsNaN(dimensions.Width))
            {
                translateMatrix.OffsetX     = -dimensions.Width / 2;
                translateBackMatrix.OffsetX = dimensions.Width / 2;
            }

            if (!double.IsNaN(dimensions.Height))
            {
                translateMatrix.OffsetY     = -dimensions.Height / 2;
                translateBackMatrix.OffsetY = dimensions.Height / 2;
            }

            var projectionMatrix = translateMatrix * transformMatrix * translateBackMatrix;

            ApplyProjection(view, projectionMatrix);
        }
Example #59
0
        public override PagedData ProcessRequest(HttpContext context, CookDBDataContext db)
        {
            string readOnly = context.Request.Params.Get("read_only");

            if (readOnly == "true" && context.Request.RequestType != "GET")
            {
                return(new PagedData("Read Only"));
            }

            IQueryable <MISUpdateDNI> q = db.MISUpdateDNIs;

            System.IO.StreamReader reader = new System.IO.StreamReader(context.Request.InputStream, context.Request.ContentEncoding);

            var     jsonSerializer = new JsonSerializer();
            JObject blob           = (JObject)jsonSerializer.Deserialize(new JsonTextReader(new StringReader(reader.ReadToEnd())));


            switch (context.Request.RequestType)
            {
            case "GET":
            {
                string filter = context.Request.Params.Get("mis_update_id");
                if (!isNull(filter))
                {
                    q = q.Where(a => a.mis_update_id.Equals(int.Parse(filter)) && a.remove_from.Length > 1 && a.reroute_to.Length > 1);
                }

                return(new PagedData(q.Select(a => new { a.mis_updatednis_id, a.mis_update_id, a.dnis, a.remove_from, a.platform, a.description, a.effective_date, a.reroute_to, a.platform_from })));
            }

            case "POST":
            {
                if (blob["rows"].GetType() == typeof(JObject))
                {
                    JObject obj = (JObject)blob["rows"];

                    MISUpdateDNI record = new MISUpdateDNI();
                    record.mis_update_id = (int)obj["mis_update_id"];
                    record.dnis          = (String)obj["dnis"];
                    record.remove_from   = (String)obj["remove_from"];
                    if (obj["platform"].GetType() == typeof(JValue))
                    {
                        record.platform = (String)obj["platform"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)obj["platform"])[0];
                        for (int i = 1; i < ((JArray)obj["platform"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)obj["platform"])[i];
                        }
                        record.platform = platforms;
                    }
                    record.description    = (String)obj["description"];
                    record.effective_date = (String)obj["effective_date"];
                    record.reroute_to     = (String)obj["reroute_to"];
                    if (obj["platform_from"].GetType() == typeof(JValue))
                    {
                        record.platform_from = (String)obj["platform_from"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)obj["platform_from"])[0];
                        for (int i = 1; i < ((JArray)obj["platform_from"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)obj["platform_from"])[i];
                        }
                        record.platform_from = platforms;
                    }

                    db.MISUpdateDNIs.InsertOnSubmit(record);
                    db.SubmitChanges();

                    return(new PagedData(new { record.mis_updatednis_id, record.mis_update_id, record.dnis, record.remove_from, record.platform, record.description, record.effective_date, record.reroute_to, record.platform_from }));
                }

                JArray        objs = (JArray)blob["rows"];
                List <Object> list = new List <Object>();
                for (int j = 0; j < objs.Count; j++)
                {
                    MISUpdateDNI record = new MISUpdateDNI();
                    record.mis_update_id = (int)objs[j]["mis_update_id"];
                    record.dnis          = (String)objs[j]["dnis"];
                    record.remove_from   = (String)objs[j]["remove_from"];
                    if (objs[j]["platform"].GetType() == typeof(JValue))
                    {
                        record.platform = (String)objs[j]["platform"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)objs[j]["platform"])[0];
                        for (int i = 1; i < ((JArray)objs[j]["platform"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)objs[j]["platform"])[i];
                        }
                        record.platform = platforms;
                    }
                    record.description    = (String)objs[j]["description"];
                    record.effective_date = (String)objs[j]["effective_date"];
                    record.reroute_to     = (String)objs[j]["reroute_to"];
                    if (objs[j]["platform_from"].GetType() == typeof(JValue))
                    {
                        record.platform_from = (String)objs[j]["platform_from"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)objs[j]["platform_from"])[0];
                        for (int i = 1; i < ((JArray)objs[j]["platform_from"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)objs[j]["platform_from"])[i];
                        }
                        record.platform_from = platforms;
                    }

                    db.MISUpdateDNIs.InsertOnSubmit(record);
                    db.SubmitChanges();

                    list.Add(new { record.mis_updatednis_id, record.mis_update_id, record.dnis, record.remove_from, record.platform, record.description, record.effective_date, record.reroute_to, record.platform_from });
                }

                return(new PagedData(list));
            }

            case "PUT":
            {
                if (blob["rows"].GetType() == typeof(JObject))
                {
                    JObject obj = (JObject)blob["rows"];

                    MISUpdateDNI record = db.MISUpdateDNIs.Single(a => a.mis_updatednis_id.Equals((int)obj["mis_updatednis_id"]));
                    record.dnis = (String)obj["dnis"];
                    if (obj["remove_from"] != null)
                    {
                        record.remove_from = (String)obj["remove_from"];
                    }
                    //record.platform = (string)obj["platform"];

                    if (obj["platform"].GetType() == typeof(JValue))
                    {
                        record.platform = (String)obj["platform"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)obj["platform"])[0];
                        for (int i = 1; i < ((JArray)obj["platform"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)obj["platform"])[i];
                        }
                        record.platform = platforms;
                    }
                    record.description    = (String)obj["description"];
                    record.effective_date = (String)obj["effective_date"];
                    record.reroute_to     = (String)obj["reroute_to"];
                    if (obj["platform_from"].GetType() == typeof(JValue))
                    {
                        record.platform_from = (String)obj["platform_from"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)obj["platform_from"])[0];
                        for (int i = 1; i < ((JArray)obj["platform_from"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)obj["platform_from"])[i];
                        }
                        record.platform_from = platforms;
                    }

                    db.SubmitChanges();

                    return(new PagedData(new { record.mis_updatednis_id, record.mis_update_id, record.dnis, record.remove_from, record.platform, record.description, record.effective_date, record.reroute_to, record.platform_from }));
                }

                JArray        objs = (JArray)blob["rows"];
                List <Object> list = new List <Object>();
                for (int j = 0; j < objs.Count; j++)
                {
                    MISUpdateDNI record = db.MISUpdateDNIs.Single(a => a.mis_updatednis_id.Equals((int)objs[j]["mis_updatednis_id"]));
                    record.dnis        = (String)objs[j]["dnis"];
                    record.remove_from = (String)objs[j]["remove_from"];
                    if (objs[j]["platform"].GetType() == typeof(JValue))
                    {
                        record.platform = (String)objs[j]["platform"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)objs[j]["platform"])[0];
                        for (int i = 1; i < ((JArray)objs[j]["platform"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)objs[j]["platform"])[i];
                        }
                        record.platform = platforms;
                    }
                    record.description    = (String)objs[j]["description"];
                    record.effective_date = (String)objs[j]["effective_date"];
                    record.reroute_to     = (String)objs[j]["reroute_to"];
                    if (objs[j]["platform_from"].GetType() == typeof(JValue))
                    {
                        record.platform_from = (String)objs[j]["platform_from"];
                    }
                    else
                    {
                        string platforms = (String)((JArray)objs[j]["platform_from"])[0];
                        for (int i = 1; i < ((JArray)objs[j]["platform_from"]).Count; i++)
                        {
                            platforms = platforms + ", " + (String)((JArray)objs[j]["platform_from"])[i];
                        }
                        record.platform_from = platforms;
                    }

                    list.Add(new { record.mis_updatednis_id, record.mis_update_id, record.dnis, record.remove_from, record.platform, record.description, record.effective_date, record.reroute_to, record.platform_from });
                }

                db.SubmitChanges();

                return(new PagedData(list));
            }

            case "DELETE":
            {
                if (blob["rows"].GetType() == typeof(JObject))
                {
                    JObject obj = (JObject)blob["rows"];

                    MISUpdateDNI record = db.MISUpdateDNIs.Single(a => a.mis_updatednis_id.Equals((int)obj["mis_updatednis_id"]));
                    db.MISUpdateDNIs.DeleteOnSubmit(record);

                    db.SubmitChanges();

                    return(new PagedData("dnis deleted"));
                }

                JArray objs = (JArray)blob["rows"];
                for (int j = 0; j < objs.Count; j++)
                {
                    MISUpdateDNI record = db.MISUpdateDNIs.Single(a => a.mis_updatednis_id.Equals((int)objs[j]["mis_updatednis_id"]));
                    db.MISUpdateDNIs.DeleteOnSubmit(record);
                }

                db.SubmitChanges();

                return(new PagedData("dnises deleted"));
            }

            default:
                return(new PagedData("Unsupported Http Request:  " + context.Request.RequestType + " not recognized"));
            }
        }
Example #60
-1
    public void AddToSelf()
    {
      JArray a = new JArray();
      a.Add(a);

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